This commit is contained in:
2022-07-18 02:50:52 +00:00
parent befd344ab0
commit 06181b34d6
8569 changed files with 818704 additions and 352705 deletions
+3 -3
View File
@@ -2,18 +2,18 @@
> Babel helper functions for implementing ES6 module transformations
See our website [@babel/helper-module-transforms](https://babeljs.io/docs/en/next/babel-helper-module-transforms.html) for more information.
See our website [@babel/helper-module-transforms](https://babeljs.io/docs/en/babel-helper-module-transforms) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/helper-module-transforms
npm install --save @babel/helper-module-transforms
```
or using yarn:
```sh
yarn add @babel/helper-module-transforms --dev
yarn add @babel/helper-module-transforms
```
+19 -7
View File
@@ -4,20 +4,32 @@ Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getModuleName;
{
const originalGetModuleName = getModuleName;
exports.default = getModuleName = function getModuleName(rootOpts, pluginOpts) {
var _pluginOpts$moduleId, _pluginOpts$moduleIds, _pluginOpts$getModule, _pluginOpts$moduleRoo;
return originalGetModuleName(rootOpts, {
moduleId: (_pluginOpts$moduleId = pluginOpts.moduleId) != null ? _pluginOpts$moduleId : rootOpts.moduleId,
moduleIds: (_pluginOpts$moduleIds = pluginOpts.moduleIds) != null ? _pluginOpts$moduleIds : rootOpts.moduleIds,
getModuleId: (_pluginOpts$getModule = pluginOpts.getModuleId) != null ? _pluginOpts$getModule : rootOpts.getModuleId,
moduleRoot: (_pluginOpts$moduleRoo = pluginOpts.moduleRoot) != null ? _pluginOpts$moduleRoo : rootOpts.moduleRoot
});
};
}
function getModuleName(rootOpts, pluginOpts) {
var _pluginOpts$moduleRoo, _rootOpts$moduleIds, _rootOpts$moduleRoot;
const {
filename,
filenameRelative = filename,
sourceRoot = (_pluginOpts$moduleRoo = pluginOpts.moduleRoot) != null ? _pluginOpts$moduleRoo : rootOpts.moduleRoot
sourceRoot = pluginOpts.moduleRoot
} = rootOpts;
const {
moduleId = rootOpts.moduleId,
moduleIds = (_rootOpts$moduleIds = rootOpts.moduleIds) != null ? _rootOpts$moduleIds : !!moduleId,
getModuleId = rootOpts.getModuleId,
moduleRoot = (_rootOpts$moduleRoot = rootOpts.moduleRoot) != null ? _rootOpts$moduleRoot : sourceRoot
moduleId,
moduleIds = !!moduleId,
getModuleId,
moduleRoot = sourceRoot
} = pluginOpts;
if (!moduleIds) return null;
+195 -87
View File
@@ -3,20 +3,12 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.rewriteModuleStatementsAndPrepareHeader = rewriteModuleStatementsAndPrepareHeader;
exports.ensureStatementsHoisted = ensureStatementsHoisted;
exports.wrapInterop = wrapInterop;
exports.buildNamespaceInitStatements = buildNamespaceInitStatements;
Object.defineProperty(exports, "isModule", {
exports.ensureStatementsHoisted = ensureStatementsHoisted;
Object.defineProperty(exports, "getModuleName", {
enumerable: true,
get: function () {
return _helperModuleImports.isModule;
}
});
Object.defineProperty(exports, "rewriteThis", {
enumerable: true,
get: function () {
return _rewriteThis.default;
return _getModuleName.default;
}
});
Object.defineProperty(exports, "hasExports", {
@@ -25,60 +17,85 @@ Object.defineProperty(exports, "hasExports", {
return _normalizeAndLoadMetadata.hasExports;
}
});
Object.defineProperty(exports, "isModule", {
enumerable: true,
get: function () {
return _helperModuleImports.isModule;
}
});
Object.defineProperty(exports, "isSideEffectImport", {
enumerable: true,
get: function () {
return _normalizeAndLoadMetadata.isSideEffectImport;
}
});
Object.defineProperty(exports, "getModuleName", {
exports.rewriteModuleStatementsAndPrepareHeader = rewriteModuleStatementsAndPrepareHeader;
Object.defineProperty(exports, "rewriteThis", {
enumerable: true,
get: function () {
return _getModuleName.default;
return _rewriteThis.default;
}
});
exports.wrapInterop = wrapInterop;
var _assert = _interopRequireDefault(require("assert"));
var _assert = require("assert");
var t = _interopRequireWildcard(require("@babel/types"));
var _t = require("@babel/types");
var _template = _interopRequireDefault(require("@babel/template"));
var _chunk = _interopRequireDefault(require("lodash/chunk"));
var _template = require("@babel/template");
var _helperModuleImports = require("@babel/helper-module-imports");
var _rewriteThis = _interopRequireDefault(require("./rewrite-this"));
var _rewriteThis = require("./rewrite-this");
var _rewriteLiveReferences = _interopRequireDefault(require("./rewrite-live-references"));
var _rewriteLiveReferences = require("./rewrite-live-references");
var _normalizeAndLoadMetadata = _interopRequireWildcard(require("./normalize-and-load-metadata"));
var _normalizeAndLoadMetadata = require("./normalize-and-load-metadata");
var _getModuleName = _interopRequireDefault(require("./get-module-name"));
var _getModuleName = require("./get-module-name");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const {
booleanLiteral,
callExpression,
cloneNode,
directive,
directiveLiteral,
expressionStatement,
identifier,
isIdentifier,
memberExpression,
stringLiteral,
valueToNode,
variableDeclaration,
variableDeclarator
} = _t;
function rewriteModuleStatementsAndPrepareHeader(path, {
loose,
exportName,
strict,
allowTopLevelThis,
strictMode,
loose,
noInterop,
importInterop = noInterop ? "none" : "babel",
lazy,
esNamespaceOnly
esNamespaceOnly,
filename,
constantReexports = loose,
enumerableModuleMeta = loose,
noIncompleteNsImportDetection
}) {
(0, _assert.default)((0, _helperModuleImports.isModule)(path), "Cannot process module statements in a script");
(0, _normalizeAndLoadMetadata.validateImportInteropOption)(importInterop);
_assert((0, _helperModuleImports.isModule)(path), "Cannot process module statements in a script");
path.node.sourceType = "script";
const meta = (0, _normalizeAndLoadMetadata.default)(path, exportName, {
noInterop,
loose,
importInterop,
initializeReexports: constantReexports,
lazy,
esNamespaceOnly
esNamespaceOnly,
filename
});
if (!allowTopLevelThis) {
@@ -93,14 +110,14 @@ function rewriteModuleStatementsAndPrepareHeader(path, {
});
if (!hasStrict) {
path.unshiftContainer("directives", t.directive(t.directiveLiteral("use strict")));
path.unshiftContainer("directives", directive(directiveLiteral("use strict")));
}
}
const headers = [];
if ((0, _normalizeAndLoadMetadata.hasExports)(meta) && !strict) {
headers.push(buildESModuleHeader(meta, loose));
headers.push(buildESModuleHeader(meta, enumerableModuleMeta));
}
const nameList = buildExportNameListDeclaration(path, meta);
@@ -110,7 +127,7 @@ function rewriteModuleStatementsAndPrepareHeader(path, {
headers.push(nameList.statement);
}
headers.push(...buildExportInitializationStatements(path, meta, loose));
headers.push(...buildExportInitializationStatements(path, meta, constantReexports, noIncompleteNsImportDetection));
return {
meta,
headers
@@ -128,6 +145,12 @@ function wrapInterop(programPath, expr, type) {
return null;
}
if (type === "node-namespace") {
return callExpression(programPath.hub.addHelper("interopRequireWildcard"), [expr, booleanLiteral(true)]);
} else if (type === "node-default") {
return null;
}
let helper;
if (type === "default") {
@@ -138,24 +161,24 @@ function wrapInterop(programPath, expr, type) {
throw new Error(`Unknown interop: ${type}`);
}
return t.callExpression(programPath.hub.addHelper(helper), [expr]);
return callExpression(programPath.hub.addHelper(helper), [expr]);
}
function buildNamespaceInitStatements(metadata, sourceMetadata, loose = false) {
function buildNamespaceInitStatements(metadata, sourceMetadata, constantReexports = false) {
const statements = [];
let srcNamespace = t.identifier(sourceMetadata.name);
if (sourceMetadata.lazy) srcNamespace = t.callExpression(srcNamespace, []);
let srcNamespace = identifier(sourceMetadata.name);
if (sourceMetadata.lazy) srcNamespace = callExpression(srcNamespace, []);
for (const localName of sourceMetadata.importsNamespace) {
if (localName === sourceMetadata.name) continue;
statements.push(_template.default.statement`var NAME = SOURCE;`({
NAME: localName,
SOURCE: t.cloneNode(srcNamespace)
SOURCE: cloneNode(srcNamespace)
}));
}
if (loose) {
statements.push(...buildReexportsFromMeta(metadata, sourceMetadata, loose));
if (constantReexports) {
statements.push(...buildReexportsFromMeta(metadata, sourceMetadata, true));
}
for (const exportName of sourceMetadata.reexportNamespace) {
@@ -169,12 +192,12 @@ function buildNamespaceInitStatements(metadata, sourceMetadata, loose = false) {
` : _template.default.statement`EXPORTS.NAME = NAMESPACE;`)({
EXPORTS: metadata.exportName,
NAME: exportName,
NAMESPACE: t.cloneNode(srcNamespace)
NAMESPACE: cloneNode(srcNamespace)
}));
}
if (sourceMetadata.reexportAll) {
const statement = buildNamespaceReexport(metadata, t.cloneNode(srcNamespace), loose);
const statement = buildNamespaceReexport(metadata, cloneNode(srcNamespace), constantReexports);
statement.loc = sourceMetadata.reexportAll.loc;
statements.push(statement);
}
@@ -182,30 +205,53 @@ function buildNamespaceInitStatements(metadata, sourceMetadata, loose = false) {
return statements;
}
const getTemplateForReexport = loose => {
return loose ? _template.default.statement`EXPORTS.EXPORT_NAME = NAMESPACE.IMPORT_NAME;` : (0, _template.default)`
Object.defineProperty(EXPORTS, "EXPORT_NAME", {
enumerable: true,
get: function() {
return NAMESPACE.IMPORT_NAME;
},
});
`;
const ReexportTemplate = {
constant: _template.default.statement`EXPORTS.EXPORT_NAME = NAMESPACE_IMPORT;`,
constantComputed: _template.default.statement`EXPORTS["EXPORT_NAME"] = NAMESPACE_IMPORT;`,
spec: _template.default.statement`
Object.defineProperty(EXPORTS, "EXPORT_NAME", {
enumerable: true,
get: function() {
return NAMESPACE_IMPORT;
},
});
`
};
const buildReexportsFromMeta = (meta, metadata, loose) => {
const namespace = metadata.lazy ? t.callExpression(t.identifier(metadata.name), []) : t.identifier(metadata.name);
const templateForCurrentMode = getTemplateForReexport(loose);
return Array.from(metadata.reexports, ([exportName, importName]) => templateForCurrentMode({
EXPORTS: meta.exportName,
EXPORT_NAME: exportName,
NAMESPACE: t.cloneNode(namespace),
IMPORT_NAME: importName
}));
const buildReexportsFromMeta = (meta, metadata, constantReexports) => {
const namespace = metadata.lazy ? callExpression(identifier(metadata.name), []) : identifier(metadata.name);
const {
stringSpecifiers
} = meta;
return Array.from(metadata.reexports, ([exportName, importName]) => {
let NAMESPACE_IMPORT = cloneNode(namespace);
if (importName === "default" && metadata.interop === "node-default") {} else if (stringSpecifiers.has(importName)) {
NAMESPACE_IMPORT = memberExpression(NAMESPACE_IMPORT, stringLiteral(importName), true);
} else {
NAMESPACE_IMPORT = memberExpression(NAMESPACE_IMPORT, identifier(importName));
}
const astNodes = {
EXPORTS: meta.exportName,
EXPORT_NAME: exportName,
NAMESPACE_IMPORT
};
if (constantReexports || isIdentifier(NAMESPACE_IMPORT)) {
if (stringSpecifiers.has(exportName)) {
return ReexportTemplate.constantComputed(astNodes);
} else {
return ReexportTemplate.constant(astNodes);
}
} else {
return ReexportTemplate.spec(astNodes);
}
});
};
function buildESModuleHeader(metadata, enumerable = false) {
return (enumerable ? _template.default.statement`
function buildESModuleHeader(metadata, enumerableModuleMeta = false) {
return (enumerableModuleMeta ? _template.default.statement`
EXPORTS.__esModule = true;
` : _template.default.statement`
Object.defineProperty(EXPORTS, "__esModule", {
@@ -216,11 +262,12 @@ function buildESModuleHeader(metadata, enumerable = false) {
});
}
function buildNamespaceReexport(metadata, namespace, loose) {
return (loose ? _template.default.statement`
function buildNamespaceReexport(metadata, namespace, constantReexports) {
return (constantReexports ? _template.default.statement`
Object.keys(NAMESPACE).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
VERIFY_NAME_LIST;
if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return;
EXPORTS[key] = NAMESPACE[key];
});
@@ -228,6 +275,7 @@ function buildNamespaceReexport(metadata, namespace, loose) {
Object.keys(NAMESPACE).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
VERIFY_NAME_LIST;
if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return;
Object.defineProperty(EXPORTS, key, {
enumerable: true,
@@ -267,7 +315,7 @@ function buildExportNameListDeclaration(programPath, metadata) {
exportedVars[exportName] = true;
}
hasReexport = hasReexport || data.reexportAll;
hasReexport = hasReexport || !!data.reexportAll;
}
if (!hasReexport || Object.keys(exportedVars).length === 0) return null;
@@ -275,42 +323,102 @@ function buildExportNameListDeclaration(programPath, metadata) {
delete exportedVars.default;
return {
name: name.name,
statement: t.variableDeclaration("var", [t.variableDeclarator(name, t.valueToNode(exportedVars))])
statement: variableDeclaration("var", [variableDeclarator(name, valueToNode(exportedVars))])
};
}
function buildExportInitializationStatements(programPath, metadata, loose = false) {
function buildExportInitializationStatements(programPath, metadata, constantReexports = false, noIncompleteNsImportDetection = false) {
const initStatements = [];
const exportNames = [];
for (const [localName, data] of metadata.local) {
if (data.kind === "import") {} else if (data.kind === "hoisted") {
initStatements.push(buildInitStatement(metadata, data.names, t.identifier(localName)));
} else {
exportNames.push(...data.names);
initStatements.push([data.names[0], buildInitStatement(metadata, data.names, identifier(localName))]);
} else if (!noIncompleteNsImportDetection) {
for (const exportName of data.names) {
initStatements.push([exportName, null]);
}
}
}
for (const data of metadata.source.values()) {
if (!loose) {
initStatements.push(...buildReexportsFromMeta(metadata, data, loose));
if (!constantReexports) {
const reexportsStatements = buildReexportsFromMeta(metadata, data, false);
const reexports = [...data.reexports.keys()];
for (let i = 0; i < reexportsStatements.length; i++) {
initStatements.push([reexports[i], reexportsStatements[i]]);
}
}
for (const exportName of data.reexportNamespace) {
exportNames.push(exportName);
if (!noIncompleteNsImportDetection) {
for (const exportName of data.reexportNamespace) {
initStatements.push([exportName, null]);
}
}
}
initStatements.push(...(0, _chunk.default)(exportNames, 100).map(members => {
return buildInitStatement(metadata, members, programPath.scope.buildUndefinedNode());
}));
return initStatements;
initStatements.sort(([a], [b]) => {
if (a < b) return -1;
if (b < a) return 1;
return 0;
});
const results = [];
if (noIncompleteNsImportDetection) {
for (const [, initStatement] of initStatements) {
results.push(initStatement);
}
} else {
const chunkSize = 100;
for (let i = 0; i < initStatements.length; i += chunkSize) {
let uninitializedExportNames = [];
for (let j = 0; j < chunkSize && i + j < initStatements.length; j++) {
const [exportName, initStatement] = initStatements[i + j];
if (initStatement !== null) {
if (uninitializedExportNames.length > 0) {
results.push(buildInitStatement(metadata, uninitializedExportNames, programPath.scope.buildUndefinedNode()));
uninitializedExportNames = [];
}
results.push(initStatement);
} else {
uninitializedExportNames.push(exportName);
}
}
if (uninitializedExportNames.length > 0) {
results.push(buildInitStatement(metadata, uninitializedExportNames, programPath.scope.buildUndefinedNode()));
}
}
}
return results;
}
const InitTemplate = {
computed: _template.default.expression`EXPORTS["NAME"] = VALUE`,
default: _template.default.expression`EXPORTS.NAME = VALUE`
};
function buildInitStatement(metadata, exportNames, initExpr) {
return t.expressionStatement(exportNames.reduce((acc, exportName) => _template.default.expression`EXPORTS.NAME = VALUE`({
EXPORTS: metadata.exportName,
NAME: exportName,
VALUE: acc
}), initExpr));
const {
stringSpecifiers,
exportName: EXPORTS
} = metadata;
return expressionStatement(exportNames.reduce((acc, exportName) => {
const params = {
EXPORTS,
NAME: exportName,
VALUE: acc
};
if (stringSpecifiers.has(exportName)) {
return InitTemplate.computed(params);
} else {
return InitTemplate.default(params);
}
}, initExpr));
}
@@ -3,15 +3,16 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = normalizeModuleAndLoadMetadata;
exports.hasExports = hasExports;
exports.isSideEffectImport = isSideEffectImport;
exports.default = normalizeModuleAndLoadMetadata;
exports.validateImportInteropOption = validateImportInteropOption;
var _path = require("path");
var _helperSplitExportDeclaration = _interopRequireDefault(require("@babel/helper-split-export-declaration"));
var _helperValidatorIdentifier = require("@babel/helper-validator-identifier");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _helperSplitExportDeclaration = require("@babel/helper-split-export-declaration");
function hasExports(metadata) {
return metadata.hasExports;
@@ -21,25 +22,43 @@ function isSideEffectImport(source) {
return source.imports.size === 0 && source.importsNamespace.size === 0 && source.reexports.size === 0 && source.reexportNamespace.size === 0 && !source.reexportAll;
}
function validateImportInteropOption(importInterop) {
if (typeof importInterop !== "function" && importInterop !== "none" && importInterop !== "babel" && importInterop !== "node") {
throw new Error(`.importInterop must be one of "none", "babel", "node", or a function returning one of those values (received ${importInterop}).`);
}
return importInterop;
}
function resolveImportInterop(importInterop, source, filename) {
if (typeof importInterop === "function") {
return validateImportInteropOption(importInterop(source, filename));
}
return importInterop;
}
function normalizeModuleAndLoadMetadata(programPath, exportName, {
noInterop = false,
loose = false,
importInterop,
initializeReexports = false,
lazy = false,
esNamespaceOnly = false
} = {}) {
esNamespaceOnly = false,
filename
}) {
if (!exportName) {
exportName = programPath.scope.generateUidIdentifier("exports").name;
}
const stringSpecifiers = new Set();
nameAnonymousExports(programPath);
const {
local,
source,
hasExports
} = getModuleMetadata(programPath, {
loose,
initializeReexports,
lazy
});
}, stringSpecifiers);
removeModuleDeclarations(programPath);
for (const [, metadata] of source) {
@@ -47,10 +66,16 @@ function normalizeModuleAndLoadMetadata(programPath, exportName, {
metadata.name = metadata.importsNamespace.values().next().value;
}
if (noInterop) metadata.interop = "none";else if (esNamespaceOnly) {
if (metadata.interop === "namespace") {
metadata.interop = "default";
}
const resolvedInterop = resolveImportInterop(importInterop, metadata.source, filename);
if (resolvedInterop === "none") {
metadata.interop = "none";
} else if (resolvedInterop === "node" && metadata.interop === "namespace") {
metadata.interop = "node-namespace";
} else if (resolvedInterop === "node" && metadata.interop === "default") {
metadata.interop = "node-default";
} else if (esNamespaceOnly && metadata.interop === "namespace") {
metadata.interop = "default";
}
}
@@ -59,15 +84,42 @@ function normalizeModuleAndLoadMetadata(programPath, exportName, {
exportNameListName: null,
hasExports,
local,
source
source,
stringSpecifiers
};
}
function getExportSpecifierName(path, stringSpecifiers) {
if (path.isIdentifier()) {
return path.node.name;
} else if (path.isStringLiteral()) {
const stringValue = path.node.value;
if (!(0, _helperValidatorIdentifier.isIdentifierName)(stringValue)) {
stringSpecifiers.add(stringValue);
}
return stringValue;
} else {
throw new Error(`Expected export specifier to be either Identifier or StringLiteral, got ${path.node.type}`);
}
}
function assertExportSpecifier(path) {
if (path.isExportSpecifier()) {
return;
} else if (path.isExportNamespaceSpecifier()) {
throw path.buildCodeFrameError("Export namespace should be first transformed by `@babel/plugin-proposal-export-namespace-from`.");
} else {
throw path.buildCodeFrameError("Unexpected export specifier type");
}
}
function getModuleMetadata(programPath, {
loose,
lazy
}) {
const localData = getLocalExportMetadata(programPath, loose);
lazy,
initializeReexports
}, stringSpecifiers) {
const localData = getLocalExportMetadata(programPath, initializeReexports, stringSpecifiers);
const sourceData = new Map();
const getData = sourceNode => {
@@ -84,7 +136,8 @@ function getModuleMetadata(programPath, {
reexports: new Map(),
reexportNamespace: new Set(),
reexportAll: null,
lazy: false
lazy: false,
source
};
sourceData.set(source, data);
}
@@ -121,7 +174,7 @@ function getModuleMetadata(programPath, {
});
}
} else if (spec.isImportSpecifier()) {
const importName = spec.get("imported").node.name;
const importName = getExportSpecifierName(spec.get("imported"), stringSpecifiers);
const localName = spec.get("local").node.name;
data.imports.set(localName, importName);
const reexport = localData.get(localName);
@@ -146,16 +199,13 @@ function getModuleMetadata(programPath, {
const data = getData(child.node.source);
if (!data.loc) data.loc = child.node.loc;
child.get("specifiers").forEach(spec => {
if (!spec.isExportSpecifier()) {
throw spec.buildCodeFrameError("Unexpected export specifier type");
}
const importName = spec.get("local").node.name;
const exportName = spec.get("exported").node.name;
assertExportSpecifier(spec);
const importName = getExportSpecifierName(spec.get("local"), stringSpecifiers);
const exportName = getExportSpecifierName(spec.get("exported"), stringSpecifiers);
data.reexports.set(exportName, importName);
if (exportName === "__esModule") {
throw exportName.buildCodeFrameError('Illegal export "__esModule".');
throw spec.get("exported").buildCodeFrameError('Illegal export "__esModule".');
}
});
} else if (child.isExportNamedDeclaration() || child.isExportDefaultDeclaration()) {
@@ -212,7 +262,7 @@ function getModuleMetadata(programPath, {
};
}
function getLocalExportMetadata(programPath, loose) {
function getLocalExportMetadata(programPath, initializeReexports, stringSpecifiers) {
const bindingKindLookup = new Map();
programPath.get("body").forEach(child => {
let kind;
@@ -220,14 +270,17 @@ function getLocalExportMetadata(programPath, loose) {
if (child.isImportDeclaration()) {
kind = "import";
} else {
if (child.isExportDefaultDeclaration()) child = child.get("declaration");
if (child.isExportDefaultDeclaration()) {
child = child.get("declaration");
}
if (child.isExportNamedDeclaration()) {
if (child.node.declaration) {
child = child.get("declaration");
} else if (loose && child.node.source && child.get("source").isStringLiteral()) {
child.node.specifiers.forEach(specifier => {
bindingKindLookup.set(specifier.local.name, "block");
} else if (initializeReexports && child.node.source && child.get("source").isStringLiteral()) {
child.get("specifiers").forEach(spec => {
assertExportSpecifier(spec);
bindingKindLookup.set(spec.get("local").node.name, "block");
});
return;
}
@@ -276,7 +329,7 @@ function getLocalExportMetadata(programPath, loose) {
};
programPath.get("body").forEach(child => {
if (child.isExportNamedDeclaration() && (loose || !child.node.source)) {
if (child.isExportNamedDeclaration() && (initializeReexports || !child.node.source)) {
if (child.node.declaration) {
const declaration = child.get("declaration");
const ids = declaration.getOuterBindingIdentifierPaths();
@@ -291,12 +344,14 @@ function getLocalExportMetadata(programPath, loose) {
child.get("specifiers").forEach(spec => {
const local = spec.get("local");
const exported = spec.get("exported");
const localMetadata = getLocalMetadata(local);
const exportName = getExportSpecifierName(exported, stringSpecifiers);
if (exported.node.name === "__esModule") {
if (exportName === "__esModule") {
throw exported.buildCodeFrameError('Illegal export "__esModule".');
}
getLocalMetadata(local).names.push(exported.node.name);
localMetadata.names.push(exportName);
});
}
} else if (child.isExportDefaultDeclaration()) {
+167 -47
View File
@@ -5,19 +5,54 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = rewriteLiveReferences;
var _assert = _interopRequireDefault(require("assert"));
var _assert = require("assert");
var t = _interopRequireWildcard(require("@babel/types"));
var _t = require("@babel/types");
var _template = _interopRequireDefault(require("@babel/template"));
var _template = require("@babel/template");
var _helperSimpleAccess = _interopRequireDefault(require("@babel/helper-simple-access"));
var _helperSimpleAccess = require("@babel/helper-simple-access");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
const {
assignmentExpression,
callExpression,
cloneNode,
expressionStatement,
getOuterBindingIdentifiers,
identifier,
isMemberExpression,
isVariableDeclaration,
jsxIdentifier,
jsxMemberExpression,
memberExpression,
numericLiteral,
sequenceExpression,
stringLiteral,
variableDeclaration,
variableDeclarator
} = _t;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function isInType(path) {
do {
switch (path.parent.type) {
case "TSTypeAnnotation":
case "TSTypeAliasDeclaration":
case "TSTypeReference":
case "TypeAnnotation":
case "TypeAlias":
return true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
case "ExportSpecifier":
return path.parentPath.parent.exportKind === "type";
default:
if (path.parentPath.isStatement() || path.parentPath.isExpression()) {
return false;
}
}
} while (path = path.parentPath);
}
function rewriteLiveReferences(programPath, metadata) {
const imported = new Map();
@@ -48,14 +83,15 @@ function rewriteLiveReferences(programPath, metadata) {
exportMeta.push(...data.names);
}
programPath.traverse(rewriteBindingInitVisitor, {
const rewriteBindingInitVisitorState = {
metadata,
requeueInParent,
scope: programPath.scope,
exported
});
(0, _helperSimpleAccess.default)(programPath, new Set([...Array.from(imported.keys()), ...Array.from(exported.keys())]));
programPath.traverse(rewriteReferencesVisitor, {
};
programPath.traverse(rewriteBindingInitVisitor, rewriteBindingInitVisitorState);
(0, _helperSimpleAccess.default)(programPath, new Set([...Array.from(imported.keys()), ...Array.from(exported.keys())]), false);
const rewriteReferencesVisitorState = {
seen: new WeakSet(),
metadata,
requeueInParent,
@@ -66,15 +102,25 @@ function rewriteLiveReferences(programPath, metadata) {
const meta = metadata.source.get(source);
if (localName) {
if (meta.lazy) identNode = t.callExpression(identNode, []);
if (meta.lazy) {
identNode = callExpression(identNode, []);
}
return identNode;
}
let namespace = t.identifier(meta.name);
if (meta.lazy) namespace = t.callExpression(namespace, []);
return t.memberExpression(namespace, t.identifier(importName));
let namespace = identifier(meta.name);
if (meta.lazy) namespace = callExpression(namespace, []);
if (importName === "default" && meta.interop === "node-default") {
return namespace;
}
const computed = metadata.stringSpecifiers.has(importName);
return memberExpression(namespace, computed ? stringLiteral(importName) : identifier(importName), computed);
}
});
};
programPath.traverse(rewriteReferencesVisitor, rewriteReferencesVisitorState);
}
const rewriteBindingInitVisitor = {
@@ -96,7 +142,7 @@ const rewriteBindingInitVisitor = {
const exportNames = exported.get(localName) || [];
if (exportNames.length > 0) {
const statement = t.expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, t.identifier(localName)));
const statement = expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, identifier(localName), path.scope));
statement._blockHoist = path.node._blockHoist;
requeueInParent(path.insertAfter(statement)[0]);
}
@@ -112,7 +158,7 @@ const rewriteBindingInitVisitor = {
const exportNames = exported.get(localName) || [];
if (exportNames.length > 0) {
const statement = t.expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, t.identifier(localName)));
const statement = expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, identifier(localName), path.scope));
statement._blockHoist = path.node._blockHoist;
requeueInParent(path.insertAfter(statement)[0]);
}
@@ -121,9 +167,21 @@ const rewriteBindingInitVisitor = {
};
const buildBindingExportAssignmentExpression = (metadata, exportNames, localExpr) => {
const buildBindingExportAssignmentExpression = (metadata, exportNames, localExpr, scope) => {
const exportsObjectName = metadata.exportName;
for (let currentScope = scope; currentScope != null; currentScope = currentScope.parent) {
if (currentScope.hasOwnBinding(exportsObjectName)) {
currentScope.rename(exportsObjectName);
}
}
return (exportNames || []).reduce((expr, exportName) => {
return t.assignmentExpression("=", t.memberExpression(t.identifier(metadata.exportName), t.identifier(exportName)), expr);
const {
stringSpecifiers
} = metadata;
const computed = stringSpecifiers.has(exportName);
return assignmentExpression("=", memberExpression(identifier(exportsObjectName), computed ? stringLiteral(exportName) : identifier(exportName), computed), expr);
}, localExpr);
};
@@ -147,12 +205,16 @@ const rewriteReferencesVisitor = {
if (seen.has(path.node)) return;
seen.add(path.node);
const localName = path.node.name;
const localBinding = path.scope.getBinding(localName);
const rootBinding = scope.getBinding(localName);
if (rootBinding !== localBinding) return;
const importData = imported.get(localName);
if (importData) {
if (isInType(path)) {
throw path.buildCodeFrameError(`Cannot transform the imported binding "${localName}" since it's also used in a type annotation. ` + `Please strip type annotations using @babel/preset-typescript or @babel/preset-flow.`);
}
const localBinding = path.scope.getBinding(localName);
const rootBinding = scope.getBinding(localName);
if (rootBinding !== localBinding) return;
const ref = buildImportReference(importData, path.node);
ref.loc = path.node.loc;
@@ -162,14 +224,14 @@ const rewriteReferencesVisitor = {
callee: path.node
}) || path.parentPath.isTaggedTemplateExpression({
tag: path.node
})) && t.isMemberExpression(ref)) {
path.replaceWith(t.sequenceExpression([t.numericLiteral(0), ref]));
} else if (path.isJSXIdentifier() && t.isMemberExpression(ref)) {
})) && isMemberExpression(ref)) {
path.replaceWith(sequenceExpression([numericLiteral(0), ref]));
} else if (path.isJSXIdentifier() && isMemberExpression(ref)) {
const {
object,
property
} = ref;
path.replaceWith(t.JSXMemberExpression(t.JSXIdentifier(object.name), t.JSXIdentifier(property.name)));
path.replaceWith(jsxMemberExpression(jsxIdentifier(object.name), jsxIdentifier(property.name)));
} else {
path.replaceWith(ref);
}
@@ -179,6 +241,47 @@ const rewriteReferencesVisitor = {
}
},
UpdateExpression(path) {
const {
scope,
seen,
imported,
exported,
requeueInParent,
buildImportReference
} = this;
if (seen.has(path.node)) return;
seen.add(path.node);
const arg = path.get("argument");
if (arg.isMemberExpression()) return;
const update = path.node;
if (arg.isIdentifier()) {
const localName = arg.node.name;
if (scope.getBinding(localName) !== path.scope.getBinding(localName)) {
return;
}
const exportedNames = exported.get(localName);
const importData = imported.get(localName);
if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) {
if (importData) {
path.replaceWith(assignmentExpression(update.operator[0] + "=", buildImportReference(importData, arg.node), buildImportThrow(localName)));
} else if (update.prefix) {
path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, cloneNode(update), path.scope));
} else {
const ref = scope.generateDeclaredUidIdentifier(localName);
path.replaceWith(sequenceExpression([assignmentExpression("=", cloneNode(ref), cloneNode(update)), buildBindingExportAssignmentExpression(this.metadata, exportedNames, identifier(localName), path.scope), cloneNode(ref)]));
}
}
}
requeueInParent(path);
path.skip();
},
AssignmentExpression: {
exit(path) {
const {
@@ -205,15 +308,16 @@ const rewriteReferencesVisitor = {
const importData = imported.get(localName);
if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) {
(0, _assert.default)(path.node.operator === "=", "Path was not simplified");
_assert(path.node.operator === "=", "Path was not simplified");
const assignment = path.node;
if (importData) {
assignment.left = buildImportReference(importData, assignment.left);
assignment.right = t.sequenceExpression([assignment.right, buildImportThrow(localName)]);
assignment.left = buildImportReference(importData, left.node);
assignment.right = sequenceExpression([assignment.right, buildImportThrow(localName)]);
}
path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, assignment));
path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, assignment, path.scope));
requeueInParent(path);
}
} else {
@@ -222,7 +326,7 @@ const rewriteReferencesVisitor = {
const id = programScopeIds.find(localName => imported.has(localName));
if (id) {
path.node.right = t.sequenceExpression([path.node.right, buildImportThrow(id)]);
path.node.right = sequenceExpression([path.node.right, buildImportThrow(id)]);
}
const items = [];
@@ -230,15 +334,15 @@ const rewriteReferencesVisitor = {
const exportedNames = exported.get(localName) || [];
if (exportedNames.length > 0) {
items.push(buildBindingExportAssignmentExpression(this.metadata, exportedNames, t.identifier(localName)));
items.push(buildBindingExportAssignmentExpression(this.metadata, exportedNames, identifier(localName), path.scope));
}
});
if (items.length > 0) {
let node = t.sequenceExpression(items);
let node = sequenceExpression(items);
if (path.parentPath.isExpressionStatement()) {
node = t.expressionStatement(node);
node = expressionStatement(node);
node._blockHoist = path.parentPath.node._blockHoist;
}
@@ -260,32 +364,48 @@ const rewriteReferencesVisitor = {
} = node;
const {
exported,
imported,
scope: programScope
} = this;
if (!t.isVariableDeclaration(left)) {
let didTransform = false;
const bodyPath = path.get("body");
const loopBodyScope = bodyPath.scope;
if (!isVariableDeclaration(left)) {
let didTransformExport = false,
importConstViolationName;
const loopBodyScope = path.get("body").scope;
for (const name of Object.keys(t.getOuterBindingIdentifiers(left))) {
if (exported.get(name) && programScope.getBinding(name) === scope.getBinding(name)) {
didTransform = true;
for (const name of Object.keys(getOuterBindingIdentifiers(left))) {
if (programScope.getBinding(name) === scope.getBinding(name)) {
if (exported.has(name)) {
didTransformExport = true;
if (loopBodyScope.hasOwnBinding(name)) {
loopBodyScope.rename(name);
if (loopBodyScope.hasOwnBinding(name)) {
loopBodyScope.rename(name);
}
}
if (imported.has(name) && !importConstViolationName) {
importConstViolationName = name;
}
}
}
if (!didTransform) {
if (!didTransformExport && !importConstViolationName) {
return;
}
path.ensureBlock();
const bodyPath = path.get("body");
const newLoopId = scope.generateUidIdentifierBasedOnNode(left);
bodyPath.unshiftContainer("body", t.expressionStatement(t.assignmentExpression("=", left, newLoopId)));
path.get("left").replaceWith(t.variableDeclaration("let", [t.variableDeclarator(newLoopId)]));
path.get("left").replaceWith(variableDeclaration("let", [variableDeclarator(cloneNode(newLoopId))]));
scope.registerDeclaration(path.get("left"));
if (didTransformExport) {
bodyPath.unshiftContainer("body", expressionStatement(assignmentExpression("=", left, newLoopId)));
}
if (importConstViolationName) {
bodyPath.unshiftContainer("body", expressionStatement(buildImportThrow(importConstViolationName)));
}
}
}
+16 -17
View File
@@ -5,27 +5,26 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = rewriteThis;
var _helperReplaceSupers = require("@babel/helper-replace-supers");
var _helperEnvironmentVisitor = require("@babel/helper-environment-visitor");
var _traverse = require("@babel/traverse");
var _t = require("@babel/types");
const {
numericLiteral,
unaryExpression
} = _t;
function rewriteThis(programPath) {
programPath.traverse(rewriteThisVisitor);
(0, _traverse.default)(programPath.node, Object.assign({}, rewriteThisVisitor, {
noScope: true
}));
}
const rewriteThisVisitor = {
const rewriteThisVisitor = _traverse.default.visitors.merge([_helperEnvironmentVisitor.default, {
ThisExpression(path) {
path.replaceWith(path.scope.buildUndefinedNode());
},
Function(path) {
if (path.isMethod()) (0, _helperReplaceSupers.skipAllButComputedKey)(path);else if (!path.isArrowFunctionExpression()) path.skip();
},
ClassProperty(path) {
(0, _helperReplaceSupers.skipAllButComputedKey)(path);
},
ClassPrivateProperty(path) {
path.skip();
path.replaceWith(unaryExpression("void", numericLiteral(0), true));
}
};
}]);
+28 -24
View File
@@ -1,26 +1,26 @@
{
"_args": [
[
"@babel/helper-module-transforms@7.10.4",
"/mnt/Foxconn/Digitalent/Deverloper/liff-push_2series"
"@babel/helper-module-transforms@7.18.8",
"/home/node/nuxt"
]
],
"_from": "@babel/helper-module-transforms@7.10.4",
"_id": "@babel/helper-module-transforms@7.10.4",
"_from": "@babel/helper-module-transforms@7.18.8",
"_id": "@babel/helper-module-transforms@7.18.8",
"_inBundle": false,
"_integrity": "sha512-Er2FQX0oa3nV7eM1o0tNCTx7izmQtwAQsIiaLRWtavAAEcskb0XJ5OjJbVrYXWOTr8om921Scabn4/tzlx7j1Q==",
"_integrity": "sha512-che3jvZwIcZxrwh63VfnFTUzcAM9v/lznYkkRxIBGMPt1SudOKHAEec0SIRCfiuIzTcF7VGj/CaTT6gY4eWxvA==",
"_location": "/@babel/helper-module-transforms",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@babel/helper-module-transforms@7.10.4",
"raw": "@babel/helper-module-transforms@7.18.8",
"name": "@babel/helper-module-transforms",
"escapedName": "@babel%2fhelper-module-transforms",
"scope": "@babel",
"rawSpec": "7.10.4",
"rawSpec": "7.18.8",
"saveSpec": null,
"fetchSpec": "7.10.4"
"fetchSpec": "7.18.8"
},
"_requiredBy": [
"/@babel/core",
@@ -29,30 +29,33 @@
"/@babel/plugin-transform-modules-systemjs",
"/@babel/plugin-transform-modules-umd"
],
"_resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.10.4.tgz",
"_spec": "7.10.4",
"_where": "/mnt/Foxconn/Digitalent/Deverloper/liff-push_2series",
"_resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.18.8.tgz",
"_spec": "7.18.8",
"_where": "/home/node/nuxt",
"author": {
"name": "Logan Smyth",
"email": "loganfsmyth@gmail.com"
"name": "The Babel Team",
"url": "https://babel.dev/team"
},
"bugs": {
"url": "https://github.com/babel/babel/issues"
},
"dependencies": {
"@babel/helper-module-imports": "^7.10.4",
"@babel/helper-replace-supers": "^7.10.4",
"@babel/helper-simple-access": "^7.10.4",
"@babel/helper-split-export-declaration": "^7.10.4",
"@babel/template": "^7.10.4",
"@babel/types": "^7.10.4",
"lodash": "^4.17.13"
"@babel/helper-environment-visitor": "^7.18.6",
"@babel/helper-module-imports": "^7.18.6",
"@babel/helper-simple-access": "^7.18.6",
"@babel/helper-split-export-declaration": "^7.18.6",
"@babel/helper-validator-identifier": "^7.18.6",
"@babel/template": "^7.18.6",
"@babel/traverse": "^7.18.8",
"@babel/types": "^7.18.8"
},
"description": "Babel helper functions for implementing ES6 module transformations",
"gitHead": "7fd40d86a0d03ff0e9c3ea16b29689945433d4df",
"homepage": "https://babeljs.io/",
"engines": {
"node": ">=6.9.0"
},
"homepage": "https://babel.dev/docs/en/next/babel-helper-module-transforms",
"license": "MIT",
"main": "lib/index.js",
"main": "./lib/index.js",
"name": "@babel/helper-module-transforms",
"publishConfig": {
"access": "public"
@@ -62,5 +65,6 @@
"url": "git+https://github.com/babel/babel.git",
"directory": "packages/babel-helper-module-transforms"
},
"version": "7.10.4"
"type": "commonjs",
"version": "7.18.8"
}