Merge branch '7.0' into fix-require-debug

This commit is contained in:
Sven SAULEAU
2017-03-11 12:17:04 +01:00
703 changed files with 14486 additions and 6482 deletions

View File

@@ -1,32 +1,39 @@
{
"name": "babel-cli",
"version": "6.18.0",
"version": "7.0.0-alpha.2",
"description": "Babel command line.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
"license": "MIT",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-cli",
"keywords": [
"6to5",
"babel",
"es6",
"transpile",
"transpiler",
"babel-cli",
"compiler"
],
"dependencies": {
"babel-core": "^6.18.0",
"babel-register": "^6.18.0",
"babel-polyfill": "^6.16.0",
"babel-runtime": "^6.9.0",
"babel-core": "7.0.0-alpha.2",
"babel-register": "7.0.0-alpha.2",
"babel-polyfill": "7.0.0-alpha.1",
"commander": "^2.8.1",
"convert-source-map": "^1.1.0",
"fs-readdir-recursive": "^1.0.0",
"glob": "^5.0.5",
"glob": "^7.0.0",
"lodash": "^4.2.0",
"output-file-sync": "^1.1.0",
"path-is-absolute": "^1.0.0",
"slash": "^1.0.0",
"source-map": "^0.5.0",
"v8flags": "^2.0.10"
},
"optionalDependencies": {
"chokidar": "^1.0.0"
"chokidar": "^1.6.1"
},
"devDependencies": {
"babel-helper-fixtures": "^6.18.0"
"babel-helper-fixtures": "7.0.0-alpha.1"
},
"bin": {
"babel-doctor": "./bin/babel-doctor.js",

View File

@@ -1,4 +1,3 @@
import pathIsAbsolute from "path-is-absolute";
import commander from "commander";
import Module from "module";
import { inspect } from "util";
@@ -7,11 +6,12 @@ import repl from "repl";
import { util } from "babel-core";
import * as babel from "babel-core";
import vm from "vm";
import _ from "lodash";
import "babel-polyfill";
import register from "babel-register";
let program = new commander.Command("babel-node");
import pkg from "../package.json";
const program = new commander.Command("babel-node");
program.option("-e, --eval [script]", "Evaluate script");
program.option("-p, --print [code]", "Evaluate script and print result");
@@ -21,7 +21,6 @@ program.option("-x, --extensions [extensions]", "List of extensions to hook into
program.option("-w, --plugins [string]", "", util.list);
program.option("-b, --presets [string]", "", util.list);
let pkg = require("../package.json");
program.version(pkg.version);
program.usage("[options] [ -e script | script.js ] [arguments]");
program.parse(process.argv);
@@ -30,15 +29,15 @@ program.parse(process.argv);
register({
extensions: program.extensions,
ignore: program.ignore,
only: program.only,
plugins: program.plugins,
presets: program.presets,
ignore: program.ignore,
only: program.only,
plugins: program.plugins,
presets: program.presets,
});
//
let replPlugin = ({ types: t }) => ({
const replPlugin = ({ types: t }) => ({
visitor: {
ModuleDeclaration(path) {
throw path.buildCodeFrameError("Modules aren't supported in the REPL");
@@ -56,24 +55,24 @@ let replPlugin = ({ types: t }) => ({
// If the executed code doesn't evaluate to a value,
// prevent implicit strict mode from printing 'use strict'.
path.pushContainer("body", t.expressionStatement(t.identifier("undefined")));
}
}
},
},
});
//
let _eval = function (code, filename) {
const _eval = function (code, filename) {
code = code.trim();
if (!code) return undefined;
code = babel.transform(code, {
filename: filename,
presets: program.presets,
plugins: (program.plugins || []).concat([replPlugin])
plugins: (program.plugins || []).concat([replPlugin]),
}).code;
return vm.runInThisContext(code, {
filename: filename
filename: filename,
});
};
@@ -84,17 +83,17 @@ if (program.eval || program.print) {
global.__filename = "[eval]";
global.__dirname = process.cwd();
let module = new Module(global.__filename);
const module = new Module(global.__filename);
module.filename = global.__filename;
module.paths = Module._nodeModulePaths(global.__dirname);
module.paths = Module._nodeModulePaths(global.__dirname);
global.exports = module.exports;
global.module = module;
global.module = module;
global.require = module.require.bind(module);
let result = _eval(code, global.__filename);
const result = _eval(code, global.__filename);
if (program.print) {
let output = _.isString(result) ? result : inspect(result);
const output = typeof result === "string" ? result : inspect(result);
process.stdout.write(output + "\n");
}
} else {
@@ -104,27 +103,27 @@ if (program.eval || program.print) {
let i = 0;
let ignoreNext = false;
_.each(args, function (arg, i2) {
args.some(function (arg, i2) {
if (ignoreNext) {
ignoreNext = false;
return;
}
if (arg[0] === "-") {
let parsedArg = program[arg.slice(2)];
const parsedArg = program[arg.slice(2)];
if (parsedArg && parsedArg !== true) {
ignoreNext = true;
}
} else {
i = i2;
return false;
return true;
}
});
args = args.slice(i);
// make the filename absolute
let filename = args[0];
if (!pathIsAbsolute(filename)) args[0] = path.join(process.cwd(), filename);
const filename = args[0];
if (!path.isAbsolute(filename)) args[0] = path.join(process.cwd(), filename);
// add back on node and concat the sliced args
process.argv = ["node"].concat(args);
@@ -142,7 +141,7 @@ function replStart() {
input: process.stdin,
output: process.stdout,
eval: replEval,
useGlobal: true
useGlobal: true,
});
}

View File

@@ -1,12 +1,10 @@
/* eslint indent: 0 */
/**
* This tiny wrapper file checks for known node flags and appends them
* when found, before invoking the "real" _babel-node(1) executable.
*/
let getV8Flags = require("v8flags");
let path = require("path");
import getV8Flags from "v8flags";
import path from "path";
let args = [path.join(__dirname, "_babel-node")];
@@ -14,9 +12,9 @@ let babelArgs = process.argv.slice(2);
let userArgs;
// separate node arguments from script arguments
let argSeparator = babelArgs.indexOf("--");
const argSeparator = babelArgs.indexOf("--");
if (argSeparator > -1) {
userArgs = babelArgs.slice(argSeparator); // including the --
userArgs = babelArgs.slice(argSeparator); // including the --
babelArgs = babelArgs.slice(0, argSeparator);
}
@@ -75,13 +73,13 @@ getV8Flags(function (err, v8Flags) {
}
try {
let kexec = require("kexec");
const kexec = require("kexec");
kexec(process.argv[0], args);
} catch (err) {
if (err.code !== "MODULE_NOT_FOUND") throw err;
let child_process = require("child_process");
let proc = child_process.spawn(process.argv[0], args, { stdio: "inherit" });
const child_process = require("child_process");
const proc = child_process.spawn(process.argv[0], args, { stdio: "inherit" });
proc.on("exit", function (code, signal) {
process.on("exit", function () {
if (signal) {

View File

@@ -1,26 +1,26 @@
let outputFileSync = require("output-file-sync");
let slash = require("slash");
let path = require("path");
let util = require("./util");
let fs = require("fs");
let _ = require("lodash");
import outputFileSync from "output-file-sync";
import slash from "slash";
import path from "path";
import fs from "fs";
module.exports = function (commander, filenames) {
import * as util from "./util";
export default function (commander, filenames) {
function write(src, relative) {
// remove extension and then append back on .js
relative = relative.replace(/\.(\w*?)$/, "") + ".js";
let dest = path.join(commander.outDir, relative);
const dest = path.join(commander.outDir, relative);
let data = util.compile(src, {
const data = util.compile(src, {
sourceFileName: slash(path.relative(dest + "/..", src)),
sourceMapTarget: path.basename(relative)
sourceMapTarget: path.basename(relative),
});
if (!commander.copyFiles && data.ignored) return;
// we've requested explicit sourcemaps to be written to disk
if (data.map && commander.sourceMaps && commander.sourceMaps !== "inline") {
let mapLoc = dest + ".map";
const mapLoc = dest + ".map";
data.code = util.addSourceMappingUrl(data.code, mapLoc);
outputFileSync(mapLoc, JSON.stringify(data.map));
}
@@ -37,7 +37,7 @@ module.exports = function (commander, filenames) {
if (util.canCompile(filename, commander.extensions)) {
write(src, filename);
} else if (commander.copyFiles) {
let dest = path.join(commander.outDir, filename);
const dest = path.join(commander.outDir, filename);
outputFileSync(dest, fs.readFileSync(src));
util.chmod(src, dest);
}
@@ -46,13 +46,13 @@ module.exports = function (commander, filenames) {
function handle(filename) {
if (!fs.existsSync(filename)) return;
let stat = fs.statSync(filename);
const stat = fs.statSync(filename);
if (stat.isDirectory(filename)) {
let dirname = filename;
const dirname = filename;
_.each(util.readdir(dirname), function (filename) {
let src = path.join(dirname, filename);
util.readdir(dirname).forEach(function (filename) {
const src = path.join(dirname, filename);
handleFile(src, filename);
});
} else {
@@ -61,21 +61,25 @@ module.exports = function (commander, filenames) {
}
if (!commander.skipInitialBuild) {
_.each(filenames, handle);
filenames.forEach(handle);
}
if (commander.watch) {
let chokidar = util.requireChokidar();
const chokidar = util.requireChokidar();
_.each(filenames, function (dirname) {
let watcher = chokidar.watch(dirname, {
filenames.forEach(function (dirname) {
const watcher = chokidar.watch(dirname, {
persistent: true,
ignoreInitial: true
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: 50,
pollInterval: 10,
},
});
_.each(["add", "change"], function (type) {
["add", "change"].forEach(function (type) {
watcher.on(type, function (filename) {
let relative = path.relative(dirname, filename) || filename;
const relative = path.relative(dirname, filename) || filename;
try {
handleFile(filename, relative);
} catch (err) {
@@ -85,4 +89,4 @@ module.exports = function (commander, filenames) {
});
});
}
};
}

View File

@@ -1,33 +1,33 @@
let convertSourceMap = require("convert-source-map");
let sourceMap = require("source-map");
let slash = require("slash");
let path = require("path");
let util = require("./util");
let fs = require("fs");
let _ = require("lodash");
import convertSourceMap from "convert-source-map";
import sourceMap from "source-map";
import slash from "slash";
import path from "path";
import fs from "fs";
module.exports = function (commander, filenames, opts) {
import * as util from "./util";
export default function (commander, filenames, opts) {
if (commander.sourceMaps === "inline") {
opts.sourceMaps = true;
}
let results = [];
let buildResult = function () {
let map = new sourceMap.SourceMapGenerator({
const buildResult = function () {
const map = new sourceMap.SourceMapGenerator({
file: path.basename(commander.outFile || "") || "stdout",
sourceRoot: opts.sourceRoot
sourceRoot: opts.sourceRoot,
});
let code = "";
let offset = 0;
_.each(results, function (result) {
results.forEach(function (result) {
code += result.code + "\n";
if (result.map) {
let consumer = new sourceMap.SourceMapConsumer(result.map);
let sources = new Set();
const consumer = new sourceMap.SourceMapConsumer(result.map);
const sources = new Set();
consumer.eachMapping(function (mapping) {
if (mapping.source != null) sources.add(mapping.source);
@@ -46,13 +46,13 @@ module.exports = function (commander, filenames, opts) {
});
sources.forEach((source) => {
let content = consumer.sourceContentFor(source, true);
const content = consumer.sourceContentFor(source, true);
if (content !== null) {
map.setSourceContent(source, content);
}
});
offset = code.split("\n").length;
offset = code.split("\n").length - 1;
}
});
@@ -64,17 +64,17 @@ module.exports = function (commander, filenames, opts) {
return {
map: map,
code: code
code: code,
};
};
let output = function () {
let result = buildResult();
const output = function () {
const result = buildResult();
if (commander.outFile) {
// we've requested for a sourcemap to be written to disk
if (commander.sourceMaps && commander.sourceMaps !== "inline") {
let mapLoc = commander.outFile + ".map";
const mapLoc = commander.outFile + ".map";
result.code = util.addSourceMappingUrl(result.code, mapLoc);
fs.writeFileSync(mapLoc, JSON.stringify(result.map));
}
@@ -85,13 +85,13 @@ module.exports = function (commander, filenames, opts) {
}
};
let stdin = function () {
const stdin = function () {
let code = "";
process.stdin.setEncoding("utf8");
process.stdin.on("readable", function () {
let chunk = process.stdin.read();
const chunk = process.stdin.read();
if (chunk !== null) code += chunk;
});
@@ -103,18 +103,18 @@ module.exports = function (commander, filenames, opts) {
});
};
let walk = function () {
let _filenames = [];
const walk = function () {
const _filenames = [];
results = [];
_.each(filenames, function (filename) {
filenames.forEach(function (filename) {
if (!fs.existsSync(filename)) return;
let stat = fs.statSync(filename);
const stat = fs.statSync(filename);
if (stat.isDirectory()) {
let dirname = filename;
const dirname = filename;
_.each(util.readdirFilter(filename), function (filename) {
util.readdirFilter(filename).forEach(function (filename) {
_filenames.push(path.join(dirname, filename));
});
} else {
@@ -122,7 +122,7 @@ module.exports = function (commander, filenames, opts) {
}
});
_.each(_filenames, function (filename) {
_filenames.forEach(function (filename) {
if (util.shouldIgnore(filename)) return;
let sourceFilename = filename;
@@ -131,7 +131,7 @@ module.exports = function (commander, filenames, opts) {
}
sourceFilename = slash(sourceFilename);
let data = util.compile(filename, {
const data = util.compile(filename, {
sourceFileName: sourceFilename,
});
@@ -142,17 +142,21 @@ module.exports = function (commander, filenames, opts) {
output();
};
let files = function () {
const files = function () {
if (!commander.skipInitialBuild) {
walk();
}
if (commander.watch) {
let chokidar = util.requireChokidar();
const chokidar = util.requireChokidar();
chokidar.watch(filenames, {
persistent: true,
ignoreInitial: true
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: 50,
pollInterval: 10,
},
}).on("all", function (type, filename) {
if (util.shouldIgnore(filename) || !util.canCompile(filename, commander.extensions)) return;
@@ -173,4 +177,4 @@ module.exports = function (commander, filenames, opts) {
} else {
stdin();
}
};
}

View File

@@ -1,18 +1,19 @@
#!/usr/bin/env node
/* eslint max-len: 0 */
require("babel-core");
import fs from "fs";
import commander from "commander";
import kebabCase from "lodash/kebabCase";
import { options, util, version } from "babel-core";
import uniq from "lodash/uniq";
import glob from "glob";
let fs = require("fs");
let commander = require("commander");
let kebabCase = require("lodash/kebabCase");
let options = require("babel-core").options;
let util = require("babel-core").util;
let uniq = require("lodash/uniq");
let each = require("lodash/each");
let glob = require("glob");
import dirCommand from "./dir";
import fileCommand from "./file";
each(options, function (option, key) {
import pkg from "../../package.json";
Object.keys(options).forEach(function (key) {
const option = options[key];
if (option.hidden) return;
let arg = kebabCase(key);
@@ -31,13 +32,14 @@ each(options, function (option, key) {
arg = "-" + option.shorthand + ", " + arg;
}
let desc = [];
const desc = [];
if (option.deprecated) desc.push("[DEPRECATED] " + option.deprecated);
if (option.description) desc.push(option.description);
commander.option(arg, desc.join(" "));
});
/* eslint-disable max-len */
commander.option("-x, --extensions [extensions]", "List of extensions to compile when a directory has been input [.es6,.js,.es,.jsx]");
commander.option("-w, --watch", "Recompile files on changes");
commander.option("--skip-initial-build", "Do not compile files before watching");
@@ -45,9 +47,9 @@ commander.option("-o, --out-file [out]", "Compile all input files into a single
commander.option("-d, --out-dir [out]", "Compile an input directory of modules into an output directory");
commander.option("-D, --copy-files", "When compiling a directory copy over non-compilable files");
commander.option("-q, --quiet", "Don't log anything");
/* eslint-enable max-len */
let pkg = require("../../package.json");
commander.version(pkg.version + " (babel-core " + require("babel-core").version + ")");
commander.version(pkg.version + " (babel-core " + version + ")");
commander.usage("[options] <files ...>");
commander.parse(process.argv);
@@ -59,7 +61,7 @@ if (commander.extensions) {
//
let errors = [];
const errors = [];
let filenames = commander.args.reduce(function (globbed, input) {
let files = glob.sync(input);
@@ -69,7 +71,7 @@ let filenames = commander.args.reduce(function (globbed, input) {
filenames = uniq(filenames);
each(filenames, function (filename) {
filenames.forEach(function (filename) {
if (!fs.existsSync(filename)) {
errors.push(filename + " doesn't exist");
}
@@ -104,9 +106,10 @@ if (errors.length) {
//
let opts = exports.opts = {};
export const opts = {};
each(options, function (opt, key) {
Object.keys(options).forEach(function (key) {
const opt = options[key];
if (commander[key] !== undefined && commander[key] !== opt.default) {
opts[key] = commander[key];
}
@@ -118,12 +121,5 @@ if (opts.only) {
opts.only = util.arrayify(opts.only, util.regexify);
}
let fn;
if (commander.outDir) {
fn = require("./dir");
} else {
fn = require("./file");
}
fn(commander, filenames, exports.opts);
const fn = commander.outDir ? dirCommand : fileCommand;
fn(commander, filenames, opts);

View File

@@ -1,11 +1,11 @@
let commander = require("commander");
let readdir = require("fs-readdir-recursive");
let index = require("./index");
let babel = require("babel-core");
let util = require("babel-core").util;
let path = require("path");
let fs = require("fs");
let _ = require("lodash");
import commander from "commander";
import defaults from "lodash/defaults";
import readdir from "fs-readdir-recursive";
import * as babel from "babel-core";
import path from "path";
import fs from "fs";
import * as index from "./index";
export function chmod(src, dest) {
fs.chmodSync(dest, fs.statSync(src).mode);
@@ -13,16 +13,16 @@ export function chmod(src, dest) {
export function readdirFilter(filename) {
return readdir(filename).filter(function (filename) {
return util.canCompile(filename);
return babel.util.canCompile(filename);
});
}
export { readdir };
export let canCompile = util.canCompile;
export const canCompile = babel.util.canCompile;
export function shouldIgnore(loc) {
return util.shouldIgnore(loc, index.opts.ignore, index.opts.only);
return babel.util.shouldIgnore(loc, index.opts.ignore, index.opts.only);
}
export function addSourceMappingUrl(code, loc) {
@@ -34,10 +34,10 @@ export function log(msg) {
}
export function transform(filename, code, opts) {
opts = _.defaults(opts || {}, index.opts);
opts = defaults(opts || {}, index.opts);
opts.filename = filename;
let result = babel.transform(code, opts);
const result = babel.transform(code, opts);
result.filename = filename;
result.actual = code;
return result;
@@ -45,7 +45,7 @@ export function transform(filename, code, opts) {
export function compile(filename, opts) {
try {
let code = fs.readFileSync(filename, "utf8");
const code = fs.readFileSync(filename, "utf8");
return transform(filename, code, opts);
} catch (err) {
if (commander.watch) {

View File

@@ -0,0 +1 @@
console.log(process.argv[2]);

View File

@@ -0,0 +1,4 @@
{
"args": ["bar", "foo"],
"stdout": "foo"
}

View File

@@ -11,4 +11,4 @@ arr.map(function (x) {
return x * MULTIPLIER;
});
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNjcmlwdC5qcyIsInNjcmlwdDIuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7OztJQUFNLEk7Ozs7OztBQ0FOLElBQUksR0FBSixDQUFRO0FBQUEsU0FBSyxJQUFJLFVBQVQ7QUFBQSxDQUFSIiwiZmlsZSI6InNjcmlwdDMuanMiLCJzb3VyY2VzQ29udGVudCI6WyJjbGFzcyBUZXN0IHtcblxufSIsImFyci5tYXAoeCA9PiB4ICogTVVMVElQTElFUik7Il19
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNjcmlwdC5qcyIsInNjcmlwdDIuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7OztJQUFNLEk7Ozs7O0FDQU4sSUFBSSxHQUFKLENBQVE7QUFBQSxTQUFLLElBQUksVUFBVDtBQUFBLENBQVIiLCJmaWxlIjoic2NyaXB0My5qcyIsInNvdXJjZXNDb250ZW50IjpbImNsYXNzIFRlc3Qge1xuXG59IiwiYXJyLm1hcCh4ID0+IHggKiBNVUxUSVBMSUVSKTsiXX0=

View File

@@ -1 +1 @@
{"version":3,"sources":["script.js","script2.js"],"names":[],"mappings":";;;;IAAM,I;;;;;;ACAN,IAAI,GAAJ,CAAQ;AAAA,SAAK,IAAI,UAAT;AAAA,CAAR","file":"script3.js","sourcesContent":["class Test {\n\n}","arr.map(x => x * MULTIPLIER);"]}
{"version":3,"sources":["script.js","script2.js"],"names":[],"mappings":";;;;IAAM,I;;;;;ACAN,IAAI,GAAJ,CAAQ;AAAA,SAAK,IAAI,UAAT;AAAA,CAAR","file":"script3.js","sourcesContent":["class Test {\n\n}","arr.map(x => x * MULTIPLIER);"]}

View File

@@ -1,50 +1,53 @@
let readdir = require("fs-readdir-recursive");
let helper = require("babel-helper-fixtures");
let assert = require("assert");
let rimraf = require("rimraf");
let outputFileSync = require("output-file-sync");
let child = require("child_process");
let path = require("path");
let chai = require("chai");
let fs = require("fs");
let _ = require("lodash");
const includes = require("lodash/includes");
const readdir = require("fs-readdir-recursive");
const helper = require("babel-helper-fixtures");
const assert = require("assert");
const rimraf = require("rimraf");
const outputFileSync = require("output-file-sync");
const child = require("child_process");
const merge = require("lodash/merge");
const path = require("path");
const chai = require("chai");
const fs = require("fs");
let fixtureLoc = path.join(__dirname, "fixtures");
let tmpLoc = path.join(__dirname, "tmp");
const fixtureLoc = path.join(__dirname, "fixtures");
const tmpLoc = path.join(__dirname, "tmp");
let presetLocs = [
const presetLocs = [
path.join(__dirname, "../../babel-preset-es2015"),
path.join(__dirname, "../../babel-preset-react")
path.join(__dirname, "../../babel-preset-react"),
].join(",");
let pluginLocs = [
const pluginLocs = [
path.join(__dirname, "/../../babel-plugin-transform-strict-mode"),
path.join(__dirname, "/../../babel-plugin-transform-es2015-modules-commonjs"),
].join(",");
let readDir = function (loc) {
let files = {};
const readDir = function (loc) {
const files = {};
if (fs.existsSync(loc)) {
_.each(readdir(loc), function (filename) {
readdir(loc).forEach(function (filename) {
files[filename] = helper.readFile(path.join(loc, filename));
});
}
return files;
};
let saveInFiles = function (files) {
_.each(files, function (content, filename) {
const saveInFiles = function (files) {
Object.keys(files).forEach(function (filename) {
const content = files[filename];
outputFileSync(filename, content);
});
};
let assertTest = function (stdout, stderr, opts) {
let expectStderr = opts.stderr.trim();
const assertTest = function (stdout, stderr, opts) {
const expectStderr = opts.stderr.trim();
stderr = stderr.trim();
if (opts.stderr) {
if (opts.stderrContains) {
assert.ok(_.includes(stderr, expectStderr), "stderr " + JSON.stringify(stderr) + " didn't contain " + JSON.stringify(expectStderr));
assert.ok(includes(stderr, expectStderr), "stderr " + JSON.stringify(stderr) +
" didn't contain " + JSON.stringify(expectStderr));
} else {
chai.expect(stderr).to.equal(expectStderr, "stderr didn't match");
}
@@ -52,13 +55,14 @@ let assertTest = function (stdout, stderr, opts) {
throw new Error("stderr:\n" + stderr);
}
let expectStdout = opts.stdout.trim();
const expectStdout = opts.stdout.trim();
stdout = stdout.trim();
stdout = stdout.replace(/\\/g, "/");
if (opts.stdout) {
if (opts.stdoutContains) {
assert.ok(_.includes(stdout, expectStdout), "stdout " + JSON.stringify(stdout) + " didn't contain " + JSON.stringify(expectStdout));
assert.ok(includes(stdout, expectStdout), "stdout " + JSON.stringify(stdout) +
" didn't contain " + JSON.stringify(expectStdout));
} else {
chai.expect(stdout).to.equal(expectStdout, "stdout didn't match");
}
@@ -66,14 +70,15 @@ let assertTest = function (stdout, stderr, opts) {
throw new Error("stdout:\n" + stdout);
}
_.each(opts.outFiles, function (expect, filename) {
let actual = helper.readFile(filename);
Object.keys(opts.outFiles, function (filename) {
const expect = opts.outFiles[filename];
const actual = helper.readFile(filename);
chai.expect(actual).to.equal(expect, "out-file " + filename);
});
};
let buildTest = function (binName, testName, opts) {
let binLoc = path.join(__dirname, "../lib", binName);
const buildTest = function (binName, testName, opts) {
const binLoc = path.join(__dirname, "../lib", binName);
return function (callback) {
clear();
@@ -91,7 +96,7 @@ let buildTest = function (binName, testName, opts) {
args = args.concat(opts.args);
let spawn = child.spawn(process.execPath, args);
const spawn = child.spawn(process.execPath, args);
let stderr = "";
let stdout = "";
@@ -127,32 +132,32 @@ let buildTest = function (binName, testName, opts) {
};
};
let clear = function () {
const clear = function () {
process.chdir(__dirname);
if (fs.existsSync(tmpLoc)) rimraf.sync(tmpLoc);
fs.mkdirSync(tmpLoc);
process.chdir(tmpLoc);
};
_.each(fs.readdirSync(fixtureLoc), function (binName) {
fs.readdirSync(fixtureLoc).forEach(function (binName) {
if (binName[0] === ".") return;
let suiteLoc = path.join(fixtureLoc, binName);
const suiteLoc = path.join(fixtureLoc, binName);
describe("bin/" + binName, function () {
_.each(fs.readdirSync(suiteLoc), function (testName) {
fs.readdirSync(suiteLoc).forEach(function (testName) {
if (testName[0] === ".") return;
let testLoc = path.join(suiteLoc, testName);
const testLoc = path.join(suiteLoc, testName);
let opts = {
args: []
const opts = {
args: [],
};
let optionsLoc = path.join(testLoc, "options.json");
if (fs.existsSync(optionsLoc)) _.merge(opts, require(optionsLoc));
const optionsLoc = path.join(testLoc, "options.json");
if (fs.existsSync(optionsLoc)) merge(opts, require(optionsLoc));
_.each(["stdout", "stdin", "stderr"], function (key) {
let loc = path.join(testLoc, key + ".txt");
["stdout", "stdin", "stderr"].forEach(function (key) {
const loc = path.join(testLoc, key + ".txt");
if (fs.existsSync(loc)) {
opts[key] = helper.readFile(loc);
} else {
@@ -161,9 +166,9 @@ _.each(fs.readdirSync(fixtureLoc), function (binName) {
});
opts.outFiles = readDir(path.join(testLoc, "out-files"));
opts.inFiles = readDir(path.join(testLoc, "in-files"));
opts.inFiles = readDir(path.join(testLoc, "in-files"));
let babelrcLoc = path.join(testLoc, ".babelrc");
const babelrcLoc = path.join(testLoc, ".babelrc");
if (fs.existsSync(babelrcLoc)) {
// copy .babelrc file to tmp directory
opts.inFiles[".babelrc"] = helper.readFile(babelrcLoc);

View File

@@ -35,9 +35,26 @@ If the column number is not known, you may pass `null` instead.
## Options
name | type | default | description
-----------------------|----------|-----------------|------------------------------------------------------
highlightCode | boolean | `false` | Syntax highlight the code as JavaScript for terminals
linesAbove | number | 2 | The number of lines to show above the error
linesBelow | number | 3 | The number of lines to show below the error
forceColor | boolean | `false` | Forcibly syntax highlight the code as JavaScript (for non-terminals); overrides highlightCode
### `highlightCode`
`boolean`, defaults to `false`.
Toggles syntax highlighting the code as JavaScript for terminals.
### `linesAbove`
`number`, defaults to `2`.
Adjust the number of lines to show above the error.
### `linesBelow`
`number`, defaults to `3`.
Adjust the number of lines to show below the error.
### `forceColor`
`boolean`, defaults to `false`.
Enable this to forcibly syntax highlight the code as JavaScript (for non-terminals); overrides `highlightCode`.

View File

@@ -1,6 +1,6 @@
{
"name": "babel-code-frame",
"version": "6.20.0",
"version": "7.0.0-alpha.1",
"description": "Generate errors that contain a code frame that point to source locations.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -10,6 +10,6 @@
"dependencies": {
"chalk": "^1.1.0",
"esutils": "^2.0.2",
"js-tokens": "^2.0.0"
"js-tokens": "^3.0.0"
}
}

View File

@@ -1,4 +1,4 @@
import jsTokens from "js-tokens";
import jsTokens, { matchToToken } from "js-tokens";
import esutils from "esutils";
import Chalk from "chalk";
@@ -8,18 +8,18 @@ import Chalk from "chalk";
function getDefs(chalk) {
return {
keyword: chalk.cyan,
keyword: chalk.cyan,
capitalized: chalk.yellow,
jsx_tag: chalk.yellow,
punctuator: chalk.yellow,
jsx_tag: chalk.yellow,
punctuator: chalk.yellow,
// bracket: intentionally omitted.
number: chalk.magenta,
string: chalk.green,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.white.bgRed.bold,
gutter: chalk.grey,
marker: chalk.red.bold,
number: chalk.magenta,
string: chalk.green,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.white.bgRed.bold,
gutter: chalk.grey,
marker: chalk.red.bold,
};
}
@@ -46,8 +46,8 @@ const BRACKET = /^[()\[\]{}]$/;
*/
function getTokenType(match) {
let [offset, text] = match.slice(-2);
let token = jsTokens.matchToToken(match);
const [offset, text] = match.slice(-2);
const token = matchToToken(match);
if (token.type === "name") {
if (esutils.keyword.isReservedWordES6(token.value)) {
@@ -79,8 +79,8 @@ function getTokenType(match) {
function highlight(defs: Object, text: string) {
return text.replace(jsTokens, function (...args) {
let type = getTokenType(args);
let colorize = defs[type];
const type = getTokenType(args);
const colorize = defs[type];
if (colorize) {
return args[0].split(NEWLINE).map((str) => colorize(str)).join("\n");
} else {
@@ -101,51 +101,51 @@ export default function (
): string {
colNumber = Math.max(colNumber, 0);
let highlighted = (opts.highlightCode && Chalk.supportsColor) || opts.forceColor;
const highlighted = (opts.highlightCode && Chalk.supportsColor) || opts.forceColor;
let chalk = Chalk;
if (opts.forceColor) {
chalk = new Chalk.constructor({ enabled: true });
}
let maybeHighlight = (chalkFn, string) => {
const maybeHighlight = (chalkFn, string) => {
return highlighted ? chalkFn(string) : string;
};
let defs = getDefs(chalk);
const defs = getDefs(chalk);
if (highlighted) rawLines = highlight(defs, rawLines);
let linesAbove = opts.linesAbove || 2;
let linesBelow = opts.linesBelow || 3;
const linesAbove = opts.linesAbove || 2;
const linesBelow = opts.linesBelow || 3;
let lines = rawLines.split(NEWLINE);
const lines = rawLines.split(NEWLINE);
let start = Math.max(lineNumber - (linesAbove + 1), 0);
let end = Math.min(lines.length, lineNumber + linesBelow);
let end = Math.min(lines.length, lineNumber + linesBelow);
if (!lineNumber && !colNumber) {
start = 0;
end = lines.length;
}
let numberMaxWidth = String(end).length;
const numberMaxWidth = String(end).length;
let frame = lines.slice(start, end).map((line, index) => {
let number = start + 1 + index;
let paddedNumber = ` ${number}`.slice(-numberMaxWidth);
let gutter = ` ${paddedNumber} | `;
const frame = lines.slice(start, end).map((line, index) => {
const number = start + 1 + index;
const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
const gutter = ` ${paddedNumber} | `;
if (number === lineNumber) {
let markerLine = "";
if (colNumber) {
let markerSpacing = line.slice(0, colNumber - 1).replace(/[^\t]/g, " ");
const markerSpacing = line.slice(0, colNumber - 1).replace(/[^\t]/g, " ");
markerLine = [
"\n ",
maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")),
markerSpacing,
maybeHighlight(defs.marker, "^")
maybeHighlight(defs.marker, "^"),
].join("");
}
return [
maybeHighlight(defs.marker, ">"),
maybeHighlight(defs.gutter, gutter),
line,
markerLine
markerLine,
].join("");
} else {
return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;

View File

@@ -1,6 +1,6 @@
let assert = require("assert");
let chalk = require("chalk");
let codeFrame = require("..");
import assert from "assert";
import chalk from "chalk";
import codeFrame from "..";
describe("babel-code-frame", function () {
it("basic usage", function () {
@@ -55,7 +55,7 @@ describe("babel-code-frame", function () {
"",
"function sum(a, b) {",
" return a + b",
"}"
"}",
].join("\n");
assert.equal(codeFrame(rawLines, 7, 2), [
" 5 | * @param b Number",
@@ -80,7 +80,7 @@ describe("babel-code-frame", function () {
"",
"function sum(a, b) {",
" return a + b",
"}"
"}",
].join("\n");
assert.equal(codeFrame(rawLines, 6, 2), [
" 4 | * @param a Number",
@@ -109,7 +109,7 @@ describe("babel-code-frame", function () {
it("opts.highlightCode", function () {
const rawLines = "console.log('babel')";
const result = codeFrame(rawLines, 1, 9, {highlightCode: true});
const result = codeFrame(rawLines, 1, 9, { highlightCode: true });
const stripped = chalk.stripColor(result);
assert.ok(result.length > stripped.length);
assert.equal(stripped, [
@@ -119,7 +119,7 @@ describe("babel-code-frame", function () {
});
it("opts.linesAbove", function () {
let rawLines = [
const rawLines = [
"/**",
" * Sums two numbers.",
" *",
@@ -130,7 +130,7 @@ describe("babel-code-frame", function () {
"",
"function sum(a, b) {",
" return a + b",
"}"
"}",
].join("\n");
assert.equal(codeFrame(rawLines, 7, 2, { linesAbove: 1 }), [
" 6 | * @returns Number",
@@ -143,7 +143,7 @@ describe("babel-code-frame", function () {
});
it("opts.linesBelow", function () {
let rawLines = [
const rawLines = [
"/**",
" * Sums two numbers.",
" *",
@@ -154,19 +154,19 @@ describe("babel-code-frame", function () {
"",
"function sum(a, b) {",
" return a + b",
"}"
"}",
].join("\n");
assert.equal(codeFrame(rawLines, 7, 2, { linesBelow: 1 }), [
" 5 | * @param b Number",
" 6 | * @returns Number",
"> 7 | */",
" | ^",
" 8 | "
" 8 | ",
].join("\n"));
});
it("opts.linesAbove and opts.linesBelow", function () {
let rawLines = [
const rawLines = [
"/**",
" * Sums two numbers.",
" *",
@@ -177,30 +177,32 @@ describe("babel-code-frame", function () {
"",
"function sum(a, b) {",
" return a + b",
"}"
"}",
].join("\n");
assert.equal(codeFrame(rawLines, 7, 2, { linesAbove: 1, linesBelow: 1 }), [
" 6 | * @returns Number",
"> 7 | */",
" | ^",
" 8 | "
" 8 | ",
].join("\n"));
});
it("opts.forceColor", function() {
let marker = chalk.red.bold;
let gutter = chalk.grey;
const marker = chalk.red.bold;
const gutter = chalk.grey;
let rawLines = [
const rawLines = [
"",
"",
"",
"",
""
].join("\n");
assert.equal(codeFrame(rawLines, 3, null, { linesAbove: 1, linesBelow: 1, forceColor: true }), chalk.reset([
" " + gutter(" 2 | "),
marker(">") + gutter(" 3 | "),
" " + gutter(" 4 | ")
].join("\n")));
assert.equal(codeFrame(rawLines, 3, null, { linesAbove: 1, linesBelow: 1, forceColor: true }),
chalk.reset([
" " + gutter(" 2 | "),
marker(">") + gutter(" 3 | "),
" " + gutter(" 4 | "),
].join("\n"))
);
});
});

View File

@@ -9,7 +9,9 @@ import { transform } from 'babel-core';
import * as babel from 'babel-core';
```
## babel.transform(code: string, [options?](/docs/usage/api/#options): Object)
All transformations will use your local configuration files (.babelrc or in package.json). See [options](#options) to disable it.
## babel.transform(code: string, [options?](#options): Object)
Transforms the passed in `code`. Returning an object with the generated code,
source map, and AST.
@@ -27,7 +29,7 @@ result.map;
result.ast;
```
## babel.transformFile(filename: string, [options?](/docs/usage/api/#options): Object, callback: Function)
## babel.transformFile(filename: string, [options?](#options): Object, callback: Function)
Asynchronously transforms the entire contents of a file.
@@ -43,7 +45,7 @@ babel.transformFile("filename.js", options, function (err, result) {
});
```
## babel.transformFileSync(filename: string, [options?](/docs/usage/api/#options): Object)
## babel.transformFileSync(filename: string, [options?](#options): Object)
Synchronous version of `babel.transformFile`. Returns the transformed contents of
the `filename`.
@@ -58,7 +60,7 @@ babel.transformFileSync(filename, options) // => { code, map, ast }
babel.transformFileSync("filename.js", options).code;
```
## babel.transformFromAst(ast: Object, code?: string, [options?](/docs/usage/api/#options): Object)
## babel.transformFromAst(ast: Object, code?: string, [options?](#options): Object)
Given, an [AST](https://astexplorer.net/), transform it.
@@ -84,34 +86,36 @@ Following is a table of the options you can use:
| Option | Default | Description |
| ------------------------ | -------------------- | ------------------------------- |
| `ast` | `true` | Include the AST in the returned object |
| `auxiliaryCommentAfter` | `null` | Attach a comment after all non-user injected code. |
| `auxiliaryCommentBefore` | `null` | Attach a comment before all non-user injected code. |
| `babelrc` | `true` | Specify whether or not to use .babelrc and .babelignore files. Not available when using the CLI, [use `--no-babelrc` instead](https://babeljs.io/docs/usage/cli/#babel-ignoring-babelrc). |
| `code` | `true` | Enable code generation |
| `comments` | `true` | Output comments in generated output. |
| `compact` | `"auto"` | Do not include superfluous whitespace characters and line terminators. When set to `"auto"` compact is set to `true` on input sizes of >500KB. |
| `env` | `{}` | This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { /* specific options */ } } }` which will use those options when the environment variable `BABEL_ENV` is set to `"production"`. If `BABEL_ENV` isn't set then `NODE_ENV` will be used, if it's not set then it defaults to `"development"` |
| `extends` | `null` | A path to an `.babelrc` file to extend |
| `filename` | `"unknown"` | Filename for use in errors etc. |
| `filenameRelative` | `(filename)` | Filename relative to `sourceRoot`. |
| `presets` | `[]` | List of [presets](/docs/plugins/#presets) (a set of plugins) to load and use. |
| `plugins` | `[]` | List of [plugins](/docs/plugins/) to load and use. |
| `parserOpts` | `{}` | An object containing the options to be passed down to the babel parser, babylon |
| `generatorOpts` | `{}` | An object containing the options to be passed down to the babel code generator, babel-generator |
| `highlightCode` | `true` | ANSI highlight syntax error code frames |
| `only` | `null` | A [glob](https://github.com/isaacs/minimatch), regex, or mixed array of both, matching paths to **only** compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile a non-matching file it's returned verbatim. |
| `ignore` | `null` | Opposite to the `only` option. `ignore` is disregarded if `only` is specified. |
| `auxiliaryCommentBefore` | `null` | Attach a comment before all non-user injected code. |
| `auxiliaryCommentAfter` | `null` | Attach a comment after all non-user injected code. |
| `sourceMaps` | `false` | If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a sourceMappingURL directive is added to the bottom of the returned code. If set to `"both"` then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!** To have sourcemaps emitted using the CLI, you must pass it the `--source-maps` option. |
| `inputSourceMap` | `null` | A source map object that the output source map will be based on. |
| `sourceMapTarget` | `(filenameRelative)` | Set `file` on returned source map. |
| `sourceFileName` | `(filenameRelative)` | Set `sources[0]` on returned source map. |
| `sourceRoot` | `(moduleRoot)` | The root from which all sources are relative. |
| `moduleRoot` | `(sourceRoot)` | Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions. |
| `moduleIds` | `false` | If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for `common` modules) |
| `moduleId` | `null` | Specify a custom name for module ids. |
| `getModuleId` | `null` | Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. If falsy value is returned then the generated module id is used. |
| `resolveModuleSource` | `null` | Resolve a module source ie. `import "SOURCE";` to a custom value. Called as `resolveModuleSource(source, filename)`. |
| `code` | `true` | Enable code generation |
| `no-babelrc` | [CLI flag](http://babeljs.io/docs/usage/cli/#ignoring-babelrc) | Specify whether or not to use .babelrc and .babelignore files. Only available when using the CLI. |
| `ast` | `true` | Include the AST in the returned object |
| `compact` | `"auto"` | Do not include superfluous whitespace characters and line terminators. When set to `"auto"` compact is set to `true` on input sizes of >500KB. |
| `highlightCode` | `true` | ANSI highlight syntax error code frames |
| `ignore` | `null` | Opposite to the `only` option. `ignore` is disregarded if `only` is specified. |
| `inputSourceMap` | `null` | A source map object that the output source map will be based on. |
| `minified` | `false` | Should the output be minified (not printing last semicolons in blocks, printing literal string values instead of escaped ones, stripping `()` from `new` when safe) |
| `comments` | `true` | Output comments in generated output. |
| `shouldPrintComment` | `null` | An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE:** This overrides the `comment` option when used. |
| `env` | `{}` | This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { /* specific options */ } } }` which will use those options when the enviroment variable `BABEL_ENV` is set to `"production"`. If `BABEL_ENV` isn't set then `NODE_ENV` will be used, if it's not set then it defaults to `"development"` |
| `moduleId` | `null` | Specify a custom name for module ids. |
| `moduleIds` | `false` | If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for `common` modules) |
| `moduleRoot` | `(sourceRoot)` | Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions. |
| `only` | `null` | A [glob](https://github.com/isaacs/minimatch), regex, or mixed array of both, matching paths to **only** compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile a non-matching file it's returned verbatim. |
| `parserOpts` | `{}` | An object containing the options to be passed down to the babel parser, babylon |
| `plugins` | `[]` | List of [plugins](/docs/plugins/) to load and use. |
| `presets` | `[]` | List of [presets](/docs/plugins/#presets) (a set of plugins) to load and use. |
| `retainLines` | `false` | Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps. (**NOTE:** This will not retain the columns) |
| `extends` | `null` | A path to an `.babelrc` file to extend |
| `resolveModuleSource` | `null` | Resolve a module source ie. `import "SOURCE";` to a custom value. Called as `resolveModuleSource(source, filename)`. |
| `shouldPrintComment` | `null` | An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE:** This overrides the `comment` option when used. |
| `sourceFileName` | `(filenameRelative)` | Set `sources[0]` on returned source map. |
| `sourceMaps` | `false` | If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a sourceMappingURL directive is added to the bottom of the returned code. If set to `"both"` then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!** To have sourcemaps emitted using the CLI, you must pass it the `--source-maps` option. |
| `sourceMapTarget` | `(filenameRelative)` | Set `file` on returned source map. |
| `sourceRoot` | `(moduleRoot)` | The root from which all sources are relative. |
| `sourceType` | `"module"` | Indicate the mode the code should be parsed in. Can be either "script" or "module". |
| `wrapPluginVisitorMethod`| `null` | An optional callback that can be used to wrap visitor methods. **NOTE:** This is useful for things like introspection, and not really needed for implementing anything. Called as `wrapPluginVisitorMethod(pluginAlias, visitorType, callback)`.

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "babel-core",
"version": "6.21.0",
"version": "7.0.0-alpha.2",
"description": "Babel compiler core.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -18,36 +18,36 @@
"transpile",
"transpiler",
"var",
"babel-core"
"babel-core",
"compiler"
],
"scripts": {
"bench": "make bench",
"test": "make test"
},
"dependencies": {
"babel-code-frame": "^6.20.0",
"babel-generator": "^6.21.0",
"babel-helpers": "^6.16.0",
"babel-messages": "^6.8.0",
"babel-template": "^6.16.0",
"babel-runtime": "^6.20.0",
"babel-register": "^6.18.0",
"babel-traverse": "^6.21.0",
"babel-types": "^6.21.0",
"babylon": "^6.11.0",
"babel-code-frame": "7.0.0-alpha.1",
"babel-generator": "7.0.0-alpha.1",
"babel-helpers": "7.0.0-alpha.1",
"babel-messages": "7.0.0-alpha.1",
"babel-template": "7.0.0-alpha.1",
"babel-register": "7.0.0-alpha.2",
"babel-traverse": "7.0.0-alpha.1",
"babel-types": "7.0.0-alpha.1",
"babylon": "7.0.0-beta.4",
"convert-source-map": "^1.1.0",
"debug": "^2.1.1",
"json5": "^0.5.0",
"lodash": "^4.2.0",
"minimatch": "^3.0.2",
"path-is-absolute": "^1.0.0",
"private": "^0.1.6",
"resolve": "^1.3.2",
"slash": "^1.0.0",
"source-map": "^0.5.0"
},
"devDependencies": {
"babel-helper-fixtures": "^6.20.0",
"babel-helper-transform-fixture-test-runner": "^6.21.0",
"babel-polyfill": "^6.20.0"
"babel-helper-fixtures": "7.0.0-alpha.1",
"babel-helper-transform-fixture-test-runner": "7.0.0-alpha.2",
"babel-polyfill": "7.0.0-alpha.1"
}
}

View File

@@ -1,3 +1 @@
/* eslint max-len: 0 */
// TODO: eventually deprecate this console.trace("use the `babel-register` package instead of `babel-core/register`");
module.exports = require("babel-register");
throw new Error("`babel-core/register` has been moved to `babel-register`.");

View File

@@ -1,112 +0,0 @@
/* eslint max-len: 0 */
/* eslint no-new-func: 0 */
import { transform } from "./node";
export {
File,
options,
buildExternalHelpers,
template,
version,
util,
messages,
types,
traverse,
OptionManager,
Plugin,
Pipeline,
analyse,
transform,
transformFromAst,
transformFile,
transformFileSync
} from "./node";
export function run(code: string, opts: Object = {}): any {
return new Function(transform(code, opts).code)();
}
export function load(url: string, callback: Function, opts: Object = {}, hold?: boolean) {
opts.filename = opts.filename || url;
let xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest();
xhr.open("GET", url, true);
if ("overrideMimeType" in xhr) xhr.overrideMimeType("text/plain");
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
let status = xhr.status;
if (status === 0 || status === 200) {
let param = [xhr.responseText, opts];
if (!hold) run(param);
if (callback) callback(param);
} else {
throw new Error(`Could not load ${url}`);
}
};
xhr.send(null);
}
function runScripts() {
let scripts: Array<Array<any> | Object> = [];
let types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"];
let index = 0;
/**
* Transform and execute script. Ensures correct load order.
*/
function exec() {
let param = scripts[index];
if (param instanceof Array) {
run(param, index);
index++;
exec();
}
}
/**
* Load, transform, and execute all scripts.
*/
function run(script: Object, i: number) {
let opts = {};
if (script.src) {
load(script.src, function (param) {
scripts[i] = param;
exec();
}, opts, true);
} else {
opts.filename = "embedded";
scripts[i] = [script.innerHTML, opts];
}
}
// Collect scripts with Babel `types`.
let _scripts = global.document.getElementsByTagName("script");
for (let i = 0; i < _scripts.length; ++i) {
let _script = _scripts[i];
if (types.indexOf(_script.type) >= 0) scripts.push(_script);
}
for (let i = 0; i < scripts.length; i++) {
run(scripts[i], i);
}
exec();
}
/**
* Register load event to transform and execute scripts.
*/
if (global.addEventListener) {
global.addEventListener("DOMContentLoaded", runScripts, false);
} else if (global.attachEvent) {
global.attachEvent("onload", runScripts);
}

View File

@@ -0,0 +1,3 @@
export default function getPossiblePluginNames(pluginName: string): Array<string> {
return [`babel-plugin-${pluginName}`, pluginName];
}

View File

@@ -0,0 +1,13 @@
export default function getPossiblePresetNames(presetName: string): Array<string> {
const possibleNames = [`babel-preset-${presetName}`, presetName];
// trying to resolve @organization shortcat
// @foo/es2015 -> @foo/babel-preset-es2015
const matches = presetName.match(/^(@[^/]+)\/(.+)$/);
if (matches) {
const [, orgName, presetPath] = matches;
possibleNames.push(`${orgName}/babel-preset-${presetPath}`);
}
return possibleNames;
}

View File

@@ -5,9 +5,9 @@ export default function (dest?: Object, src?: Object): ?Object {
return mergeWith(dest, src, function (a, b) {
if (b && Array.isArray(a)) {
let newArray = b.slice(0);
const newArray = b.slice(0);
for (let item of a) {
for (const item of a) {
if (newArray.indexOf(item) < 0) {
newArray.push(item);
}

View File

@@ -0,0 +1,5 @@
import resolve from "./resolve";
export default function resolveFromPossibleNames(possibleNames: Array<string>, dirname: string): ?string {
return possibleNames.reduce((accum, curr) => accum || resolve(curr, dirname), null);
}

View File

@@ -0,0 +1,6 @@
import resolveFromPossibleNames from "./resolve-from-possible-names";
import getPossiblePluginNames from "./get-possible-plugin-names";
export default function resolvePlugin(pluginName: string, dirname: string = process.cwd()): ?string {
return resolveFromPossibleNames(getPossiblePluginNames(pluginName), dirname);
}

View File

@@ -0,0 +1,6 @@
import resolveFromPossibleNames from "./resolve-from-possible-names";
import getPossiblePresetNames from "./get-possible-preset-names";
export default function resolvePreset(presetName: string, dirname: string = process.cwd()): ?string {
return resolveFromPossibleNames(getPossiblePresetNames(presetName), dirname);
}

View File

@@ -1,33 +1,8 @@
import Module from "module";
import path from "path";
let relativeModules = {};
import resolve from "resolve";
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;
// We need to define an id and filename on our "fake" relative` module so that
// Node knows what "." means in the case of us trying to resolve a plugin
// such as "./myPlugins/somePlugin.js". If we don't specify id and filename here,
// Node presumes "." is process.cwd(), not our relative path.
// Since this fake module is never "loaded", we don't have to worry about mutating
// any global Node module cache state here.
let filename = path.join(relative, ".babelrc");
relativeMod.id = filename;
relativeMod.filename = filename;
relativeMod.paths = Module._nodeModulePaths(relative);
relativeModules[relative] = relativeMod;
}
try {
return Module._resolveFilename(loc, relativeMod);
return resolve.sync(loc, { basedir: relative });
} catch (err) {
return null;
}

View File

@@ -1,13 +1,14 @@
import isFunction from "lodash/isFunction";
import fs from "fs";
export { default as File } from "../transformation/file";
export { default as options } from "../transformation/file/options/config";
export { default as buildExternalHelpers } from "../tools/build-external-helpers";
export { default as File } from "./transformation/file";
export { default as options } from "./transformation/file/options/config";
export { default as buildExternalHelpers } from "./tools/build-external-helpers";
export { default as template } from "babel-template";
export { version } from "../../package";
export { default as resolvePlugin } from "./helpers/resolve-plugin";
export { default as resolvePreset } from "./helpers/resolve-preset";
export { version } from "../package";
import * as util from "../util";
import * as util from "./util";
export { util };
import * as messages from "babel-messages";
@@ -19,23 +20,18 @@ export { t as types };
import traverse from "babel-traverse";
export { traverse };
import OptionManager from "../transformation/file/options/option-manager";
import OptionManager from "./transformation/file/options/option-manager";
export { OptionManager };
export function Plugin(alias) {
throw new Error(`The (${alias}) Babel 5 plugin is being run with Babel 6.`);
}
import Pipeline from "../transformation/pipeline";
export { Pipeline };
let pipeline = new Pipeline;
export let analyse = pipeline.analyse.bind(pipeline);
export let transform = pipeline.transform.bind(pipeline);
export let transformFromAst = pipeline.transformFromAst.bind(pipeline);
import { transform, analyse, transformFromAst } from "./transformation/pipeline";
export { transform, analyse, transformFromAst };
export function transformFile(filename: string, opts?: Object, callback: Function) {
if (isFunction(opts)) {
if (typeof opts === "function") {
callback = opts;
opts = {};
}

View File

@@ -1,22 +1,24 @@
export default class Store extends Map {
export default class Store {
constructor() {
super();
this.dynamicData = {};
this._map = new Map();
this._map.dynamicData = {};
}
dynamicData: Object;
setDynamic(key, fn) {
this.dynamicData[key] = fn;
this._map.dynamicData[key] = fn;
}
set(key: string, val) {
this._map.set(key, val);
}
get(key: string): any {
if (this.has(key)) {
return super.get(key);
if (this._map.has(key)) {
return this._map.get(key);
} else {
if (Object.prototype.hasOwnProperty.call(this.dynamicData, key)) {
let val = this.dynamicData[key]();
this.set(key, val);
if (Object.prototype.hasOwnProperty.call(this._map.dynamicData, key)) {
const val = this._map.dynamicData[key]();
this._map.set(key, val);
return val;
}
}

View File

@@ -1,13 +1,10 @@
/* eslint max-len: 0 */
import * as helpers from "babel-helpers";
import generator from "babel-generator";
import * as messages from "babel-messages";
import template from "babel-template";
import each from "lodash/each";
import * as t from "babel-types";
let buildUmdWrapper = template(`
const buildUmdWrapper = template(`
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define(AMD_ARGUMENTS, factory);
@@ -22,15 +19,17 @@ let buildUmdWrapper = template(`
`);
function buildGlobal(namespace, builder) {
let body = [];
let container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
let tree = t.program([t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]);
const body = [];
const container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
const tree = t.program([
t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]);
body.push(t.variableDeclaration("var", [
t.variableDeclarator(
namespace,
t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([]))
)
t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace),
t.objectExpression([]))
),
]));
builder(body);
@@ -39,9 +38,9 @@ function buildGlobal(namespace, builder) {
}
function buildUmd(namespace, builder) {
let body = [];
const body = [];
body.push(t.variableDeclaration("var", [
t.variableDeclarator(namespace, t.identifier("global"))
t.variableDeclarator(namespace, t.identifier("global")),
]));
builder(body);
@@ -49,23 +48,23 @@ function buildUmd(namespace, builder) {
return t.program([
buildUmdWrapper({
FACTORY_PARAMETERS: t.identifier("global"),
BROWSER_ARGUMENTS: t.assignmentExpression(
BROWSER_ARGUMENTS: t.assignmentExpression(
"=",
t.memberExpression(t.identifier("root"), namespace),
t.objectExpression([])
),
COMMON_ARGUMENTS: t.identifier("exports"),
AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]),
FACTORY_BODY: body,
UMD_ROOT: t.identifier("this")
})
COMMON_ARGUMENTS: t.identifier("exports"),
AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]),
FACTORY_BODY: body,
UMD_ROOT: t.identifier("this"),
}),
]);
}
function buildVar(namespace, builder) {
let body = [];
const body = [];
body.push(t.variableDeclaration("var", [
t.variableDeclarator(namespace, t.objectExpression([]))
t.variableDeclarator(namespace, t.objectExpression([])),
]));
builder(body);
body.push(t.expressionStatement(namespace));
@@ -73,10 +72,10 @@ function buildVar(namespace, builder) {
}
function buildHelpers(body, namespace, whitelist) {
each(helpers.list, function (name) {
helpers.list.forEach(function (name) {
if (whitelist && whitelist.indexOf(name) < 0) return;
let key = t.identifier(name);
const key = t.identifier(name);
body.push(t.expressionStatement(
t.assignmentExpression("=", t.memberExpression(namespace, key), helpers.get(name))
));
@@ -86,18 +85,18 @@ export default function (
whitelist?: Array<string>,
outputType: "global" | "umd" | "var" = "global",
) {
let namespace = t.identifier("babelHelpers");
const namespace = t.identifier("babelHelpers");
let builder = function (body) {
const builder = function (body) {
return buildHelpers(body, namespace, whitelist);
};
let tree;
let build = {
const build = {
global: buildGlobal,
umd: buildUmd,
var: buildVar,
umd: buildUmd,
var: buildVar,
}[outputType];
if (build) {

View File

@@ -1,11 +1,9 @@
/* global BabelFileResult, BabelParserOptions, BabelFileMetadata */
/* eslint max-len: 0 */
import getHelper from "babel-helpers";
import * as metadataVisitor from "./metadata";
import convertSourceMap from "convert-source-map";
import OptionManager from "./options/option-manager";
import type Pipeline from "../pipeline";
import PluginPass from "../plugin-pass";
import { NodePath, Hub, Scope } from "babel-traverse";
import sourceMap from "source-map";
@@ -16,7 +14,7 @@ import traverse from "babel-traverse";
import Logger from "./logger";
import Store from "../../store";
import { parse } from "babylon";
import * as util from "../../util";
import * as util from "../../util";
import path from "path";
import * as t from "babel-types";
@@ -29,50 +27,48 @@ const shebangRegex = /^#!.*/;
const INTERNAL_PLUGINS = [
[blockHoistPlugin],
[shadowFunctionsPlugin]
[shadowFunctionsPlugin],
];
let errorVisitor = {
const errorVisitor = {
enter(path, state) {
let loc = path.node.loc;
const loc = path.node.loc;
if (loc) {
state.loc = loc;
path.stop();
}
}
},
};
export default class File extends Store {
constructor(opts: Object = {}, pipeline: Pipeline) {
constructor(opts: Object = {}) {
super();
this.pipeline = pipeline;
this.log = new Logger(this, opts.filename || "unknown");
this.log = new Logger(this, opts.filename || "unknown");
this.opts = this.initOptions(opts);
opts = this.initOptions(opts);
let passes = [];
if (opts.plugins) passes.push(opts.plugins);
// With "passPerPreset" enabled there may still be presets in the options.
if (opts.presets) passes = passes.concat(opts.presets.map((preset) => preset.plugins).filter(Boolean));
this.pluginPasses = passes;
this.opts = opts;
this.parserOpts = {
sourceType: this.opts.sourceType,
sourceType: this.opts.sourceType,
sourceFileName: this.opts.filename,
plugins: []
plugins: [],
};
this.pluginVisitors = [];
this.pluginPasses = [];
// Plugins for top-level options.
this.buildPluginsForOptions(this.opts);
// If we are in the "pass per preset" mode, build
// also plugins for each preset.
if (this.opts.passPerPreset) {
// All the "per preset" options are inherited from the main options.
this.perPresetOpts = [];
this.opts.presets.forEach((presetOpts) => {
let perPresetOpts = Object.assign(Object.create(this.opts), presetOpts);
this.perPresetOpts.push(perPresetOpts);
this.buildPluginsForOptions(perPresetOpts);
});
for (const pluginPairs of passes) {
for (const [ plugin ] of pluginPairs) {
if (plugin.manipulateOptions) {
plugin.manipulateOptions(opts, this.parserOpts, this);
}
}
}
this.metadata = {
@@ -82,21 +78,21 @@ export default class File extends Store {
imports: [],
exports: {
exported: [],
specifiers: []
}
}
specifiers: [],
},
},
};
this.dynamicImportTypes = {};
this.dynamicImportIds = {};
this.dynamicImports = [];
this.declarations = {};
this.usedHelpers = {};
this.dynamicImportIds = {};
this.dynamicImports = [];
this.declarations = {};
this.usedHelpers = {};
this.path = null;
this.ast = {};
this.ast = {};
this.code = "";
this.code = "";
this.shebang = "";
this.hub = new Hub(this);
@@ -104,9 +100,7 @@ export default class File extends Store {
static helpers: Array<string>;
pluginVisitors: Array<Object>;
pluginPasses: Array<PluginPass>;
pipeline: Pipeline;
pluginPasses: Array<Array<[Plugin, Object]>>;
parserOpts: BabelParserOptions;
log: Logger;
opts: Object;
@@ -125,7 +119,7 @@ export default class File extends Store {
getMetadata() {
let has = false;
for (let node of (this.ast.program.body: Array<Object>)) {
for (const node of (this.ast.program.body: Array<Object>)) {
if (t.isModuleDeclaration(node)) {
has = true;
break;
@@ -137,7 +131,7 @@ export default class File extends Store {
}
initOptions(opts) {
opts = new OptionManager(this.log, this.pipeline).init(opts);
opts = this.log.wrap(() => new OptionManager().init(opts));
if (opts.inputSourceMap) {
opts.sourceMaps = true;
@@ -154,54 +148,29 @@ export default class File extends Store {
if (opts.only) opts.only = util.arrayify(opts.only, util.regexify);
defaults(opts, {
moduleRoot: opts.sourceRoot
moduleRoot: opts.sourceRoot,
});
defaults(opts, {
sourceRoot: opts.moduleRoot
sourceRoot: opts.moduleRoot,
});
defaults(opts, {
filenameRelative: opts.filename
filenameRelative: opts.filename,
});
let basenameRelative = path.basename(opts.filenameRelative);
const basenameRelative = path.basename(opts.filenameRelative);
defaults(opts, {
sourceFileName: basenameRelative,
sourceMapTarget: basenameRelative
sourceFileName: basenameRelative,
sourceMapTarget: basenameRelative,
});
return opts;
}
buildPluginsForOptions(opts) {
if (!Array.isArray(opts.plugins)) {
return;
}
let plugins: Array<[PluginPass, Object]> = opts.plugins.concat(INTERNAL_PLUGINS);
let currentPluginVisitors = [];
let currentPluginPasses = [];
// init plugins!
for (let ref of plugins) {
let [plugin, pluginOpts] = ref; // todo: fix - can't embed in loop head because of flow bug
currentPluginVisitors.push(plugin.visitor);
currentPluginPasses.push(new PluginPass(this, plugin, pluginOpts));
if (plugin.manipulateOptions) {
plugin.manipulateOptions(opts, this.parserOpts, this);
}
}
this.pluginVisitors.push(currentPluginVisitors);
this.pluginPasses.push(currentPluginPasses);
}
getModuleName(): ?string {
let opts = this.opts;
const opts = this.opts;
if (!opts.moduleIds) {
return null;
}
@@ -224,7 +193,7 @@ export default class File extends Store {
if (opts.sourceRoot != null) {
// remove sourceRoot from filename
let sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?");
const sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?");
filenameRelative = filenameRelative.replace(sourceRootRegEx, "");
}
@@ -245,20 +214,20 @@ export default class File extends Store {
}
resolveModuleSource(source: string): string {
let resolveModuleSource = this.opts.resolveModuleSource;
const resolveModuleSource = this.opts.resolveModuleSource;
if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename);
return source;
}
addImport(source: string, imported: string, name?: string = imported): Object {
let alias = `${source}:${imported}`;
const alias = `${source}:${imported}`;
let id = this.dynamicImportIds[alias];
if (!id) {
source = this.resolveModuleSource(source);
id = this.dynamicImportIds[alias] = this.scope.generateUidIdentifier(name);
let specifiers = [];
const specifiers = [];
if (imported === "*") {
specifiers.push(t.importNamespaceSpecifier(id));
@@ -268,7 +237,7 @@ export default class File extends Store {
specifiers.push(t.importSpecifier(id, t.identifier(imported)));
}
let declar = t.importDeclaration(specifiers, t.stringLiteral(source));
const declar = t.importDeclaration(specifiers, t.stringLiteral(source));
declar._blockHoist = 3;
this.path.unshiftContainer("body", declar);
@@ -278,7 +247,7 @@ export default class File extends Store {
}
addHelper(name: string): Object {
let declar = this.declarations[name];
const declar = this.declarations[name];
if (declar) return declar;
if (!this.usedHelpers[name]) {
@@ -286,17 +255,17 @@ export default class File extends Store {
this.usedHelpers[name] = true;
}
let generator = this.get("helperGenerator");
let runtime = this.get("helpersNamespace");
const generator = this.get("helperGenerator");
const runtime = this.get("helpersNamespace");
if (generator) {
let res = generator(name);
const res = generator(name);
if (res) return res;
} else if (runtime) {
return t.memberExpression(runtime, t.identifier(name));
}
let ref = getHelper(name);
let uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
const ref = getHelper(name);
const uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
if (t.isFunctionExpression(ref) && !ref.id) {
ref.body._compact = true;
@@ -309,7 +278,7 @@ export default class File extends Store {
this.scope.push({
id: uid,
init: ref,
unique: true
unique: true,
});
}
@@ -323,31 +292,31 @@ export default class File extends Store {
): Object {
// Generate a unique name based on the string literals so we dedupe
// identical strings used in the program.
let stringIds = raw.elements.map(function(string) {
const stringIds = raw.elements.map(function(string) {
return string.value;
});
let name = `${helperName}_${raw.elements.length}_${stringIds.join(",")}`;
const name = `${helperName}_${raw.elements.length}_${stringIds.join(",")}`;
let declar = this.declarations[name];
const declar = this.declarations[name];
if (declar) return declar;
let uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject");
const uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject");
let helperId = this.addHelper(helperName);
let init = t.callExpression(helperId, [strings, raw]);
const helperId = this.addHelper(helperName);
const init = t.callExpression(helperId, [strings, raw]);
init._compact = true;
this.scope.push({
id: uid,
init: init,
_blockHoist: 1.9 // This ensures that we don't fail if not using function expression helpers
_blockHoist: 1.9, // This ensures that we don't fail if not using function expression helpers
});
return uid;
}
buildCodeFrameError(node: Object, msg: string, Error: typeof Error = SyntaxError): Error {
let loc = node && (node.loc || node._loc);
const loc = node && (node.loc || node._loc);
let err = new Error(msg);
const err = new Error(msg);
if (loc) {
err.loc = loc.start;
@@ -367,26 +336,26 @@ export default class File extends Store {
}
mergeSourceMap(map: Object) {
let inputMap = this.opts.inputSourceMap;
const inputMap = this.opts.inputSourceMap;
if (inputMap) {
let inputMapConsumer = new sourceMap.SourceMapConsumer(inputMap);
let outputMapConsumer = new sourceMap.SourceMapConsumer(map);
const inputMapConsumer = new sourceMap.SourceMapConsumer(inputMap);
const outputMapConsumer = new sourceMap.SourceMapConsumer(map);
let mergedGenerator = new sourceMap.SourceMapGenerator({
const mergedGenerator = new sourceMap.SourceMapGenerator({
file: inputMapConsumer.file,
sourceRoot: inputMapConsumer.sourceRoot
sourceRoot: inputMapConsumer.sourceRoot,
});
// This assumes the output map always has a single source, since Babel always compiles a single source file to a
// single output file.
// This assumes the output map always has a single source, since Babel always compiles a
// single source file to a single output file.
const source = outputMapConsumer.sources[0];
inputMapConsumer.eachMapping(function (mapping) {
const generatedPosition = outputMapConsumer.generatedPositionFor({
line: mapping.generatedLine,
column: mapping.generatedColumn,
source: source
source: source,
});
if (generatedPosition.column != null) {
mergedGenerator.addMapping({
@@ -394,15 +363,15 @@ export default class File extends Store {
original: mapping.source == null ? null : {
line: mapping.originalLine,
column: mapping.originalColumn
column: mapping.originalColumn,
},
generated: generatedPosition
generated: generatedPosition,
});
}
});
let mergedMap = mergedGenerator.toJSON();
const mergedMap = mergedGenerator.toJSON();
inputMap.mappings = mergedMap.mappings;
return inputMap;
} else {
@@ -419,12 +388,13 @@ export default class File extends Store {
if (parserOpts.parser) {
if (typeof parserOpts.parser === "string") {
let dirname = path.dirname(this.opts.filename) || process.cwd();
let parser = resolve(parserOpts.parser, dirname);
const dirname = path.dirname(this.opts.filename) || process.cwd();
const parser = resolve(parserOpts.parser, dirname);
if (parser) {
parseCode = require(parser).parse;
} else {
throw new Error(`Couldn't find parser ${parserOpts.parser} with "parse" method relative to directory ${dirname}`);
throw new Error(`Couldn't find parser ${parserOpts.parser} with "parse" method ` +
`relative to directory ${dirname}`);
}
} else {
parseCode = parserOpts.parser;
@@ -433,13 +403,13 @@ export default class File extends Store {
parserOpts.parser = {
parse(source) {
return parse(source, parserOpts);
}
},
};
}
}
this.log.debug("Parse start");
let ast = parseCode(code, parserOpts || this.parserOpts);
const ast = parseCode(code, parserOpts || this.parserOpts);
this.log.debug("Parse stop");
return ast;
}
@@ -450,10 +420,10 @@ export default class File extends Store {
parentPath: null,
parent: ast,
container: ast,
key: "program"
key: "program",
}).setContext();
this.scope = this.path.scope;
this.ast = ast;
this.ast = ast;
this.getMetadata();
}
@@ -464,19 +434,25 @@ export default class File extends Store {
}
transform(): BabelFileResult {
// In the "pass per preset" mode, we have grouped passes.
// Otherwise, there is only one plain pluginPasses array.
for (let i = 0; i < this.pluginPasses.length; i++) {
const pluginPasses = this.pluginPasses[i];
this.call("pre", pluginPasses);
for (const pluginPairs of this.pluginPasses) {
const passes = [];
const visitors = [];
for (const [ plugin, pluginOpts ] of pluginPairs.concat(INTERNAL_PLUGINS)) {
const pass = new PluginPass(this, plugin, pluginOpts);
passes.push(pass);
visitors.push(plugin.visitor);
}
this.call("pre", passes);
this.log.debug("Start transform traverse");
// merge all plugin visitors into a single visitor
let visitor = traverse.visitors.merge(this.pluginVisitors[i], pluginPasses, this.opts.wrapPluginVisitorMethod);
const visitor = traverse.visitors.merge(visitors, passes, this.opts.wrapPluginVisitorMethod);
traverse(this.ast, visitor, this.scope);
this.log.debug("End transform traverse");
this.call("post", pluginPasses);
this.call("post", passes);
}
return this.generate();
@@ -500,7 +476,7 @@ export default class File extends Store {
let message = err.message = `${this.opts.filename}: ${err.message}`;
let loc = err.loc;
const loc = err.loc;
if (loc) {
err.codeFrame = codeFrame(code, loc.line, loc.column + 1, this.opts);
message += "\n" + err.codeFrame;
@@ -513,7 +489,7 @@ export default class File extends Store {
}
if (err.stack) {
let newStack = err.stack.replace(err.message, message);
const newStack = err.stack.replace(err.message, message);
err.stack = newStack;
}
@@ -529,28 +505,28 @@ export default class File extends Store {
parseCode() {
this.parseShebang();
let ast = this.parse(this.code);
const ast = this.parse(this.code);
this.addAst(ast);
}
shouldIgnore() {
let opts = this.opts;
const opts = this.opts;
return util.shouldIgnore(opts.filename, opts.ignore, opts.only);
}
call(key: "pre" | "post", pluginPasses: Array<PluginPass>) {
for (let pass of pluginPasses) {
let plugin = pass.plugin;
let fn = plugin[key];
for (const pass of pluginPasses) {
const plugin = pass.plugin;
const fn = plugin[key];
if (fn) fn.call(pass, this);
}
}
parseInputSourceMap(code: string): string {
let opts = this.opts;
const opts = this.opts;
if (opts.inputSourceMap !== false) {
let inputMap = convertSourceMap.fromSource(code);
const inputMap = convertSourceMap.fromSource(code);
if (inputMap) {
opts.inputSourceMap = inputMap.toObject();
code = convertSourceMap.removeComments(code);
@@ -561,7 +537,7 @@ export default class File extends Store {
}
parseShebang() {
let shebangMatch = shebangRegex.exec(this.code);
const shebangMatch = shebangRegex.exec(this.code);
if (shebangMatch) {
this.shebang = shebangMatch[0];
this.code = this.code.replace(shebangRegex, "");
@@ -569,13 +545,13 @@ export default class File extends Store {
}
makeResult({ code, map, ast, ignored }: BabelFileResult): BabelFileResult {
let result = {
const result = {
metadata: null,
options: this.opts,
ignored: !!ignored,
code: null,
ast: null,
map: map || null
options: this.opts,
ignored: !!ignored,
code: null,
ast: null,
map: map || null,
};
if (this.opts.code) {
@@ -594,10 +570,10 @@ export default class File extends Store {
}
generate(): BabelFileResult {
let opts = this.opts;
let ast = this.ast;
const opts = this.opts;
const ast = this.ast;
let result: BabelFileResult = { ast };
const result: BabelFileResult = { ast };
if (!opts.code) return this.makeResult(result);
let gen = generate;
@@ -605,21 +581,23 @@ export default class File extends Store {
gen = opts.generatorOpts.generator;
if (typeof gen === "string") {
let dirname = path.dirname(this.opts.filename) || process.cwd();
let generator = resolve(gen, dirname);
const dirname = path.dirname(this.opts.filename) || process.cwd();
const generator = resolve(gen, dirname);
if (generator) {
gen = require(generator).print;
} else {
throw new Error(`Couldn't find generator ${gen} with "print" method relative to directory ${dirname}`);
throw new Error(`Couldn't find generator ${gen} with "print" method relative ` +
`to directory ${dirname}`);
}
}
}
this.log.debug("Generation start");
let _result = gen(ast, opts.generatorOpts ? Object.assign(opts, opts.generatorOpts) : opts, this.code);
const _result = gen(ast, opts.generatorOpts ? Object.assign(opts, opts.generatorOpts) : opts,
this.code);
result.code = _result.code;
result.map = _result.map;
result.map = _result.map;
this.log.debug("Generation end");

View File

@@ -1,15 +1,15 @@
import type File from "./index";
import buildDebug from "debug";
let verboseDebug = buildDebug("babel:verbose");
let generalDebug = buildDebug("babel");
const verboseDebug = buildDebug("babel:verbose");
const generalDebug = buildDebug("babel");
let seenDeprecatedMessages = [];
const seenDeprecatedMessages = [];
export default class Logger {
constructor(file: File, filename: string) {
this.filename = filename;
this.file = file;
this.file = file;
}
filename: string;
@@ -21,6 +21,15 @@ export default class Logger {
return parts;
}
wrap<T>(callback: () => T): T {
try {
return callback();
} catch (e) {
e.message = this._buildMessage(e.message);
throw e;
}
}
warn(msg: string) {
console.warn(this._buildMessage(msg));
}

View File

@@ -1,45 +1,45 @@
import * as t from "babel-types";
export let ModuleDeclaration = {
export const ModuleDeclaration = {
enter(path, file) {
let { node } = path;
const { node } = path;
if (node.source) {
node.source.value = file.resolveModuleSource(node.source.value);
}
}
},
};
export let ImportDeclaration = {
export const ImportDeclaration = {
exit(path, file) {
let { node } = path;
const { node } = path;
let specifiers = [];
let imported = [];
const specifiers = [];
const imported = [];
file.metadata.modules.imports.push({
source: node.source.value,
imported,
specifiers
specifiers,
});
for (let specifier of (path.get("specifiers"): Array<Object>)) {
let local = specifier.node.local.name;
for (const specifier of (path.get("specifiers"): Array<Object>)) {
const local = specifier.node.local.name;
if (specifier.isImportDefaultSpecifier()) {
imported.push("default");
specifiers.push({
kind: "named",
imported: "default",
local
local,
});
}
if (specifier.isImportSpecifier()) {
let importedName = specifier.node.imported.name;
const importedName = specifier.node.imported.name;
imported.push(importedName);
specifiers.push({
kind: "named",
imported: importedName,
local
local,
});
}
@@ -47,38 +47,38 @@ export let ImportDeclaration = {
imported.push("*");
specifiers.push({
kind: "namespace",
local
local,
});
}
}
}
},
};
export function ExportDeclaration(path, file) {
let { node } = path;
const { node } = path;
let source = node.source ? node.source.value : null;
let exports = file.metadata.modules.exports;
const source = node.source ? node.source.value : null;
const exports = file.metadata.modules.exports;
// export function foo() {}
// export let foo = "bar";
let declar = path.get("declaration");
const declar = path.get("declaration");
if (declar.isStatement()) {
let bindings = declar.getBindingIdentifiers();
const bindings = declar.getBindingIdentifiers();
for (let name in bindings) {
for (const name in bindings) {
exports.exported.push(name);
exports.specifiers.push({
kind: "local",
local: name,
exported: path.isExportDefaultDeclaration() ? "default" : name
exported: path.isExportDefaultDeclaration() ? "default" : name,
});
}
}
if (path.isExportNamedDeclaration() && node.specifiers) {
for (let specifier of (node.specifiers: Array<Object>)) {
let exported = specifier.exported.name;
for (const specifier of (node.specifiers: Array<Object>)) {
const exported = specifier.exported.name;
exports.exported.push(exported);
// export foo from "bar";
@@ -87,7 +87,7 @@ export function ExportDeclaration(path, file) {
kind: "external",
local: exported,
exported,
source
source,
});
}
@@ -96,11 +96,11 @@ export function ExportDeclaration(path, file) {
exports.specifiers.push({
kind: "external-namespace",
exported,
source
source,
});
}
let local = specifier.local;
const local = specifier.local;
if (!local) continue;
// export { foo } from "bar";
@@ -110,7 +110,7 @@ export function ExportDeclaration(path, file) {
kind: "external",
local: local.name,
exported,
source
source,
});
}
@@ -120,7 +120,7 @@ export function ExportDeclaration(path, file) {
exports.specifiers.push({
kind: "local",
local: local.name,
exported
exported,
});
}
}
@@ -130,7 +130,7 @@ export function ExportDeclaration(path, file) {
if (path.isExportAllDeclaration()) {
exports.specifiers.push({
kind: "external-all",
source
source,
});
}
}

View File

@@ -1,20 +1,18 @@
import type Logger from "../logger";
import resolve from "../../../helpers/resolve";
import json5 from "json5";
import isAbsolute from "path-is-absolute";
import path from "path";
import fs from "fs";
let existsCache = {};
let jsonCache = {};
const existsCache = {};
const jsonCache = {};
const BABELRC_FILENAME = ".babelrc";
const BABELRC_JS_FILENAME = ".babelrc.js";
const PACKAGE_FILENAME = "package.json";
const BABELIGNORE_FILENAME = ".babelignore";
const BABELRC_FILENAME = ".babelrc";
const PACKAGE_FILENAME = "package.json";
function exists(filename) {
let cached = existsCache[filename];
const cached = existsCache[filename];
if (cached == null) {
return existsCache[filename] = fs.existsSync(filename);
} else {
@@ -22,9 +20,9 @@ function exists(filename) {
}
}
export default function buildConfigChain(opts: Object = {}, log?: Logger) {
let filename = opts.filename;
let builder = new ConfigChainBuilder(log);
export default function buildConfigChain(opts: Object = {}) {
const filename = opts.filename;
const builder = new ConfigChainBuilder();
// resolve all .babelrc files
if (opts.babelrc !== false) {
@@ -34,23 +32,27 @@ export default function buildConfigChain(opts: Object = {}, log?: Logger) {
builder.mergeConfig({
options: opts,
alias: "base",
dirname: filename && path.dirname(filename)
dirname: filename && path.dirname(filename),
});
return builder.configs;
}
class ConfigChainBuilder {
constructor(log?: Logger) {
constructor() {
this.resolvedConfigs = [];
this.configs = [];
this.log = log;
}
findConfigs(loc) {
errorMultipleConfigs(loc1: string, loc2: string) {
throw new Error(`Multiple configuration files found. Please remove one:\n- ${
loc1}\n- ${loc2}`);
}
findConfigs(loc: string) {
if (!loc) return;
if (!isAbsolute(loc)) {
if (!path.isAbsolute(loc)) {
loc = path.join(process.cwd(), loc);
}
@@ -59,20 +61,31 @@ class ConfigChainBuilder {
while (loc !== (loc = path.dirname(loc))) {
if (!foundConfig) {
let configLoc = path.join(loc, BABELRC_FILENAME);
if (exists(configLoc)) {
this.addConfig(configLoc);
foundConfig = true;
}
const configLoc = path.join(loc, BABELRC_FILENAME);
const configJSLoc = path.join(loc, BABELRC_JS_FILENAME);
const pkgLoc = path.join(loc, PACKAGE_FILENAME);
const configLocs = [configLoc, configJSLoc, pkgLoc];
const foundConfigs = configLocs.reduce((arr, config) => {
if (exists(config)) {
const configAdded = config === pkgLoc
? this.addConfig(config, "babel", JSON)
: this.addConfig(config);
let pkgLoc = path.join(loc, PACKAGE_FILENAME);
if (!foundConfig && exists(pkgLoc)) {
foundConfig = this.addConfig(pkgLoc, "babel", JSON);
}
if (configAdded && arr.length) {
this.errorMultipleConfigs(arr.pop(), config);
}
arr.push(config);
}
return arr;
}, []);
foundConfig = !!foundConfigs.length;
}
if (!foundIgnore) {
let ignoreLoc = path.join(loc, BABELIGNORE_FILENAME);
const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME);
if (exists(ignoreLoc)) {
this.addIgnoreConfig(ignoreLoc);
foundIgnore = true;
@@ -83,8 +96,8 @@ class ConfigChainBuilder {
}
}
addIgnoreConfig(loc) {
let file = fs.readFileSync(loc, "utf8");
addIgnoreConfig(loc: string) {
const file = fs.readFileSync(loc, "utf8");
let lines = file.split("\n");
lines = lines
@@ -95,7 +108,7 @@ class ConfigChainBuilder {
this.mergeConfig({
options: { ignore: lines },
alias: loc,
dirname: path.dirname(loc)
dirname: path.dirname(loc),
});
}
}
@@ -107,21 +120,41 @@ class ConfigChainBuilder {
this.resolvedConfigs.push(loc);
let content = fs.readFileSync(loc, "utf8");
let options;
if (path.extname(loc) === ".js") {
try {
const configModule = require(loc);
options = configModule && configModule.__esModule ? configModule.default : configModule;
} catch (err) {
err.message = `${loc}: Error while loading config - ${err.message}`;
throw err;
}
try {
options = jsonCache[content] = jsonCache[content] || json.parse(content);
if (key) options = options[key];
} catch (err) {
err.message = `${loc}: Error while parsing JSON - ${err.message}`;
throw err;
if (!options || typeof options !== "object") {
throw new Error("Configuration should be an exported JavaScript object.");
}
} else {
const content = fs.readFileSync(loc, "utf8");
try {
options = jsonCache[content] = jsonCache[content] || json.parse(content);
} catch (err) {
err.message = `${loc}: Error while parsing JSON - ${err.message}`;
throw err;
}
}
if (key) {
if (!options[key]) {
return false;
}
options = options[key];
}
this.mergeConfig({
options,
alias: loc,
dirname: path.dirname(loc)
dirname: path.dirname(loc),
});
return !!options;
@@ -131,7 +164,7 @@ class ConfigChainBuilder {
options,
alias,
loc,
dirname
dirname,
}) {
if (!options) {
return false;
@@ -144,11 +177,11 @@ class ConfigChainBuilder {
// add extends clause
if (options.extends) {
let extendsLoc = resolve(options.extends, dirname);
const extendsLoc = resolve(options.extends, dirname);
if (extendsLoc) {
this.addConfig(extendsLoc);
} else {
if (this.log) this.log.error(`Couldn't resolve extends clause of ${options.extends} in ${alias}`);
throw new Error(`Couldn't resolve extends clause of ${options.extends} in ${alias}`);
}
delete options.extends;
}
@@ -157,12 +190,12 @@ class ConfigChainBuilder {
options,
alias,
loc,
dirname
dirname,
});
// env
let envOpts;
let envKey = process.env.BABEL_ENV || process.env.NODE_ENV || "development";
const envKey = process.env.BABEL_ENV || process.env.NODE_ENV || "development";
if (options.env) {
envOpts = options.env[envKey];
delete options.env;
@@ -171,7 +204,7 @@ class ConfigChainBuilder {
this.mergeConfig({
options: envOpts,
alias: `${alias}.env.${envKey}`,
dirname: dirname
dirname: dirname,
});
}
}

View File

@@ -1,195 +1,195 @@
/* eslint max-len: 0 */
/* eslint max-len: "off" */
module.exports = {
export default {
filename: {
type: "filename",
description: "filename to use when reading from stdin - this will be used in source-maps, errors etc",
default: "unknown",
shorthand: "f"
shorthand: "f",
},
filenameRelative: {
hidden: true,
type: "string"
type: "string",
},
inputSourceMap: {
hidden: true
hidden: true,
},
env: {
hidden: true,
default: {}
default: {},
},
mode: {
description: "",
hidden: true
hidden: true,
},
retainLines: {
type: "boolean",
default: false,
description: "retain line numbers - will result in really ugly code"
description: "retain line numbers - will result in really ugly code",
},
highlightCode: {
description: "enable/disable ANSI syntax highlighting of code frames (on by default)",
type: "boolean",
default: true
default: true,
},
suppressDeprecationMessages: {
type: "boolean",
default: false,
hidden: true
hidden: true,
},
presets: {
type: "list",
description: "",
default: []
default: [],
},
plugins: {
type: "list",
default: [],
description: ""
description: "",
},
ignore: {
type: "list",
description: "list of glob paths to **not** compile",
default: []
default: [],
},
only: {
type: "list",
description: "list of glob paths to **only** compile"
description: "list of glob paths to **only** compile",
},
code: {
hidden: true,
default: true,
type: "boolean"
type: "boolean",
},
metadata: {
hidden: true,
default: true,
type: "boolean"
type: "boolean",
},
ast: {
hidden: true,
default: true,
type: "boolean"
type: "boolean",
},
extends: {
type: "string",
hidden: true
hidden: true,
},
comments: {
type: "boolean",
default: true,
description: "write comments to generated output (true by default)"
description: "write comments to generated output (true by default)",
},
shouldPrintComment: {
hidden: true,
description: "optional callback to control whether a comment should be inserted, when this is used the comments option is ignored"
description: "optional callback to control whether a comment should be inserted, when this is used the comments option is ignored",
},
wrapPluginVisitorMethod: {
hidden: true,
description: "optional callback to wrap all visitor methods"
description: "optional callback to wrap all visitor methods",
},
compact: {
type: "booleanString",
default: "auto",
description: "do not include superfluous whitespace characters and line terminators [true|false|auto]"
description: "do not include superfluous whitespace characters and line terminators [true|false|auto]",
},
minified: {
type: "boolean",
default: false,
description: "save as much bytes when printing [true|false]"
description: "save as much bytes when printing [true|false]",
},
sourceMap: {
alias: "sourceMaps",
hidden: true
hidden: true,
},
sourceMaps: {
type: "booleanString",
description: "[true|false|inline]",
default: false,
shorthand: "s"
shorthand: "s",
},
sourceMapTarget: {
type: "string",
description: "set `file` on returned source map"
description: "set `file` on returned source map",
},
sourceFileName: {
type: "string",
description: "set `sources[0]` on returned source map"
description: "set `sources[0]` on returned source map",
},
sourceRoot: {
type: "filename",
description: "the root from which all sources are relative"
description: "the root from which all sources are relative",
},
babelrc: {
description: "Whether or not to look up .babelrc and .babelignore files",
type: "boolean",
default: true
default: true,
},
sourceType: {
description: "",
default: "module"
default: "module",
},
auxiliaryCommentBefore: {
type: "string",
description: "print a comment before any injected non-user code"
description: "print a comment before any injected non-user code",
},
auxiliaryCommentAfter: {
type: "string",
description: "print a comment after any injected non-user code"
description: "print a comment after any injected non-user code",
},
resolveModuleSource: {
hidden: true
hidden: true,
},
getModuleId: {
hidden: true
hidden: true,
},
moduleRoot: {
type: "filename",
description: "optional prefix for the AMD module formatter that will be prepend to the filename on module definitions"
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"
description: "insert an explicit id for modules",
},
moduleId: {
description: "specify a custom name for module ids",
type: "string"
type: "string",
},
passPerPreset: {
@@ -202,12 +202,12 @@ module.exports = {
// Deprecate top level parserOpts
parserOpts: {
description: "Options to pass into the parser, or to change parsers (parserOpts.parser)",
default: false
default: false,
},
// Deprecate top level generatorOpts
generatorOpts: {
description: "Options to pass into the generator, or to change generators (generatorOpts.generator)",
default: false
}
default: false,
},
};

View File

@@ -4,7 +4,7 @@ import config from "./config";
export { config };
export function normaliseOptions(options: Object = {}): Object {
for (let key in options) {
for (const key in options) {
let val = options[key];
if (val == null) continue;
@@ -12,7 +12,7 @@ export function normaliseOptions(options: Object = {}): Object {
if (opt && opt.alias) opt = config[opt.alias];
if (!opt) continue;
let parser = parsers[opt.type];
const parser = parsers[opt.type];
if (parser) val = parser(val);
options[key] = val;

View File

@@ -1,11 +1,9 @@
/* eslint max-len: 0 */
import * as context from "../../../api/node";
import type Logger from "../logger";
import * as context from "../../../index";
import Plugin from "../../plugin";
import * as messages from "babel-messages";
import { normaliseOptions } from "./index";
import resolve from "../../../helpers/resolve";
import resolvePlugin from "../../../helpers/resolve-plugin";
import resolvePreset from "../../../helpers/resolve-preset";
import cloneDeepWith from "lodash/cloneDeepWith";
import clone from "lodash/clone";
import merge from "../../../helpers/merge";
@@ -36,15 +34,13 @@ type MergeOptions = {
};
export default class OptionManager {
constructor(log?: Logger) {
constructor() {
this.resolvedConfigs = [];
this.options = OptionManager.createBareOptions();
this.log = log;
}
resolvedConfigs: Array<string>;
options: Object;
log: ?Logger;
static memoisedPlugins: Array<{
container: Function;
@@ -52,7 +48,7 @@ export default class OptionManager {
}>;
static memoisePluginContainer(fn, loc, i, alias) {
for (let cache of (OptionManager.memoisedPlugins: Array<Object>)) {
for (const cache of (OptionManager.memoisedPlugins: Array<Object>)) {
if (cache.container === fn) return cache.plugin;
}
@@ -65,10 +61,10 @@ export default class OptionManager {
}
if (typeof obj === "object") {
let plugin = new Plugin(obj, alias);
const plugin = new Plugin(obj, alias);
OptionManager.memoisedPlugins.push({
container: fn,
plugin: plugin
plugin: plugin,
});
return plugin;
} else {
@@ -77,10 +73,10 @@ export default class OptionManager {
}
static createBareOptions() {
let opts = {};
const opts = {};
for (let key in config) {
let opt = config[key];
for (const key in config) {
const opt = config[key];
opts[key] = clone(opt.default);
}
@@ -119,11 +115,11 @@ export default class OptionManager {
plugin = val;
}
let alias = typeof plugin === "string" ? plugin : `${loc}$${i}`;
const alias = typeof plugin === "string" ? plugin : `${loc}$${i}`;
// allow plugins to be specified as strings
if (typeof plugin === "string") {
let pluginLoc = resolve(`babel-plugin-${plugin}`, dirname) || resolve(plugin, dirname);
const pluginLoc = resolvePlugin(plugin, dirname);
if (pluginLoc) {
plugin = require(pluginLoc);
} else {
@@ -152,18 +148,18 @@ export default class OptionManager {
extending: extendingOpts,
alias,
loc,
dirname
dirname,
}: MergeOptions) {
alias = alias || "foreign";
if (!rawOpts) return;
//
if (typeof rawOpts !== "object" || Array.isArray(rawOpts)) {
this.log.error(`Invalid options type for ${alias}`, TypeError);
throw new TypeError(`Invalid options type for ${alias}`);
}
//
let opts = cloneDeepWith(rawOpts, (val) => {
const opts = cloneDeepWith(rawOpts, (val) => {
if (val instanceof Plugin) {
return val;
}
@@ -173,18 +169,18 @@ export default class OptionManager {
dirname = dirname || process.cwd();
loc = loc || alias;
for (let key in opts) {
let option = config[key];
for (const key in opts) {
const option = config[key];
// check for an unknown option
if (!option && this.log) {
if (!option) {
if (removed[key]) {
this.log.error(`Using removed Babel 5 option: ${alias}.${key} - ${removed[key].message}`, ReferenceError);
throw new ReferenceError(`Using removed Babel 5 option: ${alias}.${key} - ${removed[key].message}`);
} else {
let unknownOptErr = `Unknown option: ${alias}.${key}. Check out http://babeljs.io/docs/usage/options/ for more information about options.`;
let presetConfigErr = "A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:\n\nInvalid:\n `{ presets: [{option: value}] }`\nValid:\n `{ presets: [['presetName', {option: value}]] }`\n\nFor more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options.";
// eslint-disable-next-line max-len
const unknownOptErr = `Unknown option: ${alias}.${key}. Check out http://babeljs.io/docs/usage/options/ for more information about options.`;
this.log.error(`${unknownOptErr}\n\n${presetConfigErr}`, ReferenceError);
throw new ReferenceError(unknownOptErr);
}
}
}
@@ -208,7 +204,7 @@ export default class OptionManager {
extending: preset,
alias: presetLoc,
loc: presetLoc,
dirname: dirname
dirname: dirname,
});
});
} else {
@@ -238,7 +234,7 @@ export default class OptionManager {
options: presetOpts,
alias: presetLoc,
loc: presetLoc,
dirname: path.dirname(presetLoc || "")
dirname: path.dirname(presetLoc || ""),
});
});
}
@@ -248,89 +244,77 @@ export default class OptionManager {
* or a module name to require.
*/
resolvePresets(presets: Array<string | Object>, dirname: string, onResolve?) {
return presets.map((val) => {
return presets.map((preset) => {
let options;
if (Array.isArray(val)) {
if (val.length > 2) {
throw new Error(`Unexpected extra options ${JSON.stringify(val.slice(2))} passed to preset.`);
if (Array.isArray(preset)) {
if (preset.length > 2) {
throw new Error(`Unexpected extra options ${JSON.stringify(preset.slice(2))} passed to preset.`);
}
[val, options] = val;
[preset, options] = preset;
}
let presetLoc;
try {
if (typeof val === "string") {
presetLoc = resolve(`babel-preset-${val}`, dirname) || resolve(val, dirname);
// trying to resolve @organization shortcat
// @foo/es2015 -> @foo/babel-preset-es2015
if (!presetLoc) {
let matches = val.match(/^(@[^/]+)\/(.+)$/);
if (matches) {
let [, orgName, presetPath] = matches;
val = `${orgName}/babel-preset-${presetPath}`;
presetLoc = resolve(val, dirname);
}
}
if (typeof preset === "string") {
presetLoc = resolvePreset(preset, dirname);
if (!presetLoc) {
throw new Error(`Couldn't find preset ${JSON.stringify(val)} relative to directory ` +
throw new Error(`Couldn't find preset ${JSON.stringify(preset)} relative to directory ` +
JSON.stringify(dirname));
}
val = require(presetLoc);
}
const resolvedPreset = this.loadPreset(presetLoc || preset, options, { dirname });
// If the imported preset is a transpiled ES2015 module
if (typeof val === "object" && val.__esModule) {
// Try to grab the default export.
if (val.default) {
val = val.default;
} else {
// If there is no default export we treat all named exports as options
// and just remove the __esModule. This is to support presets that have been
// exporting named exports in the past, although we definitely want presets to
// only use the default export (with either an object or a function)
const { __esModule, ...rest } = val; // eslint-disable-line no-unused-vars
val = rest;
}
}
if (onResolve) onResolve(resolvedPreset, presetLoc);
// For compatibility with babel-core < 6.13.x, allow presets to export an object with a
// a 'buildPreset' function that will return the preset itself, while still exporting a
// simple object (rather than a function), for supporting old Babel versions.
if (typeof val === "object" && val.buildPreset) val = val.buildPreset;
if (typeof val !== "function" && options !== undefined) {
throw new Error(`Options ${JSON.stringify(options)} passed to ` +
(presetLoc || "a preset") + " which does not accept options.");
}
if (typeof val === "function") val = val(context, options);
if (typeof val !== "object") {
throw new Error(`Unsupported preset format: ${val}.`);
}
onResolve && onResolve(val, presetLoc);
return resolvedPreset;
} catch (e) {
if (presetLoc) {
e.message += ` (While processing preset: ${JSON.stringify(presetLoc)})`;
}
throw e;
}
return val;
});
}
normaliseOptions() {
let opts = this.options;
/**
* Tries to load one preset. The input is either the module name of the preset,
* a function, or an object
*/
loadPreset(preset, options, meta) {
let presetFactory = preset;
if (typeof presetFactory === "string") {
presetFactory = require(presetFactory);
}
for (let key in config) {
let option = config[key];
let val = opts[key];
if (typeof presetFactory === "object" && presetFactory.__esModule) {
if (presetFactory.default) {
presetFactory = presetFactory.default;
} else {
throw new Error("Preset must export a default export when using ES6 modules.");
}
}
// Allow simple object exports
if (typeof presetFactory === "object") {
return presetFactory;
}
if (typeof presetFactory !== "function") {
// eslint-disable-next-line max-len
throw new Error(`Unsupported preset format: ${typeof presetFactory}. Expected preset to return a function.`);
}
return presetFactory(context, options, meta);
}
normaliseOptions() {
const opts = this.options;
for (const key in config) {
const option = config[key];
const val = opts[key];
// optional
if (!val && option.optional) continue;
@@ -345,7 +329,7 @@ export default class OptionManager {
}
init(opts: Object = {}): Object {
for (let config of buildConfigChain(opts, this.log)) {
for (const config of buildConfigChain(opts)) {
this.mergeOptions(config);
}

View File

@@ -1,7 +1,7 @@
import slash from "slash";
import * as util from "../../../util";
export let filename = slash;
export const filename = slash;
export function boolean(val: any): boolean {
return !!val;

View File

@@ -1,35 +1,35 @@
/* eslint max-len: 0 */
/* eslint max-len: "off" */
module.exports = {
export default {
"auxiliaryComment": {
"message": "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`"
"message": "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`",
},
"blacklist": {
"message": "Put the specific transforms you want in the `plugins` option"
"message": "Put the specific transforms you want in the `plugins` option",
},
"breakConfig": {
"message": "This is not a necessary option in Babel 6"
"message": "This is not a necessary option in Babel 6",
},
"experimental": {
"message": "Put the specific transforms you want in the `plugins` option"
"message": "Put the specific transforms you want in the `plugins` option",
},
"externalHelpers": {
"message": "Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/"
"message": "Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/",
},
"extra": {
"message": ""
"message": "",
},
"jsxPragma": {
"message": "use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/"
"message": "use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/",
},
// "keepModuleIdExtensions": {
// "message": ""
// },
"loose": {
"message": "Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option."
"message": "Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option.",
},
"metadataUsedHelpers": {
"message": "Not required anymore as this is enabled by default"
"message": "Not required anymore as this is enabled by default",
},
"modules": {
"message": "Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules",
@@ -38,15 +38,15 @@ module.exports = {
"message": "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/",
},
"optional": {
"message": "Put the specific transforms you want in the `plugins` option"
"message": "Put the specific transforms you want in the `plugins` option",
},
"sourceMapName": {
"message": "Use the `sourceMapTarget` option"
"message": "Use the `sourceMapTarget` option",
},
"stage": {
"message": "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets"
"message": "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets",
},
"whitelist": {
"message": "Put the specific transforms you want in the `plugins` option"
}
"message": "Put the specific transforms you want in the `plugins` option",
},
};

View File

@@ -20,7 +20,7 @@ export default new Plugin({
exit({ node }) {
let hasChange = false;
for (let i = 0; i < node.body.length; i++) {
let bodyNode = node.body[i];
const bodyNode = node.body[i];
if (bodyNode && bodyNode._blockHoist != null) {
hasChange = true;
break;
@@ -36,7 +36,7 @@ export default new Plugin({
// Higher priorities should move toward the top.
return -1 * priority;
});
}
}
}
},
},
},
});

View File

@@ -7,12 +7,12 @@ const superVisitor = {
CallExpression(path) {
if (!path.get("callee").isSuper()) return;
const {node} = path;
const { node } = path;
if (node[SUPER_THIS_BOUND]) return;
node[SUPER_THIS_BOUND] = true;
path.replaceWith(t.assignmentExpression("=", this.id, node));
}
},
};
export default new Plugin({
@@ -27,8 +27,8 @@ export default new Plugin({
if (path.node.name === "arguments") {
remap(path, "arguments");
}
}
}
},
},
});
function shouldShadow(path, shadowPath) {
@@ -41,10 +41,10 @@ function shouldShadow(path, shadowPath) {
function remap(path, key) {
// ensure that we're shadowed
let shadowPath = path.inShadow(key);
const shadowPath = path.inShadow(key);
if (!shouldShadow(path, shadowPath)) return;
let shadowFunction = path.node._shadowedFunctionLiteral;
const shadowFunction = path.node._shadowedFunctionLiteral;
let currentFunction;
let passedShadowFunction = false;
@@ -91,17 +91,17 @@ function remap(path, key) {
// binding since arrow function syntax already does that.
if (!passedShadowFunction) return;
let cached = fnPath.getData(key);
const cached = fnPath.getData(key);
if (cached) return path.replaceWith(cached);
let id = path.scope.generateUidIdentifier(key);
const id = path.scope.generateUidIdentifier(key);
fnPath.setData(key, id);
let classPath = fnPath.findParent((p) => p.isClass());
let hasSuperClass = !!(classPath && classPath.node && classPath.node.superClass);
const classPath = fnPath.findParent((p) => p.isClass());
const hasSuperClass = !!(classPath && classPath.node && classPath.node.superClass);
if (key === "this" && fnPath.isMethod({kind: "constructor"}) && hasSuperClass) {
if (key === "this" && fnPath.isMethod({ kind: "constructor" }) && hasSuperClass) {
fnPath.scope.push({ id });
fnPath.traverse(superVisitor, { id });

View File

@@ -3,48 +3,31 @@ import normalizeAst from "../helpers/normalize-ast";
import Plugin from "./plugin";
import File from "./file";
export default class Pipeline {
lint(code: string, opts?: Object = {}): BabelFileResult {
opts.code = false;
opts.mode = "lint";
return this.transform(code, opts);
}
pretransform(code: string, opts?: Object): BabelFileResult {
let file = new File(opts, this);
return file.wrap(code, function () {
file.addCode(code);
file.parseCode(code);
return file;
});
}
transform(code: string, opts?: Object): BabelFileResult {
let file = new File(opts, this);
return file.wrap(code, function () {
file.addCode(code);
file.parseCode(code);
return file.transform();
});
}
analyse(code: string, opts: Object = {}, visitor?: Object): ?BabelFileMetadata {
opts.code = false;
if (visitor) {
opts.plugins = opts.plugins || [];
opts.plugins.push(new Plugin({ visitor }));
}
return this.transform(code, opts).metadata;
}
transformFromAst(ast: Object, code: string, opts: Object): BabelFileResult {
ast = normalizeAst(ast);
let file = new File(opts, this);
return file.wrap(code, function () {
file.addCode(code);
file.addAst(ast);
return file.transform();
});
export function analyse(code: string, opts: Object = {}, visitor?: Object): ?BabelFileMetadata {
opts.code = false;
if (visitor) {
opts.plugins = opts.plugins || [];
opts.plugins.push(new Plugin({ visitor }));
}
return transform(code, opts).metadata;
}
export function transform(code: string, opts?: Object): BabelFileResult {
const file = new File(opts);
return file.wrap(code, function () {
file.addCode(code);
file.parseCode(code);
return file.transform();
});
}
export function transformFromAst(ast: Object, code: string, opts: Object): BabelFileResult {
ast = normalizeAst(ast);
const file = new File(opts);
return file.wrap(code, function () {
file.addCode(code);
file.addAst(ast);
return file.transform();
});
}

View File

@@ -6,9 +6,9 @@ export default class PluginPass extends Store {
constructor(file: File, plugin: Plugin, options: Object = {}) {
super();
this.plugin = plugin;
this.key = plugin.key;
this.file = file;
this.opts = options;
this.key = plugin.key;
this.file = file;
this.opts = options;
}
key: string;

View File

@@ -1,10 +1,7 @@
/* eslint max-len: 0 */
import OptionManager from "./file/options/option-manager";
import * as messages from "babel-messages";
import Store from "../store";
import traverse from "babel-traverse";
import assign from "lodash/assign";
import clone from "lodash/clone";
const GLOBAL_VISITOR_PROPS = ["enter", "exit"];
@@ -14,13 +11,13 @@ export default class Plugin extends Store {
super();
this.initialized = false;
this.raw = assign({}, plugin);
this.key = this.take("name") || key;
this.raw = Object.assign({}, plugin);
this.key = this.take("name") || key;
this.manipulateOptions = this.take("manipulateOptions");
this.post = this.take("post");
this.pre = this.take("pre");
this.visitor = this.normaliseVisitor(clone(this.take("visitor")) || {});
this.post = this.take("post");
this.pre = this.take("pre");
this.visitor = this.normaliseVisitor(clone(this.take("visitor")) || {});
}
initialized: boolean;
@@ -31,7 +28,7 @@ export default class Plugin extends Store {
visitor: Object;
take(key) {
let val = this.raw[key];
const val = this.raw[key];
delete this.raw[key];
return val;
}
@@ -40,13 +37,13 @@ export default class Plugin extends Store {
if (!target[key]) return this[key];
if (!this[key]) return target[key];
let fns: Array<?Function> = [target[key], this[key]];
const fns: Array<?Function> = [target[key], this[key]];
return function (...args) {
let val;
for (let fn of fns) {
for (const fn of fns) {
if (fn) {
let ret = fn.apply(this, args);
const ret = fn.apply(this, args);
if (ret != null) val = ret;
}
}
@@ -77,15 +74,16 @@ export default class Plugin extends Store {
this.maybeInherit(loc);
for (let key in this.raw) {
for (const key in this.raw) {
throw new Error(messages.get("pluginInvalidProperty", loc, i, key));
}
}
normaliseVisitor(visitor: Object): Object {
for (let key of GLOBAL_VISITOR_PROPS) {
for (const key of GLOBAL_VISITOR_PROPS) {
if (visitor[key]) {
throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. Please target individual nodes.");
throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. " +
"Please target individual nodes.");
}
}

View File

@@ -1,9 +1,7 @@
import escapeRegExp from "lodash/escapeRegExp";
import startsWith from "lodash/startsWith";
import isBoolean from "lodash/isBoolean";
import minimatch from "minimatch";
import includes from "lodash/includes";
import isString from "lodash/isString";
import isRegExp from "lodash/isRegExp";
import path from "path";
import slash from "slash";
@@ -15,8 +13,8 @@ export { inherits, inspect } from "util";
*/
export function canCompile(filename: string, altExts?: Array<string>): boolean {
let exts = altExts || canCompile.EXTENSIONS;
let ext = path.extname(filename);
const exts = altExts || canCompile.EXTENSIONS;
const ext = path.extname(filename);
return includes(exts, ext);
}
@@ -63,7 +61,7 @@ export function regexify(val: any): RegExp {
if (startsWith(val, "./") || startsWith(val, "*/")) val = val.slice(2);
if (startsWith(val, "**/")) val = val.slice(3);
let regex = minimatch.makeRe(val, { nocase: true });
const regex = minimatch.makeRe(val, { nocase: true });
return new RegExp(regex.source.slice(1, -1), "i");
}
@@ -80,8 +78,8 @@ export function regexify(val: any): RegExp {
export function arrayify(val: any, mapFn?: Function): Array<any> {
if (!val) return [];
if (isBoolean(val)) return arrayify([val], mapFn);
if (isString(val)) return arrayify(list(val), mapFn);
if (typeof val === "boolean") return arrayify([val], mapFn);
if (typeof val === "string") return arrayify(list(val), mapFn);
if (Array.isArray(val)) {
if (mapFn) val = val.map(mapFn);
@@ -119,12 +117,12 @@ export function shouldIgnore(
filename = filename.replace(/\\/g, "/");
if (only) {
for (let pattern of only) {
for (const pattern of only) {
if (_shouldIgnore(pattern, filename)) return false;
}
return true;
} else if (ignore.length) {
for (let pattern of ignore) {
for (const pattern of ignore) {
if (_shouldIgnore(pattern, filename)) return true;
}
}

View File

@@ -1,7 +0,0 @@
if (process.browser) {
require("../lib/api/browser");
require("./generation");
require("./transformation");
require("./traverse");
require("./util");
}

View File

@@ -1,9 +1,9 @@
let babel = require("../lib/api/node");
let buildExternalHelpers = require("../lib/tools/build-external-helpers");
let sourceMap = require("source-map");
let assert = require("assert");
let Plugin = require("../lib/transformation/plugin");
let generator = require("babel-generator").default;
import * as babel from "../lib/index";
import buildExternalHelpers from "../lib/tools/build-external-helpers";
import sourceMap from "source-map";
import assert from "assert";
import Plugin from "../lib/transformation/plugin";
import generator from "babel-generator";
function assertIgnored(result) {
assert.ok(result.ignored);
@@ -18,18 +18,18 @@ function transformAsync(code, opts) {
return {
then: function (resolve) {
resolve(babel.transform(code, opts));
}
},
};
}
describe("parser and generator options", function() {
let recast = {
const recast = {
parse: function(code, opts) {
return opts.parser.parse(code);
},
print: function(ast) {
return generator(ast);
}
},
};
function newTransform(string) {
@@ -37,27 +37,27 @@ describe("parser and generator options", function() {
parserOpts: {
parser: recast.parse,
plugins: ["flow"],
allowImportExportEverywhere: true
allowImportExportEverywhere: true,
},
generatorOpts: {
generator: recast.print
}
generator: recast.print,
},
});
}
it("options", function() {
let string = "original;";
const string = "original;";
assert.deepEqual(newTransform(string).ast, babel.transform(string).ast);
assert.equal(newTransform(string).code, string);
});
it("experimental syntax", function() {
let experimental = "var a: number = 1;";
const experimental = "var a: number = 1;";
assert.deepEqual(newTransform(experimental).ast, babel.transform(experimental, {
parserOpts: {
plugins: ["flow"]
}
plugins: ["flow"],
},
}).ast);
assert.equal(newTransform(experimental).code, experimental);
@@ -65,29 +65,29 @@ describe("parser and generator options", function() {
return babel.transform(string, {
plugins: [__dirname + "/../../babel-plugin-syntax-flow"],
parserOpts: {
parser: recast.parse
parser: recast.parse,
},
generatorOpts: {
generator: recast.print
}
generator: recast.print,
},
});
}
assert.deepEqual(newTransformWithPlugins(experimental).ast, babel.transform(experimental, {
parserOpts: {
plugins: ["flow"]
}
plugins: ["flow"],
},
}).ast);
assert.equal(newTransformWithPlugins(experimental).code, experimental);
});
it("other options", function() {
let experimental = "if (true) {\n import a from 'a';\n}";
const experimental = "if (true) {\n import a from 'a';\n}";
assert.notEqual(newTransform(experimental).ast, babel.transform(experimental, {
parserOpts: {
allowImportExportEverywhere: true
}
allowImportExportEverywhere: true,
},
}).ast);
assert.equal(newTransform(experimental).code, experimental);
});
@@ -102,18 +102,26 @@ describe("api", function () {
visitor: {
Program: function (path) {
path.mark("category", "foobar");
}
}
})]
},
},
})],
}).marked[0].message, "foobar");
assert.equal(babel.analyse("foobar;", {}, {
Program: function (path) {
path.mark("category", "foobar");
}
},
}).marked[0].message, "foobar");
});
it("exposes the resolvePlugin method", function() {
assert.equal(babel.resolvePlugin("nonexistent-plugin"), null);
});
it("exposes the resolvePreset method", function() {
assert.equal(babel.resolvePreset("nonexistent-preset"), null);
});
it("transformFile", function (done) {
babel.transformFile(__dirname + "/fixtures/api/file.js", {}, function (err, res) {
if (err) return done(err);
@@ -130,17 +138,17 @@ describe("api", function () {
return assert.throws(
function () {
babel.transform("", {
plugins: [__dirname + "/../../babel-plugin-syntax-jsx", false]
plugins: [__dirname + "/../../babel-plugin-syntax-jsx", false],
});
},
/TypeError: Falsy value found in plugins/
/TypeError: \[BABEL\] unknown: Falsy value found in plugins/
);
});
it("options merge backwards", function () {
return transformAsync("", {
presets: [__dirname + "/../../babel-preset-es2015"],
plugins: [__dirname + "/../../babel-plugin-syntax-jsx"]
plugins: [__dirname + "/../../babel-plugin-syntax-jsx"],
}).then(function (result) {
assert.ok(result.options.plugins[0][0].manipulateOptions.toString().indexOf("jsx") >= 0);
});
@@ -169,9 +177,9 @@ describe("api", function () {
visitor: {
"Program|Identifier": function () {
calledRaw++;
}
}
})]
},
},
})],
});
assert.equal(calledRaw, 4);
@@ -186,39 +194,43 @@ describe("api", function () {
passPerPreset: passPerPreset,
presets: [
// First preset with our plugin, "before"
{
plugins: [
new Plugin({
visitor: {
Function: function(path) {
let alias = path.scope.getProgramParent().path.get("body")[0].node;
if (!babel.types.isTypeAlias(alias)) return;
function () {
return {
plugins: [
new Plugin({
visitor: {
Function: function (path) {
const alias = path.scope.getProgramParent().path.get("body")[0].node;
if (!babel.types.isTypeAlias(alias)) return;
// In case of `passPerPreset` being `false`, the
// alias node is already removed by Flow plugin.
if (!alias) {
return;
}
// In case of `passPerPreset` being `false`, the
// alias node is already removed by Flow plugin.
if (!alias) {
return;
}
// In case of `passPerPreset` being `true`, the
// alias node should still exist.
aliasBaseType = alias.right.type; // NumberTypeAnnotation
}
}
})
]
// In case of `passPerPreset` being `true`, the
// alias node should still exist.
aliasBaseType = alias.right.type; // NumberTypeAnnotation
},
},
}),
],
};
},
// ES2015 preset
require(__dirname + "/../../babel-preset-es2015"),
// Third preset for Flow.
{
plugins: [
require(__dirname + "/../../babel-plugin-syntax-flow"),
require(__dirname + "/../../babel-plugin-transform-flow-strip-types"),
]
}
function () {
return {
plugins: [
require(__dirname + "/../../babel-plugin-syntax-flow"),
require(__dirname + "/../../babel-plugin-transform-flow-strip-types"),
],
};
},
],
});
}
@@ -234,7 +246,7 @@ describe("api", function () {
"",
"var x = function x(y) {",
" return y;",
"};"
"};",
].join("\n"), result.code);
// 2. passPerPreset: false
@@ -250,44 +262,24 @@ describe("api", function () {
"",
"var x = function x(y) {",
" return y;",
"};"
"};",
].join("\n"), result.code);
});
it("handles preset shortcuts (adds babel-preset-)", function () {
return assert.throws(
function () {
babel.transform("", {
presets: ["@babel/es2015"]
});
},
/Couldn\'t find preset \"\@babel\/babel\-preset\-es2015\" relative to directory/
);
});
it("handles preset shortcuts 2 (adds babel-preset-)", function () {
return assert.throws(
function () {
babel.transform("", {
presets: ["@babel/react/optimizations"]
});
},
/Couldn\'t find preset \"\@babel\/babel\-preset\-react\/optimizations\" relative to directory/
);
});
it("source map merging", function () {
let result = babel.transform([
const result = babel.transform([
/* eslint-disable max-len */
"function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }",
"",
"let Foo = function Foo() {",
" _classCallCheck(this, Foo);",
"};",
"",
"//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0ZG91dCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztJQUFNLEdBQUcsWUFBSCxHQUFHO3dCQUFILEdBQUciLCJmaWxlIjoidW5kZWZpbmVkIiwic291cmNlc0NvbnRlbnQiOlsiY2xhc3MgRm9vIHt9XG4iXX0="
"//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0ZG91dCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztJQUFNLEdBQUcsWUFBSCxHQUFHO3dCQUFILEdBQUciLCJmaWxlIjoidW5kZWZpbmVkIiwic291cmNlc0NvbnRlbnQiOlsiY2xhc3MgRm9vIHt9XG4iXX0=",
/* eslint-enable max-len */
].join("\n"), {
sourceMap: true
sourceMap: true,
});
assert.deepEqual([
@@ -299,19 +291,19 @@ describe("api", function () {
"",
"let Foo = function Foo() {",
" _classCallCheck(this, Foo);",
"};"
"};",
].join("\n"), result.code);
let consumer = new sourceMap.SourceMapConsumer(result.map);
const consumer = new sourceMap.SourceMapConsumer(result.map);
assert.deepEqual(consumer.originalPositionFor({
line: 7,
column: 4
column: 4,
}), {
name: null,
source: "stdout",
line: 1,
column: 6
column: 6,
});
});
@@ -332,23 +324,25 @@ describe("api", function () {
auxiliaryCommentBefore: "before",
auxiliaryCommentAfter: "after",
plugins: [function (babel) {
let t = babel.types;
const t = babel.types;
return {
visitor: {
Program: function (path) {
path.unshiftContainer("body", t.expressionStatement(t.identifier("start")));
path.pushContainer("body", t.expressionStatement(t.identifier("end")));
}
}
},
},
};
}]
}],
}).then(function (result) {
assert.equal(result.code, "/*before*/start;\n/*after*/class Foo {}\n/*before*/end;\n/*after*/");
assert.equal(result.code,
"/*before*/start;\n/*after*/class Foo {}\n/*before*/end;\n/*after*/");
});
});
it("modules metadata", function () {
return Promise.all([
// eslint-disable-next-line max-len
transformAsync("import { externalName as localName } from \"external\";").then(function (result) {
assert.deepEqual(result.metadata.modules.imports[0], {
source: "external",
@@ -356,8 +350,8 @@ describe("api", function () {
specifiers: [{
kind: "named",
imported: "externalName",
local: "localName"
}]
local: "localName",
}],
});
}),
@@ -367,8 +361,8 @@ describe("api", function () {
imported: ["*"],
specifiers: [{
kind: "namespace",
local: "localName2"
}]
local: "localName2",
}],
});
}),
@@ -379,15 +373,15 @@ describe("api", function () {
specifiers: [{
kind: "named",
imported: "default",
local: "localName3"
}]
local: "localName3",
}],
});
}),
transformAsync("import localName from \"./array\";", {
resolveModuleSource: function() {
return "override-source";
}
},
}).then(function (result) {
assert.deepEqual(result.metadata.modules.imports, [
{
@@ -397,15 +391,15 @@ describe("api", function () {
{
"kind": "named",
"imported": "default",
"local": "localName"
}
]
}
"local": "localName",
},
],
},
]);
}),
transformAsync("export * as externalName1 from \"external\";", {
plugins: [require("../../babel-plugin-syntax-export-extensions")]
plugins: [require("../../babel-plugin-syntax-export-extensions")],
}).then(function (result) {
assert.deepEqual(result.metadata.modules.exports, {
exported: ["externalName1"],
@@ -413,12 +407,12 @@ describe("api", function () {
kind: "external-namespace",
exported: "externalName1",
source: "external",
}]
}],
});
}),
transformAsync("export externalName2 from \"external\";", {
plugins: [require("../../babel-plugin-syntax-export-extensions")]
plugins: [require("../../babel-plugin-syntax-export-extensions")],
}).then(function (result) {
assert.deepEqual(result.metadata.modules.exports, {
exported: ["externalName2"],
@@ -426,8 +420,8 @@ describe("api", function () {
kind: "external",
local: "externalName2",
exported: "externalName2",
source: "external"
}]
source: "external",
}],
});
}),
@@ -437,8 +431,8 @@ describe("api", function () {
specifiers: [{
kind: "local",
local: "namedFunction",
exported: "namedFunction"
}]
exported: "namedFunction",
}],
});
}),
@@ -448,8 +442,8 @@ describe("api", function () {
specifiers: [{
kind: "local",
local: "foo",
exported: "foo"
}]
exported: "foo",
}],
});
}),
@@ -459,8 +453,8 @@ describe("api", function () {
specifiers: [{
kind: "local",
local: "localName",
exported: "externalName3"
}]
exported: "externalName3",
}],
});
}),
@@ -471,8 +465,8 @@ describe("api", function () {
kind: "external",
local: "externalName4",
exported: "externalName4",
source: "external"
}]
source: "external",
}],
});
}),
@@ -481,8 +475,8 @@ describe("api", function () {
exported: [],
specifiers: [{
kind: "external-all",
source: "external"
}]
source: "external",
}],
});
}),
@@ -492,10 +486,10 @@ describe("api", function () {
specifiers: [{
kind: "local",
local: "defaultFunction",
exported: "default"
}]
exported: "default",
}],
});
})
}),
]);
});
@@ -503,18 +497,18 @@ describe("api", function () {
return Promise.all([
transformAsync("", {
ignore: "node_modules",
filename: "/foo/node_modules/bar"
filename: "/foo/node_modules/bar",
}).then(assertIgnored),
transformAsync("", {
ignore: "foo/node_modules",
filename: "/foo/node_modules/bar"
filename: "/foo/node_modules/bar",
}).then(assertIgnored),
transformAsync("", {
ignore: "foo/node_modules/*.bar",
filename: "/foo/node_modules/foo.bar"
}).then(assertIgnored)
filename: "/foo/node_modules/foo.bar",
}).then(assertIgnored),
]);
});
@@ -522,39 +516,39 @@ describe("api", function () {
return Promise.all([
transformAsync("", {
only: "node_modules",
filename: "/foo/node_modules/bar"
filename: "/foo/node_modules/bar",
}).then(assertNotIgnored),
transformAsync("", {
only: "foo/node_modules",
filename: "/foo/node_modules/bar"
filename: "/foo/node_modules/bar",
}).then(assertNotIgnored),
transformAsync("", {
only: "foo/node_modules/*.bar",
filename: "/foo/node_modules/foo.bar"
filename: "/foo/node_modules/foo.bar",
}).then(assertNotIgnored),
transformAsync("", {
only: "node_modules",
filename: "/foo/node_module/bar"
filename: "/foo/node_module/bar",
}).then(assertIgnored),
transformAsync("", {
only: "foo/node_modules",
filename: "/bar/node_modules/foo"
filename: "/bar/node_modules/foo",
}).then(assertIgnored),
transformAsync("", {
only: "foo/node_modules/*.bar",
filename: "/foo/node_modules/bar.foo"
}).then(assertIgnored)
filename: "/foo/node_modules/bar.foo",
}).then(assertIgnored),
]);
});
describe("env option", function () {
let oldBabelEnv = process.env.BABEL_ENV;
let oldNodeEnv = process.env.NODE_ENV;
const oldBabelEnv = process.env.BABEL_ENV;
const oldNodeEnv = process.env.NODE_ENV;
setup(function () {
// Tests need to run with the default and specific values for these. They
@@ -569,10 +563,10 @@ describe("api", function () {
});
it("default", function () {
let result = babel.transform("foo;", {
const result = babel.transform("foo;", {
env: {
development: { code: false }
}
development: { code: false },
},
});
assert.equal(result.code, undefined);
@@ -580,33 +574,35 @@ describe("api", function () {
it("BABEL_ENV", function () {
process.env.BABEL_ENV = "foo";
let result = babel.transform("foo;", {
const result = babel.transform("foo;", {
env: {
foo: { code: false }
}
foo: { code: false },
},
});
assert.equal(result.code, undefined);
});
it("NODE_ENV", function () {
process.env.NODE_ENV = "foo";
let result = babel.transform("foo;", {
const result = babel.transform("foo;", {
env: {
foo: { code: false }
}
foo: { code: false },
},
});
assert.equal(result.code, undefined);
});
});
it("resolveModuleSource option", function () {
let actual = "import foo from \"foo-import-default\";\nimport \"foo-import-bare\";\nexport { foo } from \"foo-export-named\";";
let expected = "import foo from \"resolved/foo-import-default\";\nimport \"resolved/foo-import-bare\";\nexport { foo } from \"resolved/foo-export-named\";";
/* eslint-disable max-len */
const actual = "import foo from \"foo-import-default\";\nimport \"foo-import-bare\";\nexport { foo } from \"foo-export-named\";";
const expected = "import foo from \"resolved/foo-import-default\";\nimport \"resolved/foo-import-bare\";\nexport { foo } from \"resolved/foo-export-named\";";
/* eslint-enable max-len */
return transformAsync(actual, {
resolveModuleSource: function (originalSource) {
return "resolved/" + originalSource;
}
},
}).then(function (result) {
assert.equal(result.code.trim(), expected);
});
@@ -614,25 +610,25 @@ describe("api", function () {
describe("buildExternalHelpers", function () {
it("all", function () {
let script = buildExternalHelpers();
const script = buildExternalHelpers();
assert.ok(script.indexOf("classCallCheck") >= -1);
assert.ok(script.indexOf("inherits") >= 0);
});
it("whitelist", function () {
let script = buildExternalHelpers(["inherits"]);
const script = buildExternalHelpers(["inherits"]);
assert.ok(script.indexOf("classCallCheck") === -1);
assert.ok(script.indexOf("inherits") >= 0);
});
it("empty whitelist", function () {
let script = buildExternalHelpers([]);
const script = buildExternalHelpers([]);
assert.ok(script.indexOf("classCallCheck") === -1);
assert.ok(script.indexOf("inherits") === -1);
});
it("underscored", function () {
let script = buildExternalHelpers(["typeof"]);
const script = buildExternalHelpers(["typeof"]);
assert.ok(script.indexOf("typeof") >= 0);
});
});

View File

@@ -1,11 +1,11 @@
let browserify = require("browserify");
let assert = require("assert");
let path = require("path");
let vm = require("vm");
import browserify from "browserify";
import assert from "assert";
import path from "path";
import vm from "vm";
describe("browserify", function() {
it("babel/register may be used without breaking browserify", function(done) {
let bundler = browserify(path.join(__dirname, "fixtures/browserify/register.js"));
const bundler = browserify(path.join(__dirname, "fixtures/browserify/register.js"));
bundler.bundle(function(err, bundle) {
if (err) return done(err);

View File

@@ -1,9 +1,9 @@
let assert = require("assert");
let path = require("path");
let buildConfigChain = require("../lib/transformation/file/options/build-config-chain");
import assert from "assert";
import path from "path";
import buildConfigChain from "../lib/transformation/file/options/build-config-chain";
function fixture() {
let args = [__dirname, "fixtures", "config"];
const args = [__dirname, "fixtures", "config"];
for (let i = 0; i < arguments.length; i ++) {
args.push(arguments[i]);
}
@@ -28,127 +28,127 @@ describe("buildConfigChain", function () {
});
it("dir1", function () {
let chain = buildConfigChain({
filename: fixture("dir1", "src.js")
const chain = buildConfigChain({
filename: fixture("dir1", "src.js"),
});
let expected = [
const expected = [
{
options: {
plugins: [
"extended"
]
"extended",
],
},
alias: fixture("extended.babelrc.json"),
loc: fixture("extended.babelrc.json"),
dirname: fixture()
dirname: fixture(),
},
{
options: {
plugins: [
"root"
]
"root",
],
},
alias: fixture(".babelrc"),
loc: fixture(".babelrc"),
dirname: fixture()
dirname: fixture(),
},
{
options: {
ignore: [
"root-ignore"
]
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture()
dirname: fixture(),
},
{
options: {
filename: fixture("dir1", "src.js")
filename: fixture("dir1", "src.js"),
},
alias: "base",
loc: "base",
dirname: fixture("dir1")
}
dirname: fixture("dir1"),
},
];
assert.deepEqual(chain, expected);
});
it("dir2", function () {
let chain = buildConfigChain({
filename: fixture("dir2", "src.js")
const chain = buildConfigChain({
filename: fixture("dir2", "src.js"),
});
let expected = [
const expected = [
{
options: {
plugins: [
"dir2"
]
"dir2",
],
},
alias: fixture("dir2", ".babelrc"),
loc: fixture("dir2", ".babelrc"),
dirname: fixture("dir2")
dirname: fixture("dir2"),
},
{
options: {
ignore: [
"root-ignore"
]
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture()
dirname: fixture(),
},
{
options: {
filename: fixture("dir2", "src.js")
filename: fixture("dir2", "src.js"),
},
alias: "base",
loc: "base",
dirname: fixture("dir2")
}
dirname: fixture("dir2"),
},
];
assert.deepEqual(chain, expected);
});
it("env - base", function () {
let chain = buildConfigChain({
filename: fixture("env", "src.js")
const chain = buildConfigChain({
filename: fixture("env", "src.js"),
});
let expected = [
const expected = [
{
options: {
plugins: [
"env-base"
]
"env-base",
],
},
alias: fixture("env", ".babelrc"),
loc: fixture("env", ".babelrc"),
dirname: fixture("env")
dirname: fixture("env"),
},
{
options: {
ignore: [
"root-ignore"
]
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture()
dirname: fixture(),
},
{
options: {
filename: fixture("env", "src.js")
filename: fixture("env", "src.js"),
},
alias: "base",
loc: "base",
dirname: fixture("env")
}
dirname: fixture("env"),
},
];
assert.deepEqual(chain, expected);
@@ -157,49 +157,49 @@ describe("buildConfigChain", function () {
it("env - foo", function () {
process.env.NODE_ENV = "foo";
let chain = buildConfigChain({
filename: fixture("env", "src.js")
const chain = buildConfigChain({
filename: fixture("env", "src.js"),
});
let expected = [
const expected = [
{
options: {
plugins: [
"env-base"
]
"env-base",
],
},
alias: fixture("env", ".babelrc"),
loc: fixture("env", ".babelrc"),
dirname: fixture("env")
dirname: fixture("env"),
},
{
options: {
plugins: [
"env-foo"
]
"env-foo",
],
},
alias: fixture("env", ".babelrc.env.foo"),
loc: fixture("env", ".babelrc.env.foo"),
dirname: fixture("env")
dirname: fixture("env"),
},
{
options: {
ignore: [
"root-ignore"
]
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture()
dirname: fixture(),
},
{
options: {
filename: fixture("env", "src.js")
filename: fixture("env", "src.js"),
},
alias: "base",
loc: "base",
dirname: fixture("env")
}
dirname: fixture("env"),
},
];
assert.deepEqual(chain, expected);
@@ -209,49 +209,49 @@ describe("buildConfigChain", function () {
process.env.NODE_ENV = "foo"; // overridden
process.env.NODE_ENV = "bar";
let chain = buildConfigChain({
filename: fixture("env", "src.js")
const chain = buildConfigChain({
filename: fixture("env", "src.js"),
});
let expected = [
const expected = [
{
options: {
plugins: [
"env-base"
]
"env-base",
],
},
alias: fixture("env", ".babelrc"),
loc: fixture("env", ".babelrc"),
dirname: fixture("env")
dirname: fixture("env"),
},
{
options: {
plugins: [
"env-bar"
]
"env-bar",
],
},
alias: fixture("env", ".babelrc.env.bar"),
loc: fixture("env", ".babelrc.env.bar"),
dirname: fixture("env")
dirname: fixture("env"),
},
{
options: {
ignore: [
"root-ignore"
]
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture()
dirname: fixture(),
},
{
options: {
filename: fixture("env", "src.js")
filename: fixture("env", "src.js"),
},
alias: "base",
loc: "base",
dirname: fixture("env")
}
dirname: fixture("env"),
},
];
assert.deepEqual(chain, expected);
@@ -261,37 +261,286 @@ describe("buildConfigChain", function () {
it("env - foo", function () {
process.env.NODE_ENV = "foo";
let chain = buildConfigChain({
filename: fixture("pkg", "src.js")
const chain = buildConfigChain({
filename: fixture("pkg", "src.js"),
});
let expected = [
const expected = [
{
options: {
plugins: ["pkg-plugin"]
plugins: ["pkg-plugin"],
},
alias: fixture("pkg", "package.json"),
loc: fixture("pkg", "package.json"),
dirname: fixture("pkg")
dirname: fixture("pkg"),
},
{
options: {
ignore: ["pkg-ignore"]
ignore: ["pkg-ignore"],
},
alias: fixture("pkg", ".babelignore"),
loc: fixture("pkg", ".babelignore"),
dirname: fixture("pkg")
dirname: fixture("pkg"),
},
{
options: {
filename: fixture("pkg", "src.js")
filename: fixture("pkg", "src.js"),
},
alias: "base",
loc: "base",
dirname: fixture("pkg")
}
dirname: fixture("pkg"),
},
];
assert.deepEqual(chain, expected);
});
it("js-config", function () {
const chain = buildConfigChain({
filename: fixture("js-config", "src.js"),
});
const expected = [
{
options: {
plugins: [
"foo",
"bar",
],
},
alias: fixture("js-config", ".babelrc.js"),
loc: fixture("js-config", ".babelrc.js"),
dirname: fixture("js-config"),
},
{
options: {
ignore: [
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
filename: fixture("js-config", "src.js"),
},
alias: "base",
loc: "base",
dirname: fixture("js-config"),
},
];
assert.deepEqual(chain, expected);
});
it("js-config-default - should read transpiled export default", function () {
const chain = buildConfigChain({
filename: fixture("js-config-default", "src.js"),
});
const expected = [
{
options: {
plugins: [
"foo",
"bar",
],
},
alias: fixture("js-config-default", ".babelrc.js"),
loc: fixture("js-config-default", ".babelrc.js"),
dirname: fixture("js-config-default"),
},
{
options: {
ignore: [
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
filename: fixture("js-config-default", "src.js"),
},
alias: "base",
loc: "base",
dirname: fixture("js-config-default"),
},
];
assert.deepEqual(chain, expected);
});
it("js-config-extended", function () {
const chain = buildConfigChain({
filename: fixture("js-config-extended", "src.js"),
});
const expected = [
{
options: {
plugins: [
"extended",
],
},
alias: fixture("extended.babelrc.json"),
loc: fixture("extended.babelrc.json"),
dirname: fixture(),
},
{
options: {
plugins: [
"foo",
"bar",
],
},
alias: fixture("js-config-extended", ".babelrc.js"),
loc: fixture("js-config-extended", ".babelrc.js"),
dirname: fixture("js-config-extended"),
},
{
options: {
ignore: [
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
filename: fixture("js-config-extended", "src.js"),
},
alias: "base",
loc: "base",
dirname: fixture("js-config-extended"),
},
];
assert.deepEqual(chain, expected);
});
it("json-pkg-config-no-babel - should not throw if" +
" package.json doesn't contain a `babel` field", function () {
const chain = buildConfigChain({
filename: fixture("json-pkg-config-no-babel", "src.js"),
});
const expected = [
{
options: {
plugins: [
"json",
],
},
alias: fixture("json-pkg-config-no-babel", ".babelrc"),
loc: fixture("json-pkg-config-no-babel", ".babelrc"),
dirname: fixture("json-pkg-config-no-babel"),
},
{
options: {
ignore: [
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
filename: fixture("json-pkg-config-no-babel", "src.js"),
},
alias: "base",
loc: "base",
dirname: fixture("json-pkg-config-no-babel"),
},
];
assert.deepEqual(chain, expected);
});
it("js-json-config - should throw an error if both a .babelrc" +
" and a .babelrc.js are present", function () {
assert.throws(
function () {
buildConfigChain({
filename: fixture("js-json-config", "src.js"),
});
},
/Multiple configuration files found\.(.|\n)*\.babelrc(.|\n)*\.babelrc\.js/
);
});
it("js-pkg-config - should throw an error if both a .babelrc.js" +
" and a package.json with a babel field are present", function () {
assert.throws(
function () {
buildConfigChain({
filename: fixture("js-pkg-config", "src.js"),
});
},
/Multiple configuration files found\.(.|\n)*\.babelrc\.js(.|\n)*package\.json/
);
});
it("json-pkg-config - should throw an error if both a .babelrc" +
" and a package.json with a babel field are present", function () {
assert.throws(
function () {
buildConfigChain({
filename: fixture("json-pkg-config", "src.js"),
});
},
/Multiple configuration files found\.(.|\n)*\.babelrc(.|\n)*package\.json/
);
});
it("js-config-error", function () {
assert.throws(
function () {
buildConfigChain({
filename: fixture("js-config-error", "src.js"),
});
},
/Error while loading config/
);
});
it("js-config-error2", function () {
assert.throws(
function () {
buildConfigChain({
filename: fixture("js-config-error2", "src.js"),
});
},
/Configuration should be an exported JavaScript object/
);
});
it("js-config-error3", function () {
assert.throws(
function () {
buildConfigChain({
filename: fixture("js-config-error3", "src.js"),
});
},
/Configuration should be an exported JavaScript object/
);
});
it("json-config-error", function () {
assert.throws(
function () {
buildConfigChain({
filename: fixture("json-config-error", "src.js"),
});
},
/Error while parsing JSON/
);
});
});

View File

@@ -1,20 +1,20 @@
let traverse = require("babel-traverse").default;
let assert = require("assert");
let parse = require("babylon").parse;
import traverse from "babel-traverse";
import assert from "assert";
import { parse } from "babylon";
describe("evaluation", function () {
function addTest(code, type, value, notConfident) {
it(type + ": " + code, function () {
let visitor = {};
const visitor = {};
visitor[type] = function (path) {
let evaluate = path.evaluate();
const evaluate = path.evaluate();
assert.equal(evaluate.confident, !notConfident);
assert.deepEqual(evaluate.value, value);
};
traverse(parse(code, {
plugins: ["*"]
plugins: ["*"],
}), visitor);
});
}
@@ -64,6 +64,6 @@ describe("evaluation", function () {
addTest("'abc' === 'xyz' || (1 === 1 && 'four' === 'four')", "LogicalExpression", true);
addTest("'abc' === 'abc' && (1 === 1 && 'four' === 'four')", "LogicalExpression", true);
addTest("({})", "ObjectExpression", {});
addTest("({a: '1'})", "ObjectExpression", {a: "1"});
addTest("({['a' + 'b']: 10 * 20, 'z': [1, 2, 3]})", "ObjectExpression", {ab: 200, z: [1, 2, 3]});
addTest("({a: '1'})", "ObjectExpression", { a: "1" });
addTest("({['a' + 'b']: 10 * 20, 'z': [1, 2, 3]})", "ObjectExpression", { ab: 200, z: [1, 2, 3] });
});

View File

@@ -1,3 +1,3 @@
require("../../../register")({
require("babel-register").default({
ignore: false
});

View File

@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var plugins = ["foo", "bar"];
exports.default = {
plugins: plugins
};

View File

@@ -0,0 +1 @@
// empty

View File

@@ -0,0 +1,2 @@
throw new Error("Something bad happened!");
module.exports = {}

View File

@@ -0,0 +1 @@
// empty

View File

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

View File

@@ -0,0 +1 @@
// empty

View File

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

View File

@@ -0,0 +1 @@
// empty

View File

@@ -0,0 +1,6 @@
var plugins = ["foo", "bar"];
module.exports = {
extends: "../extended.babelrc.json",
plugins: plugins
}

View File

@@ -0,0 +1 @@
// empty

View File

@@ -0,0 +1,5 @@
var plugins = ["foo", "bar"];
module.exports = {
plugins: plugins
}

View File

@@ -0,0 +1 @@
// empty

View File

@@ -0,0 +1,5 @@
{
"plugins": [
"json"
]
}

View File

@@ -0,0 +1,5 @@
module.exports = {
plugins: [
"js"
]
}

View File

@@ -0,0 +1 @@
// empty

View File

@@ -0,0 +1,5 @@
module.exports = {
plugins: [
"js"
]
}

View File

@@ -0,0 +1,3 @@
{
"babel": {}
}

View File

@@ -0,0 +1 @@
// empty

View File

@@ -0,0 +1,3 @@
{
"bad: "json"
}

View File

@@ -0,0 +1 @@
// empty

View File

@@ -0,0 +1,5 @@
{
"plugins": [
"json"
]
}

View File

@@ -0,0 +1 @@
{}

View File

@@ -0,0 +1 @@
// empty

View File

@@ -0,0 +1,5 @@
{
"plugins": [
"json"
]
}

View File

@@ -0,0 +1,3 @@
{
"babel": {}
}

View File

@@ -0,0 +1 @@
// empty

View File

@@ -1,3 +1,3 @@
module.exports = function () {
throw new Error('Not a real preset');
}
};

View File

@@ -1,18 +0,0 @@
// from code:
// export default {
// buildPreset: function() {
// return {
// plugins: [require('../../../../../babel-plugin-syntax-decorators'),]
// };
// }
// }
'use strict';
exports.__esModule = true;
exports.default = {
buildPreset: function buildPreset() {
return {
plugins: [require('../../../../../babel-plugin-syntax-decorators')]
};
}
};

View File

@@ -1,17 +0,0 @@
// from code:
// export const buildPreset = function() {
// return {
// plugins: [require('../../../../../babel-plugin-syntax-decorators'),]
// };
// }
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var buildPreset = exports.buildPreset = function buildPreset() {
return {
plugins: [require('../../../../../babel-plugin-syntax-decorators')]
};
};

View File

@@ -1,50 +0,0 @@
// from code:
// function preset() {
// return {
// plugins: [
// require('../../../../../babel-plugin-syntax-decorators'),
// ]
// };
// }
//
// const oldConfig = preset();
//
// export default oldConfig;
//
// // However, for backward compatibility with babel-core < v6.13.x, we use the 'buildPreset'
// // property of the preset object for the preset creation function with the enumerability
// // caveat mentioned below.
// Object.defineProperty(oldConfig, "buildPreset", {
// configurable: true,
// writable: true,
// // We make this non-enumerable so old versions of babel-core won't see it as an unknown property,
// // while allowing new versions to see it as a preset builder function.
// enumerable: false,
// value: preset,
// });
//
"use strict";
exports.__esModule = true;
function preset() {
return {
plugins: [require('../../../../../babel-plugin-syntax-decorators')]
};
}
var oldConfig = preset();
exports.default = oldConfig;
// However, for backward compatibility with babel-core < v6.13.x, we use the 'buildPreset'
// property of the preset object for the preset creation function with the enumerability
// caveat mentioned below.
Object.defineProperty(oldConfig, "buildPreset", {
configurable: true,
writable: true,
// We make this non-enumerable so old versions of babel-core won't see it as an unknown property,
// while allowing new versions to see it as a preset builder function.
enumerable: false,
value: preset
});

View File

@@ -0,0 +1,6 @@
// from code:
// export default "string";
'use strict';
exports.__esModule = true;
exports.default = "string";

View File

@@ -1,9 +1,7 @@
module.exports = {
buildPreset: function () {
return {
plugins: [
require('../../../../../babel-plugin-syntax-decorators'),
]
};
}
module.exports = function () {
return {
plugins: [
require('../../../../../babel-plugin-syntax-decorators'),
]
};
};

View File

@@ -0,0 +1,2 @@
'use strict';
module.exports = "invalid";

View File

@@ -1,5 +1,10 @@
module.exports = {
plugins: [plugin],
module.exports = function (context, options, fileContext) {
if (/resolve-addons-relative-to-file$/.test(fileContext.dirname)) {
return {
plugins: [plugin],
};
}
return {};
};
function plugin () {

View File

@@ -1,6 +1,6 @@
function wrapper(fn) {
return (...args) => {
if (someCondition) {
while (someCondition) {
const val = fn(...args);
return val.test(() => {
console.log(val);

View File

@@ -2,17 +2,19 @@ function wrapper(fn) {
return function () {
var _arguments = arguments;
if (someCondition) {
var _ret = function () {
var val = fn(..._arguments);
return {
v: val.test(function () {
console.log(val);
})
};
}();
var _loop = function () {
var val = fn(..._arguments);
return {
v: val.test(function () {
console.log(val);
})
};
};
while (someCondition) {
var _ret = _loop();
if (typeof _ret === "object") return _ret.v;
}
};
}
}

View File

@@ -1,4 +1,4 @@
arr.map(function (x) {
return x * x;
});
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNvdXJjZS1tYXBzL2lubGluZS9hY3R1YWwuanMiXSwibmFtZXMiOlsiYXJyIiwibWFwIiwieCJdLCJtYXBwaW5ncyI6IkFBQUFBLElBQUlDLEdBQUosQ0FBUTtBQUFBLFNBQUtDLElBQUlBLENBQVQ7QUFBQSxDQUFSIiwiZmlsZSI6InNvdXJjZS1tYXBzL2lubGluZS9leHBlY3RlZC5qcyIsInNvdXJjZXNDb250ZW50IjpbImFyci5tYXAoeCA9PiB4ICogeCk7Il19
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNvdXJjZS1tYXBzL2lubGluZS9hY3R1YWwuanMiXSwibmFtZXMiOlsiYXJyIiwibWFwIiwieCJdLCJtYXBwaW5ncyI6IkFBQUFBLElBQUlDLEdBQUosQ0FBUTtBQUFBLFNBQUtDLElBQUlBLENBQVQ7QUFBQSxDQUFSIiwiZmlsZSI6InNvdXJjZS1tYXBzL2lubGluZS9leHBlY3RlZC5qcyIsInNvdXJjZXNDb250ZW50IjpbImFyci5tYXAoeCA9PiB4ICogeCk7Il19

View File

@@ -0,0 +1,8 @@
import assert from "assert";
import getPossiblePluginNames from "../lib/helpers/get-possible-plugin-names";
describe("getPossiblePluginNames", function () {
it("adds the babel-plugin prefix", function() {
assert.deepEqual(getPossiblePluginNames("foobar"), ["babel-plugin-foobar", "foobar"]);
});
});

View File

@@ -0,0 +1,22 @@
import assert from "assert";
import getPossiblePresetNames from "../lib/helpers/get-possible-preset-names";
describe("getPossiblePresetNames", function () {
it("adds the babel-preset prefix", function() {
assert.deepEqual(getPossiblePresetNames("foobar"), ["babel-preset-foobar", "foobar"]);
});
it("inserts babel-preset after @org/", function() {
assert.deepEqual(getPossiblePresetNames("@babel/es2015"), [
"babel-preset-@babel/es2015",
"@babel/es2015",
"@babel/babel-preset-es2015",
]);
assert.deepEqual(getPossiblePresetNames("@babel/react/optimizations"), [
"babel-preset-@babel/react/optimizations",
"@babel/react/optimizations",
"@babel/babel-preset-react/optimizations",
]);
});
});

View File

@@ -1,6 +1,5 @@
import assert from "assert";
import OptionManager from "../lib/transformation/file/options/option-manager";
import Logger from "../lib/transformation/file/logger";
import path from "path";
describe("option-manager", () => {
@@ -17,9 +16,9 @@ describe("option-manager", () => {
it("throws for removed babel 5 options", () => {
return assert.throws(
() => {
let opt = new OptionManager(new Logger(null, "unknown"));
const opt = new OptionManager();
opt.init({
"randomOption": true
"randomOption": true,
});
},
/Unknown option: base.randomOption/
@@ -29,12 +28,13 @@ describe("option-manager", () => {
it("throws for removed babel 5 options", () => {
return assert.throws(
() => {
let opt = new OptionManager(new Logger(null, "unknown"));
const opt = new OptionManager();
opt.init({
"auxiliaryComment": true,
"blacklist": true
"blacklist": true,
});
},
// eslint-disable-next-line max-len
/Using removed Babel 5 option: base.auxiliaryComment - Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`/
);
});
@@ -42,34 +42,22 @@ describe("option-manager", () => {
it("throws for resolved but erroring preset", () => {
return assert.throws(
() => {
let opt = new OptionManager(new Logger(null, "unknown"));
const opt = new OptionManager();
opt.init({
"presets": [path.join(__dirname, "fixtures/option-manager/not-a-preset")]
"presets": [path.join(__dirname, "fixtures/option-manager/not-a-preset")],
});
},
/While processing preset: .*option-manager(?:\/|\\\\)not-a-preset\.js/
);
});
it("throws for invalid preset configuration", function() {
return assert.throws(
function () {
let opt = new OptionManager(new Logger(null, "unknown"));
opt.init({
"presets": [{ option: "value" }]
});
},
/Unknown option: foreign.option\.(?:.|\n)+A common cause of this error is the presence of a configuration options object without the corresponding preset name/
);
});
});
describe("presets", function () {
function presetTest(name) {
it(name, function () {
let opt = new OptionManager(new Logger(null, "unknown"));
let options = opt.init({
"presets": [path.join(__dirname, "fixtures/option-manager/presets", name)]
const opt = new OptionManager();
const options = opt.init({
"presets": [path.join(__dirname, "fixtures/option-manager/presets", name)],
});
assert.equal(true, Array.isArray(options.plugins));
@@ -77,14 +65,22 @@ describe("option-manager", () => {
});
}
presetTest("es5");
presetTest("es5_function");
presetTest("es2015_default");
presetTest("es2015_default_function");
presetTest("es2015_default_object_function");
presetTest("es2015_function");
presetTest("es2015_function_fallback");
presetTest("es2015_named");
function presetThrowsTest(name, msg) {
it(name, function () {
const opt = new OptionManager();
assert.throws(() => opt.init({
"presets": [path.join(__dirname, "fixtures/option-manager/presets", name)],
}), msg);
});
}
presetTest("es5_function");
presetTest("es5_object");
presetTest("es2015_default_function");
presetTest("es2015_default_object");
presetThrowsTest("es2015_named", /Preset must export a default export when using ES6 modules/);
presetThrowsTest("es2015_invalid", /Unsupported preset format: string/);
presetThrowsTest("es5_invalid", /Unsupported preset format: string/);
});
});

View File

@@ -1,28 +1,28 @@
let transform = require("../lib/api/node").transform;
let Plugin = require("../lib/transformation/plugin");
let chai = require("chai");
import { transform } from "../lib/index";
import Plugin from "../lib/transformation/plugin";
import chai from "chai";
describe("traversal path", function () {
it("replaceWithSourceString", function () {
let expectCode = "function foo() {}";
const expectCode = "function foo() {}";
let actualCode = transform(expectCode, {
const actualCode = transform(expectCode, {
plugins: [new Plugin({
visitor: {
FunctionDeclaration: function (path) {
path.replaceWithSourceString("console.whatever()");
}
}
})]
},
},
})],
}).code;
chai.expect(actualCode).to.be.equal("console.whatever();");
});
it("replaceWith (arrow expression body to block statement body)", function () {
let expectCode = "var fn = () => true;";
const expectCode = "var fn = () => true;";
let actualCode = transform(expectCode, {
const actualCode = transform(expectCode, {
plugins: [new Plugin({
visitor: {
ArrowFunctionExpression: function (path) {
@@ -32,41 +32,41 @@ describe("traversal path", function () {
type: "ReturnStatement",
argument: {
type: "BooleanLiteral",
value: true
}
}]
value: true,
},
}],
});
}
}
})]
},
},
})],
}).code;
chai.expect(actualCode).to.be.equal("var fn = () => {\n return true;\n};");
});
it("replaceWith (arrow block statement body to expression body)", function () {
let expectCode = "var fn = () => { return true; }";
const expectCode = "var fn = () => { return true; }";
let actualCode = transform(expectCode, {
const actualCode = transform(expectCode, {
plugins: [new Plugin({
visitor: {
ArrowFunctionExpression: function (path) {
path.get("body").replaceWith({
type: "BooleanLiteral",
value: true
value: true,
});
}
}
})]
},
},
})],
}).code;
chai.expect(actualCode).to.be.equal("var fn = () => true;");
});
it("replaceWith (for-in left expression to variable declaration)", function () {
let expectCode = "for (KEY in right);";
const expectCode = "for (KEY in right);";
let actualCode = transform(expectCode, {
const actualCode = transform(expectCode, {
plugins: [new Plugin({
visitor: {
ForInStatement: function (path) {
@@ -77,41 +77,41 @@ describe("traversal path", function () {
type: "VariableDeclarator",
id: {
type: "Identifier",
name: "KEY"
}
}]
name: "KEY",
},
}],
});
}
}
})]
},
},
})],
}).code;
chai.expect(actualCode).to.be.equal("for (var KEY in right);");
});
it("replaceWith (for-in left variable declaration to expression)", function () {
let expectCode = "for (var KEY in right);";
const expectCode = "for (var KEY in right);";
let actualCode = transform(expectCode, {
const actualCode = transform(expectCode, {
plugins: [new Plugin({
visitor: {
ForInStatement: function (path) {
path.get("left").replaceWith({
type: "Identifier",
name: "KEY"
name: "KEY",
});
}
}
})]
},
},
})],
}).code;
chai.expect(actualCode).to.be.equal("for (KEY in right);");
});
it("replaceWith (for-loop left expression to variable declaration)", function () {
let expectCode = "for (KEY;;);";
const expectCode = "for (KEY;;);";
let actualCode = transform(expectCode, {
const actualCode = transform(expectCode, {
plugins: [new Plugin({
visitor: {
ForStatement: function (path) {
@@ -122,32 +122,32 @@ describe("traversal path", function () {
type: "VariableDeclarator",
id: {
type: "Identifier",
name: "KEY"
}
}]
name: "KEY",
},
}],
});
}
}
})]
},
},
})],
}).code;
chai.expect(actualCode).to.be.equal("for (var KEY;;);");
});
it("replaceWith (for-loop left variable declaration to expression)", function () {
let expectCode = "for (var KEY;;);";
const expectCode = "for (var KEY;;);";
let actualCode = transform(expectCode, {
const actualCode = transform(expectCode, {
plugins: [new Plugin({
visitor: {
ForStatement: function (path) {
path.get("init").replaceWith({
type: "Identifier",
name: "KEY"
name: "KEY",
});
}
}
})]
},
},
})],
}).code;
chai.expect(actualCode).to.be.equal("for (KEY;;);");

View File

@@ -1 +1,3 @@
require("babel-helper-transform-fixture-test-runner")(__dirname + "/fixtures/plugins", "plugins");
import runner from "babel-helper-transform-fixture-test-runner";
runner(`${__dirname}/fixtures/plugins`, "plugins");

View File

@@ -1,14 +1,14 @@
let assert = require("assert");
let async = require("async");
let babel = require("../lib/api/node");
let fs = require("fs");
let path = require("path");
import assert from "assert";
import async from "async";
import * as babel from "../lib/index";
import fs from "fs";
import path from "path";
// Test that plugins & presets are resolved relative to `filename`.
describe("addon resolution", function () {
it("addon resolution", function (done) {
let fixtures = {};
let paths = {};
const fixtures = {};
const paths = {};
paths.fixtures = path.join(
__dirname,
@@ -33,7 +33,7 @@ describe("addon resolution", function () {
function fixturesReady (err) {
if (err) return done(err);
let actual = babel.transform(fixtures.actual, {
const actual = babel.transform(fixtures.actual, {
filename: paths.actual,
plugins: ["addons/plugin"],
presets: ["addons/preset"],

View File

@@ -1 +1,3 @@
require("babel-helper-transform-fixture-test-runner")(__dirname + "/fixtures/transformation", "transformation");
import runner from "babel-helper-transform-fixture-test-runner";
runner(`${__dirname}/fixtures/transformation`, "transformation");

View File

@@ -1,6 +1,6 @@
let assert = require("assert");
let util = require("../lib/util");
let t = require("babel-types");
import assert from "assert";
import * as util from "../lib/util";
import * as t from "babel-types";
describe("util", function () {
it("canCompile", function () {
@@ -36,7 +36,7 @@ describe("util", function () {
assert.deepEqual(util.list(["foo", "bar"]), ["foo", "bar"]);
assert.deepEqual(util.list(/foo/), [/foo/]);
let date = new Date;
const date = new Date;
assert.deepEqual(util.list(date), [date]);
});
@@ -84,8 +84,8 @@ describe("util", function () {
});
it("shouldIgnore", function () {
let reIgnore = /\-reIgnore\.js/;
let fnIgnore = function (src) {
const reIgnore = /\-reIgnore\.js/;
const fnIgnore = function (src) {
if (src.indexOf("fnIgnore") > 0) {
return true;
}

View File

@@ -35,9 +35,7 @@ comments | boolean | `true` | Should comments be include
compact | boolean or `'auto'` | `opts.minified` | Set to `true` to avoid adding whitespace for formatting
minified | boolean | `false` | Should the output be minified
concise | boolean | `false` | Set to `true` to reduce whitespace (but not as much as `opts.compact`)
quotes | `'single'` or `'double'` | autodetect based on `ast.tokens` | The type of quote to use in the output
filename | string | | Used in warning messages
flowCommaSeparator | boolean | `false` | Set to `true` to use commas instead of semicolons as Flow property separators
jsonCompatibleStrings | boolean | `false` | Set to true to run `jsesc` with "json": true to print "\u00A9" vs. "©";
Options for source maps:

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