1
0
mirror of https://github.com/S2-/minifyfromhtml.git synced 2025-08-03 04:10:04 +02:00

add some babel stuff

This commit is contained in:
s2
2018-05-05 15:35:25 +02:00
parent d17c4fe70c
commit e76e795120
604 changed files with 103725 additions and 62 deletions

172
node_modules/@babel/template/README.md generated vendored Normal file
View File

@@ -0,0 +1,172 @@
# @babel/template
> Generate an AST from a string template or template literal.
In computer science, this is known as an implementation of quasiquotes.
## Install
```sh
npm install --save-dev @babel/template
```
## String Usage
```js
import template from "@babel/template";
import generate from "@babel/generator";
import * as t from "@babel/types";
const buildRequire = template(`
var IMPORT_NAME = require(SOURCE);
`);
const ast = buildRequire({
IMPORT_NAME: t.identifier("myModule"),
SOURCE: t.stringLiteral("my-module")
});
console.log(generate(ast).code);
```
```js
const myModule = require("my-module");
```
### `.ast`
If no placeholders are in use and you just want a simple way to parse a
string into an AST, you can use the `.ast` version of the template.
```js
const ast = template.ast(`
var myModule = require("my-module");
`);
```
which will parse and return the AST directly.
## Template Literal Usage
```js
import template from "@babel/template";
import generate from "@babel/generator";
import * as t from "@babel/types";
const fn = template`
var IMPORT_NAME = require('${"my-module"}');
`);
const ast = fn({
IMPORT_NAME: t.identifier("myModule");
});
console.log(generate(ast).code);
```
Note that placeholders can be passed directly as part of the template literal
in order to make things as readable as possible, or they can be passed into
the template function.
### `.ast`
If no placeholders are in use and you just want a simple way to parse a
string into an AST, you can use the `.ast` version of the template.
```js
const name = "my-module";
const mod = "myModule";
const ast = template.ast`
var ${mod} = require("${name}");
`;
```
which will parse and return the AST directly. Note that unlike the string-based
version mentioned earlier, since this is a template literal, it is still
valid to perform replacements using template literal replacements.
## AST results
The `@babel/template` API exposes a few flexible APIs to make it as easy as
possible to create ASTs with an expected structure. Each of these also has
the `.ast` property mentioned above.
### `template`
`template` returns either a single statement, or an array of
statements, depending on the parsed result.
### `template.smart`
This is the same as the default `template` API, returning either a single
node, or an array of nodes, depending on the parsed result.
### `template.statement`
`template.statement("foo;")()` returns a single statement node, and throw
an exception if the result is anything but a single statement.
### `template.statements`
`template.statements("foo;foo;")()` returns an array of statement nodes.
### `template.expression`
`template.expression("foo")()` returns the expression node.
### `template.program`
`template.program("foo;")()` returns the `Program` node for the template.
## API
### `template(code, [opts])`
#### code
Type: `string`
#### options
`@babel/template` accepts all of the options from [babylon](https://github.com/babel/babel/tree/master/packages/babylon), and specifies
some defaults of its own:
* `allowReturnOutsideFunction` is set to `true` by default.
* `allowSuperOutsideMethod` is set to `true` by default.
* `sourceType` is set to `module` by default.
##### placeholderWhitelist
Type: `Set<string>`
Default: `undefined`
A set of placeholder names to automatically accept. Items in this list do
not need to match the given placeholder pattern.
##### placeholderPattern
Type: `RegExp | false`
Default: `/^[_$A-Z0-9]+$/`
A pattern to search for when looking for Identifier and StringLiteral
nodes that should be considered placeholders.
'false' will disable placeholder searching entirely, leaving only the
'placeholderWhitelist' value to find placeholders.
##### preserveComments
Type: `boolean`
Default: `false`
Set this to `true` to preserve any comments from the `code` parameter.
#### Return value
By default `@babel/template` returns a `function` which is invoked with an
optional object of replacements. See the usage section for an example.
When using `.ast`, the AST will be returned directly.
[babylon]: https://github.com/babel/babylon#options

91
node_modules/@babel/template/lib/builder.js generated vendored Normal file
View File

@@ -0,0 +1,91 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = createTemplateBuilder;
var _options = require("./options");
var _string = _interopRequireDefault(require("./string"));
var _literal = _interopRequireDefault(require("./literal"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var NO_PLACEHOLDER = (0, _options.validate)({
placeholderPattern: false
});
function createTemplateBuilder(formatter, defaultOpts) {
var templateFnCache = new WeakMap();
var templateAstCache = new WeakMap();
var cachedOpts = defaultOpts || (0, _options.validate)(null);
return Object.assign(function (tpl) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (typeof tpl === "string") {
if (args.length > 1) throw new Error("Unexpected extra params.");
return extendedTrace((0, _string.default)(formatter, tpl, (0, _options.merge)(cachedOpts, (0, _options.validate)(args[0]))));
} else if (Array.isArray(tpl)) {
var builder = templateFnCache.get(tpl);
if (!builder) {
builder = (0, _literal.default)(formatter, tpl, cachedOpts);
templateFnCache.set(tpl, builder);
}
return extendedTrace(builder(args));
} else if (typeof tpl === "object" && tpl) {
if (args.length > 0) throw new Error("Unexpected extra params.");
return createTemplateBuilder(formatter, (0, _options.merge)(cachedOpts, (0, _options.validate)(tpl)));
}
throw new Error("Unexpected template param " + typeof tpl);
}, {
ast: function ast(tpl) {
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
if (typeof tpl === "string") {
if (args.length > 1) throw new Error("Unexpected extra params.");
return (0, _string.default)(formatter, tpl, (0, _options.merge)((0, _options.merge)(cachedOpts, (0, _options.validate)(args[0])), NO_PLACEHOLDER))();
} else if (Array.isArray(tpl)) {
var builder = templateAstCache.get(tpl);
if (!builder) {
builder = (0, _literal.default)(formatter, tpl, (0, _options.merge)(cachedOpts, NO_PLACEHOLDER));
templateAstCache.set(tpl, builder);
}
return builder(args)();
}
throw new Error("Unexpected template param " + typeof tpl);
}
});
}
function extendedTrace(fn) {
var rootStack = "";
try {
throw new Error();
} catch (error) {
if (error.stack) {
rootStack = error.stack.split("\n").slice(3).join("\n");
}
}
return function (arg) {
try {
return fn(arg);
} catch (err) {
err.stack += "\n =============\n" + rootStack;
throw err;
}
};
}

75
node_modules/@babel/template/lib/formatters.js generated vendored Normal file
View File

@@ -0,0 +1,75 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.program = exports.expression = exports.statement = exports.statements = exports.smart = void 0;
function makeStatementFormatter(fn) {
return {
code: function code(str) {
return "/* @babel/template */;\n" + str;
},
validate: function validate() {},
unwrap: function unwrap(ast) {
return fn(ast.program.body.slice(1));
}
};
}
var smart = makeStatementFormatter(function (body) {
if (body.length > 1) {
return body;
} else {
return body[0];
}
});
exports.smart = smart;
var statements = makeStatementFormatter(function (body) {
return body;
});
exports.statements = statements;
var statement = makeStatementFormatter(function (body) {
if (body.length === 0) {
throw new Error("Found nothing to return.");
}
if (body.length > 1) {
throw new Error("Found multiple statements but wanted one");
}
return body[0];
});
exports.statement = statement;
var expression = {
code: function code(str) {
return "(\n" + str + "\n)";
},
validate: function validate(_ref) {
var program = _ref.program;
if (program.body.length > 1) {
throw new Error("Found multiple statements but wanted one");
}
var expression = program.body[0].expression;
if (expression.start === 0) {
throw new Error("Parse result included parens.");
}
},
unwrap: function unwrap(ast) {
return ast.program.body[0].expression;
}
};
exports.expression = expression;
var program = {
code: function code(str) {
return str;
},
validate: function validate() {},
unwrap: function unwrap(ast) {
return ast.program;
}
};
exports.program = program;

36
node_modules/@babel/template/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.program = exports.expression = exports.statements = exports.statement = exports.smart = void 0;
var formatters = _interopRequireWildcard(require("./formatters"));
var _builder = _interopRequireDefault(require("./builder"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
var smart = (0, _builder.default)(formatters.smart);
exports.smart = smart;
var statement = (0, _builder.default)(formatters.statement);
exports.statement = statement;
var statements = (0, _builder.default)(formatters.statements);
exports.statements = statements;
var expression = (0, _builder.default)(formatters.expression);
exports.expression = expression;
var program = (0, _builder.default)(formatters.program);
exports.program = program;
var _default = Object.assign(smart.bind(undefined), {
smart: smart,
statement: statement,
statements: statements,
expression: expression,
program: program,
ast: smart.ast
});
exports.default = _default;

83
node_modules/@babel/template/lib/literal.js generated vendored Normal file
View File

@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = literalTemplate;
var _options = require("./options");
var _parse = _interopRequireDefault(require("./parse"));
var _populate = _interopRequireDefault(require("./populate"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function literalTemplate(formatter, tpl, opts) {
var _buildLiteralData = buildLiteralData(formatter, tpl, opts),
metadata = _buildLiteralData.metadata,
names = _buildLiteralData.names;
return function (arg) {
var defaultReplacements = arg.reduce(function (acc, replacement, i) {
acc[names[i]] = replacement;
return acc;
}, {});
return function (arg) {
var replacements = (0, _options.normalizeReplacements)(arg);
if (replacements) {
Object.keys(replacements).forEach(function (key) {
if (Object.prototype.hasOwnProperty.call(defaultReplacements, key)) {
throw new Error("Unexpected replacement overlap.");
}
});
}
return formatter.unwrap((0, _populate.default)(metadata, replacements ? Object.assign(replacements, defaultReplacements) : defaultReplacements));
};
};
}
function buildLiteralData(formatter, tpl, opts) {
var names;
var nameSet;
var metadata;
var prefix = "";
do {
prefix += "$";
var result = buildTemplateCode(tpl, prefix);
names = result.names;
nameSet = new Set(names);
metadata = (0, _parse.default)(formatter, formatter.code(result.code), {
parser: opts.parser,
placeholderWhitelist: new Set(result.names.concat(opts.placeholderWhitelist ? Array.from(opts.placeholderWhitelist) : [])),
placeholderPattern: opts.placeholderPattern,
preserveComments: opts.preserveComments
});
} while (metadata.placeholders.some(function (placeholder) {
return placeholder.isDuplicate && nameSet.has(placeholder.name);
}));
return {
metadata: metadata,
names: names
};
}
function buildTemplateCode(tpl, prefix) {
var names = [];
var code = tpl[0];
for (var i = 1; i < tpl.length; i++) {
var value = "" + prefix + (i - 1);
names.push(value);
code += value + tpl[i];
}
return {
names: names,
code: code
};
}

69
node_modules/@babel/template/lib/options.js generated vendored Normal file
View File

@@ -0,0 +1,69 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.merge = merge;
exports.validate = validate;
exports.normalizeReplacements = normalizeReplacements;
function _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function merge(a, b) {
var _b$placeholderWhiteli = b.placeholderWhitelist,
placeholderWhitelist = _b$placeholderWhiteli === void 0 ? a.placeholderWhitelist : _b$placeholderWhiteli,
_b$placeholderPattern = b.placeholderPattern,
placeholderPattern = _b$placeholderPattern === void 0 ? a.placeholderPattern : _b$placeholderPattern,
_b$preserveComments = b.preserveComments,
preserveComments = _b$preserveComments === void 0 ? a.preserveComments : _b$preserveComments;
return {
parser: Object.assign({}, a.parser, b.parser),
placeholderWhitelist: placeholderWhitelist,
placeholderPattern: placeholderPattern,
preserveComments: preserveComments
};
}
function validate(opts) {
if (opts != null && typeof opts !== "object") {
throw new Error("Unknown template options.");
}
var _ref = opts || {},
placeholderWhitelist = _ref.placeholderWhitelist,
placeholderPattern = _ref.placeholderPattern,
preserveComments = _ref.preserveComments,
parser = _objectWithoutProperties(_ref, ["placeholderWhitelist", "placeholderPattern", "preserveComments"]);
if (placeholderWhitelist != null && !(placeholderWhitelist instanceof Set)) {
throw new Error("'.placeholderWhitelist' must be a Set, null, or undefined");
}
if (placeholderPattern != null && !(placeholderPattern instanceof RegExp) && placeholderPattern !== false) {
throw new Error("'.placeholderPattern' must be a RegExp, false, null, or undefined");
}
if (preserveComments != null && typeof preserveComments !== "boolean") {
throw new Error("'.preserveComments' must be a boolean, null, or undefined");
}
return {
parser: parser,
placeholderWhitelist: placeholderWhitelist || undefined,
placeholderPattern: placeholderPattern == null ? undefined : placeholderPattern,
preserveComments: preserveComments == null ? false : preserveComments
};
}
function normalizeReplacements(replacements) {
if (Array.isArray(replacements)) {
return replacements.reduce(function (acc, replacement, i) {
acc["$" + i] = replacement;
return acc;
}, {});
} else if (typeof replacements === "object" || replacements == null) {
return replacements || undefined;
}
throw new Error("Template replacements must be an array, object, null, or undefined");
}

156
node_modules/@babel/template/lib/parse.js generated vendored Normal file
View File

@@ -0,0 +1,156 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = parseAndBuildMetadata;
function t() {
var data = _interopRequireWildcard(require("@babel/types"));
t = function t() {
return data;
};
return data;
}
function _babylon() {
var data = require("babylon");
_babylon = function _babylon() {
return data;
};
return data;
}
function _codeFrame() {
var data = require("@babel/code-frame");
_codeFrame = function _codeFrame() {
return data;
};
return data;
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
var PATTERN = /^[_$A-Z0-9]+$/;
function parseAndBuildMetadata(formatter, code, opts) {
var ast = parseWithCodeFrame(code, opts.parser);
var placeholderWhitelist = opts.placeholderWhitelist,
_opts$placeholderPatt = opts.placeholderPattern,
placeholderPattern = _opts$placeholderPatt === void 0 ? PATTERN : _opts$placeholderPatt,
preserveComments = opts.preserveComments;
t().removePropertiesDeep(ast, {
preserveComments: preserveComments
});
formatter.validate(ast);
var placeholders = [];
var placeholderNames = new Set();
t().traverse(ast, placeholderVisitorHandler, {
placeholders: placeholders,
placeholderNames: placeholderNames,
placeholderWhitelist: placeholderWhitelist,
placeholderPattern: placeholderPattern
});
return {
ast: ast,
placeholders: placeholders,
placeholderNames: placeholderNames
};
}
function placeholderVisitorHandler(node, ancestors, state) {
var name;
if (t().isIdentifier(node) || t().isJSXIdentifier(node)) {
name = node.name;
} else if (t().isStringLiteral(node)) {
name = node.value;
} else {
return;
}
if ((!state.placeholderPattern || !state.placeholderPattern.test(name)) && (!state.placeholderWhitelist || !state.placeholderWhitelist.has(name))) {
return;
}
ancestors = ancestors.slice();
var _ancestors = ancestors[ancestors.length - 1],
parent = _ancestors.node,
key = _ancestors.key;
var type;
if (t().isStringLiteral(node)) {
type = "string";
} else if (t().isNewExpression(parent) && key === "arguments" || t().isCallExpression(parent) && key === "arguments" || t().isFunction(parent) && key === "params") {
type = "param";
} else if (t().isExpressionStatement(parent)) {
type = "statement";
ancestors = ancestors.slice(0, -1);
} else {
type = "other";
}
state.placeholders.push({
name: name,
type: type,
resolve: function resolve(ast) {
return resolveAncestors(ast, ancestors);
},
isDuplicate: state.placeholderNames.has(name)
});
state.placeholderNames.add(name);
}
function resolveAncestors(ast, ancestors) {
var parent = ast;
for (var i = 0; i < ancestors.length - 1; i++) {
var _ancestors$i = ancestors[i],
_key = _ancestors$i.key,
_index = _ancestors$i.index;
if (_index === undefined) {
parent = parent[_key];
} else {
parent = parent[_key][_index];
}
}
var _ancestors2 = ancestors[ancestors.length - 1],
key = _ancestors2.key,
index = _ancestors2.index;
return {
parent: parent,
key: key,
index: index
};
}
function parseWithCodeFrame(code, parserOpts) {
parserOpts = Object.assign({
allowReturnOutsideFunction: true,
allowSuperOutsideMethod: true,
sourceType: "module"
}, parserOpts);
try {
return (0, _babylon().parse)(code, parserOpts);
} catch (err) {
var loc = err.loc;
if (loc) {
err.message += "\n" + (0, _codeFrame().codeFrameColumns)(code, {
start: loc
});
err.code = "BABEL_TEMPLATE_PARSE_ERROR";
}
throw err;
}
}

131
node_modules/@babel/template/lib/populate.js generated vendored Normal file
View File

@@ -0,0 +1,131 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = populatePlaceholders;
function t() {
var data = _interopRequireWildcard(require("@babel/types"));
t = function t() {
return data;
};
return data;
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function populatePlaceholders(metadata, replacements) {
var ast = t().cloneNode(metadata.ast);
if (replacements) {
metadata.placeholders.forEach(function (placeholder) {
if (!Object.prototype.hasOwnProperty.call(replacements, placeholder.name)) {
var placeholderName = placeholder.name;
throw new Error("Error: No substitution given for \"" + placeholderName + "\". If this is not meant to be a\n placeholder you may want to consider passing one of the following options to @babel/template:\n - { placeholderPattern: false, placeholderWhitelist: new Set(['" + placeholderName + "'])}\n - { placeholderPattern: /^" + placeholderName + "$/ }");
}
});
Object.keys(replacements).forEach(function (key) {
if (!metadata.placeholderNames.has(key)) {
throw new Error("Unknown substitution \"" + key + "\" given");
}
});
}
metadata.placeholders.slice().reverse().forEach(function (placeholder) {
try {
applyReplacement(placeholder, ast, replacements && replacements[placeholder.name] || null);
} catch (e) {
e.message = "@babel/template placeholder \"" + placeholder.name + "\": " + e.message;
throw e;
}
});
return ast;
}
function applyReplacement(placeholder, ast, replacement) {
if (placeholder.isDuplicate) {
if (Array.isArray(replacement)) {
replacement = replacement.map(function (node) {
return t().cloneNode(node);
});
} else if (typeof replacement === "object") {
replacement = t().cloneNode(replacement);
}
}
var _placeholder$resolve = placeholder.resolve(ast),
parent = _placeholder$resolve.parent,
key = _placeholder$resolve.key,
index = _placeholder$resolve.index;
if (placeholder.type === "string") {
if (typeof replacement === "string") {
replacement = t().stringLiteral(replacement);
}
if (!replacement || !t().isStringLiteral(replacement)) {
throw new Error("Expected string substitution");
}
} else if (placeholder.type === "statement") {
if (index === undefined) {
if (!replacement) {
replacement = t().emptyStatement();
} else if (Array.isArray(replacement)) {
replacement = t().blockStatement(replacement);
} else if (typeof replacement === "string") {
replacement = t().expressionStatement(t().identifier(replacement));
} else if (!t().isStatement(replacement)) {
replacement = t().expressionStatement(replacement);
}
} else {
if (replacement && !Array.isArray(replacement)) {
if (typeof replacement === "string") {
replacement = t().identifier(replacement);
}
if (!t().isStatement(replacement)) {
replacement = t().expressionStatement(replacement);
}
}
}
} else if (placeholder.type === "param") {
if (typeof replacement === "string") {
replacement = t().identifier(replacement);
}
if (index === undefined) throw new Error("Assertion failure.");
} else {
if (typeof replacement === "string") {
replacement = t().identifier(replacement);
}
if (Array.isArray(replacement)) {
throw new Error("Cannot replace single expression with an array.");
}
}
if (index === undefined) {
t().validate(parent, key, replacement);
parent[key] = replacement;
} else {
var items = parent[key].slice();
if (placeholder.type === "statement" || placeholder.type === "param") {
if (replacement == null) {
items.splice(index, 1);
} else if (Array.isArray(replacement)) {
items.splice.apply(items, [index, 1].concat(replacement));
} else {
items[index] = replacement;
}
} else {
items[index] = replacement;
}
t().validate(parent, key, items);
parent[key] = items;
}
}

24
node_modules/@babel/template/lib/string.js generated vendored Normal file
View File

@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = stringTemplate;
var _options = require("./options");
var _parse = _interopRequireDefault(require("./parse"));
var _populate = _interopRequireDefault(require("./populate"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function stringTemplate(formatter, code, opts) {
code = formatter.code(code);
var metadata;
return function (arg) {
var replacements = (0, _options.normalizeReplacements)(arg);
if (!metadata) metadata = (0, _parse.default)(formatter, code, opts);
return formatter.unwrap((0, _populate.default)(metadata, replacements));
};
}

1
node_modules/@babel/template/node_modules/.bin/babylon generated vendored Symbolic link
View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,19 @@
Copyright (C) 2012-2014 by various contributors (see AUTHORS)
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

@@ -0,0 +1,167 @@
<p align="center">
<img alt="babylon" src="https://raw.githubusercontent.com/babel/logo/master/babylon.png" width="700">
</p>
<p align="center">
Babylon is a JavaScript parser used in <a href="https://github.com/babel/babel">Babel</a>.
</p>
- The latest ECMAScript version enabled by default (ES2017).
- Comment attachment.
- Support for JSX, Flow, Typescript.
- Support for experimental language proposals (accepting PRs for anything at least [stage-0](https://github.com/tc39/proposals/blob/master/stage-0-proposals.md)).
## Credits
Heavily based on [acorn](https://github.com/marijnh/acorn) and [acorn-jsx](https://github.com/RReverser/acorn-jsx),
thanks to the awesome work of [@RReverser](https://github.com/RReverser) and [@marijnh](https://github.com/marijnh).
## API
### `babylon.parse(code, [options])`
### `babylon.parseExpression(code, [options])`
`parse()` parses the provided `code` as an entire ECMAScript program, while
`parseExpression()` tries to parse a single Expression with performance in
mind. When in doubt, use `.parse()`.
### Options
- **allowImportExportEverywhere**: By default, `import` and `export`
declarations can only appear at a program's top level. Setting this
option to `true` allows them anywhere where a statement is allowed.
- **allowAwaitOutsideFunction**: By default, `await` use is not allowed
outside of an async function. Set this to `true` to accept such
code.
- **allowReturnOutsideFunction**: By default, a return statement at
the top level raises an error. Set this to `true` to accept such
code.
- **allowSuperOutsideMethod**: TODO
- **sourceType**: Indicate the mode the code should be parsed in. Can be
one of `"script"`, `"module"`, or `"unambiguous"`. Defaults to `"script"`. `"unambiguous"` will make Babylon attempt to _guess_, based on the presence of ES6 `import` or `export` statements. Files with ES6 `import`s and `export`s are considered `"module"` and are otherwise `"script"`.
- **sourceFilename**: Correlate output AST nodes with their source filename. Useful when generating code and source maps from the ASTs of multiple input files.
- **startLine**: By default, the first line of code parsed is treated as line 1. You can provide a line number to alternatively start with. Useful for integration with other source tools.
- **plugins**: Array containing the plugins that you want to enable.
- **strictMode**: TODO
- **ranges**: Adds a `ranges` property to each node: `[node.start, node.end]`
- **tokens**: Adds all parsed tokens to a `tokens` property on the `File` node
### Output
Babylon generates AST according to [Babel AST format][].
It is based on [ESTree spec][] with the following deviations:
> There is now an `estree` plugin which reverts these deviations
- [Literal][] token is replaced with [StringLiteral][], [NumericLiteral][], [BooleanLiteral][], [NullLiteral][], [RegExpLiteral][]
- [Property][] token is replaced with [ObjectProperty][] and [ObjectMethod][]
- [MethodDefinition][] is replaced with [ClassMethod][]
- [Program][] and [BlockStatement][] contain additional `directives` field with [Directive][] and [DirectiveLiteral][]
- [ClassMethod][], [ObjectProperty][], and [ObjectMethod][] value property's properties in [FunctionExpression][] is coerced/brought into the main method node.
AST for JSX code is based on [Facebook JSX AST][].
[Babel AST format]: https://github.com/babel/babylon/blob/master/ast/spec.md
[ESTree spec]: https://github.com/estree/estree
[Literal]: https://github.com/estree/estree/blob/master/es5.md#literal
[Property]: https://github.com/estree/estree/blob/master/es5.md#property
[MethodDefinition]: https://github.com/estree/estree/blob/master/es2015.md#methoddefinition
[StringLiteral]: https://github.com/babel/babel/tree/master/packages/babylon/ast/spec.md#stringliteral
[NumericLiteral]: https://github.com/babel/babel/tree/master/packages/babylon/ast/spec.md#numericliteral
[BooleanLiteral]: https://github.com/babel/babel/tree/master/packages/babylon/ast/spec.md#booleanliteral
[NullLiteral]: https://github.com/babel/babel/tree/master/packages/babylon/ast/spec.md#nullliteral
[RegExpLiteral]: https://github.com/babel/babel/tree/master/packages/babylon/ast/spec.md#regexpliteral
[ObjectProperty]: https://github.com/babel/babel/tree/master/packages/babylon/ast/spec.md#objectproperty
[ObjectMethod]: https://github.com/babel/babel/tree/master/packages/babylon/ast/spec.md#objectmethod
[ClassMethod]: https://github.com/babel/babel/tree/master/packages/babylon/ast/spec.md#classmethod
[Program]: https://github.com/babel/babel/tree/master/packages/babylon/ast/spec.md#programs
[BlockStatement]: https://github.com/babel/babel/tree/master/packages/babylon/ast/spec.md#blockstatement
[Directive]: https://github.com/babel/babel/tree/master/packages/babylon/ast/spec.md#directive
[DirectiveLiteral]: https://github.com/babel/babel/tree/master/packages/babylon/ast/spec.md#directiveliteral
[FunctionExpression]: https://github.com/babel/babel/tree/master/packages/babylon/ast/spec.md#functionexpression
[Facebook JSX AST]: https://github.com/facebook/jsx/blob/master/AST.md
### Semver
Babylon follows semver in most situations. The only thing to note is that some spec-compliancy bug fixes may be released under patch versions.
For example: We push a fix to early error on something like [#107](https://github.com/babel/babylon/pull/107) - multiple default exports per file. That would be considered a bug fix even though it would cause a build to fail.
### Example
```javascript
require("babylon").parse("code", {
// parse in strict mode and allow module declarations
sourceType: "module",
plugins: [
// enable jsx and flow syntax
"jsx",
"flow"
]
});
```
### Plugins
| Name | Code Example |
|------|--------------|
| `estree` ([repo](https://github.com/estree/estree)) | n/a |
| `jsx` ([repo](https://facebook.github.io/jsx/)) | `<a attr="b">{s}</a>` |
| `flow` ([repo](https://github.com/facebook/flow)) | `var a: string = "";` |
| `flowComments` ([docs](https://flow.org/en/docs/types/comments/)) | `/*:: type Foo = {...}; */` |
| `typescript` ([repo](https://github.com/Microsoft/TypeScript)) | `var a: string = "";` |
| `doExpressions` | `var a = do { if (true) { 'hi'; } };` |
| `objectRestSpread` ([proposal](https://github.com/tc39/proposal-object-rest-spread)) | `var a = { b, ...c };` |
| `decorators` (Stage 1) and `decorators2` (Stage 2 [proposal](https://github.com/tc39/proposal-decorators)) | `@a class A {}` |
| `classProperties` ([proposal](https://github.com/tc39/proposal-class-public-fields)) | `class A { b = 1; }` |
| `classPrivateProperties` ([proposal](https://github.com/tc39/proposal-private-fields)) | `class A { #b = 1; }` |
| `classPrivateMethods` ([proposal](https://github.com/tc39/proposal-private-methods)) | `class A { #c() {} }` |
| `exportDefaultFrom` ([proposal](https://github.com/leebyron/ecmascript-export-default-from)) | `export v from "mod"` |
| `exportNamespaceFrom` ([proposal](https://github.com/leebyron/ecmascript-export-ns-from)) | `export * as ns from "mod"` |
| `asyncGenerators` ([proposal](https://github.com/tc39/proposal-async-iteration)) | `async function*() {}`, `for await (let a of b) {}` |
| `functionBind` ([proposal](https://github.com/zenparsing/es-function-bind)) | `a::b`, `::console.log` |
| `functionSent` | `function.sent` |
| `dynamicImport` ([proposal](https://github.com/tc39/proposal-dynamic-import)) | `import('./guy').then(a)` |
| `numericSeparator` ([proposal](https://github.com/samuelgoto/proposal-numeric-separator)) | `1_000_000` |
| `optionalChaining` ([proposal](https://github.com/tc39/proposal-optional-chaining)) | `a?.b` |
| `importMeta` ([proposal](https://github.com/tc39/proposal-import-meta)) | `import.meta.url` |
| `bigInt` ([proposal](https://github.com/tc39/proposal-bigint)) | `100n` |
| `optionalCatchBinding` ([proposal](https://github.com/babel/proposals/issues/7)) | `try {throw 0;} catch{do();}` |
| `throwExpressions` ([proposal](https://github.com/babel/proposals/issues/23)) | `() => throw new Error("")` |
| `pipelineOperator` ([proposal](https://github.com/babel/proposals/issues/29)) | `a \|> b` |
| `nullishCoalescingOperator` ([proposal](https://github.com/babel/proposals/issues/14)) | `a ?? b` |
### FAQ
#### Will Babylon support a plugin system?
Previous issues: [#1351](https://github.com/babel/babel/issues/1351), [#6694](https://github.com/babel/babel/issues/6694).
We currently aren't willing to commit to supporting the API for plugins or the resulting ecosystem (there is already enough work maintaining Babel's own plugin system). It's not clear how to make that API effective, and it would limit out ability to refactor and optimize the codebase.
Our current recommendation for those that want to create their own custom syntax is for users to fork Babylon.
To consume your custom parser, you can add to your `.babelrc` via its npm package name or require it if using JavaScript,
```json
{
"parserOpts": {
"parser": "custom-fork-of-babylon-on-npm-here"
}
}
```

View File

@@ -0,0 +1,16 @@
#!/usr/bin/env node
/* eslint no-var: 0 */
var babylon = require("..");
var fs = require("fs");
var filename = process.argv[2];
if (!filename) {
console.error("no filename specified");
process.exit(0);
}
var file = fs.readFileSync(filename, "utf8");
var ast = babylon.parse(file);
console.log(JSON.stringify(ast, null, " "));

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,67 @@
{
"_from": "babylon@7.0.0-beta.46",
"_id": "babylon@7.0.0-beta.46",
"_inBundle": false,
"_integrity": "sha512-WFJlg2WatdkXRFMpk7BN/Uzzkjkcjk+WaqnrSCpay+RYl4ypW9ZetZyT9kNt22IH/BQNst3M6PaaBn9IXsUNrg==",
"_location": "/@babel/template/babylon",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "babylon@7.0.0-beta.46",
"name": "babylon",
"escapedName": "babylon",
"rawSpec": "7.0.0-beta.46",
"saveSpec": null,
"fetchSpec": "7.0.0-beta.46"
},
"_requiredBy": [
"/@babel/template"
],
"_resolved": "https://registry.npmjs.org/babylon/-/babylon-7.0.0-beta.46.tgz",
"_shasum": "b6ddaba81bbb130313932757ff9c195d527088b6",
"_spec": "babylon@7.0.0-beta.46",
"_where": "/home/s2/Documents/Code/minifyfromhtml/node_modules/@babel/template",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"bin": {
"babylon": "./bin/babylon.js"
},
"bundleDependencies": false,
"deprecated": false,
"description": "A JavaScript parser",
"devDependencies": {
"@babel/helper-fixtures": "7.0.0-beta.46",
"charcodes": "0.1.0",
"unicode-10.0.0": "^0.7.4"
},
"engines": {
"node": ">=6.0.0"
},
"files": [
"bin",
"lib"
],
"homepage": "https://babeljs.io/",
"keywords": [
"babel",
"javascript",
"parser",
"tc39",
"ecmascript",
"babylon"
],
"license": "MIT",
"main": "lib/index.js",
"name": "babylon",
"publishConfig": {
"tag": "next"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babylon"
},
"version": "7.0.0-beta.46"
}

50
node_modules/@babel/template/package.json generated vendored Normal file
View File

@@ -0,0 +1,50 @@
{
"_from": "@babel/template@7.0.0-beta.46",
"_id": "@babel/template@7.0.0-beta.46",
"_inBundle": false,
"_integrity": "sha512-3/qi4m0l6G/vZbEwtqfzJk73mYtuE7nvAO1zT3/ZrTAHy4sHf2vaF9Eh1w+Tau263Yrkh0bjVQPb9zw6G+GeMQ==",
"_location": "/@babel/template",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@babel/template@7.0.0-beta.46",
"name": "@babel/template",
"escapedName": "@babel%2ftemplate",
"scope": "@babel",
"rawSpec": "7.0.0-beta.46",
"saveSpec": null,
"fetchSpec": "7.0.0-beta.46"
},
"_requiredBy": [
"/@babel/core",
"/@babel/helper-function-name",
"/@babel/helpers"
],
"_resolved": "https://registry.npmjs.org/@babel/template/-/template-7.0.0-beta.46.tgz",
"_shasum": "8b23982411d5b5dbfa479437bfe414adb1411bb9",
"_spec": "@babel/template@7.0.0-beta.46",
"_where": "/home/s2/Documents/Code/minifyfromhtml/node_modules/@babel/core",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"@babel/code-frame": "7.0.0-beta.46",
"@babel/types": "7.0.0-beta.46",
"babylon": "7.0.0-beta.46",
"lodash": "^4.2.0"
},
"deprecated": false,
"description": "Generate an AST from a string template.",
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/template",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-template"
},
"version": "7.0.0-beta.46"
}