| 1 |
"use strict"; |
| 2 |
|
| 3 |
const pathUtils = require("path"); |
| 4 |
const fs = require("fs"); |
| 5 |
const { parseSync } = require("@babel/core"); |
| 6 |
|
| 7 |
function normalize(src) { |
| 8 |
return src.replace(/\//, pathUtils.sep); |
| 9 |
} |
| 10 |
|
| 11 |
module.exports = function (api) { |
| 12 |
const env = api.env(); |
| 13 |
|
| 14 |
const outputType = api.cache.invalidate(() => { |
| 15 |
try { |
| 16 |
return fs.readFileSync(__dirname + "/.module-type", "utf-8").trim(); |
| 17 |
} catch (_) { |
| 18 |
return "script"; |
| 19 |
} |
| 20 |
}); |
| 21 |
|
| 22 |
const sources = ["packages/*/src", "codemods/*/src", "eslint/*/src"]; |
| 23 |
|
| 24 |
const envOpts = { |
| 25 |
shippedProposals: true, |
| 26 |
modules: false, |
| 27 |
exclude: [ |
| 28 |
"transform-typeof-symbol", |
| 29 |
// We need to enable useBuiltIns |
| 30 |
"proposal-object-rest-spread", |
| 31 |
], |
| 32 |
}; |
| 33 |
|
| 34 |
// These are "safe" assumptions, that we can enable globally |
| 35 |
const assumptions = { |
| 36 |
constantSuper: true, |
| 37 |
ignoreFunctionLength: true, |
| 38 |
ignoreToPrimitiveHint: true, |
| 39 |
mutableTemplateObject: true, |
| 40 |
noClassCalls: true, |
| 41 |
noDocumentAll: true, |
| 42 |
noNewArrows: true, |
| 43 |
setClassMethods: true, |
| 44 |
setComputedProperties: true, |
| 45 |
setSpreadProperties: true, |
| 46 |
skipForOfIteratorClosing: true, |
| 47 |
superIsCallableConstructor: true, |
| 48 |
}; |
| 49 |
|
| 50 |
// These are "less safe": we only enable them on our own code |
| 51 |
// and not when compiling dependencies. |
| 52 |
const sourceAssumptions = { |
| 53 |
objectRestNoSymbols: true, |
| 54 |
pureGetters: true, |
| 55 |
setPublicClassFields: true, |
| 56 |
}; |
| 57 |
|
| 58 |
const parserAssumptions = { |
| 59 |
iterableIsArray: true, |
| 60 |
}; |
| 61 |
|
| 62 |
let targets = {}; |
| 63 |
let convertESM = outputType === "script"; |
| 64 |
/** @type {false | "externals" | "always"} */ |
| 65 |
let addImportExtension = convertESM ? false : "always"; |
| 66 |
let ignoreLib = true; |
| 67 |
let includeRegeneratorRuntime = false; |
| 68 |
let needsPolyfillsForOldNode = false; |
| 69 |
|
| 70 |
let transformRuntimeOptions; |
| 71 |
|
| 72 |
const nodeVersion = bool(process.env.BABEL_8_BREAKING) ? "14.17" : "6.9"; |
| 73 |
// The vast majority of our src files are modules, but we use |
| 74 |
// unambiguous to keep things simple until we get around to renaming |
| 75 |
// the modules to be more easily distinguished from CommonJS |
| 76 |
const unambiguousSources = [ |
| 77 |
...sources, |
| 78 |
"packages/*/test", |
| 79 |
"codemods/*/test", |
| 80 |
"eslint/*/test", |
| 81 |
]; |
| 82 |
|
| 83 |
const lazyRequireSources = [ |
| 84 |
"./packages/babel-cli", |
| 85 |
"./packages/babel-core", |
| 86 |
"./packages/babel-preset-env/src/available-plugins.js", |
| 87 |
]; |
| 88 |
|
| 89 |
switch (env) { |
| 90 |
// Configs used during bundling builds. |
| 91 |
case "standalone": |
| 92 |
includeRegeneratorRuntime = true; |
| 93 |
convertESM = false; |
| 94 |
addImportExtension = false; |
| 95 |
ignoreLib = false; |
| 96 |
// rollup-commonjs will converts node_modules to ESM |
| 97 |
unambiguousSources.push( |
| 98 |
"/**/node_modules", |
| 99 |
"packages/babel-preset-env/data", |
| 100 |
"packages/babel-compat-data", |
| 101 |
"packages/babel-runtime/regenerator" |
| 102 |
); |
| 103 |
targets = { ie: 7 }; |
| 104 |
break; |
| 105 |
case "rollup": |
| 106 |
convertESM = false; |
| 107 |
addImportExtension = "externals"; |
| 108 |
ignoreLib = false; |
| 109 |
// rollup-commonjs will converts node_modules to ESM |
| 110 |
unambiguousSources.push( |
| 111 |
"/**/node_modules", |
| 112 |
"packages/babel-preset-env/data", |
| 113 |
"packages/babel-compat-data" |
| 114 |
); |
| 115 |
targets = { node: nodeVersion }; |
| 116 |
needsPolyfillsForOldNode = true; |
| 117 |
break; |
| 118 |
case "test-legacy": // In test-legacy environment, we build babel on latest node but test on minimum supported legacy versions |
| 119 |
// fall through |
| 120 |
case "production": |
| 121 |
// Config during builds before publish. |
| 122 |
targets = { node: nodeVersion }; |
| 123 |
needsPolyfillsForOldNode = true; |
| 124 |
break; |
| 125 |
case "test": |
| 126 |
targets = { node: "current" }; |
| 127 |
needsPolyfillsForOldNode = true; |
| 128 |
break; |
| 129 |
case "development": |
| 130 |
envOpts.debug = true; |
| 131 |
targets = { node: "current" }; |
| 132 |
break; |
| 133 |
} |
| 134 |
|
| 135 |
if (process.env.STRIP_BABEL_8_FLAG && bool(process.env.BABEL_8_BREAKING)) { |
| 136 |
// Never apply polyfills when compiling for Babel 8 |
| 137 |
needsPolyfillsForOldNode = false; |
| 138 |
} |
| 139 |
|
| 140 |
if (includeRegeneratorRuntime) { |
| 141 |
const babelRuntimePkgPath = require.resolve("@babel/runtime/package.json"); |
| 142 |
|
| 143 |
transformRuntimeOptions = { |
| 144 |
helpers: false, // Helpers are handled by rollup when needed |
| 145 |
regenerator: true, |
| 146 |
version: require(babelRuntimePkgPath).version, |
| 147 |
}; |
| 148 |
} |
| 149 |
|
| 150 |
const config = { |
| 151 |
targets, |
| 152 |
assumptions, |
| 153 |
|
| 154 |
// Our dependencies are all standard CommonJS, along with all sorts of |
| 155 |
// other random files in Babel's codebase, so we use script as the default, |
| 156 |
// and then mark actual modules as modules farther down. |
| 157 |
sourceType: "script", |
| 158 |
comments: false, |
| 159 |
ignore: [ |
| 160 |
// These may not be strictly necessary with the newly-limited scope of |
| 161 |
// babelrc searching, but including them for now because we had them |
| 162 |
// in our .babelignore before. |
| 163 |
"packages/*/test/fixtures", |
| 164 |
ignoreLib ? "packages/*/lib" : null, |
| 165 |
"packages/babel-standalone/babel.js", |
| 166 |
] |
| 167 |
.filter(Boolean) |
| 168 |
.map(normalize), |
| 169 |
presets: [ |
| 170 |
// presets are applied from right to left |
| 171 |
["@babel/env", envOpts], |
| 172 |
[ |
| 173 |
"@babel/preset-typescript", |
| 174 |
{ |
| 175 |
onlyRemoveTypeImports: true, |
| 176 |
allowDeclareFields: true, |
| 177 |
optimizeConstEnums: true, |
| 178 |
}, |
| 179 |
], |
| 180 |
], |
| 181 |
plugins: [ |
| 182 |
["@babel/proposal-object-rest-spread", { useBuiltIns: true }], |
| 183 |
|
| 184 |
convertESM ? "@babel/proposal-export-namespace-from" : null, |
| 185 |
convertESM ? pluginImportMetaUrl : null, |
| 186 |
|
| 187 |
pluginPackageJsonMacro, |
| 188 |
|
| 189 |
needsPolyfillsForOldNode && pluginPolyfillsOldNode, |
| 190 |
].filter(Boolean), |
| 191 |
overrides: [ |
| 192 |
{ |
| 193 |
test: [ |
| 194 |
"packages/babel-parser", |
| 195 |
"packages/babel-helper-validator-identifier", |
| 196 |
].map(normalize), |
| 197 |
plugins: [ |
| 198 |
"babel-plugin-transform-charcodes", |
| 199 |
pluginBabelParserTokenType, |
| 200 |
], |
| 201 |
assumptions: parserAssumptions, |
| 202 |
}, |
| 203 |
{ |
| 204 |
test: [ |
| 205 |
"packages/babel-generator", |
| 206 |
"packages/babel-plugin-proposal-decorators", |
| 207 |
"packages/babel-helper-string-parser", |
| 208 |
].map(normalize), |
| 209 |
plugins: ["babel-plugin-transform-charcodes"], |
| 210 |
}, |
| 211 |
{ |
| 212 |
test: ["packages/babel-generator"].map(normalize), |
| 213 |
plugins: [pluginGeneratorOptimization], |
| 214 |
}, |
| 215 |
convertESM && { |
| 216 |
test: ["./packages/babel-node/src"].map(normalize), |
| 217 |
// Used to conditionally import kexec |
| 218 |
plugins: ["@babel/plugin-proposal-dynamic-import"], |
| 219 |
}, |
| 220 |
{ |
| 221 |
test: sources.map(normalize), |
| 222 |
assumptions: sourceAssumptions, |
| 223 |
plugins: [ |
| 224 |
transformNamedBabelTypesImportToDestructuring, |
| 225 |
addImportExtension |
| 226 |
? [pluginAddImportExtension, { when: addImportExtension }] |
| 227 |
: null, |
| 228 |
|
| 229 |
[ |
| 230 |
pluginToggleBooleanFlag, |
| 231 |
{ name: "USE_ESM", value: outputType === "module" }, |
| 232 |
"flag-USE_ESM", |
| 233 |
], |
| 234 |
|
| 235 |
process.env.STRIP_BABEL_8_FLAG && [ |
| 236 |
pluginToggleBooleanFlag, |
| 237 |
{ |
| 238 |
name: "process.env.BABEL_8_BREAKING", |
| 239 |
value: bool(process.env.BABEL_8_BREAKING), |
| 240 |
}, |
| 241 |
"flag-BABEL_8_BREAKING", |
| 242 |
], |
| 243 |
].filter(Boolean), |
| 244 |
}, |
| 245 |
convertESM && { |
| 246 |
test: lazyRequireSources.map(normalize), |
| 247 |
plugins: [ |
| 248 |
// Explicitly use the lazy version of CommonJS modules. |
| 249 |
[ |
| 250 |
"@babel/transform-modules-commonjs", |
| 251 |
{ importInterop: importInteropSrc, lazy: true }, |
| 252 |
], |
| 253 |
], |
| 254 |
}, |
| 255 |
convertESM && { |
| 256 |
test: ["./packages/babel-core/src"].map(normalize), |
| 257 |
plugins: [ |
| 258 |
[ |
| 259 |
pluginInjectNodeReexportsHints, |
| 260 |
{ names: ["types", "tokTypes", "traverse", "template"] }, |
| 261 |
], |
| 262 |
], |
| 263 |
}, |
| 264 |
convertESM && { |
| 265 |
test: sources.map(normalize), |
| 266 |
exclude: lazyRequireSources.map(normalize), |
| 267 |
plugins: [ |
| 268 |
[ |
| 269 |
"@babel/transform-modules-commonjs", |
| 270 |
{ importInterop: importInteropSrc }, |
| 271 |
], |
| 272 |
], |
| 273 |
}, |
| 274 |
{ |
| 275 |
test: sources.map(source => normalize(source.replace("/src", "/test"))), |
| 276 |
plugins: [ |
| 277 |
[ |
| 278 |
"@babel/transform-modules-commonjs", |
| 279 |
{ importInterop: importInteropTest }, |
| 280 |
], |
| 281 |
], |
| 282 |
}, |
| 283 |
{ |
| 284 |
test: unambiguousSources.map(normalize), |
| 285 |
sourceType: "unambiguous", |
| 286 |
}, |
| 287 |
includeRegeneratorRuntime && { |
| 288 |
exclude: /regenerator-runtime/, |
| 289 |
plugins: [["@babel/transform-runtime", transformRuntimeOptions]], |
| 290 |
}, |
| 291 |
].filter(Boolean), |
| 292 |
}; |
| 293 |
|
| 294 |
return config; |
| 295 |
}; |
| 296 |
|
| 297 |
let monorepoPackages; |
| 298 |
function getMonorepoPackages() { |
| 299 |
if (!monorepoPackages) { |
| 300 |
monorepoPackages = ["codemods", "eslint", "packages"] |
| 301 |
.map(folder => fs.readdirSync(__dirname + "/" + folder)) |
| 302 |
.reduce((a, b) => a.concat(b)) |
| 303 |
.map(name => name.replace(/^babel-/, "@babel/")); |
| 304 |
} |
| 305 |
return monorepoPackages; |
| 306 |
} |
| 307 |
|
| 308 |
function importInteropSrc(source, filename) { |
| 309 |
if ( |
| 310 |
// These internal files are "real CJS" (whose default export is |
| 311 |
// on module.exports) and not compiled ESM. |
| 312 |
source.startsWith("@babel/compat-data/") || |
| 313 |
source.includes("babel-eslint-shared-fixtures/utils") || |
| 314 |
(source.includes("../data/") && |
| 315 |
/babel-preset-env[\\/]src[\\/]/.test(filename)) |
| 316 |
) { |
| 317 |
return "node"; |
| 318 |
} |
| 319 |
if ( |
| 320 |
source[0] === "." || |
| 321 |
getMonorepoPackages().some(name => source.startsWith(name)) |
| 322 |
) { |
| 323 |
// We don't need to worry about interop for internal files, since we know |
| 324 |
// for sure that they are ESM modules compiled to CJS |
| 325 |
return "none"; |
| 326 |
} |
| 327 |
|
| 328 |
// For external modules, we want to match the Node.js behavior |
| 329 |
return "node"; |
| 330 |
} |
| 331 |
|
| 332 |
function importInteropTest(source) { |
| 333 |
// This file will soon have an esm entrypoint |
| 334 |
if (source === "@babel/helper-plugin-test-runner") { |
| 335 |
return "none"; |
| 336 |
} |
| 337 |
if ( |
| 338 |
// non-test files |
| 339 |
!source.startsWith(".") || |
| 340 |
// lib files |
| 341 |
/(?:\.\.\/)+(?:babel-[a-z-]+\/)?lib/.test(source) |
| 342 |
) { |
| 343 |
return "node"; |
| 344 |
} |
| 345 |
return "babel"; |
| 346 |
} |
| 347 |
|
| 348 |
// env vars from the cli are always strings, so !!ENV_VAR returns true for "false" |
| 349 |
function bool(value) { |
| 350 |
return value && value !== "false" && value !== "0"; |
| 351 |
} |
| 352 |
|
| 353 |
// A minimum semver GTE implementation |
| 354 |
// Limitation: |
| 355 |
// - it only supports comparing major and minor version, assuming Node.js will never ship |
| 356 |
// features in patch release so we will never need to compare a version with "1.2.3" |
| 357 |
// |
| 358 |
// @example |
| 359 |
// semverGte("8.10", "8.9") // true |
| 360 |
// semverGte("8.9", "8.9") // true |
| 361 |
// semverGte("9.0", "8.9") // true |
| 362 |
// semverGte("8.9", "8.10") // false |
| 363 |
// TODO: figure out how to inject it to the `@babel/template` usage so we don't need to |
| 364 |
// copy and paste it. |
| 365 |
// `((v,w)=>(v=v.split("."),w=w.split("."),+v[0]>+w[0]||v[0]==w[0]&&+v[1]>=+w[1]))`; |
| 366 |
|
| 367 |
// TODO(Babel 8) This polyfills are only needed for Node.js 6 and 8 |
| 368 |
/** @param {import("@babel/core")} api */ |
| 369 |
function pluginPolyfillsOldNode({ template, types: t }) { |
| 370 |
const polyfills = [ |
| 371 |
{ |
| 372 |
name: "require.resolve", |
| 373 |
necessary({ node, parent }) { |
| 374 |
return ( |
| 375 |
t.isCallExpression(parent, { callee: node }) && |
| 376 |
parent.arguments.length > 1 |
| 377 |
); |
| 378 |
}, |
| 379 |
supported({ parent: { arguments: args } }) { |
| 380 |
return ( |
| 381 |
t.isObjectExpression(args[1]) && |
| 382 |
args[1].properties.length === 1 && |
| 383 |
t.isIdentifier(args[1].properties[0].key, { name: "paths" }) && |
| 384 |
t.isArrayExpression(args[1].properties[0].value) && |
| 385 |
args[1].properties[0].value.elements.length === 1 |
| 386 |
); |
| 387 |
}, |
| 388 |
// require.resolve's paths option has been introduced in Node.js 8.9 |
| 389 |
// https://nodejs.org/api/modules.html#modules_require_resolve_request_options |
| 390 |
replacement: template({ syntacticPlaceholders: true })` |
| 391 |
((v,w)=>(v=v.split("."),w=w.split("."),+v[0]>+w[0]||v[0]==w[0]&&+v[1]>=+w[1]))(process.versions.node, "8.9") |
| 392 |
? require.resolve |
| 393 |
: (/* request */ r, { paths: [/* base */ b] }, M = require("module")) => { |
| 394 |
let /* filename */ f = M._findPath(r, M._nodeModulePaths(b).concat(b)); |
| 395 |
if (f) return f; |
| 396 |
f = new Error(\`Cannot resolve module '\${r}'\`); |
| 397 |
f.code = "MODULE_NOT_FOUND"; |
| 398 |
throw f; |
| 399 |
} |
| 400 |
`, |
| 401 |
}, |
| 402 |
{ |
| 403 |
// NOTE: This polyfills depends on the "make-dir" library. Any package |
| 404 |
// using fs.mkdirSync must have "make-dir" as a dependency. |
| 405 |
name: "fs.mkdirSync", |
| 406 |
necessary({ node, parent }) { |
| 407 |
return ( |
| 408 |
t.isCallExpression(parent, { callee: node }) && |
| 409 |
parent.arguments.length > 1 |
| 410 |
); |
| 411 |
}, |
| 412 |
supported({ parent: { arguments: args } }) { |
| 413 |
return ( |
| 414 |
t.isObjectExpression(args[1]) && |
| 415 |
args[1].properties.length === 1 && |
| 416 |
t.isIdentifier(args[1].properties[0].key, { name: "recursive" }) && |
| 417 |
t.isBooleanLiteral(args[1].properties[0].value, { value: true }) |
| 418 |
); |
| 419 |
}, |
| 420 |
// fs.mkdirSync's recursive option has been introduced in Node.js 10.12 |
| 421 |
// https://nodejs.org/api/fs.html#fs_fs_mkdirsync_path_options |
| 422 |
replacement: template` |
| 423 |
((v,w)=>(v=v.split("."),w=w.split("."),+v[0]>+w[0]||v[0]==w[0]&&+v[1]>=+w[1]))(process.versions.node, "10.12") |
| 424 |
? fs.mkdirSync |
| 425 |
: require("make-dir").sync |
| 426 |
`, |
| 427 |
}, |
| 428 |
{ |
| 429 |
// NOTE: This polyfills depends on the "node-environment-flags" |
| 430 |
// library. Any package using process.allowedNodeEnvironmentFlags |
| 431 |
// must have "node-environment-flags" as a dependency. |
| 432 |
name: "process.allowedNodeEnvironmentFlags", |
| 433 |
necessary({ parent, node }) { |
| 434 |
// To avoid infinite replacement loops |
| 435 |
return !t.isLogicalExpression(parent, { operator: "||", left: node }); |
| 436 |
}, |
| 437 |
supported: () => true, |
| 438 |
// process.allowedNodeEnvironmentFlags has been introduced in Node.js 10.10 |
| 439 |
// https://nodejs.org/api/process.html#process_process_allowednodeenvironmentflags |
| 440 |
replacement: template` |
| 441 |
process.allowedNodeEnvironmentFlags || require("node-environment-flags") |
| 442 |
`, |
| 443 |
}, |
| 444 |
]; |
| 445 |
|
| 446 |
return { |
| 447 |
visitor: { |
| 448 |
MemberExpression(path) { |
| 449 |
for (const polyfill of polyfills) { |
| 450 |
if (!path.matchesPattern(polyfill.name)) continue; |
| 451 |
|
| 452 |
if (!polyfill.necessary(path)) return; |
| 453 |
if (!polyfill.supported(path)) { |
| 454 |
throw path.buildCodeFrameError( |
| 455 |
`This '${polyfill.name}' usage is not supported by the inline polyfill.` |
| 456 |
); |
| 457 |
} |
| 458 |
|
| 459 |
path.replaceWith(polyfill.replacement()); |
| 460 |
|
| 461 |
break; |
| 462 |
} |
| 463 |
}, |
| 464 |
}, |
| 465 |
}; |
| 466 |
} |
| 467 |
function pluginToggleBooleanFlag({ types: t }, { name, value }) { |
| 468 |
return { |
| 469 |
visitor: { |
| 470 |
"IfStatement|ConditionalExpression"(path) { |
| 471 |
let test = path.get("test"); |
| 472 |
let keepConsequent = value; |
| 473 |
|
| 474 |
if (test.isUnaryExpression({ operator: "!" })) { |
| 475 |
test = test.get("argument"); |
| 476 |
keepConsequent = !keepConsequent; |
| 477 |
} |
| 478 |
|
| 479 |
// yarn-plugin-conditions injects bool(process.env.BABEL_8_BREAKING) |
| 480 |
// tests, to properly cast the env variable to a boolean. |
| 481 |
if ( |
| 482 |
test.isCallExpression() && |
| 483 |
test.get("callee").isIdentifier({ name: "bool" }) && |
| 484 |
test.get("arguments").length === 1 |
| 485 |
) { |
| 486 |
test = test.get("arguments")[0]; |
| 487 |
} |
| 488 |
|
| 489 |
if (!test.isIdentifier({ name }) && !test.matchesPattern(name)) return; |
| 490 |
|
| 491 |
path.replaceWith( |
| 492 |
keepConsequent |
| 493 |
? path.node.consequent |
| 494 |
: path.node.alternate || t.emptyStatement() |
| 495 |
); |
| 496 |
}, |
| 497 |
MemberExpression(path) { |
| 498 |
if (path.matchesPattern(name)) { |
| 499 |
throw path.buildCodeFrameError("This check could not be stripped."); |
| 500 |
} |
| 501 |
}, |
| 502 |
ReferencedIdentifier(path) { |
| 503 |
if (path.node.name === name) { |
| 504 |
throw path.buildCodeFrameError("This check could not be stripped."); |
| 505 |
} |
| 506 |
}, |
| 507 |
}, |
| 508 |
}; |
| 509 |
} |
| 510 |
|
| 511 |
function pluginPackageJsonMacro({ types: t }) { |
| 512 |
const fnName = "PACKAGE_JSON"; |
| 513 |
|
| 514 |
return { |
| 515 |
visitor: { |
| 516 |
ReferencedIdentifier(path) { |
| 517 |
if (path.isIdentifier({ name: fnName })) { |
| 518 |
throw path.buildCodeFrameError( |
| 519 |
`"${fnName}" is only supported in member expressions.` |
| 520 |
); |
| 521 |
} |
| 522 |
}, |
| 523 |
MemberExpression(path) { |
| 524 |
if (!path.get("object").isIdentifier({ name: fnName })) return; |
| 525 |
|
| 526 |
if (path.node.computed) { |
| 527 |
throw path.buildCodeFrameError( |
| 528 |
`"${fnName}" does not support computed properties.` |
| 529 |
); |
| 530 |
} |
| 531 |
const field = path.node.property.name; |
| 532 |
|
| 533 |
// TODO: When dropping old Node.js versions, use require.resolve |
| 534 |
// instead of looping through the folders hierarchy |
| 535 |
|
| 536 |
let pkg; |
| 537 |
for (let dir = pathUtils.dirname(this.filename); ; ) { |
| 538 |
try { |
| 539 |
pkg = fs.readFileSync(pathUtils.join(dir, "package.json"), "utf8"); |
| 540 |
break; |
| 541 |
} catch (_) {} |
| 542 |
|
| 543 |
const prev = dir; |
| 544 |
dir = pathUtils.resolve(dir, ".."); |
| 545 |
|
| 546 |
// We are in the root and didn't find a package.json file |
| 547 |
if (dir === prev) return; |
| 548 |
} |
| 549 |
|
| 550 |
const value = JSON.parse(pkg)[field]; |
| 551 |
path.replaceWith(t.valueToNode(value)); |
| 552 |
}, |
| 553 |
}, |
| 554 |
}; |
| 555 |
} |
| 556 |
|
| 557 |
// transform `import { x } from "@babel/types"` to `import * as _t from "@babel/types"; const { x } = _t; |
| 558 |
function transformNamedBabelTypesImportToDestructuring({ |
| 559 |
types: { |
| 560 |
cloneNode, |
| 561 |
importNamespaceSpecifier, |
| 562 |
objectPattern, |
| 563 |
objectProperty, |
| 564 |
variableDeclarator, |
| 565 |
variableDeclaration, |
| 566 |
}, |
| 567 |
}) { |
| 568 |
return { |
| 569 |
name: "transform-babel-types-named-imports", |
| 570 |
visitor: { |
| 571 |
ImportDeclaration(path) { |
| 572 |
const { node } = path; |
| 573 |
if ( |
| 574 |
node.importKind === "value" && |
| 575 |
node.source.value === "@babel/types" && |
| 576 |
node.specifiers[0].type === "ImportSpecifier" |
| 577 |
) { |
| 578 |
const hoistedDestructuringProperties = []; |
| 579 |
for (const { imported, local } of node.specifiers) { |
| 580 |
hoistedDestructuringProperties.push( |
| 581 |
objectProperty( |
| 582 |
imported, |
| 583 |
local, |
| 584 |
false, |
| 585 |
imported.name === local.name |
| 586 |
) |
| 587 |
); |
| 588 |
} |
| 589 |
const babelTypeNsImport = path.scope.generateUidIdentifier("t"); |
| 590 |
node.specifiers = [importNamespaceSpecifier(babelTypeNsImport)]; |
| 591 |
path.insertAfter([ |
| 592 |
variableDeclaration("const", [ |
| 593 |
variableDeclarator( |
| 594 |
objectPattern(hoistedDestructuringProperties), |
| 595 |
cloneNode(babelTypeNsImport) |
| 596 |
), |
| 597 |
]), |
| 598 |
]); |
| 599 |
} |
| 600 |
}, |
| 601 |
}, |
| 602 |
}; |
| 603 |
} |
| 604 |
|
| 605 |
function pluginImportMetaUrl({ types: t, template }) { |
| 606 |
const isImportMeta = node => |
| 607 |
t.isMetaProperty(node) && |
| 608 |
t.isIdentifier(node.meta, { name: "import" }) && |
| 609 |
t.isIdentifier(node.property, { name: "meta" }); |
| 610 |
|
| 611 |
const isImportMetaUrl = node => |
| 612 |
t.isMemberExpression(node, { computed: false }) && |
| 613 |
t.isIdentifier(node.property, { name: "url" }) && |
| 614 |
isImportMeta(node.object); |
| 615 |
|
| 616 |
return { |
| 617 |
visitor: { |
| 618 |
Program(programPath) { |
| 619 |
// We must be sure to run this before the instanbul plugins, because its |
| 620 |
// instrumentation breaks our detection. |
| 621 |
programPath.traverse({ |
| 622 |
// fileURLToPath(import.meta.url) |
| 623 |
CallExpression(path) { |
| 624 |
const { node } = path; |
| 625 |
|
| 626 |
if ( |
| 627 |
!t.isIdentifier(node.callee, { name: "fileURLToPath" }) || |
| 628 |
node.arguments.length !== 1 |
| 629 |
) { |
| 630 |
return; |
| 631 |
} |
| 632 |
|
| 633 |
const arg = node.arguments[0]; |
| 634 |
|
| 635 |
if ( |
| 636 |
!t.isMemberExpression(arg, { computed: false }) || |
| 637 |
!t.isIdentifier(arg.property, { name: "url" }) || |
| 638 |
!isImportMeta(arg.object) |
| 639 |
) { |
| 640 |
return; |
| 641 |
} |
| 642 |
|
| 643 |
path.replaceWith(t.identifier("__filename")); |
| 644 |
}, |
| 645 |
|
| 646 |
// const require = createRequire(import.meta.url) |
| 647 |
VariableDeclarator(path) { |
| 648 |
const { node } = path; |
| 649 |
|
| 650 |
if ( |
| 651 |
!t.isIdentifier(node.id, { name: "require" }) || |
| 652 |
!t.isCallExpression(node.init) || |
| 653 |
!t.isIdentifier(node.init.callee, { name: "createRequire" }) || |
| 654 |
node.init.arguments.length !== 1 || |
| 655 |
!isImportMetaUrl(node.init.arguments[0]) |
| 656 |
) { |
| 657 |
return; |
| 658 |
} |
| 659 |
|
| 660 |
// Let's just remove this declaration to unshadow the "global" cjs require. |
| 661 |
path.remove(); |
| 662 |
}, |
| 663 |
|
| 664 |
// import.meta.url |
| 665 |
MemberExpression(path) { |
| 666 |
if (!isImportMetaUrl(path.node)) return; |
| 667 |
|
| 668 |
path.replaceWith( |
| 669 |
template.expression |
| 670 |
.ast`\`file://\${__filename.replace(/\\\\/g, "/")}\`` |
| 671 |
); |
| 672 |
}, |
| 673 |
|
| 674 |
MetaProperty(path) { |
| 675 |
if (isImportMeta(path.node)) { |
| 676 |
throw path.buildCodeFrameError("Unsupported import.meta"); |
| 677 |
} |
| 678 |
}, |
| 679 |
}); |
| 680 |
}, |
| 681 |
}, |
| 682 |
}; |
| 683 |
} |
| 684 |
|
| 685 |
function pluginAddImportExtension(api, { when }) { |
| 686 |
return { |
| 687 |
visitor: { |
| 688 |
"ImportDeclaration|ExportDeclaration"({ node }) { |
| 689 |
const { source } = node; |
| 690 |
if (!source) return; |
| 691 |
|
| 692 |
if ( |
| 693 |
when === "always" && |
| 694 |
source.value.startsWith(".") && |
| 695 |
!/\.[a-z]+$/.test(source.value) |
| 696 |
) { |
| 697 |
const dir = pathUtils.dirname(this.filename); |
| 698 |
|
| 699 |
try { |
| 700 |
const pkg = JSON.parse( |
| 701 |
fs.readFileSync( |
| 702 |
pathUtils.join(dir, `${source.value}/package.json`) |
| 703 |
), |
| 704 |
"utf8" |
| 705 |
); |
| 706 |
|
| 707 |
if (pkg.main) source.value = pathUtils.join(source.value, pkg.main); |
| 708 |
} catch (_) {} |
| 709 |
|
| 710 |
try { |
| 711 |
if (fs.statSync(pathUtils.join(dir, source.value)).isFile()) return; |
| 712 |
} catch (_) {} |
| 713 |
|
| 714 |
for (const [src, lib = src] of [["ts", "js"], ["js"], ["cjs"]]) { |
| 715 |
try { |
| 716 |
fs.statSync(pathUtils.join(dir, `${source.value}.${src}`)); |
| 717 |
source.value += `.${lib}`; |
| 718 |
return; |
| 719 |
} catch (_) {} |
| 720 |
} |
| 721 |
|
| 722 |
source.value += "/index.js"; |
| 723 |
} |
| 724 |
if ( |
| 725 |
source.value.startsWith("lodash/") || |
| 726 |
source.value.startsWith("core-js-compat/") || |
| 727 |
source.value === "core-js/stable/index" || |
| 728 |
source.value === "regenerator-runtime/runtime" || |
| 729 |
source.value === "babel-plugin-dynamic-import-node/utils" |
| 730 |
) { |
| 731 |
source.value += ".js"; |
| 732 |
} |
| 733 |
if (source.value.startsWith("@babel/preset-modules/")) { |
| 734 |
source.value += "/index.js"; |
| 735 |
} |
| 736 |
}, |
| 737 |
}, |
| 738 |
}; |
| 739 |
} |
| 740 |
|
| 741 |
const tokenTypesMapping = new Map(); |
| 742 |
const tokenTypeSourcePath = "./packages/babel-parser/src/tokenizer/types.ts"; |
| 743 |
|
| 744 |
function getTokenTypesMapping() { |
| 745 |
if (tokenTypesMapping.size === 0) { |
| 746 |
const tokenTypesAst = parseSync( |
| 747 |
fs.readFileSync(tokenTypeSourcePath, { |
| 748 |
encoding: "utf-8", |
| 749 |
}), |
| 750 |
{ |
| 751 |
configFile: false, |
| 752 |
parserOpts: { attachComments: false, plugins: ["typescript"] }, |
| 753 |
} |
| 754 |
); |
| 755 |
|
| 756 |
let typesDeclaration; |
| 757 |
for (const n of tokenTypesAst.program.body) { |
| 758 |
if (n.type === "ExportNamedDeclaration" && n.exportKind === "value") { |
| 759 |
const declarations = n.declaration.declarations; |
| 760 |
if (declarations !== undefined) typesDeclaration = declarations[0]; |
| 761 |
if ( |
| 762 |
typesDeclaration !== undefined && |
| 763 |
typesDeclaration.id.name === "types" |
| 764 |
) { |
| 765 |
break; |
| 766 |
} |
| 767 |
} |
| 768 |
} |
| 769 |
if (typesDeclaration === undefined) { |
| 770 |
throw new Error( |
| 771 |
"The plugin can not find TokenType definition in " + tokenTypeSourcePath |
| 772 |
); |
| 773 |
} |
| 774 |
|
| 775 |
const tokenTypesDefinition = typesDeclaration.init.expression.properties; |
| 776 |
for (let i = 0; i < tokenTypesDefinition.length; i++) { |
| 777 |
tokenTypesMapping.set(tokenTypesDefinition[i].key.name, i); |
| 778 |
} |
| 779 |
} |
| 780 |
return tokenTypesMapping; |
| 781 |
} |
| 782 |
|
| 783 |
function pluginBabelParserTokenType({ |
| 784 |
types: { isIdentifier, numericLiteral }, |
| 785 |
}) { |
| 786 |
return { |
| 787 |
visitor: { |
| 788 |
MemberExpression(path) { |
| 789 |
const { node } = path; |
| 790 |
if ( |
| 791 |
isIdentifier(node.object, { name: "tt" }) && |
| 792 |
isIdentifier(node.property) && |
| 793 |
!node.computed |
| 794 |
) { |
| 795 |
const tokenName = node.property.name; |
| 796 |
const tokenType = getTokenTypesMapping().get(node.property.name); |
| 797 |
if (tokenType === undefined) { |
| 798 |
throw path.buildCodeFrameError( |
| 799 |
`${tokenName} is not defined in ${tokenTypeSourcePath}` |
| 800 |
); |
| 801 |
} |
| 802 |
path.replaceWith(numericLiteral(tokenType)); |
| 803 |
} |
| 804 |
}, |
| 805 |
}, |
| 806 |
}; |
| 807 |
} |
| 808 |
|
| 809 |
// Inject `0 && exports.foo = 0` hints for the specified exports, |
| 810 |
// to help the Node.js CJS-ESM interop. This is only |
| 811 |
// needed when compiling ESM re-exports to CJS in `lazy` mode. |
| 812 |
function pluginInjectNodeReexportsHints({ types: t, template }, { names }) { |
| 813 |
return { |
| 814 |
visitor: { |
| 815 |
Program: { |
| 816 |
exit(path) { |
| 817 |
const seen = []; |
| 818 |
for (const stmt of path.get("body")) { |
| 819 |
if (!stmt.isExpressionStatement()) continue; |
| 820 |
const expr = stmt.get("expression"); |
| 821 |
if ( |
| 822 |
!expr.isCallExpression() || |
| 823 |
!expr.get("callee").matchesPattern("Object.defineProperty") || |
| 824 |
expr.node.arguments.length !== 3 || |
| 825 |
!expr.get("arguments.0").isIdentifier({ name: "exports" }) || |
| 826 |
!expr.get("arguments.1").isStringLiteral() || |
| 827 |
!names.includes(expr.node.arguments[1].value) |
| 828 |
) { |
| 829 |
continue; |
| 830 |
} |
| 831 |
|
| 832 |
expr |
| 833 |
.get("arguments.0") |
| 834 |
.replaceWith(template.expression.ast`(0, exports)`); |
| 835 |
seen.push(expr.node.arguments[1].value); |
| 836 |
} |
| 837 |
|
| 838 |
const assign = seen.reduce( |
| 839 |
(rhs, name) => template.expression.ast`exports.${name} = ${rhs}`, |
| 840 |
t.numericLiteral(0) |
| 841 |
); |
| 842 |
path.pushContainer("body", template.statement.ast`0 && (${assign})`); |
| 843 |
}, |
| 844 |
}, |
| 845 |
}, |
| 846 |
}; |
| 847 |
} |
| 848 |
|
| 849 |
/** |
| 850 |
* @param {import("@babel/core")} pluginAPI |
| 851 |
* @returns {import("@babel/core").PluginObj} |
| 852 |
*/ |
| 853 |
function pluginGeneratorOptimization({ types: t }) { |
| 854 |
return { |
| 855 |
visitor: { |
| 856 |
CallExpression: { |
| 857 |
exit(path) { |
| 858 |
const node = path.node; |
| 859 |
if ( |
| 860 |
t.isMemberExpression(node.callee) && |
| 861 |
t.isThisExpression(node.callee.object) |
| 862 |
) { |
| 863 |
const args = node.arguments; |
| 864 |
|
| 865 |
if ( |
| 866 |
node.callee.property.name === "token" && |
| 867 |
args.length === 1 && |
| 868 |
t.isStringLiteral(args[0]) |
| 869 |
) { |
| 870 |
const str = args[0].value; |
| 871 |
if (str.length == 1) { |
| 872 |
node.callee.property.name = "tokenChar"; |
| 873 |
args[0] = t.numericLiteral(str.charCodeAt(0)); |
| 874 |
} |
| 875 |
} |
| 876 |
} |
| 877 |
}, |
| 878 |
}, |
| 879 |
}, |
| 880 |
}; |
| 881 |
} |