@module-federation/runtime-core 0.0.0-next-20241115035905

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 (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +13 -0
  3. package/dist/LICENSE +21 -0
  4. package/dist/index.cjs.d.ts +1 -0
  5. package/dist/index.cjs.js +3010 -0
  6. package/dist/index.esm.d.ts +1 -0
  7. package/dist/index.esm.js +2980 -0
  8. package/dist/package.json +42 -0
  9. package/dist/polyfills.cjs.js +28 -0
  10. package/dist/polyfills.esm.js +25 -0
  11. package/dist/src/constant.d.ts +2 -0
  12. package/dist/src/core.d.ts +105 -0
  13. package/dist/src/global.d.ts +42 -0
  14. package/dist/src/helpers.d.ts +31 -0
  15. package/dist/src/index.d.ts +14 -0
  16. package/dist/src/module/index.d.ts +21 -0
  17. package/dist/src/plugins/generate-preload-assets.d.ts +8 -0
  18. package/dist/src/plugins/snapshot/SnapshotHandler.d.ts +58 -0
  19. package/dist/src/plugins/snapshot/index.d.ts +5 -0
  20. package/dist/src/remote/index.d.ts +109 -0
  21. package/dist/src/shared/index.d.ts +66 -0
  22. package/dist/src/type/config.d.ts +112 -0
  23. package/dist/src/type/index.d.ts +3 -0
  24. package/dist/src/type/plugin.d.ts +34 -0
  25. package/dist/src/type/preload.d.ts +26 -0
  26. package/dist/src/types.d.ts +1 -0
  27. package/dist/src/utils/env.d.ts +3 -0
  28. package/dist/src/utils/hooks/asyncHook.d.ts +6 -0
  29. package/dist/src/utils/hooks/asyncWaterfallHooks.d.ts +10 -0
  30. package/dist/src/utils/hooks/index.d.ts +6 -0
  31. package/dist/src/utils/hooks/pluginSystem.d.ts +15 -0
  32. package/dist/src/utils/hooks/syncHook.d.ts +12 -0
  33. package/dist/src/utils/hooks/syncWaterfallHook.d.ts +9 -0
  34. package/dist/src/utils/index.d.ts +6 -0
  35. package/dist/src/utils/load.d.ts +9 -0
  36. package/dist/src/utils/logger.d.ts +6 -0
  37. package/dist/src/utils/manifest.d.ts +7 -0
  38. package/dist/src/utils/plugin.d.ts +4 -0
  39. package/dist/src/utils/preload.d.ts +6 -0
  40. package/dist/src/utils/semver/compare.d.ts +9 -0
  41. package/dist/src/utils/semver/constants.d.ts +10 -0
  42. package/dist/src/utils/semver/index.d.ts +2 -0
  43. package/dist/src/utils/semver/parser.d.ts +9 -0
  44. package/dist/src/utils/semver/utils.d.ts +11 -0
  45. package/dist/src/utils/share.d.ts +27 -0
  46. package/dist/src/utils/tool.d.ts +18 -0
  47. package/dist/types.cjs.d.ts +1 -0
  48. package/dist/types.cjs.js +2 -0
  49. package/dist/types.esm.d.ts +1 -0
  50. package/dist/types.esm.js +1 -0
  51. package/package.json +42 -0
@@ -0,0 +1,3010 @@
1
+ 'use strict';
2
+
3
+ var polyfills = require('./polyfills.cjs.js');
4
+ var sdk = require('@module-federation/sdk');
5
+ var errorCodes = require('@module-federation/error-codes');
6
+
7
+ const LOG_CATEGORY = '[ Federation Runtime ]';
8
+ // FIXME: pre-bundle ?
9
+ const logger = sdk.createLogger(LOG_CATEGORY);
10
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
11
+ function assert(condition, msg) {
12
+ if (!condition) {
13
+ error(msg);
14
+ }
15
+ }
16
+ function error(msg) {
17
+ if (msg instanceof Error) {
18
+ msg.message = `${LOG_CATEGORY}: ${msg.message}`;
19
+ throw msg;
20
+ }
21
+ throw new Error(`${LOG_CATEGORY}: ${msg}`);
22
+ }
23
+ function warn(msg) {
24
+ if (msg instanceof Error) {
25
+ msg.message = `${LOG_CATEGORY}: ${msg.message}`;
26
+ logger.warn(msg);
27
+ } else {
28
+ logger.warn(msg);
29
+ }
30
+ }
31
+
32
+ function addUniqueItem(arr, item) {
33
+ if (arr.findIndex((name)=>name === item) === -1) {
34
+ arr.push(item);
35
+ }
36
+ return arr;
37
+ }
38
+ function getFMId(remoteInfo) {
39
+ if ('version' in remoteInfo && remoteInfo.version) {
40
+ return `${remoteInfo.name}:${remoteInfo.version}`;
41
+ } else if ('entry' in remoteInfo && remoteInfo.entry) {
42
+ return `${remoteInfo.name}:${remoteInfo.entry}`;
43
+ } else {
44
+ return `${remoteInfo.name}`;
45
+ }
46
+ }
47
+ function isRemoteInfoWithEntry(remote) {
48
+ return typeof remote.entry !== 'undefined';
49
+ }
50
+ function isPureRemoteEntry(remote) {
51
+ return !remote.entry.includes('.json') && remote.entry.includes('.js');
52
+ }
53
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
54
+ async function safeWrapper(callback, disableWarn) {
55
+ try {
56
+ const res = await callback();
57
+ return res;
58
+ } catch (e) {
59
+ !disableWarn && warn(e);
60
+ return;
61
+ }
62
+ }
63
+ function isObject(val) {
64
+ return val && typeof val === 'object';
65
+ }
66
+ const objectToString = Object.prototype.toString;
67
+ // eslint-disable-next-line @typescript-eslint/ban-types
68
+ function isPlainObject(val) {
69
+ return objectToString.call(val) === '[object Object]';
70
+ }
71
+ function isStaticResourcesEqual(url1, url2) {
72
+ const REG_EXP = /^(https?:)?\/\//i;
73
+ // Transform url1 and url2 into relative paths
74
+ const relativeUrl1 = url1.replace(REG_EXP, '').replace(/\/$/, '');
75
+ const relativeUrl2 = url2.replace(REG_EXP, '').replace(/\/$/, '');
76
+ // Check if the relative paths are identical
77
+ return relativeUrl1 === relativeUrl2;
78
+ }
79
+ function arrayOptions(options) {
80
+ return Array.isArray(options) ? options : [
81
+ options
82
+ ];
83
+ }
84
+ function getRemoteEntryInfoFromSnapshot(snapshot) {
85
+ const defaultRemoteEntryInfo = {
86
+ url: '',
87
+ type: 'global',
88
+ globalName: ''
89
+ };
90
+ if (sdk.isBrowserEnv()) {
91
+ return 'remoteEntry' in snapshot ? {
92
+ url: snapshot.remoteEntry,
93
+ type: snapshot.remoteEntryType,
94
+ globalName: snapshot.globalName
95
+ } : defaultRemoteEntryInfo;
96
+ }
97
+ if ('ssrRemoteEntry' in snapshot) {
98
+ return {
99
+ url: snapshot.ssrRemoteEntry || defaultRemoteEntryInfo.url,
100
+ type: snapshot.ssrRemoteEntryType || defaultRemoteEntryInfo.type,
101
+ globalName: snapshot.globalName
102
+ };
103
+ }
104
+ return defaultRemoteEntryInfo;
105
+ }
106
+ const processModuleAlias = (name, subPath)=>{
107
+ // @host/ ./button -> @host/button
108
+ let moduleName;
109
+ if (name.endsWith('/')) {
110
+ moduleName = name.slice(0, -1);
111
+ } else {
112
+ moduleName = name;
113
+ }
114
+ if (subPath.startsWith('.')) {
115
+ subPath = subPath.slice(1);
116
+ }
117
+ moduleName = moduleName + subPath;
118
+ return moduleName;
119
+ };
120
+
121
+ const CurrentGlobal = typeof globalThis === 'object' ? globalThis : window;
122
+ const nativeGlobal = (()=>{
123
+ try {
124
+ // get real window (incase of sandbox)
125
+ return document.defaultView;
126
+ } catch (e) {
127
+ // node env
128
+ return CurrentGlobal;
129
+ }
130
+ })();
131
+ const Global = nativeGlobal;
132
+ function definePropertyGlobalVal(target, key, val) {
133
+ Object.defineProperty(target, key, {
134
+ value: val,
135
+ configurable: false,
136
+ writable: true
137
+ });
138
+ }
139
+ function includeOwnProperty(target, key) {
140
+ return Object.hasOwnProperty.call(target, key);
141
+ }
142
+ // This section is to prevent encapsulation by certain microfrontend frameworks. Due to reuse policies, sandbox escapes.
143
+ // The sandbox in the microfrontend does not replicate the value of 'configurable'.
144
+ // If there is no loading content on the global object, this section defines the loading object.
145
+ if (!includeOwnProperty(CurrentGlobal, '__GLOBAL_LOADING_REMOTE_ENTRY__')) {
146
+ definePropertyGlobalVal(CurrentGlobal, '__GLOBAL_LOADING_REMOTE_ENTRY__', {});
147
+ }
148
+ const globalLoading = CurrentGlobal.__GLOBAL_LOADING_REMOTE_ENTRY__;
149
+ function setGlobalDefaultVal(target) {
150
+ var _target___FEDERATION__, _target___FEDERATION__1, _target___FEDERATION__2, _target___FEDERATION__3, _target___FEDERATION__4, _target___FEDERATION__5;
151
+ if (includeOwnProperty(target, '__VMOK__') && !includeOwnProperty(target, '__FEDERATION__')) {
152
+ definePropertyGlobalVal(target, '__FEDERATION__', target.__VMOK__);
153
+ }
154
+ if (!includeOwnProperty(target, '__FEDERATION__')) {
155
+ definePropertyGlobalVal(target, '__FEDERATION__', {
156
+ __GLOBAL_PLUGIN__: [],
157
+ __INSTANCES__: [],
158
+ moduleInfo: {},
159
+ __SHARE__: {},
160
+ __MANIFEST_LOADING__: {},
161
+ __PRELOADED_MAP__: new Map()
162
+ });
163
+ definePropertyGlobalVal(target, '__VMOK__', target.__FEDERATION__);
164
+ }
165
+ var ___GLOBAL_PLUGIN__;
166
+ (___GLOBAL_PLUGIN__ = (_target___FEDERATION__ = target.__FEDERATION__).__GLOBAL_PLUGIN__) != null ? ___GLOBAL_PLUGIN__ : _target___FEDERATION__.__GLOBAL_PLUGIN__ = [];
167
+ var ___INSTANCES__;
168
+ (___INSTANCES__ = (_target___FEDERATION__1 = target.__FEDERATION__).__INSTANCES__) != null ? ___INSTANCES__ : _target___FEDERATION__1.__INSTANCES__ = [];
169
+ var _moduleInfo;
170
+ (_moduleInfo = (_target___FEDERATION__2 = target.__FEDERATION__).moduleInfo) != null ? _moduleInfo : _target___FEDERATION__2.moduleInfo = {};
171
+ var ___SHARE__;
172
+ (___SHARE__ = (_target___FEDERATION__3 = target.__FEDERATION__).__SHARE__) != null ? ___SHARE__ : _target___FEDERATION__3.__SHARE__ = {};
173
+ var ___MANIFEST_LOADING__;
174
+ (___MANIFEST_LOADING__ = (_target___FEDERATION__4 = target.__FEDERATION__).__MANIFEST_LOADING__) != null ? ___MANIFEST_LOADING__ : _target___FEDERATION__4.__MANIFEST_LOADING__ = {};
175
+ var ___PRELOADED_MAP__;
176
+ (___PRELOADED_MAP__ = (_target___FEDERATION__5 = target.__FEDERATION__).__PRELOADED_MAP__) != null ? ___PRELOADED_MAP__ : _target___FEDERATION__5.__PRELOADED_MAP__ = new Map();
177
+ }
178
+ setGlobalDefaultVal(CurrentGlobal);
179
+ setGlobalDefaultVal(nativeGlobal);
180
+ function resetFederationGlobalInfo() {
181
+ CurrentGlobal.__FEDERATION__.__GLOBAL_PLUGIN__ = [];
182
+ CurrentGlobal.__FEDERATION__.__INSTANCES__ = [];
183
+ CurrentGlobal.__FEDERATION__.moduleInfo = {};
184
+ CurrentGlobal.__FEDERATION__.__SHARE__ = {};
185
+ CurrentGlobal.__FEDERATION__.__MANIFEST_LOADING__ = {};
186
+ Object.keys(globalLoading).forEach((key)=>{
187
+ delete globalLoading[key];
188
+ });
189
+ }
190
+ function setGlobalFederationInstance(FederationInstance) {
191
+ CurrentGlobal.__FEDERATION__.__INSTANCES__.push(FederationInstance);
192
+ }
193
+ function getGlobalFederationConstructor() {
194
+ return CurrentGlobal.__FEDERATION__.__DEBUG_CONSTRUCTOR__;
195
+ }
196
+ function setGlobalFederationConstructor(FederationConstructor, isDebug = sdk.isDebugMode()) {
197
+ if (isDebug) {
198
+ CurrentGlobal.__FEDERATION__.__DEBUG_CONSTRUCTOR__ = FederationConstructor;
199
+ CurrentGlobal.__FEDERATION__.__DEBUG_CONSTRUCTOR_VERSION__ = "0.6.14";
200
+ }
201
+ }
202
+ // eslint-disable-next-line @typescript-eslint/ban-types
203
+ function getInfoWithoutType(target, key) {
204
+ if (typeof key === 'string') {
205
+ const keyRes = target[key];
206
+ if (keyRes) {
207
+ return {
208
+ value: target[key],
209
+ key: key
210
+ };
211
+ } else {
212
+ const targetKeys = Object.keys(target);
213
+ for (const targetKey of targetKeys){
214
+ const [targetTypeOrName, _] = targetKey.split(':');
215
+ const nKey = `${targetTypeOrName}:${key}`;
216
+ const typeWithKeyRes = target[nKey];
217
+ if (typeWithKeyRes) {
218
+ return {
219
+ value: typeWithKeyRes,
220
+ key: nKey
221
+ };
222
+ }
223
+ }
224
+ return {
225
+ value: undefined,
226
+ key: key
227
+ };
228
+ }
229
+ } else {
230
+ throw new Error('key must be string');
231
+ }
232
+ }
233
+ const getGlobalSnapshot = ()=>nativeGlobal.__FEDERATION__.moduleInfo;
234
+ const getTargetSnapshotInfoByModuleInfo = (moduleInfo, snapshot)=>{
235
+ // Check if the remote is included in the hostSnapshot
236
+ const moduleKey = getFMId(moduleInfo);
237
+ const getModuleInfo = getInfoWithoutType(snapshot, moduleKey).value;
238
+ // The remoteSnapshot might not include a version
239
+ if (getModuleInfo && !getModuleInfo.version && 'version' in moduleInfo && moduleInfo['version']) {
240
+ getModuleInfo.version = moduleInfo['version'];
241
+ }
242
+ if (getModuleInfo) {
243
+ return getModuleInfo;
244
+ }
245
+ // If the remote is not included in the hostSnapshot, deploy a micro app snapshot
246
+ if ('version' in moduleInfo && moduleInfo['version']) {
247
+ const { version } = moduleInfo, resModuleInfo = polyfills._object_without_properties_loose(moduleInfo, [
248
+ "version"
249
+ ]);
250
+ const moduleKeyWithoutVersion = getFMId(resModuleInfo);
251
+ const getModuleInfoWithoutVersion = getInfoWithoutType(nativeGlobal.__FEDERATION__.moduleInfo, moduleKeyWithoutVersion).value;
252
+ if ((getModuleInfoWithoutVersion == null ? void 0 : getModuleInfoWithoutVersion.version) === version) {
253
+ return getModuleInfoWithoutVersion;
254
+ }
255
+ }
256
+ return;
257
+ };
258
+ const getGlobalSnapshotInfoByModuleInfo = (moduleInfo)=>getTargetSnapshotInfoByModuleInfo(moduleInfo, nativeGlobal.__FEDERATION__.moduleInfo);
259
+ const setGlobalSnapshotInfoByModuleInfo = (remoteInfo, moduleDetailInfo)=>{
260
+ const moduleKey = getFMId(remoteInfo);
261
+ nativeGlobal.__FEDERATION__.moduleInfo[moduleKey] = moduleDetailInfo;
262
+ return nativeGlobal.__FEDERATION__.moduleInfo;
263
+ };
264
+ const addGlobalSnapshot = (moduleInfos)=>{
265
+ nativeGlobal.__FEDERATION__.moduleInfo = polyfills._extends({}, nativeGlobal.__FEDERATION__.moduleInfo, moduleInfos);
266
+ return ()=>{
267
+ const keys = Object.keys(moduleInfos);
268
+ for (const key of keys){
269
+ delete nativeGlobal.__FEDERATION__.moduleInfo[key];
270
+ }
271
+ };
272
+ };
273
+ const getRemoteEntryExports = (name, globalName)=>{
274
+ const remoteEntryKey = globalName || `__FEDERATION_${name}:custom__`;
275
+ const entryExports = CurrentGlobal[remoteEntryKey];
276
+ return {
277
+ remoteEntryKey,
278
+ entryExports
279
+ };
280
+ };
281
+ // This function is used to register global plugins.
282
+ // It iterates over the provided plugins and checks if they are already registered.
283
+ // If a plugin is not registered, it is added to the global plugins.
284
+ // If a plugin is already registered, a warning message is logged.
285
+ const registerGlobalPlugins = (plugins)=>{
286
+ const { __GLOBAL_PLUGIN__ } = nativeGlobal.__FEDERATION__;
287
+ plugins.forEach((plugin)=>{
288
+ if (__GLOBAL_PLUGIN__.findIndex((p)=>p.name === plugin.name) === -1) {
289
+ __GLOBAL_PLUGIN__.push(plugin);
290
+ } else {
291
+ warn(`The plugin ${plugin.name} has been registered.`);
292
+ }
293
+ });
294
+ };
295
+ const getGlobalHostPlugins = ()=>nativeGlobal.__FEDERATION__.__GLOBAL_PLUGIN__;
296
+ const getPreloaded = (id)=>CurrentGlobal.__FEDERATION__.__PRELOADED_MAP__.get(id);
297
+ const setPreloaded = (id)=>CurrentGlobal.__FEDERATION__.__PRELOADED_MAP__.set(id, true);
298
+
299
+ const DEFAULT_SCOPE = 'default';
300
+ const DEFAULT_REMOTE_TYPE = 'global';
301
+
302
+ // fork from https://github.com/originjs/vite-plugin-federation/blob/v1.1.12/packages/lib/src/utils/semver/index.ts
303
+ // those constants are based on https://www.rubydoc.info/gems/semantic_range/3.0.0/SemanticRange#BUILDIDENTIFIER-constant
304
+ // Copyright (c)
305
+ // vite-plugin-federation is licensed under Mulan PSL v2.
306
+ // You can use this software according to the terms and conditions of the Mulan PSL v2.
307
+ // You may obtain a copy of Mulan PSL v2 at:
308
+ // http://license.coscl.org.cn/MulanPSL2
309
+ // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
310
+ // See the Mulan PSL v2 for more details.
311
+ const buildIdentifier = '[0-9A-Za-z-]+';
312
+ const build = `(?:\\+(${buildIdentifier}(?:\\.${buildIdentifier})*))`;
313
+ const numericIdentifier = '0|[1-9]\\d*';
314
+ const numericIdentifierLoose = '[0-9]+';
315
+ const nonNumericIdentifier = '\\d*[a-zA-Z-][a-zA-Z0-9-]*';
316
+ const preReleaseIdentifierLoose = `(?:${numericIdentifierLoose}|${nonNumericIdentifier})`;
317
+ const preReleaseLoose = `(?:-?(${preReleaseIdentifierLoose}(?:\\.${preReleaseIdentifierLoose})*))`;
318
+ const preReleaseIdentifier = `(?:${numericIdentifier}|${nonNumericIdentifier})`;
319
+ const preRelease = `(?:-(${preReleaseIdentifier}(?:\\.${preReleaseIdentifier})*))`;
320
+ const xRangeIdentifier = `${numericIdentifier}|x|X|\\*`;
321
+ const xRangePlain = `[v=\\s]*(${xRangeIdentifier})(?:\\.(${xRangeIdentifier})(?:\\.(${xRangeIdentifier})(?:${preRelease})?${build}?)?)?`;
322
+ const hyphenRange = `^\\s*(${xRangePlain})\\s+-\\s+(${xRangePlain})\\s*$`;
323
+ const mainVersionLoose = `(${numericIdentifierLoose})\\.(${numericIdentifierLoose})\\.(${numericIdentifierLoose})`;
324
+ const loosePlain = `[v=\\s]*${mainVersionLoose}${preReleaseLoose}?${build}?`;
325
+ const gtlt = '((?:<|>)?=?)';
326
+ const comparatorTrim = `(\\s*)${gtlt}\\s*(${loosePlain}|${xRangePlain})`;
327
+ const loneTilde = '(?:~>?)';
328
+ const tildeTrim = `(\\s*)${loneTilde}\\s+`;
329
+ const loneCaret = '(?:\\^)';
330
+ const caretTrim = `(\\s*)${loneCaret}\\s+`;
331
+ const star = '(<|>)?=?\\s*\\*';
332
+ const caret = `^${loneCaret}${xRangePlain}$`;
333
+ const mainVersion = `(${numericIdentifier})\\.(${numericIdentifier})\\.(${numericIdentifier})`;
334
+ const fullPlain = `v?${mainVersion}${preRelease}?${build}?`;
335
+ const tilde = `^${loneTilde}${xRangePlain}$`;
336
+ const xRange = `^${gtlt}\\s*${xRangePlain}$`;
337
+ const comparator = `^${gtlt}\\s*(${fullPlain})$|^$`;
338
+ // copy from semver package
339
+ const gte0 = '^\\s*>=\\s*0.0.0\\s*$';
340
+
341
+ // fork from https://github.com/originjs/vite-plugin-federation/blob/v1.1.12/packages/lib/src/utils/semver/index.ts
342
+ // Copyright (c)
343
+ // vite-plugin-federation is licensed under Mulan PSL v2.
344
+ // You can use this software according to the terms and conditions of the Mulan PSL v2.
345
+ // You may obtain a copy of Mulan PSL v2 at:
346
+ // http://license.coscl.org.cn/MulanPSL2
347
+ // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
348
+ // See the Mulan PSL v2 for more details.
349
+ function parseRegex(source) {
350
+ return new RegExp(source);
351
+ }
352
+ function isXVersion(version) {
353
+ return !version || version.toLowerCase() === 'x' || version === '*';
354
+ }
355
+ function pipe(...fns) {
356
+ return (x)=>fns.reduce((v, f)=>f(v), x);
357
+ }
358
+ function extractComparator(comparatorString) {
359
+ return comparatorString.match(parseRegex(comparator));
360
+ }
361
+ function combineVersion(major, minor, patch, preRelease) {
362
+ const mainVersion = `${major}.${minor}.${patch}`;
363
+ if (preRelease) {
364
+ return `${mainVersion}-${preRelease}`;
365
+ }
366
+ return mainVersion;
367
+ }
368
+
369
+ // fork from https://github.com/originjs/vite-plugin-federation/blob/v1.1.12/packages/lib/src/utils/semver/index.ts
370
+ // Copyright (c)
371
+ // vite-plugin-federation is licensed under Mulan PSL v2.
372
+ // You can use this software according to the terms and conditions of the Mulan PSL v2.
373
+ // You may obtain a copy of Mulan PSL v2 at:
374
+ // http://license.coscl.org.cn/MulanPSL2
375
+ // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
376
+ // See the Mulan PSL v2 for more details.
377
+ function parseHyphen(range) {
378
+ return range.replace(parseRegex(hyphenRange), (_range, from, fromMajor, fromMinor, fromPatch, _fromPreRelease, _fromBuild, to, toMajor, toMinor, toPatch, toPreRelease)=>{
379
+ if (isXVersion(fromMajor)) {
380
+ from = '';
381
+ } else if (isXVersion(fromMinor)) {
382
+ from = `>=${fromMajor}.0.0`;
383
+ } else if (isXVersion(fromPatch)) {
384
+ from = `>=${fromMajor}.${fromMinor}.0`;
385
+ } else {
386
+ from = `>=${from}`;
387
+ }
388
+ if (isXVersion(toMajor)) {
389
+ to = '';
390
+ } else if (isXVersion(toMinor)) {
391
+ to = `<${Number(toMajor) + 1}.0.0-0`;
392
+ } else if (isXVersion(toPatch)) {
393
+ to = `<${toMajor}.${Number(toMinor) + 1}.0-0`;
394
+ } else if (toPreRelease) {
395
+ to = `<=${toMajor}.${toMinor}.${toPatch}-${toPreRelease}`;
396
+ } else {
397
+ to = `<=${to}`;
398
+ }
399
+ return `${from} ${to}`.trim();
400
+ });
401
+ }
402
+ function parseComparatorTrim(range) {
403
+ return range.replace(parseRegex(comparatorTrim), '$1$2$3');
404
+ }
405
+ function parseTildeTrim(range) {
406
+ return range.replace(parseRegex(tildeTrim), '$1~');
407
+ }
408
+ function parseCaretTrim(range) {
409
+ return range.replace(parseRegex(caretTrim), '$1^');
410
+ }
411
+ function parseCarets(range) {
412
+ return range.trim().split(/\s+/).map((rangeVersion)=>rangeVersion.replace(parseRegex(caret), (_, major, minor, patch, preRelease)=>{
413
+ if (isXVersion(major)) {
414
+ return '';
415
+ } else if (isXVersion(minor)) {
416
+ return `>=${major}.0.0 <${Number(major) + 1}.0.0-0`;
417
+ } else if (isXVersion(patch)) {
418
+ if (major === '0') {
419
+ return `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0-0`;
420
+ } else {
421
+ return `>=${major}.${minor}.0 <${Number(major) + 1}.0.0-0`;
422
+ }
423
+ } else if (preRelease) {
424
+ if (major === '0') {
425
+ if (minor === '0') {
426
+ return `>=${major}.${minor}.${patch}-${preRelease} <${major}.${minor}.${Number(patch) + 1}-0`;
427
+ } else {
428
+ return `>=${major}.${minor}.${patch}-${preRelease} <${major}.${Number(minor) + 1}.0-0`;
429
+ }
430
+ } else {
431
+ return `>=${major}.${minor}.${patch}-${preRelease} <${Number(major) + 1}.0.0-0`;
432
+ }
433
+ } else {
434
+ if (major === '0') {
435
+ if (minor === '0') {
436
+ return `>=${major}.${minor}.${patch} <${major}.${minor}.${Number(patch) + 1}-0`;
437
+ } else {
438
+ return `>=${major}.${minor}.${patch} <${major}.${Number(minor) + 1}.0-0`;
439
+ }
440
+ }
441
+ return `>=${major}.${minor}.${patch} <${Number(major) + 1}.0.0-0`;
442
+ }
443
+ })).join(' ');
444
+ }
445
+ function parseTildes(range) {
446
+ return range.trim().split(/\s+/).map((rangeVersion)=>rangeVersion.replace(parseRegex(tilde), (_, major, minor, patch, preRelease)=>{
447
+ if (isXVersion(major)) {
448
+ return '';
449
+ } else if (isXVersion(minor)) {
450
+ return `>=${major}.0.0 <${Number(major) + 1}.0.0-0`;
451
+ } else if (isXVersion(patch)) {
452
+ return `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0-0`;
453
+ } else if (preRelease) {
454
+ return `>=${major}.${minor}.${patch}-${preRelease} <${major}.${Number(minor) + 1}.0-0`;
455
+ }
456
+ return `>=${major}.${minor}.${patch} <${major}.${Number(minor) + 1}.0-0`;
457
+ })).join(' ');
458
+ }
459
+ function parseXRanges(range) {
460
+ return range.split(/\s+/).map((rangeVersion)=>rangeVersion.trim().replace(parseRegex(xRange), (ret, gtlt, major, minor, patch, preRelease)=>{
461
+ const isXMajor = isXVersion(major);
462
+ const isXMinor = isXMajor || isXVersion(minor);
463
+ const isXPatch = isXMinor || isXVersion(patch);
464
+ if (gtlt === '=' && isXPatch) {
465
+ gtlt = '';
466
+ }
467
+ preRelease = '';
468
+ if (isXMajor) {
469
+ if (gtlt === '>' || gtlt === '<') {
470
+ // nothing is allowed
471
+ return '<0.0.0-0';
472
+ } else {
473
+ // nothing is forbidden
474
+ return '*';
475
+ }
476
+ } else if (gtlt && isXPatch) {
477
+ // replace X with 0
478
+ if (isXMinor) {
479
+ minor = 0;
480
+ }
481
+ patch = 0;
482
+ if (gtlt === '>') {
483
+ // >1 => >=2.0.0
484
+ // >1.2 => >=1.3.0
485
+ gtlt = '>=';
486
+ if (isXMinor) {
487
+ major = Number(major) + 1;
488
+ minor = 0;
489
+ patch = 0;
490
+ } else {
491
+ minor = Number(minor) + 1;
492
+ patch = 0;
493
+ }
494
+ } else if (gtlt === '<=') {
495
+ // <=0.7.x is actually <0.8.0, since any 0.7.x should pass
496
+ // Similarly, <=7.x is actually <8.0.0, etc.
497
+ gtlt = '<';
498
+ if (isXMinor) {
499
+ major = Number(major) + 1;
500
+ } else {
501
+ minor = Number(minor) + 1;
502
+ }
503
+ }
504
+ if (gtlt === '<') {
505
+ preRelease = '-0';
506
+ }
507
+ return `${gtlt + major}.${minor}.${patch}${preRelease}`;
508
+ } else if (isXMinor) {
509
+ return `>=${major}.0.0${preRelease} <${Number(major) + 1}.0.0-0`;
510
+ } else if (isXPatch) {
511
+ return `>=${major}.${minor}.0${preRelease} <${major}.${Number(minor) + 1}.0-0`;
512
+ }
513
+ return ret;
514
+ })).join(' ');
515
+ }
516
+ function parseStar(range) {
517
+ return range.trim().replace(parseRegex(star), '');
518
+ }
519
+ function parseGTE0(comparatorString) {
520
+ return comparatorString.trim().replace(parseRegex(gte0), '');
521
+ }
522
+
523
+ // fork from https://github.com/originjs/vite-plugin-federation/blob/v1.1.12/packages/lib/src/utils/semver/index.ts
524
+ // Copyright (c)
525
+ // vite-plugin-federation is licensed under Mulan PSL v2.
526
+ // You can use this software according to the terms and conditions of the Mulan PSL v2.
527
+ // You may obtain a copy of Mulan PSL v2 at:
528
+ // http://license.coscl.org.cn/MulanPSL2
529
+ // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
530
+ // See the Mulan PSL v2 for more details.
531
+ function compareAtom(rangeAtom, versionAtom) {
532
+ rangeAtom = Number(rangeAtom) || rangeAtom;
533
+ versionAtom = Number(versionAtom) || versionAtom;
534
+ if (rangeAtom > versionAtom) {
535
+ return 1;
536
+ }
537
+ if (rangeAtom === versionAtom) {
538
+ return 0;
539
+ }
540
+ return -1;
541
+ }
542
+ function comparePreRelease(rangeAtom, versionAtom) {
543
+ const { preRelease: rangePreRelease } = rangeAtom;
544
+ const { preRelease: versionPreRelease } = versionAtom;
545
+ if (rangePreRelease === undefined && Boolean(versionPreRelease)) {
546
+ return 1;
547
+ }
548
+ if (Boolean(rangePreRelease) && versionPreRelease === undefined) {
549
+ return -1;
550
+ }
551
+ if (rangePreRelease === undefined && versionPreRelease === undefined) {
552
+ return 0;
553
+ }
554
+ for(let i = 0, n = rangePreRelease.length; i <= n; i++){
555
+ const rangeElement = rangePreRelease[i];
556
+ const versionElement = versionPreRelease[i];
557
+ if (rangeElement === versionElement) {
558
+ continue;
559
+ }
560
+ if (rangeElement === undefined && versionElement === undefined) {
561
+ return 0;
562
+ }
563
+ if (!rangeElement) {
564
+ return 1;
565
+ }
566
+ if (!versionElement) {
567
+ return -1;
568
+ }
569
+ return compareAtom(rangeElement, versionElement);
570
+ }
571
+ return 0;
572
+ }
573
+ function compareVersion(rangeAtom, versionAtom) {
574
+ return compareAtom(rangeAtom.major, versionAtom.major) || compareAtom(rangeAtom.minor, versionAtom.minor) || compareAtom(rangeAtom.patch, versionAtom.patch) || comparePreRelease(rangeAtom, versionAtom);
575
+ }
576
+ function eq(rangeAtom, versionAtom) {
577
+ return rangeAtom.version === versionAtom.version;
578
+ }
579
+ function compare(rangeAtom, versionAtom) {
580
+ switch(rangeAtom.operator){
581
+ case '':
582
+ case '=':
583
+ return eq(rangeAtom, versionAtom);
584
+ case '>':
585
+ return compareVersion(rangeAtom, versionAtom) < 0;
586
+ case '>=':
587
+ return eq(rangeAtom, versionAtom) || compareVersion(rangeAtom, versionAtom) < 0;
588
+ case '<':
589
+ return compareVersion(rangeAtom, versionAtom) > 0;
590
+ case '<=':
591
+ return eq(rangeAtom, versionAtom) || compareVersion(rangeAtom, versionAtom) > 0;
592
+ case undefined:
593
+ {
594
+ // mean * or x -> all versions
595
+ return true;
596
+ }
597
+ default:
598
+ return false;
599
+ }
600
+ }
601
+
602
+ // fork from https://github.com/originjs/vite-plugin-federation/blob/v1.1.12/packages/lib/src/utils/semver/index.ts
603
+ // Copyright (c)
604
+ // vite-plugin-federation is licensed under Mulan PSL v2.
605
+ // You can use this software according to the terms and conditions of the Mulan PSL v2.
606
+ // You may obtain a copy of Mulan PSL v2 at:
607
+ // http://license.coscl.org.cn/MulanPSL2
608
+ // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
609
+ // See the Mulan PSL v2 for more details.
610
+ function parseComparatorString(range) {
611
+ return pipe(// handle caret
612
+ // ^ --> * (any, kinda silly)
613
+ // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
614
+ // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
615
+ // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
616
+ // ^1.2.3 --> >=1.2.3 <2.0.0-0
617
+ // ^1.2.0 --> >=1.2.0 <2.0.0-0
618
+ parseCarets, // handle tilde
619
+ // ~, ~> --> * (any, kinda silly)
620
+ // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
621
+ // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
622
+ // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
623
+ // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
624
+ // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
625
+ parseTildes, parseXRanges, parseStar)(range);
626
+ }
627
+ function parseRange(range) {
628
+ return pipe(// handle hyphenRange
629
+ // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
630
+ parseHyphen, // handle trim comparator
631
+ // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
632
+ parseComparatorTrim, // handle trim tilde
633
+ // `~ 1.2.3` => `~1.2.3`
634
+ parseTildeTrim, // handle trim caret
635
+ // `^ 1.2.3` => `^1.2.3`
636
+ parseCaretTrim)(range.trim()).split(/\s+/).join(' ');
637
+ }
638
+ function satisfy(version, range) {
639
+ if (!version) {
640
+ return false;
641
+ }
642
+ const parsedRange = parseRange(range);
643
+ const parsedComparator = parsedRange.split(' ').map((rangeVersion)=>parseComparatorString(rangeVersion)).join(' ');
644
+ const comparators = parsedComparator.split(/\s+/).map((comparator)=>parseGTE0(comparator));
645
+ const extractedVersion = extractComparator(version);
646
+ if (!extractedVersion) {
647
+ return false;
648
+ }
649
+ const [, versionOperator, , versionMajor, versionMinor, versionPatch, versionPreRelease] = extractedVersion;
650
+ const versionAtom = {
651
+ operator: versionOperator,
652
+ version: combineVersion(versionMajor, versionMinor, versionPatch, versionPreRelease),
653
+ major: versionMajor,
654
+ minor: versionMinor,
655
+ patch: versionPatch,
656
+ preRelease: versionPreRelease == null ? void 0 : versionPreRelease.split('.')
657
+ };
658
+ for (const comparator of comparators){
659
+ const extractedComparator = extractComparator(comparator);
660
+ if (!extractedComparator) {
661
+ return false;
662
+ }
663
+ const [, rangeOperator, , rangeMajor, rangeMinor, rangePatch, rangePreRelease] = extractedComparator;
664
+ const rangeAtom = {
665
+ operator: rangeOperator,
666
+ version: combineVersion(rangeMajor, rangeMinor, rangePatch, rangePreRelease),
667
+ major: rangeMajor,
668
+ minor: rangeMinor,
669
+ patch: rangePatch,
670
+ preRelease: rangePreRelease == null ? void 0 : rangePreRelease.split('.')
671
+ };
672
+ if (!compare(rangeAtom, versionAtom)) {
673
+ return false; // early return
674
+ }
675
+ }
676
+ return true;
677
+ }
678
+
679
+ function formatShare(shareArgs, from, name, shareStrategy) {
680
+ let get;
681
+ if ('get' in shareArgs) {
682
+ // eslint-disable-next-line prefer-destructuring
683
+ get = shareArgs.get;
684
+ } else if ('lib' in shareArgs) {
685
+ get = ()=>Promise.resolve(shareArgs.lib);
686
+ } else {
687
+ get = ()=>Promise.resolve(()=>{
688
+ throw new Error(`Can not get shared '${name}'!`);
689
+ });
690
+ }
691
+ if (shareArgs.strategy) {
692
+ warn(`"shared.strategy is deprecated, please set in initOptions.shareStrategy instead!"`);
693
+ }
694
+ var _shareArgs_version, _shareArgs_scope, _shareArgs_strategy;
695
+ return polyfills._extends({
696
+ deps: [],
697
+ useIn: [],
698
+ from,
699
+ loading: null
700
+ }, shareArgs, {
701
+ shareConfig: polyfills._extends({
702
+ requiredVersion: `^${shareArgs.version}`,
703
+ singleton: false,
704
+ eager: false,
705
+ strictVersion: false
706
+ }, shareArgs.shareConfig),
707
+ get,
708
+ loaded: (shareArgs == null ? void 0 : shareArgs.loaded) || 'lib' in shareArgs ? true : undefined,
709
+ version: (_shareArgs_version = shareArgs.version) != null ? _shareArgs_version : '0',
710
+ scope: Array.isArray(shareArgs.scope) ? shareArgs.scope : [
711
+ (_shareArgs_scope = shareArgs.scope) != null ? _shareArgs_scope : 'default'
712
+ ],
713
+ strategy: ((_shareArgs_strategy = shareArgs.strategy) != null ? _shareArgs_strategy : shareStrategy) || 'version-first'
714
+ });
715
+ }
716
+ function formatShareConfigs(globalOptions, userOptions) {
717
+ const shareArgs = userOptions.shared || {};
718
+ const from = userOptions.name;
719
+ const shareInfos = Object.keys(shareArgs).reduce((res, pkgName)=>{
720
+ const arrayShareArgs = arrayOptions(shareArgs[pkgName]);
721
+ res[pkgName] = res[pkgName] || [];
722
+ arrayShareArgs.forEach((shareConfig)=>{
723
+ res[pkgName].push(formatShare(shareConfig, from, pkgName, userOptions.shareStrategy));
724
+ });
725
+ return res;
726
+ }, {});
727
+ const shared = polyfills._extends({}, globalOptions.shared);
728
+ Object.keys(shareInfos).forEach((shareKey)=>{
729
+ if (!shared[shareKey]) {
730
+ shared[shareKey] = shareInfos[shareKey];
731
+ } else {
732
+ shareInfos[shareKey].forEach((newUserSharedOptions)=>{
733
+ const isSameVersion = shared[shareKey].find((sharedVal)=>sharedVal.version === newUserSharedOptions.version);
734
+ if (!isSameVersion) {
735
+ shared[shareKey].push(newUserSharedOptions);
736
+ }
737
+ });
738
+ }
739
+ });
740
+ return {
741
+ shared,
742
+ shareInfos
743
+ };
744
+ }
745
+ function versionLt(a, b) {
746
+ const transformInvalidVersion = (version)=>{
747
+ const isNumberVersion = !Number.isNaN(Number(version));
748
+ if (isNumberVersion) {
749
+ const splitArr = version.split('.');
750
+ let validVersion = version;
751
+ for(let i = 0; i < 3 - splitArr.length; i++){
752
+ validVersion += '.0';
753
+ }
754
+ return validVersion;
755
+ }
756
+ return version;
757
+ };
758
+ if (satisfy(transformInvalidVersion(a), `<=${transformInvalidVersion(b)}`)) {
759
+ return true;
760
+ } else {
761
+ return false;
762
+ }
763
+ }
764
+ const findVersion = (shareVersionMap, cb)=>{
765
+ const callback = cb || function(prev, cur) {
766
+ return versionLt(prev, cur);
767
+ };
768
+ return Object.keys(shareVersionMap).reduce((prev, cur)=>{
769
+ if (!prev) {
770
+ return cur;
771
+ }
772
+ if (callback(prev, cur)) {
773
+ return cur;
774
+ }
775
+ // default version is '0' https://github.com/webpack/webpack/blob/main/lib/sharing/ProvideSharedModule.js#L136
776
+ if (prev === '0') {
777
+ return cur;
778
+ }
779
+ return prev;
780
+ }, 0);
781
+ };
782
+ const isLoaded = (shared)=>{
783
+ return Boolean(shared.loaded) || typeof shared.lib === 'function';
784
+ };
785
+ const isLoading = (shared)=>{
786
+ return Boolean(shared.loading);
787
+ };
788
+ function findSingletonVersionOrderByVersion(shareScopeMap, scope, pkgName) {
789
+ const versions = shareScopeMap[scope][pkgName];
790
+ const callback = function(prev, cur) {
791
+ return !isLoaded(versions[prev]) && versionLt(prev, cur);
792
+ };
793
+ return findVersion(shareScopeMap[scope][pkgName], callback);
794
+ }
795
+ function findSingletonVersionOrderByLoaded(shareScopeMap, scope, pkgName) {
796
+ const versions = shareScopeMap[scope][pkgName];
797
+ const callback = function(prev, cur) {
798
+ const isLoadingOrLoaded = (shared)=>{
799
+ return isLoaded(shared) || isLoading(shared);
800
+ };
801
+ if (isLoadingOrLoaded(versions[cur])) {
802
+ if (isLoadingOrLoaded(versions[prev])) {
803
+ return Boolean(versionLt(prev, cur));
804
+ } else {
805
+ return true;
806
+ }
807
+ }
808
+ if (isLoadingOrLoaded(versions[prev])) {
809
+ return false;
810
+ }
811
+ return versionLt(prev, cur);
812
+ };
813
+ return findVersion(shareScopeMap[scope][pkgName], callback);
814
+ }
815
+ function getFindShareFunction(strategy) {
816
+ if (strategy === 'loaded-first') {
817
+ return findSingletonVersionOrderByLoaded;
818
+ }
819
+ return findSingletonVersionOrderByVersion;
820
+ }
821
+ function getRegisteredShare(localShareScopeMap, pkgName, shareInfo, resolveShare) {
822
+ if (!localShareScopeMap) {
823
+ return;
824
+ }
825
+ const { shareConfig, scope = DEFAULT_SCOPE, strategy } = shareInfo;
826
+ const scopes = Array.isArray(scope) ? scope : [
827
+ scope
828
+ ];
829
+ for (const sc of scopes){
830
+ if (shareConfig && localShareScopeMap[sc] && localShareScopeMap[sc][pkgName]) {
831
+ const { requiredVersion } = shareConfig;
832
+ const findShareFunction = getFindShareFunction(strategy);
833
+ const maxOrSingletonVersion = findShareFunction(localShareScopeMap, sc, pkgName);
834
+ //@ts-ignore
835
+ const defaultResolver = ()=>{
836
+ if (shareConfig.singleton) {
837
+ if (typeof requiredVersion === 'string' && !satisfy(maxOrSingletonVersion, requiredVersion)) {
838
+ const msg = `Version ${maxOrSingletonVersion} from ${maxOrSingletonVersion && localShareScopeMap[sc][pkgName][maxOrSingletonVersion].from} of shared singleton module ${pkgName} does not satisfy the requirement of ${shareInfo.from} which needs ${requiredVersion})`;
839
+ if (shareConfig.strictVersion) {
840
+ error(msg);
841
+ } else {
842
+ warn(msg);
843
+ }
844
+ }
845
+ return localShareScopeMap[sc][pkgName][maxOrSingletonVersion];
846
+ } else {
847
+ if (requiredVersion === false || requiredVersion === '*') {
848
+ return localShareScopeMap[sc][pkgName][maxOrSingletonVersion];
849
+ }
850
+ if (satisfy(maxOrSingletonVersion, requiredVersion)) {
851
+ return localShareScopeMap[sc][pkgName][maxOrSingletonVersion];
852
+ }
853
+ for (const [versionKey, versionValue] of Object.entries(localShareScopeMap[sc][pkgName])){
854
+ if (satisfy(versionKey, requiredVersion)) {
855
+ return versionValue;
856
+ }
857
+ }
858
+ }
859
+ };
860
+ const params = {
861
+ shareScopeMap: localShareScopeMap,
862
+ scope: sc,
863
+ pkgName,
864
+ version: maxOrSingletonVersion,
865
+ GlobalFederation: Global.__FEDERATION__,
866
+ resolver: defaultResolver
867
+ };
868
+ const resolveShared = resolveShare.emit(params) || params;
869
+ return resolveShared.resolver();
870
+ }
871
+ }
872
+ }
873
+ function getGlobalShareScope() {
874
+ return Global.__FEDERATION__.__SHARE__;
875
+ }
876
+ function getTargetSharedOptions(options) {
877
+ const { pkgName, extraOptions, shareInfos } = options;
878
+ const defaultResolver = (sharedOptions)=>{
879
+ if (!sharedOptions) {
880
+ return undefined;
881
+ }
882
+ const shareVersionMap = {};
883
+ sharedOptions.forEach((shared)=>{
884
+ shareVersionMap[shared.version] = shared;
885
+ });
886
+ const callback = function(prev, cur) {
887
+ return !isLoaded(shareVersionMap[prev]) && versionLt(prev, cur);
888
+ };
889
+ const maxVersion = findVersion(shareVersionMap, callback);
890
+ return shareVersionMap[maxVersion];
891
+ };
892
+ var _extraOptions_resolver;
893
+ const resolver = (_extraOptions_resolver = extraOptions == null ? void 0 : extraOptions.resolver) != null ? _extraOptions_resolver : defaultResolver;
894
+ return Object.assign({}, resolver(shareInfos[pkgName]), extraOptions == null ? void 0 : extraOptions.customShareInfo);
895
+ }
896
+
897
+ const ShareUtils = {
898
+ getRegisteredShare,
899
+ getGlobalShareScope
900
+ };
901
+ const GlobalUtils = {
902
+ Global,
903
+ nativeGlobal,
904
+ resetFederationGlobalInfo,
905
+ setGlobalFederationInstance,
906
+ getGlobalFederationConstructor,
907
+ setGlobalFederationConstructor,
908
+ getInfoWithoutType,
909
+ getGlobalSnapshot,
910
+ getTargetSnapshotInfoByModuleInfo,
911
+ getGlobalSnapshotInfoByModuleInfo,
912
+ setGlobalSnapshotInfoByModuleInfo,
913
+ addGlobalSnapshot,
914
+ getRemoteEntryExports,
915
+ registerGlobalPlugins,
916
+ getGlobalHostPlugins,
917
+ getPreloaded,
918
+ setPreloaded
919
+ };
920
+ var helpers = {
921
+ global: GlobalUtils,
922
+ share: ShareUtils
923
+ };
924
+
925
+ function getBuilderId() {
926
+ //@ts-ignore
927
+ return typeof FEDERATION_BUILD_IDENTIFIER !== 'undefined' ? FEDERATION_BUILD_IDENTIFIER : '';
928
+ }
929
+
930
+ // Function to match a remote with its name and expose
931
+ // id: pkgName(@federation/app1) + expose(button) = @federation/app1/button
932
+ // id: alias(app1) + expose(button) = app1/button
933
+ // id: alias(app1/utils) + expose(loadash/sort) = app1/utils/loadash/sort
934
+ function matchRemoteWithNameAndExpose(remotes, id) {
935
+ for (const remote of remotes){
936
+ // match pkgName
937
+ const isNameMatched = id.startsWith(remote.name);
938
+ let expose = id.replace(remote.name, '');
939
+ if (isNameMatched) {
940
+ if (expose.startsWith('/')) {
941
+ const pkgNameOrAlias = remote.name;
942
+ expose = `.${expose}`;
943
+ return {
944
+ pkgNameOrAlias,
945
+ expose,
946
+ remote
947
+ };
948
+ } else if (expose === '') {
949
+ return {
950
+ pkgNameOrAlias: remote.name,
951
+ expose: '.',
952
+ remote
953
+ };
954
+ }
955
+ }
956
+ // match alias
957
+ const isAliasMatched = remote.alias && id.startsWith(remote.alias);
958
+ let exposeWithAlias = remote.alias && id.replace(remote.alias, '');
959
+ if (remote.alias && isAliasMatched) {
960
+ if (exposeWithAlias && exposeWithAlias.startsWith('/')) {
961
+ const pkgNameOrAlias = remote.alias;
962
+ exposeWithAlias = `.${exposeWithAlias}`;
963
+ return {
964
+ pkgNameOrAlias,
965
+ expose: exposeWithAlias,
966
+ remote
967
+ };
968
+ } else if (exposeWithAlias === '') {
969
+ return {
970
+ pkgNameOrAlias: remote.alias,
971
+ expose: '.',
972
+ remote
973
+ };
974
+ }
975
+ }
976
+ }
977
+ return;
978
+ }
979
+ // Function to match a remote with its name or alias
980
+ function matchRemote(remotes, nameOrAlias) {
981
+ for (const remote of remotes){
982
+ const isNameMatched = nameOrAlias === remote.name;
983
+ if (isNameMatched) {
984
+ return remote;
985
+ }
986
+ const isAliasMatched = remote.alias && nameOrAlias === remote.alias;
987
+ if (isAliasMatched) {
988
+ return remote;
989
+ }
990
+ }
991
+ return;
992
+ }
993
+
994
+ function registerPlugins(plugins, hookInstances) {
995
+ const globalPlugins = getGlobalHostPlugins();
996
+ // Incorporate global plugins
997
+ if (globalPlugins.length > 0) {
998
+ globalPlugins.forEach((plugin)=>{
999
+ if (plugins == null ? void 0 : plugins.find((item)=>item.name !== plugin.name)) {
1000
+ plugins.push(plugin);
1001
+ }
1002
+ });
1003
+ }
1004
+ if (plugins && plugins.length > 0) {
1005
+ plugins.forEach((plugin)=>{
1006
+ hookInstances.forEach((hookInstance)=>{
1007
+ hookInstance.applyPlugin(plugin);
1008
+ });
1009
+ });
1010
+ }
1011
+ return plugins;
1012
+ }
1013
+
1014
+ async function loadEsmEntry({ entry, remoteEntryExports }) {
1015
+ return new Promise((resolve, reject)=>{
1016
+ try {
1017
+ if (!remoteEntryExports) {
1018
+ import(/* webpackIgnore: true */ entry).then(resolve).catch(reject);
1019
+ } else {
1020
+ resolve(remoteEntryExports);
1021
+ }
1022
+ } catch (e) {
1023
+ reject(e);
1024
+ }
1025
+ });
1026
+ }
1027
+ async function loadSystemJsEntry({ entry, remoteEntryExports }) {
1028
+ return new Promise((resolve, reject)=>{
1029
+ try {
1030
+ if (!remoteEntryExports) {
1031
+ //@ts-ignore
1032
+ if (typeof __system_context__ === 'undefined') {
1033
+ //@ts-ignore
1034
+ System.import(entry).then(resolve).catch(reject);
1035
+ } else {
1036
+ new Function('callbacks', `System.import("${entry}").then(callbacks[0]).catch(callbacks[1])`)([
1037
+ resolve,
1038
+ reject
1039
+ ]);
1040
+ }
1041
+ } else {
1042
+ resolve(remoteEntryExports);
1043
+ }
1044
+ } catch (e) {
1045
+ reject(e);
1046
+ }
1047
+ });
1048
+ }
1049
+ async function loadEntryScript({ name, globalName, entry, loaderHook }) {
1050
+ const { entryExports: remoteEntryExports } = getRemoteEntryExports(name, globalName);
1051
+ if (remoteEntryExports) {
1052
+ return remoteEntryExports;
1053
+ }
1054
+ return sdk.loadScript(entry, {
1055
+ attrs: {},
1056
+ createScriptHook: (url, attrs)=>{
1057
+ const res = loaderHook.lifecycle.createScript.emit({
1058
+ url,
1059
+ attrs
1060
+ });
1061
+ if (!res) return;
1062
+ if (res instanceof HTMLScriptElement) {
1063
+ return res;
1064
+ }
1065
+ if ('script' in res || 'timeout' in res) {
1066
+ return res;
1067
+ }
1068
+ return;
1069
+ }
1070
+ }).then(()=>{
1071
+ const { remoteEntryKey, entryExports } = getRemoteEntryExports(name, globalName);
1072
+ assert(entryExports, errorCodes.getShortErrorMsg(errorCodes.RUNTIME_001, errorCodes.runtimeDescMap, {
1073
+ remoteName: name,
1074
+ remoteEntryUrl: entry,
1075
+ remoteEntryKey
1076
+ }));
1077
+ return entryExports;
1078
+ }).catch((e)=>{
1079
+ throw e;
1080
+ });
1081
+ }
1082
+ async function loadEntryDom({ remoteInfo, remoteEntryExports, loaderHook }) {
1083
+ const { entry, entryGlobalName: globalName, name, type } = remoteInfo;
1084
+ switch(type){
1085
+ case 'esm':
1086
+ case 'module':
1087
+ return loadEsmEntry({
1088
+ entry,
1089
+ remoteEntryExports
1090
+ });
1091
+ case 'system':
1092
+ return loadSystemJsEntry({
1093
+ entry,
1094
+ remoteEntryExports
1095
+ });
1096
+ default:
1097
+ return loadEntryScript({
1098
+ entry,
1099
+ globalName,
1100
+ name,
1101
+ loaderHook
1102
+ });
1103
+ }
1104
+ }
1105
+ async function loadEntryNode({ remoteInfo, loaderHook }) {
1106
+ const { entry, entryGlobalName: globalName, name, type } = remoteInfo;
1107
+ const { entryExports: remoteEntryExports } = getRemoteEntryExports(name, globalName);
1108
+ if (remoteEntryExports) {
1109
+ return remoteEntryExports;
1110
+ }
1111
+ return sdk.loadScriptNode(entry, {
1112
+ attrs: {
1113
+ name,
1114
+ globalName,
1115
+ type
1116
+ },
1117
+ loaderHook: {
1118
+ createScriptHook: (url, attrs = {})=>{
1119
+ const res = loaderHook.lifecycle.createScript.emit({
1120
+ url,
1121
+ attrs
1122
+ });
1123
+ if (!res) return;
1124
+ if ('url' in res) {
1125
+ return res;
1126
+ }
1127
+ return;
1128
+ }
1129
+ }
1130
+ }).then(()=>{
1131
+ const { remoteEntryKey, entryExports } = getRemoteEntryExports(name, globalName);
1132
+ assert(entryExports, errorCodes.getShortErrorMsg(errorCodes.RUNTIME_001, errorCodes.runtimeDescMap, {
1133
+ remoteName: name,
1134
+ remoteEntryUrl: entry,
1135
+ remoteEntryKey
1136
+ }));
1137
+ return entryExports;
1138
+ }).catch((e)=>{
1139
+ throw e;
1140
+ });
1141
+ }
1142
+ function getRemoteEntryUniqueKey(remoteInfo) {
1143
+ const { entry, name } = remoteInfo;
1144
+ return sdk.composeKeyWithSeparator(name, entry);
1145
+ }
1146
+ async function getRemoteEntry({ origin, remoteEntryExports, remoteInfo }) {
1147
+ const uniqueKey = getRemoteEntryUniqueKey(remoteInfo);
1148
+ if (remoteEntryExports) {
1149
+ return remoteEntryExports;
1150
+ }
1151
+ if (!globalLoading[uniqueKey]) {
1152
+ const loadEntryHook = origin.remoteHandler.hooks.lifecycle.loadEntry;
1153
+ origin.loaderHook.lifecycle.createScript;
1154
+ const loaderHook = origin.loaderHook;
1155
+ globalLoading[uniqueKey] = loadEntryHook.emit({
1156
+ loaderHook,
1157
+ remoteInfo,
1158
+ remoteEntryExports
1159
+ }).then((res)=>{
1160
+ if (res) {
1161
+ return res;
1162
+ }
1163
+ return sdk.isBrowserEnv() ? loadEntryDom({
1164
+ remoteInfo,
1165
+ remoteEntryExports,
1166
+ loaderHook
1167
+ }) : loadEntryNode({
1168
+ remoteInfo,
1169
+ loaderHook
1170
+ });
1171
+ });
1172
+ }
1173
+ return globalLoading[uniqueKey];
1174
+ }
1175
+ function getRemoteInfo(remote) {
1176
+ return polyfills._extends({}, remote, {
1177
+ entry: 'entry' in remote ? remote.entry : '',
1178
+ type: remote.type || DEFAULT_REMOTE_TYPE,
1179
+ entryGlobalName: remote.entryGlobalName || remote.name,
1180
+ shareScope: remote.shareScope || DEFAULT_SCOPE
1181
+ });
1182
+ }
1183
+
1184
+ let Module = class Module {
1185
+ async getEntry() {
1186
+ if (this.remoteEntryExports) {
1187
+ return this.remoteEntryExports;
1188
+ }
1189
+ // Get remoteEntry.js
1190
+ const remoteEntryExports = await getRemoteEntry({
1191
+ origin: this.host,
1192
+ remoteInfo: this.remoteInfo,
1193
+ remoteEntryExports: this.remoteEntryExports
1194
+ });
1195
+ assert(remoteEntryExports, `remoteEntryExports is undefined \n ${sdk.safeToString(this.remoteInfo)}`);
1196
+ this.remoteEntryExports = remoteEntryExports;
1197
+ return this.remoteEntryExports;
1198
+ }
1199
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
1200
+ async get(id, expose, options, remoteSnapshot) {
1201
+ const { loadFactory = true } = options || {
1202
+ loadFactory: true
1203
+ };
1204
+ // Get remoteEntry.js
1205
+ const remoteEntryExports = await this.getEntry();
1206
+ if (!this.inited) {
1207
+ const localShareScopeMap = this.host.shareScopeMap;
1208
+ const remoteShareScope = this.remoteInfo.shareScope || 'default';
1209
+ if (!localShareScopeMap[remoteShareScope]) {
1210
+ localShareScopeMap[remoteShareScope] = {};
1211
+ }
1212
+ const shareScope = localShareScopeMap[remoteShareScope];
1213
+ const initScope = [];
1214
+ const remoteEntryInitOptions = {
1215
+ version: this.remoteInfo.version || ''
1216
+ };
1217
+ // Help to find host instance
1218
+ Object.defineProperty(remoteEntryInitOptions, 'shareScopeMap', {
1219
+ value: localShareScopeMap,
1220
+ // remoteEntryInitOptions will be traversed and assigned during container init, ,so this attribute is not allowed to be traversed
1221
+ enumerable: false
1222
+ });
1223
+ const initContainerOptions = await this.host.hooks.lifecycle.beforeInitContainer.emit({
1224
+ shareScope,
1225
+ // @ts-ignore shareScopeMap will be set by Object.defineProperty
1226
+ remoteEntryInitOptions,
1227
+ initScope,
1228
+ remoteInfo: this.remoteInfo,
1229
+ origin: this.host
1230
+ });
1231
+ if (typeof (remoteEntryExports == null ? void 0 : remoteEntryExports.init) === 'undefined') {
1232
+ error(errorCodes.getShortErrorMsg(errorCodes.RUNTIME_002, errorCodes.runtimeDescMap, {
1233
+ remoteName: name,
1234
+ remoteEntryUrl: this.remoteInfo.entry,
1235
+ remoteEntryKey: this.remoteInfo.entryGlobalName
1236
+ }));
1237
+ }
1238
+ await remoteEntryExports.init(initContainerOptions.shareScope, initContainerOptions.initScope, initContainerOptions.remoteEntryInitOptions);
1239
+ await this.host.hooks.lifecycle.initContainer.emit(polyfills._extends({}, initContainerOptions, {
1240
+ id,
1241
+ remoteSnapshot,
1242
+ remoteEntryExports
1243
+ }));
1244
+ }
1245
+ this.lib = remoteEntryExports;
1246
+ this.inited = true;
1247
+ let moduleFactory;
1248
+ moduleFactory = await this.host.loaderHook.lifecycle.getModuleFactory.emit({
1249
+ remoteEntryExports,
1250
+ expose,
1251
+ moduleInfo: this.remoteInfo
1252
+ });
1253
+ // get exposeGetter
1254
+ if (!moduleFactory) {
1255
+ moduleFactory = await remoteEntryExports.get(expose);
1256
+ }
1257
+ assert(moduleFactory, `${getFMId(this.remoteInfo)} remote don't export ${expose}.`);
1258
+ // keep symbol for module name always one format
1259
+ const symbolName = processModuleAlias(this.remoteInfo.name, expose);
1260
+ const wrapModuleFactory = this.wraperFactory(moduleFactory, symbolName);
1261
+ if (!loadFactory) {
1262
+ return wrapModuleFactory;
1263
+ }
1264
+ const exposeContent = await wrapModuleFactory();
1265
+ return exposeContent;
1266
+ }
1267
+ wraperFactory(moduleFactory, id) {
1268
+ function defineModuleId(res, id) {
1269
+ if (res && typeof res === 'object' && Object.isExtensible(res) && !Object.getOwnPropertyDescriptor(res, Symbol.for('mf_module_id'))) {
1270
+ Object.defineProperty(res, Symbol.for('mf_module_id'), {
1271
+ value: id,
1272
+ enumerable: false
1273
+ });
1274
+ }
1275
+ }
1276
+ if (moduleFactory instanceof Promise) {
1277
+ return async ()=>{
1278
+ const res = await moduleFactory();
1279
+ // This parameter is used for bridge debugging
1280
+ defineModuleId(res, id);
1281
+ return res;
1282
+ };
1283
+ } else {
1284
+ return ()=>{
1285
+ const res = moduleFactory();
1286
+ // This parameter is used for bridge debugging
1287
+ defineModuleId(res, id);
1288
+ return res;
1289
+ };
1290
+ }
1291
+ }
1292
+ constructor({ remoteInfo, host }){
1293
+ this.inited = false;
1294
+ this.lib = undefined;
1295
+ this.remoteInfo = remoteInfo;
1296
+ this.host = host;
1297
+ }
1298
+ };
1299
+
1300
+ class SyncHook {
1301
+ on(fn) {
1302
+ if (typeof fn === 'function') {
1303
+ this.listeners.add(fn);
1304
+ }
1305
+ }
1306
+ once(fn) {
1307
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
1308
+ const self = this;
1309
+ this.on(function wrapper(...args) {
1310
+ self.remove(wrapper);
1311
+ // eslint-disable-next-line prefer-spread
1312
+ return fn.apply(null, args);
1313
+ });
1314
+ }
1315
+ emit(...data) {
1316
+ let result;
1317
+ if (this.listeners.size > 0) {
1318
+ // eslint-disable-next-line prefer-spread
1319
+ this.listeners.forEach((fn)=>{
1320
+ result = fn(...data);
1321
+ });
1322
+ }
1323
+ return result;
1324
+ }
1325
+ remove(fn) {
1326
+ this.listeners.delete(fn);
1327
+ }
1328
+ removeAll() {
1329
+ this.listeners.clear();
1330
+ }
1331
+ constructor(type){
1332
+ this.type = '';
1333
+ this.listeners = new Set();
1334
+ if (type) {
1335
+ this.type = type;
1336
+ }
1337
+ }
1338
+ }
1339
+
1340
+ class AsyncHook extends SyncHook {
1341
+ emit(...data) {
1342
+ let result;
1343
+ const ls = Array.from(this.listeners);
1344
+ if (ls.length > 0) {
1345
+ let i = 0;
1346
+ const call = (prev)=>{
1347
+ if (prev === false) {
1348
+ return false; // Abort process
1349
+ } else if (i < ls.length) {
1350
+ return Promise.resolve(ls[i++].apply(null, data)).then(call);
1351
+ } else {
1352
+ return prev;
1353
+ }
1354
+ };
1355
+ result = call();
1356
+ }
1357
+ return Promise.resolve(result);
1358
+ }
1359
+ }
1360
+
1361
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
1362
+ function checkReturnData(originalData, returnedData) {
1363
+ if (!isObject(returnedData)) {
1364
+ return false;
1365
+ }
1366
+ if (originalData !== returnedData) {
1367
+ // eslint-disable-next-line no-restricted-syntax
1368
+ for(const key in originalData){
1369
+ if (!(key in returnedData)) {
1370
+ return false;
1371
+ }
1372
+ }
1373
+ }
1374
+ return true;
1375
+ }
1376
+ class SyncWaterfallHook extends SyncHook {
1377
+ emit(data) {
1378
+ if (!isObject(data)) {
1379
+ error(`The data for the "${this.type}" hook should be an object.`);
1380
+ }
1381
+ for (const fn of this.listeners){
1382
+ try {
1383
+ const tempData = fn(data);
1384
+ if (checkReturnData(data, tempData)) {
1385
+ data = tempData;
1386
+ } else {
1387
+ this.onerror(`A plugin returned an unacceptable value for the "${this.type}" type.`);
1388
+ break;
1389
+ }
1390
+ } catch (e) {
1391
+ warn(e);
1392
+ this.onerror(e);
1393
+ }
1394
+ }
1395
+ return data;
1396
+ }
1397
+ constructor(type){
1398
+ super(), this.onerror = error;
1399
+ this.type = type;
1400
+ }
1401
+ }
1402
+
1403
+ class AsyncWaterfallHook extends SyncHook {
1404
+ emit(data) {
1405
+ if (!isObject(data)) {
1406
+ error(`The response data for the "${this.type}" hook must be an object.`);
1407
+ }
1408
+ const ls = Array.from(this.listeners);
1409
+ if (ls.length > 0) {
1410
+ let i = 0;
1411
+ const processError = (e)=>{
1412
+ warn(e);
1413
+ this.onerror(e);
1414
+ return data;
1415
+ };
1416
+ const call = (prevData)=>{
1417
+ if (checkReturnData(data, prevData)) {
1418
+ data = prevData;
1419
+ if (i < ls.length) {
1420
+ try {
1421
+ return Promise.resolve(ls[i++](data)).then(call, processError);
1422
+ } catch (e) {
1423
+ return processError(e);
1424
+ }
1425
+ }
1426
+ } else {
1427
+ this.onerror(`A plugin returned an incorrect value for the "${this.type}" type.`);
1428
+ }
1429
+ return data;
1430
+ };
1431
+ return Promise.resolve(call(data));
1432
+ }
1433
+ return Promise.resolve(data);
1434
+ }
1435
+ constructor(type){
1436
+ super(), this.onerror = error;
1437
+ this.type = type;
1438
+ }
1439
+ }
1440
+
1441
+ class PluginSystem {
1442
+ applyPlugin(plugin) {
1443
+ assert(isPlainObject(plugin), 'Plugin configuration is invalid.');
1444
+ // The plugin's name is mandatory and must be unique
1445
+ const pluginName = plugin.name;
1446
+ assert(pluginName, 'A name must be provided by the plugin.');
1447
+ if (!this.registerPlugins[pluginName]) {
1448
+ this.registerPlugins[pluginName] = plugin;
1449
+ Object.keys(this.lifecycle).forEach((key)=>{
1450
+ const pluginLife = plugin[key];
1451
+ if (pluginLife) {
1452
+ this.lifecycle[key].on(pluginLife);
1453
+ }
1454
+ });
1455
+ }
1456
+ }
1457
+ removePlugin(pluginName) {
1458
+ assert(pluginName, 'A name is required.');
1459
+ const plugin = this.registerPlugins[pluginName];
1460
+ assert(plugin, `The plugin "${pluginName}" is not registered.`);
1461
+ Object.keys(plugin).forEach((key)=>{
1462
+ if (key !== 'name') {
1463
+ this.lifecycle[key].remove(plugin[key]);
1464
+ }
1465
+ });
1466
+ }
1467
+ // eslint-disable-next-line @typescript-eslint/no-shadow
1468
+ inherit({ lifecycle, registerPlugins }) {
1469
+ Object.keys(lifecycle).forEach((hookName)=>{
1470
+ assert(!this.lifecycle[hookName], `The hook "${hookName}" has a conflict and cannot be inherited.`);
1471
+ this.lifecycle[hookName] = lifecycle[hookName];
1472
+ });
1473
+ Object.keys(registerPlugins).forEach((pluginName)=>{
1474
+ assert(!this.registerPlugins[pluginName], `The plugin "${pluginName}" has a conflict and cannot be inherited.`);
1475
+ this.applyPlugin(registerPlugins[pluginName]);
1476
+ });
1477
+ }
1478
+ constructor(lifecycle){
1479
+ this.registerPlugins = {};
1480
+ this.lifecycle = lifecycle;
1481
+ this.lifecycleKeys = Object.keys(lifecycle);
1482
+ }
1483
+ }
1484
+
1485
+ function defaultPreloadArgs(preloadConfig) {
1486
+ return polyfills._extends({
1487
+ resourceCategory: 'sync',
1488
+ share: true,
1489
+ depsRemote: true,
1490
+ prefetchInterface: false
1491
+ }, preloadConfig);
1492
+ }
1493
+ function formatPreloadArgs(remotes, preloadArgs) {
1494
+ return preloadArgs.map((args)=>{
1495
+ const remoteInfo = matchRemote(remotes, args.nameOrAlias);
1496
+ assert(remoteInfo, `Unable to preload ${args.nameOrAlias} as it is not included in ${!remoteInfo && sdk.safeToString({
1497
+ remoteInfo,
1498
+ remotes
1499
+ })}`);
1500
+ return {
1501
+ remote: remoteInfo,
1502
+ preloadConfig: defaultPreloadArgs(args)
1503
+ };
1504
+ });
1505
+ }
1506
+ function normalizePreloadExposes(exposes) {
1507
+ if (!exposes) {
1508
+ return [];
1509
+ }
1510
+ return exposes.map((expose)=>{
1511
+ if (expose === '.') {
1512
+ return expose;
1513
+ }
1514
+ if (expose.startsWith('./')) {
1515
+ return expose.replace('./', '');
1516
+ }
1517
+ return expose;
1518
+ });
1519
+ }
1520
+ function preloadAssets(remoteInfo, host, assets, // It is used to distinguish preload from load remote parallel loading
1521
+ useLinkPreload = true) {
1522
+ const { cssAssets, jsAssetsWithoutEntry, entryAssets } = assets;
1523
+ if (host.options.inBrowser) {
1524
+ entryAssets.forEach((asset)=>{
1525
+ const { moduleInfo } = asset;
1526
+ const module = host.moduleCache.get(remoteInfo.name);
1527
+ if (module) {
1528
+ getRemoteEntry({
1529
+ origin: host,
1530
+ remoteInfo: moduleInfo,
1531
+ remoteEntryExports: module.remoteEntryExports
1532
+ });
1533
+ } else {
1534
+ getRemoteEntry({
1535
+ origin: host,
1536
+ remoteInfo: moduleInfo,
1537
+ remoteEntryExports: undefined
1538
+ });
1539
+ }
1540
+ });
1541
+ if (useLinkPreload) {
1542
+ const defaultAttrs = {
1543
+ rel: 'preload',
1544
+ as: 'style'
1545
+ };
1546
+ cssAssets.forEach((cssUrl)=>{
1547
+ const { link: cssEl, needAttach } = sdk.createLink({
1548
+ url: cssUrl,
1549
+ cb: ()=>{
1550
+ // noop
1551
+ },
1552
+ attrs: defaultAttrs,
1553
+ createLinkHook: (url, attrs)=>{
1554
+ const res = host.loaderHook.lifecycle.createLink.emit({
1555
+ url,
1556
+ attrs
1557
+ });
1558
+ if (res instanceof HTMLLinkElement) {
1559
+ return res;
1560
+ }
1561
+ return;
1562
+ }
1563
+ });
1564
+ needAttach && document.head.appendChild(cssEl);
1565
+ });
1566
+ } else {
1567
+ const defaultAttrs = {
1568
+ rel: 'stylesheet',
1569
+ type: 'text/css'
1570
+ };
1571
+ cssAssets.forEach((cssUrl)=>{
1572
+ const { link: cssEl, needAttach } = sdk.createLink({
1573
+ url: cssUrl,
1574
+ cb: ()=>{
1575
+ // noop
1576
+ },
1577
+ attrs: defaultAttrs,
1578
+ createLinkHook: (url, attrs)=>{
1579
+ const res = host.loaderHook.lifecycle.createLink.emit({
1580
+ url,
1581
+ attrs
1582
+ });
1583
+ if (res instanceof HTMLLinkElement) {
1584
+ return res;
1585
+ }
1586
+ return;
1587
+ },
1588
+ needDeleteLink: false
1589
+ });
1590
+ needAttach && document.head.appendChild(cssEl);
1591
+ });
1592
+ }
1593
+ if (useLinkPreload) {
1594
+ const defaultAttrs = {
1595
+ rel: 'preload',
1596
+ as: 'script'
1597
+ };
1598
+ jsAssetsWithoutEntry.forEach((jsUrl)=>{
1599
+ const { link: linkEl, needAttach } = sdk.createLink({
1600
+ url: jsUrl,
1601
+ cb: ()=>{
1602
+ // noop
1603
+ },
1604
+ attrs: defaultAttrs,
1605
+ createLinkHook: (url, attrs)=>{
1606
+ const res = host.loaderHook.lifecycle.createLink.emit({
1607
+ url,
1608
+ attrs
1609
+ });
1610
+ if (res instanceof HTMLLinkElement) {
1611
+ return res;
1612
+ }
1613
+ return;
1614
+ }
1615
+ });
1616
+ needAttach && document.head.appendChild(linkEl);
1617
+ });
1618
+ } else {
1619
+ const defaultAttrs = {
1620
+ fetchpriority: 'high',
1621
+ type: (remoteInfo == null ? void 0 : remoteInfo.type) === 'module' ? 'module' : 'text/javascript'
1622
+ };
1623
+ jsAssetsWithoutEntry.forEach((jsUrl)=>{
1624
+ const { script: scriptEl, needAttach } = sdk.createScript({
1625
+ url: jsUrl,
1626
+ cb: ()=>{
1627
+ // noop
1628
+ },
1629
+ attrs: defaultAttrs,
1630
+ createScriptHook: (url, attrs)=>{
1631
+ const res = host.loaderHook.lifecycle.createScript.emit({
1632
+ url,
1633
+ attrs
1634
+ });
1635
+ if (res instanceof HTMLScriptElement) {
1636
+ return res;
1637
+ }
1638
+ return;
1639
+ },
1640
+ needDeleteScript: true
1641
+ });
1642
+ needAttach && document.head.appendChild(scriptEl);
1643
+ });
1644
+ }
1645
+ }
1646
+ }
1647
+
1648
+ function assignRemoteInfo(remoteInfo, remoteSnapshot) {
1649
+ const remoteEntryInfo = getRemoteEntryInfoFromSnapshot(remoteSnapshot);
1650
+ if (!remoteEntryInfo.url) {
1651
+ error(`The attribute remoteEntry of ${remoteInfo.name} must not be undefined.`);
1652
+ }
1653
+ let entryUrl = sdk.getResourceUrl(remoteSnapshot, remoteEntryInfo.url);
1654
+ if (!sdk.isBrowserEnv() && !entryUrl.startsWith('http')) {
1655
+ entryUrl = `https:${entryUrl}`;
1656
+ }
1657
+ remoteInfo.type = remoteEntryInfo.type;
1658
+ remoteInfo.entryGlobalName = remoteEntryInfo.globalName;
1659
+ remoteInfo.entry = entryUrl;
1660
+ remoteInfo.version = remoteSnapshot.version;
1661
+ remoteInfo.buildVersion = remoteSnapshot.buildVersion;
1662
+ }
1663
+ function snapshotPlugin() {
1664
+ return {
1665
+ name: 'snapshot-plugin',
1666
+ async afterResolve (args) {
1667
+ const { remote, pkgNameOrAlias, expose, origin, remoteInfo } = args;
1668
+ if (!isRemoteInfoWithEntry(remote) || !isPureRemoteEntry(remote)) {
1669
+ const { remoteSnapshot, globalSnapshot } = await origin.snapshotHandler.loadRemoteSnapshotInfo(remote);
1670
+ assignRemoteInfo(remoteInfo, remoteSnapshot);
1671
+ // preloading assets
1672
+ const preloadOptions = {
1673
+ remote,
1674
+ preloadConfig: {
1675
+ nameOrAlias: pkgNameOrAlias,
1676
+ exposes: [
1677
+ expose
1678
+ ],
1679
+ resourceCategory: 'sync',
1680
+ share: false,
1681
+ depsRemote: false
1682
+ }
1683
+ };
1684
+ const assets = await origin.remoteHandler.hooks.lifecycle.generatePreloadAssets.emit({
1685
+ origin,
1686
+ preloadOptions,
1687
+ remoteInfo,
1688
+ remote,
1689
+ remoteSnapshot,
1690
+ globalSnapshot
1691
+ });
1692
+ if (assets) {
1693
+ preloadAssets(remoteInfo, origin, assets, false);
1694
+ }
1695
+ return polyfills._extends({}, args, {
1696
+ remoteSnapshot
1697
+ });
1698
+ }
1699
+ return args;
1700
+ }
1701
+ };
1702
+ }
1703
+
1704
+ // name
1705
+ // name:version
1706
+ function splitId(id) {
1707
+ const splitInfo = id.split(':');
1708
+ if (splitInfo.length === 1) {
1709
+ return {
1710
+ name: splitInfo[0],
1711
+ version: undefined
1712
+ };
1713
+ } else if (splitInfo.length === 2) {
1714
+ return {
1715
+ name: splitInfo[0],
1716
+ version: splitInfo[1]
1717
+ };
1718
+ } else {
1719
+ return {
1720
+ name: splitInfo[1],
1721
+ version: splitInfo[2]
1722
+ };
1723
+ }
1724
+ }
1725
+ // Traverse all nodes in moduleInfo and traverse the entire snapshot
1726
+ function traverseModuleInfo(globalSnapshot, remoteInfo, traverse, isRoot, memo = {}, remoteSnapshot) {
1727
+ const id = getFMId(remoteInfo);
1728
+ const { value: snapshotValue } = getInfoWithoutType(globalSnapshot, id);
1729
+ const effectiveRemoteSnapshot = remoteSnapshot || snapshotValue;
1730
+ if (effectiveRemoteSnapshot && !sdk.isManifestProvider(effectiveRemoteSnapshot)) {
1731
+ traverse(effectiveRemoteSnapshot, remoteInfo, isRoot);
1732
+ if (effectiveRemoteSnapshot.remotesInfo) {
1733
+ const remoteKeys = Object.keys(effectiveRemoteSnapshot.remotesInfo);
1734
+ for (const key of remoteKeys){
1735
+ if (memo[key]) {
1736
+ continue;
1737
+ }
1738
+ memo[key] = true;
1739
+ const subRemoteInfo = splitId(key);
1740
+ const remoteValue = effectiveRemoteSnapshot.remotesInfo[key];
1741
+ traverseModuleInfo(globalSnapshot, {
1742
+ name: subRemoteInfo.name,
1743
+ version: remoteValue.matchedVersion
1744
+ }, traverse, false, memo, undefined);
1745
+ }
1746
+ }
1747
+ }
1748
+ }
1749
+ // eslint-disable-next-line max-lines-per-function
1750
+ function generatePreloadAssets(origin, preloadOptions, remote, globalSnapshot, remoteSnapshot) {
1751
+ const cssAssets = [];
1752
+ const jsAssets = [];
1753
+ const entryAssets = [];
1754
+ const loadedSharedJsAssets = new Set();
1755
+ const loadedSharedCssAssets = new Set();
1756
+ const { options } = origin;
1757
+ const { preloadConfig: rootPreloadConfig } = preloadOptions;
1758
+ const { depsRemote } = rootPreloadConfig;
1759
+ const memo = {};
1760
+ traverseModuleInfo(globalSnapshot, remote, (moduleInfoSnapshot, remoteInfo, isRoot)=>{
1761
+ let preloadConfig;
1762
+ if (isRoot) {
1763
+ preloadConfig = rootPreloadConfig;
1764
+ } else {
1765
+ if (Array.isArray(depsRemote)) {
1766
+ // eslint-disable-next-line array-callback-return
1767
+ const findPreloadConfig = depsRemote.find((remoteConfig)=>{
1768
+ if (remoteConfig.nameOrAlias === remoteInfo.name || remoteConfig.nameOrAlias === remoteInfo.alias) {
1769
+ return true;
1770
+ }
1771
+ return false;
1772
+ });
1773
+ if (!findPreloadConfig) {
1774
+ return;
1775
+ }
1776
+ preloadConfig = defaultPreloadArgs(findPreloadConfig);
1777
+ } else if (depsRemote === true) {
1778
+ preloadConfig = rootPreloadConfig;
1779
+ } else {
1780
+ return;
1781
+ }
1782
+ }
1783
+ const remoteEntryUrl = sdk.getResourceUrl(moduleInfoSnapshot, getRemoteEntryInfoFromSnapshot(moduleInfoSnapshot).url);
1784
+ if (remoteEntryUrl) {
1785
+ entryAssets.push({
1786
+ name: remoteInfo.name,
1787
+ moduleInfo: {
1788
+ name: remoteInfo.name,
1789
+ entry: remoteEntryUrl,
1790
+ type: 'remoteEntryType' in moduleInfoSnapshot ? moduleInfoSnapshot.remoteEntryType : 'global',
1791
+ entryGlobalName: 'globalName' in moduleInfoSnapshot ? moduleInfoSnapshot.globalName : remoteInfo.name,
1792
+ shareScope: '',
1793
+ version: 'version' in moduleInfoSnapshot ? moduleInfoSnapshot.version : undefined
1794
+ },
1795
+ url: remoteEntryUrl
1796
+ });
1797
+ }
1798
+ let moduleAssetsInfo = 'modules' in moduleInfoSnapshot ? moduleInfoSnapshot.modules : [];
1799
+ const normalizedPreloadExposes = normalizePreloadExposes(preloadConfig.exposes);
1800
+ if (normalizedPreloadExposes.length && 'modules' in moduleInfoSnapshot) {
1801
+ var _moduleInfoSnapshot_modules;
1802
+ moduleAssetsInfo = moduleInfoSnapshot == null ? void 0 : (_moduleInfoSnapshot_modules = moduleInfoSnapshot.modules) == null ? void 0 : _moduleInfoSnapshot_modules.reduce((assets, moduleAssetInfo)=>{
1803
+ if ((normalizedPreloadExposes == null ? void 0 : normalizedPreloadExposes.indexOf(moduleAssetInfo.moduleName)) !== -1) {
1804
+ assets.push(moduleAssetInfo);
1805
+ }
1806
+ return assets;
1807
+ }, []);
1808
+ }
1809
+ function handleAssets(assets) {
1810
+ const assetsRes = assets.map((asset)=>sdk.getResourceUrl(moduleInfoSnapshot, asset));
1811
+ if (preloadConfig.filter) {
1812
+ return assetsRes.filter(preloadConfig.filter);
1813
+ }
1814
+ return assetsRes;
1815
+ }
1816
+ if (moduleAssetsInfo) {
1817
+ const assetsLength = moduleAssetsInfo.length;
1818
+ for(let index = 0; index < assetsLength; index++){
1819
+ const assetsInfo = moduleAssetsInfo[index];
1820
+ const exposeFullPath = `${remoteInfo.name}/${assetsInfo.moduleName}`;
1821
+ origin.remoteHandler.hooks.lifecycle.handlePreloadModule.emit({
1822
+ id: assetsInfo.moduleName === '.' ? remoteInfo.name : exposeFullPath,
1823
+ name: remoteInfo.name,
1824
+ remoteSnapshot: moduleInfoSnapshot,
1825
+ preloadConfig,
1826
+ remote: remoteInfo,
1827
+ origin
1828
+ });
1829
+ const preloaded = getPreloaded(exposeFullPath);
1830
+ if (preloaded) {
1831
+ continue;
1832
+ }
1833
+ if (preloadConfig.resourceCategory === 'all') {
1834
+ cssAssets.push(...handleAssets(assetsInfo.assets.css.async));
1835
+ cssAssets.push(...handleAssets(assetsInfo.assets.css.sync));
1836
+ jsAssets.push(...handleAssets(assetsInfo.assets.js.async));
1837
+ jsAssets.push(...handleAssets(assetsInfo.assets.js.sync));
1838
+ // eslint-disable-next-line no-constant-condition
1839
+ } else if (preloadConfig.resourceCategory = 'sync') {
1840
+ cssAssets.push(...handleAssets(assetsInfo.assets.css.sync));
1841
+ jsAssets.push(...handleAssets(assetsInfo.assets.js.sync));
1842
+ }
1843
+ setPreloaded(exposeFullPath);
1844
+ }
1845
+ }
1846
+ }, true, memo, remoteSnapshot);
1847
+ if (remoteSnapshot.shared) {
1848
+ const collectSharedAssets = (shareInfo, snapshotShared)=>{
1849
+ const registeredShared = getRegisteredShare(origin.shareScopeMap, snapshotShared.sharedName, shareInfo, origin.sharedHandler.hooks.lifecycle.resolveShare);
1850
+ // If the global share does not exist, or the lib function does not exist, it means that the shared has not been loaded yet and can be preloaded.
1851
+ if (registeredShared && typeof registeredShared.lib === 'function') {
1852
+ snapshotShared.assets.js.sync.forEach((asset)=>{
1853
+ loadedSharedJsAssets.add(asset);
1854
+ });
1855
+ snapshotShared.assets.css.sync.forEach((asset)=>{
1856
+ loadedSharedCssAssets.add(asset);
1857
+ });
1858
+ }
1859
+ };
1860
+ remoteSnapshot.shared.forEach((shared)=>{
1861
+ var _options_shared;
1862
+ const shareInfos = (_options_shared = options.shared) == null ? void 0 : _options_shared[shared.sharedName];
1863
+ if (!shareInfos) {
1864
+ return;
1865
+ }
1866
+ // if no version, preload all shared
1867
+ const sharedOptions = shared.version ? shareInfos.find((s)=>s.version === shared.version) : shareInfos;
1868
+ if (!sharedOptions) {
1869
+ return;
1870
+ }
1871
+ const arrayShareInfo = arrayOptions(sharedOptions);
1872
+ arrayShareInfo.forEach((s)=>{
1873
+ collectSharedAssets(s, shared);
1874
+ });
1875
+ });
1876
+ }
1877
+ const needPreloadJsAssets = jsAssets.filter((asset)=>!loadedSharedJsAssets.has(asset));
1878
+ const needPreloadCssAssets = cssAssets.filter((asset)=>!loadedSharedCssAssets.has(asset));
1879
+ return {
1880
+ cssAssets: needPreloadCssAssets,
1881
+ jsAssetsWithoutEntry: needPreloadJsAssets,
1882
+ entryAssets
1883
+ };
1884
+ }
1885
+ const generatePreloadAssetsPlugin = function() {
1886
+ return {
1887
+ name: 'generate-preload-assets-plugin',
1888
+ async generatePreloadAssets (args) {
1889
+ const { origin, preloadOptions, remoteInfo, remote, globalSnapshot, remoteSnapshot } = args;
1890
+ if (isRemoteInfoWithEntry(remote) && isPureRemoteEntry(remote)) {
1891
+ return {
1892
+ cssAssets: [],
1893
+ jsAssetsWithoutEntry: [],
1894
+ entryAssets: [
1895
+ {
1896
+ name: remote.name,
1897
+ url: remote.entry,
1898
+ moduleInfo: {
1899
+ name: remoteInfo.name,
1900
+ entry: remote.entry,
1901
+ type: remoteInfo.type || 'global',
1902
+ entryGlobalName: '',
1903
+ shareScope: ''
1904
+ }
1905
+ }
1906
+ ]
1907
+ };
1908
+ }
1909
+ assignRemoteInfo(remoteInfo, remoteSnapshot);
1910
+ const assets = generatePreloadAssets(origin, preloadOptions, remoteInfo, globalSnapshot, remoteSnapshot);
1911
+ return assets;
1912
+ }
1913
+ };
1914
+ };
1915
+
1916
+ function getGlobalRemoteInfo(moduleInfo, origin) {
1917
+ const hostGlobalSnapshot = getGlobalSnapshotInfoByModuleInfo({
1918
+ name: origin.options.name,
1919
+ version: origin.options.version
1920
+ });
1921
+ // get remote detail info from global
1922
+ const globalRemoteInfo = hostGlobalSnapshot && 'remotesInfo' in hostGlobalSnapshot && hostGlobalSnapshot.remotesInfo && getInfoWithoutType(hostGlobalSnapshot.remotesInfo, moduleInfo.name).value;
1923
+ if (globalRemoteInfo && globalRemoteInfo.matchedVersion) {
1924
+ return {
1925
+ hostGlobalSnapshot,
1926
+ globalSnapshot: getGlobalSnapshot(),
1927
+ remoteSnapshot: getGlobalSnapshotInfoByModuleInfo({
1928
+ name: moduleInfo.name,
1929
+ version: globalRemoteInfo.matchedVersion
1930
+ })
1931
+ };
1932
+ }
1933
+ return {
1934
+ hostGlobalSnapshot: undefined,
1935
+ globalSnapshot: getGlobalSnapshot(),
1936
+ remoteSnapshot: getGlobalSnapshotInfoByModuleInfo({
1937
+ name: moduleInfo.name,
1938
+ version: 'version' in moduleInfo ? moduleInfo.version : undefined
1939
+ })
1940
+ };
1941
+ }
1942
+ class SnapshotHandler {
1943
+ async loadSnapshot(moduleInfo) {
1944
+ const { options } = this.HostInstance;
1945
+ const { hostGlobalSnapshot, remoteSnapshot, globalSnapshot } = this.getGlobalRemoteInfo(moduleInfo);
1946
+ const { remoteSnapshot: globalRemoteSnapshot, globalSnapshot: globalSnapshotRes } = await this.hooks.lifecycle.loadSnapshot.emit({
1947
+ options,
1948
+ moduleInfo,
1949
+ hostGlobalSnapshot,
1950
+ remoteSnapshot,
1951
+ globalSnapshot
1952
+ });
1953
+ return {
1954
+ remoteSnapshot: globalRemoteSnapshot,
1955
+ globalSnapshot: globalSnapshotRes
1956
+ };
1957
+ }
1958
+ // eslint-disable-next-line max-lines-per-function
1959
+ async loadRemoteSnapshotInfo(moduleInfo) {
1960
+ const { options } = this.HostInstance;
1961
+ await this.hooks.lifecycle.beforeLoadRemoteSnapshot.emit({
1962
+ options,
1963
+ moduleInfo
1964
+ });
1965
+ let hostSnapshot = getGlobalSnapshotInfoByModuleInfo({
1966
+ name: this.HostInstance.options.name,
1967
+ version: this.HostInstance.options.version
1968
+ });
1969
+ if (!hostSnapshot) {
1970
+ hostSnapshot = {
1971
+ version: this.HostInstance.options.version || '',
1972
+ remoteEntry: '',
1973
+ remotesInfo: {}
1974
+ };
1975
+ addGlobalSnapshot({
1976
+ [this.HostInstance.options.name]: hostSnapshot
1977
+ });
1978
+ }
1979
+ // In dynamic loadRemote scenarios, incomplete remotesInfo delivery may occur. In such cases, the remotesInfo in the host needs to be completed in the snapshot at runtime.
1980
+ // This ensures the snapshot's integrity and helps the chrome plugin correctly identify all producer modules, ensuring that proxyable producer modules will not be missing.
1981
+ if (hostSnapshot && 'remotesInfo' in hostSnapshot && !getInfoWithoutType(hostSnapshot.remotesInfo, moduleInfo.name).value) {
1982
+ if ('version' in moduleInfo || 'entry' in moduleInfo) {
1983
+ hostSnapshot.remotesInfo = polyfills._extends({}, hostSnapshot == null ? void 0 : hostSnapshot.remotesInfo, {
1984
+ [moduleInfo.name]: {
1985
+ matchedVersion: 'version' in moduleInfo ? moduleInfo.version : moduleInfo.entry
1986
+ }
1987
+ });
1988
+ }
1989
+ }
1990
+ const { hostGlobalSnapshot, remoteSnapshot, globalSnapshot } = this.getGlobalRemoteInfo(moduleInfo);
1991
+ const { remoteSnapshot: globalRemoteSnapshot, globalSnapshot: globalSnapshotRes } = await this.hooks.lifecycle.loadSnapshot.emit({
1992
+ options,
1993
+ moduleInfo,
1994
+ hostGlobalSnapshot,
1995
+ remoteSnapshot,
1996
+ globalSnapshot
1997
+ });
1998
+ let mSnapshot;
1999
+ let gSnapshot;
2000
+ // global snapshot includes manifest or module info includes manifest
2001
+ if (globalRemoteSnapshot) {
2002
+ if (sdk.isManifestProvider(globalRemoteSnapshot)) {
2003
+ const remoteEntry = sdk.isBrowserEnv() ? globalRemoteSnapshot.remoteEntry : globalRemoteSnapshot.ssrRemoteEntry || globalRemoteSnapshot.remoteEntry || '';
2004
+ const moduleSnapshot = await this.getManifestJson(remoteEntry, moduleInfo, {});
2005
+ // eslint-disable-next-line @typescript-eslint/no-shadow
2006
+ const globalSnapshotRes = setGlobalSnapshotInfoByModuleInfo(polyfills._extends({}, moduleInfo, {
2007
+ // The global remote may be overridden
2008
+ // Therefore, set the snapshot key to the global address of the actual request
2009
+ entry: remoteEntry
2010
+ }), moduleSnapshot);
2011
+ mSnapshot = moduleSnapshot;
2012
+ gSnapshot = globalSnapshotRes;
2013
+ } else {
2014
+ const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
2015
+ options: this.HostInstance.options,
2016
+ moduleInfo,
2017
+ remoteSnapshot: globalRemoteSnapshot,
2018
+ from: 'global'
2019
+ });
2020
+ mSnapshot = remoteSnapshotRes;
2021
+ gSnapshot = globalSnapshotRes;
2022
+ }
2023
+ } else {
2024
+ if (isRemoteInfoWithEntry(moduleInfo)) {
2025
+ // get from manifest.json and merge remote info from remote server
2026
+ const moduleSnapshot = await this.getManifestJson(moduleInfo.entry, moduleInfo, {});
2027
+ // eslint-disable-next-line @typescript-eslint/no-shadow
2028
+ const globalSnapshotRes = setGlobalSnapshotInfoByModuleInfo(moduleInfo, moduleSnapshot);
2029
+ const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
2030
+ options: this.HostInstance.options,
2031
+ moduleInfo,
2032
+ remoteSnapshot: moduleSnapshot,
2033
+ from: 'global'
2034
+ });
2035
+ mSnapshot = remoteSnapshotRes;
2036
+ gSnapshot = globalSnapshotRes;
2037
+ } else {
2038
+ error(errorCodes.getShortErrorMsg(errorCodes.RUNTIME_007, errorCodes.runtimeDescMap, {
2039
+ hostName: moduleInfo.name,
2040
+ hostVersion: moduleInfo.version,
2041
+ globalSnapshot: JSON.stringify(globalSnapshotRes)
2042
+ }));
2043
+ }
2044
+ }
2045
+ await this.hooks.lifecycle.afterLoadSnapshot.emit({
2046
+ options,
2047
+ moduleInfo,
2048
+ remoteSnapshot: mSnapshot
2049
+ });
2050
+ return {
2051
+ remoteSnapshot: mSnapshot,
2052
+ globalSnapshot: gSnapshot
2053
+ };
2054
+ }
2055
+ getGlobalRemoteInfo(moduleInfo) {
2056
+ return getGlobalRemoteInfo(moduleInfo, this.HostInstance);
2057
+ }
2058
+ async getManifestJson(manifestUrl, moduleInfo, extraOptions) {
2059
+ const getManifest = async ()=>{
2060
+ let manifestJson = this.manifestCache.get(manifestUrl);
2061
+ if (manifestJson) {
2062
+ return manifestJson;
2063
+ }
2064
+ try {
2065
+ let res = await this.loaderHook.lifecycle.fetch.emit(manifestUrl, {});
2066
+ if (!res || !(res instanceof Response)) {
2067
+ res = await fetch(manifestUrl, {});
2068
+ }
2069
+ manifestJson = await res.json();
2070
+ assert(manifestJson.metaData && manifestJson.exposes && manifestJson.shared, `${manifestUrl} is not a federation manifest`);
2071
+ this.manifestCache.set(manifestUrl, manifestJson);
2072
+ return manifestJson;
2073
+ } catch (err) {
2074
+ delete this.manifestLoading[manifestUrl];
2075
+ error(errorCodes.getShortErrorMsg(errorCodes.RUNTIME_003, errorCodes.runtimeDescMap, {
2076
+ manifestUrl,
2077
+ moduleName: moduleInfo.name
2078
+ }, `${err}`));
2079
+ }
2080
+ };
2081
+ const asyncLoadProcess = async ()=>{
2082
+ const manifestJson = await getManifest();
2083
+ const remoteSnapshot = sdk.generateSnapshotFromManifest(manifestJson, {
2084
+ version: manifestUrl
2085
+ });
2086
+ const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
2087
+ options: this.HostInstance.options,
2088
+ moduleInfo,
2089
+ manifestJson,
2090
+ remoteSnapshot,
2091
+ manifestUrl,
2092
+ from: 'manifest'
2093
+ });
2094
+ return remoteSnapshotRes;
2095
+ };
2096
+ if (!this.manifestLoading[manifestUrl]) {
2097
+ this.manifestLoading[manifestUrl] = asyncLoadProcess().then((res)=>res);
2098
+ }
2099
+ return this.manifestLoading[manifestUrl];
2100
+ }
2101
+ constructor(HostInstance){
2102
+ this.loadingHostSnapshot = null;
2103
+ this.manifestCache = new Map();
2104
+ this.hooks = new PluginSystem({
2105
+ beforeLoadRemoteSnapshot: new AsyncHook('beforeLoadRemoteSnapshot'),
2106
+ loadSnapshot: new AsyncWaterfallHook('loadGlobalSnapshot'),
2107
+ loadRemoteSnapshot: new AsyncWaterfallHook('loadRemoteSnapshot'),
2108
+ afterLoadSnapshot: new AsyncWaterfallHook('afterLoadSnapshot')
2109
+ });
2110
+ this.manifestLoading = Global.__FEDERATION__.__MANIFEST_LOADING__;
2111
+ this.HostInstance = HostInstance;
2112
+ this.loaderHook = HostInstance.loaderHook;
2113
+ }
2114
+ }
2115
+
2116
+ class SharedHandler {
2117
+ // register shared in shareScopeMap
2118
+ registerShared(globalOptions, userOptions) {
2119
+ const { shareInfos, shared } = formatShareConfigs(globalOptions, userOptions);
2120
+ const sharedKeys = Object.keys(shareInfos);
2121
+ sharedKeys.forEach((sharedKey)=>{
2122
+ const sharedVals = shareInfos[sharedKey];
2123
+ sharedVals.forEach((sharedVal)=>{
2124
+ const registeredShared = getRegisteredShare(this.shareScopeMap, sharedKey, sharedVal, this.hooks.lifecycle.resolveShare);
2125
+ if (!registeredShared && sharedVal && sharedVal.lib) {
2126
+ this.setShared({
2127
+ pkgName: sharedKey,
2128
+ lib: sharedVal.lib,
2129
+ get: sharedVal.get,
2130
+ loaded: true,
2131
+ shared: sharedVal,
2132
+ from: userOptions.name
2133
+ });
2134
+ }
2135
+ });
2136
+ });
2137
+ return {
2138
+ shareInfos,
2139
+ shared
2140
+ };
2141
+ }
2142
+ async loadShare(pkgName, extraOptions) {
2143
+ const { host } = this;
2144
+ // This function performs the following steps:
2145
+ // 1. Checks if the currently loaded share already exists, if not, it throws an error
2146
+ // 2. Searches globally for a matching share, if found, it uses it directly
2147
+ // 3. If not found, it retrieves it from the current share and stores the obtained share globally.
2148
+ const shareInfo = getTargetSharedOptions({
2149
+ pkgName,
2150
+ extraOptions,
2151
+ shareInfos: host.options.shared
2152
+ });
2153
+ if (shareInfo == null ? void 0 : shareInfo.scope) {
2154
+ await Promise.all(shareInfo.scope.map(async (shareScope)=>{
2155
+ await Promise.all(this.initializeSharing(shareScope, {
2156
+ strategy: shareInfo.strategy
2157
+ }));
2158
+ return;
2159
+ }));
2160
+ }
2161
+ const loadShareRes = await this.hooks.lifecycle.beforeLoadShare.emit({
2162
+ pkgName,
2163
+ shareInfo,
2164
+ shared: host.options.shared,
2165
+ origin: host
2166
+ });
2167
+ const { shareInfo: shareInfoRes } = loadShareRes;
2168
+ // Assert that shareInfoRes exists, if not, throw an error
2169
+ assert(shareInfoRes, `Cannot find ${pkgName} Share in the ${host.options.name}. Please ensure that the ${pkgName} Share parameters have been injected`);
2170
+ // Retrieve from cache
2171
+ const registeredShared = getRegisteredShare(this.shareScopeMap, pkgName, shareInfoRes, this.hooks.lifecycle.resolveShare);
2172
+ const addUseIn = (shared)=>{
2173
+ if (!shared.useIn) {
2174
+ shared.useIn = [];
2175
+ }
2176
+ addUniqueItem(shared.useIn, host.options.name);
2177
+ };
2178
+ if (registeredShared && registeredShared.lib) {
2179
+ addUseIn(registeredShared);
2180
+ return registeredShared.lib;
2181
+ } else if (registeredShared && registeredShared.loading && !registeredShared.loaded) {
2182
+ const factory = await registeredShared.loading;
2183
+ registeredShared.loaded = true;
2184
+ if (!registeredShared.lib) {
2185
+ registeredShared.lib = factory;
2186
+ }
2187
+ addUseIn(registeredShared);
2188
+ return factory;
2189
+ } else if (registeredShared) {
2190
+ const asyncLoadProcess = async ()=>{
2191
+ const factory = await registeredShared.get();
2192
+ shareInfoRes.lib = factory;
2193
+ shareInfoRes.loaded = true;
2194
+ addUseIn(shareInfoRes);
2195
+ const gShared = getRegisteredShare(this.shareScopeMap, pkgName, shareInfoRes, this.hooks.lifecycle.resolveShare);
2196
+ if (gShared) {
2197
+ gShared.lib = factory;
2198
+ gShared.loaded = true;
2199
+ }
2200
+ return factory;
2201
+ };
2202
+ const loading = asyncLoadProcess();
2203
+ this.setShared({
2204
+ pkgName,
2205
+ loaded: false,
2206
+ shared: registeredShared,
2207
+ from: host.options.name,
2208
+ lib: null,
2209
+ loading
2210
+ });
2211
+ return loading;
2212
+ } else {
2213
+ if (extraOptions == null ? void 0 : extraOptions.customShareInfo) {
2214
+ return false;
2215
+ }
2216
+ const asyncLoadProcess = async ()=>{
2217
+ const factory = await shareInfoRes.get();
2218
+ shareInfoRes.lib = factory;
2219
+ shareInfoRes.loaded = true;
2220
+ addUseIn(shareInfoRes);
2221
+ const gShared = getRegisteredShare(this.shareScopeMap, pkgName, shareInfoRes, this.hooks.lifecycle.resolveShare);
2222
+ if (gShared) {
2223
+ gShared.lib = factory;
2224
+ gShared.loaded = true;
2225
+ }
2226
+ return factory;
2227
+ };
2228
+ const loading = asyncLoadProcess();
2229
+ this.setShared({
2230
+ pkgName,
2231
+ loaded: false,
2232
+ shared: shareInfoRes,
2233
+ from: host.options.name,
2234
+ lib: null,
2235
+ loading
2236
+ });
2237
+ return loading;
2238
+ }
2239
+ }
2240
+ /**
2241
+ * This function initializes the sharing sequence (executed only once per share scope).
2242
+ * It accepts one argument, the name of the share scope.
2243
+ * If the share scope does not exist, it creates one.
2244
+ */ // eslint-disable-next-line @typescript-eslint/member-ordering
2245
+ initializeSharing(shareScopeName = DEFAULT_SCOPE, extraOptions) {
2246
+ const { host } = this;
2247
+ const from = extraOptions == null ? void 0 : extraOptions.from;
2248
+ const strategy = extraOptions == null ? void 0 : extraOptions.strategy;
2249
+ let initScope = extraOptions == null ? void 0 : extraOptions.initScope;
2250
+ const promises = [];
2251
+ if (from !== 'build') {
2252
+ const { initTokens } = this;
2253
+ if (!initScope) initScope = [];
2254
+ let initToken = initTokens[shareScopeName];
2255
+ if (!initToken) initToken = initTokens[shareScopeName] = {
2256
+ from: this.host.name
2257
+ };
2258
+ if (initScope.indexOf(initToken) >= 0) return promises;
2259
+ initScope.push(initToken);
2260
+ }
2261
+ const shareScope = this.shareScopeMap;
2262
+ const hostName = host.options.name;
2263
+ // Creates a new share scope if necessary
2264
+ if (!shareScope[shareScopeName]) {
2265
+ shareScope[shareScopeName] = {};
2266
+ }
2267
+ // Executes all initialization snippets from all accessible modules
2268
+ const scope = shareScope[shareScopeName];
2269
+ const register = (name, shared)=>{
2270
+ var _activeVersion_shareConfig;
2271
+ const { version, eager } = shared;
2272
+ scope[name] = scope[name] || {};
2273
+ const versions = scope[name];
2274
+ const activeVersion = versions[version];
2275
+ const activeVersionEager = Boolean(activeVersion && (activeVersion.eager || ((_activeVersion_shareConfig = activeVersion.shareConfig) == null ? void 0 : _activeVersion_shareConfig.eager)));
2276
+ if (!activeVersion || activeVersion.strategy !== 'loaded-first' && !activeVersion.loaded && (Boolean(!eager) !== !activeVersionEager ? eager : hostName > activeVersion.from)) {
2277
+ versions[version] = shared;
2278
+ }
2279
+ };
2280
+ const initFn = (mod)=>mod && mod.init && mod.init(shareScope[shareScopeName], initScope);
2281
+ const initRemoteModule = async (key)=>{
2282
+ const { module } = await host.remoteHandler.getRemoteModuleAndOptions({
2283
+ id: key
2284
+ });
2285
+ if (module.getEntry) {
2286
+ let remoteEntryExports;
2287
+ try {
2288
+ remoteEntryExports = await module.getEntry();
2289
+ } catch (error) {
2290
+ remoteEntryExports = await host.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({
2291
+ id: key,
2292
+ error,
2293
+ from: 'runtime',
2294
+ lifecycle: 'beforeLoadShare',
2295
+ origin: host
2296
+ });
2297
+ }
2298
+ if (!module.inited) {
2299
+ await initFn(remoteEntryExports);
2300
+ module.inited = true;
2301
+ }
2302
+ }
2303
+ };
2304
+ Object.keys(host.options.shared).forEach((shareName)=>{
2305
+ const sharedArr = host.options.shared[shareName];
2306
+ sharedArr.forEach((shared)=>{
2307
+ if (shared.scope.includes(shareScopeName)) {
2308
+ register(shareName, shared);
2309
+ }
2310
+ });
2311
+ });
2312
+ // TODO: strategy==='version-first' need to be removed in the future
2313
+ if (host.options.shareStrategy === 'version-first' || strategy === 'version-first') {
2314
+ host.options.remotes.forEach((remote)=>{
2315
+ if (remote.shareScope === shareScopeName) {
2316
+ promises.push(initRemoteModule(remote.name));
2317
+ }
2318
+ });
2319
+ }
2320
+ return promises;
2321
+ }
2322
+ // The lib function will only be available if the shared set by eager or runtime init is set or the shared is successfully loaded.
2323
+ // 1. If the loaded shared already exists globally, then it will be reused
2324
+ // 2. If lib exists in local shared, it will be used directly
2325
+ // 3. If the local get returns something other than Promise, then it will be used directly
2326
+ loadShareSync(pkgName, extraOptions) {
2327
+ const { host } = this;
2328
+ const shareInfo = getTargetSharedOptions({
2329
+ pkgName,
2330
+ extraOptions,
2331
+ shareInfos: host.options.shared
2332
+ });
2333
+ if (shareInfo == null ? void 0 : shareInfo.scope) {
2334
+ shareInfo.scope.forEach((shareScope)=>{
2335
+ this.initializeSharing(shareScope, {
2336
+ strategy: shareInfo.strategy
2337
+ });
2338
+ });
2339
+ }
2340
+ const registeredShared = getRegisteredShare(this.shareScopeMap, pkgName, shareInfo, this.hooks.lifecycle.resolveShare);
2341
+ const addUseIn = (shared)=>{
2342
+ if (!shared.useIn) {
2343
+ shared.useIn = [];
2344
+ }
2345
+ addUniqueItem(shared.useIn, host.options.name);
2346
+ };
2347
+ if (registeredShared) {
2348
+ if (typeof registeredShared.lib === 'function') {
2349
+ addUseIn(registeredShared);
2350
+ if (!registeredShared.loaded) {
2351
+ registeredShared.loaded = true;
2352
+ if (registeredShared.from === host.options.name) {
2353
+ shareInfo.loaded = true;
2354
+ }
2355
+ }
2356
+ return registeredShared.lib;
2357
+ }
2358
+ if (typeof registeredShared.get === 'function') {
2359
+ const module = registeredShared.get();
2360
+ if (!(module instanceof Promise)) {
2361
+ addUseIn(registeredShared);
2362
+ this.setShared({
2363
+ pkgName,
2364
+ loaded: true,
2365
+ from: host.options.name,
2366
+ lib: module,
2367
+ shared: registeredShared
2368
+ });
2369
+ return module;
2370
+ }
2371
+ }
2372
+ }
2373
+ if (shareInfo.lib) {
2374
+ if (!shareInfo.loaded) {
2375
+ shareInfo.loaded = true;
2376
+ }
2377
+ return shareInfo.lib;
2378
+ }
2379
+ if (shareInfo.get) {
2380
+ const module = shareInfo.get();
2381
+ if (module instanceof Promise) {
2382
+ const errorCode = (extraOptions == null ? void 0 : extraOptions.from) === 'build' ? errorCodes.RUNTIME_005 : errorCodes.RUNTIME_006;
2383
+ throw new Error(errorCodes.getShortErrorMsg(errorCode, errorCodes.runtimeDescMap, {
2384
+ hostName: host.options.name,
2385
+ sharedPkgName: pkgName
2386
+ }));
2387
+ }
2388
+ shareInfo.lib = module;
2389
+ this.setShared({
2390
+ pkgName,
2391
+ loaded: true,
2392
+ from: host.options.name,
2393
+ lib: shareInfo.lib,
2394
+ shared: shareInfo
2395
+ });
2396
+ return shareInfo.lib;
2397
+ }
2398
+ throw new Error(errorCodes.getShortErrorMsg(errorCodes.RUNTIME_006, errorCodes.runtimeDescMap, {
2399
+ hostName: host.options.name,
2400
+ sharedPkgName: pkgName
2401
+ }));
2402
+ }
2403
+ initShareScopeMap(scopeName, shareScope, extraOptions = {}) {
2404
+ const { host } = this;
2405
+ this.shareScopeMap[scopeName] = shareScope;
2406
+ this.hooks.lifecycle.initContainerShareScopeMap.emit({
2407
+ shareScope,
2408
+ options: host.options,
2409
+ origin: host,
2410
+ scopeName,
2411
+ hostShareScopeMap: extraOptions.hostShareScopeMap
2412
+ });
2413
+ }
2414
+ setShared({ pkgName, shared, from, lib, loading, loaded, get }) {
2415
+ const { version, scope = 'default' } = shared, shareInfo = polyfills._object_without_properties_loose(shared, [
2416
+ "version",
2417
+ "scope"
2418
+ ]);
2419
+ const scopes = Array.isArray(scope) ? scope : [
2420
+ scope
2421
+ ];
2422
+ scopes.forEach((sc)=>{
2423
+ if (!this.shareScopeMap[sc]) {
2424
+ this.shareScopeMap[sc] = {};
2425
+ }
2426
+ if (!this.shareScopeMap[sc][pkgName]) {
2427
+ this.shareScopeMap[sc][pkgName] = {};
2428
+ }
2429
+ if (!this.shareScopeMap[sc][pkgName][version]) {
2430
+ this.shareScopeMap[sc][pkgName][version] = polyfills._extends({
2431
+ version,
2432
+ scope: [
2433
+ 'default'
2434
+ ]
2435
+ }, shareInfo, {
2436
+ lib,
2437
+ loaded,
2438
+ loading
2439
+ });
2440
+ if (get) {
2441
+ this.shareScopeMap[sc][pkgName][version].get = get;
2442
+ }
2443
+ return;
2444
+ }
2445
+ const registeredShared = this.shareScopeMap[sc][pkgName][version];
2446
+ if (loading && !registeredShared.loading) {
2447
+ registeredShared.loading = loading;
2448
+ }
2449
+ });
2450
+ }
2451
+ _setGlobalShareScopeMap(hostOptions) {
2452
+ const globalShareScopeMap = getGlobalShareScope();
2453
+ const identifier = hostOptions.id || hostOptions.name;
2454
+ if (identifier && !globalShareScopeMap[identifier]) {
2455
+ globalShareScopeMap[identifier] = this.shareScopeMap;
2456
+ }
2457
+ }
2458
+ constructor(host){
2459
+ this.hooks = new PluginSystem({
2460
+ afterResolve: new AsyncWaterfallHook('afterResolve'),
2461
+ beforeLoadShare: new AsyncWaterfallHook('beforeLoadShare'),
2462
+ // not used yet
2463
+ loadShare: new AsyncHook(),
2464
+ resolveShare: new SyncWaterfallHook('resolveShare'),
2465
+ // maybe will change, temporarily for internal use only
2466
+ initContainerShareScopeMap: new SyncWaterfallHook('initContainerShareScopeMap')
2467
+ });
2468
+ this.host = host;
2469
+ this.shareScopeMap = {};
2470
+ this.initTokens = {};
2471
+ this._setGlobalShareScopeMap(host.options);
2472
+ }
2473
+ }
2474
+
2475
+ class RemoteHandler {
2476
+ formatAndRegisterRemote(globalOptions, userOptions) {
2477
+ const userRemotes = userOptions.remotes || [];
2478
+ return userRemotes.reduce((res, remote)=>{
2479
+ this.registerRemote(remote, res, {
2480
+ force: false
2481
+ });
2482
+ return res;
2483
+ }, globalOptions.remotes);
2484
+ }
2485
+ setIdToRemoteMap(id, remoteMatchInfo) {
2486
+ const { remote, expose } = remoteMatchInfo;
2487
+ const { name, alias } = remote;
2488
+ this.idToRemoteMap[id] = {
2489
+ name: remote.name,
2490
+ expose
2491
+ };
2492
+ if (alias && id.startsWith(name)) {
2493
+ const idWithAlias = id.replace(name, alias);
2494
+ this.idToRemoteMap[idWithAlias] = {
2495
+ name: remote.name,
2496
+ expose
2497
+ };
2498
+ return;
2499
+ }
2500
+ if (alias && id.startsWith(alias)) {
2501
+ const idWithName = id.replace(alias, name);
2502
+ this.idToRemoteMap[idWithName] = {
2503
+ name: remote.name,
2504
+ expose
2505
+ };
2506
+ }
2507
+ }
2508
+ // eslint-disable-next-line max-lines-per-function
2509
+ // eslint-disable-next-line @typescript-eslint/member-ordering
2510
+ async loadRemote(id, options) {
2511
+ const { host } = this;
2512
+ try {
2513
+ const { loadFactory = true } = options || {
2514
+ loadFactory: true
2515
+ };
2516
+ // 1. Validate the parameters of the retrieved module. There are two module request methods: pkgName + expose and alias + expose.
2517
+ // 2. Request the snapshot information of the current host and globally store the obtained snapshot information. The retrieved module information is partially offline and partially online. The online module information will retrieve the modules used online.
2518
+ // 3. Retrieve the detailed information of the current module from global (remoteEntry address, expose resource address)
2519
+ // 4. After retrieving remoteEntry, call the init of the module, and then retrieve the exported content of the module through get
2520
+ // id: pkgName(@federation/app1) + expose(button) = @federation/app1/button
2521
+ // id: alias(app1) + expose(button) = app1/button
2522
+ // id: alias(app1/utils) + expose(loadash/sort) = app1/utils/loadash/sort
2523
+ const { module, moduleOptions, remoteMatchInfo } = await this.getRemoteModuleAndOptions({
2524
+ id
2525
+ });
2526
+ const { pkgNameOrAlias, remote, expose, id: idRes, remoteSnapshot } = remoteMatchInfo;
2527
+ const moduleOrFactory = await module.get(idRes, expose, options, remoteSnapshot);
2528
+ const moduleWrapper = await this.hooks.lifecycle.onLoad.emit({
2529
+ id: idRes,
2530
+ pkgNameOrAlias,
2531
+ expose,
2532
+ exposeModule: loadFactory ? moduleOrFactory : undefined,
2533
+ exposeModuleFactory: loadFactory ? undefined : moduleOrFactory,
2534
+ remote,
2535
+ options: moduleOptions,
2536
+ moduleInstance: module,
2537
+ origin: host
2538
+ });
2539
+ this.setIdToRemoteMap(id, remoteMatchInfo);
2540
+ if (typeof moduleWrapper === 'function') {
2541
+ return moduleWrapper;
2542
+ }
2543
+ return moduleOrFactory;
2544
+ } catch (error) {
2545
+ const { from = 'runtime' } = options || {
2546
+ from: 'runtime'
2547
+ };
2548
+ const failOver = await this.hooks.lifecycle.errorLoadRemote.emit({
2549
+ id,
2550
+ error,
2551
+ from,
2552
+ lifecycle: 'onLoad',
2553
+ origin: host
2554
+ });
2555
+ if (!failOver) {
2556
+ throw error;
2557
+ }
2558
+ return failOver;
2559
+ }
2560
+ }
2561
+ // eslint-disable-next-line @typescript-eslint/member-ordering
2562
+ async preloadRemote(preloadOptions) {
2563
+ const { host } = this;
2564
+ await this.hooks.lifecycle.beforePreloadRemote.emit({
2565
+ preloadOps: preloadOptions,
2566
+ options: host.options,
2567
+ origin: host
2568
+ });
2569
+ const preloadOps = formatPreloadArgs(host.options.remotes, preloadOptions);
2570
+ await Promise.all(preloadOps.map(async (ops)=>{
2571
+ const { remote } = ops;
2572
+ const remoteInfo = getRemoteInfo(remote);
2573
+ const { globalSnapshot, remoteSnapshot } = await host.snapshotHandler.loadRemoteSnapshotInfo(remote);
2574
+ const assets = await this.hooks.lifecycle.generatePreloadAssets.emit({
2575
+ origin: host,
2576
+ preloadOptions: ops,
2577
+ remote,
2578
+ remoteInfo,
2579
+ globalSnapshot,
2580
+ remoteSnapshot
2581
+ });
2582
+ if (!assets) {
2583
+ return;
2584
+ }
2585
+ preloadAssets(remoteInfo, host, assets);
2586
+ }));
2587
+ }
2588
+ registerRemotes(remotes, options) {
2589
+ const { host } = this;
2590
+ remotes.forEach((remote)=>{
2591
+ this.registerRemote(remote, host.options.remotes, {
2592
+ force: options == null ? void 0 : options.force
2593
+ });
2594
+ });
2595
+ }
2596
+ async getRemoteModuleAndOptions(options) {
2597
+ const { host } = this;
2598
+ const { id } = options;
2599
+ let loadRemoteArgs;
2600
+ try {
2601
+ loadRemoteArgs = await this.hooks.lifecycle.beforeRequest.emit({
2602
+ id,
2603
+ options: host.options,
2604
+ origin: host
2605
+ });
2606
+ } catch (error) {
2607
+ loadRemoteArgs = await this.hooks.lifecycle.errorLoadRemote.emit({
2608
+ id,
2609
+ options: host.options,
2610
+ origin: host,
2611
+ from: 'runtime',
2612
+ error,
2613
+ lifecycle: 'beforeRequest'
2614
+ });
2615
+ if (!loadRemoteArgs) {
2616
+ throw error;
2617
+ }
2618
+ }
2619
+ const { id: idRes } = loadRemoteArgs;
2620
+ const remoteSplitInfo = matchRemoteWithNameAndExpose(host.options.remotes, idRes);
2621
+ assert(remoteSplitInfo, errorCodes.getShortErrorMsg(errorCodes.RUNTIME_004, errorCodes.runtimeDescMap, {
2622
+ hostName: host.options.name,
2623
+ requestId: idRes
2624
+ }));
2625
+ const { remote: rawRemote } = remoteSplitInfo;
2626
+ const remoteInfo = getRemoteInfo(rawRemote);
2627
+ const matchInfo = await host.sharedHandler.hooks.lifecycle.afterResolve.emit(polyfills._extends({
2628
+ id: idRes
2629
+ }, remoteSplitInfo, {
2630
+ options: host.options,
2631
+ origin: host,
2632
+ remoteInfo
2633
+ }));
2634
+ const { remote, expose } = matchInfo;
2635
+ assert(remote && expose, `The 'beforeRequest' hook was executed, but it failed to return the correct 'remote' and 'expose' values while loading ${idRes}.`);
2636
+ let module = host.moduleCache.get(remote.name);
2637
+ const moduleOptions = {
2638
+ host: host,
2639
+ remoteInfo
2640
+ };
2641
+ if (!module) {
2642
+ module = new Module(moduleOptions);
2643
+ host.moduleCache.set(remote.name, module);
2644
+ }
2645
+ return {
2646
+ module,
2647
+ moduleOptions,
2648
+ remoteMatchInfo: matchInfo
2649
+ };
2650
+ }
2651
+ registerRemote(remote, targetRemotes, options) {
2652
+ const { host } = this;
2653
+ const normalizeRemote = ()=>{
2654
+ if (remote.alias) {
2655
+ // Validate if alias equals the prefix of remote.name and remote.alias, if so, throw an error
2656
+ // As multi-level path references cannot guarantee unique names, alias being a prefix of remote.name is not supported
2657
+ const findEqual = targetRemotes.find((item)=>{
2658
+ var _item_alias;
2659
+ return remote.alias && (item.name.startsWith(remote.alias) || ((_item_alias = item.alias) == null ? void 0 : _item_alias.startsWith(remote.alias)));
2660
+ });
2661
+ assert(!findEqual, `The alias ${remote.alias} of remote ${remote.name} is not allowed to be the prefix of ${findEqual && findEqual.name} name or alias`);
2662
+ }
2663
+ // Set the remote entry to a complete path
2664
+ if ('entry' in remote) {
2665
+ if (sdk.isBrowserEnv() && !remote.entry.startsWith('http')) {
2666
+ remote.entry = new URL(remote.entry, window.location.origin).href;
2667
+ }
2668
+ }
2669
+ if (!remote.shareScope) {
2670
+ remote.shareScope = DEFAULT_SCOPE;
2671
+ }
2672
+ if (!remote.type) {
2673
+ remote.type = DEFAULT_REMOTE_TYPE;
2674
+ }
2675
+ };
2676
+ this.hooks.lifecycle.beforeRegisterRemote.emit({
2677
+ remote,
2678
+ origin: host
2679
+ });
2680
+ const registeredRemote = targetRemotes.find((item)=>item.name === remote.name);
2681
+ if (!registeredRemote) {
2682
+ normalizeRemote();
2683
+ targetRemotes.push(remote);
2684
+ this.hooks.lifecycle.registerRemote.emit({
2685
+ remote,
2686
+ origin: host
2687
+ });
2688
+ } else {
2689
+ const messages = [
2690
+ `The remote "${remote.name}" is already registered.`,
2691
+ (options == null ? void 0 : options.force) ? 'Hope you have known that OVERRIDE it may have some unexpected errors' : 'If you want to merge the remote, you can set "force: true".'
2692
+ ];
2693
+ if (options == null ? void 0 : options.force) {
2694
+ // remove registered remote
2695
+ this.removeRemote(registeredRemote);
2696
+ normalizeRemote();
2697
+ targetRemotes.push(remote);
2698
+ this.hooks.lifecycle.registerRemote.emit({
2699
+ remote,
2700
+ origin: host
2701
+ });
2702
+ }
2703
+ sdk.warn(messages.join(' '));
2704
+ }
2705
+ }
2706
+ removeRemote(remote) {
2707
+ try {
2708
+ const { host } = this;
2709
+ const { name } = remote;
2710
+ const remoteIndex = host.options.remotes.findIndex((item)=>item.name === name);
2711
+ if (remoteIndex !== -1) {
2712
+ host.options.remotes.splice(remoteIndex, 1);
2713
+ }
2714
+ const loadedModule = host.moduleCache.get(remote.name);
2715
+ if (loadedModule) {
2716
+ const remoteInfo = loadedModule.remoteInfo;
2717
+ const key = remoteInfo.entryGlobalName;
2718
+ if (CurrentGlobal[key]) {
2719
+ var _Object_getOwnPropertyDescriptor;
2720
+ if ((_Object_getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor(CurrentGlobal, key)) == null ? void 0 : _Object_getOwnPropertyDescriptor.configurable) {
2721
+ delete CurrentGlobal[key];
2722
+ } else {
2723
+ // @ts-ignore
2724
+ CurrentGlobal[key] = undefined;
2725
+ }
2726
+ }
2727
+ const remoteEntryUniqueKey = getRemoteEntryUniqueKey(loadedModule.remoteInfo);
2728
+ if (globalLoading[remoteEntryUniqueKey]) {
2729
+ delete globalLoading[remoteEntryUniqueKey];
2730
+ }
2731
+ host.snapshotHandler.manifestCache.delete(remoteInfo.entry);
2732
+ // delete unloaded shared and instance
2733
+ let remoteInsId = remoteInfo.buildVersion ? sdk.composeKeyWithSeparator(remoteInfo.name, remoteInfo.buildVersion) : remoteInfo.name;
2734
+ const remoteInsIndex = CurrentGlobal.__FEDERATION__.__INSTANCES__.findIndex((ins)=>{
2735
+ if (remoteInfo.buildVersion) {
2736
+ return ins.options.id === remoteInsId;
2737
+ } else {
2738
+ return ins.name === remoteInsId;
2739
+ }
2740
+ });
2741
+ if (remoteInsIndex !== -1) {
2742
+ const remoteIns = CurrentGlobal.__FEDERATION__.__INSTANCES__[remoteInsIndex];
2743
+ remoteInsId = remoteIns.options.id || remoteInsId;
2744
+ const globalShareScopeMap = getGlobalShareScope();
2745
+ let isAllSharedNotUsed = true;
2746
+ const needDeleteKeys = [];
2747
+ Object.keys(globalShareScopeMap).forEach((instId)=>{
2748
+ const shareScopeMap = globalShareScopeMap[instId];
2749
+ shareScopeMap && Object.keys(shareScopeMap).forEach((shareScope)=>{
2750
+ const shareScopeVal = shareScopeMap[shareScope];
2751
+ shareScopeVal && Object.keys(shareScopeVal).forEach((shareName)=>{
2752
+ const sharedPkgs = shareScopeVal[shareName];
2753
+ sharedPkgs && Object.keys(sharedPkgs).forEach((shareVersion)=>{
2754
+ const shared = sharedPkgs[shareVersion];
2755
+ if (shared && typeof shared === 'object' && shared.from === remoteInfo.name) {
2756
+ if (shared.loaded || shared.loading) {
2757
+ shared.useIn = shared.useIn.filter((usedHostName)=>usedHostName !== remoteInfo.name);
2758
+ if (shared.useIn.length) {
2759
+ isAllSharedNotUsed = false;
2760
+ } else {
2761
+ needDeleteKeys.push([
2762
+ instId,
2763
+ shareScope,
2764
+ shareName,
2765
+ shareVersion
2766
+ ]);
2767
+ }
2768
+ } else {
2769
+ needDeleteKeys.push([
2770
+ instId,
2771
+ shareScope,
2772
+ shareName,
2773
+ shareVersion
2774
+ ]);
2775
+ }
2776
+ }
2777
+ });
2778
+ });
2779
+ });
2780
+ });
2781
+ if (isAllSharedNotUsed) {
2782
+ remoteIns.shareScopeMap = {};
2783
+ delete globalShareScopeMap[remoteInsId];
2784
+ }
2785
+ needDeleteKeys.forEach(([insId, shareScope, shareName, shareVersion])=>{
2786
+ var _globalShareScopeMap_insId_shareScope_shareName, _globalShareScopeMap_insId_shareScope, _globalShareScopeMap_insId;
2787
+ (_globalShareScopeMap_insId = globalShareScopeMap[insId]) == null ? true : (_globalShareScopeMap_insId_shareScope = _globalShareScopeMap_insId[shareScope]) == null ? true : (_globalShareScopeMap_insId_shareScope_shareName = _globalShareScopeMap_insId_shareScope[shareName]) == null ? true : delete _globalShareScopeMap_insId_shareScope_shareName[shareVersion];
2788
+ });
2789
+ CurrentGlobal.__FEDERATION__.__INSTANCES__.splice(remoteInsIndex, 1);
2790
+ }
2791
+ const { hostGlobalSnapshot } = getGlobalRemoteInfo(remote, host);
2792
+ if (hostGlobalSnapshot) {
2793
+ const remoteKey = hostGlobalSnapshot && 'remotesInfo' in hostGlobalSnapshot && hostGlobalSnapshot.remotesInfo && getInfoWithoutType(hostGlobalSnapshot.remotesInfo, remote.name).key;
2794
+ if (remoteKey) {
2795
+ delete hostGlobalSnapshot.remotesInfo[remoteKey];
2796
+ if (//eslint-disable-next-line no-extra-boolean-cast
2797
+ Boolean(Global.__FEDERATION__.__MANIFEST_LOADING__[remoteKey])) {
2798
+ delete Global.__FEDERATION__.__MANIFEST_LOADING__[remoteKey];
2799
+ }
2800
+ }
2801
+ }
2802
+ host.moduleCache.delete(remote.name);
2803
+ }
2804
+ } catch (err) {
2805
+ logger.log('removeRemote fail: ', err);
2806
+ }
2807
+ }
2808
+ constructor(host){
2809
+ this.hooks = new PluginSystem({
2810
+ beforeRegisterRemote: new SyncWaterfallHook('beforeRegisterRemote'),
2811
+ registerRemote: new SyncWaterfallHook('registerRemote'),
2812
+ beforeRequest: new AsyncWaterfallHook('beforeRequest'),
2813
+ onLoad: new AsyncHook('onLoad'),
2814
+ handlePreloadModule: new SyncHook('handlePreloadModule'),
2815
+ errorLoadRemote: new AsyncHook('errorLoadRemote'),
2816
+ beforePreloadRemote: new AsyncHook('beforePreloadRemote'),
2817
+ generatePreloadAssets: new AsyncHook('generatePreloadAssets'),
2818
+ // not used yet
2819
+ afterPreloadRemote: new AsyncHook(),
2820
+ loadEntry: new AsyncHook()
2821
+ });
2822
+ this.host = host;
2823
+ this.idToRemoteMap = {};
2824
+ }
2825
+ }
2826
+
2827
+ class FederationHost {
2828
+ initOptions(userOptions) {
2829
+ this.registerPlugins(userOptions.plugins);
2830
+ const options = this.formatOptions(this.options, userOptions);
2831
+ this.options = options;
2832
+ return options;
2833
+ }
2834
+ async loadShare(pkgName, extraOptions) {
2835
+ return this.sharedHandler.loadShare(pkgName, extraOptions);
2836
+ }
2837
+ // The lib function will only be available if the shared set by eager or runtime init is set or the shared is successfully loaded.
2838
+ // 1. If the loaded shared already exists globally, then it will be reused
2839
+ // 2. If lib exists in local shared, it will be used directly
2840
+ // 3. If the local get returns something other than Promise, then it will be used directly
2841
+ loadShareSync(pkgName, extraOptions) {
2842
+ return this.sharedHandler.loadShareSync(pkgName, extraOptions);
2843
+ }
2844
+ initializeSharing(shareScopeName = DEFAULT_SCOPE, extraOptions) {
2845
+ return this.sharedHandler.initializeSharing(shareScopeName, extraOptions);
2846
+ }
2847
+ initRawContainer(name, url, container) {
2848
+ const remoteInfo = getRemoteInfo({
2849
+ name,
2850
+ entry: url
2851
+ });
2852
+ const module = new Module({
2853
+ host: this,
2854
+ remoteInfo
2855
+ });
2856
+ module.remoteEntryExports = container;
2857
+ this.moduleCache.set(name, module);
2858
+ return module;
2859
+ }
2860
+ // eslint-disable-next-line max-lines-per-function
2861
+ // eslint-disable-next-line @typescript-eslint/member-ordering
2862
+ async loadRemote(id, options) {
2863
+ return this.remoteHandler.loadRemote(id, options);
2864
+ }
2865
+ // eslint-disable-next-line @typescript-eslint/member-ordering
2866
+ async preloadRemote(preloadOptions) {
2867
+ return this.remoteHandler.preloadRemote(preloadOptions);
2868
+ }
2869
+ initShareScopeMap(scopeName, shareScope, extraOptions = {}) {
2870
+ this.sharedHandler.initShareScopeMap(scopeName, shareScope, extraOptions);
2871
+ }
2872
+ formatOptions(globalOptions, userOptions) {
2873
+ const { shared } = formatShareConfigs(globalOptions, userOptions);
2874
+ const { userOptions: userOptionsRes, options: globalOptionsRes } = this.hooks.lifecycle.beforeInit.emit({
2875
+ origin: this,
2876
+ userOptions,
2877
+ options: globalOptions,
2878
+ shareInfo: shared
2879
+ });
2880
+ const remotes = this.remoteHandler.formatAndRegisterRemote(globalOptionsRes, userOptionsRes);
2881
+ const { shared: handledShared } = this.sharedHandler.registerShared(globalOptionsRes, userOptionsRes);
2882
+ const plugins = [
2883
+ ...globalOptionsRes.plugins
2884
+ ];
2885
+ if (userOptionsRes.plugins) {
2886
+ userOptionsRes.plugins.forEach((plugin)=>{
2887
+ if (!plugins.includes(plugin)) {
2888
+ plugins.push(plugin);
2889
+ }
2890
+ });
2891
+ }
2892
+ const optionsRes = polyfills._extends({}, globalOptions, userOptions, {
2893
+ plugins,
2894
+ remotes,
2895
+ shared: handledShared
2896
+ });
2897
+ this.hooks.lifecycle.init.emit({
2898
+ origin: this,
2899
+ options: optionsRes
2900
+ });
2901
+ return optionsRes;
2902
+ }
2903
+ registerPlugins(plugins) {
2904
+ const pluginRes = registerPlugins(plugins, [
2905
+ this.hooks,
2906
+ this.remoteHandler.hooks,
2907
+ this.sharedHandler.hooks,
2908
+ this.snapshotHandler.hooks,
2909
+ this.loaderHook,
2910
+ this.bridgeHook
2911
+ ]);
2912
+ // Merge plugin
2913
+ this.options.plugins = this.options.plugins.reduce((res, plugin)=>{
2914
+ if (!plugin) return res;
2915
+ if (res && !res.find((item)=>item.name === plugin.name)) {
2916
+ res.push(plugin);
2917
+ }
2918
+ return res;
2919
+ }, pluginRes || []);
2920
+ }
2921
+ registerRemotes(remotes, options) {
2922
+ return this.remoteHandler.registerRemotes(remotes, options);
2923
+ }
2924
+ constructor(userOptions){
2925
+ this.hooks = new PluginSystem({
2926
+ beforeInit: new SyncWaterfallHook('beforeInit'),
2927
+ init: new SyncHook(),
2928
+ // maybe will change, temporarily for internal use only
2929
+ beforeInitContainer: new AsyncWaterfallHook('beforeInitContainer'),
2930
+ // maybe will change, temporarily for internal use only
2931
+ initContainer: new AsyncWaterfallHook('initContainer')
2932
+ });
2933
+ this.version = "0.6.14";
2934
+ this.moduleCache = new Map();
2935
+ this.loaderHook = new PluginSystem({
2936
+ // FIXME: may not be suitable , not open to the public yet
2937
+ getModuleInfo: new SyncHook(),
2938
+ createScript: new SyncHook(),
2939
+ createLink: new SyncHook(),
2940
+ // only work for manifest , so not open to the public yet
2941
+ fetch: new AsyncHook(),
2942
+ getModuleFactory: new AsyncHook()
2943
+ });
2944
+ this.bridgeHook = new PluginSystem({
2945
+ beforeBridgeRender: new SyncHook(),
2946
+ afterBridgeRender: new SyncHook(),
2947
+ beforeBridgeDestroy: new SyncHook(),
2948
+ afterBridgeDestroy: new SyncHook()
2949
+ });
2950
+ // TODO: Validate the details of the options
2951
+ // Initialize options with default values
2952
+ const defaultOptions = {
2953
+ id: getBuilderId(),
2954
+ name: userOptions.name,
2955
+ plugins: [
2956
+ snapshotPlugin(),
2957
+ generatePreloadAssetsPlugin()
2958
+ ],
2959
+ remotes: [],
2960
+ shared: {},
2961
+ inBrowser: sdk.isBrowserEnv()
2962
+ };
2963
+ this.name = userOptions.name;
2964
+ this.options = defaultOptions;
2965
+ this.snapshotHandler = new SnapshotHandler(this);
2966
+ this.sharedHandler = new SharedHandler(this);
2967
+ this.remoteHandler = new RemoteHandler(this);
2968
+ this.shareScopeMap = this.sharedHandler.shareScopeMap;
2969
+ this.registerPlugins([
2970
+ ...defaultOptions.plugins,
2971
+ ...userOptions.plugins || []
2972
+ ]);
2973
+ this.options = this.formatOptions(defaultOptions, userOptions);
2974
+ }
2975
+ }
2976
+
2977
+ var index = /*#__PURE__*/Object.freeze({
2978
+ __proto__: null
2979
+ });
2980
+
2981
+ Object.defineProperty(exports, "loadScript", {
2982
+ enumerable: true,
2983
+ get: function () { return sdk.loadScript; }
2984
+ });
2985
+ Object.defineProperty(exports, "loadScriptNode", {
2986
+ enumerable: true,
2987
+ get: function () { return sdk.loadScriptNode; }
2988
+ });
2989
+ exports.CurrentGlobal = CurrentGlobal;
2990
+ exports.FederationHost = FederationHost;
2991
+ exports.Global = Global;
2992
+ exports.Module = Module;
2993
+ exports.addGlobalSnapshot = addGlobalSnapshot;
2994
+ exports.assert = assert;
2995
+ exports.getGlobalFederationConstructor = getGlobalFederationConstructor;
2996
+ exports.getGlobalSnapshot = getGlobalSnapshot;
2997
+ exports.getInfoWithoutType = getInfoWithoutType;
2998
+ exports.getRegisteredShare = getRegisteredShare;
2999
+ exports.getRemoteEntry = getRemoteEntry;
3000
+ exports.getRemoteInfo = getRemoteInfo;
3001
+ exports.helpers = helpers;
3002
+ exports.isStaticResourcesEqual = isStaticResourcesEqual;
3003
+ exports.matchRemoteWithNameAndExpose = matchRemoteWithNameAndExpose;
3004
+ exports.registerGlobalPlugins = registerGlobalPlugins;
3005
+ exports.resetFederationGlobalInfo = resetFederationGlobalInfo;
3006
+ exports.safeWrapper = safeWrapper;
3007
+ exports.satisfy = satisfy;
3008
+ exports.setGlobalFederationConstructor = setGlobalFederationConstructor;
3009
+ exports.setGlobalFederationInstance = setGlobalFederationInstance;
3010
+ exports.types = index;