-
-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathContainerEntryModule.ts
More file actions
364 lines (342 loc) · 11.2 KB
/
ContainerEntryModule.ts
File metadata and controls
364 lines (342 loc) · 11.2 KB
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr
*/
'use strict';
import { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';
import { infrastructureLogger as logger } from '@module-federation/sdk';
import {
getShortErrorMsg,
buildDescMap,
BUILD_001,
} from '@module-federation/error-codes';
import type { containerPlugin } from '@module-federation/sdk';
import type { Compilation, Dependency } from 'webpack';
import type {
InputFileSystem,
LibIdentOptions,
NeedBuildContext,
ObjectDeserializerContext,
ObjectSerializerContext,
RequestShortener,
ResolverWithOptions,
WebpackOptions,
} from 'webpack/lib/Module';
import { PrefetchPlugin } from '@module-federation/data-prefetch/cli';
import type WebpackError from 'webpack/lib/WebpackError';
import { JAVASCRIPT_MODULE_TYPE_DYNAMIC } from '../Constants';
import ContainerExposedDependency from './ContainerExposedDependency';
import { getFederationGlobalScope } from './runtime/utils';
const makeSerializable = require(
normalizeWebpackPath('webpack/lib/util/makeSerializable'),
) as typeof import('webpack/lib/util/makeSerializable');
const {
sources: webpackSources,
AsyncDependenciesBlock,
Template,
Module,
RuntimeGlobals,
} = require(normalizeWebpackPath('webpack')) as typeof import('webpack');
const StaticExportsDependency = require(
normalizeWebpackPath('webpack/lib/dependencies/StaticExportsDependency'),
) as typeof import('webpack/lib/dependencies/StaticExportsDependency');
const EntryDependency = require(
normalizeWebpackPath('webpack/lib/dependencies/EntryDependency'),
) as typeof import('webpack/lib/dependencies/EntryDependency');
const SOURCE_TYPES = new Set(['javascript']);
export type ExposeOptions = {
/**
* requests to exposed modules (last one is exported)
*/
import: string[];
/**
* custom chunk name for the exposed module
*/
name: string;
};
class ContainerEntryModule extends Module {
private _name: string;
private _exposes: [string, ExposeOptions][];
private _shareScope: string | string[];
private _injectRuntimeEntry: string;
private _dataPrefetch: containerPlugin.ContainerPluginOptions['dataPrefetch'];
/**
* @param {string} name container entry name
* @param {[string, ExposeOptions][]} exposes list of exposed modules
* @param {string|string[]} shareScope name of the share scope
* @param {string} injectRuntimeEntry the path of injectRuntime file.
* @param {containerPlugin.ContainerPluginOptions['dataPrefetch']} dataPrefetch whether enable dataPrefetch
*/
constructor(
name: string,
exposes: [string, ExposeOptions][],
shareScope: string | string[],
injectRuntimeEntry: string,
dataPrefetch: containerPlugin.ContainerPluginOptions['dataPrefetch'],
) {
super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null);
this._name = name;
this._exposes = exposes;
this._shareScope = shareScope;
this._injectRuntimeEntry = injectRuntimeEntry;
this._dataPrefetch = dataPrefetch;
}
/**
* @param {ObjectDeserializerContext} context context
* @returns {ContainerEntryModule} deserialized container entry module
*/
static deserialize(context: ObjectDeserializerContext): ContainerEntryModule {
const { read } = context;
const obj = new ContainerEntryModule(
read(),
read(),
read(),
read(),
read(),
);
obj.deserialize(context);
return obj;
}
/**
* @returns {Set<string>} types available (do not mutate)
*/
override getSourceTypes(): Set<string> {
return SOURCE_TYPES;
}
/**
* @returns {string} a unique identifier of the module
*/
override identifier(): string {
const scopeStr = Array.isArray(this._shareScope)
? this._shareScope.join('|')
: this._shareScope;
return `container entry (${scopeStr}) ${JSON.stringify(
this._exposes,
)} ${this._injectRuntimeEntry} ${JSON.stringify(this._dataPrefetch)}`;
}
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
override readableIdentifier(requestShortener: RequestShortener): string {
return 'container entry';
}
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
*/
override libIdent(options: LibIdentOptions): string | null {
return `${this.layer ? `(${this.layer})/` : ''}webpack/container/entry/${
this._name
}`;
}
/**
* @param {NeedBuildContext} context context info
* @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
override needBuild(
context: NeedBuildContext,
callback: (
arg0: (WebpackError | null) | undefined,
arg1: boolean | undefined,
) => void,
): void {
callback(null, !this.buildMeta);
}
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError): void} callback callback function
* @returns {void}
*/
override build(
options: WebpackOptions,
compilation: Compilation,
resolver: ResolverWithOptions,
fs: InputFileSystem,
callback: (err?: WebpackError) => void,
): void {
this.buildMeta = {};
this.buildInfo = {
strict: true,
topLevelDeclarations: new Set(['moduleMap', 'get', 'init']),
};
this.buildMeta.exportsType = 'namespace';
this.clearDependenciesAndBlocks();
for (const [name, options] of this._exposes) {
const block = new AsyncDependenciesBlock(
{
name: options.name,
},
{ name },
options.import[options.import.length - 1],
);
let idx = 0;
for (const request of options.import) {
const dep = new ContainerExposedDependency(name, request);
dep.loc = {
name,
index: idx++,
};
block.addDependency(dep);
}
this.addBlock(block);
}
this.addDependency(
new StaticExportsDependency(
['get', 'init'],
false,
) as unknown as Dependency,
);
this.addDependency(new EntryDependency(this._injectRuntimeEntry));
callback();
}
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
override codeGeneration({ moduleGraph, chunkGraph, runtimeTemplate }: any) {
const sources = new Map();
const runtimeRequirements = new Set([
RuntimeGlobals.definePropertyGetters,
RuntimeGlobals.hasOwnProperty,
RuntimeGlobals.exports,
]);
const getters = [];
for (const block of this.blocks) {
const { dependencies } = block;
const modules = dependencies.map((dependency: Dependency) => {
const dep = dependency as unknown as ContainerExposedDependency;
return {
name: dep.exposedName,
module: moduleGraph.getModule(dep),
request: dep.userRequest,
};
});
let str;
if (modules.some((m) => !m.module)) {
logger.error(
getShortErrorMsg(BUILD_001, buildDescMap, {
exposeModules: modules.filter((m) => !m.module),
FEDERATION_WEBPACK_PATH: process.env['FEDERATION_WEBPACK_PATH'],
}),
);
process.exit(1);
} else {
str = `return ${runtimeTemplate.blockPromise({
block,
message: '',
chunkGraph,
runtimeRequirements,
})}.then(${runtimeTemplate.returningFunction(
runtimeTemplate.returningFunction(
`(${modules
.map(({ module, request }) =>
runtimeTemplate.moduleRaw({
module,
chunkGraph,
request,
weak: false,
runtimeRequirements,
}),
)
.join(', ')})`,
),
)});`;
}
getters.push(
`${JSON.stringify(modules[0].name)}: ${runtimeTemplate.basicFunction(
'',
str,
)}`,
);
}
const federationGlobal = getFederationGlobalScope(
RuntimeGlobals || ({} as typeof RuntimeGlobals),
);
const source = Template.asString([
`var moduleMap = {`,
Template.indent(getters.join(',\n')),
'};',
`var get = ${runtimeTemplate.basicFunction('module, getScope', [
`${RuntimeGlobals.currentRemoteGetScope} = getScope;`,
// reusing the getScope variable to avoid creating a new var (and module is also used later)
'getScope = (',
Template.indent([
`${RuntimeGlobals.hasOwnProperty}(moduleMap, module)`,
Template.indent([
'? moduleMap[module]()',
`: Promise.resolve().then(${runtimeTemplate.basicFunction(
'',
"throw new Error('Module \"' + module + '\" does not exist in container.');",
)})`,
]),
]),
');',
`${RuntimeGlobals.currentRemoteGetScope} = undefined;`,
'return getScope;',
])};`,
`var init = ${runtimeTemplate.basicFunction(
'shareScope, initScope, remoteEntryInitOptions',
[
`return ${federationGlobal}.bundlerRuntime.initContainerEntry({${Template.indent(
[
`webpackRequire: ${RuntimeGlobals.require},`,
`shareScope: shareScope,`,
`initScope: initScope,`,
`remoteEntryInitOptions: remoteEntryInitOptions,`,
`shareScopeKey: ${JSON.stringify(this._shareScope)}`,
],
)}`,
'})',
],
)};`,
this._dataPrefetch ? PrefetchPlugin.setRemoteIdentifier() : '',
this._dataPrefetch ? PrefetchPlugin.removeRemoteIdentifier() : '',
'// This exports getters to disallow modifications',
`${RuntimeGlobals.definePropertyGetters}(exports, {`,
Template.indent([
`get: ${runtimeTemplate.returningFunction('get')},`,
`init: ${runtimeTemplate.returningFunction('init')}`,
]),
'});',
]);
sources.set(
'javascript',
this.useSourceMap || this.useSimpleSourceMap
? new webpackSources.OriginalSource(source, 'webpack/container-entry')
: new webpackSources.RawSource(source),
);
return {
sources,
runtimeRequirements,
};
}
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
override size(type?: string): number {
return 42;
}
/**
* @param {ObjectSerializerContext} context context
*/
override serialize(context: ObjectSerializerContext): void {
const { write } = context;
write(this._name);
write(this._exposes);
write(this._shareScope);
write(this._injectRuntimeEntry);
write(this._dataPrefetch);
super.serialize(context);
}
}
makeSerializable(
ContainerEntryModule,
'enhanced/lib/container/ContainerEntryModule',
);
export default ContainerEntryModule;