@module-federation/nextjs-mf 5.3.1 → 5.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "public": true,
3
3
  "name": "@module-federation/nextjs-mf",
4
- "version": "5.3.1",
4
+ "version": "5.3.2",
5
5
  "description": "Module Federation helper for NextJS",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/index.d.ts",
@@ -1,86 +0,0 @@
1
- 'use strict';
2
-
3
- var LoadFileChunkLoadingRuntimeModule = require('./LoadFileChunkLoadingRuntimeModule.js');
4
-
5
- const RuntimeGlobals = require('webpack/lib/RuntimeGlobals');
6
- const StartupChunkDependenciesPlugin = require('webpack/lib/runtime/StartupChunkDependenciesPlugin');
7
- // const ChunkLoadingRuntimeModule = require('webpack/lib/node/ReadFileChunkLoadingRuntimeModule')
8
- class CommonJsChunkLoadingPlugin {
9
- constructor(options) {
10
- this.options = options || {};
11
- this._asyncChunkLoading = this.options.asyncChunkLoading;
12
- }
13
-
14
- /**
15
- * Apply the plugin
16
- * @param {Compiler} compiler the compiler instance
17
- * @returns {void}
18
- */
19
- apply(compiler) {
20
- const chunkLoadingValue = this._asyncChunkLoading
21
- ? 'async-node'
22
- : 'require';
23
- new StartupChunkDependenciesPlugin({
24
- chunkLoading: chunkLoadingValue,
25
- asyncChunkLoading: this._asyncChunkLoading,
26
- }).apply(compiler);
27
- compiler.hooks.thisCompilation.tap(
28
- 'CommonJsChunkLoadingPlugin',
29
- (compilation) => {
30
- const onceForChunkSet = new WeakSet();
31
- const handler = (chunk, set) => {
32
- if (onceForChunkSet.has(chunk)) return;
33
- onceForChunkSet.add(chunk);
34
- set.add(RuntimeGlobals.moduleFactoriesAddOnly);
35
- set.add(RuntimeGlobals.hasOwnProperty);
36
- compilation.addRuntimeModule(
37
- chunk,
38
- new LoadFileChunkLoadingRuntimeModule(set, this.options, {
39
- webpack: compiler.webpack,
40
- })
41
- );
42
- };
43
-
44
- compilation.hooks.runtimeRequirementInTree
45
- .for(RuntimeGlobals.ensureChunkHandlers)
46
- .tap('CommonJsChunkLoadingPlugin', handler);
47
- compilation.hooks.runtimeRequirementInTree
48
- .for(RuntimeGlobals.hmrDownloadUpdateHandlers)
49
- .tap('CommonJsChunkLoadingPlugin', handler);
50
- compilation.hooks.runtimeRequirementInTree
51
- .for(RuntimeGlobals.hmrDownloadManifest)
52
- .tap('CommonJsChunkLoadingPlugin', handler);
53
- compilation.hooks.runtimeRequirementInTree
54
- .for(RuntimeGlobals.baseURI)
55
- .tap('CommonJsChunkLoadingPlugin', handler);
56
- compilation.hooks.runtimeRequirementInTree
57
- .for(RuntimeGlobals.externalInstallChunk)
58
- .tap('CommonJsChunkLoadingPlugin', handler);
59
- compilation.hooks.runtimeRequirementInTree
60
- .for(RuntimeGlobals.onChunksLoaded)
61
- .tap('CommonJsChunkLoadingPlugin', handler);
62
-
63
- compilation.hooks.runtimeRequirementInTree
64
- .for(RuntimeGlobals.ensureChunkHandlers)
65
- .tap('CommonJsChunkLoadingPlugin', (chunk, set) => {
66
- set.add(RuntimeGlobals.getChunkScriptFilename);
67
- });
68
- compilation.hooks.runtimeRequirementInTree
69
- .for(RuntimeGlobals.hmrDownloadUpdateHandlers)
70
- .tap('CommonJsChunkLoadingPlugin', (chunk, set) => {
71
- set.add(RuntimeGlobals.getChunkUpdateScriptFilename);
72
- set.add(RuntimeGlobals.moduleCache);
73
- set.add(RuntimeGlobals.hmrModuleData);
74
- set.add(RuntimeGlobals.moduleFactoriesAddOnly);
75
- });
76
- compilation.hooks.runtimeRequirementInTree
77
- .for(RuntimeGlobals.hmrDownloadManifest)
78
- .tap('CommonJsChunkLoadingPlugin', (chunk, set) => {
79
- set.add(RuntimeGlobals.getUpdateManifestFilename);
80
- });
81
- }
82
- );
83
- }
84
- }
85
-
86
- module.exports = CommonJsChunkLoadingPlugin;
@@ -1,410 +0,0 @@
1
- 'use strict';
2
-
3
- var loadScript = require('./loadScript.js');
4
-
5
- /*
6
- MIT License http://www.opensource.org/licenses/mit-license.php
7
- */
8
-
9
- const RuntimeGlobals = require('webpack/lib/RuntimeGlobals');
10
- const RuntimeModule = require('webpack/lib/RuntimeModule');
11
- const Template = require('webpack/lib/Template');
12
- const compileBooleanMatcher = require('webpack/lib/util/compileBooleanMatcher');
13
- const { getUndoPath } = require('webpack/lib/util/identifier');
14
-
15
- class ReadFileChunkLoadingRuntimeModule extends RuntimeModule {
16
- constructor(runtimeRequirements, options, context) {
17
- super('readFile chunk loading', RuntimeModule.STAGE_ATTACH);
18
- this.runtimeRequirements = runtimeRequirements;
19
- this.options = options;
20
- this.context = context;
21
- }
22
-
23
- /**
24
- * @private
25
- * @param {Chunk} chunk chunk
26
- * @param {string} rootOutputDir root output directory
27
- * @returns {string} generated code
28
- */
29
- _generateBaseUri(chunk, rootOutputDir) {
30
- const options = chunk.getEntryOptions();
31
- if (options && options.baseUri) {
32
- return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
33
- }
34
-
35
- return `${RuntimeGlobals.baseURI} = require("url").pathToFileURL(${
36
- rootOutputDir
37
- ? `__dirname + ${JSON.stringify('/' + rootOutputDir)}`
38
- : '__filename'
39
- });`;
40
- }
41
-
42
- /**
43
- * @returns {string} runtime code
44
- */
45
- generate() {
46
- // name in this context is always the current remote itself.
47
- // this code below is in each webpack runtime, host and remotes
48
- // remote entries handle their own loading of chunks, so i have fractal self awareness
49
- // hosts will likely never run the http chunk loading runtime, they use fs.readFile
50
- // remotes only use fs.readFile if we were to cache the chunks on disk after fetching - otherwise its always using http
51
- // so for example, if im in hostA and require(remoteb/module) --> console.log of name in runtime code will return remoteb
52
-
53
- const { baseURI, promiseBaseURI, remotes, name } = this.options;
54
- const { webpack } = this.context;
55
- const chunkHasJs =
56
- (webpack && webpack.javascript.JavascriptModulesPlugin.chunkHasJs) ||
57
- require('webpack/lib/javascript/JavascriptModulesPlugin').chunkHasJs;
58
-
59
- // workaround for next.js
60
- const getInitialChunkIds = (chunk, chunkGraph) => {
61
- const initialChunkIds = new Set(chunk.ids);
62
- for (const c of chunk.getAllInitialChunks()) {
63
- if (c === chunk || chunkHasJs(c, chunkGraph)) continue;
64
- for (const id of c.ids) initialChunkIds.add(id);
65
- }
66
- return initialChunkIds;
67
- };
68
-
69
- const { chunkGraph, chunk } = this;
70
- const { runtimeTemplate } = this.compilation;
71
- const fn = RuntimeGlobals.ensureChunkHandlers;
72
- const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI);
73
- const withExternalInstallChunk = this.runtimeRequirements.has(
74
- RuntimeGlobals.externalInstallChunk
75
- );
76
- const withOnChunkLoad = this.runtimeRequirements.has(
77
- RuntimeGlobals.onChunksLoaded
78
- );
79
- const withLoading = this.runtimeRequirements.has(
80
- RuntimeGlobals.ensureChunkHandlers
81
- );
82
- const withHmr = this.runtimeRequirements.has(
83
- RuntimeGlobals.hmrDownloadUpdateHandlers
84
- );
85
- const withHmrManifest = this.runtimeRequirements.has(
86
- RuntimeGlobals.hmrDownloadManifest
87
- );
88
-
89
- const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs);
90
- const hasJsMatcher = compileBooleanMatcher(conditionMap);
91
- const initialChunkIds = getInitialChunkIds(chunk, chunkGraph);
92
-
93
- const outputName = this.compilation.getPath(
94
- (
95
- (webpack &&
96
- webpack.javascript.JavascriptModulesPlugin
97
- .getChunkFilenameTemplate) ||
98
- require('webpack/lib/javascript/JavascriptModulesPlugin')
99
- .getChunkFilenameTemplate
100
- )(chunk, this.compilation.outputOptions),
101
- {
102
- chunk,
103
- contentHashType: 'javascript',
104
- }
105
- );
106
- const rootOutputDir = getUndoPath(
107
- outputName,
108
- this.compilation.outputOptions.path,
109
- false
110
- );
111
-
112
- const stateExpression = withHmr
113
- ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_readFileVm`
114
- : undefined;
115
-
116
- return Template.asString([
117
- withBaseURI
118
- ? this._generateBaseUri(chunk, rootOutputDir)
119
- : '// no baseURI',
120
- '',
121
- '// object to store loaded chunks',
122
- '// "0" means "already loaded", Promise means loading',
123
- `var installedChunks = ${
124
- stateExpression ? `${stateExpression} = ${stateExpression} || ` : ''
125
- }{`,
126
- Template.indent(
127
- Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 0`).join(
128
- ',\n'
129
- )
130
- ),
131
- '};',
132
- '',
133
- withOnChunkLoad
134
- ? `${
135
- RuntimeGlobals.onChunksLoaded
136
- }.readFileVm = ${runtimeTemplate.returningFunction(
137
- 'installedChunks[chunkId] === 0',
138
- 'chunkId'
139
- )};`
140
- : '// no on chunks loaded',
141
- '',
142
- withLoading || withExternalInstallChunk
143
- ? `var installChunk = ${runtimeTemplate.basicFunction('chunk', [
144
- 'var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;',
145
- 'for(var moduleId in moreModules) {',
146
- Template.indent([
147
- `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
148
- Template.indent([
149
- `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];`,
150
- ]),
151
- '}',
152
- ]),
153
- '}',
154
- `if(runtime) runtime(__webpack_require__);`,
155
- 'for(var i = 0; i < chunkIds.length; i++) {',
156
- Template.indent([
157
- 'if(installedChunks[chunkIds[i]]) {',
158
- Template.indent(['installedChunks[chunkIds[i]][0]();']),
159
- '}',
160
- 'installedChunks[chunkIds[i]] = 0;',
161
- ]),
162
- '}',
163
- withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : '',
164
- ])};`
165
- : '// no chunk install function needed',
166
- '',
167
- withLoading
168
- ? Template.asString([
169
- '// ReadFile + VM.run chunk loading for javascript',
170
- `${fn}.readFileVm = function(chunkId, promises) {`,
171
- hasJsMatcher !== false
172
- ? Template.indent([
173
- '',
174
- 'var installedChunkData = installedChunks[chunkId];',
175
- 'if(installedChunkData !== 0) { // 0 means "already installed".',
176
- Template.indent([
177
- '// array of [resolve, reject, promise] means "currently loading"',
178
- 'if(installedChunkData) {',
179
- Template.indent(['promises.push(installedChunkData[2]);']),
180
- '} else {',
181
- Template.indent([
182
- hasJsMatcher === true
183
- ? 'if(true) { // all chunks have JS'
184
- : `if(${hasJsMatcher('chunkId')}) {`,
185
- Template.indent([
186
- '// load the chunk and return promise to it',
187
- 'var promise = new Promise(async function(resolve, reject) {',
188
- Template.indent([
189
- 'installedChunkData = installedChunks[chunkId] = [resolve, reject];',
190
- `var filename = require('path').join(__dirname, ${JSON.stringify(
191
- rootOutputDir
192
- )} + ${
193
- RuntimeGlobals.getChunkScriptFilename
194
- }(chunkId));`,
195
- "var fs = require('fs');",
196
- 'if(fs.existsSync(filename)) {',
197
- Template.indent([
198
- "fs.readFile(filename, 'utf-8', function(err, content) {",
199
- Template.indent([
200
- 'if(err) return reject(err);',
201
- 'var chunk = {};',
202
- "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" +
203
- "(chunk, require, require('path').dirname(filename), filename);",
204
- 'installChunk(chunk);',
205
- ]),
206
- '});',
207
- ]),
208
- '} else {',
209
- Template.indent([
210
- loadScript,
211
-
212
- `console.log('needs to load remote module from', ${JSON.stringify(
213
- name
214
- )});`,
215
- `console.log('remotes known to', ${JSON.stringify(
216
- name
217
- )}, ${JSON.stringify(remotes)})`,
218
- // keys are mostly useless here, we want to find remote by its global (unique name)
219
- `var remotes = ${JSON.stringify(
220
- Object.values(remotes).reduce((acc, remote) => {
221
- //TODO: need to handle all other cases like when remote is not a @ syntax string
222
- const [global, url] = remote.split('@');
223
- acc[global] = url;
224
- return acc;
225
- }, {})
226
- )};`,
227
- "Object.assign(global.__remote_scope__._config, remotes)",
228
- "const remoteRegistry = global.__remote_scope__._config",
229
- /* TODO: keying by global should be ok, but need to verify - need to deal with when user passes promise new promise()
230
- global will/should still exist - but can only be known at runtime */
231
- `console.log('remotes keyed by global name',remotes)`,
232
- `console.log('remote scope configs',global.__remote_scope__._config)`,
233
-
234
- `console.log('global.__remote_scope__',global.__remote_scope__)`,
235
- `console.log('global.__remote_scope__[${JSON.stringify(
236
- name
237
- )}]',global.__remote_scope__[${JSON.stringify(
238
- name
239
- )}])`,
240
-
241
- /* TODO: this global.REMOTE_CONFIG doesnt work in this v5 core, not sure if i need to keep it or not
242
- not deleting it yet since i might need this for tracking all the remote entries across systems
243
- for now, im going to use locally known remote scope from remoteEntry config
244
- update: We will most likely need this, since remote would not have its own config
245
- id need to access the host system and find the known url
246
- basically this is how i create publicPath: auto on servers.
247
- `var requestedRemote = global.REMOTE_CONFIG[${JSON.stringify(
248
- name
249
- )}]`,
250
- */
251
- "console.log('about to derive remote making request')",
252
- `var requestedRemote = remoteRegistry[${JSON.stringify(
253
- name
254
- )}]`,
255
- "console.log('requested remote', requestedRemote)",
256
- /*TODO: we need to support when user implements own promise new promise function
257
- for example i have my own promise remotes, not global@remotename
258
- so there could be cases where remote may be function still - not sure */
259
-
260
- /*TODO: need to handle if chunk fetch fails/crashes - ensure server still can keep loading
261
- right now if you throw an error in here, server will stall forever */
262
-
263
- `if(typeof requestedRemote === 'function'){
264
- requestedRemote = await requestedRemote()
265
- }`,
266
- `console.log('var requestedRemote',requestedRemote);`,
267
-
268
- // example: uncomment this and server will never reply
269
- // `var scriptUrl = new URL(requestedRemote.split("@")[1]);`,
270
- // since im looping over remote and creating global at build time, i dont need to split string at runtime
271
- // there may still be a use case for that with promise new promise, depending on how we design it.
272
- `var scriptUrl = new URL(requestedRemote);`,
273
-
274
- `var chunkName = ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`,
275
-
276
- `console.log('chunkname to request',chunkName);`,
277
- `var fileToReplace = require('path').basename(scriptUrl.pathname);`,
278
- `scriptUrl.pathname = scriptUrl.pathname.replace(fileToReplace, chunkName);`,
279
- `console.log('will load remote chunk', scriptUrl.toString());`,
280
- `loadScript(scriptUrl.toString(), function(err, content) {`,
281
- Template.indent([
282
- "console.log('load script callback fired')",
283
- "if(err) {console.error('error loading remote chunk', scriptUrl.toString(),'got',content); return reject(err);}",
284
- 'var chunk = {};',
285
- 'try {',
286
- "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" +
287
- "(chunk, require, require('path').dirname(filename), filename);",
288
- '} catch (e) {',
289
- "console.log('runInThisContext thew', e)",
290
- '}',
291
- 'installChunk(chunk);',
292
- ]),
293
- '});',
294
- ]),
295
- '}',
296
- ]),
297
- '});',
298
- 'promises.push(installedChunkData[2] = promise);',
299
- ]),
300
- '} else installedChunks[chunkId] = 0;',
301
- ]),
302
- '}',
303
- ]),
304
- '}',
305
- ])
306
- : Template.indent(['installedChunks[chunkId] = 0;']),
307
- '};',
308
- ])
309
- : '// no chunk loading',
310
- '',
311
- withExternalInstallChunk
312
- ? Template.asString([
313
- 'module.exports = __webpack_require__;',
314
- `${RuntimeGlobals.externalInstallChunk} = installChunk;`,
315
- ])
316
- : '// no external install chunk',
317
- '',
318
- withHmr
319
- ? Template.asString([
320
- 'function loadUpdateChunk(chunkId, updatedModulesList) {',
321
- Template.indent([
322
- 'return new Promise(function(resolve, reject) {',
323
- Template.indent([
324
- `var filename = require('path').join(__dirname, ${JSON.stringify(
325
- rootOutputDir
326
- )} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`,
327
- "require('fs').readFile(filename, 'utf-8', function(err, content) {",
328
- Template.indent([
329
- 'if(err) return reject(err);',
330
- 'var update = {};',
331
- "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" +
332
- "(update, require, require('path').dirname(filename), filename);",
333
- 'var updatedModules = update.modules;',
334
- 'var runtime = update.runtime;',
335
- 'for(var moduleId in updatedModules) {',
336
- Template.indent([
337
- `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`,
338
- Template.indent([
339
- `currentUpdate[moduleId] = updatedModules[moduleId];`,
340
- 'if(updatedModulesList) updatedModulesList.push(moduleId);',
341
- ]),
342
- '}',
343
- ]),
344
- '}',
345
- 'if(runtime) currentUpdateRuntime.push(runtime);',
346
- 'resolve();',
347
- ]),
348
- '});',
349
- ]),
350
- '});',
351
- ]),
352
- '}',
353
- '',
354
- Template.getFunctionContent(
355
- require('../hmr/JavascriptHotModuleReplacement.runtime.js')
356
- )
357
- .replace(/\$key\$/g, 'readFileVm')
358
- .replace(/\$installedChunks\$/g, 'installedChunks')
359
- .replace(/\$loadUpdateChunk\$/g, 'loadUpdateChunk')
360
- .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache)
361
- .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories)
362
- .replace(
363
- /\$ensureChunkHandlers\$/g,
364
- RuntimeGlobals.ensureChunkHandlers
365
- )
366
- .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty)
367
- .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData)
368
- .replace(
369
- /\$hmrDownloadUpdateHandlers\$/g,
370
- RuntimeGlobals.hmrDownloadUpdateHandlers
371
- )
372
- .replace(
373
- /\$hmrInvalidateModuleHandlers\$/g,
374
- RuntimeGlobals.hmrInvalidateModuleHandlers
375
- ),
376
- ])
377
- : '// no HMR',
378
- '',
379
- withHmrManifest
380
- ? Template.asString([
381
- `${RuntimeGlobals.hmrDownloadManifest} = function() {`,
382
- Template.indent([
383
- 'return new Promise(function(resolve, reject) {',
384
- Template.indent([
385
- `var filename = require('path').join(__dirname, ${JSON.stringify(
386
- rootOutputDir
387
- )} + ${RuntimeGlobals.getUpdateManifestFilename}());`,
388
- "require('fs').readFile(filename, 'utf-8', function(err, content) {",
389
- Template.indent([
390
- 'if(err) {',
391
- Template.indent([
392
- 'if(err.code === "ENOENT") return resolve();',
393
- 'return reject(err);',
394
- ]),
395
- '}',
396
- 'try { resolve(JSON.parse(content)); }',
397
- 'catch(e) { reject(e); }',
398
- ]),
399
- '});',
400
- ]),
401
- '});',
402
- ]),
403
- '}',
404
- ])
405
- : '// no HMR manifest',
406
- ]);
407
- }
408
- }
409
-
410
- module.exports = ReadFileChunkLoadingRuntimeModule;
@@ -1,147 +0,0 @@
1
- 'use strict';
2
-
3
- // possible remote evaluators
4
- // this depends on the chunk format selected.
5
- // commonjs2 - it think, is lazily evaluated - beware
6
- // const remote = eval(scriptContent + '\n try{' + moduleName + '}catch(e) { null; };');
7
- // commonjs - fine to use but exports marker doesnt exist
8
- // const remote = eval('let exports = {};' + scriptContent + 'exports');
9
- // commonjs-module, ideal since it returns a commonjs module format
10
- // const remote = eval(scriptContent + 'module.exports')
11
-
12
- // Note on ESM.
13
- // Its possible to use ESM import, but its impossible to invalidate the module cache
14
- // So once something is imported, its stuck. This is problematic with at-runtime since we want to hot reload node
15
- // if ESM were used, youd be forced to restart the process to re-import modules or use a worker pool
16
- // Workaround is possible with query string on end of request, but this leaks memory badly
17
- // with commonjs, we can at least reset the require cache to "reboot" webpack runtime
18
- // It *can* leak memory, but ive not been able to replicate this to an extent that would be concerning.
19
- // ESM WILL leak memory, big difference.
20
- // Im talking with TC39 about a proposal around "virtual module trees" which would solve many problems.
21
- // VMT is like Realms but better - easiest analogy would be like forking the main thread, without going off main thread
22
- // VMT allows for scope isolation, but still allows reflection and non-primitive memory pointers to be shared - perfect for MFP
23
-
24
- //TODO: should use extractUrlAndGlobal from internal.js
25
- //TODO: should use Template system like LoadFileChunk runtime does.
26
- //TODO: should use vm.runInThisContext instead of eval
27
- //TODO: global.webpackChunkLoad could use a better convention? I have to use a special http client to get out of my infra firewall
28
- const executeLoadTemplate = `
29
- function executeLoad(remoteUrl) {
30
- console.log('remoteUrl',remoteUrl)
31
- const scriptUrl = remoteUrl.split("@")[1];
32
- const moduleName = remoteUrl.split("@")[0];
33
- console.log("executing remote load", scriptUrl);
34
- return new Promise(function (resolve, reject) {
35
-
36
- (global.webpackChunkLoad || fetch)(scriptUrl).then(function(res){
37
- return res.text();
38
- }).then(function(scriptContent){
39
- try {
40
- const remote = eval(scriptContent + 'module.exports');
41
- /* TODO: need something like a chunk loading queue, this can lead to async issues
42
- if two containers load the same remote, they can overwrite global scope
43
- should check someone is already loading remote and await that */
44
- global.__remote_scope__[moduleName] = remote[moduleName] || remote
45
- resolve(global.__remote_scope__[moduleName])
46
- } catch(e) {
47
- console.error('problem executing remote module', moduleName);
48
- reject(e);
49
- }
50
- }).catch((e)=>{
51
- console.error('failed to fetch remote', moduleName, scriptUrl);
52
- console.error(e);
53
- reject(null)
54
- })
55
- }).catch((e)=>{
56
- console.error('error',e);
57
- console.warn(moduleName,'is offline, returning fake remote')
58
- return {
59
- fake: true,
60
- get:(arg)=>{
61
- console.log('faking', arg,'module on', moduleName);
62
-
63
- return ()=> Promise.resolve();
64
- },
65
- init:()=>{}
66
- }
67
- })
68
- }
69
- `;
70
-
71
- function buildRemotes(mfConf, webpack) {
72
- return Object.entries(mfConf.remotes || {}).reduce(
73
- (acc, [name, config]) => {
74
- // if its already been converted into promise, dont do it again
75
- if(config.startsWith('promise ') || config.startsWith('external ')){
76
- acc.buildTime[name] = config;
77
- return acc;
78
- }
79
- /*
80
- TODO: global remote scope object should go into webpack runtime as a runtime requirement
81
- this can be done by referencing my LoadFile, CommonJs plugins in this directory.
82
- */
83
- const [global, url] = config.split('@');
84
- const loadTemplate = `promise new Promise((resolve)=>{
85
- if(!global.__remote_scope__) {
86
- // create a global scope for container, similar to how remotes are set on window in the browser
87
- global.__remote_scope__ = {
88
- _config: {},
89
- }
90
- }
91
-
92
- global.__remote_scope__._config[${JSON.stringify(global)}] = ${JSON.stringify(url)};
93
-
94
- ${executeLoadTemplate}
95
- resolve(executeLoad(${JSON.stringify(config)}))
96
- }).then(remote=>{
97
- console.log(remote);
98
-
99
- return {
100
- get: remote.get,
101
- init: (args)=> {
102
- console.log(args)
103
- return remote.init(args)
104
- }
105
- }
106
- });
107
- `;
108
- acc.buildTime[name] = loadTemplate;
109
- return acc;
110
- },
111
- { runtime: {}, buildTime: {}, hot: {} }
112
- );
113
- }
114
-
115
- class StreamingFederation {
116
- constructor({ experiments, ...options }, context) {
117
- this.options = options || {};
118
- this.context = context || {};
119
- this.experiments = experiments || {};
120
- }
121
-
122
- apply(compiler) {
123
- // When used with Next.js, context is needed to use Next.js webpack
124
- const { webpack } = compiler;
125
-
126
- const { buildTime, runtime, hot } = buildRemotes(
127
- this.options,
128
- webpack || require('webpack')
129
- );
130
-
131
- // new ((webpack && webpack.DefinePlugin) || require("webpack").DefinePlugin)(
132
- // defs
133
- // ).apply(compiler);
134
-
135
- const pluginOptions = {
136
- ...this.options,
137
- remotes: buildTime,
138
- };
139
-
140
- new (this.context.ModuleFederationPlugin || (webpack && webpack.container.ModuleFederationPlugin) ||
141
- require('webpack/lib/container/ModuleFederationPlugin'))(
142
- pluginOptions
143
- ).apply(compiler);
144
- }
145
- }
146
-
147
- module.exports = StreamingFederation;