source: frontend/node_modules/webpack/lib/hmr/LazyCompilationPlugin.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 14.9 KB
Line 
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5
6"use strict";
7
8const { RawSource } = require("webpack-sources");
9const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
10const Dependency = require("../Dependency");
11const Module = require("../Module");
12const ModuleFactory = require("../ModuleFactory");
13const { JAVASCRIPT_TYPES } = require("../ModuleSourceTypeConstants");
14const { JAVASCRIPT_TYPE } = require("../ModuleSourceTypeConstants");
15const {
16 WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY
17} = require("../ModuleTypeConstants");
18const RuntimeGlobals = require("../RuntimeGlobals");
19const Template = require("../Template");
20const CommonJsRequireDependency = require("../dependencies/CommonJsRequireDependency");
21const { registerNotSerializable } = require("../util/serialization");
22
23/** @typedef {import("../config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
24/** @typedef {import("../Compilation")} Compilation */
25/** @typedef {import("../Compiler")} Compiler */
26/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
27/** @typedef {import("../Module").BuildCallback} BuildCallback */
28/** @typedef {import("../Module").BuildMeta} BuildMeta */
29/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
30/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
31/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
32/** @typedef {import("../Module").LibIdent} LibIdent */
33/** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */
34/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
35/** @typedef {import("../Module").SourceTypes} SourceTypes */
36/** @typedef {import("../Module").Sources} Sources */
37/** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */
38/** @typedef {import("../ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */
39/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */
40/** @typedef {import("../RequestShortener")} RequestShortener */
41/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
42/** @typedef {import("../dependencies/HarmonyImportDependency")} HarmonyImportDependency */
43/** @typedef {import("../util/Hash")} Hash */
44/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
45
46/** @typedef {{ client: string, data: string, active: boolean }} ModuleResult */
47
48/**
49 * Defines the backend api type used by this module.
50 * @typedef {object} BackendApi
51 * @property {(callback: (err?: (Error | null)) => void) => void} dispose
52 * @property {(module: Module) => ModuleResult} module
53 */
54
55const HMR_DEPENDENCY_TYPES = new Set([
56 "import.meta.webpackHot.accept",
57 "import.meta.webpackHot.decline",
58 "module.hot.accept",
59 "module.hot.decline"
60]);
61
62/**
63 * Checks true, if the module should be selected.
64 * @param {Options["test"]} test test option
65 * @param {Module} module the module
66 * @returns {boolean | null | string} true, if the module should be selected
67 */
68const checkTest = (test, module) => {
69 if (test === undefined) return true;
70 if (typeof test === "function") {
71 return test(module);
72 }
73 if (typeof test === "string") {
74 const name = module.nameForCondition();
75 return name && name.startsWith(test);
76 }
77 if (test instanceof RegExp) {
78 const name = module.nameForCondition();
79 return name && test.test(name);
80 }
81 return false;
82};
83
84class LazyCompilationDependency extends Dependency {
85 /**
86 * Creates an instance of LazyCompilationDependency.
87 * @param {LazyCompilationProxyModule} proxyModule proxy module
88 */
89 constructor(proxyModule) {
90 super();
91 this.proxyModule = proxyModule;
92 }
93
94 get category() {
95 return "esm";
96 }
97
98 get type() {
99 return "lazy import()";
100 }
101
102 /**
103 * Returns an identifier to merge equal requests.
104 * @returns {string | null} an identifier to merge equal requests
105 */
106 getResourceIdentifier() {
107 return this.proxyModule.originalModule.identifier();
108 }
109}
110
111registerNotSerializable(LazyCompilationDependency);
112
113class LazyCompilationProxyModule extends Module {
114 /**
115 * Creates an instance of LazyCompilationProxyModule.
116 * @param {string} context context
117 * @param {Module} originalModule an original module
118 * @param {string} request request
119 * @param {ModuleResult["client"]} client client
120 * @param {ModuleResult["data"]} data data
121 * @param {ModuleResult["active"]} active true when active, otherwise false
122 */
123 constructor(context, originalModule, request, client, data, active) {
124 super(
125 WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY,
126 context,
127 originalModule.layer
128 );
129 this.originalModule = originalModule;
130 this.request = request;
131 this.client = client;
132 this.data = data;
133 this.active = active;
134 }
135
136 /**
137 * Returns the unique identifier used to reference this module.
138 * @returns {string} a unique identifier of the module
139 */
140 identifier() {
141 return `${WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY}|${this.originalModule.identifier()}`;
142 }
143
144 /**
145 * Returns a human-readable identifier for this module.
146 * @param {RequestShortener} requestShortener the request shortener
147 * @returns {string} a user readable identifier of the module
148 */
149 readableIdentifier(requestShortener) {
150 return `${WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY} ${this.originalModule.readableIdentifier(
151 requestShortener
152 )}`;
153 }
154
155 /**
156 * Assuming this module is in the cache. Update the (cached) module with
157 * the fresh module from the factory. Usually updates internal references
158 * and properties.
159 * @param {Module} module fresh module
160 * @returns {void}
161 */
162 updateCacheModule(module) {
163 super.updateCacheModule(module);
164 const m = /** @type {LazyCompilationProxyModule} */ (module);
165 this.originalModule = m.originalModule;
166 this.request = m.request;
167 this.client = m.client;
168 this.data = m.data;
169 this.active = m.active;
170 }
171
172 /**
173 * Gets the library identifier.
174 * @param {LibIdentOptions} options options
175 * @returns {LibIdent | null} an identifier for library inclusion
176 */
177 libIdent(options) {
178 return `${this.originalModule.libIdent(
179 options
180 )}!${WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY}`;
181 }
182
183 /**
184 * Checks whether the module needs to be rebuilt for the current build state.
185 * @param {NeedBuildContext} context context info
186 * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
187 * @returns {void}
188 */
189 needBuild(context, callback) {
190 callback(null, !this.buildInfo || this.buildInfo.active !== this.active);
191 }
192
193 /**
194 * Builds the module using the provided compilation context.
195 * @param {WebpackOptions} options webpack options
196 * @param {Compilation} compilation the compilation
197 * @param {ResolverWithOptions} resolver the resolver
198 * @param {InputFileSystem} fs the file system
199 * @param {BuildCallback} callback callback function
200 * @returns {void}
201 */
202 build(options, compilation, resolver, fs, callback) {
203 this.buildInfo = {
204 active: this.active
205 };
206 /** @type {BuildMeta} */
207 this.buildMeta = {};
208 this.clearDependenciesAndBlocks();
209 const dep = new CommonJsRequireDependency(this.client);
210 this.addDependency(dep);
211 if (this.active) {
212 const dep = new LazyCompilationDependency(this);
213 const block = new AsyncDependenciesBlock({});
214 block.addDependency(dep);
215 this.addBlock(block);
216 }
217 callback();
218 }
219
220 /**
221 * Returns the source types this module can generate.
222 * @returns {SourceTypes} types available (do not mutate)
223 */
224 getSourceTypes() {
225 return JAVASCRIPT_TYPES;
226 }
227
228 /**
229 * Returns the estimated size for the requested source type.
230 * @param {string=} type the source type for which the size should be estimated
231 * @returns {number} the estimated size of the module (must be non-zero)
232 */
233 size(type) {
234 return 200;
235 }
236
237 /**
238 * Generates code and runtime requirements for this module.
239 * @param {CodeGenerationContext} context context for code generation
240 * @returns {CodeGenerationResult} result
241 */
242 codeGeneration({ runtimeTemplate, chunkGraph, moduleGraph }) {
243 /** @type {Sources} */
244 const sources = new Map();
245 /** @type {RuntimeRequirements} */
246 const runtimeRequirements = new Set();
247 runtimeRequirements.add(RuntimeGlobals.module);
248 const clientDep = /** @type {CommonJsRequireDependency} */ (
249 this.dependencies[0]
250 );
251 const clientModule = moduleGraph.getModule(clientDep);
252 const block = this.blocks[0];
253 const client = Template.asString([
254 `var client = ${runtimeTemplate.moduleExports({
255 module: clientModule,
256 chunkGraph,
257 request: clientDep.userRequest,
258 runtimeRequirements
259 })}`,
260 `var data = ${JSON.stringify(this.data)};`
261 ]);
262 const keepActive = Template.asString([
263 `var dispose = client.keepAlive({ data: data, active: ${JSON.stringify(
264 Boolean(block)
265 )}, module: module, onError: onError });`
266 ]);
267 /** @type {string} */
268 let source;
269 if (block) {
270 const dep = block.dependencies[0];
271 const module = /** @type {Module} */ (moduleGraph.getModule(dep));
272 source = Template.asString([
273 client,
274 `module.exports = ${runtimeTemplate.moduleNamespacePromise({
275 chunkGraph,
276 block,
277 module,
278 request: this.request,
279 dependency: dep,
280 strict: false, // TODO this should be inherited from the original module
281 message: "import()",
282 runtimeRequirements
283 })};`,
284 "if (module.hot) {",
285 Template.indent([
286 "module.hot.accept();",
287 `module.hot.accept(${JSON.stringify(
288 chunkGraph.getModuleId(module)
289 )}, function() { module.hot.invalidate(); });`,
290 "module.hot.dispose(function(data) { delete data.resolveSelf; dispose(data); });",
291 "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);"
292 ]),
293 "}",
294 "function onError() { /* ignore */ }",
295 keepActive
296 ]);
297 } else {
298 source = Template.asString([
299 client,
300 "var resolveSelf, onError;",
301 "module.exports = new Promise(function(resolve, reject) { resolveSelf = resolve; onError = reject; });",
302 "if (module.hot) {",
303 Template.indent([
304 "module.hot.accept();",
305 "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);",
306 "module.hot.dispose(function(data) { data.resolveSelf = resolveSelf; dispose(data); });"
307 ]),
308 "}",
309 keepActive
310 ]);
311 }
312 sources.set(JAVASCRIPT_TYPE, new RawSource(source));
313 return {
314 sources,
315 runtimeRequirements
316 };
317 }
318
319 /**
320 * Updates the hash with the data contributed by this instance.
321 * @param {Hash} hash the hash used to track dependencies
322 * @param {UpdateHashContext} context context
323 * @returns {void}
324 */
325 updateHash(hash, context) {
326 super.updateHash(hash, context);
327 hash.update(this.active ? "active" : "");
328 hash.update(JSON.stringify(this.data));
329 }
330}
331
332registerNotSerializable(LazyCompilationProxyModule);
333
334class LazyCompilationDependencyFactory extends ModuleFactory {
335 constructor() {
336 super();
337 }
338
339 /**
340 * Processes the provided data.
341 * @param {ModuleFactoryCreateData} data data object
342 * @param {ModuleFactoryCallback} callback callback
343 * @returns {void}
344 */
345 create(data, callback) {
346 const dependency =
347 /** @type {LazyCompilationDependency} */
348 (data.dependencies[0]);
349 callback(null, {
350 module: dependency.proxyModule.originalModule
351 });
352 }
353}
354
355/**
356 * Defines the backend handler callback.
357 * @callback BackendHandler
358 * @param {Compiler} compiler compiler
359 * @param {(err: Error | null, backendApi?: BackendApi) => void} callback callback
360 * @returns {void}
361 */
362
363/**
364 * Defines the promise backend handler callback.
365 * @callback PromiseBackendHandler
366 * @param {Compiler} compiler compiler
367 * @returns {Promise<BackendApi>} backend
368 */
369
370/** @typedef {BackendHandler | PromiseBackendHandler} BackEnd */
371
372/** @typedef {(module: Module) => boolean} TestFn */
373
374/**
375 * Defines the options type used by this module.
376 * @typedef {object} Options options
377 * @property {BackEnd} backend the backend
378 * @property {boolean=} entries
379 * @property {boolean=} imports
380 * @property {RegExp | string | TestFn=} test additional filter for lazy compiled entrypoint modules
381 */
382
383const PLUGIN_NAME = "LazyCompilationPlugin";
384
385class LazyCompilationPlugin {
386 /**
387 * Creates an instance of LazyCompilationPlugin.
388 * @param {Options} options options
389 */
390 constructor({ backend, entries, imports, test }) {
391 this.backend = backend;
392 this.entries = entries;
393 this.imports = imports;
394 this.test = test;
395 }
396
397 /**
398 * Applies the plugin by registering its hooks on the compiler.
399 * @param {Compiler} compiler the compiler instance
400 * @returns {void}
401 */
402 apply(compiler) {
403 /** @type {BackendApi} */
404 let backend;
405 compiler.hooks.beforeCompile.tapAsync(PLUGIN_NAME, (params, callback) => {
406 if (backend !== undefined) return callback();
407 const promise = this.backend(compiler, (err, result) => {
408 if (err) return callback(err);
409 backend = /** @type {BackendApi} */ (result);
410 callback();
411 });
412 if (promise && promise.then) {
413 promise.then((b) => {
414 backend = b;
415 callback();
416 }, callback);
417 }
418 });
419 compiler.hooks.thisCompilation.tap(
420 PLUGIN_NAME,
421 (compilation, { normalModuleFactory }) => {
422 normalModuleFactory.hooks.module.tap(
423 PLUGIN_NAME,
424 (module, createData, resolveData) => {
425 if (
426 resolveData.dependencies.every((dep) =>
427 HMR_DEPENDENCY_TYPES.has(dep.type)
428 )
429 ) {
430 // for HMR only resolving, try to determine if the HMR accept/decline refers to
431 // an import() or not
432 const hmrDep = resolveData.dependencies[0];
433 const originModule =
434 /** @type {Module} */
435 (compilation.moduleGraph.getParentModule(hmrDep));
436 const isReferringToDynamicImport = originModule.blocks.some(
437 (block) =>
438 block.dependencies.some(
439 (dep) =>
440 dep.type === "import()" &&
441 /** @type {HarmonyImportDependency} */ (dep).request ===
442 hmrDep.request
443 )
444 );
445 if (!isReferringToDynamicImport) return module;
446 } else if (
447 !resolveData.dependencies.every(
448 (dep) =>
449 HMR_DEPENDENCY_TYPES.has(dep.type) ||
450 (this.imports &&
451 (dep.type === "import()" ||
452 dep.type === "import() context element")) ||
453 (this.entries && dep.type === "entry")
454 )
455 ) {
456 return module;
457 }
458 if (
459 /webpack[/\\]hot[/\\]|webpack-dev-server[/\\]client|webpack-hot-middleware[/\\]client/.test(
460 resolveData.request
461 ) ||
462 !checkTest(this.test, module)
463 ) {
464 return module;
465 }
466 const moduleInfo = backend.module(module);
467 if (!moduleInfo) return module;
468 const { client, data, active } = moduleInfo;
469
470 return new LazyCompilationProxyModule(
471 compiler.context,
472 module,
473 resolveData.request,
474 client,
475 data,
476 active
477 );
478 }
479 );
480 compilation.dependencyFactories.set(
481 LazyCompilationDependency,
482 new LazyCompilationDependencyFactory()
483 );
484 }
485 );
486 compiler.hooks.shutdown.tapAsync(PLUGIN_NAME, (callback) => {
487 backend.dispose(callback);
488 });
489 }
490}
491
492module.exports = LazyCompilationPlugin;
Note: See TracBrowser for help on using the repository browser.