Skip to content

Commit 171fe43

Browse files
committed
fix(wasm): preserve source phase in dynamic import contexts
1 parent b4d6769 commit 171fe43

9 files changed

Lines changed: 117 additions & 8 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Preserve the source phase of dynamic WebAssembly import contexts.

‎lib/context/ContextModuleFactory.js‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,8 @@ class ContextModuleFactory extends ModuleFactory {
363363
referencedExports,
364364
category,
365365
typePrefix,
366-
attributes
366+
attributes,
367+
phase
367368
} = options;
368369
const isImportMetaGlob = Boolean(patterns && requestContext);
369370
if ((!regExp && !isImportMetaGlob) || !resource) return callback(null, []);
@@ -524,7 +525,8 @@ class ContextModuleFactory extends ModuleFactory {
524525
referencedExports,
525526
ctx,
526527
attributes,
527-
contextRequest
528+
contextRequest,
529+
phase
528530
);
529531
dep.optional = true;
530532
globDeps.push(dep);
@@ -599,7 +601,8 @@ class ContextModuleFactory extends ModuleFactory {
599601
referencedExports,
600602
alt.context,
601603
attributes,
602-
contextRequest
604+
contextRequest,
605+
phase
603606
);
604607
dep.optional = true;
605608
flattenedResult.push(dep);

‎lib/dependencies/context/ContextElementDependency.js‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
const Dependency = require("../../graph/Dependency");
99
const makeSerializable = require("../../util/makeSerializable");
10+
const { ImportPhase, ImportPhaseUtils } = require("../core/ImportPhase");
1011
const ModuleDependency = require("../core/ModuleDependency");
1112

1213
/** @import ContextModule from "../../context/ContextModule" */
@@ -15,8 +16,9 @@ const ModuleDependency = require("../core/ModuleDependency");
1516
/** @import ModuleGraph from "../../graph/ModuleGraph" */
1617
/** @import { ImportAttributes } from "../../javascript/JavascriptParser" */
1718
/** @import { RuntimeSpec } from "../../util/runtime" */
18-
/** @typedef {import("../../serialization/ObjectMiddleware").ObjectDeserializerContext<[string | undefined, string, RawReferencedExports | null | undefined, ImportAttributes | undefined, string | undefined]>} ObjectDeserializerContext */
19-
/** @typedef {import("../../serialization/ObjectMiddleware").ObjectSerializerContext<[string | undefined, string, RawReferencedExports | null | undefined, ImportAttributes | undefined, string | undefined]>} ObjectSerializerContext */
19+
/** @import { ImportPhaseType } from "../core/ImportPhase" */
20+
/** @typedef {import("../../serialization/ObjectMiddleware").ObjectDeserializerContext<[string | undefined, string, RawReferencedExports | null | undefined, ImportAttributes | undefined, string | undefined, ImportPhaseType]>} ObjectDeserializerContext */
21+
/** @typedef {import("../../serialization/ObjectMiddleware").ObjectSerializerContext<[string | undefined, string, RawReferencedExports | null | undefined, ImportAttributes | undefined, string | undefined, ImportPhaseType]>} ObjectSerializerContext */
2022

2123
class ContextElementDependency extends ModuleDependency {
2224
/**
@@ -29,6 +31,7 @@ class ContextElementDependency extends ModuleDependency {
2931
* @param {string=} context context
3032
* @param {ImportAttributes=} attributes import assertions
3133
* @param {string=} contextRequest the request of the context as written by the user, without query and fragment
34+
* @param {ImportPhaseType=} phase import phase
3235
*/
3336
constructor(
3437
request,
@@ -38,7 +41,8 @@ class ContextElementDependency extends ModuleDependency {
3841
referencedExports,
3942
context,
4043
attributes,
41-
contextRequest
44+
contextRequest,
45+
phase = ImportPhase.Evaluation
4246
) {
4347
super(request);
4448

@@ -59,6 +63,8 @@ class ContextElementDependency extends ModuleDependency {
5963
this.attributes = attributes;
6064
/** @type {string | undefined} */
6165
this._contextRequest = contextRequest || undefined;
66+
/** @type {ImportPhaseType} */
67+
this.phase = phase;
6268
}
6369

6470
/**
@@ -92,6 +98,9 @@ class ContextElementDependency extends ModuleDependency {
9298
*/
9399
getResourceIdentifier() {
94100
let str = super.getResourceIdentifier();
101+
if (this.phase) {
102+
str += `|phase${ImportPhaseUtils.stringify(this.phase)}`;
103+
}
95104
if (this.attributes) {
96105
str += `|attributes${JSON.stringify(this.attributes)}`;
97106
}
@@ -149,7 +158,8 @@ class ContextElementDependency extends ModuleDependency {
149158
.write(this._category)
150159
.write(this.referencedExports)
151160
.write(this.attributes)
152-
.write(this._contextRequest);
161+
.write(this._contextRequest)
162+
.write(this.phase);
153163
super.serialize(context);
154164
}
155165

@@ -167,7 +177,9 @@ class ContextElementDependency extends ModuleDependency {
167177
this.attributes = c3.read();
168178
const c4 = c3.rest;
169179
this._contextRequest = c4.read();
170-
super.deserialize(c4.rest);
180+
const c5 = c4.rest;
181+
this.phase = c5.read();
182+
super.deserialize(c5.rest);
171183
}
172184
}
173185

‎lib/dependencies/import/ImportContextDependency.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
const makeSerializable = require("../../util/makeSerializable");
99
const ContextDependency = require("../context/ContextDependency");
1010
const ContextDependencyTemplateAsRequireCall = require("../context/ContextDependencyTemplateAsRequireCall");
11+
const { ImportPhaseUtils } = require("../core/ImportPhase");
1112
const importOptionsCheck = require("./importOptionsCheck");
1213

1314
/** @import { Range } from "../../javascript/JavascriptParser" */
@@ -46,6 +47,9 @@ class ImportContextDependency extends ContextDependency {
4647
*/
4748
getResourceIdentifier() {
4849
let str = super.getResourceIdentifier();
50+
if (this.options.phase) {
51+
str += `|phase${ImportPhaseUtils.stringify(this.options.phase)}`;
52+
}
4953

5054
if (this.options.attributes) {
5155
str += `|attributes${JSON.stringify(this.options.attributes)}`;
@@ -96,6 +100,15 @@ ImportContextDependency.Template = class ImportContextDependencyTemplate extends
96100
* @returns {void}
97101
*/
98102
replaceCall(dep, source, moduleExports, templateContext) {
103+
if (ImportPhaseUtils.isSource(dep.options.phase)) {
104+
source.insert(
105+
/** @type {Range} */ (dep.range)[1],
106+
`.then(${templateContext.runtimeTemplate.returningFunction(
107+
'm["default"]',
108+
"m"
109+
)})`
110+
);
111+
}
99112
const optionsRange = /** @type {ImportContextDependency} */ (dep)
100113
.optionsRange;
101114
if (optionsRange === undefined) {
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
for (const [mode, load] of [
2+
["lazy", name => import.source(`./modules/${name}.wat`)],
3+
["eager", name => import.source(/* webpackMode: "eager" */ `./modules/${name}.wat`)],
4+
["lazy-once", name => import.source(/* webpackMode: "lazy-once" */ `./modules/${name}.wat`)],
5+
["weak", name => import.source(/* webpackMode: "weak" */ `./modules/${name}.wat`)],
6+
["magic comment", name => import(/* webpackSource: true */ `./modules/${name}.wat`)]
7+
]) {
8+
it(`should import a Wasm source with host imports through a ${mode} context`, async () => {
9+
const expected = await import.source("./modules/imported.wat");
10+
const source = await load("imported");
11+
expect(source).toBeInstanceOf(WebAssembly.Module);
12+
expect(source).toBe(expected);
13+
expect(WebAssembly.Module.imports(source)).toEqual([
14+
{ module: "env", name: "get", kind: "function" }
15+
]);
16+
const instance = await WebAssembly.instantiate(source, {
17+
env: { get: () => 42 }
18+
});
19+
expect(instance.exports.get()).toBe(42);
20+
});
21+
22+
it(`should reject a missing Wasm source in a ${mode} context`, async () => {
23+
await expect(load("missing")).rejects.toMatchObject({
24+
code: "MODULE_NOT_FOUND"
25+
});
26+
});
27+
}
28+
29+
it("should keep source and evaluation contexts for the same request separate", async () => {
30+
let name = "value";
31+
const source = await import.source(`./shared/${name}.wat`);
32+
const evaluated = await import(`./shared/${name}.wat`);
33+
expect(source).toBeInstanceOf(WebAssembly.Module);
34+
expect(evaluated.get()).toBe(42);
35+
const instance = await WebAssembly.instantiate(source);
36+
expect(instance.exports.get()).toBe(42);
37+
});
38+
39+
it("should evaluate import options before resolving a source context", async () => {
40+
let name = "imported";
41+
const calls = [];
42+
const source = await import.source(
43+
`./modules/${(calls.push("request"), name)}.wat`,
44+
(calls.push("options"), {})
45+
);
46+
expect(calls).toEqual(["request", "options"]);
47+
expect(source).toBeInstanceOf(WebAssembly.Module);
48+
});
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
(module
2+
(import "env" "get" (func $get (result i32)))
3+
(export "get" (func $get)))
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
(module
2+
(func (export "get") (result i32)
3+
(i32.const 42)))
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
"use strict";
2+
3+
/** @type {import("../../../../").Configuration[]} */
4+
module.exports = [
5+
{ target: "node", output: { module: false } },
6+
{ target: "node", output: { module: true } },
7+
{ target: "async-node", output: { module: false } },
8+
{ target: "universal", output: { module: true } }
9+
].map((options) => ({
10+
...options,
11+
module: {
12+
rules: [
13+
{
14+
test: /\.wat$/,
15+
loader: "wast-loader",
16+
type: "webassembly/async"
17+
}
18+
]
19+
},
20+
experiments: { asyncWebAssembly: true, sourceImport: true }
21+
}));

‎types.d.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5529,6 +5529,7 @@ type ContextDependencyOptions = ContextOptions & { request: string };
55295529
declare abstract class ContextElementDependency extends ModuleDependency {
55305530
referencedExports?: null | string[][];
55315531
attributes?: ImportAttributes;
5532+
phase: ImportPhaseType;
55325533

55335534
/**
55345535
* The request as the user wrote it, e.g. `#configs/file.mjs` where `request`

0 commit comments

Comments
 (0)