I'm extremely stupid and didn't commit as I go. To anyone reading this
I'm extremely sorry. A lot of these changes are very broad and I plan on
releasing Babel 6.0.0 today live on stage at Ember Camp London so I'm
afraid I couldn't wait. If you're ever in London I'll buy you a beer
(or assorted beverage!) to make up for it, also I'll kiss your feet and
give you a back massage, maybe.
This commit is contained in:
Sebastian McKenzie 2015-10-29 17:51:24 +00:00
parent 3974dd762d
commit ae7d5367f1
1501 changed files with 16477 additions and 19786 deletions

14
.flowconfig Normal file
View File

@ -0,0 +1,14 @@
[ignore]
[include]
[libs]
lib/file.js
lib/parser.js
lib/types.js
[options]
strip_root=true
[version]
0.16.0

View File

@ -20,10 +20,10 @@ watch: clean
lint: lint:
node node_modules/.bin/eslint packages/*/src node node_modules/.bin/eslint packages/*/src
#flow check
clean: test-clean clean: test-clean
rm -rf coverage rm -rf coverage
rm -rf packages/*/lib packages/babel-core/templates.json
test-clean: test-clean:
rm -rf packages/*/test/tmp rm -rf packages/*/test/tmp
@ -45,7 +45,7 @@ publish:
make test make test
node scripts/publish.js node scripts/publish.js
make clean make clean
./scripts/build-website.sh #./scripts/build-website.sh
bootstrap: bootstrap:
npm install npm install

View File

@ -1 +1 @@
5.8.23 5.8.33

View File

@ -0,0 +1,9 @@
# Compiler assumptions
Babel and it's associated official transforms make some assumptions about your code. These
assumptions are only made as they're either **impossible** to take into consideration or
are extremely exotic.
- `undefined`, `NaN` and `Infinity` have not been externally redefined.
- Built-in objects such as `Object`, `Array`, `String`, `Number`, `Boolean` etc have not been redefined.
- Standard methods on built-ins have not been redefined in a way that breaks the original contract.

View File

View File

@ -5,9 +5,10 @@
"babel": "5.8.21", "babel": "5.8.21",
"babel-eslint": "^4.0.6", "babel-eslint": "^4.0.6",
"babel-plugin-flow-comments": "^1.0.9", "babel-plugin-flow-comments": "^1.0.9",
"browserify": "^11.0.0", "browserify": "^11.2.0",
"bundle-collapser": "^1.2.1",
"chai": "^2.2.0", "chai": "^2.2.0",
"chalk": "^1.1.0", "derequire": "^2.0.2",
"es5-shim": "^4.1.7", "es5-shim": "^4.1.7",
"eslint": "^1.1.0", "eslint": "^1.1.0",
"fs-readdir-recursive": "^0.1.2", "fs-readdir-recursive": "^0.1.2",
@ -81,7 +82,8 @@
"no-process-exit": 0, "no-process-exit": 0,
"camelcase": 0, "camelcase": 0,
"no-console": 0, "no-console": 0,
"no-constant-condition": 0 "no-constant-condition": 0,
"no-inner-declarations": 0
}, },
"env": { "env": {
"node": true "node": true

View File

@ -1,88 +1,3 @@
# Woah, what's going on here? # Woah, what's going on here?
A monorepo, muhahahahahaha. See the [monorepo design doc](/doc/design/monorepo.md) for reasoning. Here's an explanation for each package listed: A monorepo, muhahahahahaha. See the [monorepo design doc](/doc/design/monorepo.md) for reasoning.
## `babylon`
## `babel-core`
#### `babel-cli`
#### `babel-types`
#### `babel-code-frame`
#### `babel-messages`
#### `babel-polyfill`
#### `babel-runtime`
#### `babel-traverse`
#### `babel-plugin-*`
- `babel-plugin-auxiliary-comments`
- `babel-plugin-external-helpers`
- `babel-plugin-transform-async-functions`
- `babel-plugin-transform-async-to-bluebird-coroutines`
- `babel-plugin-transform-async-to-generator`
- `babel-plugin-transform-class-properties`
- `babel-plugin-transform-comprehensions`
- `babel-plugin-transform-constant-folding`
- `babel-plugin-transform-dead-code-elimination`
- `babel-plugin-transform-decorators`
- `babel-plugin-transform-do-expressions`
- `babel-plugin-transform-es2015-arrow-functions`
- `babel-plugin-transform-es2015-block-scoped-functions`
- `babel-plugin-transform-es2015-block-scoping`
- `babel-plugin-transform-es2015-classes`
- `babel-plugin-transform-es2015-computed-properties`
- `babel-plugin-transform-es2015-constants`
- `babel-plugin-transform-es2015-destructuring`
- `babel-plugin-transform-es2015-for-of`
- `babel-plugin-transform-es2015-function-name`
- `babel-plugin-transform-es2015-literals`
- `babel-plugin-transform-es2015-modules-amd`
- `babel-plugin-transform-es2015-modules-commonjs`
- `babel-plugin-transform-es2015-modules-systemjs`
- `babel-plugin-transform-es2015-modules-umd`
- `babel-plugin-transform-es2015-object-super`
- `babel-plugin-transform-es2015-parameters`
- `babel-plugin-transform-es2015-shorthand-properties`
- `babel-plugin-transform-es2015-spread`
- `babel-plugin-transform-es2015-sticky-regex`
- `babel-plugin-transform-es2015-tail-call`
- `babel-plugin-transform-es2015-template-literals`
- `babel-plugin-transform-es2015-unicode-regex`
- `babel-plugin-transform-es3-member-expression-literals`
- `babel-plugin-transform-es3-property-literals`
- `babel-plugin-transform-es5-property-mutators`
- `babel-plugin-transform-eval`
- `babel-plugin-transform-exponentiation-operator`
- `babel-plugin-transform-export-extensions`
- `babel-plugin-transform-flow-strip-types`
- `babel-plugin-transform-function-bind`
- `babel-plugin-transform-inline-environment-variables`
- `babel-plugin-transform-jscript`
- `babel-plugin-transform-member-expression-literals`
- `babel-plugin-transform-merge-sibling-variables`
- `babel-plugin-transform-minify-booleans`
- `babel-plugin-transform-node-env-inline`
- `babel-plugin-transform-object-assign`
- `babel-plugin-transform-object-rest-spread`
- `babel-plugin-transform-object-set-prototype-of-to-assign`
- `babel-plugin-transform-property-literals`
- `babel-plugin-transform-proto-to-assign`
- `babel-plugin-transform-react-compat-jsx`
- `babel-plugin-transform-react-constant-elements`
- `babel-plugin-transform-react-display-name`
- `babel-plugin-transform-react-inline-elements`
- `babel-plugin-transform-react-jsx`
- `babel-plugin-transform-remove-console`
- `babel-plugin-transform-remove-debugger`
- `babel-plugin-transform-runtime`
- `babel-plugin-transform-simplify-comparison-operators`
- `babel-plugin-transform-trailing-function-commas`
- `babel-plugin-transform-undeclared-variables-check`
- `babel-plugin-transform-undefined-to-void`

View File

@ -1 +1 @@
module.exports = require("babel-core"); throw new Error("Use the `babel-core` package not `babel`.");

View File

@ -1,6 +1,6 @@
{ {
"name": "babel", "name": "babel-cli",
"version": "5.8.23", "version": "5.10.32",
"description": "Turn ES6 code into readable vanilla ES5 with source maps", "description": "Turn ES6 code into readable vanilla ES5 with source maps",
"author": "Sebastian McKenzie <sebmck@gmail.com>", "author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/", "homepage": "https://babeljs.io/",
@ -8,10 +8,10 @@
"repository": "babel/babel", "repository": "babel/babel",
"preferGlobal": true, "preferGlobal": true,
"dependencies": { "dependencies": {
"babel-core": "^5.6.21", "babel-core": "^5.10.32",
"babel-polyfill": "^5.0.0", "babel-polyfill": "^5.10.32",
"chokidar": "^1.0.0", "chokidar": "^1.0.0",
"commander": "^2.6.0", "commander": "^2.8.1",
"convert-source-map": "^1.1.0", "convert-source-map": "^1.1.0",
"fs-readdir-recursive": "^0.1.0", "fs-readdir-recursive": "^0.1.0",
"glob": "^5.0.5", "glob": "^5.0.5",
@ -20,13 +20,13 @@
"path-exists": "^1.0.0", "path-exists": "^1.0.0",
"path-is-absolute": "^1.0.0", "path-is-absolute": "^1.0.0",
"slash": "^1.0.0", "slash": "^1.0.0",
"source-map": "^0.4.0", "source-map": "^0.5.0",
"v8flags": "^2.0.10" "v8flags": "^2.0.10",
"babel-runtime": "^5.10.32"
}, },
"bin": { "bin": {
"babel": "./bin/babel.js", "babel": "./bin/babel.js",
"babel-node": "./bin/babel-node.js", "babel-node": "./bin/babel-node.js",
"babel-external-helpers": "./bin/babel-external-helpers.js", "babel-external-helpers": "./bin/babel-external-helpers.js"
"babel-plugin": "./bin/babel-plugin.js"
} }
} }

View File

@ -15,10 +15,11 @@ let program = new commander.Command("babel-node");
program.option("-e, --eval [script]", "Evaluate script"); program.option("-e, --eval [script]", "Evaluate script");
program.option("-p, --print [code]", "Evaluate script and print result"); program.option("-p, --print [code]", "Evaluate script and print result");
program.option("-i, --ignore [regex]", "Ignore all files that match this regex when using the require hook"); program.option("-o, --only [globs]", "");
program.option("-i, --ignore [globs]", "");
program.option("-x, --extensions [extensions]", "List of extensions to hook into [.es6,.js,.es,.jsx]"); program.option("-x, --extensions [extensions]", "List of extensions to hook into [.es6,.js,.es,.jsx]");
program.option("-w, --plugins [string]", "TODO", util.list); program.option("-w, --plugins [string]", "", util.list);
program.option("-b, --presets [string]", "TODO", util.list); program.option("-b, --presets [string]", "", util.list);
let pkg = require("../package.json"); let pkg = require("../package.json");
program.version(pkg.version); program.version(pkg.version);
@ -28,24 +29,24 @@ program.parse(process.argv);
// //
register({ register({
extensions: program.extensions, extensions: program.extensions,
optional: program.optional, ignore: program.ignore,
ignore: program.ignore, only: program.only,
plugins: program.plugins, plugins: program.plugins,
presets: program.presets, presets: program.presets,
}); });
// //
let replPlugin = new babel.Plugin("repl", { let replPlugin = () => ({
visitor: { visitor: {
ModuleDeclaration() { ModuleDeclaration(path) {
throw this.errorWithNode("Modules aren't supported in the REPL"); throw path.buildCodeFrameError("Modules aren't supported in the REPL");
}, },
VariableDeclaration(node) { VariableDeclaration(path) {
if (node.kind !== "var") { if (path.node.kind !== "var") {
throw this.errorWithNode("Only `var` variables are supported in the REPL"); throw path.buildCodeFrameError("Only `var` variables are supported in the REPL");
} }
} }
} }
@ -59,11 +60,8 @@ let _eval = function (code, filename) {
code = babel.transform(code, { code = babel.transform(code, {
filename: filename, filename: filename,
blacklist: program.blacklist, presets: program.presets,
whitelist: program.whitelist, plugins: (program.plugins || []).concat([replPlugin])
optional: program.optional,
stage: program.stage,
plugins: [replPlugin]
}).code; }).code;
return vm.runInThisContext(code, { return vm.runInThisContext(code, {

View File

@ -18,7 +18,7 @@ if (argSeparator > -1) {
babelArgs = babelArgs.slice(0, argSeparator); babelArgs = babelArgs.slice(0, argSeparator);
} }
getV8Flags(function (v8Flags) { getV8Flags(function (err, v8Flags) {
babelArgs.forEach(function(arg){ babelArgs.forEach(function(arg){
let flag = arg.split("=")[0]; let flag = arg.split("=")[0];

View File

@ -1,162 +0,0 @@
import pathExists from "path-exists";
import readline from "readline";
import child from "child_process";
import path from "path";
import fs from "fs";
function spawn(cmd, args, callback) {
console.log(">", cmd, args);
let spawn = child.spawn(cmd, args, { stdio: "inherit" });
spawn.on("exit", function (code) {
if (code === 0) {
callback();
} else {
console.log("Killing...");
process.exit(1);
}
});
}
function spawnMultiple(cmds) {
function next() {
let cmd = cmds.shift();
if (cmd) {
spawn(cmd.command, cmd.args, next);
} else {
process.exit();
}
}
next();
}
function template(name, data = {}) {
let source = fs.readFileSync(path.join(__dirname, "templates", name), "utf8");
source = source.replace(/[A-Z_]+/g, function (key) {
return data[key] === undefined ? key : data[key];
});
return source;
}
function write(filename, content) {
console.log(filename);
fs.writeFileSync(filename, content);
}
function execMaybe(cmd) {
try {
return child.execSync(cmd).toString();
} catch (err) {
return "";
}
}
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let BABEL_PLUGIN_PREFIX = "babel-plugin-";
let cmds = {
init: function () {
let name = path.basename(process.cwd());
if (name.indexOf(BABEL_PLUGIN_PREFIX) === 0) {
name = name.slice(BABEL_PLUGIN_PREFIX.length);
}
rl.question("Description (optional): ", function (description) {
let remote = execMaybe("git config --get remote.origin.url").trim().match(/git@github.com:(.*?).git/);
if (remote) {
build(description, remote[1]);
} else {
rl.question("GitHub Repository (eg. sebmck/babel-plugin-foobar) (optional): ", function (repo) {
build(description, repo);
});
}
});
function build(description, repo) {
rl.close();
let templateData = {
DESCRIPTION: description,
FULL_NAME: BABEL_PLUGIN_PREFIX + name,
NAME: name
};
write("package.json", JSON.stringify({
name: templateData.FULL_NAME,
version: "1.0.0",
description: templateData.DESCRIPTION,
repository: repo || undefined,
license: "MIT",
main: "lib/index.js",
devDependencies: {
babel: "^5.6.0"
},
scripts: {
build: "babel-plugin build",
push: "babel-plugin publish",
test: "babel-plugin test"
},
keywords: ["babel-plugin"]
}, null, " ") + "\n");
write(".npmignore", "node_modules\n*.log\nsrc\n");
write(".gitignore", "node_modules\n*.log\nlib\n");
write("README.md", template("README.md", templateData));
write("LICENSE", template("LICENSE", {
AUTHOR_EMAIL: execMaybe("git config --get user.email").trim(),
AUTHOR_NAME: execMaybe("git config --get user.name").trim(),
YEAR: new Date().getFullYear()
}));
if (!pathExists.sync("src")) {
fs.mkdirSync("src");
write("src/index.js", template("index.js", templateData));
}
}
},
build: function () {
spawn("babel", ["src", "--out-dir", "lib", "--copy-files"], process.exit);
},
publish: function () {
let pkg = require(process.cwd() + "/package.json");
console.log("Current version:", pkg.version);
rl.question("New version (enter nothing for patch): ", function (newVersion) {
rl.close();
newVersion = newVersion || "patch";
spawnMultiple([
{ command: "git", args: ["pull"] },
{ command: "git", args: ["push"] },
{ command: "babel-plugin", args: ["build"] },
{ command: "npm", args: ["version", newVersion] },
{ command: "npm", args: ["publish"] },
{ command: "git", args: ["push", "--follow-tags"] }
]);
});
}
};
let cmd = cmds[process.argv[2]];
if (cmd) {
cmd();
} else {
console.error("Unknown command:", cmd);
process.exit(1);
}

View File

@ -1,22 +0,0 @@
Copyright (c) YEAR AUTHOR_NAME <AUTHOR_EMAIL>
MIT License
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,35 +0,0 @@
# FULL_NAME
DESCRIPTION
## Installation
```sh
$ npm install FULL_NAME
```
## Usage
### Via `.babelrc` (Recommended)
**.babelrc**
```json
{
"plugins": ["NAME"]
}
```
### Via CLI
```sh
$ babel --plugins NAME script.js
```
### Via Node API
```javascript
require("babel-core").transform("code", {
plugins: ["NAME"]
});
```

View File

@ -1,8 +0,0 @@
/* eslint no-unused-vars:0 */
export default function ({ Plugin, types: t }) {
return new Plugin("NAME", {
visitor: {
// your visitor methods go here
}
});
}

View File

@ -20,6 +20,7 @@ module.exports = function (commander, filenames) {
}); });
if (!commander.copyFiles && data.ignored) return; if (!commander.copyFiles && data.ignored) return;
// we've requested explicit sourcemaps to be written to disk
if (data.map && commander.sourceMaps && commander.sourceMaps !== "inline") { if (data.map && commander.sourceMaps && commander.sourceMaps !== "inline") {
let mapLoc = dest + ".map"; let mapLoc = dest + ".map";
data.code = util.addSourceMappingUrl(data.code, mapLoc); data.code = util.addSourceMappingUrl(data.code, mapLoc);
@ -27,6 +28,7 @@ module.exports = function (commander, filenames) {
} }
outputFileSync(dest, data.code); outputFileSync(dest, data.code);
util.chmod(src, dest);
util.log(src + " -> " + dest); util.log(src + " -> " + dest);
} }
@ -37,7 +39,9 @@ module.exports = function (commander, filenames) {
if (util.canCompile(filename, commander.extensions)) { if (util.canCompile(filename, commander.extensions)) {
write(src, filename); write(src, filename);
} else if (commander.copyFiles) { } else if (commander.copyFiles) {
outputFileSync(path.join(commander.outDir, filename), fs.readFileSync(src)); let dest = path.join(commander.outDir, filename);
outputFileSync(dest, fs.readFileSync(src));
util.chmod(src, dest);
} }
} }

View File

@ -54,6 +54,8 @@ module.exports = function (commander, filenames, opts) {
} }
}); });
// add the inline sourcemap comment if we've either explicitly asked for inline source
// maps, or we've requested them without any output file
if (commander.sourceMaps === "inline" || (!commander.outFile && commander.sourceMaps)) { if (commander.sourceMaps === "inline" || (!commander.outFile && commander.sourceMaps)) {
code += "\n" + convertSourceMap.fromObject(map).toComment(); code += "\n" + convertSourceMap.fromObject(map).toComment();
} }
@ -68,6 +70,7 @@ module.exports = function (commander, filenames, opts) {
let result = buildResult(); let result = buildResult();
if (commander.outFile) { if (commander.outFile) {
// we've requested for a sorucemap to be written to disk
if (commander.sourceMaps && commander.sourceMaps !== "inline") { if (commander.sourceMaps && commander.sourceMaps !== "inline") {
let mapLoc = commander.outFile + ".map"; let mapLoc = commander.outFile + ".map";
result.code = util.addSourceMappingUrl(result.code, mapLoc); result.code = util.addSourceMappingUrl(result.code, mapLoc);

View File

@ -7,29 +7,33 @@ let path = require("path");
let fs = require("fs"); let fs = require("fs");
let _ = require("lodash"); let _ = require("lodash");
exports.readdirFilter = function (filename) { export function chmod(src, dest) {
fs.chmodSync(dest, fs.statSync(src).mode);
}
export function readdirFilter(filename) {
return readdir(filename).filter(function (filename) { return readdir(filename).filter(function (filename) {
return util.canCompile(filename); return util.canCompile(filename);
}); });
}; }
exports.readdir = readdir; export { readdir };
exports.canCompile = util.canCompile; export let canCompile = util.canCompile;
exports.shouldIgnore = function (loc) { export function shouldIgnore(loc) {
return util.shouldIgnore(loc, index.opts.ignore, index.opts.only); return util.shouldIgnore(loc, index.opts.ignore, index.opts.only);
}; }
exports.addSourceMappingUrl = function (code, loc) { export function addSourceMappingUrl(code, loc) {
return code + "\n//# sourceMappingURL=" + path.basename(loc); return code + "\n//# sourceMappingURL=" + path.basename(loc);
}; }
exports.log = function (msg) { export function log(msg) {
if (!commander.quiet) console.log(msg); if (!commander.quiet) console.log(msg);
}; }
exports.transform = function (filename, code, opts) { export function transform(filename, code, opts) {
opts = _.defaults(opts || {}, index.opts); opts = _.defaults(opts || {}, index.opts);
opts.filename = filename; opts.filename = filename;
opts.ignore = null; opts.ignore = null;
@ -39,12 +43,12 @@ exports.transform = function (filename, code, opts) {
result.filename = filename; result.filename = filename;
result.actual = code; result.actual = code;
return result; return result;
}; }
exports.compile = function (filename, opts) { export function compile(filename, opts) {
try { try {
let code = fs.readFileSync(filename, "utf8"); let code = fs.readFileSync(filename, "utf8");
return exports.transform(filename, code, opts); return transform(filename, code, opts);
} catch (err) { } catch (err) {
if (commander.watch) { if (commander.watch) {
console.error(toErrorStack(err)); console.error(toErrorStack(err));
@ -53,7 +57,7 @@ exports.compile = function (filename, opts) {
throw err; throw err;
} }
} }
}; }
function toErrorStack(err) { function toErrorStack(err) {
if (err._babel && err instanceof SyntaxError) { if (err._babel && err instanceof SyntaxError) {

View File

@ -1,3 +1 @@
{ {}
"breakConfig": true
}

View File

@ -8,4 +8,4 @@
} }
})(this, function (global) { })(this, function (global) {
var babelHelpers = global; var babelHelpers = global;
}) });

View File

@ -1,3 +1,3 @@
{ {
"args": ["--whitelist", "slice,has-own"] "args": ["--whitelist", "createClass"]
} }

View File

@ -1,5 +1,21 @@
(function (global) { (function (global) {
var babelHelpers = global.babelHelpers = {}; var babelHelpers = global.babelHelpers = {};
babelHelpers.hasOwn = Object.prototype.hasOwnProperty;
babelHelpers.slice = Array.prototype.slice; babelHelpers.createClass = (function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
})();
})(typeof global === "undefined" ? self : global); })(typeof global === "undefined" ? self : global);

View File

@ -1,3 +0,0 @@
{
"args": ["--blacklist", "es6.arrowFunctions"]
}

View File

@ -1 +0,0 @@
arr.map(x => x * MULTIPLIER);

View File

@ -1,3 +0,0 @@
"use strict";
arr.map(x => x * MULTIPLIER);

View File

@ -1,3 +0,0 @@
{
"args": ["--whitelist", "es6.arrowFunctions"]
}

View File

@ -1,2 +0,0 @@
let MULTIPLER = 5;
arr.map(x => x * MULTIPLIER);

View File

@ -1,4 +0,0 @@
let MULTIPLER = 5;
arr.map(function (x) {
return x * MULTIPLIER;
});

View File

@ -15,6 +15,16 @@ var _ = require("lodash");
var fixtureLoc = __dirname + "/fixtures"; var fixtureLoc = __dirname + "/fixtures";
var tmpLoc = __dirname + "/tmp"; var tmpLoc = __dirname + "/tmp";
var presetLocs = [
__dirname + "/../../babel-preset-es2015",
__dirname + "/../../babel-preset-react"
].join(",");
var pluginLocs = [
__dirname + "/../../babel-plugin-transform-strict-mode",
__dirname + "/../../babel-plugin-transform-es2015-modules-commonjs",
].join(",");
var readDir = function (loc) { var readDir = function (loc) {
var files = {}; var files = {};
if (pathExists.sync(loc)) { if (pathExists.sync(loc)) {
@ -43,7 +53,7 @@ var assertTest = function (stdout, stderr, opts) {
chai.expect(stderr).to.equal(expectStderr, "stderr didn't match"); chai.expect(stderr).to.equal(expectStderr, "stderr didn't match");
} }
} else if (stderr) { } else if (stderr) {
throw new Error("stderr: " + JSON.stringify(stderr)); throw new Error("stderr:\n" + stderr);
} }
var expectStdout = opts.stdout.trim(); var expectStdout = opts.stdout.trim();
@ -57,7 +67,7 @@ var assertTest = function (stdout, stderr, opts) {
chai.expect(stdout).to.equal(expectStdout, "stdout didn't match"); chai.expect(stdout).to.equal(expectStdout, "stdout didn't match");
} }
} else if (stdout) { } else if (stdout) {
throw new Error("stdout: " + JSON.stringify(stdout)); throw new Error("stdout:\n" + stdout);
} }
_.each(opts.outFiles, function (expect, filename) { _.each(opts.outFiles, function (expect, filename) {
@ -74,7 +84,18 @@ var buildTest = function (binName, testName, opts) {
clear(); clear();
saveInFiles(opts.inFiles); saveInFiles(opts.inFiles);
var args = [binLoc].concat(opts.args); var args = [binLoc];
if (binName !== "babel-external-helpers") {
args.push("--presets", presetLocs, "--plugins", pluginLocs);
}
if (binName === "babel-node") {
args.push("--only", "packages/*/test");
}
args = args.concat(opts.args);
var spawn = child.spawn(process.execPath, args); var spawn = child.spawn(process.execPath, args);
var stderr = ""; var stderr = "";

View File

@ -1,6 +1,6 @@
{ {
"name": "babel-code-frame", "name": "babel-code-frame",
"version": "5.8.22", "version": "5.10.32",
"description": "", "description": "",
"author": "Sebastian McKenzie <sebmck@gmail.com>", "author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/", "homepage": "https://babeljs.io/",
@ -8,6 +8,7 @@
"repository": "babel/babel", "repository": "babel/babel",
"main": "lib/index.js", "main": "lib/index.js",
"dependencies": { "dependencies": {
"babel-runtime": "^5.10.32",
"chalk": "^1.1.0", "chalk": "^1.1.0",
"esutils": "^2.0.2", "esutils": "^2.0.2",
"js-tokens": "^1.0.1", "js-tokens": "^1.0.1",

View File

@ -1,13 +1,14 @@
{ {
"name": "babel-core", "name": "babel-core",
"version": "5.8.23", "version": "5.10.32",
"description": "A compiler for writing next generation JavaScript", "description": "A compiler for writing next generation JavaScript",
"author": "Sebastian McKenzie <sebmck@gmail.com>", "author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/", "homepage": "https://babeljs.io/",
"license": "MIT", "license": "MIT",
"repository": "babel/babel", "repository": "babel/babel",
"browser": { "browser": {
"./lib/api/register/node.js": "./lib/api/register/browser.js" "./lib/api/register/node.js": "./lib/api/register/browser.js",
"esprima-fb": false
}, },
"keywords": [ "keywords": [
"6to5", "6to5",
@ -27,28 +28,15 @@
"test": "make test" "test": "make test"
}, },
"dependencies": { "dependencies": {
"babel-polyfill": "^5.8.22", "babel-code-frame": "^5.10.32",
"babel-code-frame": "^5.8.22", "babel-generator": "^5.10.32",
"babel-types": "^5.8.22", "babel-helpers": "^6.0.6",
"babel-traverse": "^5.8.22", "babel-messages": "^5.10.32",
"babel-generator": "^5.8.22", "babel-template": "^5.10.32",
"babel-messages": "^5.8.22", "babel-runtime": "^5.10.32",
"babel-plugin-constant-folding": "^1.0.1", "babel-traverse": "^5.10.32",
"babel-plugin-dead-code-elimination": "^1.0.2", "babel-types": "^5.10.32",
"babel-plugin-eval": "^1.0.1", "babylon": "^5.10.32",
"babel-plugin-inline-environment-variables": "^1.0.1",
"babel-plugin-jscript": "^1.0.4",
"babel-plugin-member-expression-literals": "^1.0.1",
"babel-plugin-property-literals": "^1.0.1",
"babel-plugin-proto-to-assign": "^1.0.3",
"babel-plugin-react-constant-elements": "^1.0.3",
"babel-plugin-react-display-name": "^2.0.0",
"babel-plugin-remove-console": "^1.0.1",
"babel-plugin-remove-debugger": "^1.0.1",
"babel-plugin-runtime": "^1.0.7",
"babel-plugin-undeclared-variables-check": "^1.0.2",
"babel-plugin-undefined-to-void": "^1.1.6",
"babylon": "^5.8.23",
"convert-source-map": "^1.1.0", "convert-source-map": "^1.1.0",
"debug": "^2.1.1", "debug": "^2.1.1",
"esutils": "^2.0.0", "esutils": "^2.0.0",
@ -60,11 +48,12 @@
"path-is-absolute": "^1.0.0", "path-is-absolute": "^1.0.0",
"private": "^0.1.6", "private": "^0.1.6",
"regenerator": "0.8.35", "regenerator": "0.8.35",
"regexpu": "^1.1.2",
"shebang-regex": "^1.0.0", "shebang-regex": "^1.0.0",
"slash": "^1.0.0", "slash": "^1.0.0",
"source-map": "^0.4.0", "source-map": "^0.4.0",
"source-map-support": "^0.2.10", "source-map-support": "^0.2.10"
"try-resolve": "^1.0.0" },
"devDependencies": {
"babel-polyfill": "^5.10.32"
} }
} }

View File

@ -1 +0,0 @@
module.exports = require("./lib/api/register/node");

View File

@ -1 +1 @@
module.exports = require("./lib/api/register/node-polyfill"); module.exports = require("./lib/api/register/node");

View File

@ -1,23 +1,22 @@
#!/bin/sh #!/bin/sh
set -e set -ex
BROWSERIFY_CMD="../../node_modules/browserify/bin/cmd.js" BROWSERIFY_CMD="../../node_modules/browserify/bin/cmd.js"
UGLIFY_CMD="../../node_modules/uglify-js/bin/uglifyjs" UGLIFY_CMD="../../node_modules/uglify-js/bin/uglifyjs"
BROWSERIFY_IGNORE="-i esprima-fb" BROWSERIFY_IGNORE="-i esprima-fb -i through"
mkdir -p dist mkdir -p dist
node scripts/cache-templates
# Add a Unicode BOM so browsers will interpret the file as UTF-8 # Add a Unicode BOM so browsers will interpret the file as UTF-8
node -p '"\uFEFF"' > dist/browser.js node -p '"\uFEFF"' > dist/browser.js
node $BROWSERIFY_CMD lib/api/browser.js -s babel $BROWSERIFY_IGNORE >>dist/browser.js node $BROWSERIFY_CMD lib/api/browser.js \
--standalone babel \
--plugin bundle-collapser/plugin \
--plugin derequire/plugin \
$BROWSERIFY_IGNORE \
>>dist/browser.j
node -p '"\uFEFF"' > dist/browser.min.js node -p '"\uFEFF"' > dist/browser.min.js
node $UGLIFY_CMD dist/browser.js >>dist/browser.min.js node $UGLIFY_CMD dist/browser.js \
--compress warnings=false \
node $BROWSERIFY_CMD lib/api/node.js --node $BROWSERIFY_IGNORE >dist/node.js --mangle \
>>dist/browser.min.js
node ../babel-cli/lib/babel-external-helpers >dist/external-helpers.js
node $UGLIFY_CMD dist/external-helpers.js >dist/external-helpers.min.js
rm -rf templates.json

View File

@ -1,5 +0,0 @@
#!/usr/bin/env node
var fs = require("fs");
var util = require("../lib/util");
fs.writeFileSync(__dirname + "/../templates.json", JSON.stringify(util.templates));

View File

@ -4,5 +4,3 @@ function rmRelative(loc) {
rmRelative("browser.js"); rmRelative("browser.js");
rmRelative("browser.min.js"); rmRelative("browser.min.js");
rmRelative("external-helpers.js");
rmRelative("external-helpers.min.js");

View File

@ -4,6 +4,3 @@ function relative(loc) {
cp(relative("dist/browser.js"), relative("browser.js")); cp(relative("dist/browser.js"), relative("browser.js"));
cp(relative("dist/browser.min.js"), relative("browser.min.js")); cp(relative("dist/browser.min.js"), relative("browser.min.js"));
cp(relative("dist/external-helpers.js"), relative("external-helpers.js"));
cp(relative("dist/external-helpers.min.js"), relative("external-helpers.min.js"));
require("./cache-templates");

View File

@ -1,29 +1,36 @@
/* @flow */ /* @flow */
import isFunction from "lodash/lang/isFunction"; import isFunction from "lodash/lang/isFunction";
import transform from "../transformation";
import * as babylon from "babylon";
import * as util from "../util";
import fs from "fs"; import fs from "fs";
export { util, transform };
export { pipeline, lint } from "../transformation";
export { canCompile } from "../util";
export { default as File } from "../transformation/file"; export { default as File } from "../transformation/file";
export { default as options } from "../transformation/file/options/config"; export { default as options } from "../transformation/file/options/config";
export { default as Plugin } from "../transformation/plugin";
export { default as Pipeline } from "../transformation/pipeline";
export { default as buildExternalHelpers } from "../tools/build-external-helpers"; export { default as buildExternalHelpers } from "../tools/build-external-helpers";
export { default as template } from "babel-template"; export { default as template } from "babel-template";
export { version } from "../../package"; export { version } from "../../package";
//
import * as util from "../util";
export { util };
import * as messages from "babel-messages"; import * as messages from "babel-messages";
export { messages }; export { messages };
import * as t from "babel-types"; import * as t from "babel-types";
export { t as types }; export { t as types };
//
import Pipeline from "../transformation/pipeline";
export { Pipeline };
let pipeline = new Pipeline;
export let transform = pipeline.transform.bind(pipeline);
export let transformFromAst = pipeline.transformFromAst.bind(pipeline);
//
export function transformFile(filename: string, opts?: Object, callback: Function) { export function transformFile(filename: string, opts?: Object, callback: Function) {
if (isFunction(opts)) { if (isFunction(opts)) {

View File

@ -1,3 +1,5 @@
/* @flow */
import path from "path"; import path from "path";
import fs from "fs"; import fs from "fs";
import homeOrTmp from "home-or-tmp"; import homeOrTmp from "home-or-tmp";

View File

@ -1,5 +1,6 @@
/* @flow */ /* @flow */
import deepClone from "lodash/lang/cloneDeep";
import sourceMapSupport from "source-map-support"; import sourceMapSupport from "source-map-support";
import * as registerCache from "./cache"; import * as registerCache from "./cache";
import OptionManager from "../../transformation/file/options/option-manager"; import OptionManager from "../../transformation/file/options/option-manager";
@ -10,10 +11,6 @@ import * as util from "../../util";
import fs from "fs"; import fs from "fs";
import path from "path"; import path from "path";
/**
* Install sourcemaps into node.
*/
sourceMapSupport.install({ sourceMapSupport.install({
handleUncaughtExceptions: false, handleUncaughtExceptions: false,
retrieveSourceMap(source) { retrieveSourceMap(source) {
@ -29,17 +26,9 @@ sourceMapSupport.install({
} }
}); });
/**
* Load and setup cache.
*/
registerCache.load(); registerCache.load();
let cache = registerCache.get(); let cache = registerCache.get();
/**
* Store options.
*/
let transformOpts = {}; let transformOpts = {};
let ignore; let ignore;
@ -50,33 +39,21 @@ let maps = {};
let cwd = process.cwd(); let cwd = process.cwd();
/**
* Get path from `filename` relative to the current working directory.
*/
function getRelativePath(filename){ function getRelativePath(filename){
return path.relative(cwd, filename); return path.relative(cwd, filename);
} }
/**
* Get last modified time for a `filename`.
*/
function mtime(filename) { function mtime(filename) {
return +fs.statSync(filename).mtime; return +fs.statSync(filename).mtime;
} }
/**
* Compile a `filename` with optional `opts`.
*/
function compile(filename, opts = {}) { function compile(filename, opts = {}) {
let result; let result;
opts.filename = filename; opts.filename = filename;
let optsManager = new OptionManager; let optsManager = new OptionManager;
optsManager.mergeOptions(transformOpts); optsManager.mergeOptions(deepClone(transformOpts));
opts = optsManager.init(opts); opts = optsManager.init(opts);
let cacheKey = `${JSON.stringify(opts)}:${babel.version}`; let cacheKey = `${JSON.stringify(opts)}:${babel.version}`;
@ -108,10 +85,6 @@ function compile(filename, opts = {}) {
return result.code; return result.code;
} }
/**
* Test if a `filename` should be ignored by Babel.
*/
function shouldIgnore(filename) { function shouldIgnore(filename) {
if (!ignore && !only) { if (!ignore && !only) {
return getRelativePath(filename).split(path.sep).indexOf("node_modules") >= 0; return getRelativePath(filename).split(path.sep).indexOf("node_modules") >= 0;
@ -120,58 +93,13 @@ function shouldIgnore(filename) {
} }
} }
/** function loader(m, filename) {
* Monkey patch istanbul if it is running so that it works properly.
*/
let istanbulMonkey = {};
if (process.env.running_under_istanbul) {
// we need to monkey patch fs.readFileSync so we can hook into
// what istanbul gets, it's extremely dirty but it's the only way
let _readFileSync = fs.readFileSync;
fs.readFileSync = function (filename) {
if (istanbulMonkey[filename]) {
delete istanbulMonkey[filename];
let code = compile(filename, {
auxiliaryCommentBefore: "istanbul ignore next"
});
istanbulMonkey[filename] = true;
return code;
} else {
return _readFileSync.apply(this, arguments);
}
};
}
/**
* Replacement for the loader for istanbul.
*/
function istanbulLoader(m, filename, old) {
istanbulMonkey[filename] = true;
old(m, filename);
}
/**
* Default loader.
*/
function normalLoader(m, filename) {
m._compile(compile(filename), filename); m._compile(compile(filename), filename);
} }
/**
* Register a loader for an extension.
*/
function registerExtension(ext) { function registerExtension(ext) {
let old = oldHandlers[ext] || oldHandlers[".js"] || require.extensions[".js"]; let old = oldHandlers[ext] || oldHandlers[".js"] || require.extensions[".js"];
let loader = normalLoader;
if (process.env.running_under_istanbul) loader = istanbulLoader;
require.extensions[ext] = function (m, filename) { require.extensions[ext] = function (m, filename) {
if (shouldIgnore(filename)) { if (shouldIgnore(filename)) {
old(m, filename); old(m, filename);
@ -181,10 +109,6 @@ function registerExtension(ext) {
}; };
} }
/**
* Register loader for given extensions.
*/
function hookExtensions(_exts) { function hookExtensions(_exts) {
each(oldHandlers, function (old, ext) { each(oldHandlers, function (old, ext) {
if (old === undefined) { if (old === undefined) {
@ -202,16 +126,8 @@ function hookExtensions(_exts) {
}); });
} }
/**
* Register loader for default extensions.
*/
hookExtensions(util.canCompile.EXTENSIONS); hookExtensions(util.canCompile.EXTENSIONS);
/**
* Update options at runtime.
*/
export default function (opts?: Object = {}) { export default function (opts?: Object = {}) {
if (opts.only != null) only = util.arrayify(opts.only, util.regexify); if (opts.only != null) only = util.arrayify(opts.only, util.regexify);
if (opts.ignore != null) ignore = util.arrayify(opts.ignore, util.regexify); if (opts.ignore != null) ignore = util.arrayify(opts.ignore, util.regexify);

View File

@ -0,0 +1,24 @@
/* @flow */
import Module from "module";
let relativeModules = {};
export default function (loc: string, relative: string = process.cwd()): ?string {
// we're in the browser, probably
if (typeof Module === "object") return null;
let relativeMod = relativeModules[relative];
if (!relativeMod) {
relativeMod = new Module;
relativeMod.paths = Module._nodeModulePaths(relative);
relativeModules[relative] = relativeMod;
}
try {
return Module._resolveFilename(loc, relativeMod);
} catch (err) {
return null;
}
}

View File

@ -16,9 +16,10 @@ export default class Store extends Map {
if (this.has(key)) { if (this.has(key)) {
return super.get(key); return super.get(key);
} else { } else {
let dynamic = this.dynamicData[key]; if (Object.prototype.hasOwnProperty.call(this.dynamicData, key)) {
if (dynamic) { let val = this.dynamicData[key]();
return this.set(key, dynamic()); this.set(key, val);
return val;
} }
} }
} }

View File

@ -1,16 +1,30 @@
/* @flow */ /* @flow */
import * as helpers from "babel-helpers";
import generator from "babel-generator"; import generator from "babel-generator";
import * as messages from "babel-messages"; import * as messages from "babel-messages";
import * as util from "../util"; import template from "babel-template";
import File from "../transformation/file";
import each from "lodash/collection/each"; import each from "lodash/collection/each";
import * as t from "babel-types"; import * as t from "babel-types";
let buildUmdWrapper = template(`
(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
});
`);
function buildGlobal(namespace, builder) { function buildGlobal(namespace, builder) {
let body = []; let body = [];
let container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body)); let container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
let tree = t.program([t.expressionStatement(t.callExpression(container, [util.template("helper-self-global")]))]); let tree = t.program([t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]);
body.push(t.variableDeclaration("var", [ body.push(t.variableDeclaration("var", [
t.variableDeclarator( t.variableDeclarator(
@ -32,33 +46,38 @@ function buildUmd(namespace, builder) {
builder(body); builder(body);
let container = util.template("umd-commonjs-strict", { return t.program([
FACTORY_PARAMETERS: t.identifier("global"), buildUmdWrapper({
BROWSER_ARGUMENTS: t.assignmentExpression("=", t.memberExpression(t.identifier("root"), namespace), t.objectExpression({})), FACTORY_PARAMETERS: t.identifier("global"),
COMMON_ARGUMENTS: t.identifier("exports"), BROWSER_ARGUMENTS: t.assignmentExpression(
AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]), "=",
FACTORY_BODY: body, t.memberExpression(t.identifier("root"), namespace),
UMD_ROOT: t.identifier("this") t.objectExpression([])
}); ),
return t.program([container]); COMMON_ARGUMENTS: t.identifier("exports"),
AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]),
FACTORY_BODY: body,
UMD_ROOT: t.identifier("this")
})
]);
} }
function buildVar(namespace, builder) { function buildVar(namespace, builder) {
let body = []; let body = [];
body.push(t.variableDeclaration("var", [ body.push(t.variableDeclaration("var", [
t.variableDeclarator(namespace, t.objectExpression({})) t.variableDeclarator(namespace, t.objectExpression([]))
])); ]));
builder(body); builder(body);
return t.program(body); return t.program(body);
} }
function buildHelpers(body, namespace, whitelist) { function buildHelpers(body, namespace, whitelist) {
each(File.helpers, function (name) { each(helpers.list, function (name) {
if (whitelist && whitelist.indexOf(name) === -1) return; if (whitelist && whitelist.indexOf(name) === -1) return;
let key = t.identifier(t.toIdentifier(name)); let key = t.identifier(t.toIdentifier(name));
body.push(t.expressionStatement( body.push(t.expressionStatement(
t.assignmentExpression("=", t.memberExpression(namespace, key), util.template("helper-" + name)) t.assignmentExpression("=", t.memberExpression(namespace, key), helpers.get(name))
)); ));
}); });
} }

View File

@ -1,26 +1,37 @@
/* @flow */
/* global BabelParserOptions */
/* global BabelFileMetadata */
/* global BabelFileResult */
import getHelper from "babel-helpers";
import * as metadataVisitor from "./metadata";
import convertSourceMap from "convert-source-map"; import convertSourceMap from "convert-source-map";
import moduleFormatters from "../modules";
import OptionManager from "./options/option-manager"; import OptionManager from "./options/option-manager";
import PluginManager from "./plugin-manager"; import type Pipeline from "../pipeline";
import type Plugin from "../plugin";
import PluginPass from "../plugin-pass";
import shebangRegex from "shebang-regex"; import shebangRegex from "shebang-regex";
import { NodePath, Hub } from "babel-traverse"; import { NodePath, Hub, Scope } from "babel-traverse";
import isFunction from "lodash/lang/isFunction";
import sourceMap from "source-map"; import sourceMap from "source-map";
import generate from "babel-generator"; import generate from "babel-generator";
import codeFrame from "babel-code-frame"; import codeFrame from "babel-code-frame";
import shuffle from "lodash/collection/shuffle";
import defaults from "lodash/object/defaults"; import defaults from "lodash/object/defaults";
import includes from "lodash/collection/includes";
import traverse from "babel-traverse"; import traverse from "babel-traverse";
import resolve from "try-resolve";
import Logger from "./logger"; import Logger from "./logger";
import Store from "../../store"; import Store from "../../store";
import Plugin from "../plugin"; import { parse } from "babylon";
import parse from "../../helpers/parse";
import * as util from "../../util"; import * as util from "../../util";
import path from "path"; import path from "path";
import * as t from "babel-types"; import * as t from "babel-types";
import blockHoistPlugin from "../internal-plugins/block-hoist";
import shadowFunctionsPlugin from "../internal-plugins/shadow-functions";
const INTERNAL_PLUGINS = [
[blockHoistPlugin],
[shadowFunctionsPlugin]
];
let errorVisitor = { let errorVisitor = {
enter(path, state) { enter(path, state) {
let loc = path.node.loc; let loc = path.node.loc;
@ -32,80 +43,88 @@ let errorVisitor = {
}; };
export default class File extends Store { export default class File extends Store {
constructor(opts = {}, pipeline) { constructor(opts: Object = {}, pipeline: Pipeline) {
super();
this.pipeline = pipeline; this.pipeline = pipeline;
this.log = new Logger(this, opts.filename || "unknown"); this.log = new Logger(this, opts.filename || "unknown");
this.opts = this.initOptions(opts); this.opts = this.initOptions(opts);
this.buildTransformers(); this.parserOpts = {
highlightCode: this.opts.highlightCode,
nonStandard: this.opts.nonStandard,
sourceType: this.opts.sourceType,
filename: this.opts.filename,
plugins: []
};
this.pluginVisitors = [];
this.pluginPasses = [];
this.pluginStack = [];
this.buildPlugins();
this.metadata = {
usedHelpers: [],
marked: [],
modules: {
imports: [],
exports: {
exported: [],
specifiers: []
}
}
};
this.dynamicImportTypes = {};
this.dynamicImportIds = {};
this.dynamicImports = [];
this.declarations = {};
this.usedHelpers = {};
this.path = null;
this.ast = {};
this.code = "";
this.shebang = "";
this.hub = new Hub(this);
} }
transformerDependencies = {}; static helpers: Array<string>;
dynamicImportTypes = {};
dynamicImportIds = {};
dynamicImports = [];
declarations = {};
usedHelpers = {};
dynamicData = {};
data = {};
ast = {};
metadata = { pluginVisitors: Array<Object>;
marked: [], pluginPasses: Array<PluginPass>;
pluginStack: Array<Plugin>;
pipeline: Pipeline;
parserOpts: BabelParserOptions;
log: Logger;
opts: Object;
dynamicImportTypes: Object;
dynamicImportIds: Object;
dynamicImports: Array<Object>;
declarations: Object;
usedHelpers: Object;
path: NodePath;
ast: Object;
scope: Scope;
metadata: BabelFileMetadata;
hub: Hub;
code: string;
shebang: string;
modules: { getMetadata() {
imports: [], let has = false;
exports: { for (let node of (this.ast.program.body: Array<Object>)) {
exported: [], if (t.isModuleDeclaration(node)) {
specifiers: [] has = true;
break;
} }
} }
}; if (has) {
this.path.traverse(metadataVisitor, this);
hub = new Hub(this); }
}
static helpers = [
"inherits",
"defaults",
"create-class",
"create-decorated-class",
"create-decorated-object",
"define-decorated-property-descriptor",
"tagged-template-literal",
"tagged-template-literal-loose",
"to-array",
"to-consumable-array",
"sliced-to-array",
"sliced-to-array-loose",
"object-without-properties",
"has-own",
"slice",
"bind",
"define-property",
"async-to-generator",
"interop-export-wildcard",
"interop-require-wildcard",
"interop-require-default",
"typeof",
"extends",
"get",
"set",
"new-arrow-check",
"class-call-check",
"object-destructuring-empty",
"temporal-undefined",
"temporal-assert-defined",
"self-global",
"default-props",
"instanceof",
// legacy
"interop-require"
];
static soloHelpers = [];
initOptions(opts) { initOptions(opts) {
opts = new OptionManager(this.log, this.pipeline).init(opts); opts = new OptionManager(this.log, this.pipeline).init(opts);
@ -143,130 +162,67 @@ export default class File extends Store {
sourceMapTarget: basenameRelative sourceMapTarget: basenameRelative
}); });
//
if (opts.externalHelpers) {
this.set("helpersNamespace", t.identifier("babelHelpers"));
}
return opts; return opts;
} }
isLoose(key: string) { buildPlugins() {
return includes(this.opts.loose, key); let plugins: Array<[PluginPass, Object]> = this.opts.plugins.concat(INTERNAL_PLUGINS);
}
buildTransformers() {
let file = this;
let transformers = this.transformers = {};
let secondaryStack = [];
let stack = [];
// build internal transformers
for (let key in this.pipeline.transformers) {
let transformer = this.pipeline.transformers[key];
let pass = transformers[key] = transformer.buildPass(file);
if (pass.canTransform()) {
stack.push(pass);
if (transformer.metadata.secondPass) {
secondaryStack.push(pass);
}
if (transformer.manipulateOptions) {
transformer.manipulateOptions(file.opts, file);
}
}
}
// init plugins! // init plugins!
let beforePlugins = []; for (let ref of plugins) {
let afterPlugins = []; let [plugin, pluginOpts] = ref; // todo: fix - can't embed in loop head because of flow bug
let pluginManager = new PluginManager({
file: this,
transformers: this.transformers,
before: beforePlugins,
after: afterPlugins
});
for (let i = 0; i < file.opts.plugins.length; i++) {
pluginManager.add(file.opts.plugins[i]);
}
stack = beforePlugins.concat(stack, afterPlugins);
// build transformer stack this.pluginStack.push(plugin);
this.uncollapsedTransformerStack = stack = stack.concat(secondaryStack); this.pluginVisitors.push(plugin.visitor);
this.pluginPasses.push(new PluginPass(this, plugin, pluginOpts));
// build dependency graph if (plugin.manipulateOptions) {
for (let pass of (stack: Array)) { plugin.manipulateOptions(this.opts, this.parserOpts, this);
for (let dep of (pass.plugin.dependencies: Array)) {
this.transformerDependencies[dep] = pass.key;
} }
} }
// collapse stack categories
this.transformerStack = this.collapseStack(stack);
} }
collapseStack(_stack) { getModuleName(): ?string {
let stack = []; let opts = this.opts;
let ignore = []; if (!opts.moduleIds) {
return null;
for (let pass of (_stack: Array)) {
// been merged
if (ignore.indexOf(pass) >= 0) continue;
let group = pass.plugin.metadata.group;
// can't merge
if (!pass.canTransform() || !group) {
stack.push(pass);
continue;
}
let mergeStack = [];
for (let pass of (_stack: Array)) {
if (pass.plugin.metadata.group === group) {
mergeStack.push(pass);
ignore.push(pass);
} else {
//break;
}
}
shuffle;
//mergeStack = shuffle(mergeStack);
let visitors = [];
for (let pass of (mergeStack: Array)) {
visitors.push(pass.plugin.visitor);
}
let visitor = traverse.visitors.merge(visitors);
let mergePlugin = new Plugin(group, { visitor });
stack.push(mergePlugin.buildPass(this));
} }
return stack; // moduleId is n/a if a `getModuleId()` is provided
} if (opts.moduleId != null && !opts.getModuleId) {
return opts.moduleId;
}
set(key: string, val): any { let filenameRelative = opts.filenameRelative;
return this.data[key] = val; let moduleName = "";
}
setDynamic(key: string, fn: Function) { if (opts.moduleRoot != null) {
this.dynamicData[key] = fn; moduleName = opts.moduleRoot + "/";
} }
get(key: string): any { if (!opts.filenameRelative) {
let data = this.data[key]; return moduleName + opts.filename.replace(/^\//, "");
if (data) { }
return data;
if (opts.sourceRoot != null) {
// remove sourceRoot from filename
let sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?");
filenameRelative = filenameRelative.replace(sourceRootRegEx, "");
}
// remove extension
filenameRelative = filenameRelative.replace(/\.(\w*?)$/, "");
moduleName += filenameRelative;
// normalize path separators
moduleName = moduleName.replace(/\\/g, "/");
if (opts.getModuleId) {
// If return is falsy, assume they want us to use our generated default name
return opts.getModuleId(moduleName) || moduleName;
} else { } else {
let dynamic = this.dynamicData[key]; return moduleName;
if (dynamic) {
return this.set(key, dynamic());
}
} }
} }
@ -276,81 +232,52 @@ export default class File extends Store {
return source; return source;
} }
addImport(source: string, name?: string, type?: string): Object { addImport(source: string, imported: string, name?: string = imported): Object {
name = name || source; let alias = `${source}:${imported}`;
let id = this.dynamicImportIds[name]; let id = this.dynamicImportIds[alias];
if (!id) { if (!id) {
source = this.resolveModuleSource(source); source = this.resolveModuleSource(source);
id = this.dynamicImportIds[name] = this.scope.generateUidIdentifier(name); id = this.dynamicImportIds[alias] = this.scope.generateUidIdentifier(name);
let specifiers = [];
if (imported === "*") {
specifiers.push(t.importNamespaceSpecifier(id));
} else if (imported === "default") {
specifiers.push(t.importDefaultSpecifier(id));
} else {
specifiers.push(t.importSpecifier(id, t.identifier(imported)));
}
let specifiers = [t.importDefaultSpecifier(id)];
let declar = t.importDeclaration(specifiers, t.stringLiteral(source)); let declar = t.importDeclaration(specifiers, t.stringLiteral(source));
declar._blockHoist = 3; declar._blockHoist = 3;
if (type) { this.path.unshiftContainer("body", declar);
let modules = this.dynamicImportTypes[type] = this.dynamicImportTypes[type] || [];
modules.push(declar);
}
if (this.transformers["es6.modules"].canTransform()) {
this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports, this.scope);
this.moduleFormatter.hasLocalImports = true;
} else {
this.dynamicImports.push(declar);
}
} }
return id; return id;
} }
attachAuxiliaryComment(node: Object): Object {
let beforeComment = this.opts.auxiliaryCommentBefore;
if (beforeComment) {
node.leadingComments = node.leadingComments || [];
node.leadingComments.push({
type: "CommentLine",
value: " " + beforeComment
});
}
let afterComment = this.opts.auxiliaryCommentAfter;
if (afterComment) {
node.trailingComments = node.trailingComments || [];
node.trailingComments.push({
type: "CommentLine",
value: " " + afterComment
});
}
return node;
}
addHelper(name: string): Object { addHelper(name: string): Object {
let isSolo = includes(File.soloHelpers, name);
if (!isSolo && !includes(File.helpers, name)) {
throw new ReferenceError(`Unknown helper ${name}`);
}
let declar = this.declarations[name]; let declar = this.declarations[name];
if (declar) return declar; if (declar) return declar;
this.usedHelpers[name] = true; if (!this.usedHelpers[name]) {
this.metadata.usedHelpers.push(name);
if (!isSolo) { this.usedHelpers[name] = true;
let generator = this.get("helperGenerator");
let runtime = this.get("helpersNamespace");
if (generator) {
return generator(name);
} else if (runtime) {
let id = t.identifier(t.toIdentifier(name));
return t.memberExpression(runtime, id);
}
} }
let ref = util.template("helper-" + name); let generator = this.get("helperGenerator");
let runtime = this.get("helpersNamespace");
if (generator) {
return generator(name);
} else if (runtime) {
let id = t.identifier(t.toIdentifier(name));
return t.memberExpression(runtime, id);
}
let ref = getHelper(name);
let uid = this.declarations[name] = this.scope.generateUidIdentifier(name); let uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
if (t.isFunctionExpression(ref) && !ref.id) { if (t.isFunctionExpression(ref) && !ref.id) {
@ -358,7 +285,6 @@ export default class File extends Store {
ref._generated = true; ref._generated = true;
ref.id = uid; ref.id = uid;
ref.type = "FunctionDeclaration"; ref.type = "FunctionDeclaration";
this.attachAuxiliaryComment(ref);
this.path.unshiftContainer("body", ref); this.path.unshiftContainer("body", ref);
} else { } else {
ref._compact = true; ref._compact = true;
@ -372,7 +298,11 @@ export default class File extends Store {
return uid; return uid;
} }
addTemplateObject(helperName: string, strings: Array, raw: Array): Object { addTemplateObject(
helperName: string,
strings: Array<Object>,
raw: Object,
): Object {
// Generate a unique name based on the string literals so we dedupe // Generate a unique name based on the string literals so we dedupe
// identical strings used in the program. // identical strings used in the program.
let stringIds = raw.elements.map(function(string) { let stringIds = raw.elements.map(function(string) {
@ -396,7 +326,7 @@ export default class File extends Store {
return uid; return uid;
} }
buildCodeFrameError(node, msg, Error = SyntaxError) { buildCodeFrameError(node: Object, msg: string, Error: typeof Error = SyntaxError): Error {
let loc = node && (node.loc || node._loc); let loc = node && (node.loc || node._loc);
let err = new Error(msg); let err = new Error(msg);
@ -404,7 +334,7 @@ export default class File extends Store {
if (loc) { if (loc) {
err.loc = loc.start; err.loc = loc.start;
} else { } else {
traverse(node, errorVisitor, err); traverse(node, errorVisitor, this.scope, err);
err.message += " (This is an error on an internal node. Probably an internal error"; err.message += " (This is an error on an internal node. Probably an internal error";
@ -436,49 +366,9 @@ export default class File extends Store {
} }
} }
getModuleFormatter(type: string) {
if (isFunction(type) || !moduleFormatters[type]) {
this.log.deprecate("Custom module formatters are deprecated and will be removed in the next major. Please use Babel plugins instead.");
}
let ModuleFormatter = isFunction(type) ? type : moduleFormatters[type];
if (!ModuleFormatter) {
let loc = resolve.relative(type);
if (loc) ModuleFormatter = require(loc);
}
if (!ModuleFormatter) {
throw new ReferenceError(`Unknown module formatter type ${JSON.stringify(type)}`);
}
return new ModuleFormatter(this);
}
parse(code: string) { parse(code: string) {
let opts = this.opts;
//
let parseOpts = {
highlightCode: opts.highlightCode,
nonStandard: opts.nonStandard,
sourceType: opts.sourceType,
filename: opts.filename,
plugins: {}
};
let features = parseOpts.features = {};
for (let key in this.transformers) {
let transformer = this.transformers[key];
features[key] = transformer.canRun();
}
parseOpts.looseModules = this.isLoose("es6.modules");
parseOpts.strictMode = features.strict;
this.log.debug("Parse start"); this.log.debug("Parse start");
let ast = parse(code, parseOpts); let ast = parse(code, this.parserOpts);
this.log.debug("Parse stop"); this.log.debug("Parse stop");
return ast; return ast;
} }
@ -493,32 +383,25 @@ export default class File extends Store {
}).setContext(); }).setContext();
this.scope = this.path.scope; this.scope = this.path.scope;
this.ast = ast; this.ast = ast;
this.getMetadata();
} }
addAst(ast) { addAst(ast) {
this.log.debug("Start set AST"); this.log.debug("Start set AST");
this._addAst(ast); this._addAst(ast);
this.log.debug("End set AST"); this.log.debug("End set AST");
this.log.debug("Start module formatter init");
let modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
if (modFormatter.init && this.transformers["es6.modules"].canTransform()) {
modFormatter.init();
}
this.log.debug("End module formatter init");
} }
transform() { transform(): BabelFileResult {
this.call("pre"); this.call("pre");
for (let pass of (this.transformerStack: Array)) { this.log.debug(`Start transform traverse`);
pass.transform(); traverse(this.ast, traverse.visitors.merge(this.pluginVisitors, this.pluginPasses), this.scope);
} this.log.debug(`End transform traverse`);
this.call("post"); this.call("post");
return this.generate(); return this.generate();
} }
wrap(code, callback) { wrap(code: string, callback: Function): BabelFileResult {
code = code + ""; code = code + "";
try { try {
@ -578,14 +461,15 @@ export default class File extends Store {
return util.shouldIgnore(opts.filename, opts.ignore, opts.only); return util.shouldIgnore(opts.filename, opts.ignore, opts.only);
} }
call(key: string) { call(key: "pre" | "post") {
for (let pass of (this.uncollapsedTransformerStack: Array)) { for (let pass of (this.pluginPasses: Array<PluginPass>)) {
let fn = pass.plugin[key]; let plugin = pass.plugin;
if (fn) fn.call(pass, this); let fn = plugin[key];
if (fn) fn.call(pass, this, pass);
} }
} }
parseInputSourceMap(code: string) { parseInputSourceMap(code: string): string {
let opts = this.opts; let opts = this.opts;
if (opts.inputSourceMap !== false) { if (opts.inputSourceMap !== false) {
@ -607,13 +491,14 @@ export default class File extends Store {
} }
} }
makeResult({ code, map = null, ast, ignored }) { makeResult({ code, map, ast, ignored }: BabelFileResult): BabelFileResult {
let result = { let result = {
metadata: null, metadata: null,
options: this.opts,
ignored: !!ignored, ignored: !!ignored,
code: null, code: null,
ast: null, ast: null,
map: map map: map || null
}; };
if (this.opts.code) { if (this.opts.code) {
@ -626,17 +511,16 @@ export default class File extends Store {
if (this.opts.metadata) { if (this.opts.metadata) {
result.metadata = this.metadata; result.metadata = this.metadata;
result.metadata.usedHelpers = Object.keys(this.usedHelpers);
} }
return result; return result;
} }
generate() { generate(): BabelFileResult {
let opts = this.opts; let opts = this.opts;
let ast = this.ast; let ast = this.ast;
let result = { ast }; let result: BabelFileResult = { ast };
if (!opts.code) return this.makeResult(result); if (!opts.code) return this.makeResult(result);
this.log.debug("Generation start"); this.log.debug("Generation start");
@ -649,7 +533,7 @@ export default class File extends Store {
if (this.shebang) { if (this.shebang) {
// add back shebang // add back shebang
result.code = `${this.shebang}\n${result.code}`; result.code = `${this.shebang}${result.code}`;
} }
if (result.map) { if (result.map) {
@ -667,3 +551,5 @@ export default class File extends Store {
return this.makeResult(result); return this.makeResult(result);
} }
} }
export { File };

View File

@ -1,33 +1,29 @@
/* @flow */ /* @flow */
import extend from "lodash/object/extend";
import * as t from "babel-types"; import * as t from "babel-types";
export let ModuleDeclaration = { export let ModuleDeclaration = {
enter(node, parent, scope, formatter) { enter(path, file) {
let { node } = path;
if (node.source) { if (node.source) {
node.source.value = formatter.file.resolveModuleSource(node.source.value); node.source.value = file.resolveModuleSource(node.source.value);
formatter.addScope(this);
} }
} }
}; };
export let ImportDeclaration = { export let ImportDeclaration = {
exit(node, parent, scope, formatter) { exit(path, file) {
formatter.hasLocalImports = true; let { node } = path;
let specifiers = []; let specifiers = [];
let imported = []; let imported = [];
formatter.metadata.imports.push({ file.metadata.modules.imports.push({
source: node.source.value, source: node.source.value,
imported, imported,
specifiers specifiers
}); });
for (let specifier of (this.get("specifiers"): Array)) { for (let specifier of (path.get("specifiers"): Array<Object>)) {
let ids = specifier.getBindingIdentifiers();
extend(formatter.localImports, ids);
let local = specifier.node.local.name; let local = specifier.node.local.name;
if (specifier.isImportDefaultSpecifier()) { if (specifier.isImportDefaultSpecifier()) {
@ -60,33 +56,30 @@ export let ImportDeclaration = {
} }
}; };
export function ExportDeclaration(node, parent, scope, formatter) { export function ExportDeclaration(path, file) {
formatter.hasLocalExports = true; let { node } = path;
let source = node.source ? node.source.value : null; let source = node.source ? node.source.value : null;
let exports = formatter.metadata.exports; let exports = file.metadata.modules.exports;
// export function foo() {} // export function foo() {}
// export let foo = "bar"; // export let foo = "bar";
let declar = this.get("declaration"); let declar = path.get("declaration");
if (declar.isStatement()) { if (declar.isStatement()) {
let bindings = declar.getBindingIdentifiers(); let bindings = declar.getBindingIdentifiers();
for (let name in bindings) { for (let name in bindings) {
let binding = bindings[name];
formatter._addExport(name, binding);
exports.exported.push(name); exports.exported.push(name);
exports.specifiers.push({ exports.specifiers.push({
kind: "local", kind: "local",
local: name, local: name,
exported: this.isExportDefaultDeclaration() ? "default" : name exported: path.isExportDefaultDeclaration() ? "default" : name
}); });
} }
} }
if (this.isExportNamedDeclaration() && node.specifiers) { if (path.isExportNamedDeclaration() && node.specifiers) {
for (let specifier of (node.specifiers: Array)) { for (let specifier of (node.specifiers: Array<Object>)) {
let exported = specifier.exported.name; let exported = specifier.exported.name;
exports.exported.push(exported); exports.exported.push(exported);
@ -112,8 +105,6 @@ export function ExportDeclaration(node, parent, scope, formatter) {
let local = specifier.local; let local = specifier.local;
if (!local) continue; if (!local) continue;
formatter._addExport(local.name, specifier.exported);
// export { foo } from "bar"; // export { foo } from "bar";
// export { foo as bar } from "bar"; // export { foo as bar } from "bar";
if (source) { if (source) {
@ -138,23 +129,14 @@ export function ExportDeclaration(node, parent, scope, formatter) {
} }
// export * from "bar"; // export * from "bar";
if (this.isExportAllDeclaration()) { if (path.isExportAllDeclaration()) {
exports.specifiers.push({ exports.specifiers.push({
kind: "external-all", kind: "external-all",
source source
}); });
} }
if (!t.isExportDefaultDeclaration(node) && !declar.isTypeAlias()) {
let onlyDefault = node.specifiers && node.specifiers.length === 1 && t.isSpecifierDefault(node.specifiers[0]);
if (!onlyDefault) {
formatter.hasNonDefaultExports = true;
}
}
} }
export function Scope(node, parent, scope, formatter) { export function Scope(path) {
if (!formatter.isLoose()) { path.skip();
this.skip();
}
} }

View File

@ -51,8 +51,8 @@
"plugins": { "plugins": {
"type": "list", "type": "list",
"description": "", "default": [],
"default": [] "description": ""
}, },
"ignore": { "ignore": {
@ -137,5 +137,35 @@
"sourceType": { "sourceType": {
"description": "", "description": "",
"default": "module" "default": "module"
},
"auxiliaryComment": {
"description": "",
"type": "string"
},
"resolveModuleSource": {
"hidden": true
},
"getModuleId": {
"hidden": true
},
"moduleRoot": {
"type": "filename",
"description": "optional prefix for the AMD module formatter that will be prepend to the filename on module definitions"
},
"moduleIds": {
"type": "boolean",
"default": false,
"shorthand": "M",
"description": "insert an explicit id for modules"
},
"moduleId": {
"description": "specify a custom name for module ids",
"type": "string"
} }
} }

View File

@ -11,6 +11,7 @@ export function normaliseOptions(options: Object = {}): Object {
if (val == null) continue; if (val == null) continue;
let opt = config[key]; let opt = config[key];
if (opt && opt.alias) opt = config[opt.alias];
if (!opt) continue; if (!opt) continue;
let parser = parsers[opt.type]; let parser = parsers[opt.type];

View File

@ -1,9 +1,9 @@
/* @flow */ /* @flow */
import * as context from "../../../api/node";
import type Logger from "../logger"; import type Logger from "../logger";
import Plugin from "../../plugin"; import Plugin from "../../plugin";
import * as messages from "babel-messages"; import * as messages from "babel-messages";
import * as context from "../../../api/node";
import { normaliseOptions } from "./index"; import { normaliseOptions } from "./index";
import resolve from "../../../helpers/resolve"; import resolve from "../../../helpers/resolve";
import json5 from "json5"; import json5 from "json5";
@ -53,7 +53,13 @@ export default class OptionManager {
if (cache.container === fn) return cache.plugin; if (cache.container === fn) return cache.plugin;
} }
let obj = fn(context); let obj;
if (typeof fn === "function") {
obj = fn(context);
} else {
obj = fn;
}
if (typeof obj === "object") { if (typeof obj === "object") {
let plugin = new Plugin(obj); let plugin = new Plugin(obj);
@ -63,7 +69,7 @@ export default class OptionManager {
}); });
return plugin; return plugin;
} else { } else {
throw new TypeError(messages.get("pluginNotObject", loc, i, typeof obj)); throw new TypeError(messages.get("pluginNotObject", loc, i, typeof obj) + loc + i);
} }
} }
@ -78,6 +84,21 @@ export default class OptionManager {
return opts; return opts;
} }
static normalisePlugin(plugin, loc, i) {
if (!(plugin instanceof Plugin)) {
// allow plugin containers to be specified so they don't have to manually require
if (typeof plugin === "function" || typeof plugin === "object") {
plugin = OptionManager.memoisePluginContainer(plugin, loc, i);
} else {
throw new TypeError(messages.get("pluginNotFunction", loc, i, typeof plugin));
}
}
plugin.init(loc, i);
return plugin;
}
static normalisePlugins(loc, dirname, plugins) { static normalisePlugins(loc, dirname, plugins) {
return plugins.map(function (val, i) { return plugins.map(function (val, i) {
let plugin, options; let plugin, options;
@ -99,17 +120,7 @@ export default class OptionManager {
} }
} }
if (!(plugin instanceof Plugin)) { plugin = OptionManager.normalisePlugin(plugin, loc, i);
// allow plugin containers to be specified so they don't have to manually require
if (typeof plugin === "function") {
plugin = OptionManager.memoisePluginContainer(plugin, loc, i);
} else {
throw new TypeError(messages.get("pluginNotFunction", loc, i));
}
}
// validate
plugin.validate(loc, i);
return [plugin, options]; return [plugin, options];
}); });

View File

@ -1,25 +0,0 @@
/* @flow */
import * as t from "babel-types";
export default function build(node: Object, buildBody: Function): ?Object {
let self = node.blocks.shift();
if (!self) return;
let child = build(node, buildBody);
if (!child) {
// last item
child = buildBody();
// add a filter as this is our final stop
if (node.filter) {
child = t.ifStatement(node.filter, t.blockStatement([child]));
}
}
return t.forOfStatement(
t.variableDeclaration("let", [t.variableDeclarator(self.left)]),
self.right,
t.blockStatement([child])
);
}

View File

@ -1,159 +0,0 @@
// Based upon the excellent jsx-transpiler by Inglet Stepanyan (RReverser)
// https://github.com/RReverser/jsx-transpiler
// jsx
import isString from "lodash/lang/isString";
import * as messages from "babel-messages";
import esutils from "esutils";
import { react } from "babel-types";
import * as t from "babel-types";
export default function (opts) {
let visitor = {};
visitor.JSXIdentifier = function (node) {
if (node.name === "this" && this.isReferenced()) {
return t.thisExpression();
} else if (esutils.keyword.isIdentifierNameES6(node.name)) {
node.type = "Identifier";
} else {
return t.stringLiteral(node.name);
}
};
visitor.JSXNamespacedName = function () {
throw this.errorWithNode(messages.get("JSXNamespacedTags"));
};
visitor.JSXMemberExpression = {
exit(node) {
node.computed = t.isLiteral(node.property);
node.type = "MemberExpression";
}
};
visitor.JSXExpressionContainer = function (node) {
return node.expression;
};
visitor.JSXAttribute = {
enter(node) {
let value = node.value;
if (t.isLiteral(value) && isString(value.value)) {
value.value = value.value.replace(/\n\s+/g, " ");
}
},
exit(node) {
let value = node.value || t.booleanLiteral(true);
return t.inherits(t.property("init", node.name, value), node);
}
};
visitor.JSXOpeningElement = {
exit(node, parent, scope, file) {
parent.children = react.buildChildren(parent);
let tagExpr = node.name;
let args = [];
let tagName;
if (t.isIdentifier(tagExpr)) {
tagName = tagExpr.name;
} else if (t.isLiteral(tagExpr)) {
tagName = tagExpr.value;
}
let state = {
tagExpr: tagExpr,
tagName: tagName,
args: args
};
if (opts.pre) {
opts.pre(state, file);
}
let attribs = node.attributes;
if (attribs.length) {
attribs = buildJSXOpeningElementAttributes(attribs, file);
} else {
attribs = t.nullLiteral();
}
args.push(attribs);
if (opts.post) {
opts.post(state, file);
}
return state.call || t.callExpression(state.callee, args);
}
};
/**
* The logic for this is quite terse. It's because we need to
* support spread elements. We loop over all attributes,
* breaking on spreads, we then push a new object containg
* all prior attributes to an array for later processing.
*/
let buildJSXOpeningElementAttributes = function (attribs, file) {
let _props = [];
let objs = [];
let pushProps = function () {
if (!_props.length) return;
objs.push(t.objectExpression(_props));
_props = [];
};
while (attribs.length) {
let prop = attribs.shift();
if (t.isJSXSpreadAttribute(prop)) {
pushProps();
objs.push(prop.argument);
} else {
_props.push(prop);
}
}
pushProps();
if (objs.length === 1) {
// only one object
attribs = objs[0];
} else {
// looks like we have multiple objects
if (!t.isObjectExpression(objs[0])) {
objs.unshift(t.objectExpression([]));
}
// spread it
attribs = t.callExpression(
file.addHelper("extends"),
objs
);
}
return attribs;
};
visitor.JSXElement = {
exit(node) {
let callExpr = node.openingElement;
callExpr.arguments = callExpr.arguments.concat(node.children);
if (callExpr.arguments.length >= 3) {
callExpr._prettyCall = true;
}
return t.inherits(callExpr, node);
}
};
return visitor;
}

View File

@ -1,36 +0,0 @@
/* @flow */
import type { Scope } from "babel-traverse";
import * as t from "babel-types";
let visitor = {
enter(path, state) {
if (path.isThisExpression() || path.isReferencedIdentifier({ name: "arguments" })) {
state.found = true;
path.stop();
}
},
Function(path) {
path.skip();
}
};
export default function (node: Object, scope: Scope) {
let container = t.functionExpression(null, [], node.body, node.generator, node.async);
let callee = container;
let args = [];
let state = { found: false };
scope.traverse(node, visitor, state);
if (state.found) {
callee = t.memberExpression(container, t.identifier("apply"));
args = [t.thisExpression(), t.identifier("arguments")];
}
let call = t.callExpression(callee, args);
if (node.generator) call = t.yieldExpression(call, true);
return t.returnStatement(call);
}

View File

@ -1,66 +0,0 @@
/* @flow */
import type { NodePath } from "babel-traverse";
import * as t from "babel-types";
let awaitVisitor = {
Function(path) {
path.skip();
},
AwaitExpression({ node }) {
node.type = "YieldExpression";
if (node.all) {
// await* foo; -> yield Promise.all(foo);
node.all = false;
node.argument = t.callExpression(t.memberExpression(t.identifier("Promise"), t.identifier("all")), [node.argument]);
}
}
};
let referenceVisitor = {
ReferencedIdentifier({ node, scope }, state) {
let name = state.id.name;
if (node.name === name && scope.bindingIdentifierEquals(name, state.id)) {
return state.ref = state.ref || scope.generateUidIdentifier(name);
}
}
};
export default function (path: NodePath, callId: Object) {
let node = path.node;
node.async = false;
node.generator = true;
path.traverse(awaitVisitor);
let call = t.callExpression(callId, [node]);
let id = node.id;
node.id = null;
if (t.isFunctionDeclaration(node)) {
let declar = t.variableDeclaration("let", [
t.variableDeclarator(id, call)
]);
declar._blockHoist = true;
return declar;
} else {
node.type = "FunctionExpression";
if (id) {
let state = { id, ref: null };
path.traverse(referenceVisitor, state);
if (state.ref) {
path.scope.parent.push({ id: state.ref });
return t.assignmentExpression("=", state.ref, call);
}
}
return call;
}
}

View File

@ -1,10 +0,0 @@
/* @flow */
import Pipeline from "./pipeline";
let pipeline = new Pipeline;
let transform = pipeline.transform.bind(pipeline);
transform.fromAst = pipeline.transformFromAst.bind(pipeline);
transform.lint = pipeline.lint.bind(pipeline);
transform.pipeline = pipeline;
export default transform;

View File

@ -6,12 +6,12 @@ import * as t from "babel-types";
export default new Plugin({ export default new Plugin({
visitor: { visitor: {
ThisExpression(path) { ThisExpression(path) {
return remap(path, "this", () => t.thisExpression()); remap(path, "this", () => t.thisExpression());
}, },
ReferencedIdentifier(path) { ReferencedIdentifier(path) {
if (path.node.name === "arguments") { if (path.node.name === "arguments") {
return remap(path, "arguments", () => t.identifier("arguments")); remap(path, "arguments", () => t.identifier("arguments"));
} }
} }
} }
@ -56,7 +56,7 @@ function remap(path, key, create) {
if (fnPath === currentFunction) return; if (fnPath === currentFunction) return;
let cached = fnPath.getData(key); let cached = fnPath.getData(key);
if (cached) return cached; if (cached) return path.replaceWith(cached);
let init = create(); let init = create();
let id = path.scope.generateUidIdentifier(key); let id = path.scope.generateUidIdentifier(key);
@ -64,5 +64,5 @@ function remap(path, key, create) {
fnPath.setData(key, id); fnPath.setData(key, id);
fnPath.scope.push({ id, init }); fnPath.scope.push({ id, init });
return id; return path.replaceWith(id);
} }

View File

@ -1,298 +0,0 @@
/* @flow */
import type { File, FileModulesMetadata } from "../file";
import type { Scope, NodePath } from "babel-traverse";
import * as metadataVisitor from "./lib/metadata";
import * as messages from "babel-messages";
import Remaps from "./lib/remaps";
import * as util from "../../util";
import * as t from "babel-types";
export default class DefaultFormatter {
constructor(file: File) {
// object containg all module sources with the scope that they're contained in
this.sourceScopes = Object.create(null);
// ids for use in module ids
this.defaultIds = Object.create(null);
this.ids = Object.create(null);
// contains reference aliases for live bindings
this.remaps = new Remaps(file, this);
this.scope = file.scope;
this.file = file;
this.hasNonDefaultExports = false;
this.hasLocalExports = false;
this.hasLocalImports = false;
this.localExports = Object.create(null);
this.localImports = Object.create(null);
this.metadata = file.metadata.modules;
this.getMetadata();
}
sourceScopes: Object;
defaultIds: Object;
ids: Object;
remaps: Remaps;
scope: Scope;
file: File;
hasNonDefaultExports: boolean;
hasLocalExports: boolean;
hasLocalImports: boolean;
localExports: Object;
localImports: Object;
metadata: FileModulesMetadata;
addScope(path: NodePath) {
let source = path.node.source && path.node.source.value;
if (!source) return;
let existingScope = this.sourceScopes[source];
if (existingScope && existingScope !== path.scope) {
throw path.buildCodeFrameError(messages.get("modulesDuplicateDeclarations"));
}
this.sourceScopes[source] = path.scope;
}
isModuleType(node: Object, type: string): boolean {
let modules = this.file.dynamicImportTypes[type];
return modules && modules.indexOf(node) >= 0;
}
transform() {
this.remapAssignments();
}
doDefaultExportInterop(node: Object): Object {
return (t.isExportDefaultDeclaration(node) || t.isSpecifierDefault(node)) && !this.noInteropRequireExport && !this.hasNonDefaultExports;
}
getMetadata() {
let has = false;
for (let node of (this.file.ast.program.body: Array<Object>)) {
if (t.isModuleDeclaration(node)) {
has = true;
break;
}
}
if (has) {
this.file.path.traverse(metadataVisitor, this);
}
}
remapAssignments() {
if (this.hasLocalExports || this.hasLocalImports) {
this.remaps.run();
}
}
remapExportAssignment(node: Object, exported: Array<Object>) {
let assign = node;
for (let prop of exported) {
assign = t.assignmentExpression(
"=",
t.memberExpression(t.identifier("exports"), prop),
assign
);
}
return assign;
}
_addExport(name: string, exported: Array<Object>) {
let info = this.localExports[name] = this.localExports[name] || {
binding: this.scope.getBindingIdentifier(name),
exported: []
};
info.exported.push(exported);
}
getExport(node: Object, scope: Scope) {
if (!t.isIdentifier(node)) return;
let local = this.localExports[node.name];
if (local && local.binding === scope.getBindingIdentifier(node.name)) {
return local.exported;
}
}
getModuleName(): string {
let opts = this.file.opts;
// moduleId is n/a if a `getModuleId()` is provided
if (opts.moduleId != null && !opts.getModuleId) {
return opts.moduleId;
}
let filenameRelative = opts.filenameRelative;
let moduleName = "";
if (opts.moduleRoot != null) {
moduleName = opts.moduleRoot + "/";
}
if (!opts.filenameRelative) {
return moduleName + opts.filename.replace(/^\//, "");
}
if (opts.sourceRoot != null) {
// remove sourceRoot from filename
let sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?");
filenameRelative = filenameRelative.replace(sourceRootRegEx, "");
}
if (!opts.keepModuleIdExtensions) {
// remove extension
filenameRelative = filenameRelative.replace(/\.(\w*?)$/, "");
}
moduleName += filenameRelative;
// normalize path separators
moduleName = moduleName.replace(/\\/g, "/");
if (opts.getModuleId) {
// If return is falsy, assume they want us to use our generated default name
return opts.getModuleId(moduleName) || moduleName;
} else {
return moduleName;
}
}
_pushStatement(ref: Object, nodes: Array<Object>): Object {
if (t.isClass(ref) || t.isFunction(ref)) {
if (ref.id) {
nodes.push(t.toStatement(ref));
ref = ref.id;
}
}
return ref;
}
_hoistExport(declar: Object, assign: Object, priority?: number): Object {
if (t.isFunctionDeclaration(declar)) {
assign._blockHoist = priority || 2;
}
return assign;
}
getExternalReference(node: Object, nodes: Array<Object>): Object {
let ids = this.ids;
let id = node.source.value;
if (ids[id]) {
return ids[id];
} else {
return this.ids[id] = this._getExternalReference(node, nodes);
}
}
_getExternalReference() {
throw new Error("Should be implemented");
}
checkExportIdentifier(node) {
if (t.isIdentifier(node, { name: "__esModule" })) {
throw this.file.buildCodeFrameError(node, messages.get("modulesIllegalExportName", node.name));
}
}
exportAllDeclaration(node: Object, nodes: Array<Object>) {
let ref = this.getExternalReference(node, nodes);
nodes.push(this.buildExportsWildcard(ref, node));
}
exportSpecifier(specifier: Object, node: Object, nodes: Array<Object>) {
if (node.source) {
let ref = this.getExternalReference(node, nodes);
if (specifier.local.name === "default" && !this.noInteropRequireExport) {
// importing a default so we need to normalize it
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
} else {
ref = t.memberExpression(ref, specifier.local);
nodes.push(this.buildExportsFromAssignment(specifier.exported, ref, node));
return;
}
// export { foo } from "test";
nodes.push(this.buildExportsAssignment(specifier.exported, ref, node));
} else {
// export { foo };
nodes.push(this.buildExportsAssignment(specifier.exported, specifier.local, node));
}
}
buildExportsWildcard(objectIdentifier: Object) {
return t.expressionStatement(t.callExpression(this.file.addHelper("defaults"), [
t.identifier("exports"),
t.callExpression(this.file.addHelper("interop-export-wildcard"), [
objectIdentifier,
this.file.addHelper("defaults")
])
]));
}
buildExportsFromAssignment(id: Object, init: Object) {
this.checkExportIdentifier(id);
return util.template("exports-from-assign", {
INIT: init,
ID: t.stringLiteral(id.name)
}, true);
}
buildExportsAssignment(id, init) {
this.checkExportIdentifier(id);
return util.template("exports-assign", {
VALUE: init,
KEY: id
}, true);
}
exportDeclaration(node: Object, nodes: Array<Object>) {
let declar = node.declaration;
let id = declar.id;
if (t.isExportDefaultDeclaration(node)) {
id = t.identifier("default");
}
let assign;
if (t.isVariableDeclaration(declar)) {
for (let i = 0; i < declar.declarations.length; i++) {
let decl = declar.declarations[i];
decl.init = this.buildExportsAssignment(decl.id, decl.init, node).expression;
let newDeclar = t.variableDeclaration(declar.kind, [decl]);
if (i === 0) t.inherits(newDeclar, declar);
nodes.push(newDeclar);
}
} else {
let ref = declar;
if (t.isFunctionDeclaration(declar) || t.isClassDeclaration(declar)) {
ref = declar.id;
nodes.push(declar);
}
assign = this.buildExportsAssignment(id, ref, node);
nodes.push(assign);
this._hoistExport(declar, assign);
}
}
}

View File

@ -1,15 +0,0 @@
/* @flow */
import * as util from "../../util";
export default function (Parent: Function): Function {
function Constructor() {
this.noInteropRequireImport = true;
this.noInteropRequireExport = true;
Parent.apply(this, arguments);
}
util.inherits(Constructor, Parent);
return Constructor;
}

View File

@ -1,6 +0,0 @@
/* @flow */
import AMDFormatter from "./amd";
import buildStrict from "./_strict";
export default buildStrict(AMDFormatter);

View File

@ -1,145 +0,0 @@
/* @flow */
import DefaultFormatter from "./_default";
import CommonFormatter from "./common";
import includes from "lodash/collection/includes";
import values from "lodash/object/values";
import * as util from "../../util";
import * as t from "babel-types";
export default class AMDFormatter extends DefaultFormatter {
setup() {
CommonFormatter.prototype._setup.call(this, this.hasNonDefaultExports);
}
buildDependencyLiterals() {
let names = [];
for (let name in this.ids) {
names.push(t.stringLiteral(name));
}
return names;
}
/**
* Wrap the entire body in a `define` wrapper.
*/
transform(program) {
CommonFormatter.prototype.transform.apply(this, arguments);
let body = program.body;
// build an array of module names
let names = [t.stringLiteral("exports")];
if (this.passModuleArg) names.push(t.stringLiteral("module"));
names = names.concat(this.buildDependencyLiterals());
names = t.arrayExpression(names);
// build up define container
let params = values(this.ids);
if (this.passModuleArg) params.unshift(t.identifier("module"));
params.unshift(t.identifier("exports"));
let container = t.functionExpression(null, params, t.blockStatement(body));
let defineArgs = [names, container];
let moduleName = this.getModuleName();
if (moduleName) defineArgs.unshift(t.stringLiteral(moduleName));
let call = t.callExpression(t.identifier("define"), defineArgs);
program.body = [t.expressionStatement(call)];
}
/**
* Get the AMD module name that we'll prepend to the wrapper
* to define this module
*/
getModuleName() {
if (this.file.opts.moduleIds) {
return DefaultFormatter.prototype.getModuleName.apply(this, arguments);
} else {
return null;
}
}
_getExternalReference(node) {
return this.scope.generateUidIdentifier(node.source.value);
}
importDeclaration(node) {
this.getExternalReference(node);
}
importSpecifier(specifier, node, nodes, scope) {
let key = node.source.value;
let ref = this.getExternalReference(node);
if (t.isImportNamespaceSpecifier(specifier) || t.isImportDefaultSpecifier(specifier)) {
this.defaultIds[key] = specifier.local;
}
if (this.isModuleType(node, "absolute")) {
// absolute module reference
} else if (this.isModuleType(node, "absoluteDefault")) {
// prevent unnecessary renaming of dynamic imports
this.ids[node.source.value] = ref;
ref = t.memberExpression(ref, t.identifier("default"));
} else if (t.isImportNamespaceSpecifier(specifier)) {
// import * as bar from "foo";
} else if (!includes(this.file.dynamicImported, node) && t.isSpecifierDefault(specifier) && !this.noInteropRequireImport) {
// import foo from "foo";
let uid = scope.generateUidIdentifier(specifier.local.name);
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(uid, t.callExpression(this.file.addHelper("interop-require-default"), [ref]))
]));
ref = t.memberExpression(uid, t.identifier("default"));
} else {
// import { foo } from "foo";
let imported = specifier.imported;
if (t.isSpecifierDefault(specifier)) imported = t.identifier("default");
ref = t.memberExpression(ref, imported);
}
this.remaps.add(scope, specifier.local.name, ref);
}
exportSpecifier(specifier, node, nodes) {
if (this.doDefaultExportInterop(specifier)) {
this.passModuleArg = true;
if (specifier.exported !== specifier.local && !node.source) {
nodes.push(util.template("exports-default-assign", {
VALUE: specifier.local
}, true));
return;
}
}
CommonFormatter.prototype.exportSpecifier.apply(this, arguments);
}
exportDeclaration(node, nodes) {
if (this.doDefaultExportInterop(node)) {
this.passModuleArg = true;
let declar = node.declaration;
let assign = util.template("exports-default-assign", {
VALUE: this._pushStatement(declar, nodes)
}, true);
if (t.isFunctionDeclaration(declar)) {
// we can hoist this assignment to the top of the file
assign._blockHoist = 3;
}
nodes.push(assign);
return;
}
DefaultFormatter.prototype.exportDeclaration.apply(this, arguments);
}
}

View File

@ -1,6 +0,0 @@
/* @flow */
import CommonFormatter from "./common";
import buildStrict from "./_strict";
export default buildStrict(CommonFormatter);

View File

@ -1,123 +0,0 @@
import DefaultFormatter from "./_default";
import * as util from "../../util";
import * as t from "babel-types";
export default class CommonJSFormatter extends DefaultFormatter {
setup() {
this._setup(this.hasLocalExports);
}
_setup(conditional) {
let file = this.file;
let scope = file.scope;
scope.rename("module");
scope.rename("exports");
if (!this.noInteropRequireImport && conditional) {
let templateName = "exports-module-declaration";
if (this.file.isLoose("es6.modules")) templateName += "-loose";
let declar = util.template(templateName, true);
declar._blockHoist = 3;
file.path.unshiftContainer("body", [declar]);
}
}
transform(program) {
DefaultFormatter.prototype.transform.apply(this, arguments);
if (this.hasDefaultOnlyExport) {
program.body.push(
t.expressionStatement(t.assignmentExpression(
"=",
t.memberExpression(t.identifier("module"), t.identifier("exports")),
t.memberExpression(t.identifier("exports"), t.identifier("default"))
))
);
}
}
importSpecifier(specifier, node, nodes, scope) {
let variableName = specifier.local;
let ref = this.getExternalReference(node, nodes);
// import foo from "foo";
if (t.isSpecifierDefault(specifier)) {
if (this.isModuleType(node, "absolute")) {
// absolute module reference
} else if (this.isModuleType(node, "absoluteDefault")) {
this.remaps.add(scope, variableName.name, ref);
} else if (this.noInteropRequireImport) {
this.remaps.add(scope, variableName.name, t.memberExpression(ref, t.identifier("default")));
} else {
let uid = this.scope.generateUidIdentifierBasedOnNode(node, "import");
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(uid, t.callExpression(this.file.addHelper("interop-require-default"), [ref]))
]));
this.remaps.add(scope, variableName.name, t.memberExpression(uid, t.identifier("default")));
}
} else {
if (t.isImportNamespaceSpecifier(specifier)) {
if (!this.noInteropRequireImport) {
ref = t.callExpression(this.file.addHelper("interop-require-wildcard"), [ref]);
}
// import * as bar from "foo";
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(variableName, ref)
]));
} else {
// import { foo } from "foo";
this.remaps.add(scope, variableName.name,
t.memberExpression(ref, t.identifier(specifier.imported.name)));
}
}
}
importDeclaration(node, nodes) {
// import "foo";
nodes.push(util.template("require", {
MODULE_NAME: node.source
}, true));
}
exportSpecifier(specifier) {
if (this.doDefaultExportInterop(specifier)) {
this.hasDefaultOnlyExport = true;
}
DefaultFormatter.prototype.exportSpecifier.apply(this, arguments);
}
exportDeclaration(node) {
if (this.doDefaultExportInterop(node)) {
this.hasDefaultOnlyExport = true;
}
DefaultFormatter.prototype.exportDeclaration.apply(this, arguments);
}
_getExternalReference(node, nodes) {
let call = t.callExpression(t.identifier("require"), [node.source]);
let uid;
if (this.isModuleType(node, "absolute")) {
// absolute module reference
} else if (this.isModuleType(node, "absoluteDefault")) {
call = t.memberExpression(call, t.identifier("default"));
} else {
uid = this.scope.generateUidIdentifierBasedOnNode(node, "import");
}
uid = uid || node.specifiers[0].local;
let declar = t.variableDeclaration("var", [
t.variableDeclarator(uid, call)
]);
nodes.push(declar);
return uid;
}
}

View File

@ -1,17 +0,0 @@
/* @flow */
import DefaultFormatter from "./_default";
import * as t from "babel-types";
export default class IgnoreFormatter extends DefaultFormatter {
exportDeclaration(node, nodes) {
let declar = t.toStatement(node.declaration, true);
if (declar) nodes.push(t.inherits(declar, node));
}
exportAllDeclaration() {}
importDeclaration() {}
importSpecifier() {}
exportSpecifier() {}
transform() {}
}

View File

@ -1,16 +0,0 @@
/* @flow */
/**
* [Please add a description.]
*/
export default {
commonStrict: require("./common-strict"),
amdStrict: require("./amd-strict"),
umdStrict: require("./umd-strict"),
common: require("./common"),
system: require("./system"),
ignore: require("./ignore"),
amd: require("./amd"),
umd: require("./umd")
};

View File

@ -1,124 +0,0 @@
/* @flow */
import * as t from "babel-types";
let remapVisitor = {
enter(node) {
if (node._skipModulesRemap) {
return this.skip();
}
},
ReferencedIdentifier(node, parent, scope, remaps) {
let { formatter } = remaps;
let remap = remaps.get(scope, node.name);
if (!remap || node === remap) return;
if (!scope.hasBinding(node.name) ||
scope.bindingIdentifierEquals(node.name, formatter.localImports[node.name])) {
if (!formatter.isLoose() && this.key === "callee" && this.parentPath.isCallExpression()) {
return t.sequenceExpression([t.numberLiteral(0), remap]);
} else {
return remap;
}
}
},
AssignmentExpression: {
exit(node, parent, scope, { formatter }) {
if (!node._ignoreModulesRemap) {
let exported = formatter.getExport(node.left, scope);
if (exported) {
return formatter.remapExportAssignment(node, exported);
}
}
}
},
UpdateExpression(node, parent, scope, { formatter }) {
let exported = formatter.getExport(node.argument, scope);
if (!exported) return;
this.skip();
// expand to long file assignment expression
let assign = t.assignmentExpression(node.operator[0] + "=", node.argument, t.numberLiteral(1));
// remap this assignment expression
let remapped = formatter.remapExportAssignment(assign, exported);
// we don't need to change the result
if (t.isExpressionStatement(parent) || node.prefix) {
return remapped;
}
let nodes = [];
nodes.push(remapped);
let operator;
if (node.operator === "--") {
operator = "+";
} else { // "++"
operator = "-";
}
nodes.push(t.binaryExpression(operator, node.argument, t.numberLiteral(1)));
return t.sequenceExpression(nodes);
}
};
export default class Remaps {
constructor(file, formatter) {
this.formatter = formatter;
this.file = file;
}
run() {
this.file.path.traverse(remapVisitor, this);
}
_getKey(name) {
return `${name}:moduleRemap`;
}
get(scope, name) {
return scope.getData(this._getKey(name));
}
add(scope, name, val) {
if (this.all) {
this.all.push({
name,
scope,
node: val
});
}
return scope.setData(this._getKey(name), val);
}
remove(scope, name) {
return scope.removeData(this._getKey(name));
}
/**
* These methods are used by the system module formatter who needs access to all the remaps
* so it can process them into it's specific setter method. We don't do this by default since
* no other module formatters need access to this.
*/
getAll() {
return this.all;
}
clearAll() {
if (this.all) {
for (let remap of (this.all: Array)) {
remap.scope.removeData(this._getKey(remap.name));
}
}
this.all = [];
}
}

View File

@ -1,226 +0,0 @@
/* @flow */
import DefaultFormatter from "./_default";
import AMDFormatter from "./amd";
import * as util from "../../util";
import last from "lodash/array/last";
import map from "lodash/collection/map";
import * as t from "babel-types";
let hoistVariablesVisitor = {
Function(path) {
// nothing inside is accessible
path.skip();
},
VariableDeclaration({ node, parent }, state) {
if (node.kind !== "var" && !t.isProgram(parent)) { // let, const
// can't be accessed
return;
}
// ignore block hoisted nodes as these can be left in
if (state.formatter._canHoist(node)) return;
let nodes = [];
for (let i = 0; i < node.declarations.length; i++) {
let declar = node.declarations[i];
state.hoistDeclarators.push(t.variableDeclarator(declar.id));
if (declar.init) {
// no initializer so we can just hoist it as-is
let assign = t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init));
nodes.push(assign);
}
}
// for (let i in test)
if (t.isFor(parent) && parent.left === node) {
return node.declarations[0].id;
}
return nodes;
}
};
let hoistFunctionsVisitor = {
Function(path) {
path.skip();
},
enter(path, state) {
if (path.isFunctionDeclaration() || state.formatter._canHoist(path.node)) {
state.handlerBody.push(path.node);
path.remove();
}
}
};
let runnerSettersVisitor = {
enter(path, state) {
let { node } = path;
if (node._importSource === state.source) {
if (t.isVariableDeclaration(node)) {
for (let declar of (node.declarations: Array)) {
state.hoistDeclarators.push(t.variableDeclarator(declar.id));
state.nodes.push(t.expressionStatement(
t.assignmentExpression("=", declar.id, declar.init)
));
}
} else {
state.nodes.push(node);
}
path.remove();
}
}
};
export default class SystemFormatter extends AMDFormatter {
constructor(file) {
super(file);
this._setters = null;
this.exportIdentifier = file.scope.generateUidIdentifier("export");
this.noInteropRequireExport = true;
this.noInteropRequireImport = true;
this.remaps.clearAll();
}
_addImportSource(node, exportNode) {
if (node) node._importSource = exportNode.source && exportNode.source.value;
return node;
}
buildExportsWildcard(objectIdentifier, node) {
let leftIdentifier = this.scope.generateUidIdentifier("key");
let valIdentifier = t.memberExpression(objectIdentifier, leftIdentifier, true);
let left = t.variableDeclaration("var", [
t.variableDeclarator(leftIdentifier)
]);
let right = objectIdentifier;
let block = t.blockStatement([
t.ifStatement(
t.binaryExpression("!==", leftIdentifier, t.stringLiteral("default")),
t.expressionStatement(this._buildExportCall(leftIdentifier, valIdentifier))
)
]);
return this._addImportSource(t.forInStatement(left, right, block), node);
}
buildExportsAssignment(id, init, node) {
let call = this._buildExportCall(t.stringLiteral(id.name), init, true);
return this._addImportSource(call, node);
}
buildExportsFromAssignment() {
return this.buildExportsAssignment(...arguments);
}
remapExportAssignment(node, exported) {
let assign = node;
for (let i = 0; i < exported.length; i++) {
assign = this._buildExportCall(t.stringLiteral(exported[i].name), assign);
}
return assign;
}
_buildExportCall(id, init, isStatement) {
let call = t.callExpression(this.exportIdentifier, [id, init]);
if (isStatement) {
return t.expressionStatement(call);
} else {
return call;
}
}
importSpecifier(specifier, node, nodes) {
AMDFormatter.prototype.importSpecifier.apply(this, arguments);
for (let remap of (this.remaps.getAll(): Array)) {
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(t.identifier(remap.name), remap.node)
]));
}
this.remaps.clearAll();
this._addImportSource(last(nodes), node);
}
_buildRunnerSetters(block, hoistDeclarators) {
let scope = this.file.scope;
return t.arrayExpression(map(this.ids, function (uid, source) {
let state = {
hoistDeclarators: hoistDeclarators,
source: source,
nodes: []
};
scope.traverse(block, runnerSettersVisitor, state);
return t.functionExpression(null, [uid], t.blockStatement(state.nodes));
}));
}
_canHoist(node) {
return node._blockHoist && !this.file.dynamicImports.length;
}
transform(program) {
DefaultFormatter.prototype.transform.apply(this, arguments);
let hoistDeclarators = [];
let moduleName = this.getModuleName();
let moduleNameLiteral = t.stringLiteral(moduleName);
let block = t.blockStatement(program.body);
let setterListNode = this._buildRunnerSetters(block, hoistDeclarators);
this._setters = setterListNode;
let runner = util.template("system", {
MODULE_DEPENDENCIES: t.arrayExpression(this.buildDependencyLiterals()),
EXPORT_IDENTIFIER: this.exportIdentifier,
MODULE_NAME: moduleNameLiteral,
SETTERS: setterListNode,
EXECUTE: t.functionExpression(null, [], block)
}, true);
let handlerBody = runner.expression.arguments[2].body.body;
if (!moduleName) runner.expression.arguments.shift();
let returnStatement = handlerBody.pop();
// hoist up all variable declarations
this.file.scope.traverse(block, hoistVariablesVisitor, {
formatter: this,
hoistDeclarators: hoistDeclarators
});
if (hoistDeclarators.length) {
let hoistDeclar = t.variableDeclaration("var", hoistDeclarators);
hoistDeclar._blockHoist = true;
handlerBody.unshift(hoistDeclar);
}
// hoist up function declarations for circular references
this.file.scope.traverse(block, hoistFunctionsVisitor, {
formatter: this,
handlerBody: handlerBody
});
handlerBody.push(returnStatement);
program.body = [runner];
}
}

View File

@ -1,6 +0,0 @@
/* @flow */
import UMDFormatter from "./umd";
import buildStrict from "./_strict";
export default buildStrict(UMDFormatter);

View File

@ -1,85 +0,0 @@
/* @flow */
import DefaultFormatter from "./_default";
import AMDFormatter from "./amd";
import values from "lodash/object/values";
import path from "path";
import * as util from "../../util";
import * as t from "babel-types";
export default class UMDFormatter extends AMDFormatter {
transform(program) {
DefaultFormatter.prototype.transform.apply(this, arguments);
let body = program.body;
// build an array of module names
let names = [];
for (let name in this.ids) {
names.push(t.stringLiteral(name));
}
// factory
let ids = values(this.ids);
let args = [t.identifier("exports")];
if (this.passModuleArg) args.push(t.identifier("module"));
args = args.concat(ids);
let factory = t.functionExpression(null, args, t.blockStatement(body));
// amd
let defineArgs = [t.stringLiteral("exports")];
if (this.passModuleArg) defineArgs.push(t.stringLiteral("module"));
defineArgs = defineArgs.concat(names);
defineArgs = [t.arrayExpression(defineArgs)];
// common
let testExports = util.template("test-exports");
let testModule = util.template("test-module");
let commonTests = this.passModuleArg ? t.logicalExpression("&&", testExports, testModule) : testExports;
let commonArgs = [t.identifier("exports")];
if (this.passModuleArg) commonArgs.push(t.identifier("module"));
commonArgs = commonArgs.concat(names.map(function (name) {
return t.callExpression(t.identifier("require"), [name]);
}));
// globals
let browserArgs = [];
if (this.passModuleArg) browserArgs.push(t.identifier("mod"));
for (let name in this.ids) {
let id = this.defaultIds[name] || t.identifier(t.toIdentifier(path.basename(name, path.extname(name))));
browserArgs.push(t.memberExpression(t.identifier("global"), id));
}
//
let moduleName = this.getModuleName();
if (moduleName) defineArgs.unshift(t.stringLiteral(moduleName));
//
let globalArg = this.file.opts.basename;
if (moduleName) globalArg = moduleName;
globalArg = t.identifier(t.toIdentifier(globalArg));
let runner = util.template("umd-runner-body", {
AMD_ARGUMENTS: defineArgs,
COMMON_TEST: commonTests,
COMMON_ARGUMENTS: commonArgs,
BROWSER_ARGUMENTS: browserArgs,
GLOBAL_ARG: globalArg
});
//
program.body = [t.expressionStatement(
t.callExpression(runner, [t.thisExpression(), factory])
)];
}
}

View File

@ -1,11 +1,13 @@
/* @flow */ /* @flow */
import type Plugin from "./plugin"; import type Plugin from "./plugin";
import Store from "../store";
import traverse from "babel-traverse"; import traverse from "babel-traverse";
import File from "./file"; import File from "./file";
export default class PluginPass { export default class PluginPass extends Store {
constructor(file: File, plugin: Plugin, options: Object = {}) { constructor(file: File, plugin: Plugin, options: Object = {}) {
super();
this.plugin = plugin; this.plugin = plugin;
this.file = file; this.file = file;
this.opts = options; this.opts = options;
@ -25,4 +27,16 @@ export default class PluginPass {
addHelper(...args) { addHelper(...args) {
return this.file.addHelper(...args); return this.file.addHelper(...args);
} }
addImport(...args) {
return this.file.addImport(...args);
}
getModuleName(...args) {
return this.file.getModuleName(...args);
}
buildCodeFrameError(...args) {
return this.file.buildCodeFrameError(...args);
}
} }

View File

@ -1,33 +1,79 @@
/* @flow */ /* @flow */
import OptionManager from "./file/options/option-manager"
import * as messages from "babel-messages"; import * as messages from "babel-messages";
import Store from "../store";
import traverse from "babel-traverse"; import traverse from "babel-traverse";
import assign from "lodash/object/assign"; import assign from "lodash/object/assign";
import clone from "lodash/lang/clone"; import clone from "lodash/lang/clone";
export default class Plugin { export default class Plugin extends Store {
constructor(plugin: Object) { constructor(plugin: Object) {
plugin = this.raw = assign({}, plugin); super();
function take(key) { this.initialized = false;
let val = plugin[key]; this.raw = assign({}, plugin);
delete plugin[key];
return val;
}
this.manipulateOptions = take("manipulateOptions"); this.manipulateOptions = this.take("manipulateOptions");
this.post = take("post"); this.post = this.take("post");
this.pre = take("pre"); this.pre = this.take("pre");
this.visitor = this.normalize(clone(take("visitor")) || {}); this.visitor = this.normalize(clone(this.take("visitor")) || {});
} }
initialized: boolean;
raw: Object; raw: Object;
manipulateOptions: ?Function; manipulateOptions: ?Function;
post: ?Function; post: ?Function;
pre: ?Function; pre: ?Function;
visitor: Object; visitor: Object;
validate(loc: string, i: number) { take(key) {
let val = this.raw[key];
delete this.raw[key];
return val;
}
chain(target, key) {
if (!target[key]) return this[key];
if (!this[key]) return target[key];
let fns: Array<?Function> = [target[key], this[key]];
return function (...args) {
let val;
for (let fn of fns) {
if (fn) {
let ret = fn.apply(this, args);
if (ret != null) val = ret;
}
}
return val;
};
}
maybeInherit(loc: string) {
let inherits = this.take("inherits");
if (!inherits) return;
inherits = OptionManager.normalisePlugin(inherits, loc, "inherits");
this.manipulateOptions = this.chain(inherits, "manipulateOptions");
this.post = this.chain(inherits, "post");
this.pre = this.chain(inherits, "pre");
this.visitor = traverse.visitors.merge([inherits.visitor, this.visitor]);
}
/**
* We lazy initialise parts of a plugin that rely on contextual information such as
* position on disk and how it was specified.
*/
init(loc: string, i: number) {
if (this.initialized) return;
this.initialized = true;
this.maybeInherit(loc);
for (let key in this.raw) { for (let key in this.raw) {
throw new Error(messages.get("pluginInvalidProperty", loc, i, key)); throw new Error(messages.get("pluginInvalidProperty", loc, i, key));
} }

View File

@ -1,4 +0,0 @@
{
"blacklist": ["useStrict", "es6.blockScoping", "regenerator", "es6.spread"],
"loose": ["es6.modules"]
}

View File

@ -1 +0,0 @@
PROPERTY[Symbol.referenceGet](OBJECT).call(OBJECT)

View File

@ -1 +0,0 @@
PROPERTY[Symbol.referenceDelete](OBJECT)

View File

@ -1 +0,0 @@
PROPERTY[Symbol.referenceGet](OBJECT)

View File

@ -1 +0,0 @@
PROPERTY[Symbol.referenceSet](OBJECT, VALUE)

View File

@ -1 +0,0 @@
Array.from(VALUE);

View File

@ -1 +0,0 @@
OBJECT.call(CONTEXT);

View File

@ -1 +0,0 @@
exports.KEY = VALUE;

View File

@ -1 +0,0 @@
module.exports = VALUE;

View File

@ -1,6 +0,0 @@
Object.defineProperty(exports, ID, {
enumerable: true,
get: function () {
return INIT;
}
});

View File

@ -1,3 +0,0 @@
Object.defineProperty(exports, "__esModule", {
value: true
});

View File

@ -1,28 +0,0 @@
(function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
var callNext = step.bind(null, "next");
var callThrow = step.bind(null, "throw");
function step(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(callNext, callThrow);
}
}
callNext();
});
};
})

View File

@ -1 +0,0 @@
Function.prototype.bind

View File

@ -1,5 +0,0 @@
(function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
});

View File

@ -1,17 +0,0 @@
(function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i ++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
})()

View File

@ -1,42 +0,0 @@
(function() {
function defineProperties(target, descriptors, initializers) {
for (var i = 0; i < descriptors.length; i ++) {
var descriptor = descriptors[i];
var decorators = descriptor.decorators;
var key = descriptor.key;
// don't want to expose these to userland since i know people will rely on them
// and think it's spec behaviour
delete descriptor.key;
delete descriptor.decorators;
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor || descriptor.initializer) descriptor.writable = true;
if (decorators) {
for (var f = 0; f < decorators.length; f++) {
var decorator = decorators[f];
if (typeof decorator === "function") {
descriptor = decorator(target, key, descriptor) || descriptor;
} else {
throw new TypeError("The decorator for method " + descriptor.key + " is of the invalid type " + typeof decorator);
}
}
if (descriptor.initializer !== undefined) {
initializers[key] = descriptor;
continue;
}
}
Object.defineProperty(target, key, descriptor);
}
}
return function (Constructor, protoProps, staticProps, protoInitializers, staticInitializers) {
if (protoProps) defineProperties(Constructor.prototype, protoProps, protoInitializers);
if (staticProps) defineProperties(Constructor, staticProps, staticInitializers);
return Constructor;
};
})()

View File

@ -1,37 +0,0 @@
(function (descriptors) {
var target = {};
for (var i = 0; i < descriptors.length; i ++) {
var descriptor = descriptors[i];
var decorators = descriptor.decorators;
var key = descriptor.key;
// don't want to expose these to userland since i know people will rely on them
// and think it's spec behaviour
delete descriptor.key;
delete descriptor.decorators;
descriptor.enumerable = true;
descriptor.configurable = true;
if ("value" in descriptor || descriptor.initializer) descriptor.writable = true;
if (decorators) {
for (var f = 0; f < decorators.length; f++) {
var decorator = decorators[f];
if (typeof decorator === "function") {
descriptor = decorator(target, key, descriptor) || descriptor;
} else {
throw new TypeError("The decorator for method " + descriptor.key + " is of the invalid type " + typeof decorator);
}
}
}
if (descriptor.initializer) {
descriptor.value = descriptor.initializer.call(target);
}
Object.defineProperty(target, key, descriptor);
}
return target;
})

View File

@ -1,10 +0,0 @@
(function (defaultProps, props) {
if (defaultProps) {
for (var propName in defaultProps) {
if (typeof props[propName] === "undefined") {
props[propName] = defaultProps[propName];
}
}
}
return props;
})

View File

@ -1,11 +0,0 @@
(function (obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = Object.getOwnPropertyDescriptor(defaults, key);
if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}
return obj;
})

View File

@ -1,13 +0,0 @@
(function (target, key, descriptors) {
var _descriptor = descriptors[key];
if (!_descriptor) return;
// clone it
var descriptor = {};
for (var _key in _descriptor) descriptor[_key] = _descriptor[_key];
// initialize it
descriptor.value = descriptor.initializer ? descriptor.initializer.call(target) : undefined;
Object.defineProperty(target, key, descriptor);
})

View File

@ -1,18 +0,0 @@
(function (obj, key, value) {
// Shortcircuit the slow defineProperty path when possible.
// We are trying to avoid issues where setters defined on the
// prototype cause side effects under the fast path of simple
// assignment. By checking for existence of the property with
// the in operator, we can optimize most of this overhead away.
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
});

View File

@ -1,11 +0,0 @@
Object.assign || (function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
})

View File

@ -1,25 +0,0 @@
(function get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
});

View File

@ -1 +0,0 @@
Object.prototype.hasOwnProperty;

View File

@ -1,14 +0,0 @@
(function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
})

View File

@ -1,7 +0,0 @@
(function (left, right) {
if (right != null && right[Symbol.hasInstance]) {
return right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
});

View File

@ -1,5 +0,0 @@
(function (obj, defaults) {
var newObj = defaults({}, obj);
delete newObj.default;
return newObj;
})

View File

@ -1,3 +0,0 @@
(function (obj) {
return obj && obj.__esModule ? obj : { default: obj };
})

View File

@ -1,14 +0,0 @@
(function (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)) newObj[key] = obj[key];
}
}
newObj.default = obj;
return newObj;
}
})

View File

@ -1,3 +0,0 @@
(function (obj) {
return obj && obj.__esModule ? obj.default : obj;
})

View File

@ -1,5 +0,0 @@
(function (innerThis, boundThis) {
if (innerThis !== boundThis) {
throw new TypeError("Cannot instantiate an arrow function");
}
});

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