@module-federation/sdk 0.0.0-next-20250709032753 → 0.0.0-next-20250709090625

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 (36) hide show
  1. package/dist/index.cjs +812 -0
  2. package/dist/index.js +656 -0
  3. package/dist/normalize-webpack-path.cjs +77 -0
  4. package/dist/{normalize-webpack-path.esm.js → normalize-webpack-path.js} +6 -15
  5. package/dist/{src/types → types}/plugins/ModuleFederationPlugin.d.ts +0 -4
  6. package/package.json +16 -22
  7. package/dist/index.cjs.cjs +0 -821
  8. package/dist/index.cjs.d.ts +0 -1
  9. package/dist/index.esm.d.ts +0 -1
  10. package/dist/index.esm.js +0 -771
  11. package/dist/normalize-webpack-path.cjs.cjs +0 -42
  12. package/dist/normalize-webpack-path.cjs.d.ts +0 -1
  13. package/dist/normalize-webpack-path.esm.d.ts +0 -1
  14. package/dist/polyfills.cjs.cjs +0 -14
  15. package/dist/polyfills.esm.js +0 -12
  16. /package/dist/{src/constant.d.ts → constant.d.ts} +0 -0
  17. /package/dist/{src/createModuleFederationConfig.d.ts → createModuleFederationConfig.d.ts} +0 -0
  18. /package/dist/{src/dom.d.ts → dom.d.ts} +0 -0
  19. /package/dist/{src/env.d.ts → env.d.ts} +0 -0
  20. /package/dist/{src/generateSnapshotFromManifest.d.ts → generateSnapshotFromManifest.d.ts} +0 -0
  21. /package/dist/{src/index.d.ts → index.d.ts} +0 -0
  22. /package/dist/{src/logger.d.ts → logger.d.ts} +0 -0
  23. /package/dist/{src/node.d.ts → node.d.ts} +0 -0
  24. /package/dist/{src/normalize-webpack-path.d.ts → normalize-webpack-path.d.ts} +0 -0
  25. /package/dist/{src/normalizeOptions.d.ts → normalizeOptions.d.ts} +0 -0
  26. /package/dist/{src/types → types}/common.d.ts +0 -0
  27. /package/dist/{src/types → types}/hooks.d.ts +0 -0
  28. /package/dist/{src/types → types}/index.d.ts +0 -0
  29. /package/dist/{src/types → types}/manifest.d.ts +0 -0
  30. /package/dist/{src/types → types}/plugins/ContainerPlugin.d.ts +0 -0
  31. /package/dist/{src/types → types}/plugins/ContainerReferencePlugin.d.ts +0 -0
  32. /package/dist/{src/types → types}/plugins/SharePlugin.d.ts +0 -0
  33. /package/dist/{src/types → types}/plugins/index.d.ts +0 -0
  34. /package/dist/{src/types → types}/snapshot.d.ts +0 -0
  35. /package/dist/{src/types → types}/stats.d.ts +0 -0
  36. /package/dist/{src/utils.d.ts → utils.d.ts} +0 -0
@@ -1,821 +0,0 @@
1
- 'use strict';
2
-
3
- var polyfills = require('./polyfills.cjs.cjs');
4
-
5
- const FederationModuleManifest = 'federation-manifest.json';
6
- const MANIFEST_EXT = '.json';
7
- const BROWSER_LOG_KEY = 'FEDERATION_DEBUG';
8
- const NameTransformSymbol = {
9
- AT: '@',
10
- HYPHEN: '-',
11
- SLASH: '/'
12
- };
13
- const NameTransformMap = {
14
- [NameTransformSymbol.AT]: 'scope_',
15
- [NameTransformSymbol.HYPHEN]: '_',
16
- [NameTransformSymbol.SLASH]: '__'
17
- };
18
- const EncodedNameTransformMap = {
19
- [NameTransformMap[NameTransformSymbol.AT]]: NameTransformSymbol.AT,
20
- [NameTransformMap[NameTransformSymbol.HYPHEN]]: NameTransformSymbol.HYPHEN,
21
- [NameTransformMap[NameTransformSymbol.SLASH]]: NameTransformSymbol.SLASH
22
- };
23
- const SEPARATOR = ':';
24
- const ManifestFileName = 'mf-manifest.json';
25
- const StatsFileName = 'mf-stats.json';
26
- const MFModuleType = {
27
- NPM: 'npm',
28
- APP: 'app'
29
- };
30
- const MODULE_DEVTOOL_IDENTIFIER = '__MF_DEVTOOLS_MODULE_INFO__';
31
- const ENCODE_NAME_PREFIX = 'ENCODE_NAME_PREFIX';
32
- const TEMP_DIR = '.federation';
33
- const MFPrefetchCommon = {
34
- identifier: 'MFDataPrefetch',
35
- globalKey: '__PREFETCH__',
36
- library: 'mf-data-prefetch',
37
- exportsKey: '__PREFETCH_EXPORTS__',
38
- fileName: 'bootstrap.js'
39
- };
40
-
41
- var ContainerPlugin = /*#__PURE__*/Object.freeze({
42
- __proto__: null
43
- });
44
-
45
- var ContainerReferencePlugin = /*#__PURE__*/Object.freeze({
46
- __proto__: null
47
- });
48
-
49
- var ModuleFederationPlugin = /*#__PURE__*/Object.freeze({
50
- __proto__: null
51
- });
52
-
53
- var SharePlugin = /*#__PURE__*/Object.freeze({
54
- __proto__: null
55
- });
56
-
57
- function isBrowserEnv() {
58
- return typeof window !== 'undefined' && typeof window.document !== 'undefined';
59
- }
60
- function isReactNativeEnv() {
61
- var _navigator;
62
- return typeof navigator !== 'undefined' && ((_navigator = navigator) == null ? void 0 : _navigator.product) === 'ReactNative';
63
- }
64
- function isBrowserDebug() {
65
- try {
66
- if (isBrowserEnv() && window.localStorage) {
67
- return Boolean(localStorage.getItem(BROWSER_LOG_KEY));
68
- }
69
- } catch (error) {
70
- return false;
71
- }
72
- return false;
73
- }
74
- function isDebugMode() {
75
- if (typeof process !== 'undefined' && process.env && process.env['FEDERATION_DEBUG']) {
76
- return Boolean(process.env['FEDERATION_DEBUG']);
77
- }
78
- if (typeof FEDERATION_DEBUG !== 'undefined' && Boolean(FEDERATION_DEBUG)) {
79
- return true;
80
- }
81
- return isBrowserDebug();
82
- }
83
- const getProcessEnv = function() {
84
- return typeof process !== 'undefined' && process.env ? process.env : {};
85
- };
86
-
87
- const LOG_CATEGORY = '[ Federation Runtime ]';
88
- // entry: name:version version : 1.0.0 | ^1.2.3
89
- // entry: name:entry entry: https://localhost:9000/federation-manifest.json
90
- const parseEntry = (str, devVerOrUrl, separator = SEPARATOR)=>{
91
- const strSplit = str.split(separator);
92
- const devVersionOrUrl = getProcessEnv()['NODE_ENV'] === 'development' && devVerOrUrl;
93
- const defaultVersion = '*';
94
- const isEntry = (s)=>s.startsWith('http') || s.includes(MANIFEST_EXT);
95
- // Check if the string starts with a type
96
- if (strSplit.length >= 2) {
97
- let [name, ...versionOrEntryArr] = strSplit;
98
- // @name@manifest-url.json
99
- if (str.startsWith(separator)) {
100
- name = strSplit.slice(0, 2).join(separator);
101
- versionOrEntryArr = [
102
- devVersionOrUrl || strSplit.slice(2).join(separator)
103
- ];
104
- }
105
- let versionOrEntry = devVersionOrUrl || versionOrEntryArr.join(separator);
106
- if (isEntry(versionOrEntry)) {
107
- return {
108
- name,
109
- entry: versionOrEntry
110
- };
111
- } else {
112
- // Apply version rule
113
- // devVersionOrUrl => inputVersion => defaultVersion
114
- return {
115
- name,
116
- version: versionOrEntry || defaultVersion
117
- };
118
- }
119
- } else if (strSplit.length === 1) {
120
- const [name] = strSplit;
121
- if (devVersionOrUrl && isEntry(devVersionOrUrl)) {
122
- return {
123
- name,
124
- entry: devVersionOrUrl
125
- };
126
- }
127
- return {
128
- name,
129
- version: devVersionOrUrl || defaultVersion
130
- };
131
- } else {
132
- throw `Invalid entry value: ${str}`;
133
- }
134
- };
135
- const composeKeyWithSeparator = function(...args) {
136
- if (!args.length) {
137
- return '';
138
- }
139
- return args.reduce((sum, cur)=>{
140
- if (!cur) {
141
- return sum;
142
- }
143
- if (!sum) {
144
- return cur;
145
- }
146
- return `${sum}${SEPARATOR}${cur}`;
147
- }, '');
148
- };
149
- const encodeName = function(name, prefix = '', withExt = false) {
150
- try {
151
- const ext = withExt ? '.js' : '';
152
- return `${prefix}${name.replace(new RegExp(`${NameTransformSymbol.AT}`, 'g'), NameTransformMap[NameTransformSymbol.AT]).replace(new RegExp(`${NameTransformSymbol.HYPHEN}`, 'g'), NameTransformMap[NameTransformSymbol.HYPHEN]).replace(new RegExp(`${NameTransformSymbol.SLASH}`, 'g'), NameTransformMap[NameTransformSymbol.SLASH])}${ext}`;
153
- } catch (err) {
154
- throw err;
155
- }
156
- };
157
- const decodeName = function(name, prefix, withExt) {
158
- try {
159
- let decodedName = name;
160
- if (prefix) {
161
- if (!decodedName.startsWith(prefix)) {
162
- return decodedName;
163
- }
164
- decodedName = decodedName.replace(new RegExp(prefix, 'g'), '');
165
- }
166
- decodedName = decodedName.replace(new RegExp(`${NameTransformMap[NameTransformSymbol.AT]}`, 'g'), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.AT]]).replace(new RegExp(`${NameTransformMap[NameTransformSymbol.SLASH]}`, 'g'), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.SLASH]]).replace(new RegExp(`${NameTransformMap[NameTransformSymbol.HYPHEN]}`, 'g'), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.HYPHEN]]);
167
- if (withExt) {
168
- decodedName = decodedName.replace('.js', '');
169
- }
170
- return decodedName;
171
- } catch (err) {
172
- throw err;
173
- }
174
- };
175
- const generateExposeFilename = (exposeName, withExt)=>{
176
- if (!exposeName) {
177
- return '';
178
- }
179
- let expose = exposeName;
180
- if (expose === '.') {
181
- expose = 'default_export';
182
- }
183
- if (expose.startsWith('./')) {
184
- expose = expose.replace('./', '');
185
- }
186
- return encodeName(expose, '__federation_expose_', withExt);
187
- };
188
- const generateShareFilename = (pkgName, withExt)=>{
189
- if (!pkgName) {
190
- return '';
191
- }
192
- return encodeName(pkgName, '__federation_shared_', withExt);
193
- };
194
- const getResourceUrl = (module, sourceUrl)=>{
195
- if ('getPublicPath' in module) {
196
- let publicPath;
197
- if (!module.getPublicPath.startsWith('function')) {
198
- publicPath = new Function(module.getPublicPath)();
199
- } else {
200
- publicPath = new Function('return ' + module.getPublicPath)()();
201
- }
202
- return `${publicPath}${sourceUrl}`;
203
- } else if ('publicPath' in module) {
204
- if (!isBrowserEnv() && !isReactNativeEnv() && 'ssrPublicPath' in module) {
205
- return `${module.ssrPublicPath}${sourceUrl}`;
206
- }
207
- return `${module.publicPath}${sourceUrl}`;
208
- } else {
209
- console.warn('Cannot get resource URL. If in debug mode, please ignore.', module, sourceUrl);
210
- return '';
211
- }
212
- };
213
- // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
214
- const assert = (condition, msg)=>{
215
- if (!condition) {
216
- error(msg);
217
- }
218
- };
219
- const error = (msg)=>{
220
- throw new Error(`${LOG_CATEGORY}: ${msg}`);
221
- };
222
- const warn = (msg)=>{
223
- console.warn(`${LOG_CATEGORY}: ${msg}`);
224
- };
225
- function safeToString(info) {
226
- try {
227
- return JSON.stringify(info, null, 2);
228
- } catch (e) {
229
- return '';
230
- }
231
- }
232
- // RegExp for version string
233
- const VERSION_PATTERN_REGEXP = /^([\d^=v<>~]|[*xX]$)/;
234
- function isRequiredVersion(str) {
235
- return VERSION_PATTERN_REGEXP.test(str);
236
- }
237
-
238
- const simpleJoinRemoteEntry = (rPath, rName)=>{
239
- if (!rPath) {
240
- return rName;
241
- }
242
- const transformPath = (str)=>{
243
- if (str === '.') {
244
- return '';
245
- }
246
- if (str.startsWith('./')) {
247
- return str.replace('./', '');
248
- }
249
- if (str.startsWith('/')) {
250
- const strWithoutSlash = str.slice(1);
251
- if (strWithoutSlash.endsWith('/')) {
252
- return strWithoutSlash.slice(0, -1);
253
- }
254
- return strWithoutSlash;
255
- }
256
- return str;
257
- };
258
- const transformedPath = transformPath(rPath);
259
- if (!transformedPath) {
260
- return rName;
261
- }
262
- if (transformedPath.endsWith('/')) {
263
- return `${transformedPath}${rName}`;
264
- }
265
- return `${transformedPath}/${rName}`;
266
- };
267
- function inferAutoPublicPath(url) {
268
- return url.replace(/#.*$/, '').replace(/\?.*$/, '').replace(/\/[^\/]+$/, '/');
269
- }
270
- // Priority: overrides > remotes
271
- // eslint-disable-next-line max-lines-per-function
272
- function generateSnapshotFromManifest(manifest, options = {}) {
273
- var _manifest_metaData, _manifest_metaData1;
274
- const { remotes = {}, overrides = {}, version } = options;
275
- let remoteSnapshot;
276
- const getPublicPath = ()=>{
277
- if ('publicPath' in manifest.metaData) {
278
- if (manifest.metaData.publicPath === 'auto' && version) {
279
- // use same implementation as publicPath auto runtime module implements
280
- return inferAutoPublicPath(version);
281
- }
282
- return manifest.metaData.publicPath;
283
- } else {
284
- return manifest.metaData.getPublicPath;
285
- }
286
- };
287
- const overridesKeys = Object.keys(overrides);
288
- let remotesInfo = {};
289
- // If remotes are not provided, only the remotes in the manifest will be read
290
- if (!Object.keys(remotes).length) {
291
- var _manifest_remotes;
292
- remotesInfo = ((_manifest_remotes = manifest.remotes) == null ? void 0 : _manifest_remotes.reduce((res, next)=>{
293
- let matchedVersion;
294
- const name = next.federationContainerName;
295
- // overrides have higher priority
296
- if (overridesKeys.includes(name)) {
297
- matchedVersion = overrides[name];
298
- } else {
299
- if ('version' in next) {
300
- matchedVersion = next.version;
301
- } else {
302
- matchedVersion = next.entry;
303
- }
304
- }
305
- res[name] = {
306
- matchedVersion
307
- };
308
- return res;
309
- }, {})) || {};
310
- }
311
- // If remotes (deploy scenario) are specified, they need to be traversed again
312
- Object.keys(remotes).forEach((key)=>remotesInfo[key] = {
313
- // overrides will override dependencies
314
- matchedVersion: overridesKeys.includes(key) ? overrides[key] : remotes[key]
315
- });
316
- const { remoteEntry: { path: remoteEntryPath, name: remoteEntryName, type: remoteEntryType }, types: remoteTypes, buildInfo: { buildVersion }, globalName, ssrRemoteEntry } = manifest.metaData;
317
- const { exposes } = manifest;
318
- let basicRemoteSnapshot = {
319
- version: version ? version : '',
320
- buildVersion,
321
- globalName,
322
- remoteEntry: simpleJoinRemoteEntry(remoteEntryPath, remoteEntryName),
323
- remoteEntryType,
324
- remoteTypes: simpleJoinRemoteEntry(remoteTypes.path, remoteTypes.name),
325
- remoteTypesZip: remoteTypes.zip || '',
326
- remoteTypesAPI: remoteTypes.api || '',
327
- remotesInfo,
328
- shared: manifest == null ? void 0 : manifest.shared.map((item)=>({
329
- assets: item.assets,
330
- sharedName: item.name,
331
- version: item.version
332
- })),
333
- modules: exposes == null ? void 0 : exposes.map((expose)=>({
334
- moduleName: expose.name,
335
- modulePath: expose.path,
336
- assets: expose.assets
337
- }))
338
- };
339
- if ((_manifest_metaData = manifest.metaData) == null ? void 0 : _manifest_metaData.prefetchInterface) {
340
- const prefetchInterface = manifest.metaData.prefetchInterface;
341
- basicRemoteSnapshot = polyfills._({}, basicRemoteSnapshot, {
342
- prefetchInterface
343
- });
344
- }
345
- if ((_manifest_metaData1 = manifest.metaData) == null ? void 0 : _manifest_metaData1.prefetchEntry) {
346
- const { path, name, type } = manifest.metaData.prefetchEntry;
347
- basicRemoteSnapshot = polyfills._({}, basicRemoteSnapshot, {
348
- prefetchEntry: simpleJoinRemoteEntry(path, name),
349
- prefetchEntryType: type
350
- });
351
- }
352
- if ('publicPath' in manifest.metaData) {
353
- remoteSnapshot = polyfills._({}, basicRemoteSnapshot, {
354
- publicPath: getPublicPath(),
355
- ssrPublicPath: manifest.metaData.ssrPublicPath
356
- });
357
- } else {
358
- remoteSnapshot = polyfills._({}, basicRemoteSnapshot, {
359
- getPublicPath: getPublicPath()
360
- });
361
- }
362
- if (ssrRemoteEntry) {
363
- const fullSSRRemoteEntry = simpleJoinRemoteEntry(ssrRemoteEntry.path, ssrRemoteEntry.name);
364
- remoteSnapshot.ssrRemoteEntry = fullSSRRemoteEntry;
365
- remoteSnapshot.ssrRemoteEntryType = ssrRemoteEntry.type || 'commonjs-module';
366
- }
367
- return remoteSnapshot;
368
- }
369
- function isManifestProvider(moduleInfo) {
370
- if ('remoteEntry' in moduleInfo && moduleInfo.remoteEntry.includes(MANIFEST_EXT)) {
371
- return true;
372
- } else {
373
- return false;
374
- }
375
- }
376
-
377
- const PREFIX = '[ Module Federation ]';
378
- let Logger = class Logger {
379
- setPrefix(prefix) {
380
- this.prefix = prefix;
381
- }
382
- log(...args) {
383
- console.log(this.prefix, ...args);
384
- }
385
- warn(...args) {
386
- console.log(this.prefix, ...args);
387
- }
388
- error(...args) {
389
- console.log(this.prefix, ...args);
390
- }
391
- success(...args) {
392
- console.log(this.prefix, ...args);
393
- }
394
- info(...args) {
395
- console.log(this.prefix, ...args);
396
- }
397
- ready(...args) {
398
- console.log(this.prefix, ...args);
399
- }
400
- debug(...args) {
401
- if (isDebugMode()) {
402
- console.log(this.prefix, ...args);
403
- }
404
- }
405
- constructor(prefix){
406
- this.prefix = prefix;
407
- }
408
- };
409
- function createLogger(prefix) {
410
- return new Logger(prefix);
411
- }
412
- const logger = createLogger(PREFIX);
413
-
414
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
415
- async function safeWrapper(callback, disableWarn) {
416
- try {
417
- const res = await callback();
418
- return res;
419
- } catch (e) {
420
- !disableWarn && warn(e);
421
- return;
422
- }
423
- }
424
- function isStaticResourcesEqual(url1, url2) {
425
- const REG_EXP = /^(https?:)?\/\//i;
426
- // Transform url1 and url2 into relative paths
427
- const relativeUrl1 = url1.replace(REG_EXP, '').replace(/\/$/, '');
428
- const relativeUrl2 = url2.replace(REG_EXP, '').replace(/\/$/, '');
429
- // Check if the relative paths are identical
430
- return relativeUrl1 === relativeUrl2;
431
- }
432
- function createScript(info) {
433
- // Retrieve the existing script element by its src attribute
434
- let script = null;
435
- let needAttach = true;
436
- let timeout = 20000;
437
- let timeoutId;
438
- const scripts = document.getElementsByTagName('script');
439
- for(let i = 0; i < scripts.length; i++){
440
- const s = scripts[i];
441
- const scriptSrc = s.getAttribute('src');
442
- if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {
443
- script = s;
444
- needAttach = false;
445
- break;
446
- }
447
- }
448
- if (!script) {
449
- const attrs = info.attrs;
450
- script = document.createElement('script');
451
- script.type = (attrs == null ? void 0 : attrs['type']) === 'module' ? 'module' : 'text/javascript';
452
- let createScriptRes = undefined;
453
- if (info.createScriptHook) {
454
- createScriptRes = info.createScriptHook(info.url, info.attrs);
455
- if (createScriptRes instanceof HTMLScriptElement) {
456
- script = createScriptRes;
457
- } else if (typeof createScriptRes === 'object') {
458
- if ('script' in createScriptRes && createScriptRes.script) {
459
- script = createScriptRes.script;
460
- }
461
- if ('timeout' in createScriptRes && createScriptRes.timeout) {
462
- timeout = createScriptRes.timeout;
463
- }
464
- }
465
- }
466
- if (!script.src) {
467
- script.src = info.url;
468
- }
469
- if (attrs && !createScriptRes) {
470
- Object.keys(attrs).forEach((name)=>{
471
- if (script) {
472
- if (name === 'async' || name === 'defer') {
473
- script[name] = attrs[name];
474
- // Attributes that do not exist are considered overridden
475
- } else if (!script.getAttribute(name)) {
476
- script.setAttribute(name, attrs[name]);
477
- }
478
- }
479
- });
480
- }
481
- }
482
- const onScriptComplete = async (prev, // eslint-disable-next-line @typescript-eslint/no-explicit-any
483
- event)=>{
484
- clearTimeout(timeoutId);
485
- const onScriptCompleteCallback = ()=>{
486
- if ((event == null ? void 0 : event.type) === 'error') {
487
- (info == null ? void 0 : info.onErrorCallback) && (info == null ? void 0 : info.onErrorCallback(event));
488
- } else {
489
- (info == null ? void 0 : info.cb) && (info == null ? void 0 : info.cb());
490
- }
491
- };
492
- // Prevent memory leaks in IE.
493
- if (script) {
494
- script.onerror = null;
495
- script.onload = null;
496
- safeWrapper(()=>{
497
- const { needDeleteScript = true } = info;
498
- if (needDeleteScript) {
499
- (script == null ? void 0 : script.parentNode) && script.parentNode.removeChild(script);
500
- }
501
- });
502
- if (prev && typeof prev === 'function') {
503
- const result = prev(event);
504
- if (result instanceof Promise) {
505
- const res = await result;
506
- onScriptCompleteCallback();
507
- return res;
508
- }
509
- onScriptCompleteCallback();
510
- return result;
511
- }
512
- }
513
- onScriptCompleteCallback();
514
- };
515
- script.onerror = onScriptComplete.bind(null, script.onerror);
516
- script.onload = onScriptComplete.bind(null, script.onload);
517
- timeoutId = setTimeout(()=>{
518
- onScriptComplete(null, new Error(`Remote script "${info.url}" time-outed.`));
519
- }, timeout);
520
- return {
521
- script,
522
- needAttach
523
- };
524
- }
525
- function createLink(info) {
526
- // <link rel="preload" href="script.js" as="script">
527
- // Retrieve the existing script element by its src attribute
528
- let link = null;
529
- let needAttach = true;
530
- const links = document.getElementsByTagName('link');
531
- for(let i = 0; i < links.length; i++){
532
- const l = links[i];
533
- const linkHref = l.getAttribute('href');
534
- const linkRel = l.getAttribute('rel');
535
- if (linkHref && isStaticResourcesEqual(linkHref, info.url) && linkRel === info.attrs['rel']) {
536
- link = l;
537
- needAttach = false;
538
- break;
539
- }
540
- }
541
- if (!link) {
542
- link = document.createElement('link');
543
- link.setAttribute('href', info.url);
544
- let createLinkRes = undefined;
545
- const attrs = info.attrs;
546
- if (info.createLinkHook) {
547
- createLinkRes = info.createLinkHook(info.url, attrs);
548
- if (createLinkRes instanceof HTMLLinkElement) {
549
- link = createLinkRes;
550
- }
551
- }
552
- if (attrs && !createLinkRes) {
553
- Object.keys(attrs).forEach((name)=>{
554
- if (link && !link.getAttribute(name)) {
555
- link.setAttribute(name, attrs[name]);
556
- }
557
- });
558
- }
559
- }
560
- const onLinkComplete = (prev, // eslint-disable-next-line @typescript-eslint/no-explicit-any
561
- event)=>{
562
- const onLinkCompleteCallback = ()=>{
563
- if ((event == null ? void 0 : event.type) === 'error') {
564
- (info == null ? void 0 : info.onErrorCallback) && (info == null ? void 0 : info.onErrorCallback(event));
565
- } else {
566
- (info == null ? void 0 : info.cb) && (info == null ? void 0 : info.cb());
567
- }
568
- };
569
- // Prevent memory leaks in IE.
570
- if (link) {
571
- link.onerror = null;
572
- link.onload = null;
573
- safeWrapper(()=>{
574
- const { needDeleteLink = true } = info;
575
- if (needDeleteLink) {
576
- (link == null ? void 0 : link.parentNode) && link.parentNode.removeChild(link);
577
- }
578
- });
579
- if (prev) {
580
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
581
- const res = prev(event);
582
- onLinkCompleteCallback();
583
- return res;
584
- }
585
- }
586
- onLinkCompleteCallback();
587
- };
588
- link.onerror = onLinkComplete.bind(null, link.onerror);
589
- link.onload = onLinkComplete.bind(null, link.onload);
590
- return {
591
- link,
592
- needAttach
593
- };
594
- }
595
- function loadScript(url, info) {
596
- const { attrs = {}, createScriptHook } = info;
597
- return new Promise((resolve, reject)=>{
598
- const { script, needAttach } = createScript({
599
- url,
600
- cb: resolve,
601
- onErrorCallback: reject,
602
- attrs: polyfills._({
603
- fetchpriority: 'high'
604
- }, attrs),
605
- createScriptHook,
606
- needDeleteScript: true
607
- });
608
- needAttach && document.head.appendChild(script);
609
- });
610
- }
611
-
612
- function importNodeModule(name) {
613
- if (!name) {
614
- throw new Error('import specifier is required');
615
- }
616
- const importModule = new Function('name', `return import(name)`);
617
- return importModule(name).then((res)=>res).catch((error)=>{
618
- console.error(`Error importing module ${name}:`, error);
619
- throw error;
620
- });
621
- }
622
- const loadNodeFetch = async ()=>{
623
- const fetchModule = await importNodeModule('node-fetch');
624
- return fetchModule.default || fetchModule;
625
- };
626
- const lazyLoaderHookFetch = async (input, init, loaderHook)=>{
627
- const hook = (url, init)=>{
628
- return loaderHook.lifecycle.fetch.emit(url, init);
629
- };
630
- const res = await hook(input, init || {});
631
- if (!res || !(res instanceof Response)) {
632
- const fetchFunction = typeof fetch === 'undefined' ? await loadNodeFetch() : fetch;
633
- return fetchFunction(input, init || {});
634
- }
635
- return res;
636
- };
637
- const createScriptNode = typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web' ? (url, cb, attrs, loaderHook)=>{
638
- if (loaderHook == null ? void 0 : loaderHook.createScriptHook) {
639
- const hookResult = loaderHook.createScriptHook(url);
640
- if (hookResult && typeof hookResult === 'object' && 'url' in hookResult) {
641
- url = hookResult.url;
642
- }
643
- }
644
- let urlObj;
645
- try {
646
- urlObj = new URL(url);
647
- } catch (e) {
648
- console.error('Error constructing URL:', e);
649
- cb(new Error(`Invalid URL: ${e}`));
650
- return;
651
- }
652
- const getFetch = async ()=>{
653
- if (loaderHook == null ? void 0 : loaderHook.fetch) {
654
- return (input, init)=>lazyLoaderHookFetch(input, init, loaderHook);
655
- }
656
- return typeof fetch === 'undefined' ? loadNodeFetch() : fetch;
657
- };
658
- const handleScriptFetch = async (f, urlObj)=>{
659
- try {
660
- var //@ts-ignore
661
- _vm_constants;
662
- const res = await f(urlObj.href);
663
- const data = await res.text();
664
- const [path, vm] = await Promise.all([
665
- importNodeModule('path'),
666
- importNodeModule('vm')
667
- ]);
668
- const scriptContext = {
669
- exports: {},
670
- module: {
671
- exports: {}
672
- }
673
- };
674
- const urlDirname = urlObj.pathname.split('/').slice(0, -1).join('/');
675
- const filename = path.basename(urlObj.pathname);
676
- var _vm_constants_USE_MAIN_CONTEXT_DEFAULT_LOADER;
677
- const script = new vm.Script(`(function(exports, module, require, __dirname, __filename) {${data}\n})`, {
678
- filename,
679
- importModuleDynamically: (_vm_constants_USE_MAIN_CONTEXT_DEFAULT_LOADER = (_vm_constants = vm.constants) == null ? void 0 : _vm_constants.USE_MAIN_CONTEXT_DEFAULT_LOADER) != null ? _vm_constants_USE_MAIN_CONTEXT_DEFAULT_LOADER : importNodeModule
680
- });
681
- script.runInThisContext()(scriptContext.exports, scriptContext.module, eval('require'), urlDirname, filename);
682
- const exportedInterface = scriptContext.module.exports || scriptContext.exports;
683
- if (attrs && exportedInterface && attrs['globalName']) {
684
- const container = exportedInterface[attrs['globalName']] || exportedInterface;
685
- cb(undefined, container);
686
- return;
687
- }
688
- cb(undefined, exportedInterface);
689
- } catch (e) {
690
- cb(e instanceof Error ? e : new Error(`Script execution error: ${e}`));
691
- }
692
- };
693
- getFetch().then(async (f)=>{
694
- if ((attrs == null ? void 0 : attrs['type']) === 'esm' || (attrs == null ? void 0 : attrs['type']) === 'module') {
695
- return loadModule(urlObj.href, {
696
- fetch: f,
697
- vm: await importNodeModule('vm')
698
- }).then(async (module)=>{
699
- await module.evaluate();
700
- cb(undefined, module.namespace);
701
- }).catch((e)=>{
702
- cb(e instanceof Error ? e : new Error(`Script execution error: ${e}`));
703
- });
704
- }
705
- handleScriptFetch(f, urlObj);
706
- }).catch((err)=>{
707
- cb(err);
708
- });
709
- } : (url, cb, attrs, loaderHook)=>{
710
- cb(new Error('createScriptNode is disabled in non-Node.js environment'));
711
- };
712
- const loadScriptNode = typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web' ? (url, info)=>{
713
- return new Promise((resolve, reject)=>{
714
- createScriptNode(url, (error, scriptContext)=>{
715
- if (error) {
716
- reject(error);
717
- } else {
718
- var _info_attrs, _info_attrs1;
719
- const remoteEntryKey = (info == null ? void 0 : (_info_attrs = info.attrs) == null ? void 0 : _info_attrs['globalName']) || `__FEDERATION_${info == null ? void 0 : (_info_attrs1 = info.attrs) == null ? void 0 : _info_attrs1['name']}:custom__`;
720
- const entryExports = globalThis[remoteEntryKey] = scriptContext;
721
- resolve(entryExports);
722
- }
723
- }, info.attrs, info.loaderHook);
724
- });
725
- } : (url, info)=>{
726
- throw new Error('loadScriptNode is disabled in non-Node.js environment');
727
- };
728
- async function loadModule(url, options) {
729
- const { fetch: fetch1, vm } = options;
730
- const response = await fetch1(url);
731
- const code = await response.text();
732
- const module = new vm.SourceTextModule(code, {
733
- // @ts-ignore
734
- importModuleDynamically: async (specifier, script)=>{
735
- const resolvedUrl = new URL(specifier, url).href;
736
- return loadModule(resolvedUrl, options);
737
- }
738
- });
739
- await module.link(async (specifier)=>{
740
- const resolvedUrl = new URL(specifier, url).href;
741
- const module = await loadModule(resolvedUrl, options);
742
- return module;
743
- });
744
- return module;
745
- }
746
-
747
- function normalizeOptions(enableDefault, defaultOptions, key) {
748
- return function(options) {
749
- if (options === false) {
750
- return false;
751
- }
752
- if (typeof options === 'undefined') {
753
- if (enableDefault) {
754
- return defaultOptions;
755
- } else {
756
- return false;
757
- }
758
- }
759
- if (options === true) {
760
- return defaultOptions;
761
- }
762
- if (options && typeof options === 'object') {
763
- return polyfills._({}, defaultOptions, options);
764
- }
765
- throw new Error(`Unexpected type for \`${key}\`, expect boolean/undefined/object, got: ${typeof options}`);
766
- };
767
- }
768
-
769
- const createModuleFederationConfig = (options)=>{
770
- return options;
771
- };
772
-
773
- exports.BROWSER_LOG_KEY = BROWSER_LOG_KEY;
774
- exports.ENCODE_NAME_PREFIX = ENCODE_NAME_PREFIX;
775
- exports.EncodedNameTransformMap = EncodedNameTransformMap;
776
- exports.FederationModuleManifest = FederationModuleManifest;
777
- exports.MANIFEST_EXT = MANIFEST_EXT;
778
- exports.MFModuleType = MFModuleType;
779
- exports.MFPrefetchCommon = MFPrefetchCommon;
780
- exports.MODULE_DEVTOOL_IDENTIFIER = MODULE_DEVTOOL_IDENTIFIER;
781
- exports.ManifestFileName = ManifestFileName;
782
- exports.NameTransformMap = NameTransformMap;
783
- exports.NameTransformSymbol = NameTransformSymbol;
784
- exports.SEPARATOR = SEPARATOR;
785
- exports.StatsFileName = StatsFileName;
786
- exports.TEMP_DIR = TEMP_DIR;
787
- exports.assert = assert;
788
- exports.composeKeyWithSeparator = composeKeyWithSeparator;
789
- exports.containerPlugin = ContainerPlugin;
790
- exports.containerReferencePlugin = ContainerReferencePlugin;
791
- exports.createLink = createLink;
792
- exports.createLogger = createLogger;
793
- exports.createModuleFederationConfig = createModuleFederationConfig;
794
- exports.createScript = createScript;
795
- exports.createScriptNode = createScriptNode;
796
- exports.decodeName = decodeName;
797
- exports.encodeName = encodeName;
798
- exports.error = error;
799
- exports.generateExposeFilename = generateExposeFilename;
800
- exports.generateShareFilename = generateShareFilename;
801
- exports.generateSnapshotFromManifest = generateSnapshotFromManifest;
802
- exports.getProcessEnv = getProcessEnv;
803
- exports.getResourceUrl = getResourceUrl;
804
- exports.inferAutoPublicPath = inferAutoPublicPath;
805
- exports.isBrowserEnv = isBrowserEnv;
806
- exports.isDebugMode = isDebugMode;
807
- exports.isManifestProvider = isManifestProvider;
808
- exports.isReactNativeEnv = isReactNativeEnv;
809
- exports.isRequiredVersion = isRequiredVersion;
810
- exports.isStaticResourcesEqual = isStaticResourcesEqual;
811
- exports.loadScript = loadScript;
812
- exports.loadScriptNode = loadScriptNode;
813
- exports.logger = logger;
814
- exports.moduleFederationPlugin = ModuleFederationPlugin;
815
- exports.normalizeOptions = normalizeOptions;
816
- exports.parseEntry = parseEntry;
817
- exports.safeToString = safeToString;
818
- exports.safeWrapper = safeWrapper;
819
- exports.sharePlugin = SharePlugin;
820
- exports.simpleJoinRemoteEntry = simpleJoinRemoteEntry;
821
- exports.warn = warn;