don't store build state in repo

This commit is contained in:
Ren Juan 2021-08-16 06:21:06 +00:00
parent 10d2b76d79
commit b16d627c7e
38424 changed files with 0 additions and 4694037 deletions

View File

@ -1,22 +0,0 @@
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.

View File

@ -1,19 +0,0 @@
# @babel/code-frame
> Generate errors that contain a code frame that point to source locations.
See our website [@babel/code-frame](https://babeljs.io/docs/en/next/babel-code-frame.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/code-frame
```
or using yarn:
```sh
yarn add @babel/code-frame --dev
```

View File

@ -1,167 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.codeFrameColumns = codeFrameColumns;
exports.default = _default;
var _highlight = _interopRequireWildcard(require("@babel/highlight"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; }
let deprecationWarningShown = false;
function getDefs(chalk) {
return {
gutter: chalk.grey,
marker: chalk.red.bold,
message: chalk.red.bold
};
}
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
function getMarkerLines(loc, source, opts) {
const startLoc = Object.assign({
column: 0,
line: -1
}, loc.start);
const endLoc = Object.assign({}, startLoc, loc.end);
const {
linesAbove = 2,
linesBelow = 3
} = opts || {};
const startLine = startLoc.line;
const startColumn = startLoc.column;
const endLine = endLoc.line;
const endColumn = endLoc.column;
let start = Math.max(startLine - (linesAbove + 1), 0);
let end = Math.min(source.length, endLine + linesBelow);
if (startLine === -1) {
start = 0;
}
if (endLine === -1) {
end = source.length;
}
const lineDiff = endLine - startLine;
const markerLines = {};
if (lineDiff) {
for (let i = 0; i <= lineDiff; i++) {
const lineNumber = i + startLine;
if (!startColumn) {
markerLines[lineNumber] = true;
} else if (i === 0) {
const sourceLength = source[lineNumber - 1].length;
markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
} else if (i === lineDiff) {
markerLines[lineNumber] = [0, endColumn];
} else {
const sourceLength = source[lineNumber - i].length;
markerLines[lineNumber] = [0, sourceLength];
}
}
} else {
if (startColumn === endColumn) {
if (startColumn) {
markerLines[startLine] = [startColumn, 0];
} else {
markerLines[startLine] = true;
}
} else {
markerLines[startLine] = [startColumn, endColumn - startColumn];
}
}
return {
start,
end,
markerLines
};
}
function codeFrameColumns(rawLines, loc, opts = {}) {
const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
const chalk = (0, _highlight.getChalk)(opts);
const defs = getDefs(chalk);
const maybeHighlight = (chalkFn, string) => {
return highlighted ? chalkFn(string) : string;
};
const lines = rawLines.split(NEWLINE);
const {
start,
end,
markerLines
} = getMarkerLines(loc, lines, opts);
const hasColumns = loc.start && typeof loc.start.column === "number";
const numberMaxWidth = String(end).length;
const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines;
let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => {
const number = start + 1 + index;
const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
const gutter = ` ${paddedNumber} | `;
const hasMarker = markerLines[number];
const lastMarkerLine = !markerLines[number + 1];
if (hasMarker) {
let markerLine = "";
if (Array.isArray(hasMarker)) {
const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
const numberOfMarkers = hasMarker[1] || 1;
markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
if (lastMarkerLine && opts.message) {
markerLine += " " + maybeHighlight(defs.message, opts.message);
}
}
return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
} else {
return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
}
}).join("\n");
if (opts.message && !hasColumns) {
frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
}
if (highlighted) {
return chalk.reset(frame);
} else {
return frame;
}
}
function _default(rawLines, lineNumber, colNumber, opts = {}) {
if (!deprecationWarningShown) {
deprecationWarningShown = true;
const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
if (process.emitWarning) {
process.emitWarning(message, "DeprecationWarning");
} else {
const deprecationError = new Error(message);
deprecationError.name = "DeprecationWarning";
console.warn(new Error(message));
}
}
colNumber = Math.max(colNumber, 0);
const location = {
start: {
column: colNumber,
line: lineNumber
}
};
return codeFrameColumns(rawLines, location, opts);
}

View File

@ -1,78 +0,0 @@
{
"_from": "@babel/code-frame@~7.10.4",
"_id": "@babel/code-frame@7.10.4",
"_inBundle": false,
"_integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==",
"_location": "/@babel/code-frame",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@babel/code-frame@~7.10.4",
"name": "@babel/code-frame",
"escapedName": "@babel%2fcode-frame",
"scope": "@babel",
"rawSpec": "~7.10.4",
"saveSpec": null,
"fetchSpec": "~7.10.4"
},
"_requiredBy": [
"/@expo/config",
"/@expo/json-file",
"/@jest/core/jest-message-util",
"/@jest/environment/jest-message-util",
"/@jest/reporters/jest-message-util",
"/@jest/test-sequencer/jest-message-util",
"/expect/jest-message-util",
"/expo-constants/@babel/core",
"/expo-constants/@expo/json-file",
"/jest-environment-jsdom/jest-message-util",
"/jest-environment-node/jest-message-util",
"/jest-expo/@babel/core",
"/jest-expo/@expo/json-file",
"/jest-expo/jest-message-util",
"/jest-jasmine2/jest-message-util",
"/jest-message-util",
"/jest-runner/jest-message-util",
"/jest-runtime/jest-message-util",
"/jest-snapshot/jest-message-util",
"/jest-watcher/jest-message-util",
"/metro",
"/read-pkg/parse-json"
],
"_resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz",
"_shasum": "168da1a36e90da68ae8d49c0f1b48c7c6249213a",
"_spec": "@babel/code-frame@~7.10.4",
"_where": "/jd/work/GT2/newMaster/Ejectable/node_modules/@expo/config",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"bugs": {
"url": "https://github.com/babel/babel/issues"
},
"bundleDependencies": false,
"dependencies": {
"@babel/highlight": "^7.10.4"
},
"deprecated": false,
"description": "Generate errors that contain a code frame that point to source locations.",
"devDependencies": {
"chalk": "^2.0.0",
"strip-ansi": "^4.0.0"
},
"gitHead": "7fd40d86a0d03ff0e9c3ea16b29689945433d4df",
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/code-frame",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/babel/babel.git",
"directory": "packages/babel-code-frame"
},
"version": "7.10.4"
}

View File

@ -1,22 +0,0 @@
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.

View File

@ -1 +0,0 @@
module.exports = require("./data/corejs2-built-ins.json");

View File

@ -1 +0,0 @@
module.exports = require("./data/corejs3-shipped-proposals.json");

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +0,0 @@
[
"esnext.global-this",
"esnext.promise.all-settled",
"esnext.string.match-all"
]

View File

@ -1,18 +0,0 @@
{
"es6.module": {
"chrome": "61",
"and_chr": "61",
"edge": "16",
"firefox": "60",
"and_ff": "60",
"node": "13.2.0",
"opera": "48",
"op_mob": "48",
"safari": "10.1",
"ios": "10.3",
"samsung": "8.2",
"android": "61",
"electron": "2.0",
"ios_saf": "10.3"
}
}

View File

@ -1,21 +0,0 @@
{
"transform-async-to-generator": [
"bugfix/transform-async-arrows-in-class"
],
"transform-parameters": [
"bugfix/transform-edge-default-parameters"
],
"transform-function-name": [
"bugfix/transform-edge-function-name"
],
"transform-block-scoping": [
"bugfix/transform-safari-block-shadowing",
"bugfix/transform-safari-for-shadowing"
],
"transform-template-literals": [
"bugfix/transform-tagged-template-caching"
],
"proposal-optional-chaining": [
"bugfix/transform-v8-spread-parameters-in-optional-chaining"
]
}

View File

@ -1,142 +0,0 @@
{
"transform-async-to-generator": {
"chrome": "55",
"opera": "42",
"edge": "15",
"firefox": "52",
"safari": "10.1",
"node": "7.6",
"ios": "10.3",
"samsung": "6",
"electron": "1.6"
},
"bugfix/transform-async-arrows-in-class": {
"chrome": "55",
"opera": "42",
"edge": "15",
"firefox": "52",
"safari": "11",
"node": "7.6",
"ios": "11",
"samsung": "6",
"electron": "1.6"
},
"transform-parameters": {
"chrome": "49",
"opera": "36",
"edge": "15",
"firefox": "53",
"safari": "10",
"node": "6",
"ios": "10",
"samsung": "5",
"electron": "0.37"
},
"bugfix/transform-edge-default-parameters": {
"chrome": "49",
"opera": "36",
"edge": "18",
"firefox": "52",
"safari": "10",
"node": "6",
"ios": "10",
"samsung": "5",
"electron": "0.37"
},
"transform-function-name": {
"chrome": "51",
"opera": "38",
"edge": "14",
"firefox": "53",
"safari": "10",
"node": "6.5",
"ios": "10",
"samsung": "5",
"electron": "1.2"
},
"bugfix/transform-edge-function-name": {
"chrome": "51",
"opera": "38",
"edge": "79",
"firefox": "53",
"safari": "10",
"node": "6.5",
"ios": "10",
"samsung": "5",
"electron": "1.2"
},
"transform-block-scoping": {
"chrome": "49",
"opera": "36",
"edge": "14",
"firefox": "51",
"safari": "10",
"node": "6",
"ios": "10",
"samsung": "5",
"electron": "0.37"
},
"bugfix/transform-safari-block-shadowing": {
"chrome": "49",
"opera": "36",
"edge": "12",
"firefox": "44",
"safari": "11",
"node": "6",
"ie": "11",
"ios": "11",
"samsung": "5",
"electron": "0.37"
},
"bugfix/transform-safari-for-shadowing": {
"chrome": "49",
"opera": "36",
"edge": "12",
"firefox": "4",
"safari": "11",
"node": "6",
"ie": "11",
"ios": "11",
"samsung": "5",
"rhino": "1.7.13",
"electron": "0.37"
},
"transform-template-literals": {
"chrome": "41",
"opera": "28",
"edge": "13",
"firefox": "34",
"safari": "9",
"node": "4",
"ios": "9",
"samsung": "3.4",
"electron": "0.21"
},
"bugfix/transform-tagged-template-caching": {
"chrome": "41",
"opera": "28",
"edge": "12",
"firefox": "34",
"safari": "13",
"node": "4",
"ios": "13",
"samsung": "3.4",
"electron": "0.21"
},
"proposal-optional-chaining": {
"chrome": "80",
"opera": "67",
"edge": "80",
"firefox": "74",
"safari": "13.1",
"node": "14",
"ios": "13.4",
"samsung": "13",
"electron": "8.0"
},
"bugfix/transform-v8-spread-parameters-in-optional-chaining": {
"firefox": "74",
"safari": "13.1",
"ios": "13.4"
}
}

View File

@ -1,458 +0,0 @@
{
"proposal-class-static-block": {
"chrome": "91",
"electron": "13.0"
},
"proposal-private-property-in-object": {
"chrome": "91",
"firefox": "90",
"electron": "13.0"
},
"proposal-class-properties": {
"chrome": "74",
"opera": "62",
"edge": "79",
"firefox": "90",
"safari": "14.1",
"node": "12",
"samsung": "11",
"electron": "6.0"
},
"proposal-private-methods": {
"chrome": "84",
"opera": "70",
"edge": "84",
"firefox": "90",
"safari": "15",
"node": "14.6",
"electron": "10.0"
},
"proposal-numeric-separator": {
"chrome": "75",
"opera": "62",
"edge": "79",
"firefox": "70",
"safari": "13",
"node": "12.5",
"ios": "13",
"samsung": "11",
"electron": "6.0"
},
"proposal-logical-assignment-operators": {
"chrome": "85",
"opera": "71",
"edge": "85",
"firefox": "79",
"safari": "14",
"node": "15",
"ios": "14",
"electron": "10.0"
},
"proposal-nullish-coalescing-operator": {
"chrome": "80",
"opera": "67",
"edge": "80",
"firefox": "72",
"safari": "13.1",
"node": "14",
"ios": "13.4",
"samsung": "13",
"electron": "8.0"
},
"proposal-optional-chaining": {
"firefox": "74",
"safari": "13.1",
"ios": "13.4"
},
"proposal-json-strings": {
"chrome": "66",
"opera": "53",
"edge": "79",
"firefox": "62",
"safari": "12",
"node": "10",
"ios": "12",
"samsung": "9",
"electron": "3.0"
},
"proposal-optional-catch-binding": {
"chrome": "66",
"opera": "53",
"edge": "79",
"firefox": "58",
"safari": "11.1",
"node": "10",
"ios": "11.3",
"samsung": "9",
"electron": "3.0"
},
"transform-parameters": {
"chrome": "49",
"opera": "36",
"edge": "18",
"firefox": "53",
"safari": "10",
"node": "6",
"ios": "10",
"samsung": "5",
"electron": "0.37"
},
"proposal-async-generator-functions": {
"chrome": "63",
"opera": "50",
"edge": "79",
"firefox": "57",
"safari": "12",
"node": "10",
"ios": "12",
"samsung": "8",
"electron": "3.0"
},
"proposal-object-rest-spread": {
"chrome": "60",
"opera": "47",
"edge": "79",
"firefox": "55",
"safari": "11.1",
"node": "8.3",
"ios": "11.3",
"samsung": "8",
"electron": "2.0"
},
"transform-dotall-regex": {
"chrome": "62",
"opera": "49",
"edge": "79",
"firefox": "78",
"safari": "11.1",
"node": "8.10",
"ios": "11.3",
"samsung": "8",
"electron": "3.0"
},
"proposal-unicode-property-regex": {
"chrome": "64",
"opera": "51",
"edge": "79",
"firefox": "78",
"safari": "11.1",
"node": "10",
"ios": "11.3",
"samsung": "9",
"electron": "3.0"
},
"transform-named-capturing-groups-regex": {
"chrome": "64",
"opera": "51",
"edge": "79",
"firefox": "78",
"safari": "11.1",
"node": "10",
"ios": "11.3",
"samsung": "9",
"electron": "3.0"
},
"transform-async-to-generator": {
"chrome": "55",
"opera": "42",
"edge": "15",
"firefox": "52",
"safari": "11",
"node": "7.6",
"ios": "11",
"samsung": "6",
"electron": "1.6"
},
"transform-exponentiation-operator": {
"chrome": "52",
"opera": "39",
"edge": "14",
"firefox": "52",
"safari": "10.1",
"node": "7",
"ios": "10.3",
"samsung": "6",
"electron": "1.3"
},
"transform-template-literals": {
"chrome": "41",
"opera": "28",
"edge": "13",
"firefox": "34",
"safari": "13",
"node": "4",
"ios": "13",
"samsung": "3.4",
"electron": "0.21"
},
"transform-literals": {
"chrome": "44",
"opera": "31",
"edge": "12",
"firefox": "53",
"safari": "9",
"node": "4",
"ios": "9",
"samsung": "4",
"electron": "0.30"
},
"transform-function-name": {
"chrome": "51",
"opera": "38",
"edge": "79",
"firefox": "53",
"safari": "10",
"node": "6.5",
"ios": "10",
"samsung": "5",
"electron": "1.2"
},
"transform-arrow-functions": {
"chrome": "47",
"opera": "34",
"edge": "13",
"firefox": "43",
"safari": "10",
"node": "6",
"ios": "10",
"samsung": "5",
"rhino": "1.7.13",
"electron": "0.36"
},
"transform-block-scoped-functions": {
"chrome": "41",
"opera": "28",
"edge": "12",
"firefox": "46",
"safari": "10",
"node": "4",
"ie": "11",
"ios": "10",
"samsung": "3.4",
"electron": "0.21"
},
"transform-classes": {
"chrome": "46",
"opera": "33",
"edge": "13",
"firefox": "45",
"safari": "10",
"node": "5",
"ios": "10",
"samsung": "5",
"electron": "0.36"
},
"transform-object-super": {
"chrome": "46",
"opera": "33",
"edge": "13",
"firefox": "45",
"safari": "10",
"node": "5",
"ios": "10",
"samsung": "5",
"electron": "0.36"
},
"transform-shorthand-properties": {
"chrome": "43",
"opera": "30",
"edge": "12",
"firefox": "33",
"safari": "9",
"node": "4",
"ios": "9",
"samsung": "4",
"electron": "0.27"
},
"transform-duplicate-keys": {
"chrome": "42",
"opera": "29",
"edge": "12",
"firefox": "34",
"safari": "9",
"node": "4",
"ios": "9",
"samsung": "3.4",
"electron": "0.25"
},
"transform-computed-properties": {
"chrome": "44",
"opera": "31",
"edge": "12",
"firefox": "34",
"safari": "7.1",
"node": "4",
"ios": "8",
"samsung": "4",
"electron": "0.30"
},
"transform-for-of": {
"chrome": "51",
"opera": "38",
"edge": "15",
"firefox": "53",
"safari": "10",
"node": "6.5",
"ios": "10",
"samsung": "5",
"electron": "1.2"
},
"transform-sticky-regex": {
"chrome": "49",
"opera": "36",
"edge": "13",
"firefox": "3",
"safari": "10",
"node": "6",
"ios": "10",
"samsung": "5",
"electron": "0.37"
},
"transform-unicode-escapes": {
"chrome": "44",
"opera": "31",
"edge": "12",
"firefox": "53",
"safari": "9",
"node": "4",
"ios": "9",
"samsung": "4",
"electron": "0.30"
},
"transform-unicode-regex": {
"chrome": "50",
"opera": "37",
"edge": "13",
"firefox": "46",
"safari": "12",
"node": "6",
"ios": "12",
"samsung": "5",
"electron": "1.1"
},
"transform-spread": {
"chrome": "46",
"opera": "33",
"edge": "13",
"firefox": "45",
"safari": "10",
"node": "5",
"ios": "10",
"samsung": "5",
"electron": "0.36"
},
"transform-destructuring": {
"chrome": "51",
"opera": "38",
"edge": "15",
"firefox": "53",
"safari": "10",
"node": "6.5",
"ios": "10",
"samsung": "5",
"electron": "1.2"
},
"transform-block-scoping": {
"chrome": "49",
"opera": "36",
"edge": "14",
"firefox": "51",
"safari": "11",
"node": "6",
"ios": "11",
"samsung": "5",
"electron": "0.37"
},
"transform-typeof-symbol": {
"chrome": "38",
"opera": "25",
"edge": "12",
"firefox": "36",
"safari": "9",
"node": "0.12",
"ios": "9",
"samsung": "3",
"rhino": "1.7.13",
"electron": "0.20"
},
"transform-new-target": {
"chrome": "46",
"opera": "33",
"edge": "14",
"firefox": "45",
"safari": "10",
"node": "5",
"ios": "10",
"samsung": "5",
"electron": "0.36"
},
"transform-regenerator": {
"chrome": "50",
"opera": "37",
"edge": "13",
"firefox": "53",
"safari": "10",
"node": "6",
"ios": "10",
"samsung": "5",
"electron": "1.1"
},
"transform-member-expression-literals": {
"chrome": "7",
"opera": "12",
"edge": "12",
"firefox": "2",
"safari": "5.1",
"node": "0.10",
"ie": "9",
"android": "4",
"ios": "6",
"phantom": "2",
"samsung": "1",
"rhino": "1.7.13",
"electron": "0.20"
},
"transform-property-literals": {
"chrome": "7",
"opera": "12",
"edge": "12",
"firefox": "2",
"safari": "5.1",
"node": "0.10",
"ie": "9",
"android": "4",
"ios": "6",
"phantom": "2",
"samsung": "1",
"rhino": "1.7.13",
"electron": "0.20"
},
"transform-reserved-words": {
"chrome": "13",
"opera": "10.50",
"edge": "12",
"firefox": "2",
"safari": "3.1",
"node": "0.10",
"ie": "9",
"android": "4.4",
"ios": "6",
"phantom": "2",
"samsung": "1",
"rhino": "1.7.13",
"electron": "0.20"
},
"proposal-export-namespace-from": {
"chrome": "72",
"and_chr": "72",
"edge": "79",
"firefox": "80",
"and_ff": "80",
"node": "13.2",
"opera": "60",
"op_mob": "51",
"samsung": "11.0",
"android": "72",
"electron": "5.0"
}
}

View File

@ -1 +0,0 @@
module.exports = require("./data/native-modules.json");

View File

@ -1 +0,0 @@
module.exports = require("./data/overlapping-plugins.json");

View File

@ -1,77 +0,0 @@
{
"_from": "@babel/compat-data@^7.15.0",
"_id": "@babel/compat-data@7.15.0",
"_inBundle": false,
"_integrity": "sha512-0NqAC1IJE0S0+lL1SWFMxMkz1pKCNCjI4tr2Zx4LJSXxCLAdr6KyArnY+sno5m3yH9g737ygOyPABDsnXkpxiA==",
"_location": "/@babel/compat-data",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@babel/compat-data@^7.15.0",
"name": "@babel/compat-data",
"escapedName": "@babel%2fcompat-data",
"scope": "@babel",
"rawSpec": "^7.15.0",
"saveSpec": null,
"fetchSpec": "^7.15.0"
},
"_requiredBy": [
"/@babel/helper-compilation-targets",
"/@babel/plugin-proposal-object-rest-spread",
"/@babel/preset-env",
"/babel-plugin-polyfill-corejs2",
"/expo-constants/@babel/preset-env",
"/jest-expo/@babel/preset-env"
],
"_resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.15.0.tgz",
"_shasum": "2dbaf8b85334796cafbb0f5793a90a2fc010b176",
"_spec": "@babel/compat-data@^7.15.0",
"_where": "/jd/work/GT2/newMaster/Ejectable/node_modules/@babel/helper-compilation-targets",
"author": {
"name": "The Babel Team",
"url": "https://babel.dev/team"
},
"bugs": {
"url": "https://github.com/babel/babel/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "",
"devDependencies": {
"@mdn/browser-compat-data": "^3.3.4",
"core-js-compat": "^3.16.0",
"electron-to-chromium": "^1.3.749"
},
"engines": {
"node": ">=6.9.0"
},
"exports": {
"./plugins": "./plugins.js",
"./native-modules": "./native-modules.js",
"./corejs2-built-ins": "./corejs2-built-ins.js",
"./corejs3-shipped-proposals": "./corejs3-shipped-proposals.js",
"./overlapping-plugins": "./overlapping-plugins.js",
"./plugin-bugfixes": "./plugin-bugfixes.js"
},
"homepage": "https://github.com/babel/babel#readme",
"keywords": [
"babel",
"compat-table",
"compat-data"
],
"license": "MIT",
"name": "@babel/compat-data",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/babel/babel.git",
"directory": "packages/babel-compat-data"
},
"scripts": {
"build-data": "./scripts/download-compat-table.sh && node ./scripts/build-data.js && node ./scripts/build-modules-support.js && node ./scripts/build-bugfixes-targets.js"
},
"version": "7.15.0"
}

View File

@ -1 +0,0 @@
module.exports = require("./data/plugin-bugfixes.json");

View File

@ -1 +0,0 @@
module.exports = require("./data/plugins.json");

View File

@ -1,22 +0,0 @@
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.

View File

@ -1,19 +0,0 @@
# @babel/core
> Babel compiler core.
See our website [@babel/core](https://babeljs.io/docs/en/babel-core) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20core%22+is%3Aopen) associated with this package.
## Install
Using npm:
```sh
npm install --save-dev @babel/core
```
or using yarn:
```sh
yarn add @babel/core --dev
```

View File

@ -1,325 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.makeWeakCache = makeWeakCache;
exports.makeWeakCacheSync = makeWeakCacheSync;
exports.makeStrongCache = makeStrongCache;
exports.makeStrongCacheSync = makeStrongCacheSync;
exports.assertSimpleType = assertSimpleType;
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _async = require("../gensync-utils/async");
var _util = require("./util");
const synchronize = gen => {
return _gensync()(gen).sync;
};
function* genTrue() {
return true;
}
function makeWeakCache(handler) {
return makeCachedFunction(WeakMap, handler);
}
function makeWeakCacheSync(handler) {
return synchronize(makeWeakCache(handler));
}
function makeStrongCache(handler) {
return makeCachedFunction(Map, handler);
}
function makeStrongCacheSync(handler) {
return synchronize(makeStrongCache(handler));
}
function makeCachedFunction(CallCache, handler) {
const callCacheSync = new CallCache();
const callCacheAsync = new CallCache();
const futureCache = new CallCache();
return function* cachedFunction(arg, data) {
const asyncContext = yield* (0, _async.isAsync)();
const callCache = asyncContext ? callCacheAsync : callCacheSync;
const cached = yield* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data);
if (cached.valid) return cached.value;
const cache = new CacheConfigurator(data);
const handlerResult = handler(arg, cache);
let finishLock;
let value;
if ((0, _util.isIterableIterator)(handlerResult)) {
const gen = handlerResult;
value = yield* (0, _async.onFirstPause)(gen, () => {
finishLock = setupAsyncLocks(cache, futureCache, arg);
});
} else {
value = handlerResult;
}
updateFunctionCache(callCache, cache, arg, value);
if (finishLock) {
futureCache.delete(arg);
finishLock.release(value);
}
return value;
};
}
function* getCachedValue(cache, arg, data) {
const cachedValue = cache.get(arg);
if (cachedValue) {
for (const {
value,
valid
} of cachedValue) {
if (yield* valid(data)) return {
valid: true,
value
};
}
}
return {
valid: false,
value: null
};
}
function* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data) {
const cached = yield* getCachedValue(callCache, arg, data);
if (cached.valid) {
return cached;
}
if (asyncContext) {
const cached = yield* getCachedValue(futureCache, arg, data);
if (cached.valid) {
const value = yield* (0, _async.waitFor)(cached.value.promise);
return {
valid: true,
value
};
}
}
return {
valid: false,
value: null
};
}
function setupAsyncLocks(config, futureCache, arg) {
const finishLock = new Lock();
updateFunctionCache(futureCache, config, arg, finishLock);
return finishLock;
}
function updateFunctionCache(cache, config, arg, value) {
if (!config.configured()) config.forever();
let cachedValue = cache.get(arg);
config.deactivate();
switch (config.mode()) {
case "forever":
cachedValue = [{
value,
valid: genTrue
}];
cache.set(arg, cachedValue);
break;
case "invalidate":
cachedValue = [{
value,
valid: config.validator()
}];
cache.set(arg, cachedValue);
break;
case "valid":
if (cachedValue) {
cachedValue.push({
value,
valid: config.validator()
});
} else {
cachedValue = [{
value,
valid: config.validator()
}];
cache.set(arg, cachedValue);
}
}
}
class CacheConfigurator {
constructor(data) {
this._active = true;
this._never = false;
this._forever = false;
this._invalidate = false;
this._configured = false;
this._pairs = [];
this._data = void 0;
this._data = data;
}
simple() {
return makeSimpleConfigurator(this);
}
mode() {
if (this._never) return "never";
if (this._forever) return "forever";
if (this._invalidate) return "invalidate";
return "valid";
}
forever() {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
if (this._never) {
throw new Error("Caching has already been configured with .never()");
}
this._forever = true;
this._configured = true;
}
never() {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
if (this._forever) {
throw new Error("Caching has already been configured with .forever()");
}
this._never = true;
this._configured = true;
}
using(handler) {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
if (this._never || this._forever) {
throw new Error("Caching has already been configured with .never or .forever()");
}
this._configured = true;
const key = handler(this._data);
const fn = (0, _async.maybeAsync)(handler, `You appear to be using an async cache handler, but Babel has been called synchronously`);
if ((0, _async.isThenable)(key)) {
return key.then(key => {
this._pairs.push([key, fn]);
return key;
});
}
this._pairs.push([key, fn]);
return key;
}
invalidate(handler) {
this._invalidate = true;
return this.using(handler);
}
validator() {
const pairs = this._pairs;
return function* (data) {
for (const [key, fn] of pairs) {
if (key !== (yield* fn(data))) return false;
}
return true;
};
}
deactivate() {
this._active = false;
}
configured() {
return this._configured;
}
}
function makeSimpleConfigurator(cache) {
function cacheFn(val) {
if (typeof val === "boolean") {
if (val) cache.forever();else cache.never();
return;
}
return cache.using(() => assertSimpleType(val()));
}
cacheFn.forever = () => cache.forever();
cacheFn.never = () => cache.never();
cacheFn.using = cb => cache.using(() => assertSimpleType(cb()));
cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb()));
return cacheFn;
}
function assertSimpleType(value) {
if ((0, _async.isThenable)(value)) {
throw new Error(`You appear to be using an async cache handler, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously handle your caching logic.`);
}
if (value != null && typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") {
throw new Error("Cache keys must be either string, boolean, number, null, or undefined.");
}
return value;
}
class Lock {
constructor() {
this.released = false;
this.promise = void 0;
this._resolve = void 0;
this.promise = new Promise(resolve => {
this._resolve = resolve;
});
}
release(value) {
this.released = true;
this._resolve(value);
}
}

View File

@ -1,556 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildPresetChain = buildPresetChain;
exports.buildRootChain = buildRootChain;
exports.buildPresetChainWalker = void 0;
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function _debug() {
const data = require("debug");
_debug = function () {
return data;
};
return data;
}
var _options = require("./validation/options");
var _patternToRegex = require("./pattern-to-regex");
var _printer = require("./printer");
var _files = require("./files");
var _caching = require("./caching");
var _configDescriptors = require("./config-descriptors");
const debug = _debug()("babel:config:config-chain");
function* buildPresetChain(arg, context) {
const chain = yield* buildPresetChainWalker(arg, context);
if (!chain) return null;
return {
plugins: dedupDescriptors(chain.plugins),
presets: dedupDescriptors(chain.presets),
options: chain.options.map(o => normalizeOptions(o)),
files: new Set()
};
}
const buildPresetChainWalker = makeChainWalker({
root: preset => loadPresetDescriptors(preset),
env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName),
overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index),
overridesEnv: (preset, index, envName) => loadPresetOverridesEnvDescriptors(preset)(index)(envName),
createLogger: () => () => {}
});
exports.buildPresetChainWalker = buildPresetChainWalker;
const loadPresetDescriptors = (0, _caching.makeWeakCacheSync)(preset => buildRootDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors));
const loadPresetEnvDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(envName => buildEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, envName)));
const loadPresetOverridesDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(index => buildOverrideDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index)));
const loadPresetOverridesEnvDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(index => (0, _caching.makeStrongCacheSync)(envName => buildOverrideEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index, envName))));
function* buildRootChain(opts, context) {
let configReport, babelRcReport;
const programmaticLogger = new _printer.ConfigPrinter();
const programmaticChain = yield* loadProgrammaticChain({
options: opts,
dirname: context.cwd
}, context, undefined, programmaticLogger);
if (!programmaticChain) return null;
const programmaticReport = yield* programmaticLogger.output();
let configFile;
if (typeof opts.configFile === "string") {
configFile = yield* (0, _files.loadConfig)(opts.configFile, context.cwd, context.envName, context.caller);
} else if (opts.configFile !== false) {
configFile = yield* (0, _files.findRootConfig)(context.root, context.envName, context.caller);
}
let {
babelrc,
babelrcRoots
} = opts;
let babelrcRootsDirectory = context.cwd;
const configFileChain = emptyChain();
const configFileLogger = new _printer.ConfigPrinter();
if (configFile) {
const validatedFile = validateConfigFile(configFile);
const result = yield* loadFileChain(validatedFile, context, undefined, configFileLogger);
if (!result) return null;
configReport = yield* configFileLogger.output();
if (babelrc === undefined) {
babelrc = validatedFile.options.babelrc;
}
if (babelrcRoots === undefined) {
babelrcRootsDirectory = validatedFile.dirname;
babelrcRoots = validatedFile.options.babelrcRoots;
}
mergeChain(configFileChain, result);
}
let ignoreFile, babelrcFile;
let isIgnored = false;
const fileChain = emptyChain();
if ((babelrc === true || babelrc === undefined) && typeof context.filename === "string") {
const pkgData = yield* (0, _files.findPackageData)(context.filename);
if (pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)) {
({
ignore: ignoreFile,
config: babelrcFile
} = yield* (0, _files.findRelativeConfig)(pkgData, context.envName, context.caller));
if (ignoreFile) {
fileChain.files.add(ignoreFile.filepath);
}
if (ignoreFile && shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)) {
isIgnored = true;
}
if (babelrcFile && !isIgnored) {
const validatedFile = validateBabelrcFile(babelrcFile);
const babelrcLogger = new _printer.ConfigPrinter();
const result = yield* loadFileChain(validatedFile, context, undefined, babelrcLogger);
if (!result) {
isIgnored = true;
} else {
babelRcReport = yield* babelrcLogger.output();
mergeChain(fileChain, result);
}
}
if (babelrcFile && isIgnored) {
fileChain.files.add(babelrcFile.filepath);
}
}
}
if (context.showConfig) {
console.log(`Babel configs on "${context.filename}" (ascending priority):\n` + [configReport, babelRcReport, programmaticReport].filter(x => !!x).join("\n\n") + "\n-----End Babel configs-----");
}
const chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain);
return {
plugins: isIgnored ? [] : dedupDescriptors(chain.plugins),
presets: isIgnored ? [] : dedupDescriptors(chain.presets),
options: isIgnored ? [] : chain.options.map(o => normalizeOptions(o)),
fileHandling: isIgnored ? "ignored" : "transpile",
ignore: ignoreFile || undefined,
babelrc: babelrcFile || undefined,
config: configFile || undefined,
files: chain.files
};
}
function babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory) {
if (typeof babelrcRoots === "boolean") return babelrcRoots;
const absoluteRoot = context.root;
if (babelrcRoots === undefined) {
return pkgData.directories.indexOf(absoluteRoot) !== -1;
}
let babelrcPatterns = babelrcRoots;
if (!Array.isArray(babelrcPatterns)) {
babelrcPatterns = [babelrcPatterns];
}
babelrcPatterns = babelrcPatterns.map(pat => {
return typeof pat === "string" ? _path().resolve(babelrcRootsDirectory, pat) : pat;
});
if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) {
return pkgData.directories.indexOf(absoluteRoot) !== -1;
}
return babelrcPatterns.some(pat => {
if (typeof pat === "string") {
pat = (0, _patternToRegex.default)(pat, babelrcRootsDirectory);
}
return pkgData.directories.some(directory => {
return matchPattern(pat, babelrcRootsDirectory, directory, context);
});
});
}
const validateConfigFile = (0, _caching.makeWeakCacheSync)(file => ({
filepath: file.filepath,
dirname: file.dirname,
options: (0, _options.validate)("configfile", file.options)
}));
const validateBabelrcFile = (0, _caching.makeWeakCacheSync)(file => ({
filepath: file.filepath,
dirname: file.dirname,
options: (0, _options.validate)("babelrcfile", file.options)
}));
const validateExtendFile = (0, _caching.makeWeakCacheSync)(file => ({
filepath: file.filepath,
dirname: file.dirname,
options: (0, _options.validate)("extendsfile", file.options)
}));
const loadProgrammaticChain = makeChainWalker({
root: input => buildRootDescriptors(input, "base", _configDescriptors.createCachedDescriptors),
env: (input, envName) => buildEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, envName),
overrides: (input, index) => buildOverrideDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index),
overridesEnv: (input, index, envName) => buildOverrideEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index, envName),
createLogger: (input, context, baseLogger) => buildProgrammaticLogger(input, context, baseLogger)
});
const loadFileChainWalker = makeChainWalker({
root: file => loadFileDescriptors(file),
env: (file, envName) => loadFileEnvDescriptors(file)(envName),
overrides: (file, index) => loadFileOverridesDescriptors(file)(index),
overridesEnv: (file, index, envName) => loadFileOverridesEnvDescriptors(file)(index)(envName),
createLogger: (file, context, baseLogger) => buildFileLogger(file.filepath, context, baseLogger)
});
function* loadFileChain(input, context, files, baseLogger) {
const chain = yield* loadFileChainWalker(input, context, files, baseLogger);
if (chain) {
chain.files.add(input.filepath);
}
return chain;
}
const loadFileDescriptors = (0, _caching.makeWeakCacheSync)(file => buildRootDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors));
const loadFileEnvDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(envName => buildEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, envName)));
const loadFileOverridesDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(index => buildOverrideDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index)));
const loadFileOverridesEnvDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(index => (0, _caching.makeStrongCacheSync)(envName => buildOverrideEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index, envName))));
function buildFileLogger(filepath, context, baseLogger) {
if (!baseLogger) {
return () => {};
}
return baseLogger.configure(context.showConfig, _printer.ChainFormatter.Config, {
filepath
});
}
function buildRootDescriptors({
dirname,
options
}, alias, descriptors) {
return descriptors(dirname, options, alias);
}
function buildProgrammaticLogger(_, context, baseLogger) {
var _context$caller;
if (!baseLogger) {
return () => {};
}
return baseLogger.configure(context.showConfig, _printer.ChainFormatter.Programmatic, {
callerName: (_context$caller = context.caller) == null ? void 0 : _context$caller.name
});
}
function buildEnvDescriptors({
dirname,
options
}, alias, descriptors, envName) {
const opts = options.env && options.env[envName];
return opts ? descriptors(dirname, opts, `${alias}.env["${envName}"]`) : null;
}
function buildOverrideDescriptors({
dirname,
options
}, alias, descriptors, index) {
const opts = options.overrides && options.overrides[index];
if (!opts) throw new Error("Assertion failure - missing override");
return descriptors(dirname, opts, `${alias}.overrides[${index}]`);
}
function buildOverrideEnvDescriptors({
dirname,
options
}, alias, descriptors, index, envName) {
const override = options.overrides && options.overrides[index];
if (!override) throw new Error("Assertion failure - missing override");
const opts = override.env && override.env[envName];
return opts ? descriptors(dirname, opts, `${alias}.overrides[${index}].env["${envName}"]`) : null;
}
function makeChainWalker({
root,
env,
overrides,
overridesEnv,
createLogger
}) {
return function* (input, context, files = new Set(), baseLogger) {
const {
dirname
} = input;
const flattenedConfigs = [];
const rootOpts = root(input);
if (configIsApplicable(rootOpts, dirname, context)) {
flattenedConfigs.push({
config: rootOpts,
envName: undefined,
index: undefined
});
const envOpts = env(input, context.envName);
if (envOpts && configIsApplicable(envOpts, dirname, context)) {
flattenedConfigs.push({
config: envOpts,
envName: context.envName,
index: undefined
});
}
(rootOpts.options.overrides || []).forEach((_, index) => {
const overrideOps = overrides(input, index);
if (configIsApplicable(overrideOps, dirname, context)) {
flattenedConfigs.push({
config: overrideOps,
index,
envName: undefined
});
const overrideEnvOpts = overridesEnv(input, index, context.envName);
if (overrideEnvOpts && configIsApplicable(overrideEnvOpts, dirname, context)) {
flattenedConfigs.push({
config: overrideEnvOpts,
index,
envName: context.envName
});
}
}
});
}
if (flattenedConfigs.some(({
config: {
options: {
ignore,
only
}
}
}) => shouldIgnore(context, ignore, only, dirname))) {
return null;
}
const chain = emptyChain();
const logger = createLogger(input, context, baseLogger);
for (const {
config,
index,
envName
} of flattenedConfigs) {
if (!(yield* mergeExtendsChain(chain, config.options, dirname, context, files, baseLogger))) {
return null;
}
logger(config, index, envName);
yield* mergeChainOpts(chain, config);
}
return chain;
};
}
function* mergeExtendsChain(chain, opts, dirname, context, files, baseLogger) {
if (opts.extends === undefined) return true;
const file = yield* (0, _files.loadConfig)(opts.extends, dirname, context.envName, context.caller);
if (files.has(file)) {
throw new Error(`Configuration cycle detected loading ${file.filepath}.\n` + `File already loaded following the config chain:\n` + Array.from(files, file => ` - ${file.filepath}`).join("\n"));
}
files.add(file);
const fileChain = yield* loadFileChain(validateExtendFile(file), context, files, baseLogger);
files.delete(file);
if (!fileChain) return false;
mergeChain(chain, fileChain);
return true;
}
function mergeChain(target, source) {
target.options.push(...source.options);
target.plugins.push(...source.plugins);
target.presets.push(...source.presets);
for (const file of source.files) {
target.files.add(file);
}
return target;
}
function* mergeChainOpts(target, {
options,
plugins,
presets
}) {
target.options.push(options);
target.plugins.push(...(yield* plugins()));
target.presets.push(...(yield* presets()));
return target;
}
function emptyChain() {
return {
options: [],
presets: [],
plugins: [],
files: new Set()
};
}
function normalizeOptions(opts) {
const options = Object.assign({}, opts);
delete options.extends;
delete options.env;
delete options.overrides;
delete options.plugins;
delete options.presets;
delete options.passPerPreset;
delete options.ignore;
delete options.only;
delete options.test;
delete options.include;
delete options.exclude;
if (Object.prototype.hasOwnProperty.call(options, "sourceMap")) {
options.sourceMaps = options.sourceMap;
delete options.sourceMap;
}
return options;
}
function dedupDescriptors(items) {
const map = new Map();
const descriptors = [];
for (const item of items) {
if (typeof item.value === "function") {
const fnKey = item.value;
let nameMap = map.get(fnKey);
if (!nameMap) {
nameMap = new Map();
map.set(fnKey, nameMap);
}
let desc = nameMap.get(item.name);
if (!desc) {
desc = {
value: item
};
descriptors.push(desc);
if (!item.ownPass) nameMap.set(item.name, desc);
} else {
desc.value = item;
}
} else {
descriptors.push({
value: item
});
}
}
return descriptors.reduce((acc, desc) => {
acc.push(desc.value);
return acc;
}, []);
}
function configIsApplicable({
options
}, dirname, context) {
return (options.test === undefined || configFieldIsApplicable(context, options.test, dirname)) && (options.include === undefined || configFieldIsApplicable(context, options.include, dirname)) && (options.exclude === undefined || !configFieldIsApplicable(context, options.exclude, dirname));
}
function configFieldIsApplicable(context, test, dirname) {
const patterns = Array.isArray(test) ? test : [test];
return matchesPatterns(context, patterns, dirname);
}
function shouldIgnore(context, ignore, only, dirname) {
if (ignore && matchesPatterns(context, ignore, dirname)) {
var _context$filename;
const message = `No config is applied to "${(_context$filename = context.filename) != null ? _context$filename : "(unknown)"}" because it matches one of \`ignore: ${JSON.stringify(ignore)}\` from "${dirname}"`;
debug(message);
if (context.showConfig) {
console.log(message);
}
return true;
}
if (only && !matchesPatterns(context, only, dirname)) {
var _context$filename2;
const message = `No config is applied to "${(_context$filename2 = context.filename) != null ? _context$filename2 : "(unknown)"}" because it fails to match one of \`only: ${JSON.stringify(only)}\` from "${dirname}"`;
debug(message);
if (context.showConfig) {
console.log(message);
}
return true;
}
return false;
}
function matchesPatterns(context, patterns, dirname) {
return patterns.some(pattern => matchPattern(pattern, dirname, context.filename, context));
}
function matchPattern(pattern, dirname, pathToTest, context) {
if (typeof pattern === "function") {
return !!pattern(pathToTest, {
dirname,
envName: context.envName,
caller: context.caller
});
}
if (typeof pathToTest !== "string") {
throw new Error(`Configuration contains string/RegExp pattern, but no filename was passed to Babel`);
}
if (typeof pattern === "string") {
pattern = (0, _patternToRegex.default)(pattern, dirname);
}
return pattern.test(pathToTest);
}

View File

@ -1,244 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createCachedDescriptors = createCachedDescriptors;
exports.createUncachedDescriptors = createUncachedDescriptors;
exports.createDescriptor = createDescriptor;
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _files = require("./files");
var _item = require("./item");
var _caching = require("./caching");
var _resolveTargets = require("./resolve-targets");
function isEqualDescriptor(a, b) {
return a.name === b.name && a.value === b.value && a.options === b.options && a.dirname === b.dirname && a.alias === b.alias && a.ownPass === b.ownPass && (a.file && a.file.request) === (b.file && b.file.request) && (a.file && a.file.resolved) === (b.file && b.file.resolved);
}
function* handlerOf(value) {
return value;
}
function optionsWithResolvedBrowserslistConfigFile(options, dirname) {
if (typeof options.browserslistConfigFile === "string") {
options.browserslistConfigFile = (0, _resolveTargets.resolveBrowserslistConfigFile)(options.browserslistConfigFile, dirname);
}
return options;
}
function createCachedDescriptors(dirname, options, alias) {
const {
plugins,
presets,
passPerPreset
} = options;
return {
options: optionsWithResolvedBrowserslistConfigFile(options, dirname),
plugins: plugins ? () => createCachedPluginDescriptors(plugins, dirname)(alias) : () => handlerOf([]),
presets: presets ? () => createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset) : () => handlerOf([])
};
}
function createUncachedDescriptors(dirname, options, alias) {
let plugins;
let presets;
return {
options: optionsWithResolvedBrowserslistConfigFile(options, dirname),
*plugins() {
if (!plugins) {
plugins = yield* createPluginDescriptors(options.plugins || [], dirname, alias);
}
return plugins;
},
*presets() {
if (!presets) {
presets = yield* createPresetDescriptors(options.presets || [], dirname, alias, !!options.passPerPreset);
}
return presets;
}
};
}
const PRESET_DESCRIPTOR_CACHE = new WeakMap();
const createCachedPresetDescriptors = (0, _caching.makeWeakCacheSync)((items, cache) => {
const dirname = cache.using(dir => dir);
return (0, _caching.makeStrongCacheSync)(alias => (0, _caching.makeStrongCache)(function* (passPerPreset) {
const descriptors = yield* createPresetDescriptors(items, dirname, alias, passPerPreset);
return descriptors.map(desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc));
}));
});
const PLUGIN_DESCRIPTOR_CACHE = new WeakMap();
const createCachedPluginDescriptors = (0, _caching.makeWeakCacheSync)((items, cache) => {
const dirname = cache.using(dir => dir);
return (0, _caching.makeStrongCache)(function* (alias) {
const descriptors = yield* createPluginDescriptors(items, dirname, alias);
return descriptors.map(desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc));
});
});
const DEFAULT_OPTIONS = {};
function loadCachedDescriptor(cache, desc) {
const {
value,
options = DEFAULT_OPTIONS
} = desc;
if (options === false) return desc;
let cacheByOptions = cache.get(value);
if (!cacheByOptions) {
cacheByOptions = new WeakMap();
cache.set(value, cacheByOptions);
}
let possibilities = cacheByOptions.get(options);
if (!possibilities) {
possibilities = [];
cacheByOptions.set(options, possibilities);
}
if (possibilities.indexOf(desc) === -1) {
const matches = possibilities.filter(possibility => isEqualDescriptor(possibility, desc));
if (matches.length > 0) {
return matches[0];
}
possibilities.push(desc);
}
return desc;
}
function* createPresetDescriptors(items, dirname, alias, passPerPreset) {
return yield* createDescriptors("preset", items, dirname, alias, passPerPreset);
}
function* createPluginDescriptors(items, dirname, alias) {
return yield* createDescriptors("plugin", items, dirname, alias);
}
function* createDescriptors(type, items, dirname, alias, ownPass) {
const descriptors = yield* _gensync().all(items.map((item, index) => createDescriptor(item, dirname, {
type,
alias: `${alias}$${index}`,
ownPass: !!ownPass
})));
assertNoDuplicates(descriptors);
return descriptors;
}
function* createDescriptor(pair, dirname, {
type,
alias,
ownPass
}) {
const desc = (0, _item.getItemDescriptor)(pair);
if (desc) {
return desc;
}
let name;
let options;
let value = pair;
if (Array.isArray(value)) {
if (value.length === 3) {
[value, options, name] = value;
} else {
[value, options] = value;
}
}
let file = undefined;
let filepath = null;
if (typeof value === "string") {
if (typeof type !== "string") {
throw new Error("To resolve a string-based item, the type of item must be given");
}
const resolver = type === "plugin" ? _files.loadPlugin : _files.loadPreset;
const request = value;
({
filepath,
value
} = yield* resolver(value, dirname));
file = {
request,
resolved: filepath
};
}
if (!value) {
throw new Error(`Unexpected falsy value: ${String(value)}`);
}
if (typeof value === "object" && value.__esModule) {
if (value.default) {
value = value.default;
} else {
throw new Error("Must export a default export when using ES6 modules.");
}
}
if (typeof value !== "object" && typeof value !== "function") {
throw new Error(`Unsupported format: ${typeof value}. Expected an object or a function.`);
}
if (filepath !== null && typeof value === "object" && value) {
throw new Error(`Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`);
}
return {
name,
alias: filepath || alias,
value,
options,
dirname,
ownPass,
file
};
}
function assertNoDuplicates(items) {
const map = new Map();
for (const item of items) {
if (typeof item.value !== "function") continue;
let nameMap = map.get(item.value);
if (!nameMap) {
nameMap = new Set();
map.set(item.value, nameMap);
}
if (nameMap.has(item.name)) {
const conflicts = items.filter(i => i.value === item.value);
throw new Error([`Duplicate plugin/preset detected.`, `If you'd like to use two separate instances of a plugin,`, `they need separate names, e.g.`, ``, ` plugins: [`, ` ['some-plugin', {}],`, ` ['some-plugin', {}, 'some unique name'],`, ` ]`, ``, `Duplicates detected are:`, `${JSON.stringify(conflicts, null, 2)}`].join("\n"));
}
nameMap.add(item.name);
}
}

View File

@ -1,357 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findConfigUpwards = findConfigUpwards;
exports.findRelativeConfig = findRelativeConfig;
exports.findRootConfig = findRootConfig;
exports.loadConfig = loadConfig;
exports.resolveShowConfigPath = resolveShowConfigPath;
exports.ROOT_CONFIG_FILENAMES = void 0;
function _debug() {
const data = require("debug");
_debug = function () {
return data;
};
return data;
}
function _fs() {
const data = require("fs");
_fs = function () {
return data;
};
return data;
}
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function _json() {
const data = require("json5");
_json = function () {
return data;
};
return data;
}
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _caching = require("../caching");
var _configApi = require("../helpers/config-api");
var _utils = require("./utils");
var _moduleTypes = require("./module-types");
var _patternToRegex = require("../pattern-to-regex");
var fs = require("../../gensync-utils/fs");
function _module() {
const data = require("module");
_module = function () {
return data;
};
return data;
}
const debug = _debug()("babel:config:loading:files:configuration");
const ROOT_CONFIG_FILENAMES = ["babel.config.js", "babel.config.cjs", "babel.config.mjs", "babel.config.json"];
exports.ROOT_CONFIG_FILENAMES = ROOT_CONFIG_FILENAMES;
const RELATIVE_CONFIG_FILENAMES = [".babelrc", ".babelrc.js", ".babelrc.cjs", ".babelrc.mjs", ".babelrc.json"];
const BABELIGNORE_FILENAME = ".babelignore";
function findConfigUpwards(rootDir) {
let dirname = rootDir;
for (;;) {
for (const filename of ROOT_CONFIG_FILENAMES) {
if (_fs().existsSync(_path().join(dirname, filename))) {
return dirname;
}
}
const nextDir = _path().dirname(dirname);
if (dirname === nextDir) break;
dirname = nextDir;
}
return null;
}
function* findRelativeConfig(packageData, envName, caller) {
let config = null;
let ignore = null;
const dirname = _path().dirname(packageData.filepath);
for (const loc of packageData.directories) {
if (!config) {
var _packageData$pkg;
config = yield* loadOneConfig(RELATIVE_CONFIG_FILENAMES, loc, envName, caller, ((_packageData$pkg = packageData.pkg) == null ? void 0 : _packageData$pkg.dirname) === loc ? packageToBabelConfig(packageData.pkg) : null);
}
if (!ignore) {
const ignoreLoc = _path().join(loc, BABELIGNORE_FILENAME);
ignore = yield* readIgnoreConfig(ignoreLoc);
if (ignore) {
debug("Found ignore %o from %o.", ignore.filepath, dirname);
}
}
}
return {
config,
ignore
};
}
function findRootConfig(dirname, envName, caller) {
return loadOneConfig(ROOT_CONFIG_FILENAMES, dirname, envName, caller);
}
function* loadOneConfig(names, dirname, envName, caller, previousConfig = null) {
const configs = yield* _gensync().all(names.map(filename => readConfig(_path().join(dirname, filename), envName, caller)));
const config = configs.reduce((previousConfig, config) => {
if (config && previousConfig) {
throw new Error(`Multiple configuration files found. Please remove one:\n` + ` - ${_path().basename(previousConfig.filepath)}\n` + ` - ${config.filepath}\n` + `from ${dirname}`);
}
return config || previousConfig;
}, previousConfig);
if (config) {
debug("Found configuration %o from %o.", config.filepath, dirname);
}
return config;
}
function* loadConfig(name, dirname, envName, caller) {
const filepath = (((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "8.9") ? require.resolve : (r, {
paths: [b]
}, M = require("module")) => {
let f = M._findPath(r, M._nodeModulePaths(b).concat(b));
if (f) return f;
f = new Error(`Cannot resolve module '${r}'`);
f.code = "MODULE_NOT_FOUND";
throw f;
})(name, {
paths: [dirname]
});
const conf = yield* readConfig(filepath, envName, caller);
if (!conf) {
throw new Error(`Config file ${filepath} contains no configuration data`);
}
debug("Loaded config %o from %o.", name, dirname);
return conf;
}
function readConfig(filepath, envName, caller) {
const ext = _path().extname(filepath);
return ext === ".js" || ext === ".cjs" || ext === ".mjs" ? readConfigJS(filepath, {
envName,
caller
}) : readConfigJSON5(filepath);
}
const LOADING_CONFIGS = new Set();
const readConfigJS = (0, _caching.makeStrongCache)(function* readConfigJS(filepath, cache) {
if (!_fs().existsSync(filepath)) {
cache.never();
return null;
}
if (LOADING_CONFIGS.has(filepath)) {
cache.never();
debug("Auto-ignoring usage of config %o.", filepath);
return {
filepath,
dirname: _path().dirname(filepath),
options: {}
};
}
let options;
try {
LOADING_CONFIGS.add(filepath);
options = yield* (0, _moduleTypes.default)(filepath, "You appear to be using a native ECMAScript module configuration " + "file, which is only supported when running Babel asynchronously.");
} catch (err) {
err.message = `${filepath}: Error while loading config - ${err.message}`;
throw err;
} finally {
LOADING_CONFIGS.delete(filepath);
}
let assertCache = false;
if (typeof options === "function") {
yield* [];
options = options((0, _configApi.makeConfigAPI)(cache));
assertCache = true;
}
if (!options || typeof options !== "object" || Array.isArray(options)) {
throw new Error(`${filepath}: Configuration should be an exported JavaScript object.`);
}
if (typeof options.then === "function") {
throw new Error(`You appear to be using an async configuration, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously return your config.`);
}
if (assertCache && !cache.configured()) throwConfigError();
return {
filepath,
dirname: _path().dirname(filepath),
options
};
});
const packageToBabelConfig = (0, _caching.makeWeakCacheSync)(file => {
const babel = file.options["babel"];
if (typeof babel === "undefined") return null;
if (typeof babel !== "object" || Array.isArray(babel) || babel === null) {
throw new Error(`${file.filepath}: .babel property must be an object`);
}
return {
filepath: file.filepath,
dirname: file.dirname,
options: babel
};
});
const readConfigJSON5 = (0, _utils.makeStaticFileCache)((filepath, content) => {
let options;
try {
options = _json().parse(content);
} catch (err) {
err.message = `${filepath}: Error while parsing config - ${err.message}`;
throw err;
}
if (!options) throw new Error(`${filepath}: No config detected`);
if (typeof options !== "object") {
throw new Error(`${filepath}: Config returned typeof ${typeof options}`);
}
if (Array.isArray(options)) {
throw new Error(`${filepath}: Expected config object but found array`);
}
return {
filepath,
dirname: _path().dirname(filepath),
options
};
});
const readIgnoreConfig = (0, _utils.makeStaticFileCache)((filepath, content) => {
const ignoreDir = _path().dirname(filepath);
const ignorePatterns = content.split("\n").map(line => line.replace(/#(.*?)$/, "").trim()).filter(line => !!line);
for (const pattern of ignorePatterns) {
if (pattern[0] === "!") {
throw new Error(`Negation of file paths is not supported.`);
}
}
return {
filepath,
dirname: _path().dirname(filepath),
ignore: ignorePatterns.map(pattern => (0, _patternToRegex.default)(pattern, ignoreDir))
};
});
function* resolveShowConfigPath(dirname) {
const targetPath = process.env.BABEL_SHOW_CONFIG_FOR;
if (targetPath != null) {
const absolutePath = _path().resolve(dirname, targetPath);
const stats = yield* fs.stat(absolutePath);
if (!stats.isFile()) {
throw new Error(`${absolutePath}: BABEL_SHOW_CONFIG_FOR must refer to a regular file, directories are not supported.`);
}
return absolutePath;
}
return null;
}
function throwConfigError() {
throw new Error(`\
Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured
for various types of caching, using the first param of their handler functions:
module.exports = function(api) {
// The API exposes the following:
// Cache the returned value forever and don't call this function again.
api.cache(true);
// Don't cache at all. Not recommended because it will be very slow.
api.cache(false);
// Cached based on the value of some function. If this function returns a value different from
// a previously-encountered value, the plugins will re-evaluate.
var env = api.cache(() => process.env.NODE_ENV);
// If testing for a specific env, we recommend specifics to avoid instantiating a plugin for
// any possible NODE_ENV value that might come up during plugin execution.
var isProd = api.cache(() => process.env.NODE_ENV === "production");
// .cache(fn) will perform a linear search though instances to find the matching plugin based
// based on previous instantiated plugins. If you want to recreate the plugin and discard the
// previous instance whenever something changes, you may use:
var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production");
// Note, we also expose the following more-verbose versions of the above examples:
api.cache.forever(); // api.cache(true)
api.cache.never(); // api.cache(false)
api.cache.using(fn); // api.cache(fn)
// Return the value that will be cached.
return { };
};`);
}

View File

@ -1,10 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = import_;
function import_(filepath) {
return import(filepath);
}

View File

@ -1,67 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findConfigUpwards = findConfigUpwards;
exports.findPackageData = findPackageData;
exports.findRelativeConfig = findRelativeConfig;
exports.findRootConfig = findRootConfig;
exports.loadConfig = loadConfig;
exports.resolveShowConfigPath = resolveShowConfigPath;
exports.resolvePlugin = resolvePlugin;
exports.resolvePreset = resolvePreset;
exports.loadPlugin = loadPlugin;
exports.loadPreset = loadPreset;
exports.ROOT_CONFIG_FILENAMES = void 0;
function findConfigUpwards(rootDir) {
return null;
}
function* findPackageData(filepath) {
return {
filepath,
directories: [],
pkg: null,
isPackage: false
};
}
function* findRelativeConfig(pkgData, envName, caller) {
return {
config: null,
ignore: null
};
}
function* findRootConfig(dirname, envName, caller) {
return null;
}
function* loadConfig(name, dirname, envName, caller) {
throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`);
}
function* resolveShowConfigPath(dirname) {
return null;
}
const ROOT_CONFIG_FILENAMES = [];
exports.ROOT_CONFIG_FILENAMES = ROOT_CONFIG_FILENAMES;
function resolvePlugin(name, dirname) {
return null;
}
function resolvePreset(name, dirname) {
return null;
}
function loadPlugin(name, dirname) {
throw new Error(`Cannot load plugin ${name} relative to ${dirname} in a browser`);
}
function loadPreset(name, dirname) {
throw new Error(`Cannot load preset ${name} relative to ${dirname} in a browser`);
}

View File

@ -1,79 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "findPackageData", {
enumerable: true,
get: function () {
return _package.findPackageData;
}
});
Object.defineProperty(exports, "findConfigUpwards", {
enumerable: true,
get: function () {
return _configuration.findConfigUpwards;
}
});
Object.defineProperty(exports, "findRelativeConfig", {
enumerable: true,
get: function () {
return _configuration.findRelativeConfig;
}
});
Object.defineProperty(exports, "findRootConfig", {
enumerable: true,
get: function () {
return _configuration.findRootConfig;
}
});
Object.defineProperty(exports, "loadConfig", {
enumerable: true,
get: function () {
return _configuration.loadConfig;
}
});
Object.defineProperty(exports, "resolveShowConfigPath", {
enumerable: true,
get: function () {
return _configuration.resolveShowConfigPath;
}
});
Object.defineProperty(exports, "ROOT_CONFIG_FILENAMES", {
enumerable: true,
get: function () {
return _configuration.ROOT_CONFIG_FILENAMES;
}
});
Object.defineProperty(exports, "resolvePlugin", {
enumerable: true,
get: function () {
return _plugins.resolvePlugin;
}
});
Object.defineProperty(exports, "resolvePreset", {
enumerable: true,
get: function () {
return _plugins.resolvePreset;
}
});
Object.defineProperty(exports, "loadPlugin", {
enumerable: true,
get: function () {
return _plugins.loadPlugin;
}
});
Object.defineProperty(exports, "loadPreset", {
enumerable: true,
get: function () {
return _plugins.loadPreset;
}
});
var _package = require("./package");
var _configuration = require("./configuration");
var _plugins = require("./plugins");
({});

View File

@ -1,104 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = loadCjsOrMjsDefault;
var _async = require("../../gensync-utils/async");
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function _url() {
const data = require("url");
_url = function () {
return data;
};
return data;
}
function _module() {
const data = require("module");
_module = function () {
return data;
};
return data;
}
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); }); }; }
let import_;
try {
import_ = require("./import").default;
} catch (_unused) {}
function* loadCjsOrMjsDefault(filepath, asyncError, fallbackToTranspiledModule = false) {
switch (guessJSModuleType(filepath)) {
case "cjs":
return loadCjsDefault(filepath, fallbackToTranspiledModule);
case "unknown":
try {
return loadCjsDefault(filepath, fallbackToTranspiledModule);
} catch (e) {
if (e.code !== "ERR_REQUIRE_ESM") throw e;
}
case "mjs":
if (yield* (0, _async.isAsync)()) {
return yield* (0, _async.waitFor)(loadMjsDefault(filepath));
}
throw new Error(asyncError);
}
}
function guessJSModuleType(filename) {
switch (_path().extname(filename)) {
case ".cjs":
return "cjs";
case ".mjs":
return "mjs";
default:
return "unknown";
}
}
function loadCjsDefault(filepath, fallbackToTranspiledModule) {
const module = require(filepath);
return module != null && module.__esModule ? module.default || (fallbackToTranspiledModule ? module : undefined) : module;
}
function loadMjsDefault(_x) {
return _loadMjsDefault.apply(this, arguments);
}
function _loadMjsDefault() {
_loadMjsDefault = _asyncToGenerator(function* (filepath) {
if (!import_) {
throw new Error("Internal error: Native ECMAScript modules aren't supported" + " by this platform.\n");
}
const module = yield import_((0, _url().pathToFileURL)(filepath));
return module.default;
});
return _loadMjsDefault.apply(this, arguments);
}

View File

@ -1,76 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findPackageData = findPackageData;
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
var _utils = require("./utils");
const PACKAGE_FILENAME = "package.json";
function* findPackageData(filepath) {
let pkg = null;
const directories = [];
let isPackage = true;
let dirname = _path().dirname(filepath);
while (!pkg && _path().basename(dirname) !== "node_modules") {
directories.push(dirname);
pkg = yield* readConfigPackage(_path().join(dirname, PACKAGE_FILENAME));
const nextLoc = _path().dirname(dirname);
if (dirname === nextLoc) {
isPackage = false;
break;
}
dirname = nextLoc;
}
return {
filepath,
directories,
pkg,
isPackage
};
}
const readConfigPackage = (0, _utils.makeStaticFileCache)((filepath, content) => {
let options;
try {
options = JSON.parse(content);
} catch (err) {
err.message = `${filepath}: Error while parsing JSON - ${err.message}`;
throw err;
}
if (!options) throw new Error(`${filepath}: No config detected`);
if (typeof options !== "object") {
throw new Error(`${filepath}: Config returned typeof ${typeof options}`);
}
if (Array.isArray(options)) {
throw new Error(`${filepath}: Expected config object but found array`);
}
return {
filepath,
dirname: _path().dirname(filepath),
options
};
});

View File

@ -1,206 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.resolvePlugin = resolvePlugin;
exports.resolvePreset = resolvePreset;
exports.loadPlugin = loadPlugin;
exports.loadPreset = loadPreset;
function _debug() {
const data = require("debug");
_debug = function () {
return data;
};
return data;
}
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
var _moduleTypes = require("./module-types");
function _module() {
const data = require("module");
_module = function () {
return data;
};
return data;
}
const debug = _debug()("babel:config:loading:files:plugins");
const EXACT_RE = /^module:/;
const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/;
const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/;
const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/;
const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/;
const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/;
const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/;
const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/;
function resolvePlugin(name, dirname) {
return resolveStandardizedName("plugin", name, dirname);
}
function resolvePreset(name, dirname) {
return resolveStandardizedName("preset", name, dirname);
}
function* loadPlugin(name, dirname) {
const filepath = resolvePlugin(name, dirname);
if (!filepath) {
throw new Error(`Plugin ${name} not found relative to ${dirname}`);
}
const value = yield* requireModule("plugin", filepath);
debug("Loaded plugin %o from %o.", name, dirname);
return {
filepath,
value
};
}
function* loadPreset(name, dirname) {
const filepath = resolvePreset(name, dirname);
if (!filepath) {
throw new Error(`Preset ${name} not found relative to ${dirname}`);
}
const value = yield* requireModule("preset", filepath);
debug("Loaded preset %o from %o.", name, dirname);
return {
filepath,
value
};
}
function standardizeName(type, name) {
if (_path().isAbsolute(name)) return name;
const isPreset = type === "preset";
return name.replace(isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE, `babel-${type}-`).replace(isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE, `$1${type}-`).replace(isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE, `$1babel-${type}-`).replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`).replace(EXACT_RE, "");
}
function resolveStandardizedName(type, name, dirname = process.cwd()) {
const standardizedName = standardizeName(type, name);
try {
return (((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "8.9") ? require.resolve : (r, {
paths: [b]
}, M = require("module")) => {
let f = M._findPath(r, M._nodeModulePaths(b).concat(b));
if (f) return f;
f = new Error(`Cannot resolve module '${r}'`);
f.code = "MODULE_NOT_FOUND";
throw f;
})(standardizedName, {
paths: [dirname]
});
} catch (e) {
if (e.code !== "MODULE_NOT_FOUND") throw e;
if (standardizedName !== name) {
let resolvedOriginal = false;
try {
(((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "8.9") ? require.resolve : (r, {
paths: [b]
}, M = require("module")) => {
let f = M._findPath(r, M._nodeModulePaths(b).concat(b));
if (f) return f;
f = new Error(`Cannot resolve module '${r}'`);
f.code = "MODULE_NOT_FOUND";
throw f;
})(name, {
paths: [dirname]
});
resolvedOriginal = true;
} catch (_unused) {}
if (resolvedOriginal) {
e.message += `\n- If you want to resolve "${name}", use "module:${name}"`;
}
}
let resolvedBabel = false;
try {
(((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "8.9") ? require.resolve : (r, {
paths: [b]
}, M = require("module")) => {
let f = M._findPath(r, M._nodeModulePaths(b).concat(b));
if (f) return f;
f = new Error(`Cannot resolve module '${r}'`);
f.code = "MODULE_NOT_FOUND";
throw f;
})(standardizeName(type, "@babel/" + name), {
paths: [dirname]
});
resolvedBabel = true;
} catch (_unused2) {}
if (resolvedBabel) {
e.message += `\n- Did you mean "@babel/${name}"?`;
}
let resolvedOppositeType = false;
const oppositeType = type === "preset" ? "plugin" : "preset";
try {
(((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "8.9") ? require.resolve : (r, {
paths: [b]
}, M = require("module")) => {
let f = M._findPath(r, M._nodeModulePaths(b).concat(b));
if (f) return f;
f = new Error(`Cannot resolve module '${r}'`);
f.code = "MODULE_NOT_FOUND";
throw f;
})(standardizeName(oppositeType, name), {
paths: [dirname]
});
resolvedOppositeType = true;
} catch (_unused3) {}
if (resolvedOppositeType) {
e.message += `\n- Did you accidentally pass a ${oppositeType} as a ${type}?`;
}
throw e;
}
}
const LOADING_MODULES = new Set();
function* requireModule(type, name) {
if (LOADING_MODULES.has(name)) {
throw new Error(`Reentrant ${type} detected trying to load "${name}". This module is not ignored ` + "and is trying to load itself while compiling itself, leading to a dependency cycle. " + 'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.');
}
try {
LOADING_MODULES.add(name);
return yield* (0, _moduleTypes.default)(name, `You appear to be using a native ECMAScript module ${type}, ` + "which is only supported when running Babel asynchronously.", true);
} catch (err) {
err.message = `[BABEL]: ${err.message} (While processing: ${name})`;
throw err;
} finally {
LOADING_MODULES.delete(name);
}
}

View File

@ -1,44 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.makeStaticFileCache = makeStaticFileCache;
var _caching = require("../caching");
var fs = require("../../gensync-utils/fs");
function _fs2() {
const data = require("fs");
_fs2 = function () {
return data;
};
return data;
}
function makeStaticFileCache(fn) {
return (0, _caching.makeStrongCache)(function* (filepath, cache) {
const cached = cache.invalidate(() => fileMtime(filepath));
if (cached === null) {
return null;
}
return fn(filepath, yield* fs.readFile(filepath, "utf8"));
});
}
function fileMtime(filepath) {
if (!_fs2().existsSync(filepath)) return null;
try {
return +_fs2().statSync(filepath).mtime;
} catch (e) {
if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e;
}
return null;
}

View File

@ -1,338 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _async = require("../gensync-utils/async");
var _util = require("./util");
var context = require("../index");
var _plugin = require("./plugin");
var _item = require("./item");
var _configChain = require("./config-chain");
function _traverse() {
const data = require("@babel/traverse");
_traverse = function () {
return data;
};
return data;
}
var _caching = require("./caching");
var _options = require("./validation/options");
var _plugins = require("./validation/plugins");
var _configApi = require("./helpers/config-api");
var _partial = require("./partial");
var Context = require("./cache-contexts");
var _default = _gensync()(function* loadFullConfig(inputOpts) {
var _opts$assumptions;
const result = yield* (0, _partial.default)(inputOpts);
if (!result) {
return null;
}
const {
options,
context,
fileHandling
} = result;
if (fileHandling === "ignored") {
return null;
}
const optionDefaults = {};
const {
plugins,
presets
} = options;
if (!plugins || !presets) {
throw new Error("Assertion failure - plugins and presets exist");
}
const presetContext = Object.assign({}, context, {
targets: options.targets
});
const toDescriptor = item => {
const desc = (0, _item.getItemDescriptor)(item);
if (!desc) {
throw new Error("Assertion failure - must be config item");
}
return desc;
};
const presetsDescriptors = presets.map(toDescriptor);
const initialPluginsDescriptors = plugins.map(toDescriptor);
const pluginDescriptorsByPass = [[]];
const passes = [];
const ignored = yield* enhanceError(context, function* recursePresetDescriptors(rawPresets, pluginDescriptorsPass) {
const presets = [];
for (let i = 0; i < rawPresets.length; i++) {
const descriptor = rawPresets[i];
if (descriptor.options !== false) {
try {
if (descriptor.ownPass) {
presets.push({
preset: yield* loadPresetDescriptor(descriptor, presetContext),
pass: []
});
} else {
presets.unshift({
preset: yield* loadPresetDescriptor(descriptor, presetContext),
pass: pluginDescriptorsPass
});
}
} catch (e) {
if (e.code === "BABEL_UNKNOWN_OPTION") {
(0, _options.checkNoUnwrappedItemOptionPairs)(rawPresets, i, "preset", e);
}
throw e;
}
}
}
if (presets.length > 0) {
pluginDescriptorsByPass.splice(1, 0, ...presets.map(o => o.pass).filter(p => p !== pluginDescriptorsPass));
for (const {
preset,
pass
} of presets) {
if (!preset) return true;
pass.push(...preset.plugins);
const ignored = yield* recursePresetDescriptors(preset.presets, pass);
if (ignored) return true;
preset.options.forEach(opts => {
(0, _util.mergeOptions)(optionDefaults, opts);
});
}
}
})(presetsDescriptors, pluginDescriptorsByPass[0]);
if (ignored) return null;
const opts = optionDefaults;
(0, _util.mergeOptions)(opts, options);
const pluginContext = Object.assign({}, presetContext, {
assumptions: (_opts$assumptions = opts.assumptions) != null ? _opts$assumptions : {}
});
yield* enhanceError(context, function* loadPluginDescriptors() {
pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors);
for (const descs of pluginDescriptorsByPass) {
const pass = [];
passes.push(pass);
for (let i = 0; i < descs.length; i++) {
const descriptor = descs[i];
if (descriptor.options !== false) {
try {
pass.push(yield* loadPluginDescriptor(descriptor, pluginContext));
} catch (e) {
if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") {
(0, _options.checkNoUnwrappedItemOptionPairs)(descs, i, "plugin", e);
}
throw e;
}
}
}
}
})();
opts.plugins = passes[0];
opts.presets = passes.slice(1).filter(plugins => plugins.length > 0).map(plugins => ({
plugins
}));
opts.passPerPreset = opts.presets.length > 0;
return {
options: opts,
passes: passes
};
});
exports.default = _default;
function enhanceError(context, fn) {
return function* (arg1, arg2) {
try {
return yield* fn(arg1, arg2);
} catch (e) {
if (!/^\[BABEL\]/.test(e.message)) {
e.message = `[BABEL] ${context.filename || "unknown"}: ${e.message}`;
}
throw e;
}
};
}
const makeDescriptorLoader = apiFactory => (0, _caching.makeWeakCache)(function* ({
value,
options,
dirname,
alias
}, cache) {
if (options === false) throw new Error("Assertion failure");
options = options || {};
let item = value;
if (typeof value === "function") {
const factory = (0, _async.maybeAsync)(value, `You appear to be using an async plugin/preset, but Babel has been called synchronously`);
const api = Object.assign({}, context, apiFactory(cache));
try {
item = yield* factory(api, options, dirname);
} catch (e) {
if (alias) {
e.message += ` (While processing: ${JSON.stringify(alias)})`;
}
throw e;
}
}
if (!item || typeof item !== "object") {
throw new Error("Plugin/Preset did not return an object.");
}
if ((0, _async.isThenable)(item)) {
yield* [];
throw new Error(`You appear to be using a promise as a plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version. ` + `As an alternative, you can prefix the promise with "await". ` + `(While processing: ${JSON.stringify(alias)})`);
}
return {
value: item,
options,
dirname,
alias
};
});
const pluginDescriptorLoader = makeDescriptorLoader(_configApi.makePluginAPI);
const presetDescriptorLoader = makeDescriptorLoader(_configApi.makePresetAPI);
function* loadPluginDescriptor(descriptor, context) {
if (descriptor.value instanceof _plugin.default) {
if (descriptor.options) {
throw new Error("Passed options to an existing Plugin instance will not work.");
}
return descriptor.value;
}
return yield* instantiatePlugin(yield* pluginDescriptorLoader(descriptor, context), context);
}
const instantiatePlugin = (0, _caching.makeWeakCache)(function* ({
value,
options,
dirname,
alias
}, cache) {
const pluginObj = (0, _plugins.validatePluginObject)(value);
const plugin = Object.assign({}, pluginObj);
if (plugin.visitor) {
plugin.visitor = _traverse().default.explode(Object.assign({}, plugin.visitor));
}
if (plugin.inherits) {
const inheritsDescriptor = {
name: undefined,
alias: `${alias}$inherits`,
value: plugin.inherits,
options,
dirname
};
const inherits = yield* (0, _async.forwardAsync)(loadPluginDescriptor, run => {
return cache.invalidate(data => run(inheritsDescriptor, data));
});
plugin.pre = chain(inherits.pre, plugin.pre);
plugin.post = chain(inherits.post, plugin.post);
plugin.manipulateOptions = chain(inherits.manipulateOptions, plugin.manipulateOptions);
plugin.visitor = _traverse().default.visitors.merge([inherits.visitor || {}, plugin.visitor || {}]);
}
return new _plugin.default(plugin, options, alias);
});
const validateIfOptionNeedsFilename = (options, descriptor) => {
if (options.test || options.include || options.exclude) {
const formattedPresetName = descriptor.name ? `"${descriptor.name}"` : "/* your preset */";
throw new Error([`Preset ${formattedPresetName} requires a filename to be set when babel is called directly,`, `\`\`\``, `babel.transform(code, { filename: 'file.ts', presets: [${formattedPresetName}] });`, `\`\`\``, `See https://babeljs.io/docs/en/options#filename for more information.`].join("\n"));
}
};
const validatePreset = (preset, context, descriptor) => {
if (!context.filename) {
const {
options
} = preset;
validateIfOptionNeedsFilename(options, descriptor);
if (options.overrides) {
options.overrides.forEach(overrideOptions => validateIfOptionNeedsFilename(overrideOptions, descriptor));
}
}
};
function* loadPresetDescriptor(descriptor, context) {
const preset = instantiatePreset(yield* presetDescriptorLoader(descriptor, context));
validatePreset(preset, context, descriptor);
return yield* (0, _configChain.buildPresetChain)(preset, context);
}
const instantiatePreset = (0, _caching.makeWeakCacheSync)(({
value,
dirname,
alias
}) => {
return {
options: (0, _options.validate)("preset", value),
alias,
dirname
};
});
function chain(a, b) {
const fns = [a, b].filter(Boolean);
if (fns.length <= 1) return fns[0];
return function (...args) {
for (const fn of fns) {
fn.apply(this, args);
}
};
}

View File

@ -1,103 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.makeConfigAPI = makeConfigAPI;
exports.makePresetAPI = makePresetAPI;
exports.makePluginAPI = makePluginAPI;
function _semver() {
const data = require("semver");
_semver = function () {
return data;
};
return data;
}
var _ = require("../../");
var _caching = require("../caching");
var Context = require("../cache-contexts");
function makeConfigAPI(cache) {
const env = value => cache.using(data => {
if (typeof value === "undefined") return data.envName;
if (typeof value === "function") {
return (0, _caching.assertSimpleType)(value(data.envName));
}
if (!Array.isArray(value)) value = [value];
return value.some(entry => {
if (typeof entry !== "string") {
throw new Error("Unexpected non-string value");
}
return entry === data.envName;
});
});
const caller = cb => cache.using(data => (0, _caching.assertSimpleType)(cb(data.caller)));
return {
version: _.version,
cache: cache.simple(),
env,
async: () => false,
caller,
assertVersion
};
}
function makePresetAPI(cache) {
const targets = () => JSON.parse(cache.using(data => JSON.stringify(data.targets)));
return Object.assign({}, makeConfigAPI(cache), {
targets
});
}
function makePluginAPI(cache) {
const assumption = name => cache.using(data => data.assumptions[name]);
return Object.assign({}, makePresetAPI(cache), {
assumption
});
}
function assertVersion(range) {
if (typeof range === "number") {
if (!Number.isInteger(range)) {
throw new Error("Expected string or integer value.");
}
range = `^${range}.0.0-0`;
}
if (typeof range !== "string") {
throw new Error("Expected string or integer value.");
}
if (_semver().satisfies(_.version, range)) return;
const limit = Error.stackTraceLimit;
if (typeof limit === "number" && limit < 25) {
Error.stackTraceLimit = 25;
}
const err = new Error(`Requires Babel "${range}", but was loaded with "${_.version}". ` + `If you are sure you have a compatible version of @babel/core, ` + `it is likely that something in your build process is loading the ` + `wrong version. Inspect the stack trace of this error to look for ` + `the first entry that doesn't mention "@babel/core" or "babel-core" ` + `to see what is calling Babel.`);
if (typeof limit === "number") {
Error.stackTraceLimit = limit;
}
throw Object.assign(err, {
code: "BABEL_VERSION_UNSUPPORTED",
version: _.version,
range
});
}

View File

@ -1,10 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getEnv = getEnv;
function getEnv(defaultValue = "development") {
return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue;
}

View File

@ -1,74 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createConfigItem = createConfigItem;
Object.defineProperty(exports, "default", {
enumerable: true,
get: function () {
return _full.default;
}
});
exports.createConfigItemAsync = exports.createConfigItemSync = exports.loadOptionsAsync = exports.loadOptionsSync = exports.loadOptions = exports.loadPartialConfigAsync = exports.loadPartialConfigSync = exports.loadPartialConfig = void 0;
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _full = require("./full");
var _partial = require("./partial");
var _item = require("./item");
const loadOptionsRunner = _gensync()(function* (opts) {
var _config$options;
const config = yield* (0, _full.default)(opts);
return (_config$options = config == null ? void 0 : config.options) != null ? _config$options : null;
});
const createConfigItemRunner = _gensync()(_item.createConfigItem);
const maybeErrback = runner => (opts, callback) => {
if (callback === undefined && typeof opts === "function") {
callback = opts;
opts = undefined;
}
return callback ? runner.errback(opts, callback) : runner.sync(opts);
};
const loadPartialConfig = maybeErrback(_partial.loadPartialConfig);
exports.loadPartialConfig = loadPartialConfig;
const loadPartialConfigSync = _partial.loadPartialConfig.sync;
exports.loadPartialConfigSync = loadPartialConfigSync;
const loadPartialConfigAsync = _partial.loadPartialConfig.async;
exports.loadPartialConfigAsync = loadPartialConfigAsync;
const loadOptions = maybeErrback(loadOptionsRunner);
exports.loadOptions = loadOptions;
const loadOptionsSync = loadOptionsRunner.sync;
exports.loadOptionsSync = loadOptionsSync;
const loadOptionsAsync = loadOptionsRunner.async;
exports.loadOptionsAsync = loadOptionsAsync;
const createConfigItemSync = createConfigItemRunner.sync;
exports.createConfigItemSync = createConfigItemSync;
const createConfigItemAsync = createConfigItemRunner.async;
exports.createConfigItemAsync = createConfigItemAsync;
function createConfigItem(target, options, callback) {
if (callback !== undefined) {
return createConfigItemRunner.errback(target, options, callback);
} else if (typeof options === "function") {
return createConfigItemRunner.errback(target, undefined, callback);
} else {
return createConfigItemRunner.sync(target, options);
}
}

View File

@ -1,76 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createItemFromDescriptor = createItemFromDescriptor;
exports.createConfigItem = createConfigItem;
exports.getItemDescriptor = getItemDescriptor;
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
var _configDescriptors = require("./config-descriptors");
function createItemFromDescriptor(desc) {
return new ConfigItem(desc);
}
function* createConfigItem(value, {
dirname = ".",
type
} = {}) {
const descriptor = yield* (0, _configDescriptors.createDescriptor)(value, _path().resolve(dirname), {
type,
alias: "programmatic item"
});
return createItemFromDescriptor(descriptor);
}
function getItemDescriptor(item) {
if (item != null && item[CONFIG_ITEM_BRAND]) {
return item._descriptor;
}
return undefined;
}
const CONFIG_ITEM_BRAND = Symbol.for("@babel/core@7 - ConfigItem");
class ConfigItem {
constructor(descriptor) {
this._descriptor = void 0;
this[CONFIG_ITEM_BRAND] = true;
this.value = void 0;
this.options = void 0;
this.dirname = void 0;
this.name = void 0;
this.file = void 0;
this._descriptor = descriptor;
Object.defineProperty(this, "_descriptor", {
enumerable: false
});
Object.defineProperty(this, CONFIG_ITEM_BRAND, {
enumerable: false
});
this.value = this._descriptor.value;
this.options = this._descriptor.options;
this.dirname = this._descriptor.dirname;
this.name = this._descriptor.name;
this.file = this._descriptor.file ? {
request: this._descriptor.file.request,
resolved: this._descriptor.file.resolved
} : undefined;
Object.freeze(this);
}
}
Object.freeze(ConfigItem.prototype);

View File

@ -1,197 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = loadPrivatePartialConfig;
exports.loadPartialConfig = void 0;
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _plugin = require("./plugin");
var _util = require("./util");
var _item = require("./item");
var _configChain = require("./config-chain");
var _environment = require("./helpers/environment");
var _options = require("./validation/options");
var _files = require("./files");
var _resolveTargets = require("./resolve-targets");
const _excluded = ["showIgnoredFiles"];
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; }
function resolveRootMode(rootDir, rootMode) {
switch (rootMode) {
case "root":
return rootDir;
case "upward-optional":
{
const upwardRootDir = (0, _files.findConfigUpwards)(rootDir);
return upwardRootDir === null ? rootDir : upwardRootDir;
}
case "upward":
{
const upwardRootDir = (0, _files.findConfigUpwards)(rootDir);
if (upwardRootDir !== null) return upwardRootDir;
throw Object.assign(new Error(`Babel was run with rootMode:"upward" but a root could not ` + `be found when searching upward from "${rootDir}".\n` + `One of the following config files must be in the directory tree: ` + `"${_files.ROOT_CONFIG_FILENAMES.join(", ")}".`), {
code: "BABEL_ROOT_NOT_FOUND",
dirname: rootDir
});
}
default:
throw new Error(`Assertion failure - unknown rootMode value.`);
}
}
function* loadPrivatePartialConfig(inputOpts) {
if (inputOpts != null && (typeof inputOpts !== "object" || Array.isArray(inputOpts))) {
throw new Error("Babel options must be an object, null, or undefined");
}
const args = inputOpts ? (0, _options.validate)("arguments", inputOpts) : {};
const {
envName = (0, _environment.getEnv)(),
cwd = ".",
root: rootDir = ".",
rootMode = "root",
caller,
cloneInputAst = true
} = args;
const absoluteCwd = _path().resolve(cwd);
const absoluteRootDir = resolveRootMode(_path().resolve(absoluteCwd, rootDir), rootMode);
const filename = typeof args.filename === "string" ? _path().resolve(cwd, args.filename) : undefined;
const showConfigPath = yield* (0, _files.resolveShowConfigPath)(absoluteCwd);
const context = {
filename,
cwd: absoluteCwd,
root: absoluteRootDir,
envName,
caller,
showConfig: showConfigPath === filename
};
const configChain = yield* (0, _configChain.buildRootChain)(args, context);
if (!configChain) return null;
const merged = {
assumptions: {}
};
configChain.options.forEach(opts => {
(0, _util.mergeOptions)(merged, opts);
});
const options = Object.assign({}, merged, {
targets: (0, _resolveTargets.resolveTargets)(merged, absoluteRootDir),
cloneInputAst,
babelrc: false,
configFile: false,
browserslistConfigFile: false,
passPerPreset: false,
envName: context.envName,
cwd: context.cwd,
root: context.root,
rootMode: "root",
filename: typeof context.filename === "string" ? context.filename : undefined,
plugins: configChain.plugins.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor)),
presets: configChain.presets.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor))
});
return {
options,
context,
fileHandling: configChain.fileHandling,
ignore: configChain.ignore,
babelrc: configChain.babelrc,
config: configChain.config,
files: configChain.files
};
}
const loadPartialConfig = _gensync()(function* (opts) {
let showIgnoredFiles = false;
if (typeof opts === "object" && opts !== null && !Array.isArray(opts)) {
var _opts = opts;
({
showIgnoredFiles
} = _opts);
opts = _objectWithoutPropertiesLoose(_opts, _excluded);
_opts;
}
const result = yield* loadPrivatePartialConfig(opts);
if (!result) return null;
const {
options,
babelrc,
ignore,
config,
fileHandling,
files
} = result;
if (fileHandling === "ignored" && !showIgnoredFiles) {
return null;
}
(options.plugins || []).forEach(item => {
if (item.value instanceof _plugin.default) {
throw new Error("Passing cached plugin instances is not supported in " + "babel.loadPartialConfig()");
}
});
return new PartialConfig(options, babelrc ? babelrc.filepath : undefined, ignore ? ignore.filepath : undefined, config ? config.filepath : undefined, fileHandling, files);
});
exports.loadPartialConfig = loadPartialConfig;
class PartialConfig {
constructor(options, babelrc, ignore, config, fileHandling, files) {
this.options = void 0;
this.babelrc = void 0;
this.babelignore = void 0;
this.config = void 0;
this.fileHandling = void 0;
this.files = void 0;
this.options = options;
this.babelignore = ignore;
this.babelrc = babelrc;
this.config = config;
this.fileHandling = fileHandling;
this.files = files;
Object.freeze(this);
}
hasFilesystemConfig() {
return this.babelrc !== undefined || this.config !== undefined;
}
}
Object.freeze(PartialConfig.prototype);

View File

@ -1,44 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = pathToPattern;
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
const sep = `\\${_path().sep}`;
const endSep = `(?:${sep}|$)`;
const substitution = `[^${sep}]+`;
const starPat = `(?:${substitution}${sep})`;
const starPatLast = `(?:${substitution}${endSep})`;
const starStarPat = `${starPat}*?`;
const starStarPatLast = `${starPat}*?${starPatLast}?`;
function escapeRegExp(string) {
return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
}
function pathToPattern(pattern, dirname) {
const parts = _path().resolve(dirname, pattern).split(_path().sep);
return new RegExp(["^", ...parts.map((part, i) => {
const last = i === parts.length - 1;
if (part === "**") return last ? starStarPatLast : starStarPat;
if (part === "*") return last ? starPatLast : starPat;
if (part.indexOf("*.") === 0) {
return substitution + escapeRegExp(part.slice(1)) + (last ? endSep : sep);
}
return escapeRegExp(part) + (last ? endSep : sep);
})].join(""));
}

View File

@ -1,30 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
class Plugin {
constructor(plugin, options, key) {
this.key = void 0;
this.manipulateOptions = void 0;
this.post = void 0;
this.pre = void 0;
this.visitor = void 0;
this.parserOverride = void 0;
this.generatorOverride = void 0;
this.options = void 0;
this.key = plugin.name || key;
this.manipulateOptions = plugin.manipulateOptions;
this.post = plugin.post;
this.pre = plugin.pre;
this.visitor = plugin.visitor || {};
this.parserOverride = plugin.parserOverride;
this.generatorOverride = plugin.generatorOverride;
this.options = options;
}
}
exports.default = Plugin;

View File

@ -1,139 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ConfigPrinter = exports.ChainFormatter = void 0;
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
const ChainFormatter = {
Programmatic: 0,
Config: 1
};
exports.ChainFormatter = ChainFormatter;
const Formatter = {
title(type, callerName, filepath) {
let title = "";
if (type === ChainFormatter.Programmatic) {
title = "programmatic options";
if (callerName) {
title += " from " + callerName;
}
} else {
title = "config " + filepath;
}
return title;
},
loc(index, envName) {
let loc = "";
if (index != null) {
loc += `.overrides[${index}]`;
}
if (envName != null) {
loc += `.env["${envName}"]`;
}
return loc;
},
*optionsAndDescriptors(opt) {
const content = Object.assign({}, opt.options);
delete content.overrides;
delete content.env;
const pluginDescriptors = [...(yield* opt.plugins())];
if (pluginDescriptors.length) {
content.plugins = pluginDescriptors.map(d => descriptorToConfig(d));
}
const presetDescriptors = [...(yield* opt.presets())];
if (presetDescriptors.length) {
content.presets = [...presetDescriptors].map(d => descriptorToConfig(d));
}
return JSON.stringify(content, undefined, 2);
}
};
function descriptorToConfig(d) {
var _d$file;
let name = (_d$file = d.file) == null ? void 0 : _d$file.request;
if (name == null) {
if (typeof d.value === "object") {
name = d.value;
} else if (typeof d.value === "function") {
name = `[Function: ${d.value.toString().substr(0, 50)} ... ]`;
}
}
if (name == null) {
name = "[Unknown]";
}
if (d.options === undefined) {
return name;
} else if (d.name == null) {
return [name, d.options];
} else {
return [name, d.options, d.name];
}
}
class ConfigPrinter {
constructor() {
this._stack = [];
}
configure(enabled, type, {
callerName,
filepath
}) {
if (!enabled) return () => {};
return (content, index, envName) => {
this._stack.push({
type,
callerName,
filepath,
content,
index,
envName
});
};
}
static *format(config) {
let title = Formatter.title(config.type, config.callerName, config.filepath);
const loc = Formatter.loc(config.index, config.envName);
if (loc) title += ` ${loc}`;
const content = yield* Formatter.optionsAndDescriptors(config.content);
return `${title}\n${content}`;
}
*output() {
if (this._stack.length === 0) return "";
const configs = yield* _gensync().all(this._stack.map(s => ConfigPrinter.format(s)));
return configs.join("\n\n");
}
}
exports.ConfigPrinter = ConfigPrinter;

View File

@ -1,42 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.resolveBrowserslistConfigFile = resolveBrowserslistConfigFile;
exports.resolveTargets = resolveTargets;
function _helperCompilationTargets() {
const data = require("@babel/helper-compilation-targets");
_helperCompilationTargets = function () {
return data;
};
return data;
}
function resolveBrowserslistConfigFile(browserslistConfigFile, configFilePath) {
return undefined;
}
function resolveTargets(options, root) {
let targets = options.targets;
if (typeof targets === "string" || Array.isArray(targets)) {
targets = {
browsers: targets
};
}
if (targets && targets.esmodules) {
targets = Object.assign({}, targets, {
esmodules: "intersect"
});
}
return (0, _helperCompilationTargets().default)(targets, {
ignoreBrowserslistConfig: true,
browserslistEnv: options.browserslistEnv
});
}

View File

@ -1,68 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.resolveBrowserslistConfigFile = resolveBrowserslistConfigFile;
exports.resolveTargets = resolveTargets;
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function _helperCompilationTargets() {
const data = require("@babel/helper-compilation-targets");
_helperCompilationTargets = function () {
return data;
};
return data;
}
({});
function resolveBrowserslistConfigFile(browserslistConfigFile, configFileDir) {
return _path().resolve(configFileDir, browserslistConfigFile);
}
function resolveTargets(options, root) {
let targets = options.targets;
if (typeof targets === "string" || Array.isArray(targets)) {
targets = {
browsers: targets
};
}
if (targets && targets.esmodules) {
targets = Object.assign({}, targets, {
esmodules: "intersect"
});
}
const {
browserslistConfigFile
} = options;
let configFile;
let ignoreBrowserslistConfig = false;
if (typeof browserslistConfigFile === "string") {
configFile = browserslistConfigFile;
} else {
ignoreBrowserslistConfig = browserslistConfigFile === false;
}
return (0, _helperCompilationTargets().default)(targets, {
ignoreBrowserslistConfig,
configFile,
configPath: root,
browserslistEnv: options.browserslistEnv
});
}

View File

@ -1,31 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.mergeOptions = mergeOptions;
exports.isIterableIterator = isIterableIterator;
function mergeOptions(target, source) {
for (const k of Object.keys(source)) {
if ((k === "parserOpts" || k === "generatorOpts" || k === "assumptions") && source[k]) {
const parserOpts = source[k];
const targetObj = target[k] || (target[k] = {});
mergeDefaultFields(targetObj, parserOpts);
} else {
const val = source[k];
if (val !== undefined) target[k] = val;
}
}
}
function mergeDefaultFields(target, source) {
for (const k of Object.keys(source)) {
const val = source[k];
if (val !== undefined) target[k] = val;
}
}
function isIterableIterator(value) {
return !!value && typeof value.next === "function" && typeof value[Symbol.iterator] === "function";
}

View File

@ -1,352 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.msg = msg;
exports.access = access;
exports.assertRootMode = assertRootMode;
exports.assertSourceMaps = assertSourceMaps;
exports.assertCompact = assertCompact;
exports.assertSourceType = assertSourceType;
exports.assertCallerMetadata = assertCallerMetadata;
exports.assertInputSourceMap = assertInputSourceMap;
exports.assertString = assertString;
exports.assertFunction = assertFunction;
exports.assertBoolean = assertBoolean;
exports.assertObject = assertObject;
exports.assertArray = assertArray;
exports.assertIgnoreList = assertIgnoreList;
exports.assertConfigApplicableTest = assertConfigApplicableTest;
exports.assertConfigFileSearch = assertConfigFileSearch;
exports.assertBabelrcSearch = assertBabelrcSearch;
exports.assertPluginList = assertPluginList;
exports.assertTargets = assertTargets;
exports.assertAssumptions = assertAssumptions;
function _helperCompilationTargets() {
const data = require("@babel/helper-compilation-targets");
_helperCompilationTargets = function () {
return data;
};
return data;
}
var _options = require("./options");
function msg(loc) {
switch (loc.type) {
case "root":
return ``;
case "env":
return `${msg(loc.parent)}.env["${loc.name}"]`;
case "overrides":
return `${msg(loc.parent)}.overrides[${loc.index}]`;
case "option":
return `${msg(loc.parent)}.${loc.name}`;
case "access":
return `${msg(loc.parent)}[${JSON.stringify(loc.name)}]`;
default:
throw new Error(`Assertion failure: Unknown type ${loc.type}`);
}
}
function access(loc, name) {
return {
type: "access",
name,
parent: loc
};
}
function assertRootMode(loc, value) {
if (value !== undefined && value !== "root" && value !== "upward" && value !== "upward-optional") {
throw new Error(`${msg(loc)} must be a "root", "upward", "upward-optional" or undefined`);
}
return value;
}
function assertSourceMaps(loc, value) {
if (value !== undefined && typeof value !== "boolean" && value !== "inline" && value !== "both") {
throw new Error(`${msg(loc)} must be a boolean, "inline", "both", or undefined`);
}
return value;
}
function assertCompact(loc, value) {
if (value !== undefined && typeof value !== "boolean" && value !== "auto") {
throw new Error(`${msg(loc)} must be a boolean, "auto", or undefined`);
}
return value;
}
function assertSourceType(loc, value) {
if (value !== undefined && value !== "module" && value !== "script" && value !== "unambiguous") {
throw new Error(`${msg(loc)} must be "module", "script", "unambiguous", or undefined`);
}
return value;
}
function assertCallerMetadata(loc, value) {
const obj = assertObject(loc, value);
if (obj) {
if (typeof obj.name !== "string") {
throw new Error(`${msg(loc)} set but does not contain "name" property string`);
}
for (const prop of Object.keys(obj)) {
const propLoc = access(loc, prop);
const value = obj[prop];
if (value != null && typeof value !== "boolean" && typeof value !== "string" && typeof value !== "number") {
throw new Error(`${msg(propLoc)} must be null, undefined, a boolean, a string, or a number.`);
}
}
}
return value;
}
function assertInputSourceMap(loc, value) {
if (value !== undefined && typeof value !== "boolean" && (typeof value !== "object" || !value)) {
throw new Error(`${msg(loc)} must be a boolean, object, or undefined`);
}
return value;
}
function assertString(loc, value) {
if (value !== undefined && typeof value !== "string") {
throw new Error(`${msg(loc)} must be a string, or undefined`);
}
return value;
}
function assertFunction(loc, value) {
if (value !== undefined && typeof value !== "function") {
throw new Error(`${msg(loc)} must be a function, or undefined`);
}
return value;
}
function assertBoolean(loc, value) {
if (value !== undefined && typeof value !== "boolean") {
throw new Error(`${msg(loc)} must be a boolean, or undefined`);
}
return value;
}
function assertObject(loc, value) {
if (value !== undefined && (typeof value !== "object" || Array.isArray(value) || !value)) {
throw new Error(`${msg(loc)} must be an object, or undefined`);
}
return value;
}
function assertArray(loc, value) {
if (value != null && !Array.isArray(value)) {
throw new Error(`${msg(loc)} must be an array, or undefined`);
}
return value;
}
function assertIgnoreList(loc, value) {
const arr = assertArray(loc, value);
if (arr) {
arr.forEach((item, i) => assertIgnoreItem(access(loc, i), item));
}
return arr;
}
function assertIgnoreItem(loc, value) {
if (typeof value !== "string" && typeof value !== "function" && !(value instanceof RegExp)) {
throw new Error(`${msg(loc)} must be an array of string/Function/RegExp values, or undefined`);
}
return value;
}
function assertConfigApplicableTest(loc, value) {
if (value === undefined) return value;
if (Array.isArray(value)) {
value.forEach((item, i) => {
if (!checkValidTest(item)) {
throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`);
}
});
} else if (!checkValidTest(value)) {
throw new Error(`${msg(loc)} must be a string/Function/RegExp, or an array of those`);
}
return value;
}
function checkValidTest(value) {
return typeof value === "string" || typeof value === "function" || value instanceof RegExp;
}
function assertConfigFileSearch(loc, value) {
if (value !== undefined && typeof value !== "boolean" && typeof value !== "string") {
throw new Error(`${msg(loc)} must be a undefined, a boolean, a string, ` + `got ${JSON.stringify(value)}`);
}
return value;
}
function assertBabelrcSearch(loc, value) {
if (value === undefined || typeof value === "boolean") return value;
if (Array.isArray(value)) {
value.forEach((item, i) => {
if (!checkValidTest(item)) {
throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`);
}
});
} else if (!checkValidTest(value)) {
throw new Error(`${msg(loc)} must be a undefined, a boolean, a string/Function/RegExp ` + `or an array of those, got ${JSON.stringify(value)}`);
}
return value;
}
function assertPluginList(loc, value) {
const arr = assertArray(loc, value);
if (arr) {
arr.forEach((item, i) => assertPluginItem(access(loc, i), item));
}
return arr;
}
function assertPluginItem(loc, value) {
if (Array.isArray(value)) {
if (value.length === 0) {
throw new Error(`${msg(loc)} must include an object`);
}
if (value.length > 3) {
throw new Error(`${msg(loc)} may only be a two-tuple or three-tuple`);
}
assertPluginTarget(access(loc, 0), value[0]);
if (value.length > 1) {
const opts = value[1];
if (opts !== undefined && opts !== false && (typeof opts !== "object" || Array.isArray(opts) || opts === null)) {
throw new Error(`${msg(access(loc, 1))} must be an object, false, or undefined`);
}
}
if (value.length === 3) {
const name = value[2];
if (name !== undefined && typeof name !== "string") {
throw new Error(`${msg(access(loc, 2))} must be a string, or undefined`);
}
}
} else {
assertPluginTarget(loc, value);
}
return value;
}
function assertPluginTarget(loc, value) {
if ((typeof value !== "object" || !value) && typeof value !== "string" && typeof value !== "function") {
throw new Error(`${msg(loc)} must be a string, object, function`);
}
return value;
}
function assertTargets(loc, value) {
if ((0, _helperCompilationTargets().isBrowsersQueryValid)(value)) return value;
if (typeof value !== "object" || !value || Array.isArray(value)) {
throw new Error(`${msg(loc)} must be a string, an array of strings or an object`);
}
const browsersLoc = access(loc, "browsers");
const esmodulesLoc = access(loc, "esmodules");
assertBrowsersList(browsersLoc, value.browsers);
assertBoolean(esmodulesLoc, value.esmodules);
for (const key of Object.keys(value)) {
const val = value[key];
const subLoc = access(loc, key);
if (key === "esmodules") assertBoolean(subLoc, val);else if (key === "browsers") assertBrowsersList(subLoc, val);else if (!Object.hasOwnProperty.call(_helperCompilationTargets().TargetNames, key)) {
const validTargets = Object.keys(_helperCompilationTargets().TargetNames).join(", ");
throw new Error(`${msg(subLoc)} is not a valid target. Supported targets are ${validTargets}`);
} else assertBrowserVersion(subLoc, val);
}
return value;
}
function assertBrowsersList(loc, value) {
if (value !== undefined && !(0, _helperCompilationTargets().isBrowsersQueryValid)(value)) {
throw new Error(`${msg(loc)} must be undefined, a string or an array of strings`);
}
}
function assertBrowserVersion(loc, value) {
if (typeof value === "number" && Math.round(value) === value) return;
if (typeof value === "string") return;
throw new Error(`${msg(loc)} must be a string or an integer number`);
}
function assertAssumptions(loc, value) {
if (value === undefined) return;
if (typeof value !== "object" || value === null) {
throw new Error(`${msg(loc)} must be an object or undefined.`);
}
let root = loc;
do {
root = root.parent;
} while (root.type !== "root");
const inPreset = root.source === "preset";
for (const name of Object.keys(value)) {
const subLoc = access(loc, name);
if (!_options.assumptionsNames.has(name)) {
throw new Error(`${msg(subLoc)} is not a supported assumption.`);
}
if (typeof value[name] !== "boolean") {
throw new Error(`${msg(subLoc)} must be a boolean.`);
}
if (inPreset && value[name] === false) {
throw new Error(`${msg(subLoc)} cannot be set to 'false' inside presets.`);
}
}
return value;
}

View File

@ -1,210 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.validate = validate;
exports.checkNoUnwrappedItemOptionPairs = checkNoUnwrappedItemOptionPairs;
exports.assumptionsNames = void 0;
var _plugin = require("../plugin");
var _removed = require("./removed");
var _optionAssertions = require("./option-assertions");
const ROOT_VALIDATORS = {
cwd: _optionAssertions.assertString,
root: _optionAssertions.assertString,
rootMode: _optionAssertions.assertRootMode,
configFile: _optionAssertions.assertConfigFileSearch,
caller: _optionAssertions.assertCallerMetadata,
filename: _optionAssertions.assertString,
filenameRelative: _optionAssertions.assertString,
code: _optionAssertions.assertBoolean,
ast: _optionAssertions.assertBoolean,
cloneInputAst: _optionAssertions.assertBoolean,
envName: _optionAssertions.assertString
};
const BABELRC_VALIDATORS = {
babelrc: _optionAssertions.assertBoolean,
babelrcRoots: _optionAssertions.assertBabelrcSearch
};
const NONPRESET_VALIDATORS = {
extends: _optionAssertions.assertString,
ignore: _optionAssertions.assertIgnoreList,
only: _optionAssertions.assertIgnoreList,
targets: _optionAssertions.assertTargets,
browserslistConfigFile: _optionAssertions.assertConfigFileSearch,
browserslistEnv: _optionAssertions.assertString
};
const COMMON_VALIDATORS = {
inputSourceMap: _optionAssertions.assertInputSourceMap,
presets: _optionAssertions.assertPluginList,
plugins: _optionAssertions.assertPluginList,
passPerPreset: _optionAssertions.assertBoolean,
assumptions: _optionAssertions.assertAssumptions,
env: assertEnvSet,
overrides: assertOverridesList,
test: _optionAssertions.assertConfigApplicableTest,
include: _optionAssertions.assertConfigApplicableTest,
exclude: _optionAssertions.assertConfigApplicableTest,
retainLines: _optionAssertions.assertBoolean,
comments: _optionAssertions.assertBoolean,
shouldPrintComment: _optionAssertions.assertFunction,
compact: _optionAssertions.assertCompact,
minified: _optionAssertions.assertBoolean,
auxiliaryCommentBefore: _optionAssertions.assertString,
auxiliaryCommentAfter: _optionAssertions.assertString,
sourceType: _optionAssertions.assertSourceType,
wrapPluginVisitorMethod: _optionAssertions.assertFunction,
highlightCode: _optionAssertions.assertBoolean,
sourceMaps: _optionAssertions.assertSourceMaps,
sourceMap: _optionAssertions.assertSourceMaps,
sourceFileName: _optionAssertions.assertString,
sourceRoot: _optionAssertions.assertString,
parserOpts: _optionAssertions.assertObject,
generatorOpts: _optionAssertions.assertObject
};
{
Object.assign(COMMON_VALIDATORS, {
getModuleId: _optionAssertions.assertFunction,
moduleRoot: _optionAssertions.assertString,
moduleIds: _optionAssertions.assertBoolean,
moduleId: _optionAssertions.assertString
});
}
const assumptionsNames = new Set(["arrayLikeIsIterable", "constantReexports", "constantSuper", "enumerableModuleMeta", "ignoreFunctionLength", "ignoreToPrimitiveHint", "iterableIsArray", "mutableTemplateObject", "noClassCalls", "noDocumentAll", "noIncompleteNsImportDetection", "noNewArrows", "objectRestNoSymbols", "privateFieldsAsProperties", "pureGetters", "setClassMethods", "setComputedProperties", "setPublicClassFields", "setSpreadProperties", "skipForOfIteratorClosing", "superIsCallableConstructor"]);
exports.assumptionsNames = assumptionsNames;
function getSource(loc) {
return loc.type === "root" ? loc.source : getSource(loc.parent);
}
function validate(type, opts) {
return validateNested({
type: "root",
source: type
}, opts);
}
function validateNested(loc, opts) {
const type = getSource(loc);
assertNoDuplicateSourcemap(opts);
Object.keys(opts).forEach(key => {
const optLoc = {
type: "option",
name: key,
parent: loc
};
if (type === "preset" && NONPRESET_VALIDATORS[key]) {
throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is not allowed in preset options`);
}
if (type !== "arguments" && ROOT_VALIDATORS[key]) {
throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options`);
}
if (type !== "arguments" && type !== "configfile" && BABELRC_VALIDATORS[key]) {
if (type === "babelrcfile" || type === "extendsfile") {
throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is not allowed in .babelrc or "extends"ed files, only in root programmatic options, ` + `or babel.config.js/config file options`);
}
throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options, or babel.config.js/config file options`);
}
const validator = COMMON_VALIDATORS[key] || NONPRESET_VALIDATORS[key] || BABELRC_VALIDATORS[key] || ROOT_VALIDATORS[key] || throwUnknownError;
validator(optLoc, opts[key]);
});
return opts;
}
function throwUnknownError(loc) {
const key = loc.name;
if (_removed.default[key]) {
const {
message,
version = 5
} = _removed.default[key];
throw new Error(`Using removed Babel ${version} option: ${(0, _optionAssertions.msg)(loc)} - ${message}`);
} else {
const unknownOptErr = new Error(`Unknown option: ${(0, _optionAssertions.msg)(loc)}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`);
unknownOptErr.code = "BABEL_UNKNOWN_OPTION";
throw unknownOptErr;
}
}
function has(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
function assertNoDuplicateSourcemap(opts) {
if (has(opts, "sourceMap") && has(opts, "sourceMaps")) {
throw new Error(".sourceMap is an alias for .sourceMaps, cannot use both");
}
}
function assertEnvSet(loc, value) {
if (loc.parent.type === "env") {
throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside of another .env block`);
}
const parent = loc.parent;
const obj = (0, _optionAssertions.assertObject)(loc, value);
if (obj) {
for (const envName of Object.keys(obj)) {
const env = (0, _optionAssertions.assertObject)((0, _optionAssertions.access)(loc, envName), obj[envName]);
if (!env) continue;
const envLoc = {
type: "env",
name: envName,
parent
};
validateNested(envLoc, env);
}
}
return obj;
}
function assertOverridesList(loc, value) {
if (loc.parent.type === "env") {
throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .env block`);
}
if (loc.parent.type === "overrides") {
throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .overrides block`);
}
const parent = loc.parent;
const arr = (0, _optionAssertions.assertArray)(loc, value);
if (arr) {
for (const [index, item] of arr.entries()) {
const objLoc = (0, _optionAssertions.access)(loc, index);
const env = (0, _optionAssertions.assertObject)(objLoc, item);
if (!env) throw new Error(`${(0, _optionAssertions.msg)(objLoc)} must be an object`);
const overridesLoc = {
type: "overrides",
index,
parent
};
validateNested(overridesLoc, env);
}
}
return arr;
}
function checkNoUnwrappedItemOptionPairs(items, index, type, e) {
if (index === 0) return;
const lastItem = items[index - 1];
const thisItem = items[index];
if (lastItem.file && lastItem.options === undefined && typeof thisItem.value === "object") {
e.message += `\n- Maybe you meant to use\n` + `"${type}s": [\n ["${lastItem.file.request}", ${JSON.stringify(thisItem.value, undefined, 2)}]\n]\n` + `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`;
}
}

View File

@ -1,71 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.validatePluginObject = validatePluginObject;
var _optionAssertions = require("./option-assertions");
const VALIDATORS = {
name: _optionAssertions.assertString,
manipulateOptions: _optionAssertions.assertFunction,
pre: _optionAssertions.assertFunction,
post: _optionAssertions.assertFunction,
inherits: _optionAssertions.assertFunction,
visitor: assertVisitorMap,
parserOverride: _optionAssertions.assertFunction,
generatorOverride: _optionAssertions.assertFunction
};
function assertVisitorMap(loc, value) {
const obj = (0, _optionAssertions.assertObject)(loc, value);
if (obj) {
Object.keys(obj).forEach(prop => assertVisitorHandler(prop, obj[prop]));
if (obj.enter || obj.exit) {
throw new Error(`${(0, _optionAssertions.msg)(loc)} cannot contain catch-all "enter" or "exit" handlers. Please target individual nodes.`);
}
}
return obj;
}
function assertVisitorHandler(key, value) {
if (value && typeof value === "object") {
Object.keys(value).forEach(handler => {
if (handler !== "enter" && handler !== "exit") {
throw new Error(`.visitor["${key}"] may only have .enter and/or .exit handlers.`);
}
});
} else if (typeof value !== "function") {
throw new Error(`.visitor["${key}"] must be a function`);
}
return value;
}
function validatePluginObject(obj) {
const rootPath = {
type: "root",
source: "plugin"
};
Object.keys(obj).forEach(key => {
const validator = VALIDATORS[key];
if (validator) {
const optLoc = {
type: "option",
name: key,
parent: rootPath
};
validator(optLoc, obj[key]);
} else {
const invalidPluginPropertyError = new Error(`.${key} is not a valid Plugin property`);
invalidPluginPropertyError.code = "BABEL_UNKNOWN_PLUGIN_PROPERTY";
throw invalidPluginPropertyError;
}
});
return obj;
}

View File

@ -1,66 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = {
auxiliaryComment: {
message: "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`"
},
blacklist: {
message: "Put the specific transforms you want in the `plugins` option"
},
breakConfig: {
message: "This is not a necessary option in Babel 6"
},
experimental: {
message: "Put the specific transforms you want in the `plugins` option"
},
externalHelpers: {
message: "Use the `external-helpers` plugin instead. " + "Check out http://babeljs.io/docs/plugins/external-helpers/"
},
extra: {
message: ""
},
jsxPragma: {
message: "use the `pragma` option in the `react-jsx` plugin. " + "Check out http://babeljs.io/docs/plugins/transform-react-jsx/"
},
loose: {
message: "Specify the `loose` option for the relevant plugin you are using " + "or use a preset that sets the option."
},
metadataUsedHelpers: {
message: "Not required anymore as this is enabled by default"
},
modules: {
message: "Use the corresponding module transform plugin in the `plugins` option. " + "Check out http://babeljs.io/docs/plugins/#modules"
},
nonStandard: {
message: "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. " + "Also check out the react preset http://babeljs.io/docs/plugins/preset-react/"
},
optional: {
message: "Put the specific transforms you want in the `plugins` option"
},
sourceMapName: {
message: "The `sourceMapName` option has been removed because it makes more sense for the " + "tooling that calls Babel to assign `map.file` themselves."
},
stage: {
message: "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets"
},
whitelist: {
message: "Put the specific transforms you want in the `plugins` option"
},
resolveModuleSource: {
version: 6,
message: "Use `babel-plugin-module-resolver@3`'s 'resolvePath' options"
},
metadata: {
version: 6,
message: "Generated plugin metadata is always included in the output result"
},
sourceMapTarget: {
version: 6,
message: "The `sourceMapTarget` option has been removed because it makes more sense for the tooling " + "that calls Babel to assign `map.file` themselves."
}
};
exports.default = _default;

View File

@ -1,93 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.maybeAsync = maybeAsync;
exports.forwardAsync = forwardAsync;
exports.isThenable = isThenable;
exports.waitFor = exports.onFirstPause = exports.isAsync = void 0;
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
const id = x => x;
const runGenerator = _gensync()(function* (item) {
return yield* item;
});
const isAsync = _gensync()({
sync: () => false,
errback: cb => cb(null, true)
});
exports.isAsync = isAsync;
function maybeAsync(fn, message) {
return _gensync()({
sync(...args) {
const result = fn.apply(this, args);
if (isThenable(result)) throw new Error(message);
return result;
},
async(...args) {
return Promise.resolve(fn.apply(this, args));
}
});
}
const withKind = _gensync()({
sync: cb => cb("sync"),
async: cb => cb("async")
});
function forwardAsync(action, cb) {
const g = _gensync()(action);
return withKind(kind => {
const adapted = g[kind];
return cb(adapted);
});
}
const onFirstPause = _gensync()({
name: "onFirstPause",
arity: 2,
sync: function (item) {
return runGenerator.sync(item);
},
errback: function (item, firstPause, cb) {
let completed = false;
runGenerator.errback(item, (err, value) => {
completed = true;
cb(err, value);
});
if (!completed) {
firstPause();
}
}
});
exports.onFirstPause = onFirstPause;
const waitFor = _gensync()({
sync: id,
async: id
});
exports.waitFor = waitFor;
function isThenable(val) {
return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function";
}

View File

@ -1,40 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.stat = exports.readFile = void 0;
function _fs() {
const data = require("fs");
_fs = function () {
return data;
};
return data;
}
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
const readFile = _gensync()({
sync: _fs().readFileSync,
errback: _fs().readFile
});
exports.readFile = readFile;
const stat = _gensync()({
sync: _fs().statSync,
errback: _fs().stat
});
exports.stat = stat;

View File

@ -1,264 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Plugin = Plugin;
Object.defineProperty(exports, "File", {
enumerable: true,
get: function () {
return _file.default;
}
});
Object.defineProperty(exports, "buildExternalHelpers", {
enumerable: true,
get: function () {
return _buildExternalHelpers.default;
}
});
Object.defineProperty(exports, "resolvePlugin", {
enumerable: true,
get: function () {
return _files.resolvePlugin;
}
});
Object.defineProperty(exports, "resolvePreset", {
enumerable: true,
get: function () {
return _files.resolvePreset;
}
});
Object.defineProperty(exports, "getEnv", {
enumerable: true,
get: function () {
return _environment.getEnv;
}
});
Object.defineProperty(exports, "tokTypes", {
enumerable: true,
get: function () {
return _parser().tokTypes;
}
});
Object.defineProperty(exports, "traverse", {
enumerable: true,
get: function () {
return _traverse().default;
}
});
Object.defineProperty(exports, "template", {
enumerable: true,
get: function () {
return _template().default;
}
});
Object.defineProperty(exports, "createConfigItem", {
enumerable: true,
get: function () {
return _config.createConfigItem;
}
});
Object.defineProperty(exports, "createConfigItemSync", {
enumerable: true,
get: function () {
return _config.createConfigItemSync;
}
});
Object.defineProperty(exports, "createConfigItemAsync", {
enumerable: true,
get: function () {
return _config.createConfigItemAsync;
}
});
Object.defineProperty(exports, "loadPartialConfig", {
enumerable: true,
get: function () {
return _config.loadPartialConfig;
}
});
Object.defineProperty(exports, "loadPartialConfigSync", {
enumerable: true,
get: function () {
return _config.loadPartialConfigSync;
}
});
Object.defineProperty(exports, "loadPartialConfigAsync", {
enumerable: true,
get: function () {
return _config.loadPartialConfigAsync;
}
});
Object.defineProperty(exports, "loadOptions", {
enumerable: true,
get: function () {
return _config.loadOptions;
}
});
Object.defineProperty(exports, "loadOptionsSync", {
enumerable: true,
get: function () {
return _config.loadOptionsSync;
}
});
Object.defineProperty(exports, "loadOptionsAsync", {
enumerable: true,
get: function () {
return _config.loadOptionsAsync;
}
});
Object.defineProperty(exports, "transform", {
enumerable: true,
get: function () {
return _transform.transform;
}
});
Object.defineProperty(exports, "transformSync", {
enumerable: true,
get: function () {
return _transform.transformSync;
}
});
Object.defineProperty(exports, "transformAsync", {
enumerable: true,
get: function () {
return _transform.transformAsync;
}
});
Object.defineProperty(exports, "transformFile", {
enumerable: true,
get: function () {
return _transformFile.transformFile;
}
});
Object.defineProperty(exports, "transformFileSync", {
enumerable: true,
get: function () {
return _transformFile.transformFileSync;
}
});
Object.defineProperty(exports, "transformFileAsync", {
enumerable: true,
get: function () {
return _transformFile.transformFileAsync;
}
});
Object.defineProperty(exports, "transformFromAst", {
enumerable: true,
get: function () {
return _transformAst.transformFromAst;
}
});
Object.defineProperty(exports, "transformFromAstSync", {
enumerable: true,
get: function () {
return _transformAst.transformFromAstSync;
}
});
Object.defineProperty(exports, "transformFromAstAsync", {
enumerable: true,
get: function () {
return _transformAst.transformFromAstAsync;
}
});
Object.defineProperty(exports, "parse", {
enumerable: true,
get: function () {
return _parse.parse;
}
});
Object.defineProperty(exports, "parseSync", {
enumerable: true,
get: function () {
return _parse.parseSync;
}
});
Object.defineProperty(exports, "parseAsync", {
enumerable: true,
get: function () {
return _parse.parseAsync;
}
});
exports.types = exports.OptionManager = exports.DEFAULT_EXTENSIONS = exports.version = void 0;
var _file = require("./transformation/file/file");
var _buildExternalHelpers = require("./tools/build-external-helpers");
var _files = require("./config/files");
var _environment = require("./config/helpers/environment");
function _types() {
const data = require("@babel/types");
_types = function () {
return data;
};
return data;
}
Object.defineProperty(exports, "types", {
enumerable: true,
get: function () {
return _types();
}
});
function _parser() {
const data = require("@babel/parser");
_parser = function () {
return data;
};
return data;
}
function _traverse() {
const data = require("@babel/traverse");
_traverse = function () {
return data;
};
return data;
}
function _template() {
const data = require("@babel/template");
_template = function () {
return data;
};
return data;
}
var _config = require("./config");
var _transform = require("./transform");
var _transformFile = require("./transform-file");
var _transformAst = require("./transform-ast");
var _parse = require("./parse");
const version = "7.15.0";
exports.version = version;
const DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs", ".cjs"]);
exports.DEFAULT_EXTENSIONS = DEFAULT_EXTENSIONS;
class OptionManager {
init(opts) {
return (0, _config.loadOptions)(opts);
}
}
exports.OptionManager = OptionManager;
function Plugin(alias) {
throw new Error(`The (${alias}) Babel 5 plugin is being run with an unsupported Babel version.`);
}

View File

@ -1,48 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parseAsync = exports.parseSync = exports.parse = void 0;
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _config = require("./config");
var _parser = require("./parser");
var _normalizeOpts = require("./transformation/normalize-opts");
const parseRunner = _gensync()(function* parse(code, opts) {
const config = yield* (0, _config.default)(opts);
if (config === null) {
return null;
}
return yield* (0, _parser.default)(config.passes, (0, _normalizeOpts.default)(config), code);
});
const parse = function parse(code, opts, callback) {
if (typeof opts === "function") {
callback = opts;
opts = undefined;
}
if (callback === undefined) return parseRunner.sync(code, opts);
parseRunner.errback(code, opts, callback);
};
exports.parse = parse;
const parseSync = parseRunner.sync;
exports.parseSync = parseSync;
const parseAsync = parseRunner.async;
exports.parseAsync = parseAsync;

View File

@ -1,95 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = parser;
function _parser() {
const data = require("@babel/parser");
_parser = function () {
return data;
};
return data;
}
function _codeFrame() {
const data = require("@babel/code-frame");
_codeFrame = function () {
return data;
};
return data;
}
var _missingPluginHelper = require("./util/missing-plugin-helper");
function* parser(pluginPasses, {
parserOpts,
highlightCode = true,
filename = "unknown"
}, code) {
try {
const results = [];
for (const plugins of pluginPasses) {
for (const plugin of plugins) {
const {
parserOverride
} = plugin;
if (parserOverride) {
const ast = parserOverride(code, parserOpts, _parser().parse);
if (ast !== undefined) results.push(ast);
}
}
}
if (results.length === 0) {
return (0, _parser().parse)(code, parserOpts);
} else if (results.length === 1) {
yield* [];
if (typeof results[0].then === "function") {
throw new Error(`You appear to be using an async parser plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`);
}
return results[0];
}
throw new Error("More than one plugin attempted to override parsing.");
} catch (err) {
if (err.code === "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED") {
err.message += "\nConsider renaming the file to '.mjs', or setting sourceType:module " + "or sourceType:unambiguous in your Babel config for this file.";
}
const {
loc,
missingPlugin
} = err;
if (loc) {
const codeFrame = (0, _codeFrame().codeFrameColumns)(code, {
start: {
line: loc.line,
column: loc.column + 1
}
}, {
highlightCode
});
if (missingPlugin) {
err.message = `${filename}: ` + (0, _missingPluginHelper.default)(missingPlugin[0], loc, codeFrame);
} else {
err.message = `${filename}: ${err.message}\n\n` + codeFrame;
}
err.code = "BABEL_PARSE_ERROR";
}
throw err;
}
}

View File

@ -1,313 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = generateMissingPluginMessage;
const pluginNameMap = {
asyncDoExpressions: {
syntax: {
name: "@babel/plugin-syntax-async-do-expressions",
url: "https://git.io/JYer8"
}
},
classProperties: {
syntax: {
name: "@babel/plugin-syntax-class-properties",
url: "https://git.io/vb4yQ"
},
transform: {
name: "@babel/plugin-proposal-class-properties",
url: "https://git.io/vb4SL"
}
},
classPrivateProperties: {
syntax: {
name: "@babel/plugin-syntax-class-properties",
url: "https://git.io/vb4yQ"
},
transform: {
name: "@babel/plugin-proposal-class-properties",
url: "https://git.io/vb4SL"
}
},
classPrivateMethods: {
syntax: {
name: "@babel/plugin-syntax-class-properties",
url: "https://git.io/vb4yQ"
},
transform: {
name: "@babel/plugin-proposal-private-methods",
url: "https://git.io/JvpRG"
}
},
classStaticBlock: {
syntax: {
name: "@babel/plugin-syntax-class-static-block",
url: "https://git.io/JTLB6"
},
transform: {
name: "@babel/plugin-proposal-class-static-block",
url: "https://git.io/JTLBP"
}
},
decimal: {
syntax: {
name: "@babel/plugin-syntax-decimal",
url: "https://git.io/JfKOH"
}
},
decorators: {
syntax: {
name: "@babel/plugin-syntax-decorators",
url: "https://git.io/vb4y9"
},
transform: {
name: "@babel/plugin-proposal-decorators",
url: "https://git.io/vb4ST"
}
},
doExpressions: {
syntax: {
name: "@babel/plugin-syntax-do-expressions",
url: "https://git.io/vb4yh"
},
transform: {
name: "@babel/plugin-proposal-do-expressions",
url: "https://git.io/vb4S3"
}
},
dynamicImport: {
syntax: {
name: "@babel/plugin-syntax-dynamic-import",
url: "https://git.io/vb4Sv"
}
},
exportDefaultFrom: {
syntax: {
name: "@babel/plugin-syntax-export-default-from",
url: "https://git.io/vb4SO"
},
transform: {
name: "@babel/plugin-proposal-export-default-from",
url: "https://git.io/vb4yH"
}
},
exportNamespaceFrom: {
syntax: {
name: "@babel/plugin-syntax-export-namespace-from",
url: "https://git.io/vb4Sf"
},
transform: {
name: "@babel/plugin-proposal-export-namespace-from",
url: "https://git.io/vb4SG"
}
},
flow: {
syntax: {
name: "@babel/plugin-syntax-flow",
url: "https://git.io/vb4yb"
},
transform: {
name: "@babel/preset-flow",
url: "https://git.io/JfeDn"
}
},
functionBind: {
syntax: {
name: "@babel/plugin-syntax-function-bind",
url: "https://git.io/vb4y7"
},
transform: {
name: "@babel/plugin-proposal-function-bind",
url: "https://git.io/vb4St"
}
},
functionSent: {
syntax: {
name: "@babel/plugin-syntax-function-sent",
url: "https://git.io/vb4yN"
},
transform: {
name: "@babel/plugin-proposal-function-sent",
url: "https://git.io/vb4SZ"
}
},
importMeta: {
syntax: {
name: "@babel/plugin-syntax-import-meta",
url: "https://git.io/vbKK6"
}
},
jsx: {
syntax: {
name: "@babel/plugin-syntax-jsx",
url: "https://git.io/vb4yA"
},
transform: {
name: "@babel/preset-react",
url: "https://git.io/JfeDR"
}
},
importAssertions: {
syntax: {
name: "@babel/plugin-syntax-import-assertions",
url: "https://git.io/JUbkv"
}
},
moduleStringNames: {
syntax: {
name: "@babel/plugin-syntax-module-string-names",
url: "https://git.io/JTL8G"
}
},
numericSeparator: {
syntax: {
name: "@babel/plugin-syntax-numeric-separator",
url: "https://git.io/vb4Sq"
},
transform: {
name: "@babel/plugin-proposal-numeric-separator",
url: "https://git.io/vb4yS"
}
},
optionalChaining: {
syntax: {
name: "@babel/plugin-syntax-optional-chaining",
url: "https://git.io/vb4Sc"
},
transform: {
name: "@babel/plugin-proposal-optional-chaining",
url: "https://git.io/vb4Sk"
}
},
pipelineOperator: {
syntax: {
name: "@babel/plugin-syntax-pipeline-operator",
url: "https://git.io/vb4yj"
},
transform: {
name: "@babel/plugin-proposal-pipeline-operator",
url: "https://git.io/vb4SU"
}
},
privateIn: {
syntax: {
name: "@babel/plugin-syntax-private-property-in-object",
url: "https://git.io/JfK3q"
},
transform: {
name: "@babel/plugin-proposal-private-property-in-object",
url: "https://git.io/JfK3O"
}
},
recordAndTuple: {
syntax: {
name: "@babel/plugin-syntax-record-and-tuple",
url: "https://git.io/JvKp3"
}
},
throwExpressions: {
syntax: {
name: "@babel/plugin-syntax-throw-expressions",
url: "https://git.io/vb4SJ"
},
transform: {
name: "@babel/plugin-proposal-throw-expressions",
url: "https://git.io/vb4yF"
}
},
typescript: {
syntax: {
name: "@babel/plugin-syntax-typescript",
url: "https://git.io/vb4SC"
},
transform: {
name: "@babel/preset-typescript",
url: "https://git.io/JfeDz"
}
},
asyncGenerators: {
syntax: {
name: "@babel/plugin-syntax-async-generators",
url: "https://git.io/vb4SY"
},
transform: {
name: "@babel/plugin-proposal-async-generator-functions",
url: "https://git.io/vb4yp"
}
},
logicalAssignment: {
syntax: {
name: "@babel/plugin-syntax-logical-assignment-operators",
url: "https://git.io/vAlBp"
},
transform: {
name: "@babel/plugin-proposal-logical-assignment-operators",
url: "https://git.io/vAlRe"
}
},
nullishCoalescingOperator: {
syntax: {
name: "@babel/plugin-syntax-nullish-coalescing-operator",
url: "https://git.io/vb4yx"
},
transform: {
name: "@babel/plugin-proposal-nullish-coalescing-operator",
url: "https://git.io/vb4Se"
}
},
objectRestSpread: {
syntax: {
name: "@babel/plugin-syntax-object-rest-spread",
url: "https://git.io/vb4y5"
},
transform: {
name: "@babel/plugin-proposal-object-rest-spread",
url: "https://git.io/vb4Ss"
}
},
optionalCatchBinding: {
syntax: {
name: "@babel/plugin-syntax-optional-catch-binding",
url: "https://git.io/vb4Sn"
},
transform: {
name: "@babel/plugin-proposal-optional-catch-binding",
url: "https://git.io/vb4SI"
}
}
};
pluginNameMap.privateIn.syntax = pluginNameMap.privateIn.transform;
const getNameURLCombination = ({
name,
url
}) => `${name} (${url})`;
function generateMissingPluginMessage(missingPluginName, loc, codeFrame) {
let helpMessage = `Support for the experimental syntax '${missingPluginName}' isn't currently enabled ` + `(${loc.line}:${loc.column + 1}):\n\n` + codeFrame;
const pluginInfo = pluginNameMap[missingPluginName];
if (pluginInfo) {
const {
syntax: syntaxPlugin,
transform: transformPlugin
} = pluginInfo;
if (syntaxPlugin) {
const syntaxPluginInfo = getNameURLCombination(syntaxPlugin);
if (transformPlugin) {
const transformPluginInfo = getNameURLCombination(transformPlugin);
const sectionType = transformPlugin.name.startsWith("@babel/plugin") ? "plugins" : "presets";
helpMessage += `\n\nAdd ${transformPluginInfo} to the '${sectionType}' section of your Babel config to enable transformation.
If you want to leave it as-is, add ${syntaxPluginInfo} to the 'plugins' section to enable parsing.`;
} else {
helpMessage += `\n\nAdd ${syntaxPluginInfo} to the 'plugins' section of your Babel config ` + `to enable parsing.`;
}
}
}
return helpMessage;
}

View File

@ -1,142 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
function helpers() {
const data = require("@babel/helpers");
helpers = function () {
return data;
};
return data;
}
function _generator() {
const data = require("@babel/generator");
_generator = function () {
return data;
};
return data;
}
function _template() {
const data = require("@babel/template");
_template = function () {
return data;
};
return data;
}
function t() {
const data = require("@babel/types");
t = function () {
return data;
};
return data;
}
var _file = require("../transformation/file/file");
const buildUmdWrapper = replacements => (0, _template().default)`
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define(AMD_ARGUMENTS, factory);
} else if (typeof exports === "object") {
factory(COMMON_ARGUMENTS);
} else {
factory(BROWSER_ARGUMENTS);
}
})(UMD_ROOT, function (FACTORY_PARAMETERS) {
FACTORY_BODY
});
`(replacements);
function buildGlobal(allowlist) {
const namespace = t().identifier("babelHelpers");
const body = [];
const container = t().functionExpression(null, [t().identifier("global")], t().blockStatement(body));
const tree = t().program([t().expressionStatement(t().callExpression(container, [t().conditionalExpression(t().binaryExpression("===", t().unaryExpression("typeof", t().identifier("global")), t().stringLiteral("undefined")), t().identifier("self"), t().identifier("global"))]))]);
body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().assignmentExpression("=", t().memberExpression(t().identifier("global"), namespace), t().objectExpression([])))]));
buildHelpers(body, namespace, allowlist);
return tree;
}
function buildModule(allowlist) {
const body = [];
const refs = buildHelpers(body, null, allowlist);
body.unshift(t().exportNamedDeclaration(null, Object.keys(refs).map(name => {
return t().exportSpecifier(t().cloneNode(refs[name]), t().identifier(name));
})));
return t().program(body, [], "module");
}
function buildUmd(allowlist) {
const namespace = t().identifier("babelHelpers");
const body = [];
body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().identifier("global"))]));
buildHelpers(body, namespace, allowlist);
return t().program([buildUmdWrapper({
FACTORY_PARAMETERS: t().identifier("global"),
BROWSER_ARGUMENTS: t().assignmentExpression("=", t().memberExpression(t().identifier("root"), namespace), t().objectExpression([])),
COMMON_ARGUMENTS: t().identifier("exports"),
AMD_ARGUMENTS: t().arrayExpression([t().stringLiteral("exports")]),
FACTORY_BODY: body,
UMD_ROOT: t().identifier("this")
})]);
}
function buildVar(allowlist) {
const namespace = t().identifier("babelHelpers");
const body = [];
body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().objectExpression([]))]));
const tree = t().program(body);
buildHelpers(body, namespace, allowlist);
body.push(t().expressionStatement(namespace));
return tree;
}
function buildHelpers(body, namespace, allowlist) {
const getHelperReference = name => {
return namespace ? t().memberExpression(namespace, t().identifier(name)) : t().identifier(`_${name}`);
};
const refs = {};
helpers().list.forEach(function (name) {
if (allowlist && allowlist.indexOf(name) < 0) return;
const ref = refs[name] = getHelperReference(name);
helpers().ensure(name, _file.default);
const {
nodes
} = helpers().get(name, getHelperReference, ref);
body.push(...nodes);
});
return refs;
}
function _default(allowlist, outputType = "global") {
let tree;
const build = {
global: buildGlobal,
module: buildModule,
umd: buildUmd,
var: buildVar
}[outputType];
if (build) {
tree = build(allowlist);
} else {
throw new Error(`Unsupported output type ${outputType}`);
}
return (0, _generator().default)(tree).code;
}

View File

@ -1,46 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformFromAstAsync = exports.transformFromAstSync = exports.transformFromAst = void 0;
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _config = require("./config");
var _transformation = require("./transformation");
const transformFromAstRunner = _gensync()(function* (ast, code, opts) {
const config = yield* (0, _config.default)(opts);
if (config === null) return null;
if (!ast) throw new Error("No AST given");
return yield* (0, _transformation.run)(config, code, ast);
});
const transformFromAst = function transformFromAst(ast, code, opts, callback) {
if (typeof opts === "function") {
callback = opts;
opts = undefined;
}
if (callback === undefined) {
return transformFromAstRunner.sync(ast, code, opts);
}
transformFromAstRunner.errback(ast, code, opts, callback);
};
exports.transformFromAst = transformFromAst;
const transformFromAstSync = transformFromAstRunner.sync;
exports.transformFromAstSync = transformFromAstSync;
const transformFromAstAsync = transformFromAstRunner.async;
exports.transformFromAstAsync = transformFromAstAsync;

View File

@ -1,26 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformFileSync = transformFileSync;
exports.transformFileAsync = transformFileAsync;
exports.transformFile = void 0;
const transformFile = function transformFile(filename, opts, callback) {
if (typeof opts === "function") {
callback = opts;
}
callback(new Error("Transforming files is not supported in browsers"), null);
};
exports.transformFile = transformFile;
function transformFileSync() {
throw new Error("Transforming files is not supported in browsers");
}
function transformFileAsync() {
return Promise.reject(new Error("Transforming files is not supported in browsers"));
}

View File

@ -1,41 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformFileAsync = exports.transformFileSync = exports.transformFile = void 0;
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _config = require("./config");
var _transformation = require("./transformation");
var fs = require("./gensync-utils/fs");
({});
const transformFileRunner = _gensync()(function* (filename, opts) {
const options = Object.assign({}, opts, {
filename
});
const config = yield* (0, _config.default)(options);
if (config === null) return null;
const code = yield* fs.readFile(filename, "utf8");
return yield* (0, _transformation.run)(config, code);
});
const transformFile = transformFileRunner.errback;
exports.transformFile = transformFile;
const transformFileSync = transformFileRunner.sync;
exports.transformFileSync = transformFileSync;
const transformFileAsync = transformFileRunner.async;
exports.transformFileAsync = transformFileAsync;

View File

@ -1,42 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformAsync = exports.transformSync = exports.transform = void 0;
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _config = require("./config");
var _transformation = require("./transformation");
const transformRunner = _gensync()(function* transform(code, opts) {
const config = yield* (0, _config.default)(opts);
if (config === null) return null;
return yield* (0, _transformation.run)(config, code);
});
const transform = function transform(code, opts, callback) {
if (typeof opts === "function") {
callback = opts;
opts = undefined;
}
if (callback === undefined) return transformRunner.sync(code, opts);
transformRunner.errback(code, opts, callback);
};
exports.transform = transform;
const transformSync = transformRunner.sync;
exports.transformSync = transformSync;
const transformAsync = transformRunner.async;
exports.transformAsync = transformAsync;

View File

@ -1,94 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = loadBlockHoistPlugin;
function _traverse() {
const data = require("@babel/traverse");
_traverse = function () {
return data;
};
return data;
}
var _plugin = require("../config/plugin");
let LOADED_PLUGIN;
function loadBlockHoistPlugin() {
if (!LOADED_PLUGIN) {
LOADED_PLUGIN = new _plugin.default(Object.assign({}, blockHoistPlugin, {
visitor: _traverse().default.explode(blockHoistPlugin.visitor)
}), {});
}
return LOADED_PLUGIN;
}
function priority(bodyNode) {
const priority = bodyNode == null ? void 0 : bodyNode._blockHoist;
if (priority == null) return 1;
if (priority === true) return 2;
return priority;
}
function stableSort(body) {
const buckets = Object.create(null);
for (let i = 0; i < body.length; i++) {
const n = body[i];
const p = priority(n);
const bucket = buckets[p] || (buckets[p] = []);
bucket.push(n);
}
const keys = Object.keys(buckets).map(k => +k).sort((a, b) => b - a);
let index = 0;
for (const key of keys) {
const bucket = buckets[key];
for (const n of bucket) {
body[index++] = n;
}
}
return body;
}
const blockHoistPlugin = {
name: "internal.blockHoist",
visitor: {
Block: {
exit({
node
}) {
const {
body
} = node;
let max = Math.pow(2, 30) - 1;
let hasChange = false;
for (let i = 0; i < body.length; i++) {
const n = body[i];
const p = priority(n);
if (p > max) {
hasChange = true;
break;
}
max = p;
}
if (!hasChange) return;
node.body = stableSort(body.slice());
}
}
}
};

View File

@ -1,249 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function helpers() {
const data = require("@babel/helpers");
helpers = function () {
return data;
};
return data;
}
function _traverse() {
const data = require("@babel/traverse");
_traverse = function () {
return data;
};
return data;
}
function _codeFrame() {
const data = require("@babel/code-frame");
_codeFrame = function () {
return data;
};
return data;
}
function t() {
const data = require("@babel/types");
t = function () {
return data;
};
return data;
}
function _helperModuleTransforms() {
const data = require("@babel/helper-module-transforms");
_helperModuleTransforms = function () {
return data;
};
return data;
}
function _semver() {
const data = require("semver");
_semver = function () {
return data;
};
return data;
}
const errorVisitor = {
enter(path, state) {
const loc = path.node.loc;
if (loc) {
state.loc = loc;
path.stop();
}
}
};
class File {
constructor(options, {
code,
ast,
inputMap
}) {
this._map = new Map();
this.opts = void 0;
this.declarations = {};
this.path = null;
this.ast = {};
this.scope = void 0;
this.metadata = {};
this.code = "";
this.inputMap = null;
this.hub = {
file: this,
getCode: () => this.code,
getScope: () => this.scope,
addHelper: this.addHelper.bind(this),
buildError: this.buildCodeFrameError.bind(this)
};
this.opts = options;
this.code = code;
this.ast = ast;
this.inputMap = inputMap;
this.path = _traverse().NodePath.get({
hub: this.hub,
parentPath: null,
parent: this.ast,
container: this.ast,
key: "program"
}).setContext();
this.scope = this.path.scope;
}
get shebang() {
const {
interpreter
} = this.path.node;
return interpreter ? interpreter.value : "";
}
set shebang(value) {
if (value) {
this.path.get("interpreter").replaceWith(t().interpreterDirective(value));
} else {
this.path.get("interpreter").remove();
}
}
set(key, val) {
if (key === "helpersNamespace") {
throw new Error("Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility." + "If you are using @babel/plugin-external-helpers you will need to use a newer " + "version than the one you currently have installed. " + "If you have your own implementation, you'll want to explore using 'helperGenerator' " + "alongside 'file.availableHelper()'.");
}
this._map.set(key, val);
}
get(key) {
return this._map.get(key);
}
has(key) {
return this._map.has(key);
}
getModuleName() {
return (0, _helperModuleTransforms().getModuleName)(this.opts, this.opts);
}
addImport() {
throw new Error("This API has been removed. If you're looking for this " + "functionality in Babel 7, you should import the " + "'@babel/helper-module-imports' module and use the functions exposed " + " from that module, such as 'addNamed' or 'addDefault'.");
}
availableHelper(name, versionRange) {
let minVersion;
try {
minVersion = helpers().minVersion(name);
} catch (err) {
if (err.code !== "BABEL_HELPER_UNKNOWN") throw err;
return false;
}
if (typeof versionRange !== "string") return true;
if (_semver().valid(versionRange)) versionRange = `^${versionRange}`;
return !_semver().intersects(`<${minVersion}`, versionRange) && !_semver().intersects(`>=8.0.0`, versionRange);
}
addHelper(name) {
const declar = this.declarations[name];
if (declar) return t().cloneNode(declar);
const generator = this.get("helperGenerator");
if (generator) {
const res = generator(name);
if (res) return res;
}
helpers().ensure(name, File);
const uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
const dependencies = {};
for (const dep of helpers().getDependencies(name)) {
dependencies[dep] = this.addHelper(dep);
}
const {
nodes,
globals
} = helpers().get(name, dep => dependencies[dep], uid, Object.keys(this.scope.getAllBindings()));
globals.forEach(name => {
if (this.path.scope.hasBinding(name, true)) {
this.path.scope.rename(name);
}
});
nodes.forEach(node => {
node._compact = true;
});
this.path.unshiftContainer("body", nodes);
this.path.get("body").forEach(path => {
if (nodes.indexOf(path.node) === -1) return;
if (path.isVariableDeclaration()) this.scope.registerDeclaration(path);
});
return uid;
}
addTemplateObject() {
throw new Error("This function has been moved into the template literal transform itself.");
}
buildCodeFrameError(node, msg, _Error = SyntaxError) {
let loc = node && (node.loc || node._loc);
if (!loc && node) {
const state = {
loc: null
};
(0, _traverse().default)(node, errorVisitor, this.scope, state);
loc = state.loc;
let txt = "This is an error on an internal node. Probably an internal error.";
if (loc) txt += " Location has been estimated.";
msg += ` (${txt})`;
}
if (loc) {
const {
highlightCode = true
} = this.opts;
msg += "\n" + (0, _codeFrame().codeFrameColumns)(this.code, {
start: {
line: loc.start.line,
column: loc.start.column + 1
},
end: loc.end && loc.start.line === loc.end.line ? {
line: loc.end.line,
column: loc.end.column + 1
} : undefined
}, {
highlightCode
});
}
return new _Error(msg);
}
}
exports.default = File;

View File

@ -1,87 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = generateCode;
function _convertSourceMap() {
const data = require("convert-source-map");
_convertSourceMap = function () {
return data;
};
return data;
}
function _generator() {
const data = require("@babel/generator");
_generator = function () {
return data;
};
return data;
}
var _mergeMap = require("./merge-map");
function generateCode(pluginPasses, file) {
const {
opts,
ast,
code,
inputMap
} = file;
const results = [];
for (const plugins of pluginPasses) {
for (const plugin of plugins) {
const {
generatorOverride
} = plugin;
if (generatorOverride) {
const result = generatorOverride(ast, opts.generatorOpts, code, _generator().default);
if (result !== undefined) results.push(result);
}
}
}
let result;
if (results.length === 0) {
result = (0, _generator().default)(ast, opts.generatorOpts, code);
} else if (results.length === 1) {
result = results[0];
if (typeof result.then === "function") {
throw new Error(`You appear to be using an async codegen plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`);
}
} else {
throw new Error("More than one plugin attempted to override codegen.");
}
let {
code: outputCode,
map: outputMap
} = result;
if (outputMap && inputMap) {
outputMap = (0, _mergeMap.default)(inputMap.toObject(), outputMap);
}
if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") {
outputCode += "\n" + _convertSourceMap().fromObject(outputMap).toComment();
}
if (opts.sourceMaps === "inline") {
outputMap = null;
}
return {
outputCode,
outputMap
};
}

View File

@ -1,245 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = mergeSourceMap;
function _sourceMap() {
const data = require("source-map");
_sourceMap = function () {
return data;
};
return data;
}
function mergeSourceMap(inputMap, map) {
const input = buildMappingData(inputMap);
const output = buildMappingData(map);
const mergedGenerator = new (_sourceMap().SourceMapGenerator)();
for (const {
source
} of input.sources) {
if (typeof source.content === "string") {
mergedGenerator.setSourceContent(source.path, source.content);
}
}
if (output.sources.length === 1) {
const defaultSource = output.sources[0];
const insertedMappings = new Map();
eachInputGeneratedRange(input, (generated, original, source) => {
eachOverlappingGeneratedOutputRange(defaultSource, generated, item => {
const key = makeMappingKey(item);
if (insertedMappings.has(key)) return;
insertedMappings.set(key, item);
mergedGenerator.addMapping({
source: source.path,
original: {
line: original.line,
column: original.columnStart
},
generated: {
line: item.line,
column: item.columnStart
},
name: original.name
});
});
});
for (const item of insertedMappings.values()) {
if (item.columnEnd === Infinity) {
continue;
}
const clearItem = {
line: item.line,
columnStart: item.columnEnd
};
const key = makeMappingKey(clearItem);
if (insertedMappings.has(key)) {
continue;
}
mergedGenerator.addMapping({
generated: {
line: clearItem.line,
column: clearItem.columnStart
}
});
}
}
const result = mergedGenerator.toJSON();
if (typeof input.sourceRoot === "string") {
result.sourceRoot = input.sourceRoot;
}
return result;
}
function makeMappingKey(item) {
return `${item.line}/${item.columnStart}`;
}
function eachOverlappingGeneratedOutputRange(outputFile, inputGeneratedRange, callback) {
const overlappingOriginal = filterApplicableOriginalRanges(outputFile, inputGeneratedRange);
for (const {
generated
} of overlappingOriginal) {
for (const item of generated) {
callback(item);
}
}
}
function filterApplicableOriginalRanges({
mappings
}, {
line,
columnStart,
columnEnd
}) {
return filterSortedArray(mappings, ({
original: outOriginal
}) => {
if (line > outOriginal.line) return -1;
if (line < outOriginal.line) return 1;
if (columnStart >= outOriginal.columnEnd) return -1;
if (columnEnd <= outOriginal.columnStart) return 1;
return 0;
});
}
function eachInputGeneratedRange(map, callback) {
for (const {
source,
mappings
} of map.sources) {
for (const {
original,
generated
} of mappings) {
for (const item of generated) {
callback(item, original, source);
}
}
}
}
function buildMappingData(map) {
const consumer = new (_sourceMap().SourceMapConsumer)(Object.assign({}, map, {
sourceRoot: null
}));
const sources = new Map();
const mappings = new Map();
let last = null;
consumer.computeColumnSpans();
consumer.eachMapping(m => {
if (m.originalLine === null) return;
let source = sources.get(m.source);
if (!source) {
source = {
path: m.source,
content: consumer.sourceContentFor(m.source, true)
};
sources.set(m.source, source);
}
let sourceData = mappings.get(source);
if (!sourceData) {
sourceData = {
source,
mappings: []
};
mappings.set(source, sourceData);
}
const obj = {
line: m.originalLine,
columnStart: m.originalColumn,
columnEnd: Infinity,
name: m.name
};
if (last && last.source === source && last.mapping.line === m.originalLine) {
last.mapping.columnEnd = m.originalColumn;
}
last = {
source,
mapping: obj
};
sourceData.mappings.push({
original: obj,
generated: consumer.allGeneratedPositionsFor({
source: m.source,
line: m.originalLine,
column: m.originalColumn
}).map(item => ({
line: item.line,
columnStart: item.column,
columnEnd: item.lastColumn + 1
}))
});
}, null, _sourceMap().SourceMapConsumer.ORIGINAL_ORDER);
return {
file: map.file,
sourceRoot: map.sourceRoot,
sources: Array.from(mappings.values())
};
}
function findInsertionLocation(array, callback) {
let left = 0;
let right = array.length;
while (left < right) {
const mid = Math.floor((left + right) / 2);
const item = array[mid];
const result = callback(item);
if (result === 0) {
left = mid;
break;
}
if (result >= 0) {
right = mid;
} else {
left = mid + 1;
}
}
let i = left;
if (i < array.length) {
while (i >= 0 && callback(array[i]) >= 0) {
i--;
}
return i + 1;
}
return i;
}
function filterSortedArray(array, callback) {
const start = findInsertionLocation(array, callback);
const results = [];
for (let i = start; i < array.length && callback(array[i]) === 0; i++) {
results.push(array[i]);
}
return results;
}

View File

@ -1,124 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = run;
function _traverse() {
const data = require("@babel/traverse");
_traverse = function () {
return data;
};
return data;
}
var _pluginPass = require("./plugin-pass");
var _blockHoistPlugin = require("./block-hoist-plugin");
var _normalizeOpts = require("./normalize-opts");
var _normalizeFile = require("./normalize-file");
var _generate = require("./file/generate");
function* run(config, code, ast) {
const file = yield* (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code, ast);
const opts = file.opts;
try {
yield* transformFile(file, config.passes);
} catch (e) {
var _opts$filename;
e.message = `${(_opts$filename = opts.filename) != null ? _opts$filename : "unknown"}: ${e.message}`;
if (!e.code) {
e.code = "BABEL_TRANSFORM_ERROR";
}
throw e;
}
let outputCode, outputMap;
try {
if (opts.code !== false) {
({
outputCode,
outputMap
} = (0, _generate.default)(config.passes, file));
}
} catch (e) {
var _opts$filename2;
e.message = `${(_opts$filename2 = opts.filename) != null ? _opts$filename2 : "unknown"}: ${e.message}`;
if (!e.code) {
e.code = "BABEL_GENERATE_ERROR";
}
throw e;
}
return {
metadata: file.metadata,
options: opts,
ast: opts.ast === true ? file.ast : null,
code: outputCode === undefined ? null : outputCode,
map: outputMap === undefined ? null : outputMap,
sourceType: file.ast.program.sourceType
};
}
function* transformFile(file, pluginPasses) {
for (const pluginPairs of pluginPasses) {
const passPairs = [];
const passes = [];
const visitors = [];
for (const plugin of pluginPairs.concat([(0, _blockHoistPlugin.default)()])) {
const pass = new _pluginPass.default(file, plugin.key, plugin.options);
passPairs.push([plugin, pass]);
passes.push(pass);
visitors.push(plugin.visitor);
}
for (const [plugin, pass] of passPairs) {
const fn = plugin.pre;
if (fn) {
const result = fn.call(pass, file);
yield* [];
if (isThenable(result)) {
throw new Error(`You appear to be using an plugin with an async .pre, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`);
}
}
}
const visitor = _traverse().default.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod);
(0, _traverse().default)(file.ast, visitor, file.scope);
for (const [plugin, pass] of passPairs) {
const fn = plugin.post;
if (fn) {
const result = fn.call(pass, file);
yield* [];
if (isThenable(result)) {
throw new Error(`You appear to be using an plugin with an async .post, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`);
}
}
}
}
}
function isThenable(val) {
return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function";
}

View File

@ -1,162 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = normalizeFile;
function _fs() {
const data = require("fs");
_fs = function () {
return data;
};
return data;
}
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function _debug() {
const data = require("debug");
_debug = function () {
return data;
};
return data;
}
function t() {
const data = require("@babel/types");
t = function () {
return data;
};
return data;
}
function _convertSourceMap() {
const data = require("convert-source-map");
_convertSourceMap = function () {
return data;
};
return data;
}
var _file = require("./file/file");
var _parser = require("../parser");
var _cloneDeep = require("./util/clone-deep");
const debug = _debug()("babel:transform:file");
const LARGE_INPUT_SOURCEMAP_THRESHOLD = 1000000;
function* normalizeFile(pluginPasses, options, code, ast) {
code = `${code || ""}`;
if (ast) {
if (ast.type === "Program") {
ast = t().file(ast, [], []);
} else if (ast.type !== "File") {
throw new Error("AST root must be a Program or File node");
}
if (options.cloneInputAst) {
ast = (0, _cloneDeep.default)(ast);
}
} else {
ast = yield* (0, _parser.default)(pluginPasses, options, code);
}
let inputMap = null;
if (options.inputSourceMap !== false) {
if (typeof options.inputSourceMap === "object") {
inputMap = _convertSourceMap().fromObject(options.inputSourceMap);
}
if (!inputMap) {
const lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast);
if (lastComment) {
try {
inputMap = _convertSourceMap().fromComment(lastComment);
} catch (err) {
debug("discarding unknown inline input sourcemap", err);
}
}
}
if (!inputMap) {
const lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast);
if (typeof options.filename === "string" && lastComment) {
try {
const match = EXTERNAL_SOURCEMAP_REGEX.exec(lastComment);
const inputMapContent = _fs().readFileSync(_path().resolve(_path().dirname(options.filename), match[1]));
if (inputMapContent.length > LARGE_INPUT_SOURCEMAP_THRESHOLD) {
debug("skip merging input map > 1 MB");
} else {
inputMap = _convertSourceMap().fromJSON(inputMapContent);
}
} catch (err) {
debug("discarding unknown file input sourcemap", err);
}
} else if (lastComment) {
debug("discarding un-loadable file input sourcemap");
}
}
}
return new _file.default(options, {
code,
ast,
inputMap
});
}
const INLINE_SOURCEMAP_REGEX = /^[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/;
const EXTERNAL_SOURCEMAP_REGEX = /^[@#][ \t]+sourceMappingURL=([^\s'"`]+)[ \t]*$/;
function extractCommentsFromList(regex, comments, lastComment) {
if (comments) {
comments = comments.filter(({
value
}) => {
if (regex.test(value)) {
lastComment = value;
return false;
}
return true;
});
}
return [comments, lastComment];
}
function extractComments(regex, ast) {
let lastComment = null;
t().traverseFast(ast, node => {
[node.leadingComments, lastComment] = extractCommentsFromList(regex, node.leadingComments, lastComment);
[node.innerComments, lastComment] = extractCommentsFromList(regex, node.innerComments, lastComment);
[node.trailingComments, lastComment] = extractCommentsFromList(regex, node.trailingComments, lastComment);
});
return lastComment;
}

View File

@ -1,62 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = normalizeOptions;
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function normalizeOptions(config) {
const {
filename,
cwd,
filenameRelative = typeof filename === "string" ? _path().relative(cwd, filename) : "unknown",
sourceType = "module",
inputSourceMap,
sourceMaps = !!inputSourceMap,
sourceRoot = config.options.moduleRoot,
sourceFileName = _path().basename(filenameRelative),
comments = true,
compact = "auto"
} = config.options;
const opts = config.options;
const options = Object.assign({}, opts, {
parserOpts: Object.assign({
sourceType: _path().extname(filenameRelative) === ".mjs" ? "module" : sourceType,
sourceFileName: filename,
plugins: []
}, opts.parserOpts),
generatorOpts: Object.assign({
filename,
auxiliaryCommentBefore: opts.auxiliaryCommentBefore,
auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
retainLines: opts.retainLines,
comments,
shouldPrintComment: opts.shouldPrintComment,
compact,
minified: opts.minified,
sourceMaps,
sourceRoot,
sourceFileName
}, opts.generatorOpts)
});
for (const plugins of config.passes) {
for (const plugin of plugins) {
if (plugin.manipulateOptions) {
plugin.manipulateOptions(options, options.parserOpts);
}
}
}
return options;
}

View File

@ -1,54 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
class PluginPass {
constructor(file, key, options) {
this._map = new Map();
this.key = void 0;
this.file = void 0;
this.opts = void 0;
this.cwd = void 0;
this.filename = void 0;
this.key = key;
this.file = file;
this.opts = options || {};
this.cwd = file.opts.cwd;
this.filename = file.opts.filename;
}
set(key, val) {
this._map.set(key, val);
}
get(key) {
return this._map.get(key);
}
availableHelper(name, versionRange) {
return this.file.availableHelper(name, versionRange);
}
addHelper(name) {
return this.file.addHelper(name);
}
addImport() {
return this.file.addImport();
}
buildCodeFrameError(node, msg, _Error) {
return this.file.buildCodeFrameError(node, msg, _Error);
}
}
exports.default = PluginPass;
{
PluginPass.prototype.getModuleName = function getModuleName() {
return this.file.getModuleName();
};
}

View File

@ -1,25 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
const serialized = "$$ babel internal serialized type" + Math.random();
function serialize(key, value) {
if (typeof value !== "bigint") return value;
return {
[serialized]: "BigInt",
value: value.toString()
};
}
function revive(key, value) {
if (!value || typeof value !== "object") return value;
if (value[serialized] !== "BigInt") return value;
return BigInt(value.value);
}
function _default(value) {
return JSON.parse(JSON.stringify(value, serialize), revive);
}

View File

@ -1,26 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
function _v() {
const data = require("v8");
_v = function () {
return data;
};
return data;
}
var _cloneDeepBrowser = require("./clone-deep-browser");
function _default(value) {
if (_v().deserialize && _v().serialize) {
return _v().deserialize(_v().serialize(value));
}
return (0, _cloneDeepBrowser.default)(value);
}

View File

@ -1 +0,0 @@
../json5/lib/cli.js

View File

@ -1 +0,0 @@
../semver/bin/semver.js

View File

@ -1,22 +0,0 @@
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.

View File

@ -1,19 +0,0 @@
# @babel/code-frame
> Generate errors that contain a code frame that point to source locations.
See our website [@babel/code-frame](https://babeljs.io/docs/en/babel-code-frame) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/code-frame
```
or using yarn:
```sh
yarn add @babel/code-frame --dev
```

View File

@ -1,163 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.codeFrameColumns = codeFrameColumns;
exports.default = _default;
var _highlight = require("@babel/highlight");
let deprecationWarningShown = false;
function getDefs(chalk) {
return {
gutter: chalk.grey,
marker: chalk.red.bold,
message: chalk.red.bold
};
}
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
function getMarkerLines(loc, source, opts) {
const startLoc = Object.assign({
column: 0,
line: -1
}, loc.start);
const endLoc = Object.assign({}, startLoc, loc.end);
const {
linesAbove = 2,
linesBelow = 3
} = opts || {};
const startLine = startLoc.line;
const startColumn = startLoc.column;
const endLine = endLoc.line;
const endColumn = endLoc.column;
let start = Math.max(startLine - (linesAbove + 1), 0);
let end = Math.min(source.length, endLine + linesBelow);
if (startLine === -1) {
start = 0;
}
if (endLine === -1) {
end = source.length;
}
const lineDiff = endLine - startLine;
const markerLines = {};
if (lineDiff) {
for (let i = 0; i <= lineDiff; i++) {
const lineNumber = i + startLine;
if (!startColumn) {
markerLines[lineNumber] = true;
} else if (i === 0) {
const sourceLength = source[lineNumber - 1].length;
markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
} else if (i === lineDiff) {
markerLines[lineNumber] = [0, endColumn];
} else {
const sourceLength = source[lineNumber - i].length;
markerLines[lineNumber] = [0, sourceLength];
}
}
} else {
if (startColumn === endColumn) {
if (startColumn) {
markerLines[startLine] = [startColumn, 0];
} else {
markerLines[startLine] = true;
}
} else {
markerLines[startLine] = [startColumn, endColumn - startColumn];
}
}
return {
start,
end,
markerLines
};
}
function codeFrameColumns(rawLines, loc, opts = {}) {
const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
const chalk = (0, _highlight.getChalk)(opts);
const defs = getDefs(chalk);
const maybeHighlight = (chalkFn, string) => {
return highlighted ? chalkFn(string) : string;
};
const lines = rawLines.split(NEWLINE);
const {
start,
end,
markerLines
} = getMarkerLines(loc, lines, opts);
const hasColumns = loc.start && typeof loc.start.column === "number";
const numberMaxWidth = String(end).length;
const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines;
let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => {
const number = start + 1 + index;
const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
const gutter = ` ${paddedNumber} |`;
const hasMarker = markerLines[number];
const lastMarkerLine = !markerLines[number + 1];
if (hasMarker) {
let markerLine = "";
if (Array.isArray(hasMarker)) {
const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
const numberOfMarkers = hasMarker[1] || 1;
markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), " ", markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
if (lastMarkerLine && opts.message) {
markerLine += " " + maybeHighlight(defs.message, opts.message);
}
}
return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
} else {
return ` ${maybeHighlight(defs.gutter, gutter)}${line.length > 0 ? ` ${line}` : ""}`;
}
}).join("\n");
if (opts.message && !hasColumns) {
frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
}
if (highlighted) {
return chalk.reset(frame);
} else {
return frame;
}
}
function _default(rawLines, lineNumber, colNumber, opts = {}) {
if (!deprecationWarningShown) {
deprecationWarningShown = true;
const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
if (process.emitWarning) {
process.emitWarning(message, "DeprecationWarning");
} else {
const deprecationError = new Error(message);
deprecationError.name = "DeprecationWarning";
console.warn(new Error(message));
}
}
colNumber = Math.max(colNumber, 0);
const location = {
start: {
column: colNumber,
line: lineNumber
}
};
return codeFrameColumns(rawLines, location, opts);
}

View File

@ -1,60 +0,0 @@
{
"_from": "@babel/code-frame@^7.14.5",
"_id": "@babel/code-frame@7.14.5",
"_inBundle": false,
"_integrity": "sha512-9pzDqyc6OLDaqe+zbACgFkb6fKMNG6CObKpnYXChRsvYGyEdc7CA2BaqeOM+vOtCS5ndmJicPJhKAwYRI6UfFw==",
"_location": "/@babel/core/@babel/code-frame",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@babel/code-frame@^7.14.5",
"name": "@babel/code-frame",
"escapedName": "@babel%2fcode-frame",
"scope": "@babel",
"rawSpec": "^7.14.5",
"saveSpec": null,
"fetchSpec": "^7.14.5"
},
"_requiredBy": [
"/@babel/core"
],
"_resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.14.5.tgz",
"_shasum": "23b08d740e83f49c5e59945fbf1b43e80bbf4edb",
"_spec": "@babel/code-frame@^7.14.5",
"_where": "/jd/work/GT2/newMaster/Ejectable/node_modules/@babel/core",
"author": {
"name": "The Babel Team",
"url": "https://babel.dev/team"
},
"bugs": {
"url": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen"
},
"bundleDependencies": false,
"dependencies": {
"@babel/highlight": "^7.14.5"
},
"deprecated": false,
"description": "Generate errors that contain a code frame that point to source locations.",
"devDependencies": {
"@types/chalk": "^2.0.0",
"chalk": "^2.0.0",
"strip-ansi": "^4.0.0"
},
"engines": {
"node": ">=6.9.0"
},
"homepage": "https://babel.dev/docs/en/next/babel-code-frame",
"license": "MIT",
"main": "./lib/index.js",
"name": "@babel/code-frame",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/babel/babel.git",
"directory": "packages/babel-code-frame"
},
"version": "7.14.5"
}

View File

@ -1,362 +0,0 @@
### Unreleased [[code][c-unreleased], [diff][d-unreleased]]
[c-unreleased]: https://github.com/json5/json5/tree/master
[d-unreleased]: https://github.com/json5/json5/compare/v2.2.0...HEAD
### v2.2.0 [[code][c2.2.0], [diff][d2.2.0]]
[c2.2.0]: https://github.com/json5/json5/tree/v2.2.0
[d2.2.0]: https://github.com/json5/json5/compare/v2.1.3...v2.2.0
- New: Accurate and documented TypeScript declarations are now included. There
is no need to install `@types/json5`. ([#236], [#244])
### v2.1.3 [[code][c2.1.3], [diff][d2.1.3]]
[c2.1.3]: https://github.com/json5/json5/tree/v2.1.3
[d2.1.3]: https://github.com/json5/json5/compare/v2.1.2...v2.1.3
- Fix: An out of memory bug when parsing numbers has been fixed. ([#228],
[#229])
### v2.1.2 [[code][c2.1.2], [diff][d2.1.2]]
[c2.1.2]: https://github.com/json5/json5/tree/v2.1.2
[d2.1.2]: https://github.com/json5/json5/compare/v2.1.1...v2.1.2
- Fix: Bump `minimist` to `v1.2.5`. ([#222])
### v2.1.1 [[code][c2.1.1], [diff][d2.1.1]]
[c2.1.1]: https://github.com/json5/json5/tree/v2.1.1
[d2.1.1]: https://github.com/json5/json5/compare/v2.0.1...v2.1.1
- New: `package.json` and `package.json5` include a `module` property so
bundlers like webpack, rollup and parcel can take advantage of the ES Module
build. ([#208])
- Fix: `stringify` outputs `\0` as `\\x00` when followed by a digit. ([#210])
- Fix: Spelling mistakes have been fixed. ([#196])
### v2.1.0 [[code][c2.1.0], [diff][d2.1.0]]
[c2.1.0]: https://github.com/json5/json5/tree/v2.1.0
[d2.1.0]: https://github.com/json5/json5/compare/v2.0.1...v2.1.0
- New: The `index.mjs` and `index.min.mjs` browser builds in the `dist`
directory support ES6 modules. ([#187])
### v2.0.1 [[code][c2.0.1], [diff][d2.0.1]]
[c2.0.1]: https://github.com/json5/json5/tree/v2.0.1
[d2.0.1]: https://github.com/json5/json5/compare/v2.0.0...v2.0.1
- Fix: The browser builds in the `dist` directory support ES5. ([#182])
### v2.0.0 [[code][c2.0.0], [diff][d2.0.0]]
[c2.0.0]: https://github.com/json5/json5/tree/v2.0.0
[d2.0.0]: https://github.com/json5/json5/compare/v1.0.1...v2.0.0
- **Major**: JSON5 officially supports Node.js v6 and later. Support for Node.js
v4 has been dropped. Since Node.js v6 supports ES5 features, the code has been
rewritten in native ES5, and the dependence on Babel has been eliminated.
- New: Support for Unicode 10 has been added.
- New: The test framework has been migrated from Mocha to Tap.
- New: The browser build at `dist/index.js` is no longer minified by default. A
minified version is available at `dist/index.min.js`. ([#181])
- Fix: The warning has been made clearer when line and paragraph separators are
used in strings.
- Fix: `package.json5` has been restored, and it is automatically generated and
committed when the version is bumped. A new `build-package` NPM script has
been added to facilitate this.
### v1.0.1 [[code][c1.0.1], [diff][d1.0.1]]
[c1.0.1]: https://github.com/json5/json5/tree/v1.0.1
[d1.0.1]: https://github.com/json5/json5/compare/v1.0.0...v1.0.1
This release includes a bug fix and minor change.
- Fix: `parse` throws on unclosed objects and arrays.
- New: `package.json5` has been removed until an easier way to keep it in sync
with `package.json` is found.
### v1.0.0 [[code][c1.0.0], [diff][d1.0.0]]
[c1.0.0]: https://github.com/json5/json5/tree/v1.0.0
[d1.0.0]: https://github.com/json5/json5/compare/v0.5.1...v1.0.0
This release includes major internal changes and public API enhancements.
- **Major**: JSON5 officially supports Node.js v4 and later. Support for Node.js
v0.10 and v0.12 have been dropped.
- New: Unicode property names and Unicode escapes in property names are
supported. ([#1])
- New: `stringify` outputs trailing commas in objects and arrays when a `space`
option is provided. ([#66])
- New: JSON5 allows line and paragraph separator characters (U+2028 and U+2029)
in strings in order to be compatible with JSON. However, ES5 does not allow
these characters in strings, so JSON5 gives a warning when they are parsed and
escapes them when they are stringified. ([#70])
- New: `stringify` accepts an options object as its second argument. The
supported options are `replacer`, `space`, and a new `quote` option that
specifies the quote character used in strings. ([#71])
- New: The CLI supports STDIN and STDOUT and adds `--out-file`, `--space`, and
`--validate` options. See `json5 --help` for more information. ([#72], [#84],
and [#108])
- New: In addition to the white space characters space `\t`, `\v`, `\f`, `\n`,
`\r`, and `\xA0`, the additional white space characters `\u2028`, `\u2029`,
and all other characters in the Space Separator Unicode category are allowed.
- New: In addition to the character escapes `\'`, `\"`, `\\`, `\b`, `\f`, `\n`,
`\r`, and `\t`, the additional character escapes `\v` and `\0`, hexadecimal
escapes like `\x0F`, and unnecessary escapes like `\a` are allowed in string
values and string property names.
- New: `stringify` outputs strings with single quotes by default but
intelligently uses double quotes if there are more single quotes than double
quotes inside the string. (i.e. `stringify('Stay here.')` outputs
`'Stay here.'` while `stringify('Let\'s go.')` outputs `"Let's go."`)
- New: When a character is not allowed in a string, `stringify` outputs a
character escape like `\t` when available, a hexadecimal escape like `\x0F`
when the Unicode code point is less than 256, or a Unicode character escape
like `\u01FF`, in that order.
- New: `stringify` checks for a `toJSON5` method on objects and, if it exists,
stringifies its return value instead of the object. `toJSON5` overrides
`toJSON` if they both exist.
- New: To `require` or `import` JSON5 files, use `require('json5/lib/register')`
or `import 'json5/lib/register'`. Previous versions used `json5/lib/require`,
which still exists for backward compatibility but is deprecated and will give
a warning.
- New: To use JSON5 in browsers, use the file at `dist/index.js` or
`https://unpkg.com/json5@^1.0.0`.
- Fix: `stringify` properly outputs `Infinity` and `NaN`. ([#67])
- Fix: `isWord` no longer becomes a property of `JSON5` after calling
`stringify`. ([#68] and [#89])
- Fix: `stringify` no longer throws when an object does not have a `prototype`.
([#154])
- Fix: `stringify` properly handles the `key` argument of `toJSON(key)` methods.
`toJSON5(key)` follows this pattern.
- Fix: `stringify` accepts `Number` and `String` objects as its `space`
argument.
- Fix: In addition to a function, `stringify` also accepts an array of keys to
include in the output as its `replacer` argument. Numbers, `Number` objects,
and `String` objects will be converted to a string if they are given as array
values.
### v0.5.1 [[code][c0.5.1], [diff][d0.5.1]]
[c0.5.1]: https://github.com/json5/json5/tree/v0.5.1
[d0.5.1]: https://github.com/json5/json5/compare/v0.5.0...v0.5.1
This release includes a minor fix for indentations when stringifying empty
arrays.
- Fix: Indents no longer appear in empty arrays when stringified. ([#134])
### v0.5.0 [[code][c0.5.0], [diff][d0.5.0]]
[c0.5.0]: https://github.com/json5/json5/tree/v0.5.0
[d0.5.0]: https://github.com/json5/json5/compare/v0.4.0...v0.5.0
This release includes major internal changes and public API enhancements.
- **Major:** JSON5 officially supports Node.js v4 LTS and v5. Support for
Node.js v0.6 and v0.8 have been dropped, while support for v0.10 and v0.12
remain.
- Fix: YUI Compressor no longer fails when compressing json5.js. ([#97])
- New: `parse` and the CLI provide line and column numbers when displaying error
messages. ([#101]; awesome work by [@amb26].)
### v0.4.0 [[code][c0.4.0], [diff][d0.4.0]]
[c0.4.0]: https://github.com/json5/json5/tree/v0.4.0
[d0.4.0]: https://github.com/json5/json5/compare/v0.2.0...v0.4.0
Note that v0.3.0 was tagged, but never published to npm, so this v0.4.0
changelog entry includes v0.3.0 features.
This is a massive release that adds `stringify` support, among other things.
- **Major:** `JSON5.stringify()` now exists!
This method is analogous to the native `JSON.stringify()`;
it just avoids quoting keys where possible.
See the [usage documentation](./README.md#usage) for more.
([#32]; huge thanks and props [@aeisenberg]!)
- New: `NaN` and `-NaN` are now allowed number literals.
([#30]; thanks [@rowanhill].)
- New: Duplicate object keys are now allowed; the last value is used.
This is the same behavior as JSON. ([#57]; thanks [@jordanbtucker].)
- Fix: Properly handle various whitespace and newline cases now.
E.g. JSON5 now properly supports escaped CR and CRLF newlines in strings,
and JSON5 now accepts the same whitespace as JSON (stricter than ES5).
([#58], [#60], and [#63]; thanks [@jordanbtucker].)
- New: Negative hexadecimal numbers (e.g. `-0xC8`) are allowed again.
(They were disallowed in v0.2.0; see below.)
It turns out they *are* valid in ES5, so JSON5 supports them now too.
([#36]; thanks [@jordanbtucker]!)
### v0.2.0 [[code][c0.2.0], [diff][d0.2.0]]
[c0.2.0]: https://github.com/json5/json5/tree/v0.2.0
[d0.2.0]: https://github.com/json5/json5/compare/v0.1.0...v0.2.0
This release fixes some bugs and adds some more utility features to help you
express data more easily:
- **Breaking:** Negative hexadecimal numbers (e.g. `-0xC8`) are rejected now.
While V8 (e.g. Chrome and Node) supported them, it turns out they're invalid
in ES5. This has been [fixed in V8][v8-hex-fix] (and by extension, Chrome
and Node), so JSON5 officially rejects them now, too. ([#36])
- New: Trailing decimal points in decimal numbers are allowed again.
(They were disallowed in v0.1.0; see below.)
They're allowed by ES5, and differentiating between integers and floats may
make sense on some platforms. ([#16]; thanks [@Midar].)
- New: `Infinity` and `-Infinity` are now allowed number literals.
([#30]; thanks [@pepkin88].)
- New: Plus signs (`+`) in front of numbers are now allowed, since it can
be helpful in some contexts to explicitly mark numbers as positive.
(E.g. when a property represents changes or deltas.)
- Fix: unescaped newlines in strings are rejected now.
([#24]; thanks [@Midar].)
### v0.1.0 [[code][c0.1.0], [diff][d0.1.0]]
[c0.1.0]: https://github.com/json5/json5/tree/v0.1.0
[d0.1.0]: https://github.com/json5/json5/compare/v0.0.1...v0.1.0
This release tightens JSON5 support and adds helpful utility features:
- New: Support hexadecimal numbers. (Thanks [@MaxNanasy].)
- Fix: Reject octal numbers properly now. Previously, they were accepted but
improperly parsed as base-10 numbers. (Thanks [@MaxNanasy].)
- **Breaking:** Reject "noctal" numbers now (base-10 numbers that begin with a
leading zero). These are disallowed by both JSON5 and JSON, as well as by
ES5's strict mode. (Thanks [@MaxNanasy].)
- New: Support leading decimal points in decimal numbers.
(Thanks [@MaxNanasy].)
- **Breaking:** Reject trailing decimal points in decimal numbers now. These
are disallowed by both JSON5 and JSON. (Thanks [@MaxNanasy].)
- **Breaking:** Reject omitted elements in arrays now. These are disallowed by
both JSON5 and JSON.
- Fix: Throw proper `SyntaxError` instances on errors now.
- New: Add Node.js `require()` hook. Register via `json5/lib/require`.
- New: Add Node.js `json5` executable to compile JSON5 files to JSON.
### v0.0.1 [[code][c0.0.1], [diff][d0.0.1]]
[c0.0.1]: https://github.com/json5/json5/tree/v0.0.1
[d0.0.1]: https://github.com/json5/json5/compare/v0.0.0...v0.0.1
This was the first implementation of this JSON5 parser.
- Support unquoted object keys, including reserved words. Unicode characters
and escape sequences sequences aren't yet supported.
- Support single-quoted strings.
- Support multi-line strings.
- Support trailing commas in arrays and objects.
- Support comments, both inline and block.
### v0.0.0 [[code](https://github.com/json5/json5/tree/v0.0.0)]
Let's consider this to be Douglas Crockford's original [json_parse.js] — a
parser for the regular JSON format.
[json_parse.js]: https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
[v8-hex-fix]: http://code.google.com/p/v8/issues/detail?id=2240
[@MaxNanasy]: https://github.com/MaxNanasy
[@Midar]: https://github.com/Midar
[@pepkin88]: https://github.com/pepkin88
[@rowanhill]: https://github.com/rowanhill
[@aeisenberg]: https://github.com/aeisenberg
[@jordanbtucker]: https://github.com/jordanbtucker
[@amb26]: https://github.com/amb26
[#1]: https://github.com/json5/json5/issues/1
[#16]: https://github.com/json5/json5/issues/16
[#24]: https://github.com/json5/json5/issues/24
[#30]: https://github.com/json5/json5/issues/30
[#32]: https://github.com/json5/json5/issues/32
[#36]: https://github.com/json5/json5/issues/36
[#57]: https://github.com/json5/json5/issues/57
[#58]: https://github.com/json5/json5/pull/58
[#60]: https://github.com/json5/json5/pull/60
[#63]: https://github.com/json5/json5/pull/63
[#66]: https://github.com/json5/json5/issues/66
[#67]: https://github.com/json5/json5/issues/67
[#68]: https://github.com/json5/json5/issues/68
[#70]: https://github.com/json5/json5/issues/70
[#71]: https://github.com/json5/json5/issues/71
[#72]: https://github.com/json5/json5/issues/72
[#84]: https://github.com/json5/json5/pull/84
[#89]: https://github.com/json5/json5/pull/89
[#97]: https://github.com/json5/json5/pull/97
[#101]: https://github.com/json5/json5/pull/101
[#108]: https://github.com/json5/json5/pull/108
[#134]: https://github.com/json5/json5/pull/134
[#154]: https://github.com/json5/json5/issues/154
[#181]: https://github.com/json5/json5/issues/181
[#182]: https://github.com/json5/json5/issues/182
[#187]: https://github.com/json5/json5/issues/187
[#196]: https://github.com/json5/json5/issues/196
[#208]: https://github.com/json5/json5/issues/208
[#210]: https://github.com/json5/json5/issues/210
[#222]: https://github.com/json5/json5/issues/222
[#228]: https://github.com/json5/json5/issues/228
[#229]: https://github.com/json5/json5/issues/229
[#236]: https://github.com/json5/json5/issues/236
[#244]: https://github.com/json5/json5/issues/244

View File

@ -1,23 +0,0 @@
MIT License
Copyright (c) 2012-2018 Aseem Kishore, and [others].
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.
[others]: https://github.com/json5/json5/contributors

View File

@ -1,234 +0,0 @@
# JSON5 JSON for Humans
[![Build Status](https://travis-ci.com/json5/json5.svg)][Build Status]
[![Coverage
Status](https://coveralls.io/repos/github/json5/json5/badge.svg)][Coverage
Status]
The JSON5 Data Interchange Format (JSON5) is a superset of [JSON] that aims to
alleviate some of the limitations of JSON by expanding its syntax to include
some productions from [ECMAScript 5.1].
This JavaScript library is the official reference implementation for JSON5
parsing and serialization libraries.
[Build Status]: https://travis-ci.com/json5/json5
[Coverage Status]: https://coveralls.io/github/json5/json5
[JSON]: https://tools.ietf.org/html/rfc7159
[ECMAScript 5.1]: https://www.ecma-international.org/ecma-262/5.1/
## Summary of Features
The following ECMAScript 5.1 features, which are not supported in JSON, have
been extended to JSON5.
### Objects
- Object keys may be an ECMAScript 5.1 _[IdentifierName]_.
- Objects may have a single trailing comma.
### Arrays
- Arrays may have a single trailing comma.
### Strings
- Strings may be single quoted.
- Strings may span multiple lines by escaping new line characters.
- Strings may include character escapes.
### Numbers
- Numbers may be hexadecimal.
- Numbers may have a leading or trailing decimal point.
- Numbers may be [IEEE 754] positive infinity, negative infinity, and NaN.
- Numbers may begin with an explicit plus sign.
### Comments
- Single and multi-line comments are allowed.
### White Space
- Additional white space characters are allowed.
[IdentifierName]: https://www.ecma-international.org/ecma-262/5.1/#sec-7.6
[IEEE 754]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
## Short Example
```js
{
// comments
unquoted: 'and you can quote me on that',
singleQuotes: 'I can use "double quotes" here',
lineBreaks: "Look, Mom! \
No \\n's!",
hexadecimal: 0xdecaf,
leadingDecimalPoint: .8675309, andTrailing: 8675309.,
positiveSign: +1,
trailingComma: 'in objects', andIn: ['arrays',],
"backwardsCompatible": "with JSON",
}
```
## Specification
For a detailed explanation of the JSON5 format, please read the [official
specification](https://json5.github.io/json5-spec/).
## Installation
### Node.js
```sh
npm install json5
```
```js
const JSON5 = require('json5')
```
### Browsers
```html
<script src="https://unpkg.com/json5@^2.0.0/dist/index.min.js"></script>
```
This will create a global `JSON5` variable.
## API
The JSON5 API is compatible with the [JSON API].
[JSON API]:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
### JSON5.parse()
Parses a JSON5 string, constructing the JavaScript value or object described by
the string. An optional reviver function can be provided to perform a
transformation on the resulting object before it is returned.
#### Syntax
JSON5.parse(text[, reviver])
#### Parameters
- `text`: The string to parse as JSON5.
- `reviver`: If a function, this prescribes how the value originally produced by
parsing is transformed, before being returned.
#### Return value
The object corresponding to the given JSON5 text.
### JSON5.stringify()
Converts a JavaScript value to a JSON5 string, optionally replacing values if a
replacer function is specified, or optionally including only the specified
properties if a replacer array is specified.
#### Syntax
JSON5.stringify(value[, replacer[, space]])
JSON5.stringify(value[, options])
#### Parameters
- `value`: The value to convert to a JSON5 string.
- `replacer`: A function that alters the behavior of the stringification
process, or an array of String and Number objects that serve as a whitelist
for selecting/filtering the properties of the value object to be included in
the JSON5 string. If this value is null or not provided, all properties of the
object are included in the resulting JSON5 string.
- `space`: A String or Number object that's used to insert white space into the
output JSON5 string for readability purposes. If this is a Number, it
indicates the number of space characters to use as white space; this number is
capped at 10 (if it is greater, the value is just 10). Values less than 1
indicate that no space should be used. If this is a String, the string (or the
first 10 characters of the string, if it's longer than that) is used as white
space. If this parameter is not provided (or is null), no white space is used.
If white space is used, trailing commas will be used in objects and arrays.
- `options`: An object with the following properties:
- `replacer`: Same as the `replacer` parameter.
- `space`: Same as the `space` parameter.
- `quote`: A String representing the quote character to use when serializing
strings.
#### Return value
A JSON5 string representing the value.
### Node.js `require()` JSON5 files
When using Node.js, you can `require()` JSON5 files by adding the following
statement.
```js
require('json5/lib/register')
```
Then you can load a JSON5 file with a Node.js `require()` statement. For
example:
```js
const config = require('./config.json5')
```
## CLI
Since JSON is more widely used than JSON5, this package includes a CLI for
converting JSON5 to JSON and for validating the syntax of JSON5 documents.
### Installation
```sh
npm install --global json5
```
### Usage
```sh
json5 [options] <file>
```
If `<file>` is not provided, then STDIN is used.
#### Options:
- `-s`, `--space`: The number of spaces to indent or `t` for tabs
- `-o`, `--out-file [file]`: Output to the specified file, otherwise STDOUT
- `-v`, `--validate`: Validate JSON5 but do not output JSON
- `-V`, `--version`: Output the version number
- `-h`, `--help`: Output usage information
## Contributing
### Development
```sh
git clone https://github.com/json5/json5
cd json5
npm install
```
When contributing code, please write relevant tests and run `npm test` and `npm
run lint` before submitting pull requests. Please use an editor that supports
[EditorConfig](http://editorconfig.org/).
### Issues
To report bugs or request features regarding the JSON5 data format, please
submit an issue to the [official specification
repository](https://github.com/json5/json5-spec).
To report bugs or request features regarding the JavaScript implementation of
JSON5, please submit an issue to this repository.
## License
MIT. See [LICENSE.md](./LICENSE.md) for details.
## Credits
[Assem Kishore](https://github.com/aseemk) founded this project.
[Michael Bolin](http://bolinfest.com/) independently arrived at and published
some of these same ideas with awesome explanations and detail. Recommended
reading: [Suggested Improvements to JSON](http://bolinfest.com/essays/json.html)
[Douglas Crockford](http://www.crockford.com/) of course designed and built
JSON, but his state machine diagrams on the [JSON website](http://json.org/), as
cheesy as it may sound, gave us motivation and confidence that building a new
parser to implement these ideas was within reach! The original
implementation of JSON5 was also modeled directly off of Dougs open-source
[json_parse.js] parser. Were grateful for that clean and well-documented
code.
[json_parse.js]:
https://github.com/douglascrockford/JSON-js/blob/03157639c7a7cddd2e9f032537f346f1a87c0f6d/json_parse.js
[Max Nanasy](https://github.com/MaxNanasy) has been an early and prolific
supporter, contributing multiple patches and ideas.
[Andrew Eisenberg](https://github.com/aeisenberg) contributed the original
`stringify` method.
[Jordan Tucker](https://github.com/jordanbtucker) has aligned JSON5 more closely
with ES5, wrote the official JSON5 specification, completely rewrote the
codebase from the ground up, and is actively maintaining this project.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,112 +0,0 @@
#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const minimist = require('minimist')
const pkg = require('../package.json')
const JSON5 = require('./')
const argv = minimist(process.argv.slice(2), {
alias: {
'convert': 'c',
'space': 's',
'validate': 'v',
'out-file': 'o',
'version': 'V',
'help': 'h',
},
boolean: [
'convert',
'validate',
'version',
'help',
],
string: [
'space',
'out-file',
],
})
if (argv.version) {
version()
} else if (argv.help) {
usage()
} else {
const inFilename = argv._[0]
let readStream
if (inFilename) {
readStream = fs.createReadStream(inFilename)
} else {
readStream = process.stdin
}
let json5 = ''
readStream.on('data', data => {
json5 += data
})
readStream.on('end', () => {
let space
if (argv.space === 't' || argv.space === 'tab') {
space = '\t'
} else {
space = Number(argv.space)
}
let value
try {
value = JSON5.parse(json5)
if (!argv.validate) {
const json = JSON.stringify(value, null, space)
let writeStream
// --convert is for backward compatibility with v0.5.1. If
// specified with <file> and not --out-file, then a file with
// the same name but with a .json extension will be written.
if (argv.convert && inFilename && !argv.o) {
const parsedFilename = path.parse(inFilename)
const outFilename = path.format(
Object.assign(
parsedFilename,
{base: path.basename(parsedFilename.base, parsedFilename.ext) + '.json'}
)
)
writeStream = fs.createWriteStream(outFilename)
} else if (argv.o) {
writeStream = fs.createWriteStream(argv.o)
} else {
writeStream = process.stdout
}
writeStream.write(json)
}
} catch (err) {
console.error(err.message)
process.exit(1)
}
})
}
function version () {
console.log(pkg.version)
}
function usage () {
console.log(
`
Usage: json5 [options] <file>
If <file> is not provided, then STDIN is used.
Options:
-s, --space The number of spaces to indent or 't' for tabs
-o, --out-file [file] Output to the specified file, otherwise STDOUT
-v, --validate Validate JSON5 but do not output JSON
-V, --version Output the version number
-h, --help Output usage information`
)
}

View File

@ -1,4 +0,0 @@
import parse = require('./parse')
import stringify = require('./stringify')
export {parse, stringify}

View File

@ -1,9 +0,0 @@
const parse = require('./parse')
const stringify = require('./stringify')
const JSON5 = {
parse,
stringify,
}
module.exports = JSON5

View File

@ -1,15 +0,0 @@
/**
* Parses a JSON5 string, constructing the JavaScript value or object described
* by the string.
* @template T The type of the return value.
* @param text The string to parse as JSON5.
* @param reviver A function that prescribes how the value originally produced
* by parsing is transformed before being returned.
* @returns The JavaScript value converted from the JSON5 string.
*/
declare function parse<T = any>(
text: string,
reviver?: ((this: any, key: string, value: any) => any) | null,
): T
export = parse

File diff suppressed because it is too large Load Diff

View File

@ -1,13 +0,0 @@
const fs = require('fs')
const JSON5 = require('./')
// eslint-disable-next-line node/no-deprecated-api
require.extensions['.json5'] = function (module, filename) {
const content = fs.readFileSync(filename, 'utf8')
try {
module.exports = JSON5.parse(content)
} catch (err) {
err.message = filename + ': ' + err.message
throw err
}
}

View File

@ -1,4 +0,0 @@
// This file is for backward compatibility with v0.5.1.
require('./register')
console.warn("'json5/require' is deprecated. Please use 'json5/register' instead.")

View File

@ -1,89 +0,0 @@
declare type StringifyOptions = {
/**
* A function that alters the behavior of the stringification process, or an
* array of String and Number objects that serve as a allowlist for
* selecting/filtering the properties of the value object to be included in
* the JSON5 string. If this value is null or not provided, all properties
* of the object are included in the resulting JSON5 string.
*/
replacer?:
| ((this: any, key: string, value: any) => any)
| (string | number)[]
| null
/**
* A String or Number object that's used to insert white space into the
* output JSON5 string for readability purposes. If this is a Number, it
* indicates the number of space characters to use as white space; this
* number is capped at 10 (if it is greater, the value is just 10). Values
* less than 1 indicate that no space should be used. If this is a String,
* the string (or the first 10 characters of the string, if it's longer than
* that) is used as white space. If this parameter is not provided (or is
* null), no white space is used. If white space is used, trailing commas
* will be used in objects and arrays.
*/
space?: string | number | null
/**
* A String representing the quote character to use when serializing
* strings.
*/
quote?: string | null
}
/**
* Converts a JavaScript value to a JSON5 string.
* @param value The value to convert to a JSON5 string.
* @param replacer A function that alters the behavior of the stringification
* process. If this value is null or not provided, all properties of the object
* are included in the resulting JSON5 string.
* @param space A String or Number object that's used to insert white space into
* the output JSON5 string for readability purposes. If this is a Number, it
* indicates the number of space characters to use as white space; this number
* is capped at 10 (if it is greater, the value is just 10). Values less than 1
* indicate that no space should be used. If this is a String, the string (or
* the first 10 characters of the string, if it's longer than that) is used as
* white space. If this parameter is not provided (or is null), no white space
* is used. If white space is used, trailing commas will be used in objects and
* arrays.
* @returns The JSON5 string converted from the JavaScript value.
*/
declare function stringify(
value: any,
replacer?: ((this: any, key: string, value: any) => any) | null,
space?: string | number | null,
): string
/**
* Converts a JavaScript value to a JSON5 string.
* @param value The value to convert to a JSON5 string.
* @param replacer An array of String and Number objects that serve as a
* allowlist for selecting/filtering the properties of the value object to be
* included in the JSON5 string. If this value is null or not provided, all
* properties of the object are included in the resulting JSON5 string.
* @param space A String or Number object that's used to insert white space into
* the output JSON5 string for readability purposes. If this is a Number, it
* indicates the number of space characters to use as white space; this number
* is capped at 10 (if it is greater, the value is just 10). Values less than 1
* indicate that no space should be used. If this is a String, the string (or
* the first 10 characters of the string, if it's longer than that) is used as
* white space. If this parameter is not provided (or is null), no white space
* is used. If white space is used, trailing commas will be used in objects and
* arrays.
* @returns The JSON5 string converted from the JavaScript value.
*/
declare function stringify(
value: any,
replacer: (string | number)[],
space?: string | number | null,
): string
/**
* Converts a JavaScript value to a JSON5 string.
* @param value The value to convert to a JSON5 string.
* @param options An object specifying options.
* @returns The JSON5 string converted from the JavaScript value.
*/
declare function stringify(value: any, options: StringifyOptions): string
export = stringify

View File

@ -1,261 +0,0 @@
const util = require('./util')
module.exports = function stringify (value, replacer, space) {
const stack = []
let indent = ''
let propertyList
let replacerFunc
let gap = ''
let quote
if (
replacer != null &&
typeof replacer === 'object' &&
!Array.isArray(replacer)
) {
space = replacer.space
quote = replacer.quote
replacer = replacer.replacer
}
if (typeof replacer === 'function') {
replacerFunc = replacer
} else if (Array.isArray(replacer)) {
propertyList = []
for (const v of replacer) {
let item
if (typeof v === 'string') {
item = v
} else if (
typeof v === 'number' ||
v instanceof String ||
v instanceof Number
) {
item = String(v)
}
if (item !== undefined && propertyList.indexOf(item) < 0) {
propertyList.push(item)
}
}
}
if (space instanceof Number) {
space = Number(space)
} else if (space instanceof String) {
space = String(space)
}
if (typeof space === 'number') {
if (space > 0) {
space = Math.min(10, Math.floor(space))
gap = ' '.substr(0, space)
}
} else if (typeof space === 'string') {
gap = space.substr(0, 10)
}
return serializeProperty('', {'': value})
function serializeProperty (key, holder) {
let value = holder[key]
if (value != null) {
if (typeof value.toJSON5 === 'function') {
value = value.toJSON5(key)
} else if (typeof value.toJSON === 'function') {
value = value.toJSON(key)
}
}
if (replacerFunc) {
value = replacerFunc.call(holder, key, value)
}
if (value instanceof Number) {
value = Number(value)
} else if (value instanceof String) {
value = String(value)
} else if (value instanceof Boolean) {
value = value.valueOf()
}
switch (value) {
case null: return 'null'
case true: return 'true'
case false: return 'false'
}
if (typeof value === 'string') {
return quoteString(value, false)
}
if (typeof value === 'number') {
return String(value)
}
if (typeof value === 'object') {
return Array.isArray(value) ? serializeArray(value) : serializeObject(value)
}
return undefined
}
function quoteString (value) {
const quotes = {
"'": 0.1,
'"': 0.2,
}
const replacements = {
"'": "\\'",
'"': '\\"',
'\\': '\\\\',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
'\v': '\\v',
'\0': '\\0',
'\u2028': '\\u2028',
'\u2029': '\\u2029',
}
let product = ''
for (let i = 0; i < value.length; i++) {
const c = value[i]
switch (c) {
case "'":
case '"':
quotes[c]++
product += c
continue
case '\0':
if (util.isDigit(value[i + 1])) {
product += '\\x00'
continue
}
}
if (replacements[c]) {
product += replacements[c]
continue
}
if (c < ' ') {
let hexString = c.charCodeAt(0).toString(16)
product += '\\x' + ('00' + hexString).substring(hexString.length)
continue
}
product += c
}
const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b)
product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar])
return quoteChar + product + quoteChar
}
function serializeObject (value) {
if (stack.indexOf(value) >= 0) {
throw TypeError('Converting circular structure to JSON5')
}
stack.push(value)
let stepback = indent
indent = indent + gap
let keys = propertyList || Object.keys(value)
let partial = []
for (const key of keys) {
const propertyString = serializeProperty(key, value)
if (propertyString !== undefined) {
let member = serializeKey(key) + ':'
if (gap !== '') {
member += ' '
}
member += propertyString
partial.push(member)
}
}
let final
if (partial.length === 0) {
final = '{}'
} else {
let properties
if (gap === '') {
properties = partial.join(',')
final = '{' + properties + '}'
} else {
let separator = ',\n' + indent
properties = partial.join(separator)
final = '{\n' + indent + properties + ',\n' + stepback + '}'
}
}
stack.pop()
indent = stepback
return final
}
function serializeKey (key) {
if (key.length === 0) {
return quoteString(key, true)
}
const firstChar = String.fromCodePoint(key.codePointAt(0))
if (!util.isIdStartChar(firstChar)) {
return quoteString(key, true)
}
for (let i = firstChar.length; i < key.length; i++) {
if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {
return quoteString(key, true)
}
}
return key
}
function serializeArray (value) {
if (stack.indexOf(value) >= 0) {
throw TypeError('Converting circular structure to JSON5')
}
stack.push(value)
let stepback = indent
indent = indent + gap
let partial = []
for (let i = 0; i < value.length; i++) {
const propertyString = serializeProperty(String(i), value)
partial.push((propertyString !== undefined) ? propertyString : 'null')
}
let final
if (partial.length === 0) {
final = '[]'
} else {
if (gap === '') {
let properties = partial.join(',')
final = '[' + properties + ']'
} else {
let separator = ',\n' + indent
let properties = partial.join(separator)
final = '[\n' + indent + properties + ',\n' + stepback + ']'
}
}
stack.pop()
indent = stepback
return final
}
}

View File

@ -1,3 +0,0 @@
export declare const Space_Separator: RegExp
export declare const ID_Start: RegExp
export declare const ID_Continue: RegExp

File diff suppressed because one or more lines are too long

View File

@ -1,5 +0,0 @@
export declare function isSpaceSeparator(c?: string): boolean
export declare function isIdStartChar(c?: string): boolean
export declare function isIdContinueChar(c?: string): boolean
export declare function isDigit(c?: string): boolean
export declare function isHexDigit(c?: string): boolean

View File

@ -1,35 +0,0 @@
const unicode = require('../lib/unicode')
module.exports = {
isSpaceSeparator (c) {
return typeof c === 'string' && unicode.Space_Separator.test(c)
},
isIdStartChar (c) {
return typeof c === 'string' && (
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c === '$') || (c === '_') ||
unicode.ID_Start.test(c)
)
},
isIdContinueChar (c) {
return typeof c === 'string' && (
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
(c === '$') || (c === '_') ||
(c === '\u200C') || (c === '\u200D') ||
unicode.ID_Continue.test(c)
)
},
isDigit (c) {
return typeof c === 'string' && /[0-9]/.test(c)
},
isHexDigit (c) {
return typeof c === 'string' && /[0-9A-Fa-f]/.test(c)
},
}

View File

@ -1,111 +0,0 @@
{
"_from": "json5@^2.1.2",
"_id": "json5@2.2.0",
"_inBundle": false,
"_integrity": "sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==",
"_location": "/@babel/core/json5",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "json5@^2.1.2",
"name": "json5",
"escapedName": "json5",
"rawSpec": "^2.1.2",
"saveSpec": null,
"fetchSpec": "^2.1.2"
},
"_requiredBy": [
"/@babel/core"
],
"_resolved": "https://registry.npmjs.org/json5/-/json5-2.2.0.tgz",
"_shasum": "2dfefe720c6ba525d9ebd909950f0515316c89a3",
"_spec": "json5@^2.1.2",
"_where": "/jd/work/GT2/newMaster/Ejectable/node_modules/@babel/core",
"author": {
"name": "Aseem Kishore",
"email": "aseem.kishore@gmail.com"
},
"bin": {
"json5": "lib/cli.js"
},
"browser": "dist/index.js",
"bugs": {
"url": "https://github.com/json5/json5/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Max Nanasy",
"email": "max.nanasy@gmail.com"
},
{
"name": "Andrew Eisenberg",
"email": "andrew@eisenberg.as"
},
{
"name": "Jordan Tucker",
"email": "jordanbtucker@gmail.com"
}
],
"dependencies": {
"minimist": "^1.2.5"
},
"deprecated": false,
"description": "JSON for humans.",
"devDependencies": {
"core-js": "^2.6.5",
"eslint": "^5.15.3",
"eslint-config-standard": "^12.0.0",
"eslint-plugin-import": "^2.16.0",
"eslint-plugin-node": "^8.0.1",
"eslint-plugin-promise": "^4.0.1",
"eslint-plugin-standard": "^4.0.0",
"regenerate": "^1.4.0",
"rollup": "^0.64.1",
"rollup-plugin-buble": "^0.19.6",
"rollup-plugin-commonjs": "^9.2.1",
"rollup-plugin-node-resolve": "^3.4.0",
"rollup-plugin-terser": "^1.0.1",
"sinon": "^6.3.5",
"tap": "^12.6.0",
"unicode-10.0.0": "^0.7.5"
},
"engines": {
"node": ">=6"
},
"files": [
"lib/",
"dist/"
],
"homepage": "http://json5.org/",
"keywords": [
"json",
"json5",
"es5",
"es2015",
"ecmascript"
],
"license": "MIT",
"main": "lib/index.js",
"module": "dist/index.mjs",
"name": "json5",
"repository": {
"type": "git",
"url": "git+https://github.com/json5/json5.git"
},
"scripts": {
"build": "rollup -c",
"build-package": "node build/package.js",
"build-unicode": "node build/unicode.js",
"coverage": "tap --coverage-report html test",
"lint": "eslint --fix .",
"prepublishOnly": "npm run production",
"preversion": "npm run production",
"production": "npm run lint && npm test && npm run build",
"test": "tap -Rspec --100 test",
"version": "npm run build-package && git add package.json5"
},
"types": "lib/index.d.ts",
"version": "2.2.0"
}

View File

@ -1,70 +0,0 @@
# changes log
## 6.2.0
* Coerce numbers to strings when passed to semver.coerce()
* Add `rtl` option to coerce from right to left
## 6.1.3
* Handle X-ranges properly in includePrerelease mode
## 6.1.2
* Do not throw when testing invalid version strings
## 6.1.1
* Add options support for semver.coerce()
* Handle undefined version passed to Range.test
## 6.1.0
* Add semver.compareBuild function
* Support `*` in semver.intersects
## 6.0
* Fix `intersects` logic.
This is technically a bug fix, but since it is also a change to behavior
that may require users updating their code, it is marked as a major
version increment.
## 5.7
* Add `minVersion` method
## 5.6
* Move boolean `loose` param to an options object, with
backwards-compatibility protection.
* Add ability to opt out of special prerelease version handling with
the `includePrerelease` option flag.
## 5.5
* Add version coercion capabilities
## 5.4
* Add intersection checking
## 5.3
* Add `minSatisfying` method
## 5.2
* Add `prerelease(v)` that returns prerelease components
## 5.1
* Add Backus-Naur for ranges
* Remove excessively cute inspection methods
## 5.0
* Remove AMD/Browserified build artifacts
* Fix ltr and gtr when using the `*` range
* Fix for range `*` with a prerelease identifier

View File

@ -1,15 +0,0 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and 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.

View File

@ -1,443 +0,0 @@
semver(1) -- The semantic versioner for npm
===========================================
## Install
```bash
npm install semver
````
## Usage
As a node module:
```js
const semver = require('semver')
semver.valid('1.2.3') // '1.2.3'
semver.valid('a.b.c') // null
semver.clean(' =v1.2.3 ') // '1.2.3'
semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true
semver.gt('1.2.3', '9.8.7') // false
semver.lt('1.2.3', '9.8.7') // true
semver.minVersion('>=1.0.0') // '1.0.0'
semver.valid(semver.coerce('v2')) // '2.0.0'
semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7'
```
As a command-line utility:
```
$ semver -h
A JavaScript implementation of the https://semver.org/ specification
Copyright Isaac Z. Schlueter
Usage: semver [options] <version> [<version> [...]]
Prints valid versions sorted by SemVer precedence
Options:
-r --range <range>
Print versions that match the specified range.
-i --increment [<level>]
Increment a version by the specified level. Level can
be one of: major, minor, patch, premajor, preminor,
prepatch, or prerelease. Default level is 'patch'.
Only one version may be specified.
--preid <identifier>
Identifier to be used to prefix premajor, preminor,
prepatch or prerelease version increments.
-l --loose
Interpret versions and ranges loosely
-p --include-prerelease
Always include prerelease versions in range matching
-c --coerce
Coerce a string into SemVer if possible
(does not imply --loose)
--rtl
Coerce version strings right to left
--ltr
Coerce version strings left to right (default)
Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.
If no satisfying versions are found, then exits failure.
Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.
```
## Versions
A "version" is described by the `v2.0.0` specification found at
<https://semver.org/>.
A leading `"="` or `"v"` character is stripped off and ignored.
## Ranges
A `version range` is a set of `comparators` which specify versions
that satisfy the range.
A `comparator` is composed of an `operator` and a `version`. The set
of primitive `operators` is:
* `<` Less than
* `<=` Less than or equal to
* `>` Greater than
* `>=` Greater than or equal to
* `=` Equal. If no operator is specified, then equality is assumed,
so this operator is optional, but MAY be included.
For example, the comparator `>=1.2.7` would match the versions
`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6`
or `1.1.0`.
Comparators can be joined by whitespace to form a `comparator set`,
which is satisfied by the **intersection** of all of the comparators
it includes.
A range is composed of one or more comparator sets, joined by `||`. A
version matches a range if and only if every comparator in at least
one of the `||`-separated comparator sets is satisfied by the version.
For example, the range `>=1.2.7 <1.3.0` would match the versions
`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`,
or `1.1.0`.
The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`,
`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`.
### Prerelease Tags
If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then
it will only be allowed to satisfy comparator sets if at least one
comparator with the same `[major, minor, patch]` tuple also has a
prerelease tag.
For example, the range `>1.2.3-alpha.3` would be allowed to match the
version `1.2.3-alpha.7`, but it would *not* be satisfied by
`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater
than" `1.2.3-alpha.3` according to the SemVer sort rules. The version
range only accepts prerelease tags on the `1.2.3` version. The
version `3.4.5` *would* satisfy the range, because it does not have a
prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`.
The purpose for this behavior is twofold. First, prerelease versions
frequently are updated very quickly, and contain many breaking changes
that are (by the author's design) not yet fit for public consumption.
Therefore, by default, they are excluded from range matching
semantics.
Second, a user who has opted into using a prerelease version has
clearly indicated the intent to use *that specific* set of
alpha/beta/rc versions. By including a prerelease tag in the range,
the user is indicating that they are aware of the risk. However, it
is still not appropriate to assume that they have opted into taking a
similar risk on the *next* set of prerelease versions.
Note that this behavior can be suppressed (treating all prerelease
versions as if they were normal versions, for the purpose of range
matching) by setting the `includePrerelease` flag on the options
object to any
[functions](https://github.com/npm/node-semver#functions) that do
range matching.
#### Prerelease Identifiers
The method `.inc` takes an additional `identifier` string argument that
will append the value of the string as a prerelease identifier:
```javascript
semver.inc('1.2.3', 'prerelease', 'beta')
// '1.2.4-beta.0'
```
command-line example:
```bash
$ semver 1.2.3 -i prerelease --preid beta
1.2.4-beta.0
```
Which then can be used to increment further:
```bash
$ semver 1.2.4-beta.0 -i prerelease
1.2.4-beta.1
```
### Advanced Range Syntax
Advanced range syntax desugars to primitive comparators in
deterministic ways.
Advanced ranges may be combined in the same way as primitive
comparators using white space or `||`.
#### Hyphen Ranges `X.Y.Z - A.B.C`
Specifies an inclusive set.
* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4`
If a partial version is provided as the first version in the inclusive
range, then the missing pieces are replaced with zeroes.
* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4`
If a partial version is provided as the second version in the
inclusive range, then all versions that start with the supplied parts
of the tuple are accepted, but nothing that would be greater than the
provided tuple parts.
* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0`
* `1.2.3 - 2` := `>=1.2.3 <3.0.0`
#### X-Ranges `1.2.x` `1.X` `1.2.*` `*`
Any of `X`, `x`, or `*` may be used to "stand in" for one of the
numeric values in the `[major, minor, patch]` tuple.
* `*` := `>=0.0.0` (Any version satisfies)
* `1.x` := `>=1.0.0 <2.0.0` (Matching major version)
* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions)
A partial version range is treated as an X-Range, so the special
character is in fact optional.
* `""` (empty string) := `*` := `>=0.0.0`
* `1` := `1.x.x` := `>=1.0.0 <2.0.0`
* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0`
#### Tilde Ranges `~1.2.3` `~1.2` `~1`
Allows patch-level changes if a minor version is specified on the
comparator. Allows minor-level changes if not.
* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0`
* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`)
* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`)
* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0`
* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`)
* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`)
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in
the `1.2.3` version will be allowed, if they are greater than or
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
`1.2.4-beta.2` would not, because it is a prerelease of a
different `[major, minor, patch]` tuple.
#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4`
Allows changes that do not modify the left-most non-zero element in the
`[major, minor, patch]` tuple. In other words, this allows patch and
minor updates for versions `1.0.0` and above, patch updates for
versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`.
Many authors treat a `0.x` version as if the `x` were the major
"breaking-change" indicator.
Caret ranges are ideal when an author may make breaking changes
between `0.2.4` and `0.3.0` releases, which is a common practice.
However, it presumes that there will *not* be breaking changes between
`0.2.4` and `0.2.5`. It allows for changes that are presumed to be
additive (but non-breaking), according to commonly observed practices.
* `^1.2.3` := `>=1.2.3 <2.0.0`
* `^0.2.3` := `>=0.2.3 <0.3.0`
* `^0.0.3` := `>=0.0.3 <0.0.4`
* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in
the `1.2.3` version will be allowed, if they are greater than or
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
`1.2.4-beta.2` would not, because it is a prerelease of a
different `[major, minor, patch]` tuple.
* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the
`0.0.3` version *only* will be allowed, if they are greater than or
equal to `beta`. So, `0.0.3-pr.2` would be allowed.
When parsing caret ranges, a missing `patch` value desugars to the
number `0`, but will allow flexibility within that value, even if the
major and minor versions are both `0`.
* `^1.2.x` := `>=1.2.0 <2.0.0`
* `^0.0.x` := `>=0.0.0 <0.1.0`
* `^0.0` := `>=0.0.0 <0.1.0`
A missing `minor` and `patch` values will desugar to zero, but also
allow flexibility within those values, even if the major version is
zero.
* `^1.x` := `>=1.0.0 <2.0.0`
* `^0.x` := `>=0.0.0 <1.0.0`
### Range Grammar
Putting all this together, here is a Backus-Naur grammar for ranges,
for the benefit of parser authors:
```bnf
range-set ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range ::= hyphen | simple ( ' ' simple ) * | ''
hyphen ::= partial ' - ' partial
simple ::= primitive | partial | tilde | caret
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr ::= 'x' | 'X' | '*' | nr
nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
tilde ::= '~' partial
caret ::= '^' partial
qualifier ::= ( '-' pre )? ( '+' build )?
pre ::= parts
build ::= parts
parts ::= part ( '.' part ) *
part ::= nr | [-0-9A-Za-z]+
```
## Functions
All methods and classes take a final `options` object argument. All
options in this object are `false` by default. The options supported
are:
- `loose` Be more forgiving about not-quite-valid semver strings.
(Any resulting output will always be 100% strict compliant, of
course.) For backwards compatibility reasons, if the `options`
argument is a boolean value instead of an object, it is interpreted
to be the `loose` param.
- `includePrerelease` Set to suppress the [default
behavior](https://github.com/npm/node-semver#prerelease-tags) of
excluding prerelease tagged versions from ranges unless they are
explicitly opted into.
Strict-mode Comparators and Ranges will be strict about the SemVer
strings that they parse.
* `valid(v)`: Return the parsed version, or null if it's not valid.
* `inc(v, release)`: Return the version incremented by the release
type (`major`, `premajor`, `minor`, `preminor`, `patch`,
`prepatch`, or `prerelease`), or null if it's not valid
* `premajor` in one call will bump the version up to the next major
version and down to a prerelease of that major version.
`preminor`, and `prepatch` work the same way.
* If called from a non-prerelease version, the `prerelease` will work the
same as `prepatch`. It increments the patch version, then makes a
prerelease. If the input version is already a prerelease it simply
increments it.
* `prerelease(v)`: Returns an array of prerelease components, or null
if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]`
* `major(v)`: Return the major version number.
* `minor(v)`: Return the minor version number.
* `patch(v)`: Return the patch version number.
* `intersects(r1, r2, loose)`: Return true if the two supplied ranges
or comparators intersect.
* `parse(v)`: Attempt to parse a string as a semantic version, returning either
a `SemVer` object or `null`.
### Comparison
* `gt(v1, v2)`: `v1 > v2`
* `gte(v1, v2)`: `v1 >= v2`
* `lt(v1, v2)`: `v1 < v2`
* `lte(v1, v2)`: `v1 <= v2`
* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent,
even if they're not the exact same string. You already know how to
compare strings.
* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`.
* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call
the corresponding function above. `"==="` and `"!=="` do simple
string comparison, but are included for completeness. Throws if an
invalid comparison string is provided.
* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions
in descending order when passed to `Array.sort()`.
* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions
are equal. Sorts in ascending order if passed to `Array.sort()`.
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
* `diff(v1, v2)`: Returns difference between two versions by the release type
(`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`),
or null if the versions are the same.
### Comparators
* `intersects(comparator)`: Return true if the comparators intersect
### Ranges
* `validRange(range)`: Return the valid range or null if it's not valid
* `satisfies(version, range)`: Return true if the version satisfies the
range.
* `maxSatisfying(versions, range)`: Return the highest version in the list
that satisfies the range, or `null` if none of them do.
* `minSatisfying(versions, range)`: Return the lowest version in the list
that satisfies the range, or `null` if none of them do.
* `minVersion(range)`: Return the lowest version that can possibly match
the given range.
* `gtr(version, range)`: Return `true` if version is greater than all the
versions possible in the range.
* `ltr(version, range)`: Return `true` if version is less than all the
versions possible in the range.
* `outside(version, range, hilo)`: Return true if the version is outside
the bounds of the range in either the high or low direction. The
`hilo` argument must be either the string `'>'` or `'<'`. (This is
the function called by `gtr` and `ltr`.)
* `intersects(range)`: Return true if any of the ranges comparators intersect
Note that, since ranges may be non-contiguous, a version might not be
greater than a range, less than a range, *or* satisfy a range! For
example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9`
until `2.0.0`, so the version `1.2.10` would not be greater than the
range (because `2.0.1` satisfies, which is higher), nor less than the
range (since `1.2.8` satisfies, which is lower), and it also does not
satisfy the range.
If you want to know if a version satisfies or does not satisfy a
range, use the `satisfies(version, range)` function.
### Coercion
* `coerce(version, options)`: Coerces a string to semver if possible
This aims to provide a very forgiving translation of a non-semver string to
semver. It looks for the first digit in a string, and consumes all
remaining characters which satisfy at least a partial semver (e.g., `1`,
`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer
versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All
surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes
`3.4.0`). Only text which lacks digits will fail coercion (`version one`
is not valid). The maximum length for any semver component considered for
coercion is 16 characters; longer components will be ignored
(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any
semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value
components are invalid (`9999999999999999.4.7.4` is likely invalid).
If the `options.rtl` flag is set, then `coerce` will return the right-most
coercible tuple that does not share an ending index with a longer coercible
tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not
`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of
any other overlapping SemVer tuple.
### Clean
* `clean(version)`: Clean a string to be a valid semver if possible
This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges.
ex.
* `s.clean(' = v 2.1.5foo')`: `null`
* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean(' = v 2.1.5-foo')`: `null`
* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean('=v2.1.5')`: `'2.1.5'`
* `s.clean(' =v2.1.5')`: `2.1.5`
* `s.clean(' 2.1.5 ')`: `'2.1.5'`
* `s.clean('~1.0.0')`: `null`

Some files were not shown because too many files have changed in this diff Show More