source: trip-planner-front/node_modules/webpack/lib/hmr/LazyCompilationPlugin.js@ 59329aa

Last change on this file since 59329aa was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 11.5 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 RuntimeGlobals = require("../RuntimeGlobals");
14const Template = require("../Template");
15const CommonJsRequireDependency = require("../dependencies/CommonJsRequireDependency");
16const { registerNotSerializable } = require("../util/serialization");
17
18/** @typedef {import("../../declarations/WebpackOptions")} WebpackOptions */
19/** @typedef {import("../Compilation")} Compilation */
20/** @typedef {import("../Compiler")} Compiler */
21/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
22/** @typedef {import("../Module").BuildMeta} BuildMeta */
23/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
24/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
25/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
26/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
27/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */
28/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */
29/** @typedef {import("../RequestShortener")} RequestShortener */
30/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
31/** @typedef {import("../WebpackError")} WebpackError */
32/** @typedef {import("../util/Hash")} Hash */
33/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
34
35const IGNORED_DEPENDENCY_TYPES = new Set([
36 "import.meta.webpackHot.accept",
37 "import.meta.webpackHot.decline",
38 "module.hot.accept",
39 "module.hot.decline"
40]);
41
42/**
43 * @param {undefined|string|RegExp|Function} test test option
44 * @param {Module} module the module
45 * @returns {boolean} true, if the module should be selected
46 */
47const checkTest = (test, module) => {
48 if (test === undefined) return true;
49 if (typeof test === "function") {
50 return test(module);
51 }
52 if (typeof test === "string") {
53 const name = module.nameForCondition();
54 return name && name.startsWith(test);
55 }
56 if (test instanceof RegExp) {
57 const name = module.nameForCondition();
58 return name && test.test(name);
59 }
60 return false;
61};
62
63const TYPES = new Set(["javascript"]);
64
65class LazyCompilationDependency extends Dependency {
66 constructor(proxyModule) {
67 super();
68 this.proxyModule = proxyModule;
69 }
70
71 get category() {
72 return "esm";
73 }
74
75 get type() {
76 return "lazy import()";
77 }
78
79 /**
80 * @returns {string | null} an identifier to merge equal requests
81 */
82 getResourceIdentifier() {
83 return this.proxyModule.originalModule.identifier();
84 }
85}
86
87registerNotSerializable(LazyCompilationDependency);
88
89class LazyCompilationProxyModule extends Module {
90 constructor(context, originalModule, request, client, data, active) {
91 super("lazy-compilation-proxy", context, originalModule.layer);
92 this.originalModule = originalModule;
93 this.request = request;
94 this.client = client;
95 this.data = data;
96 this.active = active;
97 }
98
99 /**
100 * @returns {string} a unique identifier of the module
101 */
102 identifier() {
103 return `lazy-compilation-proxy|${this.originalModule.identifier()}`;
104 }
105
106 /**
107 * @param {RequestShortener} requestShortener the request shortener
108 * @returns {string} a user readable identifier of the module
109 */
110 readableIdentifier(requestShortener) {
111 return `lazy-compilation-proxy ${this.originalModule.readableIdentifier(
112 requestShortener
113 )}`;
114 }
115
116 /**
117 * Assuming this module is in the cache. Update the (cached) module with
118 * the fresh module from the factory. Usually updates internal references
119 * and properties.
120 * @param {Module} module fresh module
121 * @returns {void}
122 */
123 updateCacheModule(module) {
124 super.updateCacheModule(module);
125 const m = /** @type {LazyCompilationProxyModule} */ (module);
126 this.originalModule = m.originalModule;
127 this.request = m.request;
128 this.client = m.client;
129 this.data = m.data;
130 this.active = m.active;
131 }
132
133 /**
134 * @param {LibIdentOptions} options options
135 * @returns {string | null} an identifier for library inclusion
136 */
137 libIdent(options) {
138 return `${this.originalModule.libIdent(options)}!lazy-compilation-proxy`;
139 }
140
141 /**
142 * @param {NeedBuildContext} context context info
143 * @param {function(WebpackError=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
144 * @returns {void}
145 */
146 needBuild(context, callback) {
147 callback(null, !this.buildInfo || this.buildInfo.active !== this.active);
148 }
149
150 /**
151 * @param {WebpackOptions} options webpack options
152 * @param {Compilation} compilation the compilation
153 * @param {ResolverWithOptions} resolver the resolver
154 * @param {InputFileSystem} fs the file system
155 * @param {function(WebpackError=): void} callback callback function
156 * @returns {void}
157 */
158 build(options, compilation, resolver, fs, callback) {
159 this.buildInfo = {
160 active: this.active
161 };
162 /** @type {BuildMeta} */
163 this.buildMeta = {};
164 this.clearDependenciesAndBlocks();
165 const dep = new CommonJsRequireDependency(this.client);
166 this.addDependency(dep);
167 if (this.active) {
168 const dep = new LazyCompilationDependency(this);
169 const block = new AsyncDependenciesBlock({});
170 block.addDependency(dep);
171 this.addBlock(block);
172 }
173 callback();
174 }
175
176 /**
177 * @returns {Set<string>} types available (do not mutate)
178 */
179 getSourceTypes() {
180 return TYPES;
181 }
182
183 /**
184 * @param {string=} type the source type for which the size should be estimated
185 * @returns {number} the estimated size of the module (must be non-zero)
186 */
187 size(type) {
188 return 200;
189 }
190
191 /**
192 * @param {CodeGenerationContext} context context for code generation
193 * @returns {CodeGenerationResult} result
194 */
195 codeGeneration({ runtimeTemplate, chunkGraph, moduleGraph }) {
196 const sources = new Map();
197 const runtimeRequirements = new Set();
198 runtimeRequirements.add(RuntimeGlobals.module);
199 const clientDep = /** @type {CommonJsRequireDependency} */ (
200 this.dependencies[0]
201 );
202 const clientModule = moduleGraph.getModule(clientDep);
203 const block = this.blocks[0];
204 const client = Template.asString([
205 `var client = ${runtimeTemplate.moduleExports({
206 module: clientModule,
207 chunkGraph,
208 request: clientDep.userRequest,
209 runtimeRequirements
210 })}`,
211 `var data = ${JSON.stringify(this.data)};`
212 ]);
213 const keepActive = Template.asString([
214 `var dispose = client.keepAlive({ data: data, active: ${JSON.stringify(
215 !!block
216 )}, module: module, onError: onError });`
217 ]);
218 let source;
219 if (block) {
220 const dep = block.dependencies[0];
221 const module = moduleGraph.getModule(dep);
222 source = Template.asString([
223 client,
224 `module.exports = ${runtimeTemplate.moduleNamespacePromise({
225 chunkGraph,
226 block,
227 module,
228 request: this.request,
229 strict: false, // TODO this should be inherited from the original module
230 message: "import()",
231 runtimeRequirements
232 })};`,
233 "if (module.hot) {",
234 Template.indent([
235 "module.hot.accept();",
236 `module.hot.accept(${JSON.stringify(
237 chunkGraph.getModuleId(module)
238 )}, function() { module.hot.invalidate(); });`,
239 "module.hot.dispose(function(data) { delete data.resolveSelf; dispose(data); });",
240 "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);"
241 ]),
242 "}",
243 "function onError() { /* ignore */ }",
244 keepActive
245 ]);
246 } else {
247 source = Template.asString([
248 client,
249 "var resolveSelf, onError;",
250 `module.exports = new Promise(function(resolve, reject) { resolveSelf = resolve; onError = reject; });`,
251 "if (module.hot) {",
252 Template.indent([
253 "module.hot.accept();",
254 "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);",
255 "module.hot.dispose(function(data) { data.resolveSelf = resolveSelf; dispose(data); });"
256 ]),
257 "}",
258 keepActive
259 ]);
260 }
261 sources.set("javascript", new RawSource(source));
262 return {
263 sources,
264 runtimeRequirements
265 };
266 }
267
268 /**
269 * @param {Hash} hash the hash used to track dependencies
270 * @param {UpdateHashContext} context context
271 * @returns {void}
272 */
273 updateHash(hash, context) {
274 super.updateHash(hash, context);
275 hash.update(this.active ? "active" : "");
276 hash.update(JSON.stringify(this.data));
277 }
278}
279
280registerNotSerializable(LazyCompilationProxyModule);
281
282class LazyCompilationDependencyFactory extends ModuleFactory {
283 constructor(factory) {
284 super();
285 this._factory = factory;
286 }
287
288 /**
289 * @param {ModuleFactoryCreateData} data data object
290 * @param {function(Error=, ModuleFactoryResult=): void} callback callback
291 * @returns {void}
292 */
293 create(data, callback) {
294 const dependency = /** @type {LazyCompilationDependency} */ (
295 data.dependencies[0]
296 );
297 callback(null, {
298 module: dependency.proxyModule.originalModule
299 });
300 }
301}
302
303class LazyCompilationPlugin {
304 /**
305 * @param {Object} options options
306 * @param {(function(Compiler, string, function(Error?, any?): void): void) | function(Compiler, string): Promise<any>} options.backend the backend
307 * @param {string} options.client the client reference
308 * @param {boolean} options.entries true, when entries are lazy compiled
309 * @param {boolean} options.imports true, when import() modules are lazy compiled
310 * @param {RegExp | string | (function(Module): boolean)} options.test additional filter for lazy compiled entrypoint modules
311 */
312 constructor({ backend, client, entries, imports, test }) {
313 this.backend = backend;
314 this.client = client;
315 this.entries = entries;
316 this.imports = imports;
317 this.test = test;
318 }
319 /**
320 * Apply the plugin
321 * @param {Compiler} compiler the compiler instance
322 * @returns {void}
323 */
324 apply(compiler) {
325 let backend;
326 compiler.hooks.beforeCompile.tapAsync(
327 "LazyCompilationPlugin",
328 (params, callback) => {
329 if (backend !== undefined) return callback();
330 const promise = this.backend(compiler, this.client, (err, result) => {
331 if (err) return callback(err);
332 backend = result;
333 callback();
334 });
335 if (promise && promise.then) {
336 promise.then(b => {
337 backend = b;
338 callback();
339 }, callback);
340 }
341 }
342 );
343 compiler.hooks.thisCompilation.tap(
344 "LazyCompilationPlugin",
345 (compilation, { normalModuleFactory }) => {
346 normalModuleFactory.hooks.module.tap(
347 "LazyCompilationPlugin",
348 (originalModule, createData, resolveData) => {
349 if (
350 resolveData.dependencies.every(
351 dep =>
352 IGNORED_DEPENDENCY_TYPES.has(dep.type) ||
353 (this.imports &&
354 (dep.type === "import()" ||
355 dep.type === "import() context element")) ||
356 (this.entries && dep.type === "entry")
357 ) &&
358 !/webpack[/\\]hot[/\\]|webpack-dev-server[/\\]client/.test(
359 resolveData.request
360 ) &&
361 checkTest(this.test, originalModule)
362 ) {
363 const moduleInfo = backend.module(originalModule);
364 if (!moduleInfo) return;
365 const { client, data, active } = moduleInfo;
366
367 return new LazyCompilationProxyModule(
368 compiler.context,
369 originalModule,
370 resolveData.request,
371 client,
372 data,
373 active
374 );
375 }
376 }
377 );
378 compilation.dependencyFactories.set(
379 LazyCompilationDependency,
380 new LazyCompilationDependencyFactory()
381 );
382 }
383 );
384 compiler.hooks.shutdown.tapAsync("LazyCompilationPlugin", callback => {
385 backend.dispose(callback);
386 });
387 }
388}
389
390module.exports = LazyCompilationPlugin;
Note: See TracBrowser for help on using the repository browser.