From 41085248560b1403b8d0f99f108491e679531c6c Mon Sep 17 00:00:00 2001 From: Bogdan Savluk Date: Sun, 7 Jun 2020 22:21:33 +0200 Subject: [PATCH] Update prettier to v2 (#11579) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Nicolò Ribaudo --- Gulpfile.js | 4 +- babel.config.js | 2 +- .../src/index.js | 2 +- .../src/index.js | 2 +- .../babel-eslint-parser/src/analyze-scope.js | 2 +- .../babel-eslint-parser/src/convert/index.js | 2 +- eslint/babel-eslint-parser/test/index.js | 2 +- eslint/babel-eslint-plugin/src/rules/semi.js | 4 +- .../test/rules/no-invalid-this.js | 4 +- package.json | 2 +- packages/babel-cli/src/babel/dir.js | 10 +- packages/babel-cli/src/babel/file.js | 16 +- packages/babel-cli/src/babel/options.js | 6 +- packages/babel-cli/src/babel/util.js | 6 +- packages/babel-cli/test/index.js | 38 ++--- packages/babel-code-frame/src/index.js | 2 +- packages/babel-code-frame/test/index.js | 48 +++--- .../scripts/utils-build-data.js | 2 +- packages/babel-core/src/config/caching.js | 2 +- .../babel-core/src/config/config-chain.js | 2 +- packages/babel-core/src/config/files/utils.js | 2 +- packages/babel-core/src/config/full.js | 6 +- packages/babel-core/src/config/index.js | 2 +- packages/babel-core/src/config/partial.js | 44 ++--- .../babel-core/src/gensync-utils/async.js | 6 +- .../src/tools/build-external-helpers.js | 4 +- packages/babel-core/src/transform-ast.js | 2 +- packages/babel-core/src/transform-file.js | 2 +- .../src/transformation/block-hoist-plugin.js | 2 +- packages/babel-core/test/api.js | 146 +++++++++-------- packages/babel-core/test/async.js | 4 +- packages/babel-core/test/caching-api.js | 6 +- packages/babel-core/test/config-chain.js | 12 +- packages/babel-core/test/config-loading.js | 4 +- packages/babel-core/test/evaluation.js | 6 +- packages/babel-core/test/option-manager.js | 6 +- packages/babel-core/test/parse.js | 6 +- packages/babel-core/test/path.js | 30 ++-- packages/babel-core/test/resolution.js | 86 +++++----- .../src/generators/expressions.js | 2 +- .../src/generators/statements.js | 6 +- packages/babel-generator/src/index.js | 2 +- packages/babel-generator/src/node/index.js | 2 +- .../babel-generator/src/node/whitespace.js | 14 +- packages/babel-generator/test/index.js | 60 +++---- .../src/index.js | 2 +- .../src/index.js | 6 +- .../babel-helper-call-delegate/src/index.js | 2 +- packages/babel-helper-define-map/src/index.js | 6 +- .../src/index.js | 2 +- .../babel-helper-explode-class/src/index.js | 2 +- .../babel-helper-function-name/src/index.js | 2 +- .../src/index.js | 2 +- .../babel-helper-hoist-variables/src/index.js | 2 +- .../src/import-injector.js | 5 +- .../babel-helper-module-imports/test/index.js | 2 +- .../src/index.js | 2 +- .../src/index.js | 2 +- .../src/index.js | 2 +- .../src/index.js | 14 +- .../test/index.js | 4 +- .../scripts/generate-identifier-regex.js | 4 +- .../test/identifier.spec.js | 10 +- packages/babel-highlight/src/index.js | 2 +- packages/babel-highlight/test/index.js | 56 +++---- packages/babel-node/src/_babel-node.js | 4 +- packages/babel-node/src/babel-node.js | 6 +- packages/babel-node/test/index.js | 36 ++-- .../babel-parser/src/plugins/jsx/index.js | 4 +- .../babel-parser/src/tokenizer/context.js | 18 +- .../test/helpers/runFixtureTests.js | 26 ++- packages/babel-parser/test/plugin-options.js | 8 +- .../src/for-await.js | 2 +- .../src/transformer-legacy.js | 4 +- .../src/index.js | 2 +- .../test/index.js | 20 +-- .../src/transformClass.js | 4 +- .../src/index.js | 2 +- .../test/copied-nodes.js | 2 +- .../test/esmodule-flag.js | 4 +- .../src/index.js | 4 +- .../src/index.js | 2 +- .../src/index.js | 2 +- .../src/index.js | 2 +- .../src/index.js | 2 +- .../src/transform-classic.js | 2 +- .../scripts/build-dist.js | 2 +- .../src/get-runtime-path/browser.js | 2 +- .../src/get-runtime-path/index.js | 2 +- .../src/index.js | 2 +- .../src/get-option-specific-excludes.js | 2 +- .../src/polyfills/corejs2/entry-plugin.js | 4 +- .../corejs2/get-platform-specific-default.js | 2 +- .../src/polyfills/corejs2/usage-plugin.js | 6 +- .../src/polyfills/corejs3/entry-plugin.js | 4 +- .../src/polyfills/corejs3/usage-plugin.js | 8 +- .../src/polyfills/regenerator/entry-plugin.js | 2 +- .../src/polyfills/regenerator/usage-plugin.js | 2 +- packages/babel-preset-env/src/utils.js | 5 +- .../test/normalize-options.spec.js | 6 +- packages/babel-register/src/index.js | 2 +- packages/babel-register/test/browserify.js | 6 +- packages/babel-register/test/index.js | 4 +- .../src/transformScriptTags.js | 2 +- packages/babel-template/src/builder.js | 5 +- packages/babel-template/test/index.js | 18 +- packages/babel-traverse/src/index.js | 10 +- packages/babel-traverse/src/path/ancestry.js | 2 +- packages/babel-traverse/src/path/index.js | 6 +- .../src/path/inference/inferer-reference.js | 2 +- .../src/path/inference/inferers.js | 4 +- .../src/path/lib/removal-hooks.js | 8 +- packages/babel-traverse/src/visitors.js | 6 +- packages/babel-traverse/test/ancestry.js | 20 +-- packages/babel-traverse/test/conversion.js | 18 +- packages/babel-traverse/test/evaluation.js | 117 +++++-------- packages/babel-traverse/test/family.js | 20 +-- packages/babel-traverse/test/hub.js | 4 +- packages/babel-traverse/test/inference.js | 154 +++++++----------- packages/babel-traverse/test/introspection.js | 34 ++-- packages/babel-traverse/test/modification.js | 72 ++++---- packages/babel-traverse/test/removal.js | 17 +- packages/babel-traverse/test/replacement.js | 26 +-- packages/babel-traverse/test/scope.js | 84 ++++------ packages/babel-traverse/test/traverse.js | 38 ++--- .../babel-types/scripts/generators/docs.js | 8 +- .../babel-types/scripts/generators/flow.js | 5 +- .../src/converters/toIdentifier.js | 2 +- .../babel-types/src/converters/toKeyAlias.js | 2 +- packages/babel-types/src/definitions/core.js | 42 ++--- .../babel-types/src/definitions/es2015.js | 31 ++-- .../src/definitions/experimental.js | 4 +- .../test/builders/es2015/templateElement.js | 12 +- .../builders/experimental/classProperty.js | 8 +- .../flow/createTypeAnnotationBasedOnTypeof.js | 12 +- .../test/builders/flow/declareClass.js | 10 +- .../builders/typescript/tsTypeParameter.js | 10 +- packages/babel-types/test/cloning.js | 26 +-- packages/babel-types/test/converters.js | 108 ++++++------ packages/babel-types/test/misc.js | 12 +- packages/babel-types/test/retrievers.js | 10 +- packages/babel-types/test/validators.js | 144 ++++++++-------- scripts/parser-tests/test262/index.js | 4 +- .../parser-tests/utils/parser-test-runner.js | 4 +- scripts/rollup-plugin-babel-source.js | 2 +- scripts/utils/formatCode.js | 27 ++- yarn.lock | 8 +- 147 files changed, 1018 insertions(+), 1106 deletions(-) diff --git a/Gulpfile.js b/Gulpfile.js index d85ea54c15..0a015ae731 100644 --- a/Gulpfile.js +++ b/Gulpfile.js @@ -33,7 +33,7 @@ function getIndexFromPackage(name) { } function compilationLogger() { - return through.obj(function(file, enc, callback) { + return through.obj(function (file, enc, callback) { fancyLog(`Compiling '${chalk.cyan(file.relative)}'...`); callback(null, file); }); @@ -48,7 +48,7 @@ function errorsLogger() { } function rename(fn) { - return through.obj(function(file, enc, callback) { + return through.obj(function (file, enc, callback) { file.path = fn(file); callback(null, file); }); diff --git a/babel.config.js b/babel.config.js index b66ad8e143..538d4c8b28 100644 --- a/babel.config.js +++ b/babel.config.js @@ -1,6 +1,6 @@ "use strict"; -module.exports = function(api) { +module.exports = function (api) { const env = api.env(); const includeCoverage = process.env.BABEL_COVERAGE === "true"; diff --git a/codemods/babel-plugin-codemod-object-assign-to-object-spread/src/index.js b/codemods/babel-plugin-codemod-object-assign-to-object-spread/src/index.js index b926f40e73..bfd6e5641d 100644 --- a/codemods/babel-plugin-codemod-object-assign-to-object-spread/src/index.js +++ b/codemods/babel-plugin-codemod-object-assign-to-object-spread/src/index.js @@ -1,6 +1,6 @@ import syntaxObjectRestSpread from "@babel/plugin-syntax-object-rest-spread"; -export default function({ types: t }) { +export default function ({ types: t }) { return { inherits: syntaxObjectRestSpread, diff --git a/codemods/babel-plugin-codemod-optional-catch-binding/src/index.js b/codemods/babel-plugin-codemod-optional-catch-binding/src/index.js index 8087226dfe..81b05e9651 100644 --- a/codemods/babel-plugin-codemod-optional-catch-binding/src/index.js +++ b/codemods/babel-plugin-codemod-optional-catch-binding/src/index.js @@ -1,6 +1,6 @@ import syntaxOptionalCatchBinding from "@babel/plugin-syntax-optional-catch-binding"; -export default function({ types: t }) { +export default function ({ types: t }) { return { inherits: syntaxOptionalCatchBinding, diff --git a/eslint/babel-eslint-parser/src/analyze-scope.js b/eslint/babel-eslint-parser/src/analyze-scope.js index 2a52043854..c7604b48a3 100644 --- a/eslint/babel-eslint-parser/src/analyze-scope.js +++ b/eslint/babel-eslint-parser/src/analyze-scope.js @@ -237,7 +237,7 @@ class Referencer extends OriginalReferencer { this._checkIdentifierOrVisit(name); } } - scope.__define = function() { + scope.__define = function () { return parentScope.__define.apply(parentScope, arguments); }; diff --git a/eslint/babel-eslint-parser/src/convert/index.js b/eslint/babel-eslint-parser/src/convert/index.js index 7a9de2b4cc..085f49eec4 100644 --- a/eslint/babel-eslint-parser/src/convert/index.js +++ b/eslint/babel-eslint-parser/src/convert/index.js @@ -2,7 +2,7 @@ import convertTokens from "./convertTokens"; import convertComments from "./convertComments"; import convertAST from "./convertAST"; -export default function(ast, code) { +export default function (ast, code) { ast.tokens = convertTokens(ast.tokens, code); convertComments(ast.comments); convertAST(ast, code); diff --git a/eslint/babel-eslint-parser/test/index.js b/eslint/babel-eslint-parser/test/index.js index 240d00d4d1..bea8b50ef8 100644 --- a/eslint/babel-eslint-parser/test/index.js +++ b/eslint/babel-eslint-parser/test/index.js @@ -84,7 +84,7 @@ describe("Babel and Espree", () => { }); describe("compatibility", () => { - it("should allow ast.analyze to be called without options", function() { + it("should allow ast.analyze to be called without options", function () { const ast = parseForESLint("`test`", { eslintScopeManager: true, eslintVisitorKeys: true, diff --git a/eslint/babel-eslint-plugin/src/rules/semi.js b/eslint/babel-eslint-plugin/src/rules/semi.js index f8cc783ac6..1668a32f8e 100644 --- a/eslint/babel-eslint-plugin/src/rules/semi.js +++ b/eslint/babel-eslint-plugin/src/rules/semi.js @@ -57,13 +57,13 @@ function report(context, node, missing) { if (!missing) { message = "Missing semicolon."; loc = loc.end; - fix = function(fixer) { + fix = function (fixer) { return fixer.insertTextAfter(lastToken, ";"); }; } else { message = "Extra semicolon."; loc = loc.start; - fix = function(fixer) { + fix = function (fixer) { return fixer.remove(lastToken); }; } diff --git a/eslint/babel-eslint-plugin/test/rules/no-invalid-this.js b/eslint/babel-eslint-plugin/test/rules/no-invalid-this.js index 7773aed806..7fdde00b72 100644 --- a/eslint/babel-eslint-plugin/test/rules/no-invalid-this.js +++ b/eslint/babel-eslint-plugin/test/rules/no-invalid-this.js @@ -50,8 +50,8 @@ function MODULES(pattern) { */ function extractPatterns(patterns, type) { // Clone and apply the pattern environment. - const patternsList = patterns.map(function(pattern) { - return pattern[type].map(function(applyCondition) { + const patternsList = patterns.map(function (pattern) { + return pattern[type].map(function (applyCondition) { const thisPattern = cloneDeep(pattern); applyCondition(thisPattern); diff --git a/package.json b/package.json index 2799491828..1b63836e5f 100644 --- a/package.json +++ b/package.json @@ -57,7 +57,7 @@ "lodash": "^4.17.13", "mergeiterator": "^1.2.5", "output-file-sync": "^2.0.0", - "prettier": "^1.19.1", + "prettier": "^2.0.5", "pump": "^3.0.0", "rimraf": "^2.6.3", "rollup": "1.27.9", diff --git a/packages/babel-cli/src/babel/dir.js b/packages/babel-cli/src/babel/dir.js index 4b63f8dd76..7356574504 100644 --- a/packages/babel-cli/src/babel/dir.js +++ b/packages/babel-cli/src/babel/dir.js @@ -22,7 +22,7 @@ function outputFileSync(filePath: string, data: string | Buffer): void { fs.writeFileSync(filePath, data); } -export default async function({ +export default async function ({ cliOptions, babelOptions, }: CmdOptions): Promise { @@ -143,7 +143,7 @@ export default async function({ let startTime = null; const logSuccess = debounce( - function() { + function () { if (startTime === null) { // This should never happen, but just in case it's better // to ignore the log message rather than making @babel/cli crash. @@ -189,7 +189,7 @@ export default async function({ if (cliOptions.watch) { const chokidar = util.requireChokidar(); - filenames.forEach(function(filenameOrDir: string): void { + filenames.forEach(function (filenameOrDir: string): void { const watcher = chokidar.watch(filenameOrDir, { persistent: true, ignoreInitial: true, @@ -203,8 +203,8 @@ export default async function({ // when we are sure that all the files have been compiled. let processing = 0; - ["add", "change"].forEach(function(type: string): void { - watcher.on(type, async function(filename: string) { + ["add", "change"].forEach(function (type: string): void { + watcher.on(type, async function (filename: string) { processing++; if (startTime === null) startTime = process.hrtime(); diff --git a/packages/babel-cli/src/babel/file.js b/packages/babel-cli/src/babel/file.js index c1c60ff916..89e780acd9 100644 --- a/packages/babel-cli/src/babel/file.js +++ b/packages/babel-cli/src/babel/file.js @@ -16,7 +16,7 @@ type CompilationOutput = { map: Object, }; -export default async function({ +export default async function ({ cliOptions, babelOptions, }: CmdOptions): Promise { @@ -41,7 +41,7 @@ export default async function({ const consumer = new sourceMap.SourceMapConsumer(result.map); const sources = new Set(); - consumer.eachMapping(function(mapping) { + consumer.eachMapping(function (mapping) { if (mapping.source != null) sources.add(mapping.source); map.addMapping({ @@ -111,13 +111,13 @@ export default async function({ process.stdin.setEncoding("utf8"); - process.stdin.on("readable", function() { + process.stdin.on("readable", function () { const chunk = process.stdin.read(); // $FlowIgnore if (chunk !== null) code += chunk; }); - process.stdin.on("end", function() { + process.stdin.on("end", function () { resolve(code); }); process.stdin.on("error", reject); @@ -144,7 +144,7 @@ export default async function({ async function walk(filenames: Array): Promise { const _filenames = []; - filenames.forEach(function(filename) { + filenames.forEach(function (filename) { if (!fs.existsSync(filename)) return; const stat = fs.statSync(filename); @@ -157,7 +157,7 @@ export default async function({ cliOptions.includeDotfiles, cliOptions.extensions, ) - .forEach(function(filename) { + .forEach(function (filename) { _filenames.push(path.join(dirname, filename)); }); } else { @@ -166,7 +166,7 @@ export default async function({ }); const results = await Promise.all( - _filenames.map(async function(filename: string): Promise { + _filenames.map(async function (filename: string): Promise { let sourceFilename = filename; if (cliOptions.outFile) { sourceFilename = path.relative( @@ -224,7 +224,7 @@ export default async function({ pollInterval: 10, }, }) - .on("all", function(type: string, filename: string): void { + .on("all", function (type: string, filename: string): void { if ( !util.isCompilableExtension(filename, cliOptions.extensions) && !filenames.includes(filename) diff --git a/packages/babel-cli/src/babel/options.js b/packages/babel-cli/src/babel/options.js index 9fc6f1a640..6b94f75cd6 100644 --- a/packages/babel-cli/src/babel/options.js +++ b/packages/babel-cli/src/babel/options.js @@ -189,7 +189,7 @@ export default function parseArgv(args: Array): CmdOptions | null { const errors = []; - let filenames = commander.args.reduce(function(globbed, input) { + let filenames = commander.args.reduce(function (globbed, input) { let files = glob.sync(input); if (!files.length) files = [input]; return globbed.concat(files); @@ -197,7 +197,7 @@ export default function parseArgv(args: Array): CmdOptions | null { filenames = uniq(filenames); - filenames.forEach(function(filename) { + filenames.forEach(function (filename) { if (!fs.existsSync(filename)) { errors.push(filename + " does not exist"); } @@ -255,7 +255,7 @@ export default function parseArgv(args: Array): CmdOptions | null { if (errors.length) { console.error("babel:"); - errors.forEach(function(e) { + errors.forEach(function (e) { console.error(" " + e); }); return null; diff --git a/packages/babel-cli/src/babel/util.js b/packages/babel-cli/src/babel/util.js index 3cdfe49279..752203cd06 100644 --- a/packages/babel-cli/src/babel/util.js +++ b/packages/babel-cli/src/babel/util.js @@ -33,7 +33,7 @@ export function readdirForCompilable( includeDotfiles: boolean, altExts?: Array, ): Array { - return readdir(dirname, includeDotfiles, function(filename) { + return readdir(dirname, includeDotfiles, function (filename) { return isCompilableExtension(filename, altExts); }); } @@ -96,7 +96,7 @@ export function compile( export function deleteDir(path: string): void { if (fs.existsSync(path)) { - fs.readdirSync(path).forEach(function(file) { + fs.readdirSync(path).forEach(function (file) { const curPath = path + "/" + file; if (fs.lstatSync(curPath).isDirectory()) { // recurse @@ -110,7 +110,7 @@ export function deleteDir(path: string): void { } } -process.on("uncaughtException", function(err) { +process.on("uncaughtException", function (err) { console.error(err); process.exitCode = 1; }); diff --git a/packages/babel-cli/test/index.js b/packages/babel-cli/test/index.js index da2a6baa91..0debf8a294 100644 --- a/packages/babel-cli/test/index.js +++ b/packages/babel-cli/test/index.js @@ -10,11 +10,11 @@ const fs = require("fs"); const fixtureLoc = path.join(__dirname, "fixtures"); const tmpLoc = path.join(__dirname, "tmp"); -const fileFilter = function(x) { +const fileFilter = function (x) { return x !== ".DS_Store"; }; -const outputFileSync = function(filePath, data) { +const outputFileSync = function (filePath, data) { makeDirSync(path.dirname(filePath)); fs.writeFileSync(filePath, data); }; @@ -27,29 +27,29 @@ const pluginLocs = [ path.join(__dirname, "/../../babel-plugin-transform-modules-commonjs"), ].join(","); -const readDir = function(loc, filter) { +const readDir = function (loc, filter) { const files = {}; if (fs.existsSync(loc)) { - readdir(loc, filter).forEach(function(filename) { + readdir(loc, filter).forEach(function (filename) { files[filename] = helper.readFile(path.join(loc, filename)); }); } return files; }; -const saveInFiles = function(files) { +const saveInFiles = function (files) { // Place an empty .babelrc in each test so tests won't unexpectedly get to repo-level config. if (!fs.existsSync(".babelrc")) { outputFileSync(".babelrc", "{}"); } - Object.keys(files).forEach(function(filename) { + Object.keys(files).forEach(function (filename) { const content = files[filename]; outputFileSync(filename, content); }); }; -const normalizeOutput = function(str, cwd) { +const normalizeOutput = function (str, cwd) { let prev; do { prev = str; @@ -59,7 +59,7 @@ const normalizeOutput = function(str, cwd) { return str.replace(/\(\d+ms\)/g, "(123ms)"); }; -const assertTest = function(stdout, stderr, opts, cwd) { +const assertTest = function (stdout, stderr, opts, cwd) { stdout = normalizeOutput(stdout, cwd); stderr = normalizeOutput(stderr, cwd); @@ -94,7 +94,7 @@ const assertTest = function(stdout, stderr, opts, cwd) { if (opts.outFiles) { const actualFiles = readDir(tmpLoc, fileFilter); - Object.keys(actualFiles).forEach(function(filename) { + Object.keys(actualFiles).forEach(function (filename) { try { if ( // saveInFiles always creates an empty .babelrc, so lets exclude for now @@ -113,16 +113,16 @@ const assertTest = function(stdout, stderr, opts, cwd) { } }); - Object.keys(opts.outFiles).forEach(function(filename) { + Object.keys(opts.outFiles).forEach(function (filename) { expect(actualFiles).toHaveProperty([filename]); }); } }; -const buildTest = function(binName, testName, opts) { +const buildTest = function (binName, testName, opts) { const binLoc = path.join(__dirname, "../lib", binName); - return function(callback) { + return function (callback) { saveInFiles(opts.inFiles); let args = [binLoc]; @@ -138,15 +138,15 @@ const buildTest = function(binName, testName, opts) { let stderr = ""; let stdout = ""; - spawn.stderr.on("data", function(chunk) { + spawn.stderr.on("data", function (chunk) { stderr += chunk; }); - spawn.stdout.on("data", function(chunk) { + spawn.stdout.on("data", function (chunk) { stdout += chunk; }); - spawn.on("close", function() { + spawn.on("close", function () { let err; try { @@ -170,11 +170,11 @@ const buildTest = function(binName, testName, opts) { }; }; -fs.readdirSync(fixtureLoc).forEach(function(binName) { +fs.readdirSync(fixtureLoc).forEach(function (binName) { if (binName.startsWith(".")) return; const suiteLoc = path.join(fixtureLoc, binName); - describe("bin/" + binName, function() { + describe("bin/" + binName, function () { let cwd; beforeEach(() => { @@ -195,7 +195,7 @@ fs.readdirSync(fixtureLoc).forEach(function(binName) { process.chdir(cwd); }); - fs.readdirSync(suiteLoc).forEach(function(testName) { + fs.readdirSync(suiteLoc).forEach(function (testName) { if (testName.startsWith(".")) return; const testLoc = path.join(suiteLoc, testName); @@ -229,7 +229,7 @@ fs.readdirSync(fixtureLoc).forEach(function(binName) { merge(opts, taskOpts); } - ["stdout", "stdin", "stderr"].forEach(function(key) { + ["stdout", "stdin", "stderr"].forEach(function (key) { const loc = path.join(testLoc, key + ".txt"); opts[key + "Path"] = loc; if (fs.existsSync(loc)) { diff --git a/packages/babel-code-frame/src/index.js b/packages/babel-code-frame/src/index.js index 0aae7fabcd..d0b06f8bf7 100644 --- a/packages/babel-code-frame/src/index.js +++ b/packages/babel-code-frame/src/index.js @@ -175,7 +175,7 @@ export function codeFrameColumns( * Create a code frame, adding line numbers, code highlighting, and pointing to a given position. */ -export default function( +export default function ( rawLines: string, lineNumber: number, colNumber: ?number, diff --git a/packages/babel-code-frame/test/index.js b/packages/babel-code-frame/test/index.js index 23f724ee32..a27ef7c83f 100644 --- a/packages/babel-code-frame/test/index.js +++ b/packages/babel-code-frame/test/index.js @@ -2,8 +2,8 @@ import chalk from "chalk"; import stripAnsi from "strip-ansi"; import codeFrame, { codeFrameColumns } from ".."; -describe("@babel/code-frame", function() { - test("basic usage", function() { +describe("@babel/code-frame", function () { + test("basic usage", function () { const rawLines = ["class Foo {", " constructor()", "};"].join("\n"); expect(codeFrame(rawLines, 2, 16)).toEqual( [ @@ -15,14 +15,14 @@ describe("@babel/code-frame", function() { ); }); - test("optional column number", function() { + test("optional column number", function () { const rawLines = ["class Foo {", " constructor()", "};"].join("\n"); expect(codeFrame(rawLines, 2, null)).toEqual( [" 1 | class Foo {", "> 2 | constructor()", " 3 | };"].join("\n"), ); }); - test("maximum context lines and padding", function() { + test("maximum context lines and padding", function () { const rawLines = [ "/**", " * Sums two numbers.", @@ -49,7 +49,7 @@ describe("@babel/code-frame", function() { ); }); - test("no unnecessary padding due to one-off errors", function() { + test("no unnecessary padding due to one-off errors", function () { const rawLines = [ "/**", " * Sums two numbers.", @@ -76,7 +76,7 @@ describe("@babel/code-frame", function() { ); }); - test("tabs", function() { + test("tabs", function () { const rawLines = [ "\tclass Foo {", "\t \t\t constructor\t(\t)", @@ -92,7 +92,7 @@ describe("@babel/code-frame", function() { ); }); - test("opts.highlightCode", function() { + test("opts.highlightCode", function () { const rawLines = "console.log('babel')"; const result = codeFrame(rawLines, 1, 9, { highlightCode: true }); const stripped = stripAnsi(result); @@ -102,7 +102,7 @@ describe("@babel/code-frame", function() { ); }); - test("opts.highlightCode with multiple columns and lines", function() { + test("opts.highlightCode with multiple columns and lines", function () { // prettier-ignore const rawLines = [ "function a(b, c) {", @@ -141,7 +141,7 @@ describe("@babel/code-frame", function() { ); }); - test("opts.linesAbove", function() { + test("opts.linesAbove", function () { const rawLines = [ "/**", " * Sums two numbers.", @@ -167,7 +167,7 @@ describe("@babel/code-frame", function() { ); }); - test("opts.linesBelow", function() { + test("opts.linesBelow", function () { const rawLines = [ "/**", " * Sums two numbers.", @@ -192,7 +192,7 @@ describe("@babel/code-frame", function() { ); }); - test("opts.linesAbove and opts.linesBelow", function() { + test("opts.linesAbove and opts.linesBelow", function () { const rawLines = [ "/**", " * Sums two numbers.", @@ -213,7 +213,7 @@ describe("@babel/code-frame", function() { ); }); - test("opts.linesAbove no lines above", function() { + test("opts.linesAbove no lines above", function () { const rawLines = [ "class Foo {", " constructor() {", @@ -233,7 +233,7 @@ describe("@babel/code-frame", function() { ); }); - test("opts.linesBelow no lines below", function() { + test("opts.linesBelow no lines below", function () { const rawLines = [ "class Foo {", " constructor() {", @@ -246,7 +246,7 @@ describe("@babel/code-frame", function() { ).toEqual([" 1 | class Foo {", "> 2 | constructor() {"].join("\n")); }); - test("opts.linesBelow single line", function() { + test("opts.linesBelow single line", function () { const rawLines = [ "class Foo {", " constructor() {", @@ -263,7 +263,7 @@ describe("@babel/code-frame", function() { ).toEqual(["> 2 | constructor() {"].join("\n")); }); - test("opts.forceColor", function() { + test("opts.forceColor", function () { const marker = chalk.red.bold; const gutter = chalk.grey; @@ -285,7 +285,7 @@ describe("@babel/code-frame", function() { ); }); - test("basic usage, new API", function() { + test("basic usage, new API", function () { const rawLines = ["class Foo {", " constructor()", "};"].join("\n"); expect( codeFrameColumns(rawLines, { start: { line: 2, column: 16 } }), @@ -299,7 +299,7 @@ describe("@babel/code-frame", function() { ); }); - test("mark multiple columns", function() { + test("mark multiple columns", function () { const rawLines = ["class Foo {", " constructor()", "};"].join("\n"); expect( codeFrameColumns(rawLines, { @@ -316,7 +316,7 @@ describe("@babel/code-frame", function() { ); }); - test("mark multiple columns across lines", function() { + test("mark multiple columns across lines", function () { const rawLines = ["class Foo {", " constructor() {", " }", "};"].join( "\n", ); @@ -337,7 +337,7 @@ describe("@babel/code-frame", function() { ); }); - test("mark multiple columns across multiple lines", function() { + test("mark multiple columns across multiple lines", function () { const rawLines = [ "class Foo {", " constructor() {", @@ -364,7 +364,7 @@ describe("@babel/code-frame", function() { ); }); - test("mark across multiple lines without columns", function() { + test("mark across multiple lines without columns", function () { const rawLines = [ "class Foo {", " constructor() {", @@ -385,7 +385,7 @@ describe("@babel/code-frame", function() { ); }); - test("opts.message", function() { + test("opts.message", function () { const rawLines = ["class Foo {", " constructor()", "};"].join("\n"); expect( codeFrameColumns( @@ -405,7 +405,7 @@ describe("@babel/code-frame", function() { ); }); - test("opts.message without column", function() { + test("opts.message without column", function () { const rawLines = ["class Foo {", " constructor()", "};"].join("\n"); expect( codeFrameColumns( @@ -425,7 +425,7 @@ describe("@babel/code-frame", function() { ); }); - test("opts.message with multiple lines", function() { + test("opts.message with multiple lines", function () { const rawLines = [ "class Foo {", " constructor() {", @@ -458,7 +458,7 @@ describe("@babel/code-frame", function() { ); }); - test("opts.message with multiple lines without columns", function() { + test("opts.message with multiple lines without columns", function () { const rawLines = [ "class Foo {", " constructor() {", diff --git a/packages/babel-compat-data/scripts/utils-build-data.js b/packages/babel-compat-data/scripts/utils-build-data.js index 28708953e4..4fdaef6bbe 100644 --- a/packages/babel-compat-data/scripts/utils-build-data.js +++ b/packages/babel-compat-data/scripts/utils-build-data.js @@ -122,7 +122,7 @@ exports.generateData = (environments, features) => { }); }; -exports.writeFile = function(data, dataPath, name) { +exports.writeFile = function (data, dataPath, name) { const stringified = JSON.stringify(data, null, 2) + "\n"; if (process.env.CHECK_COMPAT_DATA) { const currentData = fs.readFileSync(dataPath, "utf8"); diff --git a/packages/babel-core/src/config/caching.js b/packages/babel-core/src/config/caching.js index fcad6e8fcc..6b6e7967a2 100644 --- a/packages/babel-core/src/config/caching.js +++ b/packages/babel-core/src/config/caching.js @@ -330,7 +330,7 @@ class CacheConfigurator { validator(): SideChannel => Handler { const pairs = this._pairs; - return function*(data: SideChannel) { + return function* (data: SideChannel) { for (const [key, fn] of pairs) { if (key !== (yield* fn(data))) return false; } diff --git a/packages/babel-core/src/config/config-chain.js b/packages/babel-core/src/config/config-chain.js index 1af3f35d23..4fc2f8d0ef 100644 --- a/packages/babel-core/src/config/config-chain.js +++ b/packages/babel-core/src/config/config-chain.js @@ -429,7 +429,7 @@ function makeChainWalker({ ConfigContext, Set | void, ) => Handler { - return function*(input, context, files = new Set()) { + return function* (input, context, files = new Set()) { const { dirname } = input; const flattenedConfigs = []; diff --git a/packages/babel-core/src/config/files/utils.js b/packages/babel-core/src/config/files/utils.js index 61c3b24a7a..6a8818c2b3 100644 --- a/packages/babel-core/src/config/files/utils.js +++ b/packages/babel-core/src/config/files/utils.js @@ -9,7 +9,7 @@ import nodeFs from "fs"; export function makeStaticFileCache( fn: (string, string) => T, ): Gensync<[string], T | null> { - return (makeStrongCache(function*( + return (makeStrongCache(function* ( filepath: string, cache: CacheConfigurator, ): Handler { diff --git a/packages/babel-core/src/config/full.js b/packages/babel-core/src/config/full.js index 35b6dc8662..c9fb038a30 100644 --- a/packages/babel-core/src/config/full.js +++ b/packages/babel-core/src/config/full.js @@ -211,7 +211,7 @@ export default gensync<[any], ResolvedConfig | null>(function* loadFullConfig( /** * Load a generic plugin/preset from the given descriptor loaded from the config object. */ -const loadDescriptor = makeWeakCache(function*( +const loadDescriptor = makeWeakCache(function* ( { value, options, dirname, alias }: UnloadedDescriptor, cache: CacheConfigurator, ): Handler { @@ -277,7 +277,7 @@ function* loadPluginDescriptor( ); } -const instantiatePlugin = makeWeakCache(function*( +const instantiatePlugin = makeWeakCache(function* ( { value, options, dirname, alias }: LoadedDescriptor, cache: CacheConfigurator, ): Handler { @@ -383,7 +383,7 @@ function chain(a, b) { const fns = [a, b].filter(Boolean); if (fns.length <= 1) return fns[0]; - return function(...args) { + return function (...args) { for (const fn of fns) { fn.apply(this, args); } diff --git a/packages/babel-core/src/config/index.js b/packages/babel-core/src/config/index.js index b0a29c8b77..2f9a229b7c 100644 --- a/packages/babel-core/src/config/index.js +++ b/packages/babel-core/src/config/index.js @@ -15,7 +15,7 @@ import { loadPartialConfig as loadPartialConfigRunner } from "./partial"; export { loadFullConfig as default }; export type { PartialConfig } from "./partial"; -const loadOptionsRunner = gensync<[mixed], Object | null>(function*(opts) { +const loadOptionsRunner = gensync<[mixed], Object | null>(function* (opts) { const config = yield* loadFullConfig(opts); // NOTE: We want to return "null" explicitly, while ?. alone returns undefined return config?.options ?? null; diff --git a/packages/babel-core/src/config/partial.js b/packages/babel-core/src/config/partial.js index e071484ca1..4d8defe4b6 100644 --- a/packages/babel-core/src/config/partial.js +++ b/packages/babel-core/src/config/partial.js @@ -135,30 +135,32 @@ export default function* loadPrivatePartialConfig( }; } -export const loadPartialConfig = gensync<[any], PartialConfig | null>(function*( - inputOpts: mixed, -): Handler { - const result: ?PrivPartialConfig = yield* loadPrivatePartialConfig(inputOpts); - if (!result) return null; +export const loadPartialConfig = gensync<[any], PartialConfig | null>( + function* (inputOpts: mixed): Handler { + const result: ?PrivPartialConfig = yield* loadPrivatePartialConfig( + inputOpts, + ); + if (!result) return null; - const { options, babelrc, ignore, config } = result; + const { options, babelrc, ignore, config } = result; - (options.plugins || []).forEach(item => { - if (item.value instanceof Plugin) { - throw new Error( - "Passing cached plugin instances is not supported in " + - "babel.loadPartialConfig()", - ); - } - }); + (options.plugins || []).forEach(item => { + if (item.value instanceof Plugin) { + throw new Error( + "Passing cached plugin instances is not supported in " + + "babel.loadPartialConfig()", + ); + } + }); - return new PartialConfig( - options, - babelrc ? babelrc.filepath : undefined, - ignore ? ignore.filepath : undefined, - config ? config.filepath : undefined, - ); -}); + return new PartialConfig( + options, + babelrc ? babelrc.filepath : undefined, + ignore ? ignore.filepath : undefined, + config ? config.filepath : undefined, + ); + }, +); export type { PartialConfig }; diff --git a/packages/babel-core/src/gensync-utils/async.js b/packages/babel-core/src/gensync-utils/async.js index 84edcc3941..a7d70c47bc 100644 --- a/packages/babel-core/src/gensync-utils/async.js +++ b/packages/babel-core/src/gensync-utils/async.js @@ -6,7 +6,7 @@ type MaybePromise = T | Promise; const id = x => x; -const runGenerator = gensync(function*(item) { +const runGenerator = gensync(function* (item) { return yield* item; }); @@ -76,10 +76,10 @@ export function forwardAsync( export const onFirstPause = (gensync<[any, any], any>({ name: "onFirstPause", arity: 2, - sync: function(item) { + sync: function (item) { return runGenerator.sync(item); }, - errback: function(item, firstPause, cb) { + errback: function (item, firstPause, cb) { let completed = false; runGenerator.errback(item, (err, value) => { diff --git a/packages/babel-core/src/tools/build-external-helpers.js b/packages/babel-core/src/tools/build-external-helpers.js index 914f2baf4e..4f38272b14 100644 --- a/packages/babel-core/src/tools/build-external-helpers.js +++ b/packages/babel-core/src/tools/build-external-helpers.js @@ -132,7 +132,7 @@ function buildHelpers(body, namespace, whitelist) { }; const refs = {}; - helpers.list.forEach(function(name) { + helpers.list.forEach(function (name) { if (whitelist && whitelist.indexOf(name) < 0) return; const ref = (refs[name] = getHelperReference(name)); @@ -144,7 +144,7 @@ function buildHelpers(body, namespace, whitelist) { }); return refs; } -export default function( +export default function ( whitelist?: Array, outputType: "global" | "module" | "umd" | "var" = "global", ) { diff --git a/packages/babel-core/src/transform-ast.js b/packages/babel-core/src/transform-ast.js index 9a40bda90d..5a6f0993d8 100644 --- a/packages/babel-core/src/transform-ast.js +++ b/packages/babel-core/src/transform-ast.js @@ -28,7 +28,7 @@ type TransformFromAst = { const transformFromAstRunner = gensync< [AstRoot, string, ?InputOptions], FileResult | null, ->(function*(ast, code, opts) { +>(function* (ast, code, opts) { const config: ResolvedConfig | null = yield* loadConfig(opts); if (config === null) return null; diff --git a/packages/babel-core/src/transform-file.js b/packages/babel-core/src/transform-file.js index 24861d67b1..480afc1cf6 100644 --- a/packages/babel-core/src/transform-file.js +++ b/packages/babel-core/src/transform-file.js @@ -24,7 +24,7 @@ type TransformFile = { }; const transformFileRunner = gensync<[string, ?InputOptions], FileResult | null>( - function*(filename, opts) { + function* (filename, opts) { const options = { ...opts, filename }; const config: ResolvedConfig | null = yield* loadConfig(options); diff --git a/packages/babel-core/src/transformation/block-hoist-plugin.js b/packages/babel-core/src/transformation/block-hoist-plugin.js index 95e48d1cd6..477d2d5c3b 100644 --- a/packages/babel-core/src/transformation/block-hoist-plugin.js +++ b/packages/babel-core/src/transformation/block-hoist-plugin.js @@ -51,7 +51,7 @@ const blockHoistPlugin = { } if (!hasChange) return; - node.body = sortBy(node.body, function(bodyNode) { + node.body = sortBy(node.body, function (bodyNode) { let priority = bodyNode?._blockHoist; if (priority == null) priority = 1; if (priority === true) priority = 2; diff --git a/packages/babel-core/test/api.js b/packages/babel-core/test/api.js index 5ce9a364c3..8da161d595 100644 --- a/packages/babel-core/test/api.js +++ b/packages/babel-core/test/api.js @@ -57,12 +57,12 @@ function transformFromAst(ast, code, opts) { }); } -describe("parser and generator options", function() { +describe("parser and generator options", function () { const recast = { - parse: function(code, opts) { + parse: function (code, opts) { return opts.parser.parse(code); }, - print: function(ast) { + print: function (ast) { return generator(ast); }, }; @@ -81,7 +81,7 @@ describe("parser and generator options", function() { }); } - it("options", function() { + it("options", function () { const string = "original;"; expect(newTransform(string).ast).toEqual( transform(string, { ast: true }).ast, @@ -89,7 +89,7 @@ describe("parser and generator options", function() { expect(newTransform(string).code).toBe(string); }); - it("experimental syntax", function() { + it("experimental syntax", function () { const experimental = "var a: number = 1;"; expect(newTransform(experimental).ast).toEqual( @@ -126,7 +126,7 @@ describe("parser and generator options", function() { expect(newTransformWithPlugins(experimental).code).toBe(experimental); }); - it("other options", function() { + it("other options", function () { const experimental = "if (true) {\n import a from 'a';\n}"; expect(newTransform(experimental).ast).not.toBe( @@ -141,33 +141,33 @@ describe("parser and generator options", function() { }); }); -describe("api", function() { - it("exposes the resolvePlugin method", function() { +describe("api", function () { + it("exposes the resolvePlugin method", function () { expect(() => babel.resolvePlugin("nonexistent-plugin")).toThrow( /Cannot find module 'babel-plugin-nonexistent-plugin'/, ); }); - it("exposes the resolvePreset method", function() { + it("exposes the resolvePreset method", function () { expect(() => babel.resolvePreset("nonexistent-preset")).toThrow( /Cannot find module 'babel-preset-nonexistent-preset'/, ); }); - it("exposes types", function() { + it("exposes types", function () { expect(babel.types).toBeDefined(); }); - it("exposes the parser's token types", function() { + it("exposes the parser's token types", function () { expect(babel.tokTypes).toBeDefined(); }); - it("transformFile", function(done) { + it("transformFile", function (done) { const options = { babelrc: false, }; Object.freeze(options); - transformFile(__dirname + "/fixtures/api/file.js", options, function( + transformFile(__dirname + "/fixtures/api/file.js", options, function ( err, res, ) { @@ -179,7 +179,7 @@ describe("api", function() { }); }); - it("transformFileSync", function() { + it("transformFileSync", function () { const options = { babelrc: false, }; @@ -190,15 +190,15 @@ describe("api", function() { expect(options).toEqual({ babelrc: false }); }); - it("transformFromAst should not mutate the AST", function() { + it("transformFromAst should not mutate the AST", function () { const program = "const identifier = 1"; const node = parse(program); const { code } = transformFromAst(node, program, { plugins: [ - function() { + function () { return { visitor: { - Identifier: function(path) { + Identifier: function (path) { path.node.name = "replaced"; }, }, @@ -214,38 +214,38 @@ describe("api", function() { ); }); - it("options throw on falsy true", function() { - return expect(function() { + it("options throw on falsy true", function () { + return expect(function () { transform("", { plugins: [__dirname + "/../../babel-plugin-syntax-jsx", false], }); }).toThrow(/.plugins\[1\] must be a string, object, function/); }); - it("options merge backwards", function() { + it("options merge backwards", function () { return transformAsync("", { presets: [__dirname + "/../../babel-preset-env"], plugins: [__dirname + "/../../babel-plugin-syntax-jsx"], - }).then(function(result) { + }).then(function (result) { expect(result.options.plugins[0].manipulateOptions.toString()).toEqual( expect.stringContaining("jsx"), ); }); }); - it("option wrapPluginVisitorMethod", function() { + it("option wrapPluginVisitorMethod", function () { let calledRaw = 0; let calledIntercept = 0; transform("function foo() { bar(foobar); }", { - wrapPluginVisitorMethod: function(pluginAlias, visitorType, callback) { + wrapPluginVisitorMethod: function (pluginAlias, visitorType, callback) { if (pluginAlias !== "foobar") { return callback; } expect(visitorType).toBe("enter"); - return function() { + return function () { calledIntercept++; return callback.apply(this, arguments); }; @@ -255,7 +255,7 @@ describe("api", function() { new Plugin({ name: "foobar", visitor: { - "Program|Identifier": function() { + "Program|Identifier": function () { calledRaw++; }, }, @@ -267,7 +267,7 @@ describe("api", function() { expect(calledIntercept).toBe(4); }); - it("pass per preset", function() { + it("pass per preset", function () { let aliasBaseType = null; function execTest(passPerPreset) { @@ -276,12 +276,12 @@ describe("api", function() { passPerPreset: passPerPreset, presets: [ // First preset with our plugin, "before" - function() { + function () { return { plugins: [ new Plugin({ visitor: { - Function: function(path) { + Function: function (path) { const alias = path.scope .getProgramParent() .path.get("body")[0].node; @@ -307,7 +307,7 @@ describe("api", function() { require(__dirname + "/../../babel-preset-env"), // Third preset for Flow. - function() { + function () { return { plugins: [ require(__dirname + "/../../babel-plugin-syntax-flow"), @@ -339,7 +339,7 @@ describe("api", function() { expect(result.code).toBe("var x = function x(y) {\n return y;\n};"); }); - it("complex plugin and preset ordering", function() { + it("complex plugin and preset ordering", function () { function pushPlugin(str) { return { visitor: { @@ -414,7 +414,7 @@ describe("api", function() { ); }); - it("interpreter directive backward-compat", function() { + it("interpreter directive backward-compat", function () { function doTransform(code, preHandler) { return transform(code, { plugins: [ @@ -468,7 +468,7 @@ describe("api", function() { ).toBe(`#!env node3`); }); - it("source map merging", function() { + it("source map merging", function () { const result = transform( [ /* eslint-disable max-len */ @@ -515,52 +515,54 @@ describe("api", function() { }); }); - it("default source map filename", function() { + it("default source map filename", function () { return transformAsync("var a = 10;", { cwd: "/some/absolute", filename: "/some/absolute/file/path.js", sourceMaps: true, - }).then(function(result) { + }).then(function (result) { expect(result.map.sources).toEqual(["path.js"]); }); }); - it("code option false", function() { - return transformAsync("foo('bar');", { code: false }).then(function( + it("code option false", function () { + return transformAsync("foo('bar');", { code: false }).then(function ( result, ) { expect(result.code).toBeFalsy(); }); }); - it("ast option false", function() { - return transformAsync("foo('bar');", { ast: false }).then(function(result) { + it("ast option false", function () { + return transformAsync("foo('bar');", { ast: false }).then(function ( + result, + ) { expect(result.ast).toBeFalsy(); }); }); - it("ast option true", function() { - return transformAsync("foo('bar');", { ast: true }).then(function(result) { + it("ast option true", function () { + return transformAsync("foo('bar');", { ast: true }).then(function (result) { expect(result.ast).toBeTruthy(); }); }); - it("ast option default", function() { - return transformAsync("foo('bar');").then(function(result) { + it("ast option default", function () { + return transformAsync("foo('bar');").then(function (result) { expect(result.ast).toBeFalsy(); }); }); - it("auxiliaryComment option", function() { + it("auxiliaryComment option", function () { return transformAsync("class Foo {}", { auxiliaryCommentBefore: "before", auxiliaryCommentAfter: "after", plugins: [ - function(babel) { + function (babel) { const t = babel.types; return { visitor: { - Program: function(path) { + Program: function (path) { path.unshiftContainer( "body", t.expressionStatement(t.identifier("start")), @@ -574,14 +576,14 @@ describe("api", function() { }; }, ], - }).then(function(result) { + }).then(function (result) { expect(result.code).toBe( "/*before*/\nstart;\n\n/*after*/\nclass Foo {}\n\n/*before*/\nend;\n\n/*after*/", ); }); }); - it("ignore option", function() { + it("ignore option", function () { return Promise.all([ transformAsync("", { ignore: ["/foo"], @@ -620,7 +622,7 @@ describe("api", function() { ]); }); - it("only option", function() { + it("only option", function () { return Promise.all([ transformAsync("", { only: ["/foo"], @@ -659,23 +661,23 @@ describe("api", function() { ]); }); - describe("env option", function() { + describe("env option", function () { const oldBabelEnv = process.env.BABEL_ENV; const oldNodeEnv = process.env.NODE_ENV; - beforeEach(function() { + beforeEach(function () { // Tests need to run with the default and specific values for these. They // need to be cleared for each test. delete process.env.BABEL_ENV; delete process.env.NODE_ENV; }); - afterAll(function() { + afterAll(function () { process.env.BABEL_ENV = oldBabelEnv; process.env.NODE_ENV = oldNodeEnv; }); - it("default", function() { + it("default", function () { const result = transform("foo;", { env: { development: { comments: false }, @@ -685,7 +687,7 @@ describe("api", function() { expect(result.options.comments).toBe(false); }); - it("BABEL_ENV", function() { + it("BABEL_ENV", function () { process.env.BABEL_ENV = "foo"; const result = transform("foo;", { env: { @@ -695,7 +697,7 @@ describe("api", function() { expect(result.options.comments).toBe(false); }); - it("NODE_ENV", function() { + it("NODE_ENV", function () { process.env.NODE_ENV = "foo"; const result = transform("foo;", { env: { @@ -706,59 +708,59 @@ describe("api", function() { }); }); - describe("buildExternalHelpers", function() { - describe("smoke tests", function() { - it("builds external helpers in global output type", function() { + describe("buildExternalHelpers", function () { + describe("smoke tests", function () { + it("builds external helpers in global output type", function () { babel.buildExternalHelpers(null, "global"); }); - it("builds external helpers in module output type", function() { + it("builds external helpers in module output type", function () { babel.buildExternalHelpers(null, "module"); }); - it("builds external helpers in umd output type", function() { + it("builds external helpers in umd output type", function () { babel.buildExternalHelpers(null, "umd"); }); - it("builds external helpers in var output type", function() { + it("builds external helpers in var output type", function () { babel.buildExternalHelpers(null, "var"); }); }); - it("all", function() { + it("all", function () { const script = babel.buildExternalHelpers(); expect(script).toEqual(expect.stringContaining("classCallCheck")); expect(script).toEqual(expect.stringContaining("inherits")); }); - it("whitelist", function() { + it("whitelist", function () { const script = babel.buildExternalHelpers(["inherits"]); expect(script).not.toEqual(expect.stringContaining("classCallCheck")); expect(script).toEqual(expect.stringContaining("inherits")); }); - it("empty whitelist", function() { + it("empty whitelist", function () { const script = babel.buildExternalHelpers([]); expect(script).not.toEqual(expect.stringContaining("classCallCheck")); expect(script).not.toEqual(expect.stringContaining("inherits")); }); - it("underscored", function() { + it("underscored", function () { const script = babel.buildExternalHelpers(["typeof"]); expect(script).toEqual(expect.stringContaining("typeof")); }); }); - describe("handle parsing errors", function() { + describe("handle parsing errors", function () { const options = { babelrc: false, }; - it("only syntax plugin available", function(done) { + it("only syntax plugin available", function (done) { transformFile( __dirname + "/fixtures/api/parsing-errors/only-syntax/file.js", options, - function(err) { + function (err) { expect(err.message).toMatch( "Support for the experimental syntax 'pipelineOperator' isn't currently enabled (1:3):", ); @@ -771,11 +773,11 @@ describe("api", function() { ); }); - it("both syntax and transform plugin available", function(done) { + it("both syntax and transform plugin available", function (done) { transformFile( __dirname + "/fixtures/api/parsing-errors/syntax-and-transform/file.js", options, - function(err) { + function (err) { expect(err.message).toMatch( "Support for the experimental syntax 'logicalAssignment' isn't currently enabled (1:3):", ); @@ -789,13 +791,13 @@ describe("api", function() { }); }); - describe("missing helpers", function() { - it("should always throw", function() { + describe("missing helpers", function () { + it("should always throw", function () { expect(() => babel.transformSync(``, { configFile: false, plugins: [ - function() { + function () { return { visitor: { Program(path) { diff --git a/packages/babel-core/test/async.js b/packages/babel-core/test/async.js index 3d834c9e63..0e2bbdce8c 100644 --- a/packages/babel-core/test/async.js +++ b/packages/babel-core/test/async.js @@ -11,12 +11,12 @@ describe("asynchronicity", () => { const base = path.join(__dirname, "fixtures", "async"); let cwd; - beforeEach(function() { + beforeEach(function () { cwd = process.cwd(); process.chdir(base); }); - afterEach(function() { + afterEach(function () { process.chdir(cwd); }); diff --git a/packages/babel-core/test/caching-api.js b/packages/babel-core/test/caching-api.js index f8d442c150..c88e6fddf7 100644 --- a/packages/babel-core/test/caching-api.js +++ b/packages/babel-core/test/caching-api.js @@ -421,7 +421,7 @@ describe("caching API", () => { it("should throw if the cache is configured asynchronously", async () => { const fn = gensync( - makeStrongCache(function*(arg, cache) { + makeStrongCache(function* (arg, cache) { yield* wait(1000); cache.never(); return { arg }; @@ -435,7 +435,7 @@ describe("caching API", () => { it("should allow asynchronous cache invalidation functions", async () => { const fn = gensync( - makeStrongCache(function*(arg, cache) { + makeStrongCache(function* (arg, cache) { yield* waitFor( cache.using(async () => { await wait.async(50); @@ -453,7 +453,7 @@ describe("caching API", () => { it("should allow synchronous yield before cache configuration", async () => { const fn = gensync( - makeStrongCache(function*(arg, cache) { + makeStrongCache(function* (arg, cache) { yield* gensync({ sync: () => 2, errback: cb => cb(null, 2), diff --git a/packages/babel-core/test/config-chain.js b/packages/babel-core/test/config-chain.js index aef0ba90cb..c0b2e512c4 100644 --- a/packages/babel-core/test/config-chain.js +++ b/packages/babel-core/test/config-chain.js @@ -16,12 +16,12 @@ const pfs = return function copyFile(source, target) { const rd = fs.createReadStream(source); const wr = fs.createWriteStream(target); - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { rd.on("error", reject); wr.on("error", reject); wr.on("finish", resolve); rd.pipe(wr); - }).catch(function(error) { + }).catch(function (error) { rd.destroy(); wr.end(); throw error; @@ -69,7 +69,7 @@ async function getTemp(name) { return { cwd, tmp, config }; } -describe("buildConfigChain", function() { +describe("buildConfigChain", function () { describe("test", () => { describe("single", () => { it("should process matching string values", () => { @@ -702,8 +702,8 @@ describe("buildConfigChain", function() { }); }); - describe("caching", function() { - describe("programmatic options", function() { + describe("caching", function () { + describe("programmatic options", function () { const plugins1 = [() => ({})]; const plugins2 = [() => ({})]; @@ -807,7 +807,7 @@ describe("buildConfigChain", function() { }); }); - describe("config file options", function() { + describe("config file options", function () { function touch(filepath) { const s = fs.statSync(filepath); fs.utimesSync( diff --git a/packages/babel-core/test/config-loading.js b/packages/babel-core/test/config-loading.js index 4f61315404..d62a948254 100644 --- a/packages/babel-core/test/config-loading.js +++ b/packages/babel-core/test/config-loading.js @@ -40,7 +40,7 @@ describe("@babel/core config loading", () => { describe("loadPartialConfig", () => { it("should preserve disabled plugins in the partial config", () => { - const plugin = function() { + const plugin = function () { return {}; }; @@ -59,7 +59,7 @@ describe("@babel/core config loading", () => { }); it("should preserve disabled presets in the partial config", () => { - const preset = function() { + const preset = function () { return {}; }; diff --git a/packages/babel-core/test/evaluation.js b/packages/babel-core/test/evaluation.js index 8ef3b0c903..ffe9b5a3a2 100644 --- a/packages/babel-core/test/evaluation.js +++ b/packages/babel-core/test/evaluation.js @@ -1,12 +1,12 @@ import traverse from "@babel/traverse"; import { parse } from "@babel/parser"; -describe("evaluation", function() { +describe("evaluation", function () { function addTest(code, type, value, notConfident) { - it(type + ": " + code, function() { + it(type + ": " + code, function () { const visitor = {}; - visitor[type] = function(path) { + visitor[type] = function (path) { const evaluate = path.evaluate(); expect(evaluate.confident).toEqual(!notConfident); expect(evaluate.value).toEqual(value); diff --git a/packages/babel-core/test/option-manager.js b/packages/babel-core/test/option-manager.js index e792d27f05..ecc9272754 100644 --- a/packages/babel-core/test/option-manager.js +++ b/packages/babel-core/test/option-manager.js @@ -234,9 +234,9 @@ describe("option-manager", () => { }); }); - describe("presets", function() { + describe("presets", function () { function presetTest(name) { - it(name, function() { + it(name, function () { const options = loadOptions({ presets: [ path.join(__dirname, "fixtures/option-manager/presets", name), @@ -250,7 +250,7 @@ describe("option-manager", () => { } function presetThrowsTest(name, msg) { - it(name, function() { + it(name, function () { expect(() => loadOptions({ presets: [ diff --git a/packages/babel-core/test/parse.js b/packages/babel-core/test/parse.js index ec36951cb0..5e19566049 100644 --- a/packages/babel-core/test/parse.js +++ b/packages/babel-core/test/parse.js @@ -6,8 +6,8 @@ function fixture(...args) { return path.join(__dirname, "fixtures", "parse", ...args); } -describe("parse", function() { - it("should parse using configuration from .babelrc when a filename is provided", function() { +describe("parse", function () { + it("should parse using configuration from .babelrc when a filename is provided", function () { const input = fs.readFileSync(fixture("input.js"), "utf8"); const output = require(fixture("output")); @@ -18,7 +18,7 @@ describe("parse", function() { expect(JSON.parse(JSON.stringify(result))).toEqual(output); }); - it("should parse using passed in configuration", function() { + it("should parse using passed in configuration", function () { const input = fs.readFileSync(fixture("input.js"), "utf8"); const output = require(fixture("output.json")); diff --git a/packages/babel-core/test/path.js b/packages/babel-core/test/path.js index 1f139ab2a2..2edb48921b 100644 --- a/packages/babel-core/test/path.js +++ b/packages/babel-core/test/path.js @@ -1,8 +1,8 @@ import { transform } from "../lib/index"; import Plugin from "../lib/config/plugin"; -describe("traversal path", function() { - it("replaceWithSourceString", function() { +describe("traversal path", function () { + it("replaceWithSourceString", function () { const expectCode = "function foo() {}"; const actualCode = transform(expectCode, { @@ -10,7 +10,7 @@ describe("traversal path", function() { plugins: [ new Plugin({ visitor: { - FunctionDeclaration: function(path) { + FunctionDeclaration: function (path) { path.replaceWithSourceString("console.whatever()"); }, }, @@ -21,7 +21,7 @@ describe("traversal path", function() { expect(actualCode).toBe("console.whatever();"); }); - it("replaceWith (arrow expression body to block statement body)", function() { + it("replaceWith (arrow expression body to block statement body)", function () { const expectCode = "var fn = () => true;"; const actualCode = transform(expectCode, { @@ -29,7 +29,7 @@ describe("traversal path", function() { plugins: [ new Plugin({ visitor: { - ArrowFunctionExpression: function(path) { + ArrowFunctionExpression: function (path) { path.get("body").replaceWith({ type: "BlockStatement", body: [ @@ -51,7 +51,7 @@ describe("traversal path", function() { expect(actualCode).toBe("var fn = () => {\n return true;\n};"); }); - it("replaceWith (arrow block statement body to expression body)", function() { + it("replaceWith (arrow block statement body to expression body)", function () { const expectCode = "var fn = () => { return true; }"; const actualCode = transform(expectCode, { @@ -59,7 +59,7 @@ describe("traversal path", function() { plugins: [ new Plugin({ visitor: { - ArrowFunctionExpression: function(path) { + ArrowFunctionExpression: function (path) { path.get("body").replaceWith({ type: "BooleanLiteral", value: true, @@ -73,7 +73,7 @@ describe("traversal path", function() { expect(actualCode).toBe("var fn = () => true;"); }); - it("replaceWith (for-in left expression to variable declaration)", function() { + it("replaceWith (for-in left expression to variable declaration)", function () { const expectCode = "for (KEY in right);"; const actualCode = transform(expectCode, { @@ -81,7 +81,7 @@ describe("traversal path", function() { plugins: [ new Plugin({ visitor: { - ForInStatement: function(path) { + ForInStatement: function (path) { path.get("left").replaceWith({ type: "VariableDeclaration", kind: "var", @@ -104,7 +104,7 @@ describe("traversal path", function() { expect(actualCode).toBe("for (var KEY in right);"); }); - it("replaceWith (for-in left variable declaration to expression)", function() { + it("replaceWith (for-in left variable declaration to expression)", function () { const expectCode = "for (var KEY in right);"; const actualCode = transform(expectCode, { @@ -112,7 +112,7 @@ describe("traversal path", function() { plugins: [ new Plugin({ visitor: { - ForInStatement: function(path) { + ForInStatement: function (path) { path.get("left").replaceWith({ type: "Identifier", name: "KEY", @@ -126,7 +126,7 @@ describe("traversal path", function() { expect(actualCode).toBe("for (KEY in right);"); }); - it("replaceWith (for-loop left expression to variable declaration)", function() { + it("replaceWith (for-loop left expression to variable declaration)", function () { const expectCode = "for (KEY;;);"; const actualCode = transform(expectCode, { @@ -134,7 +134,7 @@ describe("traversal path", function() { plugins: [ new Plugin({ visitor: { - ForStatement: function(path) { + ForStatement: function (path) { path.get("init").replaceWith({ type: "VariableDeclaration", kind: "var", @@ -157,7 +157,7 @@ describe("traversal path", function() { expect(actualCode).toBe("for (var KEY;;);"); }); - it("replaceWith (for-loop left variable declaration to expression)", function() { + it("replaceWith (for-loop left variable declaration to expression)", function () { const expectCode = "for (var KEY;;);"; const actualCode = transform(expectCode, { @@ -165,7 +165,7 @@ describe("traversal path", function() { plugins: [ new Plugin({ visitor: { - ForStatement: function(path) { + ForStatement: function (path) { path.get("init").replaceWith({ type: "Identifier", name: "KEY", diff --git a/packages/babel-core/test/resolution.js b/packages/babel-core/test/resolution.js index 203d76ec57..7ec7a628ef 100644 --- a/packages/babel-core/test/resolution.js +++ b/packages/babel-core/test/resolution.js @@ -1,20 +1,20 @@ import * as babel from "../lib/index"; import path from "path"; -describe("addon resolution", function() { +describe("addon resolution", function () { const base = path.join(__dirname, "fixtures", "resolution"); let cwd; - beforeEach(function() { + beforeEach(function () { cwd = process.cwd(); process.chdir(base); }); - afterEach(function() { + afterEach(function () { process.chdir(cwd); }); - it("should find module: presets", function() { + it("should find module: presets", function () { process.chdir("module-paths"); babel.transform("", { @@ -24,7 +24,7 @@ describe("addon resolution", function() { }); }); - it("should find module: plugins", function() { + it("should find module: plugins", function () { process.chdir("module-paths"); babel.transform("", { @@ -34,7 +34,7 @@ describe("addon resolution", function() { }); }); - it("should find standard presets", function() { + it("should find standard presets", function () { process.chdir("standard-paths"); babel.transform("", { @@ -44,7 +44,7 @@ describe("addon resolution", function() { }); }); - it("should find standard plugins", function() { + it("should find standard plugins", function () { process.chdir("standard-paths"); babel.transform("", { @@ -54,7 +54,7 @@ describe("addon resolution", function() { }); }); - it("should find standard presets with an existing prefix", function() { + it("should find standard presets with an existing prefix", function () { process.chdir("standard-paths"); babel.transform("", { @@ -64,7 +64,7 @@ describe("addon resolution", function() { }); }); - it("should find standard plugins with an existing prefix", function() { + it("should find standard plugins with an existing prefix", function () { process.chdir("standard-paths"); babel.transform("", { @@ -74,7 +74,7 @@ describe("addon resolution", function() { }); }); - it("should find @babel scoped presets", function() { + it("should find @babel scoped presets", function () { process.chdir("babel-org-paths"); babel.transform("", { @@ -84,7 +84,7 @@ describe("addon resolution", function() { }); }); - it("should find @babel scoped plugins", function() { + it("should find @babel scoped plugins", function () { process.chdir("babel-org-paths"); babel.transform("", { @@ -94,7 +94,7 @@ describe("addon resolution", function() { }); }); - it("should find @babel scoped presets with an existing prefix", function() { + it("should find @babel scoped presets with an existing prefix", function () { process.chdir("babel-org-paths"); babel.transform("", { @@ -104,7 +104,7 @@ describe("addon resolution", function() { }); }); - it("should find @babel scoped plugins", function() { + it("should find @babel scoped plugins", function () { process.chdir("babel-org-paths"); babel.transform("", { @@ -114,7 +114,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo scoped presets", function() { + it("should find @foo scoped presets", function () { process.chdir("foo-org-paths"); babel.transform("", { @@ -124,7 +124,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo scoped plugins", function() { + it("should find @foo scoped plugins", function () { process.chdir("foo-org-paths"); babel.transform("", { @@ -134,7 +134,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo scoped presets with an inner babel-preset", function() { + it("should find @foo scoped presets with an inner babel-preset", function () { process.chdir("foo-org-paths"); babel.transform("", { @@ -144,7 +144,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo scoped plugins with an inner babel-plugin", function() { + it("should find @foo scoped plugins with an inner babel-plugin", function () { process.chdir("foo-org-paths"); babel.transform("", { @@ -154,7 +154,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo scoped presets with an babel-preset suffix", function() { + it("should find @foo scoped presets with an babel-preset suffix", function () { process.chdir("foo-org-paths"); babel.transform("", { @@ -164,7 +164,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo scoped plugins with an babel-plugin suffix", function() { + it("should find @foo scoped plugins with an babel-plugin suffix", function () { process.chdir("foo-org-paths"); babel.transform("", { @@ -174,7 +174,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo scoped presets with an existing prefix", function() { + it("should find @foo scoped presets with an existing prefix", function () { process.chdir("foo-org-paths"); babel.transform("", { @@ -184,7 +184,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo scoped plugins with an existing prefix", function() { + it("should find @foo scoped plugins with an existing prefix", function () { process.chdir("foo-org-paths"); babel.transform("", { @@ -194,7 +194,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo/babel-plugin when specified", function() { + it("should find @foo/babel-plugin when specified", function () { process.chdir("foo-org-paths"); babel.transform("", { @@ -204,7 +204,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo/babel-preset when specified", function() { + it("should find @foo/babel-preset when specified", function () { process.chdir("foo-org-paths"); babel.transform("", { @@ -214,7 +214,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo/babel-plugin/index when specified", function() { + it("should find @foo/babel-plugin/index when specified", function () { process.chdir("foo-org-paths"); babel.transform("", { @@ -224,7 +224,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo/babel-preset/index when specified", function() { + it("should find @foo/babel-preset/index when specified", function () { process.chdir("foo-org-paths"); babel.transform("", { @@ -234,7 +234,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo/babel-plugin when just scope given", function() { + it("should find @foo/babel-plugin when just scope given", function () { process.chdir("foo-org-paths"); babel.transform("", { @@ -244,7 +244,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo/babel-preset when just scope given", function() { + it("should find @foo/babel-preset when just scope given", function () { process.chdir("foo-org-paths"); babel.transform("", { @@ -254,7 +254,7 @@ describe("addon resolution", function() { }); }); - it("should find relative path presets", function() { + it("should find relative path presets", function () { process.chdir("relative-paths"); babel.transform("", { @@ -264,7 +264,7 @@ describe("addon resolution", function() { }); }); - it("should find relative path plugins", function() { + it("should find relative path plugins", function () { process.chdir("relative-paths"); babel.transform("", { @@ -274,7 +274,7 @@ describe("addon resolution", function() { }); }); - it("should find module file presets", function() { + it("should find module file presets", function () { process.chdir("nested-module-paths"); babel.transform("", { @@ -284,7 +284,7 @@ describe("addon resolution", function() { }); }); - it("should find module file plugins", function() { + it("should find module file plugins", function () { process.chdir("nested-module-paths"); babel.transform("", { @@ -294,7 +294,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo scoped module file presets", function() { + it("should find @foo scoped module file presets", function () { process.chdir("scoped-nested-module-paths"); babel.transform("", { @@ -304,7 +304,7 @@ describe("addon resolution", function() { }); }); - it("should find @foo scoped module file plugins", function() { + it("should find @foo scoped module file plugins", function () { process.chdir("scoped-nested-module-paths"); babel.transform("", { @@ -314,7 +314,7 @@ describe("addon resolution", function() { }); }); - it("should find @babel scoped module file presets", function() { + it("should find @babel scoped module file presets", function () { process.chdir("babel-scoped-nested-module-paths"); babel.transform("", { @@ -324,7 +324,7 @@ describe("addon resolution", function() { }); }); - it("should find @babel scoped module file plugins", function() { + it("should find @babel scoped module file plugins", function () { process.chdir("babel-scoped-nested-module-paths"); babel.transform("", { @@ -334,7 +334,7 @@ describe("addon resolution", function() { }); }); - it("should throw about module: usage for presets", function() { + it("should throw about module: usage for presets", function () { process.chdir("throw-module-paths"); expect(() => { @@ -348,7 +348,7 @@ describe("addon resolution", function() { ); }); - it("should throw about module: usage for plugins", function() { + it("should throw about module: usage for plugins", function () { process.chdir("throw-module-paths"); expect(() => { @@ -362,7 +362,7 @@ describe("addon resolution", function() { ); }); - it("should throw about @babel usage for presets", function() { + it("should throw about @babel usage for presets", function () { process.chdir("throw-babel-paths"); expect(() => { @@ -376,7 +376,7 @@ describe("addon resolution", function() { ); }); - it("should throw about @babel usage for plugins", function() { + it("should throw about @babel usage for plugins", function () { process.chdir("throw-babel-paths"); expect(() => { @@ -390,7 +390,7 @@ describe("addon resolution", function() { ); }); - it("should throw about passing a preset as a plugin", function() { + it("should throw about passing a preset as a plugin", function () { process.chdir("throw-opposite-paths"); expect(() => { @@ -404,7 +404,7 @@ describe("addon resolution", function() { ); }); - it("should throw about passing a plugin as a preset", function() { + it("should throw about passing a plugin as a preset", function () { process.chdir("throw-opposite-paths"); expect(() => { @@ -418,7 +418,7 @@ describe("addon resolution", function() { ); }); - it("should throw about missing presets", function() { + it("should throw about missing presets", function () { process.chdir("throw-missing-paths"); expect(() => { @@ -430,7 +430,7 @@ describe("addon resolution", function() { }).toThrow(/Cannot find module 'babel-preset-foo'/); }); - it("should throw about missing plugins", function() { + it("should throw about missing plugins", function () { process.chdir("throw-missing-paths"); expect(() => { diff --git a/packages/babel-generator/src/generators/expressions.js b/packages/babel-generator/src/generators/expressions.js index 62c3aca83b..902789ffa5 100644 --- a/packages/babel-generator/src/generators/expressions.js +++ b/packages/babel-generator/src/generators/expressions.js @@ -154,7 +154,7 @@ export function Import() { } function buildYieldAwait(keyword: string) { - return function(node: Object) { + return function (node: Object) { this.word(keyword); if (node.delegate) { diff --git a/packages/babel-generator/src/generators/statements.js b/packages/babel-generator/src/generators/statements.js index e410092a9e..24f9a2dbe5 100644 --- a/packages/babel-generator/src/generators/statements.js +++ b/packages/babel-generator/src/generators/statements.js @@ -81,8 +81,8 @@ export function WhileStatement(node: Object) { this.printBlock(node); } -const buildForXStatement = function(op) { - return function(node: Object) { +const buildForXStatement = function (op) { + return function (node: Object) { this.word("for"); this.space(); if (op === "of" && node.await) { @@ -117,7 +117,7 @@ export function DoWhileStatement(node: Object) { } function buildLabelStatement(prefix, key = "label") { - return function(node: Object) { + return function (node: Object) { this.word(prefix); const label = node[key]; diff --git a/packages/babel-generator/src/index.js b/packages/babel-generator/src/index.js index 1f56bc2854..176efa0255 100644 --- a/packages/babel-generator/src/index.js +++ b/packages/babel-generator/src/index.js @@ -108,7 +108,7 @@ export class CodeGenerator { } } -export default function(ast: Object, opts: Object, code: string): Object { +export default function (ast: Object, opts: Object, code: string): Object { const gen = new Generator(ast, opts, code); return gen.generate(); } diff --git a/packages/babel-generator/src/node/index.js b/packages/babel-generator/src/node/index.js index 43bddb3e19..c91910f75f 100644 --- a/packages/babel-generator/src/node/index.js +++ b/packages/babel-generator/src/node/index.js @@ -8,7 +8,7 @@ function expandAliases(obj) { function add(type, func) { const fn = newObj[type]; newObj[type] = fn - ? function(node, parent, stack) { + ? function (node, parent, stack) { const result = fn(node, parent, stack); return result == null ? func(node, parent, stack) : result; diff --git a/packages/babel-generator/src/node/whitespace.js b/packages/babel-generator/src/node/whitespace.js index e483749fcd..67194e5b7b 100644 --- a/packages/babel-generator/src/node/whitespace.js +++ b/packages/babel-generator/src/node/whitespace.js @@ -181,7 +181,7 @@ export const nodes = { * Test if Property needs whitespace. */ -nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function( +nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function ( node: Object, parent, ): ?WhitespaceObject { @@ -192,7 +192,7 @@ nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function( } }; -nodes.ObjectTypeCallProperty = function( +nodes.ObjectTypeCallProperty = function ( node: Object, parent, ): ?WhitespaceObject { @@ -203,7 +203,7 @@ nodes.ObjectTypeCallProperty = function( } }; -nodes.ObjectTypeIndexer = function(node: Object, parent): ?WhitespaceObject { +nodes.ObjectTypeIndexer = function (node: Object, parent): ?WhitespaceObject { if ( parent.indexers[0] === node && !parent.properties?.length && @@ -215,7 +215,7 @@ nodes.ObjectTypeIndexer = function(node: Object, parent): ?WhitespaceObject { } }; -nodes.ObjectTypeInternalSlot = function( +nodes.ObjectTypeInternalSlot = function ( node: Object, parent, ): ?WhitespaceObject { @@ -272,12 +272,12 @@ export const list = { ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true], -].forEach(function([type, amounts]) { +].forEach(function ([type, amounts]) { if (typeof amounts === "boolean") { amounts = { after: amounts, before: amounts }; } - [type].concat(t.FLIPPED_ALIAS_KEYS[type] || []).forEach(function(type) { - nodes[type] = function() { + [type].concat(t.FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) { + nodes[type] = function () { return amounts; }; }); diff --git a/packages/babel-generator/test/index.js b/packages/babel-generator/test/index.js index bde9800295..54ff79c919 100644 --- a/packages/babel-generator/test/index.js +++ b/packages/babel-generator/test/index.js @@ -6,24 +6,24 @@ import fs from "fs"; import path from "path"; import fixtures from "@babel/helper-fixtures"; -describe("generation", function() { - it("completeness", function() { - Object.keys(t.VISITOR_KEYS).forEach(function(type) { +describe("generation", function () { + it("completeness", function () { + Object.keys(t.VISITOR_KEYS).forEach(function (type) { expect(Printer.prototype[type]).toBeTruthy(); }); - Object.keys(Printer.prototype).forEach(function(type) { + Object.keys(Printer.prototype).forEach(function (type) { if (!/[A-Z]/.test(type[0])) return; expect(t.VISITOR_KEYS[type]).toBeTruthy(); }); }); - it("multiple sources", function() { + it("multiple sources", function () { const sources = { "a.js": "function hi (msg) { console.log(msg); }\n", "b.js": "hi('hello');\n", }; - const parsed = Object.keys(sources).reduce(function(_parsed, filename) { + const parsed = Object.keys(sources).reduce(function (_parsed, filename) { _parsed[filename] = parse(sources[filename], { sourceFilename: filename, }); @@ -185,7 +185,7 @@ describe("generation", function() { ); }); - it("identifierName", function() { + it("identifierName", function () { const code = "function foo() { bar; }\n"; const ast = parse(code, { filename: "inline" }).program; @@ -277,7 +277,7 @@ describe("generation", function() { expect(generated.code).toBe("function foo2() {\n bar2;\n}"); }); - it("lazy source map generation", function() { + it("lazy source map generation", function () { const code = "function hi (msg) { console.log(msg); }\n"; const ast = parse(code, { filename: "a.js" }).program; @@ -306,8 +306,8 @@ describe("generation", function() { }); }); -describe("programmatic generation", function() { - it("should add parenthesis when NullishCoalescing is used along with ||", function() { +describe("programmatic generation", function () { + it("should add parenthesis when NullishCoalescing is used along with ||", function () { // https://github.com/babel/babel/issues/10260 const nullishCoalesc = t.logicalExpression( "??", @@ -318,7 +318,7 @@ describe("programmatic generation", function() { expect(output).toBe(`(a || b) ?? c`); }); - it("should add parenthesis when NullishCoalesing is used with &&", function() { + it("should add parenthesis when NullishCoalesing is used with &&", function () { const nullishCoalesc = t.logicalExpression( "??", t.identifier("a"), @@ -332,7 +332,7 @@ describe("programmatic generation", function() { expect(output).toBe(`a ?? (b && c && d)`); }); - it("numeric member expression", function() { + it("numeric member expression", function () { // Should not generate `0.foo` const mem = t.memberExpression( t.numericLiteral(60702), @@ -341,7 +341,7 @@ describe("programmatic generation", function() { new Function(generate(mem).code); }); - it("nested if statements needs block", function() { + it("nested if statements needs block", function () { const ifStatement = t.ifStatement( t.stringLiteral("top cond"), t.whileStatement( @@ -358,7 +358,7 @@ describe("programmatic generation", function() { expect(ast.program.body[0].consequent.type).toBe("BlockStatement"); }); - it("prints directives in block with empty body", function() { + it("prints directives in block with empty body", function () { const blockStatement = t.blockStatement( [], [t.directive(t.directiveLiteral("use strict"))], @@ -370,7 +370,7 @@ describe("programmatic generation", function() { }`); }); - it("flow object indentation", function() { + it("flow object indentation", function () { const objectStatement = t.objectTypeAnnotation( [t.objectTypeProperty(t.identifier("bar"), t.stringTypeAnnotation())], null, @@ -384,7 +384,7 @@ describe("programmatic generation", function() { }`); }); - it("flow object exact", function() { + it("flow object exact", function () { const objectStatement = t.objectTypeAnnotation( [t.objectTypeProperty(t.identifier("bar"), t.stringTypeAnnotation())], null, @@ -399,7 +399,7 @@ describe("programmatic generation", function() { |}`); }); - it("flow object indentation with empty leading ObjectTypeProperty", function() { + it("flow object indentation with empty leading ObjectTypeProperty", function () { const objectStatement = t.objectTypeAnnotation( [], [ @@ -419,8 +419,8 @@ describe("programmatic generation", function() { }`); }); - describe("directives", function() { - it("preserves escapes", function() { + describe("directives", function () { + it("preserves escapes", function () { const directive = t.directive( t.directiveLiteral(String.raw`us\x65 strict`), ); @@ -429,7 +429,7 @@ describe("programmatic generation", function() { expect(output).toBe(String.raw`"us\x65 strict";`); }); - it("preserves escapes in minified output", function() { + it("preserves escapes in minified output", function () { // https://github.com/babel/babel/issues/4767 const directive = t.directive(t.directiveLiteral(String.raw`foo\n\t\r`)); @@ -438,21 +438,21 @@ describe("programmatic generation", function() { expect(output).toBe(String.raw`"foo\n\t\r";`); }); - it("unescaped single quote", function() { + it("unescaped single quote", function () { const directive = t.directive(t.directiveLiteral(String.raw`'\'\"`)); const output = generate(directive).code; expect(output).toBe(String.raw`"'\'\"";`); }); - it("unescaped double quote", function() { + it("unescaped double quote", function () { const directive = t.directive(t.directiveLiteral(String.raw`"\'\"`)); const output = generate(directive).code; expect(output).toBe(String.raw`'"\'\"';`); }); - it("unescaped single and double quotes together throw", function() { + it("unescaped single and double quotes together throw", function () { const directive = t.directive(t.directiveLiteral(String.raw`'"`)); expect(() => { @@ -461,7 +461,7 @@ describe("programmatic generation", function() { }); }); - describe("typescript generate parentheses if necessary", function() { + describe("typescript generate parentheses if necessary", function () { it("wraps around union for array", () => { const typeStatement = t.TSArrayType( t.TSUnionType([ @@ -496,8 +496,8 @@ describe("programmatic generation", function() { }); }); -describe("CodeGenerator", function() { - it("generate", function() { +describe("CodeGenerator", function () { + it("generate", function () { const codeGen = new CodeGenerator(t.numericLiteral(123)); const code = codeGen.generate().code; expect(parse(code).program.body[0].expression.value).toBe(123); @@ -506,15 +506,15 @@ describe("CodeGenerator", function() { const suites = fixtures(`${__dirname}/fixtures`); -suites.forEach(function(testSuite) { - describe("generation/" + testSuite.title, function() { - testSuite.tests.forEach(function(task) { +suites.forEach(function (testSuite) { + describe("generation/" + testSuite.title, function () { + testSuite.tests.forEach(function (task) { const testFn = task.disabled ? it.skip : it; testFn( task.title, - function() { + function () { const expected = task.expect; const actual = task.actual; const actualCode = actual.code; diff --git a/packages/babel-helper-builder-binary-assignment-operator-visitor/src/index.js b/packages/babel-helper-builder-binary-assignment-operator-visitor/src/index.js index 554f71a1c5..6764d6871d 100644 --- a/packages/babel-helper-builder-binary-assignment-operator-visitor/src/index.js +++ b/packages/babel-helper-builder-binary-assignment-operator-visitor/src/index.js @@ -1,7 +1,7 @@ import explode from "@babel/helper-explode-assignable-expression"; import * as t from "@babel/types"; -export default function(opts: { build: Function, operator: string }): Object { +export default function (opts: { build: Function, operator: string }): Object { const { build, operator } = opts; return { diff --git a/packages/babel-helper-builder-react-jsx/src/index.js b/packages/babel-helper-builder-react-jsx/src/index.js index f90014fe95..f0bce14c76 100644 --- a/packages/babel-helper-builder-react-jsx/src/index.js +++ b/packages/babel-helper-builder-react-jsx/src/index.js @@ -9,10 +9,10 @@ type ElementState = { pure: boolean, // true if the element can be marked with a #__PURE__ annotation }; -export default function(opts) { +export default function (opts) { const visitor = {}; - visitor.JSXNamespacedName = function(path) { + visitor.JSXNamespacedName = function (path) { if (opts.throwIfNamespace) { throw path.buildCodeFrameError( `Namespace tags are not supported by default. React's JSX doesn't support namespace tags. \ @@ -21,7 +21,7 @@ You can set \`throwIfNamespace: false\` to bypass this warning.`, } }; - visitor.JSXSpreadChild = function(path) { + visitor.JSXSpreadChild = function (path) { throw path.buildCodeFrameError( "Spread children are not supported in React.", ); diff --git a/packages/babel-helper-call-delegate/src/index.js b/packages/babel-helper-call-delegate/src/index.js index 7843584620..a71161d50b 100644 --- a/packages/babel-helper-call-delegate/src/index.js +++ b/packages/babel-helper-call-delegate/src/index.js @@ -18,7 +18,7 @@ const visitor = { }, }; -export default function( +export default function ( path: NodePath, scope = path.scope, shouldHoistVariables = true, diff --git a/packages/babel-helper-define-map/src/index.js b/packages/babel-helper-define-map/src/index.js index da81b3a43b..ce8322f6ec 100644 --- a/packages/babel-helper-define-map/src/index.js +++ b/packages/babel-helper-define-map/src/index.js @@ -124,13 +124,13 @@ export function toComputedObjectFromClass(obj: Object): Object { export function toClassObject(mutatorMap: Object): Object { const objExpr = t.objectExpression([]); - Object.keys(mutatorMap).forEach(function(mutatorMapKey) { + Object.keys(mutatorMap).forEach(function (mutatorMapKey) { const map = mutatorMap[mutatorMapKey]; const mapNode = t.objectExpression([]); const propNode = t.objectProperty(map._key, mapNode, map._computed); - Object.keys(map).forEach(function(key) { + Object.keys(map).forEach(function (key) { const node = map[key]; if (key[0] === "_") return; @@ -148,7 +148,7 @@ export function toClassObject(mutatorMap: Object): Object { } export function toDefineObject(mutatorMap: Object): Object { - Object.keys(mutatorMap).forEach(function(key) { + Object.keys(mutatorMap).forEach(function (key) { const map = mutatorMap[key]; if (map.value) map.writable = t.booleanLiteral(true); map.configurable = t.booleanLiteral(true); diff --git a/packages/babel-helper-explode-assignable-expression/src/index.js b/packages/babel-helper-explode-assignable-expression/src/index.js index d569c90ff6..fc24253ba2 100644 --- a/packages/babel-helper-explode-assignable-expression/src/index.js +++ b/packages/babel-helper-explode-assignable-expression/src/index.js @@ -48,7 +48,7 @@ function getPropRef(node, nodes, file, scope) { return temp; } -export default function( +export default function ( node: Object, nodes: Array, file, diff --git a/packages/babel-helper-explode-class/src/index.js b/packages/babel-helper-explode-class/src/index.js index 1c5881b37e..e9a701186f 100644 --- a/packages/babel-helper-explode-class/src/index.js +++ b/packages/babel-helper-explode-class/src/index.js @@ -2,7 +2,7 @@ import bindifyDecorators from "@babel/helper-bindify-decorators"; import type { NodePath } from "@babel/traverse"; import * as t from "@babel/types"; -export default function(classPath) { +export default function (classPath) { classPath.assertClass(); const memoisedExpressions = []; diff --git a/packages/babel-helper-function-name/src/index.js b/packages/babel-helper-function-name/src/index.js index b736d76f57..c89157c6fd 100644 --- a/packages/babel-helper-function-name/src/index.js +++ b/packages/babel-helper-function-name/src/index.js @@ -150,7 +150,7 @@ function visit(node, name, scope) { * @param {NodePath} param0 * @param {Boolean} localBinding whether a name could shadow a self-reference (e.g. converting arrow function) */ -export default function({ node, parent, scope, id }, localBinding = false) { +export default function ({ node, parent, scope, id }, localBinding = false) { // has an `id` so we don't need to infer one if (node.id) return; diff --git a/packages/babel-helper-get-function-arity/src/index.js b/packages/babel-helper-get-function-arity/src/index.js index 60b5f3ed17..6b00da3c35 100644 --- a/packages/babel-helper-get-function-arity/src/index.js +++ b/packages/babel-helper-get-function-arity/src/index.js @@ -1,6 +1,6 @@ import * as t from "@babel/types"; -export default function(node): number { +export default function (node): number { const params: Array = node.params; for (let i = 0; i < params.length; i++) { const param = params[i]; diff --git a/packages/babel-helper-hoist-variables/src/index.js b/packages/babel-helper-hoist-variables/src/index.js index 6b8bb4cf3b..f69cac4f6e 100644 --- a/packages/babel-helper-hoist-variables/src/index.js +++ b/packages/babel-helper-hoist-variables/src/index.js @@ -42,6 +42,6 @@ const visitor = { }, }; -export default function(path, emit: Function, kind: "var" | "let" = "var") { +export default function (path, emit: Function, kind: "var" | "let" = "var") { path.traverse(visitor, { kind, emit }); } diff --git a/packages/babel-helper-module-imports/src/import-injector.js b/packages/babel-helper-module-imports/src/import-injector.js index 59375b6c9c..1264dd4bc7 100644 --- a/packages/babel-helper-module-imports/src/import-injector.js +++ b/packages/babel-helper-module-imports/src/import-injector.js @@ -294,10 +294,7 @@ export default class ImportInjector { builder.var(importedSource).read(importName); } } else if (isDefault) { - builder - .var(name) - .defaultInterop() - .prop(importName); + builder.var(name).defaultInterop().prop(importName); } else if (isNamed) { builder.var(name).prop(importName); } diff --git a/packages/babel-helper-module-imports/test/index.js b/packages/babel-helper-module-imports/test/index.js index 9320fe5c6f..ada1a24cfd 100644 --- a/packages/babel-helper-module-imports/test/index.js +++ b/packages/babel-helper-module-imports/test/index.js @@ -15,7 +15,7 @@ function test(sourceType, opts, initializer, expectedCode) { filename: "example" + (sourceType === "module" ? ".mjs" : ".js"), babelrc: false, plugins: [ - function({ types: t }) { + function ({ types: t }) { return { pre(file) { file.set("helperGenerator", name => diff --git a/packages/babel-helper-optimise-call-expression/src/index.js b/packages/babel-helper-optimise-call-expression/src/index.js index 2dcfd29ec8..e6f889442e 100644 --- a/packages/babel-helper-optimise-call-expression/src/index.js +++ b/packages/babel-helper-optimise-call-expression/src/index.js @@ -1,6 +1,6 @@ import * as t from "@babel/types"; -export default function(callee, thisNode, args, optional) { +export default function (callee, thisNode, args, optional) { if ( args.length === 1 && t.isSpreadElement(args[0]) && diff --git a/packages/babel-helper-plugin-test-runner/src/index.js b/packages/babel-helper-plugin-test-runner/src/index.js index cacf680a9a..b7cd1cef6a 100644 --- a/packages/babel-helper-plugin-test-runner/src/index.js +++ b/packages/babel-helper-plugin-test-runner/src/index.js @@ -1,7 +1,7 @@ import testRunner from "@babel/helper-transform-fixture-test-runner"; import path from "path"; -export default function(loc) { +export default function (loc) { const name = path.basename(path.dirname(loc)); testRunner(loc + "/fixtures", name); } diff --git a/packages/babel-helper-remap-async-to-generator/src/index.js b/packages/babel-helper-remap-async-to-generator/src/index.js index 635b0876c2..ac96c93112 100644 --- a/packages/babel-helper-remap-async-to-generator/src/index.js +++ b/packages/babel-helper-remap-async-to-generator/src/index.js @@ -28,7 +28,7 @@ const awaitVisitor = { }, }; -export default function( +export default function ( path: NodePath, helpers: { wrapAsync: Object, wrapAwait: Object }, ) { diff --git a/packages/babel-helper-transform-fixture-test-runner/src/index.js b/packages/babel-helper-transform-fixture-test-runner/src/index.js index 416d03c544..568e183760 100644 --- a/packages/babel-helper-transform-fixture-test-runner/src/index.js +++ b/packages/babel-helper-transform-fixture-test-runner/src/index.js @@ -107,7 +107,7 @@ export function runCodeInTestContext(code: string, opts: { filename: string }) { } function wrapPackagesArray(type, names, optionsDir) { - return (names || []).map(function(val) { + return (names || []).map(function (val) { if (typeof val === "string") val = [val]; // relative path (outside of monorepo) @@ -164,7 +164,7 @@ function run(task) { "preset", newOpts.presets, optionsDir, - ).map(function(val) { + ).map(function (val) { if (val.length > 3) { throw new Error( "Unexpected extra options " + @@ -269,7 +269,7 @@ function run(task) { if (task.sourceMappings) { const consumer = new sourceMap.SourceMapConsumer(result.map); - task.sourceMappings.forEach(function(mapping) { + task.sourceMappings.forEach(function (mapping) { const actual = mapping.original; const expected = consumer.originalPositionFor(mapping.generated); @@ -342,7 +342,7 @@ const toEqualFile = () => ({ }, }); -export default function( +export default function ( fixturesLoc: string, name: string, suiteOpts = {}, @@ -354,7 +354,7 @@ export default function( for (const testSuite of suites) { if (includes(suiteOpts.ignoreSuites, testSuite.title)) continue; - describe(name + "/" + testSuite.title, function() { + describe(name + "/" + testSuite.title, function () { jest.addMatchers({ toEqualFile, }); @@ -372,7 +372,7 @@ export default function( testFn( task.title, - function() { + function () { function runTask() { run(task); } @@ -391,7 +391,7 @@ export default function( // the options object with useless options delete task.options.throws; - assert.throws(runTask, function(err) { + assert.throws(runTask, function (err) { return throwMsg === true || err.message.indexOf(throwMsg) >= 0; }); } else { diff --git a/packages/babel-helper-transform-fixture-test-runner/test/index.js b/packages/babel-helper-transform-fixture-test-runner/test/index.js index 1d02bf8029..bc872cfa51 100644 --- a/packages/babel-helper-transform-fixture-test-runner/test/index.js +++ b/packages/babel-helper-transform-fixture-test-runner/test/index.js @@ -1,7 +1,7 @@ import { runCodeInTestContext } from ".."; -describe("helper-transform-fixture-test-runner", function() { - it("should not execute code in Node's global context", function() { +describe("helper-transform-fixture-test-runner", function () { + it("should not execute code in Node's global context", function () { try { global.foo = "outer"; runCodeInTestContext( diff --git a/packages/babel-helper-validator-identifier/scripts/generate-identifier-regex.js b/packages/babel-helper-validator-identifier/scripts/generate-identifier-regex.js index e0f5b1656b..70b371508b 100644 --- a/packages/babel-helper-validator-identifier/scripts/generate-identifier-regex.js +++ b/packages/babel-helper-validator-identifier/scripts/generate-identifier-regex.js @@ -6,14 +6,14 @@ const version = "13.0.0"; const start = require("unicode-" + version + - "/Binary_Property/ID_Start/code-points.js").filter(function(ch) { + "/Binary_Property/ID_Start/code-points.js").filter(function (ch) { return ch > 0x7f; }); let last = -1; const cont = [0x200c, 0x200d].concat( require("unicode-" + version + - "/Binary_Property/ID_Continue/code-points.js").filter(function(ch) { + "/Binary_Property/ID_Continue/code-points.js").filter(function (ch) { return ch > 0x7f && search(start, ch, last + 1) == -1; }) ); diff --git a/packages/babel-helper-validator-identifier/test/identifier.spec.js b/packages/babel-helper-validator-identifier/test/identifier.spec.js index 60a25cb578..e06a3ac9f1 100644 --- a/packages/babel-helper-validator-identifier/test/identifier.spec.js +++ b/packages/babel-helper-validator-identifier/test/identifier.spec.js @@ -1,22 +1,22 @@ import { isIdentifierName } from ".."; -describe("isIdentifierName", function() { - it("returns false if provided string is empty", function() { +describe("isIdentifierName", function () { + it("returns false if provided string is empty", function () { expect(isIdentifierName("")).toBe(false); }); it.each(["hello", "$", "ゆゆ式", "$20", "hello20", "_", "if"])( "returns true if provided string %p is an IdentifierName", - function(word) { + function (word) { expect(isIdentifierName(word)).toBe(true); }, ); it.each(["+hello", "0$", "-ゆゆ式", "#_", "_#"])( "returns false if provided string %p is not an IdentifierName", - function(word) { + function (word) { expect(isIdentifierName(word)).toBe(false); }, ); - it("supports astral symbols", function() { + it("supports astral symbols", function () { expect(isIdentifierName("x\uDB40\uDDD5")).toBe(true); }); }); diff --git a/packages/babel-highlight/src/index.js b/packages/babel-highlight/src/index.js index 9112f39513..64daa050b4 100644 --- a/packages/babel-highlight/src/index.js +++ b/packages/babel-highlight/src/index.js @@ -77,7 +77,7 @@ function getTokenType(match) { * Highlight `text` using the token definitions in `defs`. */ function highlightTokens(defs: Object, text: string) { - return text.replace(jsTokens, function(...args) { + return text.replace(jsTokens, function (...args) { const type = getTokenType(args); const colorize = defs[type]; if (colorize) { diff --git a/packages/babel-highlight/test/index.js b/packages/babel-highlight/test/index.js index a33f79fd50..64877c7f7f 100644 --- a/packages/babel-highlight/test/index.js +++ b/packages/babel-highlight/test/index.js @@ -2,24 +2,24 @@ import chalk from "chalk"; import stripAnsi from "strip-ansi"; import highlight, { shouldHighlight, getChalk } from ".."; -describe("@babel/highlight", function() { +describe("@babel/highlight", function () { function stubColorSupport(supported) { let originalSupportsColor; - beforeEach(function() { + beforeEach(function () { originalSupportsColor = chalk.supportsColor; chalk.supportsColor = supported; }); - afterEach(function() { + afterEach(function () { chalk.supportsColor = originalSupportsColor; }); } - describe("highlight", function() { - describe("when colors are supported", function() { + describe("highlight", function () { + describe("when colors are supported", function () { stubColorSupport(true); - it("highlights code", function() { + it("highlights code", function () { const code = "console.log('hi')"; const result = highlight(code); const stripped = stripAnsi(result); @@ -28,10 +28,10 @@ describe("@babel/highlight", function() { }); }); - describe("when colors are not supported", function() { + describe("when colors are not supported", function () { stubColorSupport(false); - it("does not attempt to highlight code", function() { + it("does not attempt to highlight code", function () { const code = "console.log('hi')"; const result = highlight(code); const stripped = stripAnsi(result); @@ -39,8 +39,8 @@ describe("@babel/highlight", function() { expect(result).toBe(code); }); - describe("and the forceColor option is passed", function() { - it("highlights the code anyway", function() { + describe("and the forceColor option is passed", function () { + it("highlights the code anyway", function () { const code = "console.log('hi')"; const result = highlight(code, { forceColor: true }); const stripped = stripAnsi(result); @@ -51,42 +51,42 @@ describe("@babel/highlight", function() { }); }); - describe("shouldHighlight", function() { - describe("when colors are supported", function() { + describe("shouldHighlight", function () { + describe("when colors are supported", function () { stubColorSupport(true); - it("returns true", function() { + it("returns true", function () { expect(shouldHighlight({})).toBeTruthy(); }); }); - describe("when colors are not supported", function() { + describe("when colors are not supported", function () { stubColorSupport(false); - it("returns false", function() { + it("returns false", function () { expect(shouldHighlight({})).toBeFalsy(); }); - describe("and the forceColor option is passed", function() { - it("returns true", function() { + describe("and the forceColor option is passed", function () { + it("returns true", function () { expect(shouldHighlight({ forceColor: true })).toBeTruthy(); }); }); }); }); - describe("getChalk", function() { - describe("when colors are supported", function() { + describe("getChalk", function () { + describe("when colors are supported", function () { stubColorSupport(true); - describe("when forceColor is not passed", function() { - it("returns a Chalk instance", function() { + describe("when forceColor is not passed", function () { + it("returns a Chalk instance", function () { expect(getChalk({}).constructor).toBe(chalk.constructor); }); }); - describe("when forceColor is passed", function() { - it("returns a Chalk instance", function() { + describe("when forceColor is passed", function () { + it("returns a Chalk instance", function () { expect(getChalk({ forceColor: true }).constructor).toBe( chalk.constructor, ); @@ -94,17 +94,17 @@ describe("@babel/highlight", function() { }); }); - describe("when colors are not supported", function() { + describe("when colors are not supported", function () { stubColorSupport(false); - describe("when forceColor is not passed", function() { - it("returns a Chalk instance", function() { + describe("when forceColor is not passed", function () { + it("returns a Chalk instance", function () { expect(getChalk({}).constructor).toBe(chalk.constructor); }); }); - describe("when forceColor is passed", function() { - it("returns a Chalk instance", function() { + describe("when forceColor is passed", function () { + it("returns a Chalk instance", function () { expect(getChalk({ forceColor: true }).constructor).toBe( chalk.constructor, ); diff --git a/packages/babel-node/src/_babel-node.js b/packages/babel-node/src/_babel-node.js index 22b8e00b77..e2b61c9af0 100644 --- a/packages/babel-node/src/_babel-node.js +++ b/packages/babel-node/src/_babel-node.js @@ -120,7 +120,7 @@ const replPlugin = ({ types: t }) => ({ }, }); -const _eval = function(code, filename) { +const _eval = function (code, filename) { code = code.trim(); if (!code) return undefined; @@ -162,7 +162,7 @@ if (program.eval || program.print) { let i = 0; let ignoreNext = false; - args.some(function(arg, i2) { + args.some(function (arg, i2) { if (ignoreNext) { ignoreNext = false; return; diff --git a/packages/babel-node/src/babel-node.js b/packages/babel-node/src/babel-node.js index 7a3bad135f..6d0866251b 100755 --- a/packages/babel-node/src/babel-node.js +++ b/packages/babel-node/src/babel-node.js @@ -45,7 +45,7 @@ const aliases = new Map([ ["-gc", "--expose-gc"], ]); -getV8Flags(function(err, v8Flags) { +getV8Flags(function (err, v8Flags) { for (let i = 0; i < babelArgs.length; i++) { const arg = babelArgs[i]; const flag = arg.split("=")[0]; @@ -87,8 +87,8 @@ getV8Flags(function(err, v8Flags) { const proc = child_process.spawn(process.argv[0], args, { stdio: "inherit", }); - proc.on("exit", function(code, signal) { - process.on("exit", function() { + proc.on("exit", function (code, signal) { + process.on("exit", function () { if (signal) { process.kill(process.pid, signal); } else { diff --git a/packages/babel-node/test/index.js b/packages/babel-node/test/index.js index 3ac90c7123..ca4571dfb0 100644 --- a/packages/babel-node/test/index.js +++ b/packages/babel-node/test/index.js @@ -11,36 +11,36 @@ const fs = require("fs"); const fixtureLoc = path.join(__dirname, "fixtures"); const tmpLoc = path.join(__dirname, "tmp"); -const fileFilter = function(x) { +const fileFilter = function (x) { return x !== ".DS_Store"; }; -const outputFileSync = function(filePath, data) { +const outputFileSync = function (filePath, data) { makeDirSync(path.dirname(filePath)); fs.writeFileSync(filePath, data); }; -const readDir = function(loc, filter) { +const readDir = function (loc, filter) { const files = {}; if (fs.existsSync(loc)) { - readdir(loc, filter).forEach(function(filename) { + readdir(loc, filter).forEach(function (filename) { files[filename] = helper.readFile(path.join(loc, filename)); }); } return files; }; -const saveInFiles = function(files) { +const saveInFiles = function (files) { // Place an empty .babelrc in each test so tests won't unexpectedly get to repo-level config. outputFileSync(".babelrc", "{}"); - Object.keys(files).forEach(function(filename) { + Object.keys(files).forEach(function (filename) { const content = files[filename]; outputFileSync(filename, content); }); }; -const assertTest = function(stdout, stderr, opts) { +const assertTest = function (stdout, stderr, opts) { const expectStderr = opts.stderr.trim(); stderr = stderr.trim(); @@ -71,7 +71,7 @@ const assertTest = function(stdout, stderr, opts) { if (opts.outFiles) { const actualFiles = readDir(path.join(tmpLoc)); - Object.keys(actualFiles).forEach(function(filename) { + Object.keys(actualFiles).forEach(function (filename) { if (!Object.prototype.hasOwnProperty.call(opts.inFiles, filename)) { const expected = opts.outFiles[filename]; const actual = actualFiles[filename]; @@ -84,16 +84,16 @@ const assertTest = function(stdout, stderr, opts) { } }); - Object.keys(opts.outFiles).forEach(function(filename) { + Object.keys(opts.outFiles).forEach(function (filename) { expect(actualFiles).toHaveProperty(filename); }); } }; -const buildTest = function(binName, testName, opts) { +const buildTest = function (binName, testName, opts) { const binLoc = path.join(__dirname, "../lib", binName); - return function(callback) { + return function (callback) { saveInFiles(opts.inFiles); let args = [binLoc]; args.push("--config-file", "../config.json"); @@ -104,15 +104,15 @@ const buildTest = function(binName, testName, opts) { let stderr = ""; let stdout = ""; - spawn.stderr.on("data", function(chunk) { + spawn.stderr.on("data", function (chunk) { stderr += chunk; }); - spawn.stdout.on("data", function(chunk) { + spawn.stdout.on("data", function (chunk) { stdout += chunk; }); - spawn.on("close", function() { + spawn.on("close", function () { let err; try { @@ -136,11 +136,11 @@ const buildTest = function(binName, testName, opts) { }; }; -fs.readdirSync(fixtureLoc).forEach(function(binName) { +fs.readdirSync(fixtureLoc).forEach(function (binName) { if (binName[0] === ".") return; const suiteLoc = path.join(fixtureLoc, binName); - describe("bin/" + binName, function() { + describe("bin/" + binName, function () { let cwd; beforeEach(() => { @@ -161,7 +161,7 @@ fs.readdirSync(fixtureLoc).forEach(function(binName) { process.chdir(cwd); }); - fs.readdirSync(suiteLoc).forEach(function(testName) { + fs.readdirSync(suiteLoc).forEach(function (testName) { if (testName[0] === ".") return; const testLoc = path.join(suiteLoc, testName); @@ -173,7 +173,7 @@ fs.readdirSync(fixtureLoc).forEach(function(binName) { const optionsLoc = path.join(testLoc, "options.json"); if (fs.existsSync(optionsLoc)) merge(opts, require(optionsLoc)); - ["stdout", "stdin", "stderr"].forEach(function(key) { + ["stdout", "stdin", "stderr"].forEach(function (key) { const loc = path.join(testLoc, key + ".txt"); if (fs.existsSync(loc)) { opts[key] = helper.readFile(loc); diff --git a/packages/babel-parser/src/plugins/jsx/index.js b/packages/babel-parser/src/plugins/jsx/index.js index 46051e250f..ba91d78aea 100644 --- a/packages/babel-parser/src/plugins/jsx/index.js +++ b/packages/babel-parser/src/plugins/jsx/index.js @@ -39,13 +39,13 @@ tt.jsxText = new TokenType("jsxText", { beforeExpr: true }); tt.jsxTagStart = new TokenType("jsxTagStart", { startsExpr: true }); tt.jsxTagEnd = new TokenType("jsxTagEnd"); -tt.jsxTagStart.updateContext = function() { +tt.jsxTagStart.updateContext = function () { this.state.context.push(tc.j_expr); // treat as beginning of JSX expression this.state.context.push(tc.j_oTag); // start opening tag context this.state.exprAllowed = false; }; -tt.jsxTagEnd.updateContext = function(prevType) { +tt.jsxTagEnd.updateContext = function (prevType) { const out = this.state.context.pop(); if ((out === tc.j_oTag && prevType === tt.slash) || out === tc.j_cTag) { this.state.context.pop(); diff --git a/packages/babel-parser/src/tokenizer/context.js b/packages/babel-parser/src/tokenizer/context.js index 9f973085a1..101ac72596 100644 --- a/packages/babel-parser/src/tokenizer/context.js +++ b/packages/babel-parser/src/tokenizer/context.js @@ -41,7 +41,7 @@ export const types: { // Token-specific context update code -tt.parenR.updateContext = tt.braceR.updateContext = function() { +tt.parenR.updateContext = tt.braceR.updateContext = function () { if (this.state.context.length === 1) { this.state.exprAllowed = true; return; @@ -55,7 +55,7 @@ tt.parenR.updateContext = tt.braceR.updateContext = function() { this.state.exprAllowed = !out.isExpr; }; -tt.name.updateContext = function(prevType) { +tt.name.updateContext = function (prevType) { let allowed = false; if (prevType !== tt.dot) { if ( @@ -75,19 +75,19 @@ tt.name.updateContext = function(prevType) { } }; -tt.braceL.updateContext = function(prevType) { +tt.braceL.updateContext = function (prevType) { this.state.context.push( this.braceIsBlock(prevType) ? types.braceStatement : types.braceExpression, ); this.state.exprAllowed = true; }; -tt.dollarBraceL.updateContext = function() { +tt.dollarBraceL.updateContext = function () { this.state.context.push(types.templateQuasi); this.state.exprAllowed = true; }; -tt.parenL.updateContext = function(prevType) { +tt.parenL.updateContext = function (prevType) { const statementParens = prevType === tt._if || prevType === tt._for || @@ -99,11 +99,11 @@ tt.parenL.updateContext = function(prevType) { this.state.exprAllowed = true; }; -tt.incDec.updateContext = function() { +tt.incDec.updateContext = function () { // tokExprAllowed stays unchanged }; -tt._function.updateContext = tt._class.updateContext = function(prevType) { +tt._function.updateContext = tt._class.updateContext = function (prevType) { if (prevType === tt.dot || prevType === tt.questionDot) { // when function/class follows dot/questionDot, it is part of // (optional)MemberExpression, then we don't need to push new token context @@ -128,7 +128,7 @@ tt._function.updateContext = tt._class.updateContext = function(prevType) { this.state.exprAllowed = false; }; -tt.backQuote.updateContext = function() { +tt.backQuote.updateContext = function () { if (this.curContext() === types.template) { this.state.context.pop(); } else { @@ -137,6 +137,6 @@ tt.backQuote.updateContext = function() { this.state.exprAllowed = false; }; -tt.star.updateContext = function() { +tt.star.updateContext = function () { this.state.exprAllowed = false; }; diff --git a/packages/babel-parser/test/helpers/runFixtureTests.js b/packages/babel-parser/test/helpers/runFixtureTests.js index 9c21aa351e..4b03ee14fb 100644 --- a/packages/babel-parser/test/helpers/runFixtureTests.js +++ b/packages/babel-parser/test/helpers/runFixtureTests.js @@ -26,8 +26,9 @@ class FixtureError extends Error { { highlightCode: true }, ) + "\n" + - `at fixture (${fixturePath}:${previousError.loc.line}:${previousError - .loc.column + 1})\n`; + `at fixture (${fixturePath}:${previousError.loc.line}:${ + previousError.loc.column + 1 + })\n`; } this.stack = @@ -36,22 +37,19 @@ class FixtureError extends Error { previousError.message + "\n" + fixtureStackFrame + - previousError.stack - .split("\n") - .slice(messageLines) - .join("\n"); + previousError.stack.split("\n").slice(messageLines).join("\n"); } } export function runFixtureTests(fixturesPath, parseFunction) { const fixtures = getFixtures(fixturesPath); - Object.keys(fixtures).forEach(function(name) { - fixtures[name].forEach(function(testSuite) { - testSuite.tests.forEach(function(task) { + Object.keys(fixtures).forEach(function (name) { + fixtures[name].forEach(function (testSuite) { + testSuite.tests.forEach(function (task) { const testFn = task.disabled ? it.skip : it; - testFn(name + "/" + testSuite.title + "/" + task.title, function() { + testFn(name + "/" + testSuite.title + "/" + task.title, function () { try { runTest(task, parseFunction); } catch (err) { @@ -82,9 +80,9 @@ export function runFixtureTests(fixturesPath, parseFunction) { export function runThrowTestsWithEstree(fixturesPath, parseFunction) { const fixtures = getFixtures(fixturesPath); - Object.keys(fixtures).forEach(function(name) { - fixtures[name].forEach(function(testSuite) { - testSuite.tests.forEach(function(task) { + Object.keys(fixtures).forEach(function (name) { + fixtures[name].forEach(function (testSuite) { + testSuite.tests.forEach(function (task) { if (!task.options.throws) return; task.options.plugins = task.options.plugins || []; @@ -92,7 +90,7 @@ export function runThrowTestsWithEstree(fixturesPath, parseFunction) { const testFn = task.disabled ? it.skip : it; - testFn(name + "/" + testSuite.title + "/" + task.title, function() { + testFn(name + "/" + testSuite.title + "/" + task.title, function () { try { runTest(task, parseFunction); } catch (err) { diff --git a/packages/babel-parser/test/plugin-options.js b/packages/babel-parser/test/plugin-options.js index 44e6cb26ae..ff70783a82 100644 --- a/packages/babel-parser/test/plugin-options.js +++ b/packages/babel-parser/test/plugin-options.js @@ -4,12 +4,12 @@ function getParser(code, plugins) { return () => parse(code, { plugins, sourceType: "module" }); } -describe("plugin options", function() { - describe("the first options are used", function() { +describe("plugin options", function () { + describe("the first options are used", function () { // NOTE: This test is not specific about decorators, it can be applied // to any plugin with options. - it("when they aren't specified", function() { + it("when they aren't specified", function () { const WITHOUT_FLAG = "flow"; const WITH_FLAG = ["flow", { all: true }]; @@ -52,7 +52,7 @@ describe("plugin options", function() { ).toMatchObject(AST_WITH_FLAG); }); - it("when they are specified", function() { + it("when they are specified", function () { const NAME = "decorators"; const OPT_1 = [NAME, { decoratorsBeforeExport: true }]; const OPT_2 = [NAME, { decoratorsBeforeExport: false }]; diff --git a/packages/babel-plugin-proposal-async-generator-functions/src/for-await.js b/packages/babel-plugin-proposal-async-generator-functions/src/for-await.js index 4763b2854c..20198f1437 100644 --- a/packages/babel-plugin-proposal-async-generator-functions/src/for-await.js +++ b/packages/babel-plugin-proposal-async-generator-functions/src/for-await.js @@ -33,7 +33,7 @@ const buildForAwait = template(` } `); -export default function(path, { getAsyncIterator }) { +export default function (path, { getAsyncIterator }) { const { node, scope, parent } = path; const stepKey = scope.generateUidIdentifier("step"); diff --git a/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js b/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js index 52c5afed13..f617ee0940 100644 --- a/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js +++ b/packages/babel-plugin-proposal-decorators/src/transformer-legacy.js @@ -71,7 +71,7 @@ function applyClassDecorators(classPath) { return decorators .map(dec => dec.expression) .reverse() - .reduce(function(acc, decorator) { + .reduce(function (acc, decorator) { return buildClassDecorator({ CLASS_REF: t.cloneNode(name), DECORATOR: t.cloneNode(decorator), @@ -116,7 +116,7 @@ function applyTargetDecorators(path, state, decoratedProps) { path.isClass() ? "class" : "obj", ); - const exprs = decoratedProps.reduce(function(acc, node) { + const exprs = decoratedProps.reduce(function (acc, node) { const decorators = node.decorators || []; node.decorators = null; diff --git a/packages/babel-plugin-proposal-object-rest-spread/src/index.js b/packages/babel-plugin-proposal-object-rest-spread/src/index.js index 124a53c1e3..173dd794f6 100644 --- a/packages/babel-plugin-proposal-object-rest-spread/src/index.js +++ b/packages/babel-plugin-proposal-object-rest-spread/src/index.js @@ -234,7 +234,7 @@ export default declare((api, opts) => { // example: f({...R}, a = R) let idInRest = false; - const IdentifierHandler = function(path, functionScope) { + const IdentifierHandler = function (path, functionScope) { const name = path.node.name; if ( path.scope.getBinding(name) === functionScope.getBinding(name) && diff --git a/packages/babel-plugin-syntax-decorators/test/index.js b/packages/babel-plugin-syntax-decorators/test/index.js index bd5ff21888..e9251ee892 100644 --- a/packages/babel-plugin-syntax-decorators/test/index.js +++ b/packages/babel-plugin-syntax-decorators/test/index.js @@ -10,34 +10,34 @@ function makeParser(code, options) { }); } -describe("'legacy' option", function() { - test("must be boolean", function() { +describe("'legacy' option", function () { + test("must be boolean", function () { expect(makeParser("", { legacy: "legacy" })).toThrow(); }); - test("'legacy': false", function() { + test("'legacy': false", function () { expect(makeParser("({ @dec fn() {} })", { legacy: false })).toThrow(); }); - test("'legacy': true", function() { + test("'legacy': true", function () { expect(makeParser("({ @dec fn() {} })", { legacy: true })).not.toThrow(); }); - test("defaults to 'false'", function() { + test("defaults to 'false'", function () { expect(makeParser("({ @dec fn() {} })", {})).toThrow(); }); }); -describe("'decoratorsBeforeExport' option", function() { - test("must be boolean", function() { +describe("'decoratorsBeforeExport' option", function () { + test("must be boolean", function () { expect(makeParser("", { decoratorsBeforeExport: "before" })).toThrow(); }); - test("is required", function() { + test("is required", function () { expect(makeParser("", { legacy: false })).toThrow(/decoratorsBeforeExport/); }); - test("is incompatible with legacy", function() { + test("is incompatible with legacy", function () { expect( makeParser("", { decoratorsBeforeExport: false, legacy: true }), ).toThrow(); @@ -59,7 +59,7 @@ describe("'decoratorsBeforeExport' option", function() { (code === BEFORE ? "before" : "after") + "export"; - test(name, function() { + test(name, function () { const expectTheParser = expect( makeParser(code, { decoratorsBeforeExport: before }), ); diff --git a/packages/babel-plugin-transform-classes/src/transformClass.js b/packages/babel-plugin-transform-classes/src/transformClass.js index 57440d3f56..5b8f5f5171 100644 --- a/packages/babel-plugin-transform-classes/src/transformClass.js +++ b/packages/babel-plugin-transform-classes/src/transformClass.js @@ -320,7 +320,7 @@ export default function transformClass( path.traverse(findThisesVisitor); - let thisRef = function() { + let thisRef = function () { const ref = path.scope.generateDeclaredUidIdentifier("this"); thisRef = () => t.cloneNode(ref); return ref; @@ -360,7 +360,7 @@ export default function transformClass( wrapSuperCall(bareSuper, classState.superName, thisRef, body); if (guaranteedSuperBeforeFinish) { - bareSuper.find(function(parentPath) { + bareSuper.find(function (parentPath) { // hit top so short circuit if (parentPath === path) { return true; diff --git a/packages/babel-plugin-transform-computed-properties/src/index.js b/packages/babel-plugin-transform-computed-properties/src/index.js index 8107332542..dc34b5b5b0 100644 --- a/packages/babel-plugin-transform-computed-properties/src/index.js +++ b/packages/babel-plugin-transform-computed-properties/src/index.js @@ -159,7 +159,7 @@ export default declare((api, options) => { let mutatorRef; - const getMutatorId = function() { + const getMutatorId = function () { if (!mutatorRef) { mutatorRef = scope.generateUidIdentifier("mutatorMap"); diff --git a/packages/babel-plugin-transform-modules-commonjs/test/copied-nodes.js b/packages/babel-plugin-transform-modules-commonjs/test/copied-nodes.js index 7a392165d8..d0c3e4894e 100644 --- a/packages/babel-plugin-transform-modules-commonjs/test/copied-nodes.js +++ b/packages/babel-plugin-transform-modules-commonjs/test/copied-nodes.js @@ -1,6 +1,6 @@ const babel = require("@babel/core"); -test("Doesn't use the same object for two different nodes in the AST", function() { +test("Doesn't use the same object for two different nodes in the AST", function () { const code = 'import Foo from "bar"; Foo; Foo;'; const ast = babel.transform(code, { diff --git a/packages/babel-plugin-transform-modules-commonjs/test/esmodule-flag.js b/packages/babel-plugin-transform-modules-commonjs/test/esmodule-flag.js index 78961a8952..30d9a1f474 100644 --- a/packages/babel-plugin-transform-modules-commonjs/test/esmodule-flag.js +++ b/packages/babel-plugin-transform-modules-commonjs/test/esmodule-flag.js @@ -1,7 +1,7 @@ const babel = require("@babel/core"); const vm = require("vm"); -test("Re-export doesn't overwrite __esModule flag", function() { +test("Re-export doesn't overwrite __esModule flag", function () { let code = 'export * from "./dep";'; const depStub = { __esModule: false, @@ -11,7 +11,7 @@ test("Re-export doesn't overwrite __esModule flag", function() { module: { exports: {}, }, - require: function(id) { + require: function (id) { if (id === "./dep") return depStub; return require(id); }, diff --git a/packages/babel-plugin-transform-modules-systemjs/src/index.js b/packages/babel-plugin-transform-modules-systemjs/src/index.js index 54026e936f..0a4dfe74a7 100644 --- a/packages/babel-plugin-transform-modules-systemjs/src/index.js +++ b/packages/babel-plugin-transform-modules-systemjs/src/index.js @@ -253,7 +253,7 @@ export default declare((api, options) => { function pushModule(source, key, specifiers) { let module; - modules.forEach(function(m) { + modules.forEach(function (m) { if (m.key === source) { module = m; } @@ -424,7 +424,7 @@ export default declare((api, options) => { } } - modules.forEach(function(specifiers) { + modules.forEach(function (specifiers) { let setterBody = []; const target = path.scope.generateUid(specifiers.key); diff --git a/packages/babel-plugin-transform-named-capturing-groups-regex/src/index.js b/packages/babel-plugin-transform-named-capturing-groups-regex/src/index.js index 2cc0193310..f24a57d26e 100644 --- a/packages/babel-plugin-transform-named-capturing-groups-regex/src/index.js +++ b/packages/babel-plugin-transform-named-capturing-groups-regex/src/index.js @@ -1,7 +1,7 @@ /* eslint-disable @babel/development/plugin-name */ import { createRegExpFeaturePlugin } from "@babel/helper-create-regexp-features-plugin"; -export default function(core, options) { +export default function (core, options) { const { runtime = true } = options; if (typeof runtime !== "boolean") { throw new Error("The 'runtime' option must be boolean"); diff --git a/packages/babel-plugin-transform-object-assign/src/index.js b/packages/babel-plugin-transform-object-assign/src/index.js index a5467dfe1c..b24621a9b3 100644 --- a/packages/babel-plugin-transform-object-assign/src/index.js +++ b/packages/babel-plugin-transform-object-assign/src/index.js @@ -7,7 +7,7 @@ export default declare(api => { name: "transform-object-assign", visitor: { - CallExpression: function(path, file) { + CallExpression: function (path, file) { if (path.get("callee").matchesPattern("Object.assign")) { path.node.callee = file.addHelper("extends"); } diff --git a/packages/babel-plugin-transform-property-mutators/src/index.js b/packages/babel-plugin-transform-property-mutators/src/index.js index bb20e860fc..ee419c7e44 100644 --- a/packages/babel-plugin-transform-property-mutators/src/index.js +++ b/packages/babel-plugin-transform-property-mutators/src/index.js @@ -22,7 +22,7 @@ export default declare(api => { const mutatorMap = {}; - node.properties = node.properties.filter(function(prop) { + node.properties = node.properties.filter(function (prop) { if (!prop.computed && (prop.kind === "get" || prop.kind === "set")) { defineMap.push(mutatorMap, prop, null, file); return false; diff --git a/packages/babel-plugin-transform-react-display-name/src/index.js b/packages/babel-plugin-transform-react-display-name/src/index.js index cc8479cbd8..dd4f190d87 100644 --- a/packages/babel-plugin-transform-react-display-name/src/index.js +++ b/packages/babel-plugin-transform-react-display-name/src/index.js @@ -78,7 +78,7 @@ export default declare(api => { let id; // crawl up the ancestry looking for possible candidates for displayName inference - path.find(function(path) { + path.find(function (path) { if (path.isAssignmentExpression()) { id = path.node.left; } else if (path.isObjectProperty()) { diff --git a/packages/babel-plugin-transform-react-jsx/src/transform-classic.js b/packages/babel-plugin-transform-react-jsx/src/transform-classic.js index 6fd8e9d80a..d74b16078f 100644 --- a/packages/babel-plugin-transform-react-jsx/src/transform-classic.js +++ b/packages/babel-plugin-transform-react-jsx/src/transform-classic.js @@ -92,7 +92,7 @@ export default declare((api, options) => { }, }; - visitor.JSXAttribute = function(path) { + visitor.JSXAttribute = function (path) { if (t.isJSXElement(path.node.value)) { path.node.value = t.jsxExpressionContainer(path.node.value); } diff --git a/packages/babel-plugin-transform-runtime/scripts/build-dist.js b/packages/babel-plugin-transform-runtime/scripts/build-dist.js index a5ee8f16da..2991a0ad83 100644 --- a/packages/babel-plugin-transform-runtime/scripts/build-dist.js +++ b/packages/babel-plugin-transform-runtime/scripts/build-dist.js @@ -78,7 +78,7 @@ function writeCoreJS({ } const runtimeRoot = proposals ? "core-js" : "core-js-stable"; - paths.forEach(function(corejsPath) { + paths.forEach(function (corejsPath) { outputFile( path.join(pkgDirname, runtimeRoot, `${corejsPath}.js`), `module.exports = require("${corejsRoot}/${corejsPath}");` diff --git a/packages/babel-plugin-transform-runtime/src/get-runtime-path/browser.js b/packages/babel-plugin-transform-runtime/src/get-runtime-path/browser.js index 1d407ae99a..508eada797 100644 --- a/packages/babel-plugin-transform-runtime/src/get-runtime-path/browser.js +++ b/packages/babel-plugin-transform-runtime/src/get-runtime-path/browser.js @@ -1,4 +1,4 @@ -export default function(moduleName, dirname, absoluteRuntime) { +export default function (moduleName, dirname, absoluteRuntime) { if (absoluteRuntime === false) return moduleName; throw new Error( diff --git a/packages/babel-plugin-transform-runtime/src/get-runtime-path/index.js b/packages/babel-plugin-transform-runtime/src/get-runtime-path/index.js index 393bde7938..911d8e719b 100644 --- a/packages/babel-plugin-transform-runtime/src/get-runtime-path/index.js +++ b/packages/babel-plugin-transform-runtime/src/get-runtime-path/index.js @@ -1,7 +1,7 @@ import path from "path"; import resolve from "resolve"; -export default function(moduleName, dirname, absoluteRuntime) { +export default function (moduleName, dirname, absoluteRuntime) { if (absoluteRuntime === false) return moduleName; return resolveAbsoluteRuntime( diff --git a/packages/babel-plugin-transform-template-literals/src/index.js b/packages/babel-plugin-transform-template-literals/src/index.js index ba1bc4eae6..9ddbf5c9d3 100644 --- a/packages/babel-plugin-transform-template-literals/src/index.js +++ b/packages/babel-plugin-transform-template-literals/src/index.js @@ -25,7 +25,7 @@ export default declare((api, options) => { */ function buildConcatCallExpressions(items) { let avail = true; - return items.reduce(function(left, right) { + return items.reduce(function (left, right) { let canBeInserted = t.isLiteral(right); if (!canBeInserted && avail) { diff --git a/packages/babel-preset-env/src/get-option-specific-excludes.js b/packages/babel-preset-env/src/get-option-specific-excludes.js index d9bcc60bde..3adf5dcc77 100644 --- a/packages/babel-preset-env/src/get-option-specific-excludes.js +++ b/packages/babel-preset-env/src/get-option-specific-excludes.js @@ -2,6 +2,6 @@ const defaultExcludesForLooseMode = ["transform-typeof-symbol"]; -export default function({ loose }: { loose: boolean }): null | string[] { +export default function ({ loose }: { loose: boolean }): null | string[] { return loose ? defaultExcludesForLooseMode : null; } diff --git a/packages/babel-preset-env/src/polyfills/corejs2/entry-plugin.js b/packages/babel-preset-env/src/polyfills/corejs2/entry-plugin.js index da8010e2c7..cf0f17e464 100644 --- a/packages/babel-preset-env/src/polyfills/corejs2/entry-plugin.js +++ b/packages/babel-preset-env/src/polyfills/corejs2/entry-plugin.js @@ -14,7 +14,7 @@ import { logEntryPolyfills } from "../../debug"; import type { InternalPluginOptions } from "../../types"; import type { NodePath } from "@babel/traverse"; -export default function( +export default function ( _: any, { include, @@ -53,7 +53,7 @@ export default function( pre() { this.importPolyfillIncluded = false; - this.replaceBySeparateModulesImport = function(path) { + this.replaceBySeparateModulesImport = function (path) { this.importPolyfillIncluded = true; if (regenerator) { diff --git a/packages/babel-preset-env/src/polyfills/corejs2/get-platform-specific-default.js b/packages/babel-preset-env/src/polyfills/corejs2/get-platform-specific-default.js index 3674a2be8d..10674d433c 100644 --- a/packages/babel-preset-env/src/polyfills/corejs2/get-platform-specific-default.js +++ b/packages/babel-preset-env/src/polyfills/corejs2/get-platform-specific-default.js @@ -8,7 +8,7 @@ export const defaultWebIncludes = [ "web.dom.iterable", ]; -export default function(targets: Targets): null | string[] { +export default function (targets: Targets): null | string[] { const targetNames = Object.keys(targets); const isAnyTarget = !targetNames.length; const isWebTarget = targetNames.some(name => name !== "node"); diff --git a/packages/babel-preset-env/src/polyfills/corejs2/usage-plugin.js b/packages/babel-preset-env/src/polyfills/corejs2/usage-plugin.js index a9269237e5..697be14c60 100644 --- a/packages/babel-preset-env/src/polyfills/corejs2/usage-plugin.js +++ b/packages/babel-preset-env/src/polyfills/corejs2/usage-plugin.js @@ -26,7 +26,7 @@ const NO_DIRECT_POLYFILL_IMPORT = ` When setting \`useBuiltIns: 'usage'\`, polyfills are automatically imported when needed. Please remove the \`import '@babel/polyfill'\` call or use \`useBuiltIns: 'entry'\` instead.`; -export default function( +export default function ( { types: t }: { types: Object }, { include, exclude, polyfillTargets, debug }: InternalPluginOptions, ) { @@ -191,14 +191,14 @@ export default function( pre({ path }: { path: NodePath }) { this.polyfillsSet = new Set(); - this.addImport = function(builtIn) { + this.addImport = function (builtIn) { if (!this.polyfillsSet.has(builtIn)) { this.polyfillsSet.add(builtIn); createImport(path, builtIn); } }; - this.addUnsupported = function(builtIn) { + this.addUnsupported = function (builtIn) { const modules = Array.isArray(builtIn) ? builtIn : [builtIn]; for (const module of modules) { if (polyfills.has(module)) { diff --git a/packages/babel-preset-env/src/polyfills/corejs3/entry-plugin.js b/packages/babel-preset-env/src/polyfills/corejs3/entry-plugin.js index 3ec5875d2b..caa8de4cff 100644 --- a/packages/babel-preset-env/src/polyfills/corejs3/entry-plugin.js +++ b/packages/babel-preset-env/src/polyfills/corejs3/entry-plugin.js @@ -35,7 +35,7 @@ const BABEL_POLYFILL_DEPRECATION = ` \`@babel/polyfill\` is deprecated. Please, use required parts of \`core-js\` and \`regenerator-runtime/runtime\` separately`; -export default function( +export default function ( _: any, { corejs, include, exclude, polyfillTargets, debug }: InternalPluginOptions, ) { @@ -115,7 +115,7 @@ export default function( this.injectedPolyfills = new Set(); this.polyfillsSet = new Set(); - this.replaceBySeparateModulesImport = function(path, modules) { + this.replaceBySeparateModulesImport = function (path, modules) { for (const module of modules) { this.polyfillsSet.add(module); } diff --git a/packages/babel-preset-env/src/polyfills/corejs3/usage-plugin.js b/packages/babel-preset-env/src/polyfills/corejs3/usage-plugin.js index 5474418c3a..0cd423af19 100644 --- a/packages/babel-preset-env/src/polyfills/corejs3/usage-plugin.js +++ b/packages/babel-preset-env/src/polyfills/corejs3/usage-plugin.js @@ -47,7 +47,7 @@ const corejs3PolyfillsWithShippedProposals = (corejs3ShippedProposalsList: strin { ...corejs3PolyfillsWithoutProposals }, ); -export default function( +export default function ( _: any, { corejs, @@ -234,21 +234,21 @@ export default function( this.injectedPolyfills = new Set(); this.polyfillsSet = new Set(); - this.addUnsupported = function(builtIn) { + this.addUnsupported = function (builtIn) { const modules = Array.isArray(builtIn) ? builtIn : [builtIn]; for (const module of modules) { this.polyfillsSet.add(module); } }; - this.addBuiltInDependencies = function(builtIn) { + this.addBuiltInDependencies = function (builtIn) { if (has(BuiltIns, builtIn)) { const BuiltInDependencies = BuiltIns[builtIn]; this.addUnsupported(BuiltInDependencies); } }; - this.addPropertyDependencies = function(source = {}, key) { + this.addPropertyDependencies = function (source = {}, key) { const { builtIn, instanceType, isNamespaced } = source; if (isNamespaced) return; if (PossibleGlobalObjects.has(builtIn)) { diff --git a/packages/babel-preset-env/src/polyfills/regenerator/entry-plugin.js b/packages/babel-preset-env/src/polyfills/regenerator/entry-plugin.js index 53db458773..27f4850e76 100644 --- a/packages/babel-preset-env/src/polyfills/regenerator/entry-plugin.js +++ b/packages/babel-preset-env/src/polyfills/regenerator/entry-plugin.js @@ -7,7 +7,7 @@ function isRegeneratorSource(source) { return source === "regenerator-runtime/runtime"; } -export default function() { +export default function () { const visitor = { ImportDeclaration(path: NodePath) { if (isRegeneratorSource(getImportSource(path))) { diff --git a/packages/babel-preset-env/src/polyfills/regenerator/usage-plugin.js b/packages/babel-preset-env/src/polyfills/regenerator/usage-plugin.js index f417cf248d..28979ac226 100644 --- a/packages/babel-preset-env/src/polyfills/regenerator/usage-plugin.js +++ b/packages/babel-preset-env/src/polyfills/regenerator/usage-plugin.js @@ -3,7 +3,7 @@ import { createImport } from "../../utils"; import type { NodePath } from "@babel/traverse"; -export default function() { +export default function () { return { name: "regenerator-usage", pre() { diff --git a/packages/babel-preset-env/src/utils.js b/packages/babel-preset-env/src/utils.js index 2630f5a1c4..dc81f30e4b 100644 --- a/packages/babel-preset-env/src/utils.js +++ b/packages/babel-preset-env/src/utils.js @@ -8,10 +8,7 @@ import type { Targets } from "@babel/helper-compilation-targets"; export const has = Object.hasOwnProperty.call.bind(Object.hasOwnProperty); export function getType(target: any): string { - return Object.prototype.toString - .call(target) - .slice(8, -1) - .toLowerCase(); + return Object.prototype.toString.call(target).slice(8, -1).toLowerCase(); } export function intersection( diff --git a/packages/babel-preset-env/test/normalize-options.spec.js b/packages/babel-preset-env/test/normalize-options.spec.js index 959cb09fd6..be301d202c 100644 --- a/packages/babel-preset-env/test/normalize-options.spec.js +++ b/packages/babel-preset-env/test/normalize-options.spec.js @@ -214,8 +214,8 @@ describe("normalize-options", () => { }); }); - describe("checkDuplicateIncludeExcludes", function() { - it("should throw if duplicate names in both", function() { + describe("checkDuplicateIncludeExcludes", function () { + it("should throw if duplicate names in both", function () { expect(() => { checkDuplicateIncludeExcludes( ["transform-regenerator", "map"], @@ -224,7 +224,7 @@ describe("normalize-options", () => { }).toThrow(); }); - it("should not throw if no duplicate names in both", function() { + it("should not throw if no duplicate names in both", function () { expect(() => { checkDuplicateIncludeExcludes(["transform-regenerator"], ["map"]); }).not.toThrow(); diff --git a/packages/babel-register/src/index.js b/packages/babel-register/src/index.js index 0fbe1a97b7..baf93d9367 100644 --- a/packages/babel-register/src/index.js +++ b/packages/babel-register/src/index.js @@ -4,7 +4,7 @@ * from a compiled Babel import. */ -exports = module.exports = function(...args) { +exports = module.exports = function (...args) { return register(...args); }; exports.__esModule = true; diff --git a/packages/babel-register/test/browserify.js b/packages/babel-register/test/browserify.js index 2d200bb1ce..8696083e72 100644 --- a/packages/babel-register/test/browserify.js +++ b/packages/babel-register/test/browserify.js @@ -2,13 +2,13 @@ import browserify from "browserify"; import path from "path"; import vm from "vm"; -describe("browserify", function() { - it("@babel/register may be used without breaking browserify", function(done) { +describe("browserify", function () { + it("@babel/register may be used without breaking browserify", function (done) { const bundler = browserify( path.join(__dirname, "fixtures/browserify/register.js"), ); - bundler.bundle(function(err, bundle) { + bundler.bundle(function (err, bundle) { if (err) return done(err); expect(bundle.length).toBeTruthy(); diff --git a/packages/babel-register/test/index.js b/packages/babel-register/test/index.js index eb1b93dad5..af7fb0739a 100644 --- a/packages/babel-register/test/index.js +++ b/packages/babel-register/test/index.js @@ -41,7 +41,7 @@ const defaultOptions = { ignoreNodeModules: false, }; -describe("@babel/register", function() { +describe("@babel/register", function () { let babelRegister; function setupRegister(config = { babelrc: false }) { @@ -138,7 +138,7 @@ describe("@babel/register", function() { }); } - spawn.on("close", function() { + spawn.on("close", function () { let err; try { diff --git a/packages/babel-standalone/src/transformScriptTags.js b/packages/babel-standalone/src/transformScriptTags.js index 2f46945e00..b412003852 100644 --- a/packages/babel-standalone/src/transformScriptTags.js +++ b/packages/babel-standalone/src/transformScriptTags.js @@ -72,7 +72,7 @@ function load(url, successCallback, errorCallback) { if ("overrideMimeType" in xhr) { xhr.overrideMimeType("text/plain"); } - xhr.onreadystatechange = function() { + xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 0 || xhr.status === 200) { successCallback(xhr.responseText); diff --git a/packages/babel-template/src/builder.js b/packages/babel-template/src/builder.js index 93b2403272..b299e2e7b6 100644 --- a/packages/babel-template/src/builder.js +++ b/packages/babel-template/src/builder.js @@ -113,10 +113,7 @@ function extendedTrace(fn: Arg => Result): Arg => Result { // 'extendedTrace', and the anonymous builder function, with the final // stripped line being the error message itself since we threw it // in the first place and it doesn't matter. - rootStack = error.stack - .split("\n") - .slice(3) - .join("\n"); + rootStack = error.stack.split("\n").slice(3).join("\n"); } } diff --git a/packages/babel-template/test/index.js b/packages/babel-template/test/index.js index 58e552e940..cae920c2b5 100644 --- a/packages/babel-template/test/index.js +++ b/packages/babel-template/test/index.js @@ -4,36 +4,36 @@ import * as t from "@babel/types"; const comments = "// Sum two numbers\nconst add = (a, b) => a + b;"; -describe("@babel/template", function() { - it("import statements are allowed by default", function() { - expect(function() { +describe("@babel/template", function () { + it("import statements are allowed by default", function () { + expect(function () { template("import foo from 'foo'")({}); }).not.toThrow(); }); - it("with statements are allowed with sourceType: script", function() { - expect(function() { + it("with statements are allowed with sourceType: script", function () { + expect(function () { template("with({}){}", { sourceType: "script" })({}); }).not.toThrow(); }); - it("should strip comments by default", function() { + it("should strip comments by default", function () { const code = "const add = (a, b) => a + b;"; const output = template(comments)(); expect(generator(output).code).toBe(code); }); - it("should preserve comments with a flag", function() { + it("should preserve comments with a flag", function () { const output = template(comments, { preserveComments: true })(); expect(generator(output).code).toBe(comments); }); - it("should preserve comments with a flag", function() { + it("should preserve comments with a flag", function () { const output = template(comments, { preserveComments: true })(); expect(generator(output).code).toBe(comments); }); - it("should preserve comments with a flag when using .ast", function() { + it("should preserve comments with a flag when using .ast", function () { const output1 = template.ast(comments, { preserveComments: true }); const output2 = template({ preserveComments: true }).ast(comments); expect(generator(output1).code).toBe(comments); diff --git a/packages/babel-traverse/src/index.js b/packages/babel-traverse/src/index.js index da880632ad..1af05587ca 100644 --- a/packages/babel-traverse/src/index.js +++ b/packages/babel-traverse/src/index.js @@ -44,11 +44,11 @@ traverse.visitors = visitors; traverse.verify = visitors.verify; traverse.explode = visitors.explode; -traverse.cheap = function(node, enter) { +traverse.cheap = function (node, enter) { return t.traverseFast(node, enter); }; -traverse.node = function( +traverse.node = function ( node: Object, opts: Object, scope: Object, @@ -66,13 +66,13 @@ traverse.node = function( } }; -traverse.clearNode = function(node, opts) { +traverse.clearNode = function (node, opts) { t.removeProperties(node, opts); cache.path.delete(node); }; -traverse.removeProperties = function(tree, opts) { +traverse.removeProperties = function (tree, opts) { t.traverseFast(tree, traverse.clearNode, opts); return tree; }; @@ -84,7 +84,7 @@ function hasBlacklistedType(path, state) { } } -traverse.hasType = function( +traverse.hasType = function ( tree: Object, type: Object, blacklistTypes: Array, diff --git a/packages/babel-traverse/src/path/ancestry.js b/packages/babel-traverse/src/path/ancestry.js index e2667d1c8d..758def8e55 100644 --- a/packages/babel-traverse/src/path/ancestry.js +++ b/packages/babel-traverse/src/path/ancestry.js @@ -78,7 +78,7 @@ export function getStatementParent(): NodePath { export function getEarliestCommonAncestorFrom( paths: Array, ): NodePath { - return this.getDeepestCommonAncestorFrom(paths, function( + return this.getDeepestCommonAncestorFrom(paths, function ( deepest, i, ancestries, diff --git a/packages/babel-traverse/src/path/index.js b/packages/babel-traverse/src/path/index.js index 79ef050928..a2eaf79f22 100644 --- a/packages/babel-traverse/src/path/index.js +++ b/packages/babel-traverse/src/path/index.js @@ -226,11 +226,11 @@ Object.assign( for (const type of (t.TYPES: Array)) { const typeKey = `is${type}`; const fn = t[typeKey]; - NodePath.prototype[typeKey] = function(opts) { + NodePath.prototype[typeKey] = function (opts) { return fn(this.node, opts); }; - NodePath.prototype[`assert${type}`] = function(opts) { + NodePath.prototype[`assert${type}`] = function (opts) { if (!fn(this.node, opts)) { throw new TypeError(`Expected node path of type ${type}`); } @@ -243,7 +243,7 @@ for (const type of Object.keys(virtualTypes)) { const virtualType = virtualTypes[type]; - NodePath.prototype[`is${type}`] = function(opts) { + NodePath.prototype[`is${type}`] = function (opts) { return virtualType.checkPath(this, opts); }; } diff --git a/packages/babel-traverse/src/path/inference/inferer-reference.js b/packages/babel-traverse/src/path/inference/inferer-reference.js index 54e6a8b981..bb6ab6827a 100644 --- a/packages/babel-traverse/src/path/inference/inferer-reference.js +++ b/packages/babel-traverse/src/path/inference/inferer-reference.js @@ -1,7 +1,7 @@ import type NodePath from "../index"; import * as t from "@babel/types"; -export default function(node: Object) { +export default function (node: Object) { if (!this.isReferenced()) return; // check if a binding exists of this value and if so then return a union type of all diff --git a/packages/babel-traverse/src/path/inference/inferers.js b/packages/babel-traverse/src/path/inference/inferers.js index 4cfa71de59..1b3de6cbd8 100644 --- a/packages/babel-traverse/src/path/inference/inferers.js +++ b/packages/babel-traverse/src/path/inference/inferers.js @@ -117,9 +117,7 @@ export function ConditionalExpression() { } export function SequenceExpression() { - return this.get("expressions") - .pop() - .getTypeAnnotation(); + return this.get("expressions").pop().getTypeAnnotation(); } export function ParenthesizedExpression() { diff --git a/packages/babel-traverse/src/path/lib/removal-hooks.js b/packages/babel-traverse/src/path/lib/removal-hooks.js index c54f1a256b..20d7fba20e 100644 --- a/packages/babel-traverse/src/path/lib/removal-hooks.js +++ b/packages/babel-traverse/src/path/lib/removal-hooks.js @@ -5,7 +5,7 @@ */ export const hooks = [ - function(self, parent) { + function (self, parent) { const removeParent = // while (NODE); // removing the test of a while/switch, we can either just remove it entirely *or* turn the @@ -33,7 +33,7 @@ export const hooks = [ } }, - function(self, parent) { + function (self, parent) { if (parent.isSequenceExpression() && parent.node.expressions.length === 1) { // (node, NODE); // we've just removed the second element of a sequence expression so let's turn that sequence @@ -43,7 +43,7 @@ export const hooks = [ } }, - function(self, parent) { + function (self, parent) { if (parent.isBinary()) { // left + NODE; // NODE + right; @@ -58,7 +58,7 @@ export const hooks = [ } }, - function(self, parent) { + function (self, parent) { if ( (parent.isIfStatement() && (self.key === "consequent" || self.key === "alternate")) || diff --git a/packages/babel-traverse/src/visitors.js b/packages/babel-traverse/src/visitors.js index eb8516a451..0748865341 100644 --- a/packages/babel-traverse/src/visitors.js +++ b/packages/babel-traverse/src/visitors.js @@ -214,11 +214,11 @@ function wrapWithStateOrWrapper(oldVisitor, state, wrapper: ?Function) { // not an enter/exit array of callbacks if (!Array.isArray(fns)) continue; - fns = fns.map(function(fn) { + fns = fns.map(function (fn) { let newFn = fn; if (state) { - newFn = function(path) { + newFn = function (path) { return fn.call(state, path, state); }; } @@ -258,7 +258,7 @@ function ensureCallbackArrays(obj) { } function wrapCheck(wrapper, fn) { - const newFn = function(path) { + const newFn = function (path) { if (wrapper.checkPath(path)) { return fn.apply(this, arguments); } diff --git a/packages/babel-traverse/test/ancestry.js b/packages/babel-traverse/test/ancestry.js index 0baadfbca0..2c545b1f77 100644 --- a/packages/babel-traverse/test/ancestry.js +++ b/packages/babel-traverse/test/ancestry.js @@ -1,11 +1,11 @@ import traverse from "../lib"; import { parse } from "@babel/parser"; -describe("path/ancestry", function() { - describe("isAncestor", function() { +describe("path/ancestry", function () { + describe("isAncestor", function () { const ast = parse("var a = 1; 'a';"); - it("returns true if ancestor", function() { + it("returns true if ancestor", function () { const paths = []; traverse(ast, { "Program|NumericLiteral"(path) { @@ -18,7 +18,7 @@ describe("path/ancestry", function() { expect(programPath.isAncestor(numberPath)).toBeTruthy(); }); - it("returns false if not ancestor", function() { + it("returns false if not ancestor", function () { const paths = []; traverse(ast, { "Program|NumericLiteral|StringLiteral"(path) { @@ -32,10 +32,10 @@ describe("path/ancestry", function() { }); }); - describe("isDescendant", function() { + describe("isDescendant", function () { const ast = parse("var a = 1; 'a';"); - it("returns true if descendant", function() { + it("returns true if descendant", function () { const paths = []; traverse(ast, { "Program|NumericLiteral"(path) { @@ -48,7 +48,7 @@ describe("path/ancestry", function() { expect(numberPath.isDescendant(programPath)).toBeTruthy(); }); - it("returns false if not descendant", function() { + it("returns false if not descendant", function () { const paths = []; traverse(ast, { "Program|NumericLiteral|StringLiteral"(path) { @@ -62,10 +62,10 @@ describe("path/ancestry", function() { }); }); - describe("getStatementParent", function() { + describe("getStatementParent", function () { const ast = parse("var a = 1;"); - it("should throw", function() { - expect(function() { + it("should throw", function () { + expect(function () { traverse(ast, { Program(path) { path.getStatementParent(); diff --git a/packages/babel-traverse/test/conversion.js b/packages/babel-traverse/test/conversion.js index 509d6c0309..97bd0d4cdc 100644 --- a/packages/babel-traverse/test/conversion.js +++ b/packages/babel-traverse/test/conversion.js @@ -7,7 +7,7 @@ function getPath(code) { const ast = parse(code); let path; traverse(ast, { - Program: function(_path) { + Program: function (_path) { path = _path.get("body.0"); _path.stop(); }, @@ -20,9 +20,9 @@ function generateCode(path) { return generate(path.parentPath.node).code; } -describe("conversion", function() { - describe("ensureBlock", function() { - it("throws converting node without body to block", function() { +describe("conversion", function () { + describe("ensureBlock", function () { + it("throws converting node without body to block", function () { const rootPath = getPath("true;"); expect(() => { @@ -30,20 +30,20 @@ describe("conversion", function() { }).toThrow(); }); - it("throws converting already block array", function() { + it("throws converting already block array", function () { const rootPath = getPath("function test() { true; }").get("body"); expect(() => { rootPath.ensureBlock(); }).toThrow(); }); - it("converts arrow function with expression body to block", function() { + it("converts arrow function with expression body to block", function () { const rootPath = getPath("() => true").get("expression"); rootPath.ensureBlock(); expect(generateCode(rootPath)).toBe("() => {\n return true;\n};"); }); - it("preserves arrow function body's context", function() { + it("preserves arrow function body's context", function () { const rootPath = getPath("() => true").get("expression"); const body = rootPath.get("body"); rootPath.ensureBlock(); @@ -51,13 +51,13 @@ describe("conversion", function() { expect(generateCode(rootPath)).toBe("() => {\n return false;\n};"); }); - it("converts for loop with statement body to block", function() { + it("converts for loop with statement body to block", function () { const rootPath = getPath("for (;;) true;"); rootPath.ensureBlock(); expect(generateCode(rootPath)).toBe("for (;;) {\n true;\n}"); }); - it("preserves for loop body's context", function() { + it("preserves for loop body's context", function () { const rootPath = getPath("for (;;) true;"); const body = rootPath.get("body"); rootPath.ensureBlock(); diff --git a/packages/babel-traverse/test/evaluation.js b/packages/babel-traverse/test/evaluation.js index a9502b1c80..f988bb1184 100644 --- a/packages/babel-traverse/test/evaluation.js +++ b/packages/babel-traverse/test/evaluation.js @@ -5,7 +5,7 @@ function getPath(code) { const ast = parse(code); let path; traverse(ast, { - Program: function(_path) { + Program: function (_path) { path = _path; _path.stop(); }, @@ -13,26 +13,22 @@ function getPath(code) { return path; } -describe("evaluation", function() { - describe("evaluateTruthy", function() { - it("it should work with null", function() { +describe("evaluation", function () { + describe("evaluateTruthy", function () { + it("it should work with null", function () { expect( - getPath("false || a.length === 0;") - .get("body")[0] - .evaluateTruthy(), + getPath("false || a.length === 0;").get("body")[0].evaluateTruthy(), ).toBeUndefined(); }); - it("it should not mistake lack of confidence for falsy", function() { + it("it should not mistake lack of confidence for falsy", function () { expect( - getPath("foo || 'bar'") - .get("body")[0] - .evaluate().value, + getPath("foo || 'bar'").get("body")[0].evaluate().value, ).toBeUndefined(); }); }); - it("should bail out on recursive evaluation", function() { + it("should bail out on recursive evaluation", function () { expect( getPath("function fn(a) { var g = a ? 1 : 2, a = g * this.foo; }") .get("body.0.body.body.0.declarations.1.init") @@ -40,30 +36,18 @@ describe("evaluation", function() { ).toBe(false); }); - it("should short-circuit && and ||", function() { - expect( - getPath("x === 'y' || 42") - .get("body")[0] - .evaluate().confident, - ).toBe(false); - expect( - getPath("x === 'y' && 0") - .get("body")[0] - .evaluate().confident, - ).toBe(false); - expect( - getPath("42 || x === 'y'") - .get("body")[0] - .evaluate().value, - ).toBe(42); - expect( - getPath("0 && x === 'y'") - .get("body")[0] - .evaluate().value, - ).toBe(0); + it("should short-circuit && and ||", function () { + expect(getPath("x === 'y' || 42").get("body")[0].evaluate().confident).toBe( + false, + ); + expect(getPath("x === 'y' && 0").get("body")[0].evaluate().confident).toBe( + false, + ); + expect(getPath("42 || x === 'y'").get("body")[0].evaluate().value).toBe(42); + expect(getPath("0 && x === 'y'").get("body")[0].evaluate().value).toBe(0); }); - it("should work with repeated, indeterminate identifiers", function() { + it("should work with repeated, indeterminate identifiers", function () { expect( getPath("var num = foo(); (num > 0 && num < 100);") .get("body")[1] @@ -71,7 +55,7 @@ describe("evaluation", function() { ).toBeUndefined(); }); - it("should work with repeated, determinate identifiers", function() { + it("should work with repeated, determinate identifiers", function () { expect( getPath("var num = 5; (num > 0 && num < 100);") .get("body")[1] @@ -79,7 +63,7 @@ describe("evaluation", function() { ).toBe(true); }); - it("should deopt when var is redeclared in the same scope", function() { + it("should deopt when var is redeclared in the same scope", function () { expect( getPath("var x = 2; var y = x + 2; { var x = 3 }") .get("body.1.declarations.0.init") @@ -87,7 +71,7 @@ describe("evaluation", function() { ).toBe(false); }); - it("should evaluate template literals", function() { + it("should evaluate template literals", function () { expect( getPath("var x = 8; var y = 1; var z = `value is ${x >>> y}`") .get("body.2.declarations.0.init") @@ -95,7 +79,7 @@ describe("evaluation", function() { ).toBe("value is 4"); }); - it("should evaluate member expressions", function() { + it("should evaluate member expressions", function () { expect( getPath("var x = 'foo'.length") .get("body.0.declarations.0.init") @@ -114,22 +98,19 @@ describe("evaluation", function() { expect(eval_invalid_call.confident).toBe(false); }); - it("it should not deopt vars in different scope", function() { + it("it should not deopt vars in different scope", function () { const input = "var a = 5; function x() { var a = 5; var b = a + 1; } var b = a + 2"; expect( - getPath(input) - .get("body.1.body.body.1.declarations.0.init") - .evaluate().value, + getPath(input).get("body.1.body.body.1.declarations.0.init").evaluate() + .value, ).toBe(6); expect( - getPath(input) - .get("body.2.declarations.0.init") - .evaluate().value, + getPath(input).get("body.2.declarations.0.init").evaluate().value, ).toBe(7); }); - it("it should not deopt let/const inside blocks", function() { + it("it should not deopt let/const inside blocks", function () { expect( getPath("let x = 5; { let x = 1; } let y = x + 5") .get("body.2.declarations.0.init") @@ -137,15 +118,11 @@ describe("evaluation", function() { ).toBe(10); const constExample = "const d = true; if (d && true || false) { const d = false; d && 5; }"; + expect(getPath(constExample).get("body.1.test").evaluate().value).toBe( + true, + ); expect( - getPath(constExample) - .get("body.1.test") - .evaluate().value, - ).toBe(true); - expect( - getPath(constExample) - .get("body.1.consequent.body.1") - .evaluate().value, + getPath(constExample).get("body.1.consequent.body.1").evaluate().value, ).toBe(false); const test_alternate = "var y = (3 < 4)? 3 + 4: 3 + 4;"; expect( @@ -155,7 +132,7 @@ describe("evaluation", function() { ).toBe(7); }); - it("should deopt ids that are referenced before the bindings", function() { + it("should deopt ids that are referenced before the bindings", function () { expect( getPath("let x = y + 5; let y = 5;") .get("body.0.declarations.0.init") @@ -170,19 +147,13 @@ describe("evaluation", function() { it("should evaluate undefined, NaN and Infinity", () => { expect( - getPath("undefined") - .get("body.0.expression") - .evaluate().confident, + getPath("undefined").get("body.0.expression").evaluate().confident, ).toBe(true); + expect(getPath("NaN").get("body.0.expression").evaluate().confident).toBe( + true, + ); expect( - getPath("NaN") - .get("body.0.expression") - .evaluate().confident, - ).toBe(true); - expect( - getPath("Infinity") - .get("body.0.expression") - .evaluate().confident, + getPath("Infinity").get("body.0.expression").evaluate().confident, ).toBe(true); }); @@ -204,17 +175,13 @@ describe("evaluation", function() { expect(eval_undef.deopt.parentPath.node.kind).toBe("let"); }); - it("should work with String.raw", function() { - expect( - getPath("String.raw`\\d`") - .get("body")[0] - .evaluate().value, - ).toBe("\\d"); + it("should work with String.raw", function () { + expect(getPath("String.raw`\\d`").get("body")[0].evaluate().value).toBe( + "\\d", + ); expect( - getPath("`${String.raw`\\d`}`") - .get("body")[0] - .evaluate().value, + getPath("`${String.raw`\\d`}`").get("body")[0].evaluate().value, ).toBe("\\d"); }); diff --git a/packages/babel-traverse/test/family.js b/packages/babel-traverse/test/family.js index b09ce42c93..80d2d89556 100644 --- a/packages/babel-traverse/test/family.js +++ b/packages/babel-traverse/test/family.js @@ -1,8 +1,8 @@ import traverse from "../lib"; import { parse } from "@babel/parser"; -describe("path/family", function() { - describe("getBindingIdentifiers", function() { +describe("path/family", function () { + describe("getBindingIdentifiers", function () { const ast = parse("var a = 1, {b} = c, [d] = e; function f() {}"); let nodes = {}, paths = {}, @@ -19,19 +19,19 @@ describe("path/family", function() { }, }); - it("should contain keys of nodes in paths", function() { + it("should contain keys of nodes in paths", function () { Object.keys(nodes).forEach(id => { expect(hop(paths, id)).toBe(true); }); }); - it("should contain outer bindings", function() { + it("should contain outer bindings", function () { Object.keys(outerNodes).forEach(id => { expect(hop(outerPaths, id)).toBe(true); }); }); - it("should return paths", function() { + it("should return paths", function () { Object.keys(paths).forEach(id => { expect(paths[id].node).toBeTruthy(); expect(paths[id].type).toBe(paths[id].node.type); @@ -43,19 +43,19 @@ describe("path/family", function() { }); }); - it("should match paths and nodes returned for the same ast", function() { + it("should match paths and nodes returned for the same ast", function () { Object.keys(nodes).forEach(id => { expect(nodes[id]).toBe(paths[id].node); }); }); - it("should match paths and nodes returned for outer Bindings", function() { + it("should match paths and nodes returned for outer Bindings", function () { Object.keys(outerNodes).forEach(id => { expect(outerNodes[id]).toBe(outerPaths[id].node); }); }); }); - describe("getSibling", function() { + describe("getSibling", function () { const ast = parse( "var a = 1, {b} = c, [d] = e; function f() {} function g() {}", ); @@ -68,14 +68,14 @@ describe("path/family", function() { }, }); - it("should return traverse sibling nodes", function() { + it("should return traverse sibling nodes", function () { expect(sibling.getNextSibling().node).toBeTruthy(); expect(lastSibling.getPrevSibling().node).toBeTruthy(); expect(sibling.getPrevSibling().node).toBeFalsy(); expect(lastSibling.getNextSibling().node).toBeFalsy(); }); - it("should return all preceding and succeeding sibling nodes", function() { + it("should return all preceding and succeeding sibling nodes", function () { expect(sibling.getAllNextSiblings().length).toBeTruthy(); expect(lastSibling.getAllPrevSiblings().length).toBeTruthy(); expect(sibling.getAllNextSiblings()).toHaveLength(2); diff --git a/packages/babel-traverse/test/hub.js b/packages/babel-traverse/test/hub.js index 3c8cbe36c4..68ea15ef8b 100644 --- a/packages/babel-traverse/test/hub.js +++ b/packages/babel-traverse/test/hub.js @@ -1,8 +1,8 @@ import assert from "assert"; import { Hub } from "../lib"; -describe("hub", function() { - it("default buildError should return TypeError", function() { +describe("hub", function () { + it("default buildError should return TypeError", function () { const hub = new Hub(); const msg = "test_msg"; assert.deepEqual(hub.buildError(null, msg), new TypeError(msg)); diff --git a/packages/babel-traverse/test/inference.js b/packages/babel-traverse/test/inference.js index e3c55c23a4..111475df42 100644 --- a/packages/babel-traverse/test/inference.js +++ b/packages/babel-traverse/test/inference.js @@ -6,7 +6,7 @@ function getPath(code) { const ast = parse(code, { plugins: ["flow"] }); let path; traverse(ast, { - Program: function(_path) { + Program: function (_path) { path = _path; _path.stop(); }, @@ -14,9 +14,9 @@ function getPath(code) { return path; } -describe("inference", function() { - describe("baseTypeStrictlyMatches", function() { - it("it should work with null", function() { +describe("inference", function () { + describe("baseTypeStrictlyMatches", function () { + it("it should work with null", function () { const path = getPath("var x = null; x === null") .get("body")[1] .get("expression"); @@ -27,7 +27,7 @@ describe("inference", function() { expect(strictMatch).toBeTruthy(); }); - it("it should work with numbers", function() { + it("it should work with numbers", function () { const path = getPath("var x = 1; x === 2") .get("body")[1] .get("expression"); @@ -38,7 +38,7 @@ describe("inference", function() { expect(strictMatch).toBeTruthy(); }); - it("it should bail when type changes", function() { + it("it should bail when type changes", function () { const path = getPath("var x = 1; if (foo) x = null;else x = 3; x === 2") .get("body")[2] .get("expression"); @@ -50,7 +50,7 @@ describe("inference", function() { expect(strictMatch).toBeFalsy(); }); - it("it should differentiate between null and undefined", function() { + it("it should differentiate between null and undefined", function () { const path = getPath("var x; x === null") .get("body")[1] .get("expression"); @@ -61,116 +61,86 @@ describe("inference", function() { expect(strictMatch).toBeFalsy(); }); }); - describe("getTypeAnnotation", function() { - it("should infer from type cast", function() { - const path = getPath("(x: number)") - .get("body")[0] - .get("expression"); + describe("getTypeAnnotation", function () { + it("should infer from type cast", function () { + const path = getPath("(x: number)").get("body")[0].get("expression"); expect(t.isNumberTypeAnnotation(path.getTypeAnnotation())).toBeTruthy(); }); - it("should infer string from template literal", function() { - const path = getPath("`hey`") - .get("body")[0] - .get("expression"); + it("should infer string from template literal", function () { + const path = getPath("`hey`").get("body")[0].get("expression"); expect(t.isStringTypeAnnotation(path.getTypeAnnotation())).toBeTruthy(); }); - it("should infer number from +x", function() { - const path = getPath("+x") - .get("body")[0] - .get("expression"); + it("should infer number from +x", function () { + const path = getPath("+x").get("body")[0].get("expression"); expect(t.isNumberTypeAnnotation(path.getTypeAnnotation())).toBeTruthy(); }); - it("should infer T from new T", function() { - const path = getPath("new T") - .get("body")[0] - .get("expression"); + it("should infer T from new T", function () { + const path = getPath("new T").get("body")[0].get("expression"); const type = path.getTypeAnnotation(); expect( t.isGenericTypeAnnotation(type) && type.id.name === "T", ).toBeTruthy(); }); - it("should infer number from ++x", function() { - const path = getPath("++x") - .get("body")[0] - .get("expression"); + it("should infer number from ++x", function () { + const path = getPath("++x").get("body")[0].get("expression"); expect(t.isNumberTypeAnnotation(path.getTypeAnnotation())).toBeTruthy(); }); - it("should infer number from --x", function() { - const path = getPath("--x") - .get("body")[0] - .get("expression"); + it("should infer number from --x", function () { + const path = getPath("--x").get("body")[0].get("expression"); expect(t.isNumberTypeAnnotation(path.getTypeAnnotation())).toBeTruthy(); }); - it("should infer void from void x", function() { - const path = getPath("void x") - .get("body")[0] - .get("expression"); + it("should infer void from void x", function () { + const path = getPath("void x").get("body")[0].get("expression"); expect(t.isVoidTypeAnnotation(path.getTypeAnnotation())).toBeTruthy(); }); - it("should infer string from typeof x", function() { - const path = getPath("typeof x") - .get("body")[0] - .get("expression"); + it("should infer string from typeof x", function () { + const path = getPath("typeof x").get("body")[0].get("expression"); expect(t.isStringTypeAnnotation(path.getTypeAnnotation())).toBeTruthy(); }); - it("should infer boolean from !x", function() { - const path = getPath("!x") - .get("body")[0] - .get("expression"); + it("should infer boolean from !x", function () { + const path = getPath("!x").get("body")[0].get("expression"); expect(t.isBooleanTypeAnnotation(path.getTypeAnnotation())).toBeTruthy(); }); - it("should infer type of sequence expression", function() { - const path = getPath("a,1") - .get("body")[0] - .get("expression"); + it("should infer type of sequence expression", function () { + const path = getPath("a,1").get("body")[0].get("expression"); expect(t.isNumberTypeAnnotation(path.getTypeAnnotation())).toBeTruthy(); }); - it("should infer type of logical expression", function() { - const path = getPath("'a' && 1") - .get("body")[0] - .get("expression"); + it("should infer type of logical expression", function () { + const path = getPath("'a' && 1").get("body")[0].get("expression"); const type = path.getTypeAnnotation(); expect(t.isUnionTypeAnnotation(type)).toBeTruthy(); expect(t.isStringTypeAnnotation(type.types[0])).toBeTruthy(); expect(t.isNumberTypeAnnotation(type.types[1])).toBeTruthy(); }); - it("should infer type of conditional expression", function() { - const path = getPath("q ? true : 0") - .get("body")[0] - .get("expression"); + it("should infer type of conditional expression", function () { + const path = getPath("q ? true : 0").get("body")[0].get("expression"); const type = path.getTypeAnnotation(); expect(t.isUnionTypeAnnotation(type)).toBeTruthy(); expect(t.isBooleanTypeAnnotation(type.types[0])).toBeTruthy(); expect(t.isNumberTypeAnnotation(type.types[1])).toBeTruthy(); }); - it("should infer RegExp from RegExp literal", function() { - const path = getPath("/.+/") - .get("body")[0] - .get("expression"); + it("should infer RegExp from RegExp literal", function () { + const path = getPath("/.+/").get("body")[0].get("expression"); const type = path.getTypeAnnotation(); expect( t.isGenericTypeAnnotation(type) && type.id.name === "RegExp", ).toBeTruthy(); }); - it("should infer Object from object expression", function() { - const path = getPath("({ a: 5 })") - .get("body")[0] - .get("expression"); + it("should infer Object from object expression", function () { + const path = getPath("({ a: 5 })").get("body")[0].get("expression"); const type = path.getTypeAnnotation(); expect( t.isGenericTypeAnnotation(type) && type.id.name === "Object", ).toBeTruthy(); }); - it("should infer Array from array expression", function() { - const path = getPath("[ 5 ]") - .get("body")[0] - .get("expression"); + it("should infer Array from array expression", function () { + const path = getPath("[ 5 ]").get("body")[0].get("expression"); const type = path.getTypeAnnotation(); expect( t.isGenericTypeAnnotation(type) && type.id.name === "Array", ).toBeTruthy(); }); - it("should infer Function from function", function() { + it("should infer Function from function", function () { const path = getPath("(function (): string {})") .get("body")[0] .get("expression"); @@ -179,14 +149,14 @@ describe("inference", function() { t.isGenericTypeAnnotation(type) && type.id.name === "Function", ).toBeTruthy(); }); - it("should infer call return type using function", function() { + it("should infer call return type using function", function () { const path = getPath("(function (): string {})()") .get("body")[0] .get("expression"); const type = path.getTypeAnnotation(); expect(t.isStringTypeAnnotation(type)).toBeTruthy(); }); - it("should infer call return type using async function", function() { + it("should infer call return type using async function", function () { const path = getPath("(async function (): string {})()") .get("body")[0] .get("expression"); @@ -195,7 +165,7 @@ describe("inference", function() { t.isGenericTypeAnnotation(type) && type.id.name === "Promise", ).toBeTruthy(); }); - it("should infer call return type using async generator function", function() { + it("should infer call return type using async generator function", function () { const path = getPath("(async function * (): string {})()") .get("body")[0] .get("expression"); @@ -204,37 +174,29 @@ describe("inference", function() { t.isGenericTypeAnnotation(type) && type.id.name === "AsyncIterator", ).toBeTruthy(); }); - it("should infer number from x/y", function() { - const path = getPath("x/y") - .get("body")[0] - .get("expression"); + it("should infer number from x/y", function () { + const path = getPath("x/y").get("body")[0].get("expression"); const type = path.getTypeAnnotation(); expect(t.isNumberTypeAnnotation(type)).toBeTruthy(); }); - it("should infer boolean from x instanceof y", function() { - const path = getPath("x instanceof y") - .get("body")[0] - .get("expression"); + it("should infer boolean from x instanceof y", function () { + const path = getPath("x instanceof y").get("body")[0].get("expression"); const type = path.getTypeAnnotation(); expect(t.isBooleanTypeAnnotation(type)).toBeTruthy(); }); - it("should infer number from 1 + 2", function() { - const path = getPath("1 + 2") - .get("body")[0] - .get("expression"); + it("should infer number from 1 + 2", function () { + const path = getPath("1 + 2").get("body")[0].get("expression"); const type = path.getTypeAnnotation(); expect(t.isNumberTypeAnnotation(type)).toBeTruthy(); }); - it("should infer string|number from x + y", function() { - const path = getPath("x + y") - .get("body")[0] - .get("expression"); + it("should infer string|number from x + y", function () { + const path = getPath("x + y").get("body")[0].get("expression"); const type = path.getTypeAnnotation(); expect(t.isUnionTypeAnnotation(type)).toBeTruthy(); expect(t.isStringTypeAnnotation(type.types[0])).toBeTruthy(); expect(t.isNumberTypeAnnotation(type.types[1])).toBeTruthy(); }); - it("should infer type of tagged template literal", function() { + it("should infer type of tagged template literal", function () { const path = getPath("(function (): RegExp {}) `hey`") .get("body")[0] .get("expression"); @@ -243,19 +205,19 @@ describe("inference", function() { t.isGenericTypeAnnotation(type) && type.id.name === "RegExp", ).toBeTruthy(); }); - it("should infer constant identifier", function() { + it("should infer constant identifier", function () { const path = getPath("const x = 0; x").get("body.1.expression"); const type = path.getTypeAnnotation(); expect(t.isNumberTypeAnnotation(type)).toBeTruthy(); }); - it("should infer indirect constant identifier", function() { + it("should infer indirect constant identifier", function () { const path = getPath("const x = 0; const y = x; y").get( "body.2.expression", ); const type = path.getTypeAnnotation(); expect(t.isNumberTypeAnnotation(type)).toBeTruthy(); }); - it("should infer identifier type from if statement (===)", function() { + it("should infer identifier type from if statement (===)", function () { const path = getPath( `function test(x) { if (x === true) x; @@ -264,7 +226,7 @@ describe("inference", function() { const type = path.getTypeAnnotation(); expect(t.isBooleanTypeAnnotation(type)).toBeTruthy(); }); - it("should infer identifier type from if statement (typeof)", function() { + it("should infer identifier type from if statement (typeof)", function () { let path = getPath( `function test(x) { if (typeof x == 'string') x; @@ -280,7 +242,7 @@ describe("inference", function() { type = path.getTypeAnnotation(); expect(t.isNumberTypeAnnotation(type)).toBeTruthy(); }); - it("should infer identifier type from if statement (&&)", function() { + it("should infer identifier type from if statement (&&)", function () { let path = getPath( `function test(x) { if (typeof x == 'string' && x === 3) x; @@ -305,7 +267,7 @@ describe("inference", function() { type = path.getTypeAnnotation(); expect(t.isStringTypeAnnotation(type)).toBeTruthy(); }); - it("should infer identifier type from if statement (||)", function() { + it("should infer identifier type from if statement (||)", function () { const path = getPath( `function test(x) { if (typeof x == 'string' || x === 3) x; @@ -314,7 +276,7 @@ describe("inference", function() { const type = path.getTypeAnnotation(); expect(t.isAnyTypeAnnotation(type)).toBeTruthy(); }); - it("should not infer identifier type from incorrect binding", function() { + it("should not infer identifier type from incorrect binding", function () { const path = getPath( `function outer(x) { if (x === 3) { diff --git a/packages/babel-traverse/test/introspection.js b/packages/babel-traverse/test/introspection.js index 416fcd1999..481561ba9d 100644 --- a/packages/babel-traverse/test/introspection.js +++ b/packages/babel-traverse/test/introspection.js @@ -5,7 +5,7 @@ function getPath(code, options = { sourceType: "script" }) { const ast = parse(code, options); let path; traverse(ast, { - Program: function(_path) { + Program: function (_path) { path = _path; _path.stop(); }, @@ -13,10 +13,10 @@ function getPath(code, options = { sourceType: "script" }) { return path; } -describe("path/introspection", function() { - describe("isInStrictMode", function() { - describe("classes", function() { - it("returns parent's strictness for class", function() { +describe("path/introspection", function () { + describe("isInStrictMode", function () { + describe("classes", function () { + it("returns parent's strictness for class", function () { let program = getPath("class Test extends Super {}"); let klass = program.get("body.0"); expect(klass.isInStrictMode()).toBeFalsy(); @@ -26,28 +26,28 @@ describe("path/introspection", function() { expect(klass.isInStrictMode()).toBeTruthy(); }); - it("returns true for class id", function() { + it("returns true for class id", function () { const program = getPath("class Test extends Super {}"); const id = program.get("body.0.id"); expect(id.isInStrictMode()).toBeTruthy(); }); - it("returns true for superClass", function() { + it("returns true for superClass", function () { const program = getPath("class Test extends Super {}"); const superClass = program.get("body.0.superClass"); expect(superClass.isInStrictMode()).toBeTruthy(); }); - it("returns true for method", function() { + it("returns true for method", function () { const program = getPath("class Test { test() {} }"); const method = program.get("body.0.body.body.0"); expect(method.isInStrictMode()).toBeTruthy(); }); }); - describe("program", function() { - describe("when script", function() { - it("returns true when strict", function() { + describe("program", function () { + describe("when script", function () { + it("returns true when strict", function () { let program = getPath(`test;`); expect(program.isInStrictMode()).toBeFalsy(); @@ -56,16 +56,16 @@ describe("path/introspection", function() { }); }); - describe("when module", function() { - it("returns true", function() { + describe("when module", function () { + it("returns true", function () { const program = getPath(`test;`, { sourceType: "module" }); expect(program.isInStrictMode()).toBeTruthy(); }); }); }); - describe("function", function() { - it("returns parent's strictness for function", function() { + describe("function", function () { + it("returns parent's strictness for function", function () { let program = getPath("function test() {}"); let fn = program.get("body.0"); expect(fn.isInStrictMode()).toBeFalsy(); @@ -79,7 +79,7 @@ describe("path/introspection", function() { expect(fn.isInStrictMode()).toBeTruthy(); }); - it("returns function's strictness for id", function() { + it("returns function's strictness for id", function () { let program = getPath("function test(a) {}"); let id = program.get("body.0.id"); expect(id.isInStrictMode()).toBeFalsy(); @@ -89,7 +89,7 @@ describe("path/introspection", function() { expect(id.isInStrictMode()).toBeTruthy(); }); - it("returns function's strictness for parameters", function() { + it("returns function's strictness for parameters", function () { let program = getPath("function test(a) {}"); let param = program.get("body.0.params.0"); expect(param.isInStrictMode()).toBeFalsy(); diff --git a/packages/babel-traverse/test/modification.js b/packages/babel-traverse/test/modification.js index a4ccc90823..6158455476 100644 --- a/packages/babel-traverse/test/modification.js +++ b/packages/babel-traverse/test/modification.js @@ -7,7 +7,7 @@ function getPath(code, parserOpts) { const ast = parse(code, parserOpts); let path; traverse(ast, { - Program: function(_path) { + Program: function (_path) { path = _path.get("body.0"); _path.stop(); }, @@ -20,16 +20,16 @@ function generateCode(path) { return generate(path.parentPath.node).code; } -describe("modification", function() { - describe("pushContainer", function() { - it("pushes identifier into params", function() { +describe("modification", function () { + describe("pushContainer", function () { + it("pushes identifier into params", function () { const rootPath = getPath("function test(a) {}"); rootPath.pushContainer("params", t.identifier("b")); expect(generateCode(rootPath)).toBe("function test(a, b) {}"); }); - it("pushes identifier into block", function() { + it("pushes identifier into block", function () { const rootPath = getPath("function test(a) {}"); const path = rootPath.get("body"); path.pushContainer("body", t.expressionStatement(t.identifier("b"))); @@ -37,11 +37,11 @@ describe("modification", function() { expect(generateCode(rootPath)).toBe("function test(a) {\n b;\n}"); }); - it("properly handles more than one arguments", function() { + it("properly handles more than one arguments", function () { const code = "foo(a, b);"; const ast = parse(code); traverse(ast, { - CallExpression: function(path) { + CallExpression: function (path) { path.pushContainer("arguments", t.identifier("d")); expect(generateCode(path)).toBe("foo(a, b, d);"); path.pushContainer("arguments", t.stringLiteral("s")); @@ -50,15 +50,15 @@ describe("modification", function() { }); }); }); - describe("unshiftContainer", function() { - it("unshifts identifier into params", function() { + describe("unshiftContainer", function () { + it("unshifts identifier into params", function () { const rootPath = getPath("function test(a) {}"); rootPath.unshiftContainer("params", t.identifier("b")); expect(generateCode(rootPath)).toBe("function test(b, a) {}"); }); - it("unshifts identifier into block", function() { + it("unshifts identifier into block", function () { const rootPath = getPath("function test(a) {}"); const path = rootPath.get("body"); path.unshiftContainer("body", t.expressionStatement(t.identifier("b"))); @@ -66,11 +66,11 @@ describe("modification", function() { expect(generateCode(rootPath)).toBe("function test(a) {\n b;\n}"); }); - it("properly handles more than one arguments", function() { + it("properly handles more than one arguments", function () { const code = "foo(a, b);"; const ast = parse(code); traverse(ast, { - CallExpression: function(path) { + CallExpression: function (path) { path.unshiftContainer("arguments", t.identifier("d")); expect(generateCode(path)).toBe("foo(d, a, b);"); path.unshiftContainer("arguments", t.stringLiteral("s")); @@ -80,8 +80,8 @@ describe("modification", function() { }); }); - describe("insertBefore", function() { - it("returns inserted path with BlockStatement", function() { + describe("insertBefore", function () { + it("returns inserted path with BlockStatement", function () { const rootPath = getPath("if (x) { y; }"); const path = rootPath.get("consequent.body.0"); const result = path.insertBefore(t.identifier("b")); @@ -92,7 +92,7 @@ describe("modification", function() { expect(generateCode(rootPath)).toBe("if (x) {\n b\n y;\n}"); }); - it("returns inserted path without BlockStatement", function() { + it("returns inserted path without BlockStatement", function () { const rootPath = getPath("if (x) y;"); const path = rootPath.get("consequent"); const result = path.insertBefore(t.identifier("b")); @@ -103,7 +103,7 @@ describe("modification", function() { expect(generateCode(rootPath)).toBe("if (x) {\n b\n y;\n}"); }); - it("returns inserted path without BlockStatement without ExpressionStatement", function() { + it("returns inserted path without BlockStatement without ExpressionStatement", function () { const rootPath = getPath("if (x) for (var i = 0; i < 0; i++) {}"); const path = rootPath.get("consequent"); const result = path.insertBefore(t.identifier("b")); @@ -116,7 +116,7 @@ describe("modification", function() { ); }); - it("returns inserted path with BlockStatement without ExpressionStatement", function() { + it("returns inserted path with BlockStatement without ExpressionStatement", function () { const rootPath = getPath("if (x) { for (var i = 0; i < 0; i++) {} }"); const path = rootPath.get("consequent.body.0"); const result = path.insertBefore(t.identifier("b")); @@ -129,16 +129,16 @@ describe("modification", function() { ); }); - it("returns inserted path with nested JSXElement", function() { + it("returns inserted path with nested JSXElement", function () { const ast = parse("
foo
", { plugins: ["jsx"], }); let path; traverse(ast, { - Program: function(_path) { + Program: function (_path) { path = _path.get("body.0"); }, - JSXElement: function(path) { + JSXElement: function (path) { const tagName = path.node.openingElement.name.name; if (tagName !== "span") return; path.insertBefore( @@ -155,8 +155,8 @@ describe("modification", function() { ); }); - describe("when the parent is an export declaration inserts the node before", function() { - it("the ExportNamedDeclaration", function() { + describe("when the parent is an export declaration inserts the node before", function () { + it("the ExportNamedDeclaration", function () { const bodyPath = getPath("export function a() {}", { sourceType: "module", }).parentPath; @@ -167,7 +167,7 @@ describe("modification", function() { expect(bodyPath.get("body.0").node).toEqual(t.identifier("x")); }); - it("the ExportDefaultDeclaration, if a declaration is exported", function() { + it("the ExportDefaultDeclaration, if a declaration is exported", function () { const bodyPath = getPath("export default function () {}", { sourceType: "module", }).parentPath; @@ -178,7 +178,7 @@ describe("modification", function() { expect(bodyPath.get("body.0").node).toEqual(t.identifier("x")); }); - it("the exported expression", function() { + it("the exported expression", function () { const declPath = getPath("export default 2;", { sourceType: "module", }); @@ -190,8 +190,8 @@ describe("modification", function() { }); }); - describe("insertAfter", function() { - it("returns inserted path with BlockStatement with ExpressionStatement", function() { + describe("insertAfter", function () { + it("returns inserted path with BlockStatement with ExpressionStatement", function () { const rootPath = getPath("if (x) { y; }"); const path = rootPath.get("consequent.body.0"); const result = path.insertAfter(t.identifier("b")); @@ -202,7 +202,7 @@ describe("modification", function() { expect(generateCode(rootPath)).toBe("if (x) {\n y;\n b\n}"); }); - it("returns inserted path without BlockStatement with ExpressionStatement", function() { + it("returns inserted path without BlockStatement with ExpressionStatement", function () { const rootPath = getPath("if (x) y;"); const path = rootPath.get("consequent"); const result = path.insertAfter(t.identifier("b")); @@ -213,7 +213,7 @@ describe("modification", function() { expect(generateCode(rootPath)).toBe("if (x) {\n y;\n b\n}"); }); - it("returns inserted path without BlockStatement without ExpressionStatement", function() { + it("returns inserted path without BlockStatement without ExpressionStatement", function () { const rootPath = getPath("if (x) for (var i = 0; i < 0; i++) {}"); const path = rootPath.get("consequent"); const result = path.insertAfter(t.identifier("b")); @@ -226,7 +226,7 @@ describe("modification", function() { ); }); - it("returns inserted path with BlockStatement without ExpressionStatement", function() { + it("returns inserted path with BlockStatement without ExpressionStatement", function () { const rootPath = getPath("if (x) { for (var i = 0; i < 0; i++) {} }"); const path = rootPath.get("consequent.body.0"); const result = path.insertAfter(t.identifier("b")); @@ -239,16 +239,16 @@ describe("modification", function() { ); }); - it("returns inserted path with nested JSXElement", function() { + it("returns inserted path with nested JSXElement", function () { const ast = parse("
foo
", { plugins: ["jsx"], }); let path; traverse(ast, { - Program: function(_path) { + Program: function (_path) { path = _path.get("body.0"); }, - JSXElement: function(path) { + JSXElement: function (path) { const tagName = path.node.openingElement.name.name; if (tagName !== "span") return; path.insertAfter( @@ -265,8 +265,8 @@ describe("modification", function() { ); }); - describe("when the parent is an export declaration inserts the node after", function() { - it("the ExportNamedDeclaration", function() { + describe("when the parent is an export declaration inserts the node after", function () { + it("the ExportNamedDeclaration", function () { const bodyPath = getPath("export function a() {}", { sourceType: "module", }).parentPath; @@ -279,7 +279,7 @@ describe("modification", function() { ); }); - it("the ExportDefaultDeclaration, if a declaration is exported", function() { + it("the ExportDefaultDeclaration, if a declaration is exported", function () { const bodyPath = getPath("export default function () {}", { sourceType: "module", }).parentPath; @@ -292,7 +292,7 @@ describe("modification", function() { ); }); - it("the exported expression", function() { + it("the exported expression", function () { const bodyPath = getPath("export default 2;", { sourceType: "module", }).parentPath; diff --git a/packages/babel-traverse/test/removal.js b/packages/babel-traverse/test/removal.js index 46ad1a438c..0c15e03013 100644 --- a/packages/babel-traverse/test/removal.js +++ b/packages/babel-traverse/test/removal.js @@ -6,7 +6,7 @@ function getPath(code) { const ast = parse(code); let path; traverse(ast, { - Program: function(_path) { + Program: function (_path) { path = _path; _path.stop(); }, @@ -19,14 +19,11 @@ function generateCode(path) { return generate(path.node).code; } -describe("removal", function() { - describe("ArrowFunction", function() { - it("remove body", function() { +describe("removal", function () { + describe("ArrowFunction", function () { + it("remove body", function () { const rootPath = getPath("x = () => b;"); - const path = rootPath - .get("body")[0] - .get("expression") - .get("right"); + const path = rootPath.get("body")[0].get("expression").get("right"); const body = path.get("body"); body.remove(); @@ -34,10 +31,10 @@ describe("removal", function() { }); }); - it("remove with noScope", function() { + it("remove with noScope", function () { const ast = parse("a=1"); traverse(ast, { - AssignmentExpression: function(path) { + AssignmentExpression: function (path) { path.remove(); }, noScope: true, diff --git a/packages/babel-traverse/test/replacement.js b/packages/babel-traverse/test/replacement.js index 6d54972611..b28ef7c0e4 100644 --- a/packages/babel-traverse/test/replacement.js +++ b/packages/babel-traverse/test/replacement.js @@ -3,9 +3,9 @@ import { parse } from "@babel/parser"; import generate from "@babel/generator"; import * as t from "@babel/types"; -describe("path/replacement", function() { - describe("replaceWith", function() { - it("replaces declaration in ExportDefaultDeclaration node", function() { +describe("path/replacement", function () { + describe("replaceWith", function () { + it("replaces declaration in ExportDefaultDeclaration node", function () { const ast = parse("export default function() {};", { sourceType: "module", }); @@ -28,9 +28,9 @@ describe("path/replacement", function() { expect(ast.program.body[0].declaration.type).toBe("ArrayExpression"); }); - it("throws error when trying to replace Program with a non-Program node", function() { + it("throws error when trying to replace Program with a non-Program node", function () { const ast = parse("var x = 3;"); - expect(function() { + expect(function () { traverse(ast, { Program(path) { path.replaceWith(t.identifier("a")); @@ -41,9 +41,9 @@ describe("path/replacement", function() { ); }); - it("throws error when used with an array of nodes", function() { + it("throws error when used with an array of nodes", function () { const ast = parse("function abc() {}; var test = 17;"); - expect(function() { + expect(function () { traverse(ast, { NumericLiteral(path) { path.replaceWith([ @@ -58,11 +58,11 @@ describe("path/replacement", function() { ); }); - it("throws error when used with source string", function() { + it("throws error when used with source string", function () { const ast = parse( "(function() { var x = 3; var y = 17; var c = x + y; })();", ); - expect(function() { + expect(function () { traverse(ast, { BinaryExpression(path) { path.replaceWith("17 + 23"); @@ -73,9 +73,9 @@ describe("path/replacement", function() { ); }); - it("throws error when trying to replace removed node", function() { + it("throws error when trying to replace removed node", function () { const ast = parse("var z = 'abc';"); - expect(function() { + expect(function () { traverse(ast, { StringLiteral(path) { path.remove(); @@ -85,9 +85,9 @@ describe("path/replacement", function() { }).toThrow(/You can't replace this node, we've already removed it/); }); - it("throws error when passed a falsy value", function() { + it("throws error when passed a falsy value", function () { const ast = parse("var z = 'abc';"); - expect(function() { + expect(function () { traverse(ast, { StringLiteral(path) { path.replaceWith(); diff --git a/packages/babel-traverse/test/scope.js b/packages/babel-traverse/test/scope.js index d62675a5b5..dfd4bb2e82 100644 --- a/packages/babel-traverse/test/scope.js +++ b/packages/babel-traverse/test/scope.js @@ -7,7 +7,7 @@ function getPath(code, options) { typeof code === "string" ? parse(code, options) : createNode(code); let path; traverse(ast, { - Program: function(_path) { + Program: function (_path) { path = _path; _path.stop(); }, @@ -19,7 +19,7 @@ function getIdentifierPath(code) { const ast = parse(code); let nodePath; traverse(ast, { - Identifier: function(path) { + Identifier: function (path) { nodePath = path; path.stop(); }, @@ -49,13 +49,13 @@ function createNode(node) { describe("scope", () => { describe("binding paths", () => { - it("function declaration id", function() { + it("function declaration id", function () { expect( getPath("function foo() {}").scope.getBinding("foo").path.type, ).toBe("FunctionDeclaration"); }); - it("function expression id", function() { + it("function expression id", function () { expect( getPath("(function foo() {})") .get("body")[0] @@ -64,7 +64,7 @@ describe("scope", () => { ).toBe("FunctionExpression"); }); - it("function param", function() { + it("function param", function () { expect( getPath("(function (foo) {})") .get("body")[0] @@ -73,7 +73,7 @@ describe("scope", () => { ).toBe("Identifier"); }); - describe("function parameter expression", function() { + describe("function parameter expression", function () { it("should not have visibility of declarations inside function body", () => { expect( getPath( @@ -92,7 +92,7 @@ describe("scope", () => { }); }); - it("variable declaration", function() { + it("variable declaration", function () { expect(getPath("var foo = null;").scope.getBinding("foo").path.type).toBe( "VariableDeclarator", ); @@ -108,7 +108,7 @@ describe("scope", () => { ).toBe("VariableDeclarator"); }); - it("declare var", function() { + it("declare var", function () { expect( getPath("declare var foo;", { plugins: ["flow"] }).scope.getBinding( "foo", @@ -116,7 +116,7 @@ describe("scope", () => { ).toBe("DeclareVariable"); }); - it("declare function", function() { + it("declare function", function () { expect( getPath("declare function foo(): void;", { plugins: ["flow"], @@ -124,7 +124,7 @@ describe("scope", () => { ).toBe("DeclareFunction"); }); - it("declare module", function() { + it("declare module", function () { expect( getPath("declare module foo {};", { plugins: ["flow"], @@ -132,7 +132,7 @@ describe("scope", () => { ).toBe("DeclareModule"); }); - it("declare type alias", function() { + it("declare type alias", function () { expect( getPath("declare type foo = string;", { plugins: ["flow"], @@ -140,7 +140,7 @@ describe("scope", () => { ).toBe("DeclareTypeAlias"); }); - it("declare opaque type", function() { + it("declare opaque type", function () { expect( getPath("declare opaque type foo;", { plugins: ["flow"], @@ -148,7 +148,7 @@ describe("scope", () => { ).toBe("DeclareOpaqueType"); }); - it("declare interface", function() { + it("declare interface", function () { expect( getPath("declare interface Foo {};", { plugins: ["flow"], @@ -156,7 +156,7 @@ describe("scope", () => { ).toBe("DeclareInterface"); }); - it("type alias", function() { + it("type alias", function () { expect( getPath("type foo = string;", { plugins: ["flow"], @@ -164,7 +164,7 @@ describe("scope", () => { ).toBe("TypeAlias"); }); - it("opaque type alias", function() { + it("opaque type alias", function () { expect( getPath("opaque type foo = string;", { plugins: ["flow"], @@ -172,7 +172,7 @@ describe("scope", () => { ).toBe("OpaqueType"); }); - it("interface", function() { + it("interface", function () { expect( getPath("interface Foo {};", { plugins: ["flow"], @@ -180,7 +180,7 @@ describe("scope", () => { ).toBe("InterfaceDeclaration"); }); - it("import type", function() { + it("import type", function () { expect( getPath("import type {Foo} from 'foo';", { plugins: ["flow"], @@ -188,7 +188,7 @@ describe("scope", () => { ).toBe("ImportSpecifier"); }); - it("variable constantness", function() { + it("variable constantness", function () { expect(getPath("var a = 1;").scope.getBinding("a").constant).toBe(true); expect(getPath("var a = 1; a = 2;").scope.getBinding("a").constant).toBe( false, @@ -201,7 +201,7 @@ describe("scope", () => { ).toBe(false); }); - it("purity", function() { + it("purity", function () { expect( getPath("({ x: 1, foo() { return 1 } })") .get("body")[0] @@ -215,16 +215,10 @@ describe("scope", () => { .isPure(), ).toBeFalsy(); expect( - getPath("`${a}`") - .get("body")[0] - .get("expression") - .isPure(), + getPath("`${a}`").get("body")[0].get("expression").isPure(), ).toBeFalsy(); expect( - getPath("let a = 1; `${a}`") - .get("body")[1] - .get("expression") - .isPure(), + getPath("let a = 1; `${a}`").get("body")[1].get("expression").isPure(), ).toBeTruthy(); expect( getPath("let a = 1; `${a++}`") @@ -233,20 +227,14 @@ describe("scope", () => { .isPure(), ).toBeFalsy(); expect( - getPath("tagged`foo`") - .get("body")[0] - .get("expression") - .isPure(), + getPath("tagged`foo`").get("body")[0].get("expression").isPure(), ).toBeFalsy(); expect( - getPath("String.raw`foo`") - .get("body")[0] - .get("expression") - .isPure(), + getPath("String.raw`foo`").get("body")[0].get("expression").isPure(), ).toBeTruthy(); }); - test("label", function() { + test("label", function () { expect(getPath("foo: { }").scope.getBinding("foo")).toBeUndefined(); expect(getPath("foo: { }").scope.getLabel("foo").type).toBe( "LabeledStatement", @@ -262,7 +250,7 @@ describe("scope", () => { ).toBe("_foo"); }); - test("generateUid collision check with labels", function() { + test("generateUid collision check with labels", function () { expect( getPath( ` @@ -282,7 +270,7 @@ describe("scope", () => { ).toBe("_foo3"); }); - it("reference paths", function() { + it("reference paths", function () { const path = getIdentifierPath("function square(n) { return n * n}"); const referencePaths = path.context.scope.bindings.n.referencePaths; expect(referencePaths).toHaveLength(2); @@ -296,7 +284,7 @@ describe("scope", () => { }); }); - it("class identifier available in class scope after crawl", function() { + it("class identifier available in class scope after crawl", function () { const path = getPath("class a { build() { return new a(); } }"); path.scope.crawl(); @@ -310,7 +298,7 @@ describe("scope", () => { expect(path.scope.bindings.a).toBe(path.get("body[0]").scope.bindings.a); }); - it("references after re-crawling", function() { + it("references after re-crawling", function () { const path = getPath("function Foo() { var _jsx; }"); path.scope.crawl(); @@ -319,7 +307,7 @@ describe("scope", () => { expect(path.scope.references._jsx).toBeTruthy(); }); - test("generateUid collision check after re-crawling", function() { + test("generateUid collision check after re-crawling", function () { const path = getPath("function Foo() { var _jsx; }"); path.scope.crawl(); @@ -328,7 +316,7 @@ describe("scope", () => { expect(path.scope.generateUid("jsx")).toBe("_jsx2"); }); - test("generateUid collision check after re-crawling (function expression local id)", function() { + test("generateUid collision check after re-crawling (function expression local id)", function () { const path = getPath("var fn = function _name(){}"); path.scope.crawl(); @@ -337,7 +325,7 @@ describe("scope", () => { expect(path.scope.generateUid("name")).toBe("_name2"); }); - test("generateUid collision check after re-crawling (function params)", function() { + test("generateUid collision check after re-crawling (function params)", function () { const path = getPath("[].map(_unicorn => [_unicorn])"); path.scope.crawl(); @@ -346,7 +334,7 @@ describe("scope", () => { expect(path.scope.generateUid("unicorn")).toBe("_unicorn2"); }); - test("generateUid collision check after re-crawling (catch clause)", function() { + test("generateUid collision check after re-crawling (catch clause)", function () { const path = getPath("try {} catch (_err) {}"); path.scope.crawl(); @@ -355,7 +343,7 @@ describe("scope", () => { expect(path.scope.generateUid("err")).toBe("_err2"); }); - test("generateUid collision check after re-crawling (class expression local id)", function() { + test("generateUid collision check after re-crawling (class expression local id)", function () { const path = getPath("var C = class _Cls{}"); path.scope.crawl(); @@ -373,7 +361,7 @@ describe("scope", () => { */ describe("catch", () => { // try {} catch (e) { let e; } - const createTryCatch = function(kind) { + const createTryCatch = function (kind) { return t.tryStatement( t.blockStatement([]), t.catchClause( @@ -444,7 +432,7 @@ describe("scope", () => { ["class", "function", false], ]; - const createNode = function(kind) { + const createNode = function (kind) { switch (kind) { case "let": case "const": @@ -467,7 +455,7 @@ describe("scope", () => { } }; - const createAST = function(kind1, kind2) { + const createAST = function (kind1, kind2) { return [createNode(kind1), createNode(kind2)]; }; diff --git a/packages/babel-traverse/test/traverse.js b/packages/babel-traverse/test/traverse.js index 3d21529cea..d2492a71b3 100644 --- a/packages/babel-traverse/test/traverse.js +++ b/packages/babel-traverse/test/traverse.js @@ -3,7 +3,7 @@ import traverse from "../lib"; import { parse } from "@babel/parser"; import * as t from "@babel/types"; -describe("traverse", function() { +describe("traverse", function () { const code = ` var foo = "bar"; this.test = "wow"; @@ -12,7 +12,7 @@ describe("traverse", function() { const program = ast.program; const body = program.body; - it("traverse replace", function() { + it("traverse replace", function () { const replacement = { type: "StringLiteral", value: "foo", @@ -20,7 +20,7 @@ describe("traverse", function() { const ast2 = cloneDeep(program); traverse(ast2, { - enter: function(path) { + enter: function (path) { if (path.node.type === "ThisExpression") path.replaceWith(replacement); }, }); @@ -28,7 +28,7 @@ describe("traverse", function() { expect(ast2.body[1].expression.left.object).toBe(replacement); }); - it("traverse", function() { + it("traverse", function () { const expected = [ body[0], body[0].declarations[0], @@ -45,7 +45,7 @@ describe("traverse", function() { const actual = []; traverse(program, { - enter: function(path) { + enter: function (path) { actual.push(path.node); }, }); @@ -53,15 +53,15 @@ describe("traverse", function() { expect(actual).toEqual(expected); }); - it("traverse falsy parent", function() { + it("traverse falsy parent", function () { traverse(null, { - enter: function() { + enter: function () { throw new Error("should not be ran"); }, }); }); - it("traverse blacklistTypes", function() { + it("traverse blacklistTypes", function () { const expected = [ body[0], body[0].declarations[0], @@ -76,7 +76,7 @@ describe("traverse", function() { traverse(program, { blacklist: ["MemberExpression"], - enter: function(path) { + enter: function (path) { actual.push(path.node); }, }); @@ -84,7 +84,7 @@ describe("traverse", function() { expect(actual).toEqual(expected); }); - it("hasType", function() { + it("hasType", function () { expect(traverse.hasType(ast, "ThisExpression")).toBeTruthy(); expect( traverse.hasType(ast, "ThisExpression", ["AssignmentExpression"]), @@ -101,7 +101,7 @@ describe("traverse", function() { expect(traverse.hasType(ast, "ArrowFunctionExpression")).toBeFalsy(); }); - it("clearCache", function() { + it("clearCache", function () { const paths = []; const scopes = []; traverse(ast, { @@ -124,13 +124,13 @@ describe("traverse", function() { }, }); - scopes2.forEach(function(_, i) { + scopes2.forEach(function (_, i) { expect(scopes[i]).not.toBe(scopes2[i]); expect(paths[i]).not.toBe(paths2[i]); }); }); - it("clearPath", function() { + it("clearPath", function () { const paths = []; traverse(ast, { enter(path) { @@ -147,12 +147,12 @@ describe("traverse", function() { }, }); - paths2.forEach(function(p, i) { + paths2.forEach(function (p, i) { expect(p).not.toBe(paths[i]); }); }); - it("clearScope", function() { + it("clearScope", function () { const scopes = []; traverse(ast, { enter(path) { @@ -171,13 +171,13 @@ describe("traverse", function() { }, }); - scopes2.forEach(function(p, i) { + scopes2.forEach(function (p, i) { expect(p).not.toBe(scopes[i]); }); }); - describe("path.skip()", function() { - it("replaced paths can be skipped", function() { + describe("path.skip()", function () { + it("replaced paths can be skipped", function () { const ast = parse("id"); let skipped; @@ -198,7 +198,7 @@ describe("traverse", function() { // Skipped: see the comment in the `NodePath.requeue` method. // eslint-disable-next-line jest/no-disabled-tests - it.skip("skipped and requeued paths should be visited", function() { + it.skip("skipped and requeued paths should be visited", function () { const ast = parse("id"); let visited = false; diff --git a/packages/babel-types/scripts/generators/docs.js b/packages/babel-types/scripts/generators/docs.js index 340dbbc113..169894895b 100644 --- a/packages/babel-types/scripts/generators/docs.js +++ b/packages/babel-types/scripts/generators/docs.js @@ -39,7 +39,7 @@ const customTypes = { }; Object.keys(types.BUILDER_KEYS) .sort() - .forEach(function(key) { + .forEach(function (key) { readme.push("### " + key[0].toLowerCase() + key.substr(1)); readme.push("```javascript"); readme.push( @@ -63,7 +63,7 @@ Object.keys(types.BUILDER_KEYS) readme.push( "Aliases: " + types.ALIAS_KEYS[key] - .map(function(key) { + .map(function (key) { return "`" + key + "`"; }) .join(", ") @@ -71,7 +71,7 @@ Object.keys(types.BUILDER_KEYS) readme.push(""); } Object.keys(types.NODE_FIELDS[key]) - .sort(function(fieldA, fieldB) { + .sort(function (fieldA, fieldB) { const indexA = types.BUILDER_KEYS[key].indexOf(fieldA); const indexB = types.BUILDER_KEYS[key].indexOf(fieldB); if (indexA === indexB) return fieldA < fieldB ? -1 : 1; @@ -79,7 +79,7 @@ Object.keys(types.BUILDER_KEYS) if (indexB === -1) return -1; return indexA - indexB; }) - .forEach(function(field) { + .forEach(function (field) { const defaultValue = types.NODE_FIELDS[key][field].default; const fieldDescription = ["`" + field + "`"]; const validator = types.NODE_FIELDS[key][field].validate; diff --git a/packages/babel-types/scripts/generators/flow.js b/packages/babel-types/scripts/generators/flow.js index 58c1a1614a..50f20bc611 100644 --- a/packages/babel-types/scripts/generators/flow.js +++ b/packages/babel-types/scripts/generators/flow.js @@ -240,10 +240,7 @@ for (const type in t.FLIPPED_ALIAS_KEYS) { } code += `\ndeclare module "@babel/types" { - ${lines - .join("\n") - .replace(/\n/g, "\n ") - .trim()} + ${lines.join("\n").replace(/\n/g, "\n ").trim()} }\n`; // diff --git a/packages/babel-types/src/converters/toIdentifier.js b/packages/babel-types/src/converters/toIdentifier.js index 21ed978484..50337f70c0 100644 --- a/packages/babel-types/src/converters/toIdentifier.js +++ b/packages/babel-types/src/converters/toIdentifier.js @@ -11,7 +11,7 @@ export default function toIdentifier(name: string): string { name = name.replace(/^[-0-9]+/, ""); // camel case - name = name.replace(/[-\s]+(.)?/g, function(match, c) { + name = name.replace(/[-\s]+(.)?/g, function (match, c) { return c ? c.toUpperCase() : ""; }); diff --git a/packages/babel-types/src/converters/toKeyAlias.js b/packages/babel-types/src/converters/toKeyAlias.js index 71b4ef49d5..6515a34d54 100644 --- a/packages/babel-types/src/converters/toKeyAlias.js +++ b/packages/babel-types/src/converters/toKeyAlias.js @@ -32,7 +32,7 @@ export default function toKeyAlias( toKeyAlias.uid = 0; -toKeyAlias.increment = function() { +toKeyAlias.increment = function () { if (toKeyAlias.uid >= Number.MAX_SAFE_INTEGER) { return (toKeyAlias.uid = 0); } else { diff --git a/packages/babel-types/src/definitions/core.js b/packages/babel-types/src/definitions/core.js index a0f7865b9d..9dca26a5d4 100644 --- a/packages/babel-types/src/definitions/core.js +++ b/packages/babel-types/src/definitions/core.js @@ -40,7 +40,7 @@ defineType("ArrayExpression", { defineType("AssignmentExpression", { fields: { operator: { - validate: (function() { + validate: (function () { if (!process.env.BABEL_TYPES_8_BREAKING) { return assertValueType("string"); } @@ -48,7 +48,7 @@ defineType("AssignmentExpression", { const identifier = assertOneOf(...ASSIGNMENT_OPERATORS); const pattern = assertOneOf("="); - return function(node, key, val) { + return function (node, key, val) { const validator = is("Pattern", node.left) ? pattern : identifier; validator(node, key, val); }; @@ -80,11 +80,11 @@ defineType("BinaryExpression", { validate: assertOneOf(...BINARY_OPERATORS), }, left: { - validate: (function() { + validate: (function () { const expression = assertNodeType("Expression"); const inOp = assertNodeType("Expression", "PrivateName"); - return function(node, key, val) { + return function (node, key, val) { const validator = node.operator === "in" ? inOp : expression; validator(node, key, val); }; @@ -400,12 +400,12 @@ defineType("FunctionDeclaration", { "Pureish", "Declaration", ], - validate: (function() { + validate: (function () { if (!process.env.BABEL_TYPES_8_BREAKING) return () => {}; const identifier = assertNodeType("Identifier"); - return function(parent, key, node) { + return function (parent, key, node) { if (!is("ExportDefaultDeclaration", parent)) { identifier(node, "id", node.id); } @@ -457,7 +457,7 @@ defineType("Identifier", { fields: { ...patternLikeCommon, name: { - validate: chain(assertValueType("string"), function(node, key, val) { + validate: chain(assertValueType("string"), function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; if (!isValidIdentifier(val, false)) { @@ -583,7 +583,7 @@ defineType("RegExpLiteral", { validate: assertValueType("string"), }, flags: { - validate: chain(assertValueType("string"), function(node, key, val) { + validate: chain(assertValueType("string"), function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; const invalid = /[^gimsuy]/.exec(val); @@ -622,11 +622,11 @@ defineType("MemberExpression", { validate: assertNodeType("Expression"), }, property: { - validate: (function() { + validate: (function () { const normal = assertNodeType("Identifier", "PrivateName"); const computed = assertNodeType("Expression"); - return function(node, key, val) { + return function (node, key, val) { const validator = node.computed ? computed : normal; validator(node, key, val); }; @@ -711,7 +711,7 @@ defineType("ObjectMethod", { default: false, }, key: { - validate: (function() { + validate: (function () { const normal = assertNodeType( "Identifier", "StringLiteral", @@ -719,7 +719,7 @@ defineType("ObjectMethod", { ); const computed = assertNodeType("Expression"); - return function(node, key, val) { + return function (node, key, val) { const validator = node.computed ? computed : normal; validator(node, key, val); }; @@ -768,7 +768,7 @@ defineType("ObjectProperty", { default: false, }, key: { - validate: (function() { + validate: (function () { const normal = assertNodeType( "Identifier", "StringLiteral", @@ -776,7 +776,7 @@ defineType("ObjectProperty", { ); const computed = assertNodeType("Expression"); - return function(node, key, val) { + return function (node, key, val) { const validator = node.computed ? computed : normal; validator(node, key, val); }; @@ -790,7 +790,7 @@ defineType("ObjectProperty", { shorthand: { validate: chain( assertValueType("boolean"), - function(node, key, val) { + function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; if (val && node.computed) { @@ -799,7 +799,7 @@ defineType("ObjectProperty", { ); } }, - function(node, key, val) { + function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; if (val && !is("Identifier", node.key)) { @@ -821,11 +821,11 @@ defineType("ObjectProperty", { }, visitor: ["key", "value", "decorators"], aliases: ["UserWhitespacable", "Property", "ObjectMember"], - validate: (function() { + validate: (function () { const pattern = assertNodeType("Identifier", "Pattern"); const expression = assertNodeType("Expression"); - return function(parent, key, node) { + return function (parent, key, node) { if (!process.env.BABEL_TYPES_8_BREAKING) return; const validator = is("ObjectPattern", parent) ? pattern : expression; @@ -945,7 +945,7 @@ defineType("TryStatement", { aliases: ["Statement"], fields: { block: { - validate: chain(assertNodeType("BlockStatement"), function(node) { + validate: chain(assertNodeType("BlockStatement"), function (node) { if (!process.env.BABEL_TYPES_8_BREAKING) return; // This validator isn't put at the top level because we can run it @@ -1040,7 +1040,7 @@ defineType("VariableDeclarator", { visitor: ["id", "init"], fields: { id: { - validate: (function() { + validate: (function () { if (!process.env.BABEL_TYPES_8_BREAKING) { return assertNodeType("LVal"); } @@ -1052,7 +1052,7 @@ defineType("VariableDeclarator", { ); const without = assertNodeType("Identifier"); - return function(node, key, val) { + return function (node, key, val) { const validator = node.init ? normal : without; validator(node, key, val); }; diff --git a/packages/babel-types/src/definitions/es2015.js b/packages/babel-types/src/definitions/es2015.js index 535673bde5..05100548c1 100644 --- a/packages/babel-types/src/definitions/es2015.js +++ b/packages/babel-types/src/definitions/es2015.js @@ -186,10 +186,10 @@ defineType("ClassDeclaration", { optional: true, }, }, - validate: (function() { + validate: (function () { const identifier = assertNodeType("Identifier"); - return function(parent, key, node) { + return function (parent, key, node) { if (!process.env.BABEL_TYPES_8_BREAKING) return; if (!is("ExportDefaultDeclaration", parent)) { @@ -247,7 +247,7 @@ defineType("ExportNamedDeclaration", { optional: true, validate: chain( assertNodeType("Declaration"), - function(node, key, val) { + function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; // This validator isn't put at the top level because we can run it @@ -259,7 +259,7 @@ defineType("ExportNamedDeclaration", { ); } }, - function(node, key, val) { + function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; // This validator isn't put at the top level because we can run it @@ -276,7 +276,7 @@ defineType("ExportNamedDeclaration", { validate: chain( assertValueType("array"), assertEach( - (function() { + (function () { const sourced = assertNodeType( "ExportSpecifier", "ExportDefaultSpecifier", @@ -286,7 +286,7 @@ defineType("ExportNamedDeclaration", { if (!process.env.BABEL_TYPES_8_BREAKING) return sourced; - return function(node, key, val) { + return function (node, key, val) { const validator = node.source ? sourced : sourceless; validator(node, key, val); }; @@ -328,7 +328,7 @@ defineType("ForOfStatement", { ], fields: { left: { - validate: (function() { + validate: (function () { if (!process.env.BABEL_TYPES_8_BREAKING) { return assertNodeType("VariableDeclaration", "LVal"); } @@ -341,7 +341,7 @@ defineType("ForOfStatement", { "ObjectPattern", ); - return function(node, key, val) { + return function (node, key, val) { if (is("VariableDeclaration", val)) { declaration(node, key, val); } else { @@ -433,7 +433,7 @@ defineType("MetaProperty", { aliases: ["Expression"], fields: { meta: { - validate: chain(assertNodeType("Identifier"), function(node, key, val) { + validate: chain(assertNodeType("Identifier"), function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; let property; @@ -480,7 +480,7 @@ export const classMethodOrPropertyCommon = { }, key: { validate: chain( - (function() { + (function () { const normal = assertNodeType( "Identifier", "StringLiteral", @@ -488,7 +488,7 @@ export const classMethodOrPropertyCommon = { ); const computed = assertNodeType("Expression"); - return function(node: Object, key: string, val: any) { + return function (node: Object, key: string, val: any) { const validator = node.computed ? computed : normal; validator(node, key, val); }; @@ -643,13 +643,14 @@ defineType("TemplateLiteral", { validate: chain( assertValueType("array"), assertEach(assertNodeType("Expression")), - function(node, key, val) { + function (node, key, val) { if (node.quasis.length !== val.length + 1) { throw new TypeError( `Number of ${ node.type - } quasis should be exactly one more than the number of expressions.\nExpected ${val.length + - 1} quasis but got ${node.quasis.length}`, + } quasis should be exactly one more than the number of expressions.\nExpected ${ + val.length + 1 + } quasis but got ${node.quasis.length}`, ); } }, @@ -664,7 +665,7 @@ defineType("YieldExpression", { aliases: ["Expression", "Terminatorless"], fields: { delegate: { - validate: chain(assertValueType("boolean"), function(node, key, val) { + validate: chain(assertValueType("boolean"), function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; if (val && !node.argument) { diff --git a/packages/babel-types/src/definitions/experimental.js b/packages/babel-types/src/definitions/experimental.js index 5abd6cc486..3ccc2fcdd4 100644 --- a/packages/babel-types/src/definitions/experimental.js +++ b/packages/babel-types/src/definitions/experimental.js @@ -92,11 +92,11 @@ defineType("OptionalMemberExpression", { validate: assertNodeType("Expression"), }, property: { - validate: (function() { + validate: (function () { const normal = assertNodeType("Identifier"); const computed = assertNodeType("Expression"); - return function(node, key, val) { + return function (node, key, val) { const validator = node.computed ? computed : normal; validator(node, key, val); }; diff --git a/packages/babel-types/test/builders/es2015/templateElement.js b/packages/babel-types/test/builders/es2015/templateElement.js index 0e5985ae89..3afe2c1148 100644 --- a/packages/babel-types/test/builders/es2015/templateElement.js +++ b/packages/babel-types/test/builders/es2015/templateElement.js @@ -1,9 +1,9 @@ import * as t from "../../.."; -describe("builders", function() { - describe("es2015", function() { - describe("templateElement", function() { - it("should validate", function() { +describe("builders", function () { + describe("es2015", function () { + describe("templateElement", function () { + it("should validate", function () { expect( t.templateElement({ raw: "foo", cooked: "foo" }), ).toMatchSnapshot(); @@ -21,8 +21,8 @@ describe("builders", function() { expect(() => t.templateElement("foo")).toThrowErrorMatchingSnapshot(); }); }); - describe("templateLiteral", function() { - it("should validate", function() { + describe("templateLiteral", function () { + it("should validate", function () { const foo = t.templateElement({ raw: "foo" }); const bar = t.templateElement({ raw: "bar" }); diff --git a/packages/babel-types/test/builders/experimental/classProperty.js b/packages/babel-types/test/builders/experimental/classProperty.js index 3b35a1317c..396efe571e 100644 --- a/packages/babel-types/test/builders/experimental/classProperty.js +++ b/packages/babel-types/test/builders/experimental/classProperty.js @@ -1,9 +1,9 @@ import * as t from "../../.."; -describe("builders", function() { - describe("experimental", function() { - describe("classProperty", function() { - it("should validate", function() { +describe("builders", function () { + describe("experimental", function () { + describe("classProperty", function () { + it("should validate", function () { expect( t.classProperty(t.stringLiteral("test"), t.numericLiteral(1)), ).toMatchSnapshot(); diff --git a/packages/babel-types/test/builders/flow/createTypeAnnotationBasedOnTypeof.js b/packages/babel-types/test/builders/flow/createTypeAnnotationBasedOnTypeof.js index b313ba6935..d686e5c498 100644 --- a/packages/babel-types/test/builders/flow/createTypeAnnotationBasedOnTypeof.js +++ b/packages/babel-types/test/builders/flow/createTypeAnnotationBasedOnTypeof.js @@ -1,27 +1,27 @@ import { createTypeAnnotationBasedOnTypeof } from "../../.."; -describe("builders", function() { - describe("flow", function() { - describe("createTypeAnnotationBasedOnTypeof", function() { +describe("builders", function () { + describe("flow", function () { + describe("createTypeAnnotationBasedOnTypeof", function () { const values = { string: typeof "string", number: typeof 123, true: typeof true, object: typeof {}, undefined: typeof undefined, - function: typeof function() {}, + function: typeof function () {}, symbol: typeof Symbol(), }; for (const name in values) { const value = values[name]; - it(name, function() { + it(name, function () { const result = createTypeAnnotationBasedOnTypeof(value); expect(result).toMatchSnapshot(); }); } - it("invalid", function() { + it("invalid", function () { expect(() => createTypeAnnotationBasedOnTypeof("thisdoesnotexist"), ).toThrow(Error); diff --git a/packages/babel-types/test/builders/flow/declareClass.js b/packages/babel-types/test/builders/flow/declareClass.js index 38bbc0fd87..71cc376eaa 100644 --- a/packages/babel-types/test/builders/flow/declareClass.js +++ b/packages/babel-types/test/builders/flow/declareClass.js @@ -1,9 +1,9 @@ import * as t from "../../.."; -describe("builders", function() { - describe("flow", function() { - describe("declareClass", function() { - it("accept TypeParameterDeclaration as typeParameters", function() { +describe("builders", function () { + describe("flow", function () { + describe("declareClass", function () { + it("accept TypeParameterDeclaration as typeParameters", function () { const typeParameter = t.typeParameter(null, null, null); typeParameter.name = "T"; const declaredClass = t.declareClass( @@ -15,7 +15,7 @@ describe("builders", function() { expect(t.isDeclareClass(declaredClass)).toBe(true); }); - it("not accept typeParameterInstantiation as typeParameters", function() { + it("not accept typeParameterInstantiation as typeParameters", function () { expect(() => t.declareClass( t.identifier("A"), diff --git a/packages/babel-types/test/builders/typescript/tsTypeParameter.js b/packages/babel-types/test/builders/typescript/tsTypeParameter.js index 985d67909c..61ca0986d1 100644 --- a/packages/babel-types/test/builders/typescript/tsTypeParameter.js +++ b/packages/babel-types/test/builders/typescript/tsTypeParameter.js @@ -1,9 +1,9 @@ import * as t from "../../.."; -describe("builders", function() { - describe("typescript", function() { - describe("tsTypeParameter", function() { - it("accept name as argument for tsTypeParameter", function() { +describe("builders", function () { + describe("typescript", function () { + describe("tsTypeParameter", function () { + it("accept name as argument for tsTypeParameter", function () { const tsTypeParameter = t.tsTypeParameter( t.tsTypeReference(t.identifier("bar")), t.tsTypeReference(t.identifier("baz")), @@ -11,7 +11,7 @@ describe("builders", function() { ); expect(tsTypeParameter).toMatchSnapshot(); }); - it("throws when name is missing", function() { + it("throws when name is missing", function () { expect(() => { t.tsTypeParameter( t.tsTypeReference(t.identifier("bar")), diff --git a/packages/babel-types/test/cloning.js b/packages/babel-types/test/cloning.js index fecc1bd700..c8c3955157 100644 --- a/packages/babel-types/test/cloning.js +++ b/packages/babel-types/test/cloning.js @@ -1,27 +1,27 @@ import * as t from "../lib"; import { parse } from "@babel/parser"; -describe("cloneNode", function() { - it("should handle undefined", function() { +describe("cloneNode", function () { + it("should handle undefined", function () { const node = undefined; const cloned = t.cloneNode(node); expect(cloned).toBeUndefined(); }); - it("should handle null", function() { + it("should handle null", function () { const node = null; const cloned = t.cloneNode(node); expect(cloned).toBeNull(); }); - it("should handle simple cases", function() { + it("should handle simple cases", function () { const node = t.identifier("a"); const cloned = t.cloneNode(node); expect(node).not.toBe(cloned); expect(t.isNodesEquivalent(node, cloned)).toBe(true); }); - it("should handle full programs", function() { + it("should handle full programs", function () { const file = parse("1 + 1"); const cloned = t.cloneNode(file); expect(file).not.toBe(cloned); @@ -34,7 +34,7 @@ describe("cloneNode", function() { expect(t.isNodesEquivalent(file, cloned)).toBe(true); }); - it("should handle complex programs", function() { + it("should handle complex programs", function () { const program = "'use strict'; function lol() { wow();return 1; }"; const node = parse(program); const cloned = t.cloneNode(node); @@ -42,14 +42,14 @@ describe("cloneNode", function() { expect(t.isNodesEquivalent(node, cloned)).toBe(true); }); - it("should handle missing array element", function() { + it("should handle missing array element", function () { const node = parse("[,0]"); const cloned = t.cloneNode(node); expect(node).not.toBe(cloned); expect(t.isNodesEquivalent(node, cloned)).toBe(true); }); - it("should support shallow cloning", function() { + it("should support shallow cloning", function () { const node = t.memberExpression(t.identifier("foo"), t.identifier("bar")); const cloned = t.cloneNode(node, /* deep */ false); expect(node).not.toBe(cloned); @@ -57,7 +57,7 @@ describe("cloneNode", function() { expect(node.property).toBe(cloned.property); }); - it("should preserve type annotations", function() { + it("should preserve type annotations", function () { const node = t.variableDeclaration("let", [ t.variableDeclarator({ ...t.identifier("value"), @@ -73,7 +73,7 @@ describe("cloneNode", function() { ); }); - it("should support shallow cloning without loc", function() { + it("should support shallow cloning without loc", function () { const node = t.variableDeclaration("let", [ t.variableDeclarator({ ...t.identifier("value"), @@ -85,7 +85,7 @@ describe("cloneNode", function() { expect(cloned.loc).toBeNull(); }); - it("should support deep cloning without loc", function() { + it("should support deep cloning without loc", function () { const node = t.variableDeclaration("let", [ t.variableDeclarator({ ...t.identifier("value"), @@ -99,7 +99,7 @@ describe("cloneNode", function() { expect(cloned.declarations[0].id.loc).toBeNull(); }); - it("should support deep cloning for comments", function() { + it("should support deep cloning for comments", function () { const node = t.variableDeclaration("let", [ t.variableDeclarator({ ...t.identifier("value"), @@ -123,7 +123,7 @@ describe("cloneNode", function() { ); }); - it("should support deep cloning for comments without loc", function() { + it("should support deep cloning for comments without loc", function () { const node = t.variableDeclaration("let", [ t.variableDeclarator({ ...t.identifier("value"), diff --git a/packages/babel-types/test/converters.js b/packages/babel-types/test/converters.js index 29c9abb378..9e97c9af0a 100644 --- a/packages/babel-types/test/converters.js +++ b/packages/babel-types/test/converters.js @@ -11,13 +11,13 @@ function generateCode(node) { return generate(node).code; } -describe("converters", function() { - it("toIdentifier", function() { +describe("converters", function () { + it("toIdentifier", function () { expect(t.toIdentifier("swag-lord")).toBe("swagLord"); }); - describe("valueToNode", function() { - it("number", function() { + describe("valueToNode", function () { + it("number", function () { expect(t.valueToNode(Math.PI)).toEqual(t.numericLiteral(Math.PI)); expect(t.valueToNode(-Math.PI)).toEqual( t.unaryExpression("-", t.numericLiteral(Math.PI)), @@ -43,30 +43,30 @@ describe("converters", function() { ), ); }); - it("string", function() { + it("string", function () { expect(t.valueToNode('This is a "string"')).toEqual( t.stringLiteral('This is a "string"'), ); }); - it("boolean", function() { + it("boolean", function () { expect(t.valueToNode(true)).toEqual(t.booleanLiteral(true)); expect(t.valueToNode(false)).toEqual(t.booleanLiteral(false)); }); - it("null", function() { + it("null", function () { expect(t.valueToNode(null)).toEqual(t.nullLiteral()); }); - it("undefined", function() { + it("undefined", function () { expect(t.valueToNode(undefined)).toEqual(t.identifier("undefined")); }); - it("RegExp", function() { + it("RegExp", function () { expect(t.valueToNode(/abc.+/gm)).toEqual(t.regExpLiteral("abc.+", "gm")); }); - it("array", function() { + it("array", function () { expect(t.valueToNode([1, "a"])).toEqual( t.arrayExpression([t.numericLiteral(1), t.stringLiteral("a")]), ); }); - it("object", function() { + it("object", function () { expect( t.valueToNode({ a: 1, @@ -79,26 +79,26 @@ describe("converters", function() { ]), ); }); - it("throws if cannot convert", function() { - expect(function() { + it("throws if cannot convert", function () { + expect(function () { t.valueToNode(Object); }).toThrow(); - expect(function() { + expect(function () { t.valueToNode(Symbol()); }).toThrow(); }); }); - describe("toKeyAlias", function() { - beforeEach(function() { + describe("toKeyAlias", function () { + beforeEach(function () { // make tests deterministic t.toKeyAlias.uid = 0; }); - it("doesn't change string literals", function() { + it("doesn't change string literals", function () { expect( t.toKeyAlias(t.objectProperty(t.stringLiteral("a"), t.nullLiteral())), ).toBe('"a"'); }); - it("wraps around at Number.MAX_SAFE_INTEGER", function() { + it("wraps around at Number.MAX_SAFE_INTEGER", function () { expect( t.toKeyAlias( t.objectMethod("method", t.identifier("a"), [], t.blockStatement([])), @@ -106,13 +106,13 @@ describe("converters", function() { ).toBe("0"); }); }); - describe("toStatement", function() { - it("noop on statements", function() { + describe("toStatement", function () { + it("noop on statements", function () { const node = t.emptyStatement(); expect(t.toStatement(node)).toEqual(node); t.assertEmptyStatement(node); }); - it("mutate class expression to declaration", function() { + it("mutate class expression to declaration", function () { const node = t.classExpression( t.identifier("A"), null, @@ -122,15 +122,15 @@ describe("converters", function() { t.toStatement(node); t.assertClassDeclaration(node); }); - it("fail if class expression has no id", function() { + it("fail if class expression has no id", function () { const node = t.classExpression(null, null, t.classBody([]), []); - expect(function() { + expect(function () { t.toStatement(node); }).toThrow(Error); expect(t.toStatement(node, /* ignore = */ true)).toBe(false); t.assertClassExpression(node); }); - it("mutate function expression to declaration", function() { + it("mutate function expression to declaration", function () { const node = t.functionExpression( t.identifier("A"), [], @@ -139,15 +139,15 @@ describe("converters", function() { t.toStatement(node); t.assertFunctionDeclaration(node); }); - it("fail if function expression has no id", function() { + it("fail if function expression has no id", function () { const node = t.functionExpression(null, [], t.blockStatement([])); - expect(function() { + expect(function () { t.toStatement(node); }).toThrow(Error); expect(t.toStatement(node, /* ignore = */ true)).toBe(false); t.assertFunctionExpression(node); }); - it("assignment expression", function() { + it("assignment expression", function () { const node = t.assignmentExpression( "+=", t.identifier("x"), @@ -156,22 +156,22 @@ describe("converters", function() { t.assertExpressionStatement(t.toStatement(node)); t.assertAssignmentExpression(node); }); - it("fail if cannot convert node type", function() { + it("fail if cannot convert node type", function () { const node = t.yieldExpression(t.identifier("foo")); - expect(function() { + expect(function () { t.toStatement(node); }).toThrow(Error); expect(t.toStatement(node, /* ignore = */ true)).toBe(false); t.assertYieldExpression(node); }); }); - describe("toExpression", function() { - it("noop on expressions", function() { + describe("toExpression", function () { + it("noop on expressions", function () { const node = t.identifier("a"); expect(t.toExpression(node)).toEqual(node); t.assertIdentifier(node); }); - it("mutate class declaration to expression", function() { + it("mutate class declaration to expression", function () { const node = t.classDeclaration( t.identifier("A"), null, @@ -181,7 +181,7 @@ describe("converters", function() { t.toExpression(node); t.assertClassExpression(node); }); - it("mutate function declaration to expression", function() { + it("mutate function declaration to expression", function () { const node = t.functionDeclaration( t.identifier("A"), [], @@ -190,7 +190,7 @@ describe("converters", function() { t.toExpression(node); t.assertFunctionExpression(node); }); - it("mutate object method to expression", function() { + it("mutate object method to expression", function () { const node = t.objectMethod( "method", t.identifier("A"), @@ -200,7 +200,7 @@ describe("converters", function() { t.toExpression(node); t.assertFunctionExpression(node); }); - it("mutate class method to expression", function() { + it("mutate class method to expression", function () { const node = t.classMethod( "constructor", t.identifier("A"), @@ -210,31 +210,31 @@ describe("converters", function() { t.toExpression(node); t.assertFunctionExpression(node); }); - it("expression statement", function() { + it("expression statement", function () { const inner = t.yieldExpression(t.identifier("foo")); const node = t.expressionStatement(inner); t.assertYieldExpression(t.toExpression(node)); expect(t.toExpression(node)).toEqual(inner); t.assertExpressionStatement(node); }); - it("fail if cannot convert node type", function() { + it("fail if cannot convert node type", function () { const node = t.program([]); - expect(function() { + expect(function () { t.toExpression(node); }).toThrow(Error); t.assertProgram(node); }); }); - describe("toSequenceExpression", function() { + describe("toSequenceExpression", function () { let scope; const undefinedNode = t.identifier("undefined"); - beforeEach(function() { + beforeEach(function () { scope = []; - scope.buildUndefinedNode = function() { + scope.buildUndefinedNode = function () { return undefinedNode; }; }); - it("gathers nodes into sequence", function() { + it("gathers nodes into sequence", function () { const node = t.identifier("a"); const sequence = t.toSequenceExpression([undefinedNode, node], scope); t.assertSequenceExpression(sequence); @@ -242,7 +242,7 @@ describe("converters", function() { expect(sequence.expressions[1]).toBe(node); t.assertIdentifier(node); }); - it("avoids sequence for single node", function() { + it("avoids sequence for single node", function () { const node = t.identifier("a"); let sequence = t.toSequenceExpression([node], scope); expect(sequence).toBe(node); @@ -251,17 +251,17 @@ describe("converters", function() { sequence = t.toSequenceExpression([block], scope); expect(sequence).toBe(node); }); - it("gathers expression", function() { + it("gathers expression", function () { const node = t.identifier("a"); const sequence = t.toSequenceExpression([undefinedNode, node], scope); expect(sequence.expressions[1]).toBe(node); }); - it("gathers expression statement", function() { + it("gathers expression statement", function () { const node = t.expressionStatement(t.identifier("a")); const sequence = t.toSequenceExpression([undefinedNode, node], scope); expect(sequence.expressions[1]).toBe(node.expression); }); - it("gathers var declarations", function() { + it("gathers var declarations", function () { const node = parseCode("var a, b = 1;"); const sequence = t.toSequenceExpression([undefinedNode, node], scope); t.assertIdentifier(scope[0].id, { name: "a" }); @@ -269,12 +269,12 @@ describe("converters", function() { expect(generateCode(sequence.expressions[1])).toBe("b = 1"); expect(generateCode(sequence.expressions[2])).toBe("undefined"); }); - it("skips undefined if expression after var declaration", function() { + it("skips undefined if expression after var declaration", function () { const node = parseCode("{ var a, b = 1; true }"); const sequence = t.toSequenceExpression([undefinedNode, node], scope); expect(generateCode(sequence.expressions[1])).toBe("b = 1, true"); }); - it("bails on let and const declarations", function() { + it("bails on let and const declarations", function () { let node = parseCode("let a, b = 1;"); let sequence = t.toSequenceExpression([undefinedNode, node], scope); expect(sequence).toBeUndefined(); @@ -283,7 +283,7 @@ describe("converters", function() { sequence = t.toSequenceExpression([undefinedNode, node], scope); expect(sequence).toBeUndefined(); }); - it("gathers if statements", function() { + it("gathers if statements", function () { let node = parseCode("if (true) { true }"); let sequence = t.toSequenceExpression([undefinedNode, node], scope); expect(generateCode(sequence.expressions[1])).toBe( @@ -294,7 +294,7 @@ describe("converters", function() { sequence = t.toSequenceExpression([undefinedNode, node], scope); expect(generateCode(sequence.expressions[1])).toBe("true ? true : b"); }); - it("bails in if statements if recurse bails", function() { + it("bails in if statements if recurse bails", function () { let node = parseCode("if (true) { return }"); let sequence = t.toSequenceExpression([undefinedNode, node], scope); expect(sequence).toBeUndefined(); @@ -303,7 +303,7 @@ describe("converters", function() { sequence = t.toSequenceExpression([undefinedNode, node], scope); expect(sequence).toBeUndefined(); }); - it("gathers block statements", function() { + it("gathers block statements", function () { let node = parseCode("{ a }"); let sequence = t.toSequenceExpression([undefinedNode, node], scope); expect(generateCode(sequence.expressions[1])).toBe("a"); @@ -312,17 +312,17 @@ describe("converters", function() { sequence = t.toSequenceExpression([undefinedNode, node], scope); expect(generateCode(sequence.expressions[1])).toBe("a, b"); }); - it("bails in block statements if recurse bails", function() { + it("bails in block statements if recurse bails", function () { const node = parseCode("{ return }"); const sequence = t.toSequenceExpression([undefinedNode, node], scope); expect(sequence).toBeUndefined(); }); - it("gathers empty statements", function() { + it("gathers empty statements", function () { const node = parseCode(";"); const sequence = t.toSequenceExpression([undefinedNode, node], scope); expect(generateCode(sequence.expressions[1])).toBe("undefined"); }); - it("skips empty statement if expression afterwards", function() { + it("skips empty statement if expression afterwards", function () { const node = parseCode("{ ; true }"); const sequence = t.toSequenceExpression([undefinedNode, node], scope); expect(generateCode(sequence.expressions[1])).toBe("true"); diff --git a/packages/babel-types/test/misc.js b/packages/babel-types/test/misc.js index 2c9c2465bb..79b1155a0f 100644 --- a/packages/babel-types/test/misc.js +++ b/packages/babel-types/test/misc.js @@ -7,9 +7,9 @@ function parseCode(string) { }).program.body[0]; } -describe("misc helpers", function() { - describe("matchesPattern", function() { - it("matches explicitly", function() { +describe("misc helpers", function () { + describe("matchesPattern", function () { + it("matches explicitly", function () { const ast = parseCode("a.b.c.d").expression; expect(t.matchesPattern(ast, "a.b.c.d")).toBeTruthy(); expect(t.matchesPattern(ast, "a.b.c")).toBe(false); @@ -17,7 +17,7 @@ describe("misc helpers", function() { expect(t.matchesPattern(ast, "a.b.c.d.e")).toBe(false); }); - it("matches partially", function() { + it("matches partially", function () { const ast = parseCode("a.b.c.d").expression; expect(t.matchesPattern(ast, "a.b.c.d", true)).toBeTruthy(); expect(t.matchesPattern(ast, "a.b.c", true)).toBeTruthy(); @@ -25,7 +25,7 @@ describe("misc helpers", function() { expect(t.matchesPattern(ast, "a.b.c.d.e", true)).toBe(false); }); - it("matches string literal expressions", function() { + it("matches string literal expressions", function () { const ast = parseCode("a['b'].c.d").expression; expect(t.matchesPattern(ast, "a.b.c.d")).toBeTruthy(); expect(t.matchesPattern(ast, "a.b.c")).toBe(false); @@ -33,7 +33,7 @@ describe("misc helpers", function() { expect(t.matchesPattern(ast, "a.b.c.d.e")).toBe(false); }); - it("matches string literal expressions partially", function() { + it("matches string literal expressions partially", function () { const ast = parseCode("a['b'].c.d").expression; expect(t.matchesPattern(ast, "a.b.c.d", true)).toBeTruthy(); expect(t.matchesPattern(ast, "a.b.c", true)).toBeTruthy(); diff --git a/packages/babel-types/test/retrievers.js b/packages/babel-types/test/retrievers.js index 8a584450a4..73d9725715 100644 --- a/packages/babel-types/test/retrievers.js +++ b/packages/babel-types/test/retrievers.js @@ -5,19 +5,19 @@ function getBody(program) { return parse(program, { sourceType: "module" }).program.body; } -describe("retrievers", function() { - describe("getBindingIdentifiers", function() { - it("variable declarations", function() { +describe("retrievers", function () { + describe("getBindingIdentifiers", function () { + it("variable declarations", function () { const program = "var a = 1; let b = 2; const c = 3;"; const ids = t.getBindingIdentifiers(getBody(program)); expect(Object.keys(ids)).toEqual(["a", "b", "c"]); }); - it("function declarations", function() { + it("function declarations", function () { const program = "var foo = 1; function bar() { var baz = 2; }"; const ids = t.getBindingIdentifiers(getBody(program)); expect(Object.keys(ids)).toEqual(["bar", "foo"]); }); - it("export named declarations", function() { + it("export named declarations", function () { const program = "export const foo = 'foo';"; const ids = t.getBindingIdentifiers(getBody(program)); expect(Object.keys(ids)).toEqual(["foo"]); diff --git a/packages/babel-types/test/validators.js b/packages/babel-types/test/validators.js index b8ff2e7d8b..9e46dfc8f2 100644 --- a/packages/babel-types/test/validators.js +++ b/packages/babel-types/test/validators.js @@ -1,9 +1,9 @@ import * as t from "../lib"; import { parse } from "@babel/parser"; -describe("validators", function() { - describe("isNodesEquivalent", function() { - it("should handle simple cases", function() { +describe("validators", function () { + describe("isNodesEquivalent", function () { + it("should handle simple cases", function () { const mem = t.memberExpression(t.identifier("a"), t.identifier("b")); expect(t.isNodesEquivalent(mem, mem)).toBe(true); @@ -11,12 +11,12 @@ describe("validators", function() { expect(t.isNodesEquivalent(mem, mem2)).toBe(false); }); - it("should handle full programs", function() { + it("should handle full programs", function () { expect(t.isNodesEquivalent(parse("1 + 1"), parse("1+1"))).toBe(true); expect(t.isNodesEquivalent(parse("1 + 1"), parse("1+2"))).toBe(false); }); - it("should handle complex programs", function() { + it("should handle complex programs", function () { const program = "'use strict'; function lol() { wow();return 1; }"; expect(t.isNodesEquivalent(parse(program), parse(program))).toBe(true); @@ -26,7 +26,7 @@ describe("validators", function() { expect(t.isNodesEquivalent(parse(program), parse(program2))).toBe(false); }); - it("should handle nodes with object properties", function() { + it("should handle nodes with object properties", function () { const original = t.templateElement({ raw: "\\'a", cooked: "'a" }, true); const identical = t.templateElement({ raw: "\\'a", cooked: "'a" }, true); const different = t.templateElement({ raw: "'a", cooked: "'a" }, true); @@ -34,59 +34,59 @@ describe("validators", function() { expect(t.isNodesEquivalent(original, different)).toBe(false); }); - it("rejects 'await' as an identifier", function() { + it("rejects 'await' as an identifier", function () { expect(t.isValidIdentifier("await")).toBe(false); }); }); - describe("isCompatTag", function() { - it("should handle lowercase tag names", function() { + describe("isCompatTag", function () { + it("should handle lowercase tag names", function () { expect(t.react.isCompatTag("div")).toBe(true); expect(t.react.isCompatTag("a")).toBe(true); // one letter expect(t.react.isCompatTag("h3")).toBe(true); // letters and numbers }); - it("should handle custom element tag names", function() { + it("should handle custom element tag names", function () { expect(t.react.isCompatTag("plastic-button")).toBe(true); // ascii letters expect(t.react.isCompatTag("math-α")).toBe(true); // non-latin chars expect(t.react.isCompatTag("img-viewer2")).toBe(true); // numbers expect(t.react.isCompatTag("emotion-😍")).toBe(true); // emoji }); - it("accepts trailing dash '-' in custom element tag names", function() { + it("accepts trailing dash '-' in custom element tag names", function () { expect(t.react.isCompatTag("div-")).toBe(true); expect(t.react.isCompatTag("a-")).toBe(true); expect(t.react.isCompatTag("h3-")).toBe(true); }); - it("rejects empty or null tag names", function() { + it("rejects empty or null tag names", function () { expect(t.react.isCompatTag(null)).toBe(false); expect(t.react.isCompatTag()).toBe(false); expect(t.react.isCompatTag(undefined)).toBe(false); expect(t.react.isCompatTag("")).toBe(false); }); - it("rejects tag names starting with an uppercase letter", function() { + it("rejects tag names starting with an uppercase letter", function () { expect(t.react.isCompatTag("Div")).toBe(false); expect(t.react.isCompatTag("A")).toBe(false); expect(t.react.isCompatTag("H3")).toBe(false); }); - it("rejects all uppercase tag names", function() { + it("rejects all uppercase tag names", function () { expect(t.react.isCompatTag("DIV")).toBe(false); expect(t.react.isCompatTag("A")).toBe(false); expect(t.react.isCompatTag("H3")).toBe(false); }); - it("rejects leading dash '-'", function() { + it("rejects leading dash '-'", function () { expect(t.react.isCompatTag("-div")).toBe(false); expect(t.react.isCompatTag("-a")).toBe(false); expect(t.react.isCompatTag("-h3")).toBe(false); }); }); - describe("patterns", function() { - it("allows nested pattern structures", function() { + describe("patterns", function () { + it("allows nested pattern structures", function () { const pattern = t.objectPattern([ t.objectProperty( t.identifier("a"), @@ -104,15 +104,15 @@ describe("validators", function() { }); }); - describe("isReferenced", function() { - it("returns false if node is a key of ObjectTypeProperty", function() { + describe("isReferenced", function () { + it("returns false if node is a key of ObjectTypeProperty", function () { const node = t.identifier("a"); const parent = t.objectTypeProperty(node, t.numberTypeAnnotation()); expect(t.isReferenced(node, parent)).toBe(false); }); - it("returns true if node is a value of ObjectTypeProperty", function() { + it("returns true if node is a value of ObjectTypeProperty", function () { const node = t.identifier("a"); const parent = t.objectTypeProperty( t.identifier("someKey"), @@ -122,7 +122,7 @@ describe("validators", function() { expect(t.isReferenced(node, parent)).toBe(true); }); - it("returns true if node is a value of ObjectProperty of an expression", function() { + it("returns true if node is a value of ObjectProperty of an expression", function () { const node = t.identifier("a"); const parent = t.objectProperty(t.identifier("key"), node); const grandparent = t.objectExpression([parent]); @@ -130,7 +130,7 @@ describe("validators", function() { expect(t.isReferenced(node, parent, grandparent)).toBe(true); }); - it("returns false if node is a value of ObjectProperty of a pattern", function() { + it("returns false if node is a value of ObjectProperty of a pattern", function () { const node = t.identifier("a"); const parent = t.objectProperty(t.identifier("key"), node); const grandparent = t.objectPattern([parent]); @@ -138,8 +138,8 @@ describe("validators", function() { expect(t.isReferenced(node, parent, grandparent)).toBe(false); }); - describe("TSPropertySignature", function() { - it("returns false if node is a key", function() { + describe("TSPropertySignature", function () { + it("returns false if node is a key", function () { // { A: string } const node = t.identifier("A"); const parent = t.tsPropertySignature( @@ -150,7 +150,7 @@ describe("validators", function() { expect(t.isReferenced(node, parent)).toBe(false); }); - it("returns true if node is a value", function() { + it("returns true if node is a value", function () { // { someKey: A } const node = t.identifier("A"); const parent = t.tsPropertySignature( @@ -162,8 +162,8 @@ describe("validators", function() { }); }); - describe("TSEnumMember", function() { - it("returns false if node is an id", function() { + describe("TSEnumMember", function () { + it("returns false if node is an id", function () { // enum X = { A }; const node = t.identifier("A"); const parent = t.tsEnumMember(node); @@ -171,7 +171,7 @@ describe("validators", function() { expect(t.isReferenced(node, parent)).toBe(false); }); - it("returns true if node is a value", function() { + it("returns true if node is a value", function () { // enum X = { Foo = A } const node = t.identifier("A"); const parent = t.tsEnumMember(t.identifier("Foo"), node); @@ -180,15 +180,15 @@ describe("validators", function() { }); }); - describe("ObjectMethod", function() { - it("returns false if node is method key", function() { + describe("ObjectMethod", function () { + it("returns false if node is method key", function () { const node = t.identifier("A"); const parent = t.objectMethod("method", node, [], t.blockStatement([])); expect(t.isReferenced(node, parent)).toBe(false); }); - it("returns true if node is computed method key", function() { + it("returns true if node is computed method key", function () { const node = t.identifier("A"); const parent = t.objectMethod( "method", @@ -201,7 +201,7 @@ describe("validators", function() { expect(t.isReferenced(node, parent)).toBe(true); }); - it("returns false if node is method param", function() { + it("returns false if node is method param", function () { const node = t.identifier("A"); const parent = t.objectMethod( "method", @@ -214,15 +214,15 @@ describe("validators", function() { }); }); - describe("ClassMethod", function() { - it("returns false if node is method key", function() { + describe("ClassMethod", function () { + it("returns false if node is method key", function () { const node = t.identifier("A"); const parent = t.classMethod("method", node, [], t.blockStatement([])); expect(t.isReferenced(node, parent)).toBe(false); }); - it("returns true if node is computed method key", function() { + it("returns true if node is computed method key", function () { const node = t.identifier("A"); const parent = t.classMethod( "method", @@ -235,7 +235,7 @@ describe("validators", function() { expect(t.isReferenced(node, parent)).toBe(true); }); - it("returns false if node is method param", function() { + it("returns false if node is method param", function () { const node = t.identifier("A"); const parent = t.classMethod( "method", @@ -249,8 +249,8 @@ describe("validators", function() { }); }); - describe("isBinding", function() { - it("returns false if node id a value of ObjectProperty of an expression", function() { + describe("isBinding", function () { + it("returns false if node id a value of ObjectProperty of an expression", function () { const node = t.identifier("a"); const parent = t.objectProperty(t.identifier("key"), node); const grandparent = t.objectExpression([parent]); @@ -258,7 +258,7 @@ describe("validators", function() { expect(t.isBinding(node, parent, grandparent)).toBe(false); }); - it("returns true if node id a value of ObjectProperty of a pattern", function() { + it("returns true if node id a value of ObjectProperty of a pattern", function () { const node = t.identifier("a"); const parent = t.objectProperty(t.identifier("key"), node); const grandparent = t.objectPattern([parent]); @@ -267,109 +267,109 @@ describe("validators", function() { }); }); - describe("isType", function() { - it("returns true if nodeType equals targetType", function() { + describe("isType", function () { + it("returns true if nodeType equals targetType", function () { expect(t.isType("Identifier", "Identifier")).toBe(true); }); - it("returns false if targetType is a primary node type", function() { + it("returns false if targetType is a primary node type", function () { expect(t.isType("Expression", "ArrayExpression")).toBe(false); }); - it("returns true if targetType is an alias of nodeType", function() { + it("returns true if targetType is an alias of nodeType", function () { expect(t.isType("ArrayExpression", "Expression")).toBe(true); }); - it("returns false if nodeType and targetType are unrelated", function() { + it("returns false if nodeType and targetType are unrelated", function () { expect(t.isType("ArrayExpression", "ClassBody")).toBe(false); }); - it("returns false if nodeType is undefined", function() { + it("returns false if nodeType is undefined", function () { expect(t.isType(undefined, "Expression")).toBe(false); }); }); - describe("placeholders", function() { - describe("isPlaceholderType", function() { - describe("when placeholderType is a specific node type", function() { + describe("placeholders", function () { + describe("isPlaceholderType", function () { + describe("when placeholderType is a specific node type", function () { const placeholder = "Identifier"; - it("returns true if targetType is placeholderType", function() { + it("returns true if targetType is placeholderType", function () { expect(t.isPlaceholderType(placeholder, "Identifier")).toBe(true); }); - it("returns true if targetType an alias for placeholderType", function() { + it("returns true if targetType an alias for placeholderType", function () { expect(t.isPlaceholderType(placeholder, "Expression")).toBe(true); }); - it("returns false for unrelated types", function() { + it("returns false for unrelated types", function () { expect(t.isPlaceholderType(placeholder, "String")).toBe(false); }); }); - describe("when placeholderType is a generic alias type", function() { + describe("when placeholderType is a generic alias type", function () { const placeholder = "Pattern"; - it("returns true if targetType is placeholderType", function() { + it("returns true if targetType is placeholderType", function () { expect(t.isPlaceholderType(placeholder, "Pattern")).toBe(true); }); - it("returns true if targetType an alias for placeholderType", function() { + it("returns true if targetType an alias for placeholderType", function () { expect(t.isPlaceholderType(placeholder, "LVal")).toBe(true); }); - it("returns false for unrelated types", function() { + it("returns false for unrelated types", function () { expect(t.isPlaceholderType(placeholder, "Expression")).toBe(false); }); - it("returns false if targetType is aliased by placeholderType", function() { + it("returns false if targetType is aliased by placeholderType", function () { // i.e. a Pattern might not be an Identifier expect(t.isPlaceholderType(placeholder, "Identifier")).toBe(false); }); }); }); - describe("is", function() { - describe("when the placeholder matches a specific node", function() { + describe("is", function () { + describe("when the placeholder matches a specific node", function () { const identifier = t.placeholder("Identifier", t.identifier("foo")); - it("returns false if targetType is expectedNode", function() { + it("returns false if targetType is expectedNode", function () { expect(t.is("Identifier", identifier)).toBe(false); }); - it("returns true if targetType is an alias", function() { + it("returns true if targetType is an alias", function () { expect(t.is("LVal", identifier)).toBe(true); }); }); - describe("when the placeholder matches a generic alias", function() { + describe("when the placeholder matches a generic alias", function () { const pattern = t.placeholder("Pattern", t.identifier("bar")); - it("returns false if targetType is aliased as expectedNode", function() { + it("returns false if targetType is aliased as expectedNode", function () { // i.e. a Pattern might not be an Identifier expect(t.is("Identifier", pattern)).toBe(false); }); - it("returns true if targetType is expectedNode", function() { + it("returns true if targetType is expectedNode", function () { expect(t.is("Pattern", pattern)).toBe(true); }); - it("returns true if targetType is an alias for expectedNode", function() { + it("returns true if targetType is an alias for expectedNode", function () { expect(t.is("LVal", pattern)).toBe(true); }); }); }); - describe("is[Type]", function() { - describe("when the placeholder matches a specific node", function() { + describe("is[Type]", function () { + describe("when the placeholder matches a specific node", function () { const identifier = t.placeholder("Identifier", t.identifier("foo")); - it("returns false if targetType is expectedNode", function() { + it("returns false if targetType is expectedNode", function () { expect(t.isIdentifier(identifier)).toBe(false); }); - it("returns true if targetType is an alias", function() { + it("returns true if targetType is an alias", function () { expect(t.isLVal(identifier)).toBe(true); }); }); - describe("when the placeholder matches a generic alias", function() { + describe("when the placeholder matches a generic alias", function () { const pattern = t.placeholder("Pattern", t.identifier("bar")); - it("returns false if targetType is aliased as expectedNode", function() { + it("returns false if targetType is aliased as expectedNode", function () { expect(t.isIdentifier(pattern)).toBe(false); }); - it("returns true if targetType is expectedNode", function() { + it("returns true if targetType is expectedNode", function () { expect(t.isPattern(pattern)).toBe(true); }); - it("returns true if targetType is an alias for expectedNode", function() { + it("returns true if targetType is an alias for expectedNode", function () { expect(t.isLVal(pattern)).toBe(true); }); }); diff --git a/scripts/parser-tests/test262/index.js b/scripts/parser-tests/test262/index.js index fcef86a067..07766b230f 100644 --- a/scripts/parser-tests/test262/index.js +++ b/scripts/parser-tests/test262/index.js @@ -187,9 +187,7 @@ runner "The following Features are not currently mapped or ignored:" ); console.log( - Array.from(unmappedFeatures) - .join("\n") - .replace(/^/gm, " ") + Array.from(unmappedFeatures).join("\n").replace(/^/gm, " ") ); } }) diff --git a/scripts/parser-tests/utils/parser-test-runner.js b/scripts/parser-tests/utils/parser-test-runner.js index 764ef593d4..3a7cc1903f 100644 --- a/scripts/parser-tests/utils/parser-test-runner.js +++ b/scripts/parser-tests/utils/parser-test-runner.js @@ -121,7 +121,7 @@ class TestRunner { count: results.length, }; - results.forEach(function(result) { + results.forEach(function (result) { let classification, isAllowed; const inWhitelist = whitelist.has(result.id); whitelist.delete(result.id); @@ -200,7 +200,7 @@ class TestRunner { tests: summary.unrecognized, label: "non-existent programs specified in the whitelist file", }, - ].forEach(function({ tests, label }) { + ].forEach(function ({ tests, label }) { if (!tests.length) { return; } diff --git a/scripts/rollup-plugin-babel-source.js b/scripts/rollup-plugin-babel-source.js index 14dd3bb66c..98e470705d 100644 --- a/scripts/rollup-plugin-babel-source.js +++ b/scripts/rollup-plugin-babel-source.js @@ -2,7 +2,7 @@ const path = require("path"); const fs = require("fs"); const dirname = path.join(__dirname, ".."); -module.exports = function() { +module.exports = function () { return { name: "babel-source", load(id) { diff --git a/scripts/utils/formatCode.js b/scripts/utils/formatCode.js index 9801d4acf0..27ccdd1e48 100644 --- a/scripts/utils/formatCode.js +++ b/scripts/utils/formatCode.js @@ -1,11 +1,22 @@ "use strict"; -const prettier = require("prettier"); -module.exports = function formatCode(code, filename) { - filename = filename || __filename; - const prettierConfig = prettier.resolveConfig.sync(filename); - prettierConfig.filepath = filename; - prettierConfig.parser = "babel"; +// TODO: Remove this `if` in Babel 8 +// Prettier only supports Node.js 10+, so we can fallback to not formatting +// o CI on older Node.js versions - return prettier.format(code, prettierConfig); -}; +if (process.env.CI && parseInt(process.versions.node, 10) < 10) { + module.exports = function formatCode(code) { + return code; + }; +} else { + const prettier = require("prettier"); + + module.exports = function formatCode(code, filename) { + filename = filename || __filename; + const prettierConfig = prettier.resolveConfig.sync(filename); + prettierConfig.filepath = filename; + prettierConfig.parser = "babel"; + + return prettier.format(code, prettierConfig); + }; +} diff --git a/yarn.lock b/yarn.lock index a803186c1d..e657ab15d8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8436,10 +8436,10 @@ prettier-linter-helpers@^1.0.0: dependencies: fast-diff "^1.1.2" -prettier@^1.19.1: - version "1.19.1" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.19.1.tgz#f7d7f5ff8a9cd872a7be4ca142095956a60797cb" - integrity sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew== +prettier@^2.0.5: + version "2.0.5" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.0.5.tgz#d6d56282455243f2f92cc1716692c08aa31522d4" + integrity sha512-7PtVymN48hGcO4fGjybyBSIWDsLU4H4XlvOHfq91pz9kkGlonzwTfYkaIEwiRg/dAJF9YlbsduBAgtYLi+8cFg== pretty-format@^24.9.0: version "24.9.0"