Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return rejected promise when stringify import specifier throws #15290

Merged
merged 6 commits into from Dec 23, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -4,6 +4,7 @@
import * as t from "@babel/types";
import template from "@babel/template";

// TODO(Babel 8): Remove this
SuperSodaSea marked this conversation as resolved.
Show resolved Hide resolved
export function getDynamicImportSource(
node: t.CallExpression,
): t.StringLiteral | t.TemplateLiteral {
SuperSodaSea marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
@@ -1,5 +1,5 @@
define(["require"], function (_require) {
"use strict";

var modP = new Promise((_resolve, _reject) => _require(["mod"], imported => _resolve(babelHelpers.interopRequireWildcard(imported)), _reject));
var modP = Promise.resolve().then(() => new Promise((_resolve, _reject) => _require(["mod"], imported => _resolve(babelHelpers.interopRequireWildcard(imported)), _reject)));
});
@@ -1,3 +1,3 @@
define(["require"], function (_require) {
var modP = new Promise((_resolve, _reject) => _require(["mod"], imported => _resolve(imported), _reject));
var modP = Promise.resolve().then(() => new Promise((_resolve, _reject) => _require(["mod"], imported => _resolve(imported), _reject)));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the AMD require function is already asynchronous, we don't need to defer it to .then — the original code was fine. Same for SystemJS.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, I just need to set the buildDynamicImport's runInThendeferToThen to false for it.

buildDynamicImport(
path.node,
false,
false,
specifier => template.expression.ast`
new Promise((${resolveId}, ${rejectId}) =>
${requireId}(
[${specifier}],
imported => ${t.cloneNode(resolveId)}(${result}),
${t.cloneNode(rejectId)}
)
)
`,
),

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now the logic looks like this:

CommonJS (Deferred to then):

if (deferToThen) {
return template.expression.ast`
(specifier =>
new Promise(r => r(${specifierToString}))
.then(s => ${builder(t.identifier("s"))})
)(${specifier})
`;

SystemJS (Needs to return a rejected promise when toString throws so wrap it in a promise):

} else if (wrapWithPromise) {
return template.expression.ast`
(specifier =>
new Promise(r => r(${builder(specifierToString)}))
)(${specifier})
`;

AMD (Builder already returns a new Promise so do nothing):

} else {
return template.expression.ast`
(specifier => ${builder(specifierToString)})(${specifier})
`;

});
@@ -1,3 +1,3 @@
define(["require"], function (_require) {
var modP = new Promise((_resolve, _reject) => _require(["mod"], imported => _resolve(babelHelpers.interopRequireWildcard(imported)), _reject));
var modP = Promise.resolve().then(() => new Promise((_resolve, _reject) => _require(["mod"], imported => _resolve(babelHelpers.interopRequireWildcard(imported)), _reject)));
});
@@ -0,0 +1 @@
import(2);
@@ -0,0 +1,3 @@
define(["require"], function (_require) {
(source => new Promise(r => r("" + source)).then(s => new Promise((_resolve, _reject) => _require([s], imported => _resolve(babelHelpers.interopRequireWildcard(imported)), _reject))))(2);
});
Expand Up @@ -8,5 +8,5 @@ define(["require", "exports", "foo"], function (_require, _exports, _foo) {
_foo = babelHelpers.interopRequireDefault(_foo);
var mod;
_exports.mod = mod;
new Promise((_resolve, _reject) => _require(["mod"], imported => _resolve(babelHelpers.interopRequireWildcard(imported)), _reject)).then(m => _exports.mod = mod = m);
Promise.resolve().then(() => new Promise((_resolve, _reject) => _require(["mod"], imported => _resolve(babelHelpers.interopRequireWildcard(imported)), _reject))).then(m => _exports.mod = mod = m);
});
@@ -0,0 +1,11 @@
expect(() => {
function f() { throw "should throw"; }
import(f());
}).toThrow("should throw");

expect(() => {
const a = {
get x() { throw "should throw"; },
};
import(a.x);
}).toThrow("should throw");
@@ -0,0 +1 @@
module.exports = 1;
@@ -0,0 +1,7 @@
let i = 0;
const promise = expect(import({ toString: () => `./${++i}.js` }))
.resolves.toHaveProperty("default", 1);
expect(i).toBe(1);
++i;
expect(i).toBe(2);
return promise;
@@ -0,0 +1,5 @@
{
"parserOpts": {
"allowReturnOutsideFunction": true
}
}
@@ -0,0 +1,2 @@
return expect(import({ toString: () => { throw "toString failed"; } }))
.rejects.toBe("toString failed");
@@ -0,0 +1,5 @@
{
"parserOpts": {
"allowReturnOutsideFunction": true
}
}
@@ -1 +1 @@
Promise.resolve(`${2}`).then(s => babelHelpers.interopRequireWildcard(require(s)));
(source => new Promise(r => r("" + source)).then(s => babelHelpers.interopRequireWildcard(require(s))))(2);
@@ -0,0 +1 @@
import(2);
@@ -0,0 +1,10 @@
System.register([], function (_export, _context) {
"use strict";

return {
setters: [],
execute: function () {
(source => new Promise(r => r("" + source)).then(s => _context.import(s)))(2);
}
};
});
35 changes: 26 additions & 9 deletions packages/babel-plugin-transform-modules-amd/src/index.ts
Expand Up @@ -9,7 +9,6 @@ import {
ensureStatementsHoisted,
wrapInterop,
getModuleName,
getDynamicImportSource,
} from "@babel/helper-module-transforms";
import { template, types as t } from "@babel/core";
import type { PluginOptions } from "@babel/helper-module-transforms";
Expand Down Expand Up @@ -98,15 +97,33 @@ export default declare<State>((api, options: Options) => {
let result: t.Node = t.identifier("imported");
if (!noInterop) result = wrapInterop(path, result, "namespace");

const [source] = path.node.arguments;

path.replaceWith(
template.expression.ast`
new Promise((${resolveId}, ${rejectId}) =>
${requireId}(
[${getDynamicImportSource(path.node)}],
imported => ${t.cloneNode(resolveId)}(${result}),
${t.cloneNode(rejectId)}
)
)`,
t.isStringLiteral(source) ||
(t.isTemplateLiteral(source) && source.quasis.length === 0)
? template.expression.ast`
Promise.resolve()
.then(() => new Promise((${resolveId}, ${rejectId}) =>
${requireId}(
[${source}],
imported => ${t.cloneNode(resolveId)}(${result}),
${t.cloneNode(rejectId)}
)
))
`
: template.expression.ast`
(source =>
new Promise(r => r("" + source))
.then(s => new Promise((${resolveId}, ${rejectId}) =>
${requireId}(
[s],
imported => ${t.cloneNode(resolveId)}(${result}),
${t.cloneNode(rejectId)}
)
))
)(${source})
`,
);
},

Expand Down
Expand Up @@ -3,7 +3,6 @@

import type { NodePath } from "@babel/traverse";
import { types as t, template, type File } from "@babel/core";
import { getDynamicImportSource } from "@babel/helper-module-transforms";

const requireNoInterop = (source: t.Expression) =>
template.expression.ast`require(${source})`;
Expand All @@ -20,7 +19,7 @@ export function transformDynamicImport(
) {
const buildRequire = noInterop ? requireNoInterop : requireInterop;

const source = getDynamicImportSource(path.node);
const [source] = path.node.arguments;

const replacement =
t.isStringLiteral(source) ||
Expand All @@ -29,9 +28,10 @@ export function transformDynamicImport(
Promise.resolve().then(() => ${buildRequire(source, file)})
`
: template.expression.ast`
Promise.resolve(${source}).then(
s => ${buildRequire(t.identifier("s"), file)}
)
(source =>
new Promise(r => r("" + source))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
new Promise(r => r("" + source))
new Promise(r => r(${
t.isTemplateLiteral(source) ? source : t.templateLiteral([], [source])
}))

The transform from ${x} to "" + x relies on the ignoreToPrimitiveHint assumption.

Consider an exotic object:

var source = {
  [Symbol.toPrimitive](hint) {
    if (hint === 'string') {
      return "foo"
    }
    return null
  }
}

"" + source will be null while ${source} will be "foo". The ToString operation should respect the toPrimitive symbol.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed, and I go further to move the common logic to function buildDynamicImport:

export function buildDynamicImport(
node: t.CallExpression,
deferToThen: boolean,
wrapWithPromise: boolean,
builder: (specifier: t.Expression) => t.Expression,
): t.Expression {

And in transform-modules-amd/commonjs/system we only need to write code once:

buildDynamicImport(
path.node,
false,
false,
specifier => template.expression.ast`
new Promise((${resolveId}, ${rejectId}) =>
${requireId}(
[${specifier}],
imported => ${t.cloneNode(resolveId)}(${result}),
${t.cloneNode(rejectId)}
)
)
`,
),

buildDynamicImport(path.node, true, false, specifier =>
buildRequire(specifier, file),
),

buildDynamicImport(path.node, false, true, specifier =>
t.callExpression(
t.memberExpression(
t.identifier(state.contextIdent),
t.identifier("import"),
),
[specifier],
),
),

.then(s => ${buildRequire(t.identifier("s"), file)})
)(${source})
`;

path.replaceWith(replacement);
Expand Down
31 changes: 19 additions & 12 deletions packages/babel-plugin-transform-modules-systemjs/src/index.ts
@@ -1,11 +1,7 @@
import { declare } from "@babel/helper-plugin-utils";
import hoistVariables from "@babel/helper-hoist-variables";
import { template, types as t } from "@babel/core";
import {
rewriteThis,
getModuleName,
getDynamicImportSource,
} from "@babel/helper-module-transforms";
import { rewriteThis, getModuleName } from "@babel/helper-module-transforms";
import type { PluginOptions } from "@babel/helper-module-transforms";
import { isIdentifierName } from "@babel/helper-validator-identifier";
import type { NodePath, Scope, Visitor } from "@babel/traverse";
Expand Down Expand Up @@ -273,14 +269,25 @@ export default declare<PluginState>((api, options: Options) => {
}
}

const [source] = path.node.arguments;
const context = t.identifier(state.contextIdent);

path.replaceWith(
t.callExpression(
t.memberExpression(
t.identifier(state.contextIdent),
t.identifier("import"),
),
[getDynamicImportSource(path.node)],
),
t.isStringLiteral(source) ||
(t.isTemplateLiteral(source) && source.quasis.length === 0)
? t.callExpression(
t.memberExpression(
t.identifier(state.contextIdent),
t.identifier("import"),
),
[source],
)
: template.expression.ast`
(source =>
new Promise(r => r("" + source))
.then(s => ${context}.import(s))
)(${source})
`,
);
}
},
Expand Down
@@ -1,7 +1,9 @@
define(["require"], function (_require) {
new Promise(function (_resolve, _reject) {
return _require(["foo"], function (imported) {
return _resolve(babelHelpers.interopRequireWildcard(imported));
}, _reject);
Promise.resolve().then(function () {
return new Promise(function (_resolve, _reject) {
return _require(["foo"], function (imported) {
return _resolve(babelHelpers.interopRequireWildcard(imported));
}, _reject);
});
});
});
@@ -1,3 +1,3 @@
define(["require"], function (_require) {
new Promise((_resolve, _reject) => _require(["foo"], imported => _resolve(babelHelpers.interopRequireWildcard(imported)), _reject));
Promise.resolve().then(() => new Promise((_resolve, _reject) => _require(["foo"], imported => _resolve(babelHelpers.interopRequireWildcard(imported)), _reject)));
});