@module-federation/node 0.0.0-feat-node-support-1702930274547 → 0.0.0-next-20231219093413

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.
Files changed (99) hide show
  1. package/.babelrc +10 -0
  2. package/.eslintrc.json +47 -0
  3. package/CHANGELOG.md +1352 -0
  4. package/LICENSE +21 -0
  5. package/README.md +192 -0
  6. package/assets/banner.png +0 -0
  7. package/dist/jest.config.js +19 -0
  8. package/dist/jest.config.js.map +1 -0
  9. package/dist/package.json +62 -0
  10. package/dist/src/filesystem/stratagies.d.ts +11 -0
  11. package/{src → dist/src}/filesystem/stratagies.js +11 -31
  12. package/dist/src/filesystem/stratagies.js.map +1 -0
  13. package/{src → dist/src}/index.d.ts +2 -0
  14. package/{src → dist/src}/index.js +5 -1
  15. package/dist/src/index.js.map +1 -0
  16. package/dist/src/plugins/AutomaticPublicPathPlugin.js.map +1 -0
  17. package/dist/src/plugins/ChunkCorrelationPlugin.js +442 -0
  18. package/dist/src/plugins/ChunkCorrelationPlugin.js.map +1 -0
  19. package/dist/src/plugins/CommonJsChunkLoadingPlugin.js.map +1 -0
  20. package/{src → dist/src}/plugins/DynamicFilesystemChunkLoadingRuntimeModule.js +13 -0
  21. package/dist/src/plugins/DynamicFilesystemChunkLoadingRuntimeModule.js.map +1 -0
  22. package/dist/src/plugins/NodeContainerPlugin.d.ts +57 -0
  23. package/dist/src/plugins/NodeContainerPlugin.js +105 -0
  24. package/dist/src/plugins/NodeContainerPlugin.js.map +1 -0
  25. package/{src → dist/src}/plugins/NodeFederationPlugin.d.ts +20 -0
  26. package/dist/src/plugins/NodeFederationPlugin.js +127 -0
  27. package/dist/src/plugins/NodeFederationPlugin.js.map +1 -0
  28. package/dist/src/plugins/RemotePublicPathRuntimeModule.js.map +1 -0
  29. package/{src → dist/src}/plugins/StreamingTargetPlugin.js.map +1 -1
  30. package/{src → dist/src}/plugins/UniversalFederationPlugin.d.ts +0 -1
  31. package/{src → dist/src}/plugins/UniversalFederationPlugin.js +3 -3
  32. package/dist/src/plugins/UniversalFederationPlugin.js.map +1 -0
  33. package/{src → dist/src}/plugins/webpackChunkUtilities.js +5 -1
  34. package/dist/src/plugins/webpackChunkUtilities.js.map +1 -0
  35. package/dist/src/types/index.js.map +1 -0
  36. package/dist/src/utils/flush-chunks.js.map +1 -0
  37. package/dist/src/utils/hot-reload.js.map +1 -0
  38. package/dist/src/utils/index.js.map +1 -0
  39. package/global.d.ts +27 -0
  40. package/jest.config.js +14 -16
  41. package/package.json +17 -23
  42. package/project.json +58 -0
  43. package/src/filesystem/stratagies.ts +131 -0
  44. package/src/index.ts +7 -0
  45. package/src/plugins/AutomaticPublicPathPlugin.ts +48 -0
  46. package/src/plugins/ChunkCorrelationPlugin.js +474 -307
  47. package/src/plugins/CommonJsChunkLoadingPlugin.ts +168 -0
  48. package/src/plugins/DynamicFilesystemChunkLoadingRuntimeModule.ts +239 -0
  49. package/src/plugins/NodeContainerPlugin.ts +150 -0
  50. package/src/plugins/NodeFederationPlugin.ts +185 -0
  51. package/src/plugins/RemotePublicPathRuntimeModule.ts +137 -0
  52. package/src/plugins/StreamingTargetPlugin.md +88 -0
  53. package/src/plugins/StreamingTargetPlugin.ts +81 -0
  54. package/src/plugins/UniversalFederationPlugin.ts +81 -0
  55. package/src/plugins/webpackChunkUtilities.ts +383 -0
  56. package/src/types/index.ts +7 -0
  57. package/src/utils/flush-chunks.ts +182 -0
  58. package/src/utils/hot-reload.ts +169 -0
  59. package/src/utils/index.ts +2 -0
  60. package/tsconfig.json +28 -0
  61. package/tsconfig.lib.json +17 -0
  62. package/tsconfig.spec.json +9 -0
  63. package/jest.config.js.map +0 -1
  64. package/src/filesystem/stratagies.d.ts +0 -18
  65. package/src/filesystem/stratagies.js.map +0 -1
  66. package/src/index.js.map +0 -1
  67. package/src/plugins/AutomaticPublicPathPlugin.js.map +0 -1
  68. package/src/plugins/ChunkCorrelationPlugin.js.map +0 -1
  69. package/src/plugins/CommonJsChunkLoadingPlugin.js.map +0 -1
  70. package/src/plugins/DynamicFilesystemChunkLoadingRuntimeModule.js.map +0 -1
  71. package/src/plugins/NodeFederationPlugin.js +0 -76
  72. package/src/plugins/NodeFederationPlugin.js.map +0 -1
  73. package/src/plugins/RemotePublicPathRuntimeModule.js.map +0 -1
  74. package/src/plugins/UniversalFederationPlugin.js.map +0 -1
  75. package/src/plugins/webpackChunkUtilities.js.map +0 -1
  76. package/src/types/index.js.map +0 -1
  77. package/src/utils/flush-chunks.js.map +0 -1
  78. package/src/utils/hot-reload.js.map +0 -1
  79. package/src/utils/index.js.map +0 -1
  80. package/{jest.config.d.ts → dist/jest.config.d.ts} +0 -0
  81. package/{src → dist/src}/plugins/AutomaticPublicPathPlugin.d.ts +0 -0
  82. package/{src → dist/src}/plugins/AutomaticPublicPathPlugin.js +0 -0
  83. package/{src → dist/src}/plugins/ChunkCorrelationPlugin.d.ts +6 -6
  84. /package/{src → dist/src}/plugins/CommonJsChunkLoadingPlugin.d.ts +0 -0
  85. /package/{src → dist/src}/plugins/CommonJsChunkLoadingPlugin.js +0 -0
  86. /package/{src → dist/src}/plugins/DynamicFilesystemChunkLoadingRuntimeModule.d.ts +0 -0
  87. /package/{src → dist/src}/plugins/RemotePublicPathRuntimeModule.d.ts +0 -0
  88. /package/{src → dist/src}/plugins/RemotePublicPathRuntimeModule.js +0 -0
  89. /package/{src → dist/src}/plugins/StreamingTargetPlugin.d.ts +0 -0
  90. /package/{src → dist/src}/plugins/StreamingTargetPlugin.js +0 -0
  91. /package/{src → dist/src}/plugins/webpackChunkUtilities.d.ts +0 -0
  92. /package/{src → dist/src}/types/index.d.ts +0 -0
  93. /package/{src → dist/src}/types/index.js +0 -0
  94. /package/{src → dist/src}/utils/flush-chunks.d.ts +0 -0
  95. /package/{src → dist/src}/utils/flush-chunks.js +0 -0
  96. /package/{src → dist/src}/utils/hot-reload.d.ts +0 -0
  97. /package/{src → dist/src}/utils/hot-reload.js +0 -0
  98. /package/{src → dist/src}/utils/index.d.ts +0 -0
  99. /package/{src → dist/src}/utils/index.js +0 -0
@@ -0,0 +1,383 @@
1
+ import { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';
2
+ const { RuntimeGlobals, Template } = require(
3
+ normalizeWebpackPath('webpack'),
4
+ ) as typeof import('webpack');
5
+ import type { Chunk, ChunkGraph } from 'webpack';
6
+
7
+ /**
8
+ * Generates the hot module replacement (HMR) code.
9
+ * @param {boolean} withHmr - Flag indicating whether HMR is enabled.
10
+ * @param {string} rootOutputDir - The root output directory.
11
+ * @returns {string} - The generated HMR code.
12
+ */
13
+ export function generateHmrCode(
14
+ withHmr: boolean,
15
+ rootOutputDir: string,
16
+ ): string {
17
+ if (!withHmr) {
18
+ return '// no HMR';
19
+ }
20
+
21
+ return Template.asString([
22
+ // Function to load updated chunk
23
+ 'function loadUpdateChunk(chunkId, updatedModulesList) {',
24
+ Template.indent([
25
+ 'return new Promise(function(resolve, reject) {',
26
+ Template.indent([
27
+ // Construct filename for the updated chunk
28
+ `var filename = require('path').join(__dirname, ${JSON.stringify(
29
+ rootOutputDir,
30
+ )} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`,
31
+ // Read the updated chunk file
32
+ "require('fs').readFile(filename, 'utf-8', function(err, content) {",
33
+ Template.indent([
34
+ 'if(err) return reject(err);',
35
+ 'var update = {};',
36
+ // Execute the updated chunk in the current context
37
+ "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" +
38
+ "(update, require, require('path').dirname(filename), filename);",
39
+ 'var updatedModules = update.modules;',
40
+ 'var runtime = update.runtime;',
41
+ // Iterate over the updated modules
42
+ 'for(var moduleId in updatedModules) {',
43
+ Template.indent([
44
+ `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`,
45
+ Template.indent([
46
+ `currentUpdate[moduleId] = updatedModules[moduleId];`,
47
+ 'if(updatedModulesList) updatedModulesList.push(moduleId);',
48
+ ]),
49
+ '}',
50
+ ]),
51
+ '}',
52
+ 'if(runtime) currentUpdateRuntime.push(runtime);',
53
+ 'resolve();',
54
+ ]),
55
+ '});',
56
+ ]),
57
+ '});',
58
+ ]),
59
+ '}',
60
+ '',
61
+ // Replace placeholders in the HMR runtime code
62
+ Template.getFunctionContent(
63
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
64
+ require('webpack/lib/hmr/JavascriptHotModuleReplacement.runtime.js'),
65
+ )
66
+ .replace(/\$key\$/g, 'readFileVm')
67
+ .replace(/\$installedChunks\$/g, 'installedChunks')
68
+ .replace(/\$loadUpdateChunk\$/g, 'loadUpdateChunk')
69
+ .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache)
70
+ .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories)
71
+ .replace(/\$ensureChunkHandlers\$/g, RuntimeGlobals.ensureChunkHandlers)
72
+ .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty)
73
+ .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData)
74
+ .replace(
75
+ /\$hmrDownloadUpdateHandlers\$/g,
76
+ RuntimeGlobals.hmrDownloadUpdateHandlers,
77
+ )
78
+ .replace(
79
+ /\$hmrInvalidateModuleHandlers\$/g,
80
+ RuntimeGlobals.hmrInvalidateModuleHandlers,
81
+ ),
82
+ ]);
83
+ }
84
+ /**
85
+ * Retrieves the initial chunk IDs.
86
+ * @param {Chunk} chunk - The chunk object.
87
+ * @param {ChunkGraph} chunkGraph - The chunk graph object.
88
+ * @param {any} chunkHasJs - Function to check if a chunk has JavaScript.
89
+ * @returns {Set} - The set of initial chunk IDs.
90
+ */
91
+ export function getInitialChunkIds(
92
+ chunk: Chunk,
93
+ chunkGraph: ChunkGraph,
94
+ chunkHasJs: any,
95
+ ) {
96
+ const initialChunkIds = new Set(chunk.ids);
97
+ for (const c of chunk.getAllInitialChunks()) {
98
+ if (c === chunk || chunkHasJs(c, chunkGraph)) continue;
99
+ if (c.ids) {
100
+ for (const id of c.ids) initialChunkIds.add(id);
101
+ }
102
+ for (const c of chunk.getAllAsyncChunks()) {
103
+ if (c === chunk || chunkHasJs(c, chunkGraph)) continue;
104
+ if (c.ids) {
105
+ for (const id of c.ids) initialChunkIds.add(id);
106
+ }
107
+ }
108
+ }
109
+ return initialChunkIds;
110
+ }
111
+ /**
112
+ * Generates the loading code for chunks.
113
+ * @param {boolean} withLoading - Flag indicating whether chunk loading is enabled.
114
+ * @param {string} fn - The function name.
115
+ * @param {any} hasJsMatcher - Function to check if a chunk has JavaScript.
116
+ * @param {string} rootOutputDir - The root output directory.
117
+ * @param {Record<string, string>} remotes - The remotes object.
118
+ * @param {string | undefined} name - The name of the chunk.
119
+ * @returns {string} - The generated loading code.
120
+ */
121
+ export function generateLoadingCode(
122
+ withLoading: boolean,
123
+ fn: string,
124
+ hasJsMatcher: any,
125
+ rootOutputDir: string,
126
+ remotes: Record<string, string>,
127
+ name: string | undefined,
128
+ ): string {
129
+ if (!withLoading) {
130
+ return '// no chunk loading';
131
+ }
132
+
133
+ return Template.asString([
134
+ '// Dynamic filesystem chunk loading for javascript',
135
+ `${fn}.readFileVm = function(chunkId, promises) {`,
136
+ hasJsMatcher !== false
137
+ ? Template.indent([
138
+ 'var installedChunkData = installedChunks[chunkId];',
139
+ 'if(installedChunkData !== 0) { // 0 means "already installed".',
140
+ Template.indent([
141
+ '// array of [resolve, reject, promise] means "currently loading"',
142
+ 'if(installedChunkData) {',
143
+ Template.indent(['promises.push(installedChunkData[2]);']),
144
+ '} else {',
145
+ Template.indent([
146
+ hasJsMatcher === true
147
+ ? 'if(true) { // all chunks have JS'
148
+ : `if(${hasJsMatcher('chunkId')}) {`,
149
+ Template.indent([
150
+ '// load the chunk and return promise to it',
151
+ 'var promise = new Promise(async function(resolve, reject) {',
152
+ Template.indent([
153
+ 'installedChunkData = installedChunks[chunkId] = [resolve, reject];',
154
+ 'function installChunkCallback(error,chunk){',
155
+ Template.indent([
156
+ 'if(error) return reject(error);',
157
+ 'installChunk(chunk);',
158
+ ]),
159
+ '}',
160
+ 'var fs = typeof process !== "undefined" ? require(\'fs\') : false;',
161
+ `var filename = typeof process !== "undefined" ? require('path').join(__dirname, ${JSON.stringify(
162
+ rootOutputDir,
163
+ )} + ${
164
+ RuntimeGlobals.getChunkScriptFilename
165
+ }(chunkId)) : false;`,
166
+
167
+ 'if(fs && fs.existsSync(filename)) {',
168
+ Template.indent([
169
+ `loadChunkStrategy('filesystem', chunkId, ${JSON.stringify(
170
+ rootOutputDir,
171
+ )}, remotes, installChunkCallback);`,
172
+ ]),
173
+ '} else { ',
174
+ Template.indent([
175
+ `var remotes = ${JSON.stringify(
176
+ Object.values(remotes).reduce(
177
+ (acc, remote) => {
178
+ const [global, url] = remote.split('@');
179
+ acc[global] = url;
180
+ return acc;
181
+ },
182
+ {} as Record<string, string>,
183
+ ),
184
+ )};`,
185
+
186
+ `var requestedRemote = globalThis.__remote_scope__[${JSON.stringify(
187
+ name,
188
+ )}]`,
189
+
190
+ "if(typeof requestedRemote === 'function'){",
191
+ Template.indent(
192
+ 'requestedRemote = await requestedRemote()',
193
+ ),
194
+ '}',
195
+
196
+ `var chunkName = ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`,
197
+ "const loadingStrategy = typeof process !== 'undefined' ? 'http-vm' : 'http-eval';",
198
+
199
+ `loadChunkStrategy(loadingStrategy, chunkName,${JSON.stringify(
200
+ name,
201
+ )}, globalThis.__remote_scope__,installChunkCallback);`,
202
+ ]),
203
+ '}',
204
+ ]),
205
+ '});',
206
+ 'promises.push(installedChunkData[2] = promise);',
207
+ ]),
208
+ '} else installedChunks[chunkId] = 0;',
209
+ ]),
210
+ '}',
211
+ ]),
212
+ '}',
213
+ ])
214
+ : Template.indent(['installedChunks[chunkId] = 0;']),
215
+ '};',
216
+ ]);
217
+ }
218
+ /**
219
+ * Generates the HMR manifest code.
220
+ * @param {boolean} withHmrManifest - Flag indicating whether HMR manifest is enabled.
221
+ * @param {string} rootOutputDir - The root output directory.
222
+ * @returns {string} - The generated HMR manifest code.
223
+ */
224
+ export function generateHmrManifestCode(
225
+ withHmrManifest: boolean,
226
+ rootOutputDir: string,
227
+ ): string {
228
+ if (!withHmrManifest) {
229
+ return '// no HMR manifest';
230
+ }
231
+
232
+ return Template.asString([
233
+ `${RuntimeGlobals.hmrDownloadManifest} = function() {`,
234
+ Template.indent([
235
+ 'return new Promise(function(resolve, reject) {',
236
+ Template.indent([
237
+ `var filename = require('path').join(__dirname, ${JSON.stringify(
238
+ rootOutputDir,
239
+ )} + ${RuntimeGlobals.getUpdateManifestFilename}());`,
240
+ "require('fs').readFile(filename, 'utf-8', function(err, content) {",
241
+ Template.indent([
242
+ 'if(err) {',
243
+ Template.indent([
244
+ 'if(err.code === "ENOENT") return resolve();',
245
+ 'return reject(err);',
246
+ ]),
247
+ '}',
248
+ 'try { resolve(JSON.parse(content)); }',
249
+ 'catch(e) { reject(e); }',
250
+ ]),
251
+ '});',
252
+ ]),
253
+ '});',
254
+ ]),
255
+ '}',
256
+ ]);
257
+ }
258
+ /**
259
+ * Handles the on chunk load event.
260
+ * @param {boolean} withOnChunkLoad - Flag indicating whether on chunk load event is enabled.
261
+ * @param {any} runtimeTemplate - The runtime template.
262
+ * @returns {string} - The generated on chunk load event handler.
263
+ */
264
+ export function handleOnChunkLoad(
265
+ withOnChunkLoad: boolean,
266
+ runtimeTemplate: any,
267
+ ): string {
268
+ if (withOnChunkLoad) {
269
+ return `${
270
+ RuntimeGlobals.onChunksLoaded
271
+ }.readFileVm = ${runtimeTemplate.returningFunction(
272
+ 'installedChunks[chunkId] === 0',
273
+ 'chunkId',
274
+ )};`;
275
+ } else {
276
+ return '// no on chunks loaded';
277
+ }
278
+ }
279
+ /**
280
+ * Generates the load script for server-side execution. This function creates a script that loads a remote module
281
+ * and executes it in the current context. It supports both browser and Node.js environments.
282
+ * @param {any} runtimeTemplate - The runtime template used to generate the load script.
283
+ * @returns {string} - The generated load script.
284
+ */
285
+ export function generateLoadScript(runtimeTemplate: any): string {
286
+ return Template.asString([
287
+ '// load script equivalent for server side',
288
+ `${RuntimeGlobals.loadScript} = ${runtimeTemplate.basicFunction(
289
+ 'url,callback,chunkId',
290
+ [
291
+ Template.indent([
292
+ `async function executeLoad(url, callback, name) {
293
+ if (!name) {
294
+ throw new Error('__webpack_require__.l name is required for ' + url);
295
+ }
296
+ var remoteName = name;
297
+ if(name.includes('__remote_scope__')) {
298
+ remoteName = name.split('__remote_scope__.')[1]
299
+ }
300
+ if (typeof globalThis.__remote_scope__[remoteName] !== 'undefined') return callback(globalThis.__remote_scope__[remoteName]);
301
+ globalThis.__remote_scope__._config[remoteName] = url;
302
+ try {
303
+ const scriptContent = await (globalThis.webpackChunkLoad || globalThis.fetch || require("node-fetch"))(url).then(res => res.text());
304
+ let remote;
305
+ if (typeof process !== 'undefined') {
306
+ const vm = require('vm');
307
+ const m = require('module');
308
+ const remoteCapsule = vm.runInThisContext(m.wrap(scriptContent), 'node-federation-loader-' + name + '.vm')
309
+ const exp = {};
310
+ remote = {exports:{}};
311
+ remoteCapsule(exp,require,remote,'node-federation-loader-' + name + '.vm',__dirname);
312
+ remote = remote.exports || remote;
313
+ } else {
314
+ remote = eval('let module = {};' + scriptContent + '\\nmodule.exports')
315
+ }
316
+ globalThis.__remote_scope__[remoteName] = remote[remoteName] || remote;
317
+ globalThis.__remote_scope__._config[remoteName] = url;
318
+ callback(globalThis.__remote_scope__[remoteName])
319
+ } catch (e) {
320
+ e.target = {src: url};
321
+ globalThis.__remote_scope__[remoteName] = {
322
+ get: function() {
323
+ return function() {
324
+ return ()=>null
325
+ }
326
+ },
327
+ init: function() {},
328
+ fake: true
329
+ }
330
+ console.log(e);
331
+ callback(e);
332
+ }
333
+ }`,
334
+ `executeLoad(url,callback,chunkId)`,
335
+ ]),
336
+ ],
337
+ )}`,
338
+ ]);
339
+ }
340
+ export function generateInstallChunk(
341
+ runtimeTemplate: any,
342
+ withOnChunkLoad: boolean,
343
+ ): string {
344
+ return `var installChunk = ${runtimeTemplate.basicFunction('chunk', [
345
+ 'var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;',
346
+ 'for(var moduleId in moreModules) {',
347
+ Template.indent([
348
+ `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`,
349
+ Template.indent([
350
+ `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];`,
351
+ ]),
352
+ '}',
353
+ ]),
354
+ '}',
355
+ 'if(runtime) runtime(__webpack_require__);',
356
+ 'for(var i = 0; i < chunkIds.length; i++) {',
357
+ Template.indent([
358
+ 'if(installedChunks[chunkIds[i]]) {',
359
+ Template.indent(['installedChunks[chunkIds[i]][0]();']),
360
+ '}',
361
+ 'installedChunks[chunkIds[i]] = 0;',
362
+ ]),
363
+ '}',
364
+ withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : '',
365
+ ])};`;
366
+ }
367
+ export function generateExternalInstallChunkCode(
368
+ withExternalInstallChunk: boolean,
369
+ debug: boolean | undefined,
370
+ ): string {
371
+ if (!withExternalInstallChunk) {
372
+ return '// no external install chunk';
373
+ }
374
+
375
+ return Template.asString([
376
+ 'module.exports = __webpack_require__;',
377
+ `${RuntimeGlobals.externalInstallChunk} = function(){`,
378
+ debug
379
+ ? `console.debug('node: webpack installing to install chunk id:', arguments['0'].id);`
380
+ : '',
381
+ `return installChunk.apply(this, arguments)};`,
382
+ ]);
383
+ }
@@ -0,0 +1,7 @@
1
+ import type { container } from 'webpack';
2
+
3
+ export type ModuleFederationPluginOptions = ConstructorParameters<
4
+ typeof container.ModuleFederationPlugin
5
+ >['0'];
6
+
7
+ export type RemotesObject = ModuleFederationPluginOptions['remotes'];
@@ -0,0 +1,182 @@
1
+ /* eslint-disable no-undef */
2
+
3
+ // @ts-ignore
4
+ if (!globalThis.usedChunks) {
5
+ // @ts-ignore
6
+ globalThis.usedChunks = new Set();
7
+ }
8
+ /**
9
+ * Initialize usedChunks and share it globally.
10
+ * @type {Set}
11
+ */
12
+ // @ts-ignore
13
+ export const { usedChunks } = globalThis;
14
+ /**
15
+ * Load hostStats from the JSON file.
16
+ * @returns {object} hostStats - An object containing host stats data.
17
+ */
18
+ const loadHostStats = () => {
19
+ try {
20
+ return __non_webpack_require__('../federated-stats.json');
21
+ } catch (e) {
22
+ return {};
23
+ }
24
+ };
25
+
26
+ /**
27
+ * Create a shareMap based on the loaded modules.
28
+ * @returns {object} shareMap - An object containing the shareMap data.
29
+ */
30
+ const createShareMap = () => {
31
+ // Check if __webpack_share_scopes__ is defined and has a default property
32
+ // @ts-ignore
33
+ if (__webpack_share_scopes__?.default) {
34
+ // Reduce the keys of the default property to create the share map
35
+ // @ts-ignore
36
+ return Object.keys(__webpack_share_scopes__.default).reduce((acc, key) => {
37
+ // Get the loaded modules for the current key
38
+ // @ts-ignore
39
+ const loadedModules = Object.values(__webpack_share_scopes__.default[key])
40
+ // Filter out the modules that are not loaded
41
+ // @ts-ignore
42
+ .filter((sharedModule) => sharedModule.loaded)
43
+ // Map the filtered modules to their 'from' properties
44
+ // @ts-ignore
45
+ .map((sharedModule) => sharedModule.from);
46
+
47
+ // If there are any loaded modules, add them to the accumulator object
48
+ if (loadedModules.length > 0) {
49
+ // @ts-ignore
50
+ acc[key] = loadedModules;
51
+ }
52
+ // Return the accumulator object for the next iteration
53
+ return acc;
54
+ }, {});
55
+ }
56
+ // If __webpack_share_scopes__ is not defined or doesn't have a default property, return an empty object
57
+ return {};
58
+ };
59
+
60
+ /**
61
+ * Process a single chunk and return an array of updated chunks.
62
+ * @param {string} chunk - A chunk string containing remote and request data.
63
+ * @param {object} shareMap - An object containing the shareMap data.
64
+ * @param {object} hostStats - An object containing host stats data.
65
+ * @returns {Promise<Array>} A promise that resolves to an array of updated chunks.
66
+ */
67
+ // @ts-ignore
68
+ const processChunk = async (chunk, shareMap, hostStats) => {
69
+ // Create a set to store the chunks
70
+ const chunks = new Set();
71
+
72
+ // Split the chunk string into remote and request
73
+ const [remote, request] = chunk.split('->');
74
+
75
+ // If the remote is not defined in the global config, return
76
+ if (!globalThis.__remote_scope__._config[remote]) {
77
+ console.error(
78
+ `flush chunks:`,
79
+ `Remote ${remote} is not defined in the global config`,
80
+ );
81
+ return;
82
+ }
83
+
84
+ try {
85
+ // Extract the remote name from the URL
86
+ //@ts-ignore
87
+ const remoteName = new URL(
88
+ globalThis.__remote_scope__._config[remote],
89
+ ).pathname
90
+ .split('/')
91
+ .pop();
92
+
93
+ // Construct the stats file URL from the remote config
94
+ const statsFile = globalThis.__remote_scope__._config[remote]
95
+ .replace(remoteName, 'federated-stats.json')
96
+ .replace('ssr', 'chunks');
97
+
98
+ let stats = {};
99
+ try {
100
+ // Fetch the remote config and stats file
101
+ stats = await fetch(statsFile).then((res) => res.json());
102
+ } catch (e) {
103
+ console.error('flush error', e);
104
+ }
105
+
106
+ // Add the main chunk to the chunks set
107
+ //TODO: ensure host doesnt embed its own remote in ssr, this causes crash
108
+ // chunks.add(
109
+ // global.__remote_scope__._config[remote].replace('ssr', 'chunks')
110
+ // );
111
+
112
+ // Extract the prefix from the remote config
113
+ const [prefix] =
114
+ globalThis.__remote_scope__._config[remote].split('static/');
115
+
116
+ // Process federated modules from the stats object
117
+ // @ts-ignore
118
+ if (stats.federatedModules) {
119
+ // @ts-ignore
120
+ stats.federatedModules.forEach((modules) => {
121
+ // Process exposed modules
122
+ if (modules.exposes?.[request]) {
123
+ // @ts-ignore
124
+ modules.exposes[request].forEach((chunk) => {
125
+ chunks.add([prefix, chunk].join(''));
126
+
127
+ //TODO: reimplement this
128
+ Object.values(chunk).forEach((chunk) => {
129
+ // Add files to the chunks set
130
+ // @ts-ignore
131
+ if (chunk.files) {
132
+ // @ts-ignore
133
+ chunk.files.forEach((file) => {
134
+ chunks.add(prefix + file);
135
+ });
136
+ }
137
+ // Process required modules
138
+ // @ts-ignore
139
+ if (chunk.requiredModules) {
140
+ // @ts-ignore
141
+ chunk.requiredModules.forEach((module) => {
142
+ // Check if the module is in the shareMap
143
+ if (shareMap[module]) {
144
+ // If the module is from the host, log the host stats
145
+ }
146
+ });
147
+ }
148
+ });
149
+ });
150
+ }
151
+ });
152
+ }
153
+
154
+ // Return the array of chunks
155
+ return Array.from(chunks);
156
+ } catch (e) {
157
+ console.error('flush error:', e);
158
+ }
159
+ };
160
+
161
+ /**
162
+ * Flush the chunks and return a deduplicated array of chunks.
163
+ * @returns {Promise<Array>} A promise that resolves to an array of deduplicated chunks.
164
+ */
165
+ export const flushChunks = async () => {
166
+ const hostStats = loadHostStats();
167
+ const shareMap = createShareMap();
168
+
169
+ const allFlushed = await Promise.all(
170
+ Array.from(usedChunks).map(async (chunk) =>
171
+ processChunk(chunk, shareMap, hostStats),
172
+ ),
173
+ );
174
+
175
+ // Deduplicate the chunks array
176
+ const dedupe = Array.from(new Set([...allFlushed.flat()]));
177
+
178
+ // Clear usedChunks
179
+ usedChunks.clear();
180
+ // Filter out any undefined or null values
181
+ return dedupe.filter(Boolean);
182
+ };