diff --git a/codemods/babel-plugin-codemod-object-assign-to-object-spread/src/index.ts b/codemods/babel-plugin-codemod-object-assign-to-object-spread/src/index.ts index cb7ae05910d8..50a18d9bd0b0 100644 --- a/codemods/babel-plugin-codemod-object-assign-to-object-spread/src/index.ts +++ b/codemods/babel-plugin-codemod-object-assign-to-object-spread/src/index.ts @@ -1,6 +1,7 @@ import syntaxObjectRestSpread from "@babel/plugin-syntax-object-rest-spread"; +import type { PluginAPI, PluginObject } from "@babel/core"; -export default function ({ types: t }) { +export default function ({ types: t }: PluginAPI): PluginObject { return { inherits: syntaxObjectRestSpread.default, @@ -21,10 +22,15 @@ export default function ({ types: t }) { const arg = args[i]; const { node } = arg; - if (arg.isObjectExpression()) { + if (t.isObjectExpression(node)) { properties.push(...node.properties); } else { - properties.push(t.spreadElement(node)); + properties.push( + t.spreadElement( + // @ts-expect-error fixme + node, + ), + ); } } diff --git a/codemods/babel-plugin-codemod-optional-catch-binding/src/index.ts b/codemods/babel-plugin-codemod-optional-catch-binding/src/index.ts index d4873469bb7a..9cf2954e0e58 100644 --- a/codemods/babel-plugin-codemod-optional-catch-binding/src/index.ts +++ b/codemods/babel-plugin-codemod-optional-catch-binding/src/index.ts @@ -1,6 +1,7 @@ import syntaxOptionalCatchBinding from "@babel/plugin-syntax-optional-catch-binding"; +import type { PluginAPI, PluginObject } from "@babel/core"; -export default function ({ types: t }) { +export default function ({ types: t }: PluginAPI): PluginObject { return { inherits: syntaxOptionalCatchBinding.default, diff --git a/packages/babel-core/src/config/index.ts b/packages/babel-core/src/config/index.ts index d231a8ec6d59..aff0cc5b7fd2 100644 --- a/packages/babel-core/src/config/index.ts +++ b/packages/babel-core/src/config/index.ts @@ -18,7 +18,10 @@ type PluginAPI = basePluginAPI & typeof import(".."); type PresetAPI = basePresetAPI & typeof import(".."); export type { PluginAPI, PresetAPI }; // todo: may need to refine PresetObject to be a subset of ValidatedOptions -export type { ValidatedOptions as PresetObject } from "./validation/options"; +export type { + CallerMetadata, + ValidatedOptions as PresetObject, +} from "./validation/options"; import loadFullConfig from "./full"; import { loadPartialConfig as loadPartialConfigRunner } from "./partial"; diff --git a/packages/babel-core/src/index.ts b/packages/babel-core/src/index.ts index cdbc2e6998bb..fdebb2cd1a4c 100644 --- a/packages/babel-core/src/index.ts +++ b/packages/babel-core/src/index.ts @@ -30,6 +30,8 @@ export { } from "./config"; export type { + CallerMetadata, + InputOptions, PluginAPI, PluginObject, PresetAPI, diff --git a/packages/babel-plugin-transform-runtime/src/get-runtime-path/browser.ts b/packages/babel-plugin-transform-runtime/src/get-runtime-path/browser.ts index 94af79f4ce4d..53cc0f75469c 100644 --- a/packages/babel-plugin-transform-runtime/src/get-runtime-path/browser.ts +++ b/packages/babel-plugin-transform-runtime/src/get-runtime-path/browser.ts @@ -1,4 +1,8 @@ -export default function (moduleName, dirname, absoluteRuntime) { +export default function ( + moduleName: string, + dirname: string, + absoluteRuntime: string | boolean, +) { if (absoluteRuntime === false) return moduleName; resolveFSPath(); diff --git a/packages/babel-plugin-transform-runtime/src/get-runtime-path/index.ts b/packages/babel-plugin-transform-runtime/src/get-runtime-path/index.ts index 37fdc83a6827..ac92873a8e05 100644 --- a/packages/babel-plugin-transform-runtime/src/get-runtime-path/index.ts +++ b/packages/babel-plugin-transform-runtime/src/get-runtime-path/index.ts @@ -3,7 +3,11 @@ import path from "path"; import { createRequire } from "module"; const require = createRequire(import.meta.url); -export default function (moduleName, dirname, absoluteRuntime) { +export default function ( + moduleName: string, + dirname: string, + absoluteRuntime: string | boolean, +) { if (absoluteRuntime === false) return moduleName; return resolveAbsoluteRuntime( @@ -33,6 +37,6 @@ function resolveAbsoluteRuntime(moduleName: string, dirname: string) { } } -export function resolveFSPath(path) { +export function resolveFSPath(path: string) { return require.resolve(path).replace(/\\/g, "/"); } diff --git a/packages/babel-plugin-transform-runtime/src/helpers.ts b/packages/babel-plugin-transform-runtime/src/helpers.ts index ad77e524f9ae..bea33ed07af0 100644 --- a/packages/babel-plugin-transform-runtime/src/helpers.ts +++ b/packages/babel-plugin-transform-runtime/src/helpers.ts @@ -1,6 +1,9 @@ import semver from "semver"; -export function hasMinVersion(minVersion, runtimeVersion) { +export function hasMinVersion( + minVersion: string, + runtimeVersion: string | void, +) { // If the range is unavailable, we're running the script during Babel's // build process, and we want to assume that all versions are satisfied so // that the built output will include all definitions. diff --git a/packages/babel-plugin-transform-runtime/src/index.ts b/packages/babel-plugin-transform-runtime/src/index.ts index b734e4b6e3fc..d16ea9acae92 100644 --- a/packages/babel-plugin-transform-runtime/src/index.ts +++ b/packages/babel-plugin-transform-runtime/src/index.ts @@ -4,6 +4,7 @@ import { types as t } from "@babel/core"; import { hasMinVersion } from "./helpers"; import getRuntimePath, { resolveFSPath } from "./get-runtime-path"; +import type { PluginAPI, PluginObject, CallerMetadata } from "@babel/core"; import _pluginCorejs2 from "babel-plugin-polyfill-corejs2"; import _pluginCorejs3 from "babel-plugin-polyfill-corejs3"; @@ -17,7 +18,8 @@ const pluginRegenerator = (_pluginRegenerator.default || const pluginsCompat = "#__secret_key__@babel/runtime__compatibility"; -function supportsStaticESM(caller) { +function supportsStaticESM(caller: CallerMetadata | void) { + // @ts-ignore TS does not narrow down optional chaining return !!caller?.supportsStaticESM; } @@ -30,6 +32,35 @@ export interface Options { version?: string; } +interface CoreJS2PluginOptions { + absoluteImports: string | false; + method: "usage-pure"; + [pluginsCompat]: { + runtimeVersion: string; + useBabelRuntime: string | false; + ext: string; + }; +} + +interface RegeneratorPluginOptions { + absoluteImports: string | false; + method: "usage-pure"; + [pluginsCompat]: { + useBabelRuntime: string | false; + }; +} + +interface CoreJS3PluginOptions { + absoluteImports: string | false; + method: "usage-pure"; + proposals: boolean; + version: number; + [pluginsCompat]: { + useBabelRuntime: string | false; + ext: string; + }; +} + export default declare((api, options: Options, dirname) => { api.assertVersion(7); @@ -106,11 +137,12 @@ export default declare((api, options: Options, dirname) => { var supportsCJSDefault = hasMinVersion(DUAL_MODE_RUNTIME, runtimeVersion); } - function has(obj, key) { + function has(obj: {}, key: string) { return Object.prototype.hasOwnProperty.call(obj, key); } if (has(options, "useBuiltIns")) { + // @ts-expect-error deprecated options if (options["useBuiltIns"]) { throw new Error( "The 'useBuiltIns' option has been removed. The @babel/runtime " + @@ -125,6 +157,7 @@ export default declare((api, options: Options, dirname) => { } if (has(options, "polyfill")) { + // @ts-expect-error deprecated options if (options["polyfill"] === false) { throw new Error( "The 'polyfill' option has been removed. The @babel/runtime " + @@ -163,8 +196,20 @@ export default declare((api, options: Options, dirname) => { const modulePath = getRuntimePath(moduleName, dirname, absoluteRuntime); - function createCorejsPlgin(plugin, options, regeneratorPlugin) { - return (api, _, filename) => { + function createCorejsPlgin( + plugin: ( + api: PluginAPI, + options: Options, + filename: string, + ) => PluginObject, + options: Options, + regeneratorPlugin: ( + api: PluginAPI, + options: RegeneratorPluginOptions, + filename: string, + ) => PluginObject, + ): (api: PluginAPI, options: {}, filename: string) => PluginObject { + return (api: PluginAPI, _: {}, filename: string) => { return { ...plugin(api, options, filename), inherits: regeneratorPlugin, @@ -173,7 +218,13 @@ export default declare((api, options: Options, dirname) => { } // TODO: Remove this in Babel 8 - function createRegeneratorPlugin(options) { + function createRegeneratorPlugin( + options: RegeneratorPluginOptions, + ): ( + api: PluginAPI, + options: RegeneratorPluginOptions, + filename: string, + ) => PluginObject { if (!useRuntimeRegenerator) return undefined; return (api, _, filename) => { return pluginRegenerator(api, options, filename); @@ -184,7 +235,7 @@ export default declare((api, options: Options, dirname) => { name: "transform-runtime", inherits: injectCoreJS2 - ? createCorejsPlgin( + ? createCorejsPlgin( pluginCorejs2, { method: "usage-pure", @@ -202,7 +253,7 @@ export default declare((api, options: Options, dirname) => { }), ) : injectCoreJS3 - ? createCorejsPlgin( + ? createCorejsPlgin( pluginCorejs3, { method: "usage-pure", @@ -226,7 +277,7 @@ export default declare((api, options: Options, dirname) => { pre(file) { if (!useRuntimeHelpers) return; - file.set("helperGenerator", name => { + file.set("helperGenerator", (name: string) => { // If the helper didn't exist yet at the version given, we bail // out and let Babel either insert it directly, or throw an error // so that plugins can handle that case properly. @@ -271,9 +322,9 @@ export default declare((api, options: Options, dirname) => { const cache = new Map(); function addDefaultImport( - source, - nameHint, - blockHoist, + source: string, + nameHint: string, + blockHoist: number, isHelper = false, ) { // If something on the page adds a helper when the file is an ES6 diff --git a/packages/babel-plugin-transform-typescript/src/enum.ts b/packages/babel-plugin-transform-typescript/src/enum.ts index 79368a06656a..9a3234286f69 100644 --- a/packages/babel-plugin-transform-typescript/src/enum.ts +++ b/packages/babel-plugin-transform-typescript/src/enum.ts @@ -39,7 +39,7 @@ export default function transpileEnum( throw new Error(`Unexpected enum parent '${path.parent.type}`); } - function seen(parentPath: NodePath) { + function seen(parentPath: NodePath): boolean { if (parentPath.isExportDeclaration()) { return seen(parentPath.parentPath); } @@ -193,12 +193,12 @@ export function translateEnumValues( // Based on the TypeScript repository's `evalConstant` in `checker.ts`. function evaluate( - expr, + expr: t.Node, seen: PreviousEnumMembers, ): number | string | typeof undefined { return evalConstant(expr); - function evalConstant(expr): number | typeof undefined { + function evalConstant(expr: t.Node): number | typeof undefined { switch (expr.type) { case "StringLiteral": return expr.value; @@ -225,7 +225,7 @@ function evaluate( function evalUnaryExpression({ argument, operator, - }): number | typeof undefined { + }: t.UnaryExpression): number | typeof undefined { const value = evalConstant(argument); if (value === undefined) { return undefined; @@ -243,7 +243,7 @@ function evaluate( } } - function evalBinaryExpression(expr): number | typeof undefined { + function evalBinaryExpression(expr: t.BinaryExpression): number | undefined { const left = evalConstant(expr.left); if (left === undefined) { return undefined; diff --git a/packages/babel-plugin-transform-typescript/src/index.ts b/packages/babel-plugin-transform-typescript/src/index.ts index ef57f17e9e34..01ad3eac6711 100644 --- a/packages/babel-plugin-transform-typescript/src/index.ts +++ b/packages/babel-plugin-transform-typescript/src/index.ts @@ -2,7 +2,7 @@ import { declare } from "@babel/helper-plugin-utils"; import syntaxTypeScript from "@babel/plugin-syntax-typescript"; import { types as t, template } from "@babel/core"; import { injectInitialization } from "@babel/helper-create-class-features-plugin"; -import type { NodePath } from "@babel/traverse"; +import type { Binding, NodePath } from "@babel/traverse"; import type { Options as SyntaxOptions } from "@babel/plugin-syntax-typescript"; import transpileConstEnum from "./const-enum"; @@ -149,7 +149,7 @@ export default declare((api, opts: Options) => { if (node.declare) node.declare = null; if (node.override) node.override = null; }, - method({ node }) { + method({ node }: NodePath) { if (node.accessibility) node.accessibility = null; if (node.abstract) node.abstract = null; if (node.optional) node.optional = null; @@ -157,7 +157,7 @@ export default declare((api, opts: Options) => { // Rest handled by Function visitor }, - constructor(path, classPath) { + constructor(path: NodePath, classPath: NodePath) { if (path.node.accessibility) path.node.accessibility = null; // Collects parameter properties so that we can add an assignment // for each of them in the constructor body @@ -487,7 +487,11 @@ export default declare((api, opts: Options) => { path.get("body.body").forEach(child => { if (child.isClassMethod() || child.isClassPrivateMethod()) { if (child.node.kind === "constructor") { - classMemberVisitors.constructor(child, path); + classMemberVisitors.constructor( + // @ts-expect-error A constructor must not be a private method + child, + path, + ); } else { classMemberVisitors.method(child); } @@ -512,7 +516,7 @@ export default declare((api, opts: Options) => { }, TSModuleDeclaration(path) { - transpileNamespace(path, t, allowNamespaces); + transpileNamespace(path, allowNamespaces); }, TSInterfaceDeclaration(path) { @@ -614,7 +618,9 @@ export default declare((api, opts: Options) => { return node; } - function visitPattern({ node }) { + function visitPattern({ + node, + }: NodePath) { if (node.typeAnnotation) node.typeAnnotation = null; if (t.isIdentifier(node) && node.optional) node.optional = null; // 'access' and 'readonly' are only for parameter properties, so constructor visitor will handle them. @@ -625,6 +631,11 @@ export default declare((api, opts: Options) => { programPath, pragmaImportName, pragmaFragImportName, + }: { + binding: Binding; + programPath: NodePath; + pragmaImportName: string; + pragmaFragImportName: string; }) { for (const path of binding.referencePaths) { if (!isInType(path)) { diff --git a/packages/babel-plugin-transform-typescript/src/namespace.ts b/packages/babel-plugin-transform-typescript/src/namespace.ts index 186da7c3c77c..74532eca9412 100644 --- a/packages/babel-plugin-transform-typescript/src/namespace.ts +++ b/packages/babel-plugin-transform-typescript/src/namespace.ts @@ -1,29 +1,33 @@ import { template, types as t } from "@babel/core"; import type { NodePath } from "@babel/traverse"; -export default function transpileNamespace(path, t, allowNamespaces) { +export default function transpileNamespace( + path: NodePath, + allowNamespaces: boolean, +) { if (path.node.declare || path.node.id.type === "StringLiteral") { path.remove(); return; } if (!allowNamespaces) { - throw path.hub.file.buildCodeFrameError( - path.node.id, - "Namespace not marked type-only declare." + - " Non-declarative namespaces are only supported experimentally in Babel." + - " To enable and review caveats see:" + - " https://babeljs.io/docs/en/babel-plugin-transform-typescript", - ); + throw path + .get("id") + .buildCodeFrameError( + "Namespace not marked type-only declare." + + " Non-declarative namespaces are only supported experimentally in Babel." + + " To enable and review caveats see:" + + " https://babeljs.io/docs/en/babel-plugin-transform-typescript", + ); } const name = path.node.id.name; - const value = handleNested(path, t, t.cloneDeep(path.node)); + const value = handleNested(path, t.cloneNode(path.node, true)); const bound = path.scope.hasOwnBinding(name); if (path.parent.type === "ExportNamedDeclaration") { if (!bound) { path.parentPath.insertAfter(value); - path.replaceWith(getDeclaration(t, name)); + path.replaceWith(getDeclaration(name)); path.scope.registerDeclaration(path.parentPath); } else { path.parentPath.replaceWith(value); @@ -32,18 +36,18 @@ export default function transpileNamespace(path, t, allowNamespaces) { path.replaceWith(value); } else { path.scope.registerDeclaration( - path.replaceWithMultiple([getDeclaration(t, name), value])[0], + path.replaceWithMultiple([getDeclaration(name), value])[0], ); } } -function getDeclaration(t, name) { +function getDeclaration(name: string) { return t.variableDeclaration("let", [ t.variableDeclarator(t.identifier(name)), ]); } -function getMemberExpression(t, name, itemName) { +function getMemberExpression(name: string, itemName: string) { return t.memberExpression(t.identifier(name), t.identifier(itemName)); } @@ -79,7 +83,7 @@ function handleVariableDeclaration( for (const declarator of declarations) { declarator.init = t.assignmentExpression( "=", - getMemberExpression(t, name, declarator.id.name), + getMemberExpression(name, declarator.id.name), declarator.init, ); } @@ -95,7 +99,7 @@ function handleVariableDeclaration( assignments.push( t.assignmentExpression( "=", - getMemberExpression(t, name, idName), + getMemberExpression(name, idName), t.cloneNode(bindingIdentifiers[idName]), ), ); @@ -113,9 +117,8 @@ function buildNestedAmbiendModuleError(path: NodePath, node: t.Node) { function handleNested( path: NodePath, - t: typeof import("@babel/types"), node: t.TSModuleDeclaration, - parentExport?, + parentExport?: t.Expression, ) { const names = new Set(); const realName = node.id; @@ -142,7 +145,7 @@ function handleNested( throw buildNestedAmbiendModuleError(path, subNode); } - const transformed = handleNested(path, t, subNode); + const transformed = handleNested(path, subNode); const moduleName = subNode.id.name; if (names.has(moduleName)) { namespaceTopLevel[i] = transformed; @@ -151,7 +154,7 @@ function handleNested( namespaceTopLevel.splice( i++, 1, - getDeclaration(t, moduleName), + getDeclaration(moduleName), transformed, ); } @@ -191,7 +194,7 @@ function handleNested( t.expressionStatement( t.assignmentExpression( "=", - getMemberExpression(t, name, itemName), + getMemberExpression(name, itemName), t.identifier(itemName), ), ), @@ -215,7 +218,6 @@ function handleNested( const transformed = handleNested( path, - t, subNode.declaration, t.identifier(name), ); @@ -227,7 +229,7 @@ function handleNested( namespaceTopLevel.splice( i++, 1, - getDeclaration(t, moduleName), + getDeclaration(moduleName), transformed, ); } diff --git a/packages/babel-preset-typescript/src/index.ts b/packages/babel-preset-typescript/src/index.ts index e9fb7b515204..5fce63166f9e 100644 --- a/packages/babel-preset-typescript/src/index.ts +++ b/packages/babel-preset-typescript/src/index.ts @@ -18,7 +18,7 @@ export default declarePreset((api, opts: Options) => { } = normalizeOptions(opts); const pluginOptions = process.env.BABEL_8_BREAKING - ? (isTSX, disallowAmbiguousJSXLike) => ({ + ? (isTSX: boolean, disallowAmbiguousJSXLike: boolean) => ({ allowNamespaces, disallowAmbiguousJSXLike, isTSX, @@ -27,7 +27,7 @@ export default declarePreset((api, opts: Options) => { onlyRemoveTypeImports, optimizeConstEnums, }) - : (isTSX, disallowAmbiguousJSXLike) => ({ + : (isTSX: boolean, disallowAmbiguousJSXLike: boolean) => ({ allowDeclareFields: opts.allowDeclareFields, allowNamespaces, disallowAmbiguousJSXLike, diff --git a/tsconfig.base.json b/tsconfig.base.json index af2501b34cc3..64b95c92c311 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -12,6 +12,7 @@ "isolatedModules": true, "skipLibCheck": true, "resolveJsonModule": true, - "noImplicitThis": true + "noImplicitThis": true, + "noImplicitAny": true } }