@module-federation/sdk 0.0.0-perf-devtools-20260107043700 → 0.0.0-perf-website-code-usage-20260914033703

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 (125) hide show
  1. package/README.md +9 -3
  2. package/dist/_virtual/_rolldown/runtime.cjs +19 -0
  3. package/dist/_virtual/_rolldown/runtime.js +18 -0
  4. package/dist/constant.cjs +62 -0
  5. package/dist/constant.cjs.map +1 -0
  6. package/dist/constant.d.ts +46 -0
  7. package/dist/constant.js +48 -0
  8. package/dist/constant.js.map +1 -0
  9. package/dist/createModuleFederationConfig.cjs +9 -0
  10. package/dist/createModuleFederationConfig.cjs.map +1 -0
  11. package/dist/createModuleFederationConfig.d.ts +6 -0
  12. package/dist/createModuleFederationConfig.js +8 -0
  13. package/dist/createModuleFederationConfig.js.map +1 -0
  14. package/dist/dom.cjs +214 -0
  15. package/dist/dom.cjs.map +1 -0
  16. package/dist/dom.d.ts +33 -0
  17. package/dist/dom.js +210 -0
  18. package/dist/dom.js.map +1 -0
  19. package/dist/env.cjs +34 -0
  20. package/dist/env.cjs.map +1 -0
  21. package/dist/env.d.ts +12 -0
  22. package/dist/env.js +30 -0
  23. package/dist/env.js.map +1 -0
  24. package/dist/generateSnapshotFromManifest.cjs +123 -0
  25. package/dist/generateSnapshotFromManifest.cjs.map +1 -0
  26. package/dist/generateSnapshotFromManifest.d.ts +20 -0
  27. package/dist/generateSnapshotFromManifest.js +119 -0
  28. package/dist/generateSnapshotFromManifest.js.map +1 -0
  29. package/dist/index.cjs +103 -0
  30. package/dist/index.d.ts +21 -1
  31. package/dist/index.js +17 -0
  32. package/dist/logger.cjs +129 -0
  33. package/dist/logger.cjs.map +1 -0
  34. package/dist/logger.d.ts +34 -0
  35. package/dist/logger.js +125 -0
  36. package/dist/logger.js.map +1 -0
  37. package/dist/node.cjs +180 -0
  38. package/dist/node.cjs.map +1 -0
  39. package/dist/node.d.ts +15 -0
  40. package/dist/node.js +178 -0
  41. package/dist/node.js.map +1 -0
  42. package/dist/normalize-webpack-path.cjs +28 -0
  43. package/dist/normalize-webpack-path.cjs.map +1 -0
  44. package/dist/normalize-webpack-path.d.ts +10 -1
  45. package/dist/normalize-webpack-path.js +26 -0
  46. package/dist/normalize-webpack-path.js.map +1 -0
  47. package/dist/normalizeOptions.cjs +19 -0
  48. package/dist/normalizeOptions.cjs.map +1 -0
  49. package/dist/normalizeOptions.d.ts +5 -0
  50. package/dist/normalizeOptions.js +18 -0
  51. package/dist/normalizeOptions.js.map +1 -0
  52. package/dist/types/common.d.ts +14 -0
  53. package/dist/types/hooks.d.ts +21 -0
  54. package/dist/types/index.d.ts +11 -0
  55. package/dist/types/manifest.d.ts +34 -0
  56. package/dist/types/plugins/ConsumeSharedPlugin.cjs +13 -0
  57. package/dist/types/plugins/ConsumeSharedPlugin.cjs.map +1 -0
  58. package/dist/types/plugins/ConsumeSharedPlugin.d.ts +109 -0
  59. package/dist/types/plugins/ConsumeSharedPlugin.js +8 -0
  60. package/dist/types/plugins/ConsumeSharedPlugin.js.map +1 -0
  61. package/dist/types/plugins/ContainerPlugin.cjs +13 -0
  62. package/dist/types/plugins/ContainerPlugin.cjs.map +1 -0
  63. package/dist/types/plugins/ContainerPlugin.d.ts +38 -0
  64. package/dist/types/plugins/ContainerPlugin.js +8 -0
  65. package/dist/types/plugins/ContainerPlugin.js.map +1 -0
  66. package/dist/types/plugins/ContainerReferencePlugin.cjs +13 -0
  67. package/dist/types/plugins/ContainerReferencePlugin.cjs.map +1 -0
  68. package/dist/types/plugins/ContainerReferencePlugin.d.ts +24 -0
  69. package/dist/types/plugins/ContainerReferencePlugin.js +8 -0
  70. package/dist/types/plugins/ContainerReferencePlugin.js.map +1 -0
  71. package/dist/types/plugins/ModuleFederationPlugin.cjs +13 -0
  72. package/dist/types/plugins/ModuleFederationPlugin.cjs.map +1 -0
  73. package/dist/types/plugins/ModuleFederationPlugin.d.ts +470 -0
  74. package/dist/types/plugins/ModuleFederationPlugin.js +8 -0
  75. package/dist/types/plugins/ModuleFederationPlugin.js.map +1 -0
  76. package/dist/types/plugins/ProvideSharedPlugin.cjs +13 -0
  77. package/dist/types/plugins/ProvideSharedPlugin.cjs.map +1 -0
  78. package/dist/types/plugins/ProvideSharedPlugin.d.ts +97 -0
  79. package/dist/types/plugins/ProvideSharedPlugin.js +8 -0
  80. package/dist/types/plugins/ProvideSharedPlugin.js.map +1 -0
  81. package/dist/types/plugins/SharePlugin.cjs +13 -0
  82. package/dist/types/plugins/SharePlugin.cjs.map +1 -0
  83. package/dist/types/plugins/SharePlugin.d.ts +26 -0
  84. package/dist/types/plugins/SharePlugin.js +8 -0
  85. package/dist/types/plugins/SharePlugin.js.map +1 -0
  86. package/dist/types/plugins/index.d.ts +6 -0
  87. package/dist/types/snapshot.d.ts +78 -0
  88. package/dist/types/stats.d.ts +101 -0
  89. package/dist/utils.cjs +127 -0
  90. package/dist/utils.cjs.map +1 -0
  91. package/dist/{src/utils.d.ts → utils.d.ts} +15 -4
  92. package/dist/utils.js +116 -0
  93. package/dist/utils.js.map +1 -0
  94. package/package.json +21 -7
  95. package/dist/index.cjs.cjs +0 -1048
  96. package/dist/index.cjs.cjs.map +0 -1
  97. package/dist/index.cjs.d.ts +0 -1
  98. package/dist/index.esm.js +0 -994
  99. package/dist/index.esm.js.map +0 -1
  100. package/dist/normalize-webpack-path.cjs.cjs +0 -42
  101. package/dist/normalize-webpack-path.cjs.cjs.map +0 -1
  102. package/dist/normalize-webpack-path.cjs.d.ts +0 -1
  103. package/dist/normalize-webpack-path.esm.js +0 -39
  104. package/dist/normalize-webpack-path.esm.js.map +0 -1
  105. package/dist/src/constant.d.ts +0 -35
  106. package/dist/src/createModuleFederationConfig.d.ts +0 -2
  107. package/dist/src/dom.d.ts +0 -29
  108. package/dist/src/env.d.ts +0 -8
  109. package/dist/src/generateSnapshotFromManifest.d.ts +0 -15
  110. package/dist/src/index.d.ts +0 -11
  111. package/dist/src/logger.d.ts +0 -32
  112. package/dist/src/node.d.ts +0 -11
  113. package/dist/src/normalize-webpack-path.d.ts +0 -5
  114. package/dist/src/normalizeOptions.d.ts +0 -1
  115. package/dist/src/types/common.d.ts +0 -10
  116. package/dist/src/types/hooks.d.ts +0 -12
  117. package/dist/src/types/index.d.ts +0 -6
  118. package/dist/src/types/manifest.d.ts +0 -26
  119. package/dist/src/types/plugins/ContainerPlugin.d.ts +0 -164
  120. package/dist/src/types/plugins/ContainerReferencePlugin.d.ts +0 -52
  121. package/dist/src/types/plugins/ModuleFederationPlugin.d.ts +0 -409
  122. package/dist/src/types/plugins/SharePlugin.d.ts +0 -78
  123. package/dist/src/types/plugins/index.d.ts +0 -4
  124. package/dist/src/types/snapshot.d.ts +0 -70
  125. package/dist/src/types/stats.d.ts +0 -90
@@ -1,1048 +0,0 @@
1
- 'use strict';
2
-
3
- const FederationModuleManifest = 'federation-manifest.json';
4
- const MANIFEST_EXT = '.json';
5
- const BROWSER_LOG_KEY = 'FEDERATION_DEBUG';
6
- const NameTransformSymbol = {
7
- AT: '@',
8
- HYPHEN: '-',
9
- SLASH: '/',
10
- };
11
- const NameTransformMap = {
12
- [NameTransformSymbol.AT]: 'scope_',
13
- [NameTransformSymbol.HYPHEN]: '_',
14
- [NameTransformSymbol.SLASH]: '__',
15
- };
16
- const EncodedNameTransformMap = {
17
- [NameTransformMap[NameTransformSymbol.AT]]: NameTransformSymbol.AT,
18
- [NameTransformMap[NameTransformSymbol.HYPHEN]]: NameTransformSymbol.HYPHEN,
19
- [NameTransformMap[NameTransformSymbol.SLASH]]: NameTransformSymbol.SLASH,
20
- };
21
- const SEPARATOR = ':';
22
- const ManifestFileName = 'mf-manifest.json';
23
- const StatsFileName = 'mf-stats.json';
24
- const MFModuleType = {
25
- NPM: 'npm',
26
- APP: 'app',
27
- };
28
- const MODULE_DEVTOOL_IDENTIFIER = '__MF_DEVTOOLS_MODULE_INFO__';
29
- const ENCODE_NAME_PREFIX = 'ENCODE_NAME_PREFIX';
30
- const TEMP_DIR = '.federation';
31
- const MFPrefetchCommon = {
32
- identifier: 'MFDataPrefetch',
33
- globalKey: '__PREFETCH__',
34
- library: 'mf-data-prefetch',
35
- exportsKey: '__PREFETCH_EXPORTS__',
36
- fileName: 'bootstrap.js',
37
- };
38
-
39
- /*
40
- * This file was automatically generated.
41
- * DO NOT MODIFY BY HAND.
42
- * Run `yarn special-lint-fix` to update
43
- */
44
-
45
- var ContainerPlugin = /*#__PURE__*/Object.freeze({
46
- __proto__: null
47
- });
48
-
49
- /*
50
- * This file was automatically generated.
51
- * DO NOT MODIFY BY HAND.
52
- * Run `yarn special-lint-fix` to update
53
- */
54
-
55
- var ContainerReferencePlugin = /*#__PURE__*/Object.freeze({
56
- __proto__: null
57
- });
58
-
59
- var ModuleFederationPlugin = /*#__PURE__*/Object.freeze({
60
- __proto__: null
61
- });
62
-
63
- /*
64
- * This file was automatically generated.
65
- * DO NOT MODIFY BY HAND.
66
- * Run `yarn special-lint-fix` to update
67
- */
68
-
69
- var SharePlugin = /*#__PURE__*/Object.freeze({
70
- __proto__: null
71
- });
72
-
73
- function isBrowserEnv() {
74
- return (typeof window !== 'undefined' && typeof window.document !== 'undefined');
75
- }
76
- function isReactNativeEnv() {
77
- return (typeof navigator !== 'undefined' && navigator?.product === 'ReactNative');
78
- }
79
- function isBrowserDebug() {
80
- try {
81
- if (isBrowserEnv() && window.localStorage) {
82
- return Boolean(localStorage.getItem(BROWSER_LOG_KEY));
83
- }
84
- }
85
- catch (error) {
86
- return false;
87
- }
88
- return false;
89
- }
90
- function isDebugMode() {
91
- if (typeof process !== 'undefined' &&
92
- process.env &&
93
- process.env['FEDERATION_DEBUG']) {
94
- return Boolean(process.env['FEDERATION_DEBUG']);
95
- }
96
- if (typeof FEDERATION_DEBUG !== 'undefined' && Boolean(FEDERATION_DEBUG)) {
97
- return true;
98
- }
99
- return isBrowserDebug();
100
- }
101
- const getProcessEnv = function () {
102
- return typeof process !== 'undefined' && process.env ? process.env : {};
103
- };
104
-
105
- const LOG_CATEGORY = '[ Federation Runtime ]';
106
- // entry: name:version version : 1.0.0 | ^1.2.3
107
- // entry: name:entry entry: https://localhost:9000/federation-manifest.json
108
- const parseEntry = (str, devVerOrUrl, separator = SEPARATOR) => {
109
- const strSplit = str.split(separator);
110
- const devVersionOrUrl = getProcessEnv()['NODE_ENV'] === 'development' && devVerOrUrl;
111
- const defaultVersion = '*';
112
- const isEntry = (s) => s.startsWith('http') || s.includes(MANIFEST_EXT);
113
- // Check if the string starts with a type
114
- if (strSplit.length >= 2) {
115
- let [name, ...versionOrEntryArr] = strSplit;
116
- // @name@manifest-url.json
117
- if (str.startsWith(separator)) {
118
- name = strSplit.slice(0, 2).join(separator);
119
- versionOrEntryArr = [
120
- devVersionOrUrl || strSplit.slice(2).join(separator),
121
- ];
122
- }
123
- let versionOrEntry = devVersionOrUrl || versionOrEntryArr.join(separator);
124
- if (isEntry(versionOrEntry)) {
125
- return {
126
- name,
127
- entry: versionOrEntry,
128
- };
129
- }
130
- else {
131
- // Apply version rule
132
- // devVersionOrUrl => inputVersion => defaultVersion
133
- return {
134
- name,
135
- version: versionOrEntry || defaultVersion,
136
- };
137
- }
138
- }
139
- else if (strSplit.length === 1) {
140
- const [name] = strSplit;
141
- if (devVersionOrUrl && isEntry(devVersionOrUrl)) {
142
- return {
143
- name,
144
- entry: devVersionOrUrl,
145
- };
146
- }
147
- return {
148
- name,
149
- version: devVersionOrUrl || defaultVersion,
150
- };
151
- }
152
- else {
153
- throw `Invalid entry value: ${str}`;
154
- }
155
- };
156
- const composeKeyWithSeparator = function (...args) {
157
- if (!args.length) {
158
- return '';
159
- }
160
- return args.reduce((sum, cur) => {
161
- if (!cur) {
162
- return sum;
163
- }
164
- if (!sum) {
165
- return cur;
166
- }
167
- return `${sum}${SEPARATOR}${cur}`;
168
- }, '');
169
- };
170
- const encodeName = function (name, prefix = '', withExt = false) {
171
- try {
172
- const ext = withExt ? '.js' : '';
173
- return `${prefix}${name
174
- .replace(new RegExp(`${NameTransformSymbol.AT}`, 'g'), NameTransformMap[NameTransformSymbol.AT])
175
- .replace(new RegExp(`${NameTransformSymbol.HYPHEN}`, 'g'), NameTransformMap[NameTransformSymbol.HYPHEN])
176
- .replace(new RegExp(`${NameTransformSymbol.SLASH}`, 'g'), NameTransformMap[NameTransformSymbol.SLASH])}${ext}`;
177
- }
178
- catch (err) {
179
- throw err;
180
- }
181
- };
182
- const decodeName = function (name, prefix, withExt) {
183
- try {
184
- let decodedName = name;
185
- if (prefix) {
186
- if (!decodedName.startsWith(prefix)) {
187
- return decodedName;
188
- }
189
- decodedName = decodedName.replace(new RegExp(prefix, 'g'), '');
190
- }
191
- decodedName = decodedName
192
- .replace(new RegExp(`${NameTransformMap[NameTransformSymbol.AT]}`, 'g'), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.AT]])
193
- .replace(new RegExp(`${NameTransformMap[NameTransformSymbol.SLASH]}`, 'g'), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.SLASH]])
194
- .replace(new RegExp(`${NameTransformMap[NameTransformSymbol.HYPHEN]}`, 'g'), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.HYPHEN]]);
195
- if (withExt) {
196
- decodedName = decodedName.replace('.js', '');
197
- }
198
- return decodedName;
199
- }
200
- catch (err) {
201
- throw err;
202
- }
203
- };
204
- const generateExposeFilename = (exposeName, withExt) => {
205
- if (!exposeName) {
206
- return '';
207
- }
208
- let expose = exposeName;
209
- if (expose === '.') {
210
- expose = 'default_export';
211
- }
212
- if (expose.startsWith('./')) {
213
- expose = expose.replace('./', '');
214
- }
215
- return encodeName(expose, '__federation_expose_', withExt);
216
- };
217
- const generateShareFilename = (pkgName, withExt) => {
218
- if (!pkgName) {
219
- return '';
220
- }
221
- return encodeName(pkgName, '__federation_shared_', withExt);
222
- };
223
- const getResourceUrl = (module, sourceUrl) => {
224
- if ('getPublicPath' in module) {
225
- let publicPath;
226
- if (!module.getPublicPath.startsWith('function')) {
227
- publicPath = new Function(module.getPublicPath)();
228
- }
229
- else {
230
- publicPath = new Function('return ' + module.getPublicPath)()();
231
- }
232
- return `${publicPath}${sourceUrl}`;
233
- }
234
- else if ('publicPath' in module) {
235
- if (!isBrowserEnv() && !isReactNativeEnv() && 'ssrPublicPath' in module) {
236
- return `${module.ssrPublicPath}${sourceUrl}`;
237
- }
238
- return `${module.publicPath}${sourceUrl}`;
239
- }
240
- else {
241
- console.warn('Cannot get resource URL. If in debug mode, please ignore.', module, sourceUrl);
242
- return '';
243
- }
244
- };
245
- // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
246
- const assert = (condition, msg) => {
247
- if (!condition) {
248
- error(msg);
249
- }
250
- };
251
- const error = (msg) => {
252
- throw new Error(`${LOG_CATEGORY}: ${msg}`);
253
- };
254
- const warn = (msg) => {
255
- console.warn(`${LOG_CATEGORY}: ${msg}`);
256
- };
257
- function safeToString(info) {
258
- try {
259
- return JSON.stringify(info, null, 2);
260
- }
261
- catch (e) {
262
- return '';
263
- }
264
- }
265
- // RegExp for version string
266
- const VERSION_PATTERN_REGEXP = /^([\d^=v<>~]|[*xX]$)/;
267
- function isRequiredVersion(str) {
268
- return VERSION_PATTERN_REGEXP.test(str);
269
- }
270
-
271
- const simpleJoinRemoteEntry = (rPath, rName) => {
272
- if (!rPath) {
273
- return rName;
274
- }
275
- const transformPath = (str) => {
276
- if (str === '.') {
277
- return '';
278
- }
279
- if (str.startsWith('./')) {
280
- return str.replace('./', '');
281
- }
282
- if (str.startsWith('/')) {
283
- const strWithoutSlash = str.slice(1);
284
- if (strWithoutSlash.endsWith('/')) {
285
- return strWithoutSlash.slice(0, -1);
286
- }
287
- return strWithoutSlash;
288
- }
289
- return str;
290
- };
291
- const transformedPath = transformPath(rPath);
292
- if (!transformedPath) {
293
- return rName;
294
- }
295
- if (transformedPath.endsWith('/')) {
296
- return `${transformedPath}${rName}`;
297
- }
298
- return `${transformedPath}/${rName}`;
299
- };
300
- function inferAutoPublicPath(url) {
301
- return url
302
- .replace(/#.*$/, '')
303
- .replace(/\?.*$/, '')
304
- .replace(/\/[^\/]+$/, '/');
305
- }
306
- // Priority: overrides > remotes
307
- // eslint-disable-next-line max-lines-per-function
308
- function generateSnapshotFromManifest(manifest, options = {}) {
309
- const { remotes = {}, overrides = {}, version } = options;
310
- let remoteSnapshot;
311
- const getPublicPath = () => {
312
- if ('publicPath' in manifest.metaData) {
313
- if (manifest.metaData.publicPath === 'auto' && version) {
314
- // use same implementation as publicPath auto runtime module implements
315
- return inferAutoPublicPath(version);
316
- }
317
- return manifest.metaData.publicPath;
318
- }
319
- else {
320
- return manifest.metaData.getPublicPath;
321
- }
322
- };
323
- const overridesKeys = Object.keys(overrides);
324
- let remotesInfo = {};
325
- // If remotes are not provided, only the remotes in the manifest will be read
326
- if (!Object.keys(remotes).length) {
327
- remotesInfo =
328
- manifest.remotes?.reduce((res, next) => {
329
- let matchedVersion;
330
- const name = next.federationContainerName;
331
- // overrides have higher priority
332
- if (overridesKeys.includes(name)) {
333
- matchedVersion = overrides[name];
334
- }
335
- else {
336
- if ('version' in next) {
337
- matchedVersion = next.version;
338
- }
339
- else {
340
- matchedVersion = next.entry;
341
- }
342
- }
343
- res[name] = {
344
- matchedVersion,
345
- };
346
- return res;
347
- }, {}) || {};
348
- }
349
- // If remotes (deploy scenario) are specified, they need to be traversed again
350
- Object.keys(remotes).forEach((key) => (remotesInfo[key] = {
351
- // overrides will override dependencies
352
- matchedVersion: overridesKeys.includes(key)
353
- ? overrides[key]
354
- : remotes[key],
355
- }));
356
- const { remoteEntry: { path: remoteEntryPath, name: remoteEntryName, type: remoteEntryType, }, types: remoteTypes = { path: '', name: '', zip: '', api: '' }, buildInfo: { buildVersion }, globalName, ssrRemoteEntry, } = manifest.metaData;
357
- const { exposes } = manifest;
358
- let basicRemoteSnapshot = {
359
- version: version ? version : '',
360
- buildVersion,
361
- globalName,
362
- remoteEntry: simpleJoinRemoteEntry(remoteEntryPath, remoteEntryName),
363
- remoteEntryType,
364
- remoteTypes: simpleJoinRemoteEntry(remoteTypes.path, remoteTypes.name),
365
- remoteTypesZip: remoteTypes.zip || '',
366
- remoteTypesAPI: remoteTypes.api || '',
367
- remotesInfo,
368
- shared: manifest?.shared.map((item) => ({
369
- assets: item.assets,
370
- sharedName: item.name,
371
- version: item.version,
372
- })),
373
- modules: exposes?.map((expose) => ({
374
- moduleName: expose.name,
375
- modulePath: expose.path,
376
- assets: expose.assets,
377
- })),
378
- };
379
- if (manifest.metaData?.prefetchInterface) {
380
- const prefetchInterface = manifest.metaData.prefetchInterface;
381
- basicRemoteSnapshot = {
382
- ...basicRemoteSnapshot,
383
- prefetchInterface,
384
- };
385
- }
386
- if (manifest.metaData?.prefetchEntry) {
387
- const { path, name, type } = manifest.metaData.prefetchEntry;
388
- basicRemoteSnapshot = {
389
- ...basicRemoteSnapshot,
390
- prefetchEntry: simpleJoinRemoteEntry(path, name),
391
- prefetchEntryType: type,
392
- };
393
- }
394
- if ('publicPath' in manifest.metaData) {
395
- remoteSnapshot = {
396
- ...basicRemoteSnapshot,
397
- publicPath: getPublicPath(),
398
- ssrPublicPath: manifest.metaData.ssrPublicPath,
399
- };
400
- }
401
- else {
402
- remoteSnapshot = {
403
- ...basicRemoteSnapshot,
404
- getPublicPath: getPublicPath(),
405
- };
406
- }
407
- if (ssrRemoteEntry) {
408
- const fullSSRRemoteEntry = simpleJoinRemoteEntry(ssrRemoteEntry.path, ssrRemoteEntry.name);
409
- remoteSnapshot.ssrRemoteEntry = fullSSRRemoteEntry;
410
- remoteSnapshot.ssrRemoteEntryType =
411
- ssrRemoteEntry.type || 'commonjs-module';
412
- }
413
- return remoteSnapshot;
414
- }
415
- function isManifestProvider(moduleInfo) {
416
- if ('remoteEntry' in moduleInfo &&
417
- moduleInfo.remoteEntry.includes(MANIFEST_EXT)) {
418
- return true;
419
- }
420
- else {
421
- return false;
422
- }
423
- }
424
- function getManifestFileName(manifestOptions) {
425
- if (!manifestOptions) {
426
- return {
427
- statsFileName: StatsFileName,
428
- manifestFileName: ManifestFileName,
429
- };
430
- }
431
- let filePath = typeof manifestOptions === 'boolean' ? '' : manifestOptions.filePath || '';
432
- let fileName = typeof manifestOptions === 'boolean' ? '' : manifestOptions.fileName || '';
433
- const JSON_EXT = '.json';
434
- const addExt = (name) => {
435
- if (name.endsWith(JSON_EXT)) {
436
- return name;
437
- }
438
- return `${name}${JSON_EXT}`;
439
- };
440
- const insertSuffix = (name, suffix) => {
441
- return name.replace(JSON_EXT, `${suffix}${JSON_EXT}`);
442
- };
443
- const manifestFileName = fileName ? addExt(fileName) : ManifestFileName;
444
- const statsFileName = fileName
445
- ? insertSuffix(manifestFileName, '-stats')
446
- : StatsFileName;
447
- return {
448
- statsFileName: simpleJoinRemoteEntry(filePath, statsFileName),
449
- manifestFileName: simpleJoinRemoteEntry(filePath, manifestFileName),
450
- };
451
- }
452
-
453
- const PREFIX = '[ Module Federation ]';
454
- const DEFAULT_DELEGATE = console;
455
- const LOGGER_STACK_SKIP_TOKENS = [
456
- 'logger.ts',
457
- 'logger.js',
458
- 'captureStackTrace',
459
- 'Logger.emit',
460
- 'Logger.log',
461
- 'Logger.info',
462
- 'Logger.warn',
463
- 'Logger.error',
464
- 'Logger.debug',
465
- ];
466
- function captureStackTrace() {
467
- try {
468
- const stack = new Error().stack;
469
- if (!stack) {
470
- return undefined;
471
- }
472
- const [, ...rawLines] = stack.split('\n');
473
- const filtered = rawLines.filter((line) => !LOGGER_STACK_SKIP_TOKENS.some((token) => line.includes(token)));
474
- if (!filtered.length) {
475
- return undefined;
476
- }
477
- const stackPreview = filtered.slice(0, 5).join('\n');
478
- return `Stack trace:\n${stackPreview}`;
479
- }
480
- catch {
481
- return undefined;
482
- }
483
- }
484
- class Logger {
485
- constructor(prefix, delegate = DEFAULT_DELEGATE) {
486
- this.prefix = prefix;
487
- this.delegate = delegate ?? DEFAULT_DELEGATE;
488
- }
489
- setPrefix(prefix) {
490
- this.prefix = prefix;
491
- }
492
- setDelegate(delegate) {
493
- this.delegate = delegate ?? DEFAULT_DELEGATE;
494
- }
495
- emit(method, args) {
496
- const delegate = this.delegate;
497
- const debugMode = isDebugMode();
498
- const stackTrace = debugMode ? captureStackTrace() : undefined;
499
- const enrichedArgs = stackTrace ? [...args, stackTrace] : args;
500
- const order = (() => {
501
- switch (method) {
502
- case 'log':
503
- return ['log', 'info'];
504
- case 'info':
505
- return ['info', 'log'];
506
- case 'warn':
507
- return ['warn', 'info', 'log'];
508
- case 'error':
509
- return ['error', 'warn', 'log'];
510
- case 'debug':
511
- default:
512
- return ['debug', 'log'];
513
- }
514
- })();
515
- for (const candidate of order) {
516
- const handler = delegate[candidate];
517
- if (typeof handler === 'function') {
518
- handler.call(delegate, this.prefix, ...enrichedArgs);
519
- return;
520
- }
521
- }
522
- for (const candidate of order) {
523
- const handler = DEFAULT_DELEGATE[candidate];
524
- if (typeof handler === 'function') {
525
- handler.call(DEFAULT_DELEGATE, this.prefix, ...enrichedArgs);
526
- return;
527
- }
528
- }
529
- }
530
- log(...args) {
531
- this.emit('log', args);
532
- }
533
- warn(...args) {
534
- this.emit('warn', args);
535
- }
536
- error(...args) {
537
- this.emit('error', args);
538
- }
539
- success(...args) {
540
- this.emit('info', args);
541
- }
542
- info(...args) {
543
- this.emit('info', args);
544
- }
545
- ready(...args) {
546
- this.emit('info', args);
547
- }
548
- debug(...args) {
549
- if (isDebugMode()) {
550
- this.emit('debug', args);
551
- }
552
- }
553
- }
554
- function createLogger(prefix) {
555
- return new Logger(prefix);
556
- }
557
- function createInfrastructureLogger(prefix) {
558
- const infrastructureLogger = new Logger(prefix);
559
- Object.defineProperty(infrastructureLogger, '__mf_infrastructure_logger__', {
560
- value: true,
561
- enumerable: false,
562
- configurable: false,
563
- });
564
- return infrastructureLogger;
565
- }
566
- function bindLoggerToCompiler(loggerInstance, compiler, name) {
567
- if (!loggerInstance
568
- .__mf_infrastructure_logger__) {
569
- return;
570
- }
571
- if (!compiler?.getInfrastructureLogger) {
572
- return;
573
- }
574
- try {
575
- const infrastructureLogger = compiler.getInfrastructureLogger(name);
576
- if (infrastructureLogger &&
577
- typeof infrastructureLogger === 'object' &&
578
- (typeof infrastructureLogger.log === 'function' ||
579
- typeof infrastructureLogger.info === 'function' ||
580
- typeof infrastructureLogger.warn === 'function' ||
581
- typeof infrastructureLogger.error === 'function')) {
582
- loggerInstance.setDelegate(infrastructureLogger);
583
- }
584
- }
585
- catch {
586
- // If the bundler throws (older versions), fall back to default console logger.
587
- loggerInstance.setDelegate(undefined);
588
- }
589
- }
590
- const logger = createLogger(PREFIX);
591
- const infrastructureLogger = createInfrastructureLogger(PREFIX);
592
-
593
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
594
- async function safeWrapper(callback, disableWarn) {
595
- try {
596
- const res = await callback();
597
- return res;
598
- }
599
- catch (e) {
600
- !disableWarn && warn(e);
601
- return;
602
- }
603
- }
604
- function isStaticResourcesEqual(url1, url2) {
605
- const REG_EXP = /^(https?:)?\/\//i;
606
- // Transform url1 and url2 into relative paths
607
- const relativeUrl1 = url1.replace(REG_EXP, '').replace(/\/$/, '');
608
- const relativeUrl2 = url2.replace(REG_EXP, '').replace(/\/$/, '');
609
- // Check if the relative paths are identical
610
- return relativeUrl1 === relativeUrl2;
611
- }
612
- function createScript(info) {
613
- // Retrieve the existing script element by its src attribute
614
- let script = null;
615
- let needAttach = true;
616
- let timeout = 20000;
617
- let timeoutId;
618
- const scripts = document.getElementsByTagName('script');
619
- for (let i = 0; i < scripts.length; i++) {
620
- const s = scripts[i];
621
- const scriptSrc = s.getAttribute('src');
622
- if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {
623
- script = s;
624
- needAttach = false;
625
- break;
626
- }
627
- }
628
- if (!script) {
629
- const attrs = info.attrs;
630
- script = document.createElement('script');
631
- script.type = attrs?.['type'] === 'module' ? 'module' : 'text/javascript';
632
- let createScriptRes = undefined;
633
- if (info.createScriptHook) {
634
- createScriptRes = info.createScriptHook(info.url, info.attrs);
635
- if (createScriptRes instanceof HTMLScriptElement) {
636
- script = createScriptRes;
637
- }
638
- else if (typeof createScriptRes === 'object') {
639
- if ('script' in createScriptRes && createScriptRes.script) {
640
- script = createScriptRes.script;
641
- }
642
- if ('timeout' in createScriptRes && createScriptRes.timeout) {
643
- timeout = createScriptRes.timeout;
644
- }
645
- }
646
- }
647
- if (!script.src) {
648
- script.src = info.url;
649
- }
650
- if (attrs && !createScriptRes) {
651
- Object.keys(attrs).forEach((name) => {
652
- if (script) {
653
- if (name === 'async' || name === 'defer') {
654
- script[name] = attrs[name];
655
- // Attributes that do not exist are considered overridden
656
- }
657
- else if (!script.getAttribute(name)) {
658
- script.setAttribute(name, attrs[name]);
659
- }
660
- }
661
- });
662
- }
663
- }
664
- const onScriptComplete = async (prev,
665
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
666
- event) => {
667
- clearTimeout(timeoutId);
668
- const onScriptCompleteCallback = () => {
669
- if (event?.type === 'error') {
670
- info?.onErrorCallback && info?.onErrorCallback(event);
671
- }
672
- else {
673
- info?.cb && info?.cb();
674
- }
675
- };
676
- // Prevent memory leaks in IE.
677
- if (script) {
678
- script.onerror = null;
679
- script.onload = null;
680
- safeWrapper(() => {
681
- const { needDeleteScript = true } = info;
682
- if (needDeleteScript) {
683
- script?.parentNode && script.parentNode.removeChild(script);
684
- }
685
- });
686
- if (prev && typeof prev === 'function') {
687
- const result = prev(event);
688
- if (result instanceof Promise) {
689
- const res = await result;
690
- onScriptCompleteCallback();
691
- return res;
692
- }
693
- onScriptCompleteCallback();
694
- return result;
695
- }
696
- }
697
- onScriptCompleteCallback();
698
- };
699
- script.onerror = onScriptComplete.bind(null, script.onerror);
700
- script.onload = onScriptComplete.bind(null, script.onload);
701
- timeoutId = setTimeout(() => {
702
- onScriptComplete(null, new Error(`Remote script "${info.url}" time-outed.`));
703
- }, timeout);
704
- return { script, needAttach };
705
- }
706
- function createLink(info) {
707
- // <link rel="preload" href="script.js" as="script">
708
- // Retrieve the existing script element by its src attribute
709
- let link = null;
710
- let needAttach = true;
711
- const links = document.getElementsByTagName('link');
712
- for (let i = 0; i < links.length; i++) {
713
- const l = links[i];
714
- const linkHref = l.getAttribute('href');
715
- const linkRel = l.getAttribute('rel');
716
- if (linkHref &&
717
- isStaticResourcesEqual(linkHref, info.url) &&
718
- linkRel === info.attrs['rel']) {
719
- link = l;
720
- needAttach = false;
721
- break;
722
- }
723
- }
724
- if (!link) {
725
- link = document.createElement('link');
726
- link.setAttribute('href', info.url);
727
- let createLinkRes = undefined;
728
- const attrs = info.attrs;
729
- if (info.createLinkHook) {
730
- createLinkRes = info.createLinkHook(info.url, attrs);
731
- if (createLinkRes instanceof HTMLLinkElement) {
732
- link = createLinkRes;
733
- }
734
- }
735
- if (attrs && !createLinkRes) {
736
- Object.keys(attrs).forEach((name) => {
737
- if (link && !link.getAttribute(name)) {
738
- link.setAttribute(name, attrs[name]);
739
- }
740
- });
741
- }
742
- }
743
- const onLinkComplete = (prev,
744
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
745
- event) => {
746
- const onLinkCompleteCallback = () => {
747
- if (event?.type === 'error') {
748
- info?.onErrorCallback && info?.onErrorCallback(event);
749
- }
750
- else {
751
- info?.cb && info?.cb();
752
- }
753
- };
754
- // Prevent memory leaks in IE.
755
- if (link) {
756
- link.onerror = null;
757
- link.onload = null;
758
- safeWrapper(() => {
759
- const { needDeleteLink = true } = info;
760
- if (needDeleteLink) {
761
- link?.parentNode && link.parentNode.removeChild(link);
762
- }
763
- });
764
- if (prev) {
765
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
766
- const res = prev(event);
767
- onLinkCompleteCallback();
768
- return res;
769
- }
770
- }
771
- onLinkCompleteCallback();
772
- };
773
- link.onerror = onLinkComplete.bind(null, link.onerror);
774
- link.onload = onLinkComplete.bind(null, link.onload);
775
- return { link, needAttach };
776
- }
777
- function loadScript(url, info) {
778
- const { attrs = {}, createScriptHook } = info;
779
- return new Promise((resolve, reject) => {
780
- const { script, needAttach } = createScript({
781
- url,
782
- cb: resolve,
783
- onErrorCallback: reject,
784
- attrs: {
785
- fetchpriority: 'high',
786
- ...attrs,
787
- },
788
- createScriptHook,
789
- needDeleteScript: true,
790
- });
791
- needAttach && document.head.appendChild(script);
792
- });
793
- }
794
-
795
- const sdkImportCache = new Map();
796
- function importNodeModule(name) {
797
- if (!name) {
798
- throw new Error('import specifier is required');
799
- }
800
- // Check cache to prevent infinite recursion
801
- if (sdkImportCache.has(name)) {
802
- return sdkImportCache.get(name);
803
- }
804
- const importModule = new Function('name', `return import(name)`);
805
- const promise = importModule(name)
806
- .then((res) => res)
807
- .catch((error) => {
808
- console.error(`Error importing module ${name}:`, error);
809
- // Remove from cache on error so it can be retried
810
- sdkImportCache.delete(name);
811
- throw error;
812
- });
813
- // Cache the promise to prevent recursive calls
814
- sdkImportCache.set(name, promise);
815
- return promise;
816
- }
817
- const loadNodeFetch = async () => {
818
- const fetchModule = await importNodeModule('node-fetch');
819
- return (fetchModule.default || fetchModule);
820
- };
821
- const lazyLoaderHookFetch = async (input, init, loaderHook) => {
822
- const hook = (url, init) => {
823
- return loaderHook.lifecycle.fetch.emit(url, init);
824
- };
825
- const res = await hook(input, init || {});
826
- if (!res || !(res instanceof Response)) {
827
- const fetchFunction = typeof fetch === 'undefined' ? await loadNodeFetch() : fetch;
828
- return fetchFunction(input, init || {});
829
- }
830
- return res;
831
- };
832
- const createScriptNode = typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'
833
- ? (url, cb, attrs, loaderHook) => {
834
- if (loaderHook?.createScriptHook) {
835
- const hookResult = loaderHook.createScriptHook(url);
836
- if (hookResult &&
837
- typeof hookResult === 'object' &&
838
- 'url' in hookResult) {
839
- url = hookResult.url;
840
- }
841
- }
842
- let urlObj;
843
- try {
844
- urlObj = new URL(url);
845
- }
846
- catch (e) {
847
- console.error('Error constructing URL:', e);
848
- cb(new Error(`Invalid URL: ${e}`));
849
- return;
850
- }
851
- const getFetch = async () => {
852
- if (loaderHook?.fetch) {
853
- return (input, init) => lazyLoaderHookFetch(input, init, loaderHook);
854
- }
855
- return typeof fetch === 'undefined' ? loadNodeFetch() : fetch;
856
- };
857
- const handleScriptFetch = async (f, urlObj) => {
858
- try {
859
- const res = await f(urlObj.href);
860
- const data = await res.text();
861
- const [path, vm] = await Promise.all([
862
- importNodeModule('path'),
863
- importNodeModule('vm'),
864
- ]);
865
- const scriptContext = { exports: {}, module: { exports: {} } };
866
- const urlDirname = urlObj.pathname
867
- .split('/')
868
- .slice(0, -1)
869
- .join('/');
870
- const filename = path.basename(urlObj.pathname);
871
- const script = new vm.Script(`(function(exports, module, require, __dirname, __filename) {${data}\n})`, {
872
- filename,
873
- importModuleDynamically:
874
- //@ts-ignore
875
- vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ??
876
- importNodeModule,
877
- });
878
- script.runInThisContext()(scriptContext.exports, scriptContext.module, eval('require'), urlDirname, filename);
879
- const exportedInterface = scriptContext.module.exports || scriptContext.exports;
880
- if (attrs && exportedInterface && attrs['globalName']) {
881
- const container = exportedInterface[attrs['globalName']] || exportedInterface;
882
- cb(undefined, container);
883
- return;
884
- }
885
- cb(undefined, exportedInterface);
886
- }
887
- catch (e) {
888
- cb(e instanceof Error
889
- ? e
890
- : new Error(`Script execution error: ${e}`));
891
- }
892
- };
893
- getFetch()
894
- .then(async (f) => {
895
- if (attrs?.['type'] === 'esm' || attrs?.['type'] === 'module') {
896
- return loadModule(urlObj.href, {
897
- fetch: f,
898
- vm: await importNodeModule('vm'),
899
- })
900
- .then(async (module) => {
901
- await module.evaluate();
902
- cb(undefined, module.namespace);
903
- })
904
- .catch((e) => {
905
- cb(e instanceof Error
906
- ? e
907
- : new Error(`Script execution error: ${e}`));
908
- });
909
- }
910
- handleScriptFetch(f, urlObj);
911
- })
912
- .catch((err) => {
913
- cb(err);
914
- });
915
- }
916
- : (url, cb, attrs, loaderHook) => {
917
- cb(new Error('createScriptNode is disabled in non-Node.js environment'));
918
- };
919
- const loadScriptNode = typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'
920
- ? (url, info) => {
921
- return new Promise((resolve, reject) => {
922
- createScriptNode(url, (error, scriptContext) => {
923
- if (error) {
924
- reject(error);
925
- }
926
- else {
927
- const remoteEntryKey = info?.attrs?.['globalName'] ||
928
- `__FEDERATION_${info?.attrs?.['name']}:custom__`;
929
- const entryExports = (globalThis[remoteEntryKey] =
930
- scriptContext);
931
- resolve(entryExports);
932
- }
933
- }, info.attrs, info.loaderHook);
934
- });
935
- }
936
- : (url, info) => {
937
- throw new Error('loadScriptNode is disabled in non-Node.js environment');
938
- };
939
- const esmModuleCache = new Map();
940
- async function loadModule(url, options) {
941
- // Check cache to prevent infinite recursion in ESM loading
942
- if (esmModuleCache.has(url)) {
943
- return esmModuleCache.get(url);
944
- }
945
- const { fetch, vm } = options;
946
- const response = await fetch(url);
947
- const code = await response.text();
948
- const module = new vm.SourceTextModule(code, {
949
- // @ts-ignore
950
- importModuleDynamically: async (specifier, script) => {
951
- const resolvedUrl = new URL(specifier, url).href;
952
- return loadModule(resolvedUrl, options);
953
- },
954
- });
955
- // Cache the module before linking to prevent cycles
956
- esmModuleCache.set(url, module);
957
- await module.link(async (specifier) => {
958
- const resolvedUrl = new URL(specifier, url).href;
959
- const module = await loadModule(resolvedUrl, options);
960
- return module;
961
- });
962
- return module;
963
- }
964
-
965
- function normalizeOptions(enableDefault, defaultOptions, key) {
966
- return function (options) {
967
- if (options === false) {
968
- return false;
969
- }
970
- if (typeof options === 'undefined') {
971
- if (enableDefault) {
972
- return defaultOptions;
973
- }
974
- else {
975
- return false;
976
- }
977
- }
978
- if (options === true) {
979
- return defaultOptions;
980
- }
981
- if (options && typeof options === 'object') {
982
- return {
983
- ...defaultOptions,
984
- ...options,
985
- };
986
- }
987
- throw new Error(`Unexpected type for \`${key}\`, expect boolean/undefined/object, got: ${typeof options}`);
988
- };
989
- }
990
-
991
- const createModuleFederationConfig = (options) => {
992
- return options;
993
- };
994
-
995
- exports.BROWSER_LOG_KEY = BROWSER_LOG_KEY;
996
- exports.ENCODE_NAME_PREFIX = ENCODE_NAME_PREFIX;
997
- exports.EncodedNameTransformMap = EncodedNameTransformMap;
998
- exports.FederationModuleManifest = FederationModuleManifest;
999
- exports.MANIFEST_EXT = MANIFEST_EXT;
1000
- exports.MFModuleType = MFModuleType;
1001
- exports.MFPrefetchCommon = MFPrefetchCommon;
1002
- exports.MODULE_DEVTOOL_IDENTIFIER = MODULE_DEVTOOL_IDENTIFIER;
1003
- exports.ManifestFileName = ManifestFileName;
1004
- exports.NameTransformMap = NameTransformMap;
1005
- exports.NameTransformSymbol = NameTransformSymbol;
1006
- exports.SEPARATOR = SEPARATOR;
1007
- exports.StatsFileName = StatsFileName;
1008
- exports.TEMP_DIR = TEMP_DIR;
1009
- exports.assert = assert;
1010
- exports.bindLoggerToCompiler = bindLoggerToCompiler;
1011
- exports.composeKeyWithSeparator = composeKeyWithSeparator;
1012
- exports.containerPlugin = ContainerPlugin;
1013
- exports.containerReferencePlugin = ContainerReferencePlugin;
1014
- exports.createInfrastructureLogger = createInfrastructureLogger;
1015
- exports.createLink = createLink;
1016
- exports.createLogger = createLogger;
1017
- exports.createModuleFederationConfig = createModuleFederationConfig;
1018
- exports.createScript = createScript;
1019
- exports.createScriptNode = createScriptNode;
1020
- exports.decodeName = decodeName;
1021
- exports.encodeName = encodeName;
1022
- exports.error = error;
1023
- exports.generateExposeFilename = generateExposeFilename;
1024
- exports.generateShareFilename = generateShareFilename;
1025
- exports.generateSnapshotFromManifest = generateSnapshotFromManifest;
1026
- exports.getManifestFileName = getManifestFileName;
1027
- exports.getProcessEnv = getProcessEnv;
1028
- exports.getResourceUrl = getResourceUrl;
1029
- exports.inferAutoPublicPath = inferAutoPublicPath;
1030
- exports.infrastructureLogger = infrastructureLogger;
1031
- exports.isBrowserEnv = isBrowserEnv;
1032
- exports.isDebugMode = isDebugMode;
1033
- exports.isManifestProvider = isManifestProvider;
1034
- exports.isReactNativeEnv = isReactNativeEnv;
1035
- exports.isRequiredVersion = isRequiredVersion;
1036
- exports.isStaticResourcesEqual = isStaticResourcesEqual;
1037
- exports.loadScript = loadScript;
1038
- exports.loadScriptNode = loadScriptNode;
1039
- exports.logger = logger;
1040
- exports.moduleFederationPlugin = ModuleFederationPlugin;
1041
- exports.normalizeOptions = normalizeOptions;
1042
- exports.parseEntry = parseEntry;
1043
- exports.safeToString = safeToString;
1044
- exports.safeWrapper = safeWrapper;
1045
- exports.sharePlugin = SharePlugin;
1046
- exports.simpleJoinRemoteEntry = simpleJoinRemoteEntry;
1047
- exports.warn = warn;
1048
- //# sourceMappingURL=index.cjs.cjs.map