WXL
4 天以前 2cc85c64f1c64a2dbaeae276a3e2ca8420de76b7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/*
    MIT License http://www.opensource.org/licenses/mit-license.php
    Author Tobias Koppers @sokra
*/
 
"use strict";
 
const { SyncWaterfallHook } = require("tapable");
const Compilation = require("../Compilation");
const Generator = require("../Generator");
const { tryRunOrWebpackError } = require("../HookWebpackError");
const { WEBASSEMBLY_MODULE_TYPE_ASYNC } = require("../ModuleTypeConstants");
const NormalModule = require("../NormalModule");
const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency");
const { compareModulesByFullName } = require("../util/comparators");
const makeSerializable = require("../util/makeSerializable");
const memoize = require("../util/memoize");
 
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../ChunkGraph")} ChunkGraph */
/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
/** @typedef {import("../Module")} Module */
/** @typedef {import("../dependencies/ImportPhase").ImportPhaseName} ImportPhaseName */
/** @typedef {import("../NormalModule").NormalModuleCreateData} NormalModuleCreateData */
/** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("../WebpackError")} WebpackError */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
 
const getAsyncWebAssemblyGenerator = memoize(() =>
    require("./AsyncWebAssemblyGenerator")
);
const getAsyncWebAssemblyJavascriptGenerator = memoize(() =>
    require("./AsyncWebAssemblyJavascriptGenerator")
);
const getAsyncWebAssemblyParser = memoize(() =>
    require("./AsyncWebAssemblyParser")
);
 
/** @typedef {NormalModule & { phase: ImportPhaseName | undefined }} AsyncWasmModuleClass */
 
class AsyncWasmModule extends NormalModule {
    /**
     * @param {NormalModuleCreateData & { phase: ImportPhaseName | undefined }} options options object
     */
    constructor(options) {
        super(options);
        this.phase = options.phase;
    }
 
    /**
     * Returns the unique identifier used to reference this module.
     * @returns {string} a unique identifier of the module
     */
    identifier() {
        let str = super.identifier();
 
        if (this.phase) {
            str = `${str}|${this.phase}`;
        }
 
        return str;
    }
 
    /**
     * Assuming this module is in the cache. Update the (cached) module with
     * the fresh module from the factory. Usually updates internal references
     * and properties.
     * @param {Module} module fresh module
     * @returns {void}
     */
    updateCacheModule(module) {
        super.updateCacheModule(module);
        const m = /** @type {AsyncWasmModule} */ (module);
        this.phase = m.phase;
    }
 
    /**
     * Serializes this instance into the provided serializer context.
     * @param {ObjectSerializerContext} context context
     */
    serialize(context) {
        const { write } = context;
        write(this.phase);
        super.serialize(context);
    }
 
    /**
     * @param {ObjectDeserializerContext} context context
     * @returns {AsyncWasmModule} the deserialized object
     */
    static deserialize(context) {
        const obj = new AsyncWasmModule({
            // will be deserialized by Module
            layer: /** @type {EXPECTED_ANY} */ (null),
            type: "",
            // will be filled by updateCacheModule
            resource: "",
            context: "",
            request: /** @type {EXPECTED_ANY} */ (null),
            userRequest: /** @type {EXPECTED_ANY} */ (null),
            rawRequest: /** @type {EXPECTED_ANY} */ (null),
            loaders: /** @type {EXPECTED_ANY} */ (null),
            matchResource: /** @type {EXPECTED_ANY} */ (null),
            parser: /** @type {EXPECTED_ANY} */ (null),
            parserOptions: /** @type {EXPECTED_ANY} */ (null),
            generator: /** @type {EXPECTED_ANY} */ (null),
            generatorOptions: /** @type {EXPECTED_ANY} */ (null),
            resolveOptions: /** @type {EXPECTED_ANY} */ (null),
            extractSourceMap: /** @type {EXPECTED_ANY} */ (null),
            phase: /** @type {EXPECTED_ANY} */ (null)
        });
        obj.deserialize(context);
        return obj;
    }
 
    /**
     * Restores this instance from the provided deserializer context.
     * @param {ObjectDeserializerContext} context context
     */
    deserialize(context) {
        const { read } = context;
        this.phase = read();
        super.deserialize(context);
    }
}
 
makeSerializable(AsyncWasmModule, "webpack/lib/wasm-async/AsyncWasmModule");
 
/**
 * Defines the web assembly render context type used by this module.
 * @typedef {object} WebAssemblyRenderContext
 * @property {Chunk} chunk the chunk
 * @property {DependencyTemplates} dependencyTemplates the dependency templates
 * @property {RuntimeTemplate} runtimeTemplate the runtime template
 * @property {ModuleGraph} moduleGraph the module graph
 * @property {ChunkGraph} chunkGraph the chunk graph
 * @property {CodeGenerationResults} codeGenerationResults results of code generation
 */
 
/**
 * Defines the compilation hooks type used by this module.
 * @typedef {object} CompilationHooks
 * @property {SyncWaterfallHook<[Source, Module, WebAssemblyRenderContext]>} renderModuleContent
 */
 
/**
 * Defines the async web assembly modules plugin options type used by this module.
 * @typedef {object} AsyncWebAssemblyModulesPluginOptions
 * @property {boolean=} mangleImports mangle imports
 */
 
/** @type {WeakMap<Compilation, CompilationHooks>} */
const compilationHooksMap = new WeakMap();
 
const PLUGIN_NAME = "AsyncWebAssemblyModulesPlugin";
 
class AsyncWebAssemblyModulesPlugin {
    /**
     * Returns the attached hooks.
     * @param {Compilation} compilation the compilation
     * @returns {CompilationHooks} the attached hooks
     */
    static getCompilationHooks(compilation) {
        if (!(compilation instanceof Compilation)) {
            throw new TypeError(
                "The 'compilation' argument must be an instance of Compilation"
            );
        }
        let hooks = compilationHooksMap.get(compilation);
        if (hooks === undefined) {
            hooks = {
                renderModuleContent: new SyncWaterfallHook([
                    "source",
                    "module",
                    "renderContext"
                ])
            };
            compilationHooksMap.set(compilation, hooks);
        }
        return hooks;
    }
 
    /**
     * Creates an instance of AsyncWebAssemblyModulesPlugin.
     * @param {AsyncWebAssemblyModulesPluginOptions} options options
     */
    constructor(options) {
        /** @type {AsyncWebAssemblyModulesPluginOptions} */
        this.options = options;
    }
 
    /**
     * Applies the plugin by registering its hooks on the compiler.
     * @param {Compiler} compiler the compiler instance
     * @returns {void}
     */
    apply(compiler) {
        compiler.hooks.compilation.tap(
            PLUGIN_NAME,
            (compilation, { normalModuleFactory }) => {
                const hooks =
                    AsyncWebAssemblyModulesPlugin.getCompilationHooks(compilation);
                compilation.dependencyFactories.set(
                    WebAssemblyImportDependency,
                    normalModuleFactory
                );
 
                normalModuleFactory.hooks.createModuleClass
                    .for(WEBASSEMBLY_MODULE_TYPE_ASYNC)
                    .tap(
                        PLUGIN_NAME,
                        (createData, resolveData) =>
                            new AsyncWasmModule({
                                .../** @type {NormalModuleCreateData & { type: string }} */
                                (createData),
                                phase: resolveData.phase
                            })
                    );
 
                normalModuleFactory.hooks.createParser
                    .for(WEBASSEMBLY_MODULE_TYPE_ASYNC)
                    .tap(PLUGIN_NAME, () => {
                        const AsyncWebAssemblyParser = getAsyncWebAssemblyParser();
 
                        return new AsyncWebAssemblyParser();
                    });
                normalModuleFactory.hooks.createGenerator
                    .for(WEBASSEMBLY_MODULE_TYPE_ASYNC)
                    .tap(PLUGIN_NAME, () => {
                        const AsyncWebAssemblyJavascriptGenerator =
                            getAsyncWebAssemblyJavascriptGenerator();
                        const AsyncWebAssemblyGenerator = getAsyncWebAssemblyGenerator();
 
                        return Generator.byType({
                            javascript: new AsyncWebAssemblyJavascriptGenerator(),
                            webassembly: new AsyncWebAssemblyGenerator(this.options)
                        });
                    });
 
                compilation.hooks.renderManifest.tap(PLUGIN_NAME, (result, options) => {
                    const { moduleGraph, chunkGraph, runtimeTemplate } = compilation;
                    const {
                        chunk,
                        outputOptions,
                        dependencyTemplates,
                        codeGenerationResults
                    } = options;
 
                    for (const module of chunkGraph.getOrderedChunkModulesIterable(
                        chunk,
                        compareModulesByFullName(compiler)
                    )) {
                        if (module.type === WEBASSEMBLY_MODULE_TYPE_ASYNC) {
                            const filenameTemplate = outputOptions.webassemblyModuleFilename;
 
                            result.push({
                                render: () =>
                                    this.renderModule(
                                        module,
                                        {
                                            chunk,
                                            dependencyTemplates,
                                            runtimeTemplate,
                                            moduleGraph,
                                            chunkGraph,
                                            codeGenerationResults
                                        },
                                        hooks
                                    ),
                                filenameTemplate,
                                pathOptions: {
                                    module,
                                    runtime: chunk.runtime,
                                    chunkGraph
                                },
                                auxiliary: true,
                                identifier: `webassemblyAsyncModule${chunkGraph.getModuleId(
                                    module
                                )}`,
                                hash: chunkGraph.getModuleHash(module, chunk.runtime)
                            });
                        }
                    }
 
                    return result;
                });
            }
        );
    }
 
    /**
     * Renders the newly generated source from rendering.
     * @param {Module} module the rendered module
     * @param {WebAssemblyRenderContext} renderContext options object
     * @param {CompilationHooks} hooks hooks
     * @returns {Source} the newly generated source from rendering
     */
    renderModule(module, renderContext, hooks) {
        const { codeGenerationResults, chunk } = renderContext;
        try {
            const moduleSource = codeGenerationResults.getSource(
                module,
                chunk.runtime,
                "webassembly"
            );
            return tryRunOrWebpackError(
                () =>
                    hooks.renderModuleContent.call(moduleSource, module, renderContext),
                "AsyncWebAssemblyModulesPlugin.getCompilationHooks().renderModuleContent"
            );
        } catch (err) {
            /** @type {WebpackError} */ (err).module = module;
            throw err;
        }
    }
}
 
module.exports = AsyncWebAssemblyModulesPlugin;