iobroker.utility-monitor 1.4.6 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +110 -62
  2. package/admin/custom/.vite/manifest.json +90 -0
  3. package/admin/custom/@mf-types/Components.d.ts +2 -0
  4. package/admin/custom/@mf-types/compiled-types/Components/CSVImporter.d.ts +11 -0
  5. package/admin/custom/@mf-types/compiled-types/Components.d.ts +2 -0
  6. package/admin/custom/@mf-types.d.ts +3 -0
  7. package/admin/custom/@mf-types.zip +0 -0
  8. package/admin/custom/CSVImporter_v15_11.js +4415 -0
  9. package/admin/custom/assets/Components-i0AZ59nl.js +18887 -0
  10. package/admin/custom/assets/UtilityMonitor__loadShare__react__loadShare__-Da99Mak4.js +42 -0
  11. package/admin/custom/assets/UtilityMonitor__mf_v__runtimeInit__mf_v__-BmC4OGk6.js +16 -0
  12. package/admin/custom/assets/_commonjsHelpers-Dj2_voLF.js +30 -0
  13. package/admin/custom/assets/hostInit-DEXfeB0W.js +10 -0
  14. package/admin/custom/assets/index-B3WVNJTz.js +401 -0
  15. package/admin/custom/assets/index-VBwl8x_k.js +64 -0
  16. package/admin/custom/assets/preload-helper-BelkbqnE.js +61 -0
  17. package/admin/custom/assets/virtualExposes-CqCLUNLT.js +19 -0
  18. package/admin/custom/index.html +12 -0
  19. package/admin/custom/mf-manifest.json +1 -0
  20. package/admin/jsonConfig.json +90 -31
  21. package/io-package.json +15 -31
  22. package/lib/billingManager.js +382 -137
  23. package/lib/calculator.js +41 -146
  24. package/lib/consumptionManager.js +9 -252
  25. package/lib/importManager.js +300 -0
  26. package/lib/messagingHandler.js +4 -2
  27. package/lib/meter/MeterRegistry.js +110 -0
  28. package/lib/multiMeterManager.js +580 -173
  29. package/lib/stateManager.js +502 -31
  30. package/lib/utils/billingHelper.js +69 -0
  31. package/lib/utils/consumptionHelper.js +47 -0
  32. package/lib/utils/helpers.js +234 -0
  33. package/lib/utils/stateCache.js +147 -0
  34. package/lib/utils/typeMapper.js +19 -0
  35. package/main.js +67 -8
  36. package/package.json +10 -4
@@ -0,0 +1,4415 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-VBwl8x_k.js","assets/_commonjsHelpers-Dj2_voLF.js","assets/index-B3WVNJTz.js","assets/UtilityMonitor__loadShare__react__loadShare__-Da99Mak4.js","assets/UtilityMonitor__mf_v__runtimeInit__mf_v__-BmC4OGk6.js"])))=>i.map(i=>d[i]);
2
+ import exposesMap from './assets/virtualExposes-CqCLUNLT.js';
3
+ import { _ as __vitePreload } from './assets/preload-helper-BelkbqnE.js';
4
+ import { U as UtilityMonitor__mf_v__runtimeInit__mf_v__ } from './assets/UtilityMonitor__mf_v__runtimeInit__mf_v__-BmC4OGk6.js';
5
+
6
+ var index_cjs$2 = {};
7
+
8
+ var index_cjs$1 = {};
9
+
10
+ var define_process_env_default = {};
11
+ const FederationModuleManifest = "federation-manifest.json";
12
+ const MANIFEST_EXT = ".json";
13
+ const BROWSER_LOG_KEY = "FEDERATION_DEBUG";
14
+ const NameTransformSymbol = {
15
+ AT: "@",
16
+ HYPHEN: "-",
17
+ SLASH: "/"
18
+ };
19
+ const NameTransformMap = {
20
+ [NameTransformSymbol.AT]: "scope_",
21
+ [NameTransformSymbol.HYPHEN]: "_",
22
+ [NameTransformSymbol.SLASH]: "__"
23
+ };
24
+ const EncodedNameTransformMap = {
25
+ [NameTransformMap[NameTransformSymbol.AT]]: NameTransformSymbol.AT,
26
+ [NameTransformMap[NameTransformSymbol.HYPHEN]]: NameTransformSymbol.HYPHEN,
27
+ [NameTransformMap[NameTransformSymbol.SLASH]]: NameTransformSymbol.SLASH
28
+ };
29
+ const SEPARATOR = ":";
30
+ const ManifestFileName = "mf-manifest.json";
31
+ const StatsFileName = "mf-stats.json";
32
+ const MFModuleType = {
33
+ NPM: "npm",
34
+ APP: "app"
35
+ };
36
+ const MODULE_DEVTOOL_IDENTIFIER = "__MF_DEVTOOLS_MODULE_INFO__";
37
+ const ENCODE_NAME_PREFIX = "ENCODE_NAME_PREFIX";
38
+ const TEMP_DIR = ".federation";
39
+ const MFPrefetchCommon = {
40
+ identifier: "MFDataPrefetch",
41
+ globalKey: "__PREFETCH__",
42
+ library: "mf-data-prefetch",
43
+ exportsKey: "__PREFETCH_EXPORTS__",
44
+ fileName: "bootstrap.js"
45
+ };
46
+ var ContainerPlugin = /* @__PURE__ */ Object.freeze({
47
+ __proto__: null
48
+ });
49
+ var ContainerReferencePlugin = /* @__PURE__ */ Object.freeze({
50
+ __proto__: null
51
+ });
52
+ var ModuleFederationPlugin = /* @__PURE__ */ Object.freeze({
53
+ __proto__: null
54
+ });
55
+ var SharePlugin = /* @__PURE__ */ Object.freeze({
56
+ __proto__: null
57
+ });
58
+ function isBrowserEnv() {
59
+ return typeof window !== "undefined" && typeof window.document !== "undefined";
60
+ }
61
+ function isReactNativeEnv() {
62
+ return typeof navigator !== "undefined" && navigator?.product === "ReactNative";
63
+ }
64
+ function isBrowserDebug() {
65
+ try {
66
+ if (isBrowserEnv() && window.localStorage) {
67
+ return Boolean(localStorage.getItem(BROWSER_LOG_KEY));
68
+ }
69
+ } catch (error2) {
70
+ return false;
71
+ }
72
+ return false;
73
+ }
74
+ function isDebugMode() {
75
+ if (typeof process !== "undefined" && define_process_env_default && define_process_env_default["FEDERATION_DEBUG"]) {
76
+ return Boolean(define_process_env_default["FEDERATION_DEBUG"]);
77
+ }
78
+ if (typeof FEDERATION_DEBUG !== "undefined" && Boolean(FEDERATION_DEBUG)) {
79
+ return true;
80
+ }
81
+ return isBrowserDebug();
82
+ }
83
+ const getProcessEnv = function() {
84
+ return typeof process !== "undefined" && define_process_env_default ? define_process_env_default : {};
85
+ };
86
+ const LOG_CATEGORY$1 = "[ Federation Runtime ]";
87
+ const parseEntry = (str, devVerOrUrl, separator = SEPARATOR) => {
88
+ const strSplit = str.split(separator);
89
+ const devVersionOrUrl = getProcessEnv()["NODE_ENV"] === "development" && devVerOrUrl;
90
+ const defaultVersion = "*";
91
+ const isEntry = (s) => s.startsWith("http") || s.includes(MANIFEST_EXT);
92
+ if (strSplit.length >= 2) {
93
+ let [name, ...versionOrEntryArr] = strSplit;
94
+ if (str.startsWith(separator)) {
95
+ name = strSplit.slice(0, 2).join(separator);
96
+ versionOrEntryArr = [
97
+ devVersionOrUrl || strSplit.slice(2).join(separator)
98
+ ];
99
+ }
100
+ let versionOrEntry = devVersionOrUrl || versionOrEntryArr.join(separator);
101
+ if (isEntry(versionOrEntry)) {
102
+ return {
103
+ name,
104
+ entry: versionOrEntry
105
+ };
106
+ } else {
107
+ return {
108
+ name,
109
+ version: versionOrEntry || defaultVersion
110
+ };
111
+ }
112
+ } else if (strSplit.length === 1) {
113
+ const [name] = strSplit;
114
+ if (devVersionOrUrl && isEntry(devVersionOrUrl)) {
115
+ return {
116
+ name,
117
+ entry: devVersionOrUrl
118
+ };
119
+ }
120
+ return {
121
+ name,
122
+ version: devVersionOrUrl || defaultVersion
123
+ };
124
+ } else {
125
+ throw `Invalid entry value: ${str}`;
126
+ }
127
+ };
128
+ const composeKeyWithSeparator = function(...args) {
129
+ if (!args.length) {
130
+ return "";
131
+ }
132
+ return args.reduce((sum, cur) => {
133
+ if (!cur) {
134
+ return sum;
135
+ }
136
+ if (!sum) {
137
+ return cur;
138
+ }
139
+ return `${sum}${SEPARATOR}${cur}`;
140
+ }, "");
141
+ };
142
+ const encodeName = function(name, prefix = "", withExt = false) {
143
+ try {
144
+ const ext = withExt ? ".js" : "";
145
+ return `${prefix}${name.replace(new RegExp(`${NameTransformSymbol.AT}`, "g"), NameTransformMap[NameTransformSymbol.AT]).replace(new RegExp(`${NameTransformSymbol.HYPHEN}`, "g"), NameTransformMap[NameTransformSymbol.HYPHEN]).replace(new RegExp(`${NameTransformSymbol.SLASH}`, "g"), NameTransformMap[NameTransformSymbol.SLASH])}${ext}`;
146
+ } catch (err) {
147
+ throw err;
148
+ }
149
+ };
150
+ const decodeName = function(name, prefix, withExt) {
151
+ try {
152
+ let decodedName = name;
153
+ if (prefix) {
154
+ if (!decodedName.startsWith(prefix)) {
155
+ return decodedName;
156
+ }
157
+ decodedName = decodedName.replace(new RegExp(prefix, "g"), "");
158
+ }
159
+ decodedName = decodedName.replace(new RegExp(`${NameTransformMap[NameTransformSymbol.AT]}`, "g"), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.AT]]).replace(new RegExp(`${NameTransformMap[NameTransformSymbol.SLASH]}`, "g"), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.SLASH]]).replace(new RegExp(`${NameTransformMap[NameTransformSymbol.HYPHEN]}`, "g"), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.HYPHEN]]);
160
+ if (withExt) {
161
+ decodedName = decodedName.replace(".js", "");
162
+ }
163
+ return decodedName;
164
+ } catch (err) {
165
+ throw err;
166
+ }
167
+ };
168
+ const generateExposeFilename = (exposeName, withExt) => {
169
+ if (!exposeName) {
170
+ return "";
171
+ }
172
+ let expose = exposeName;
173
+ if (expose === ".") {
174
+ expose = "default_export";
175
+ }
176
+ if (expose.startsWith("./")) {
177
+ expose = expose.replace("./", "");
178
+ }
179
+ return encodeName(expose, "__federation_expose_", withExt);
180
+ };
181
+ const generateShareFilename = (pkgName, withExt) => {
182
+ if (!pkgName) {
183
+ return "";
184
+ }
185
+ return encodeName(pkgName, "__federation_shared_", withExt);
186
+ };
187
+ const getResourceUrl = (module, sourceUrl) => {
188
+ if ("getPublicPath" in module) {
189
+ let publicPath;
190
+ if (!module.getPublicPath.startsWith("function")) {
191
+ publicPath = new Function(module.getPublicPath)();
192
+ } else {
193
+ publicPath = new Function("return " + module.getPublicPath)()();
194
+ }
195
+ return `${publicPath}${sourceUrl}`;
196
+ } else if ("publicPath" in module) {
197
+ if (!isBrowserEnv() && !isReactNativeEnv() && "ssrPublicPath" in module) {
198
+ return `${module.ssrPublicPath}${sourceUrl}`;
199
+ }
200
+ return `${module.publicPath}${sourceUrl}`;
201
+ } else {
202
+ console.warn("Cannot get resource URL. If in debug mode, please ignore.", module, sourceUrl);
203
+ return "";
204
+ }
205
+ };
206
+ const assert$1 = (condition, msg) => {
207
+ if (!condition) {
208
+ error$1(msg);
209
+ }
210
+ };
211
+ const error$1 = (msg) => {
212
+ throw new Error(`${LOG_CATEGORY$1}: ${msg}`);
213
+ };
214
+ const warn$1 = (msg) => {
215
+ console.warn(`${LOG_CATEGORY$1}: ${msg}`);
216
+ };
217
+ function safeToString(info) {
218
+ try {
219
+ return JSON.stringify(info, null, 2);
220
+ } catch (e) {
221
+ return "";
222
+ }
223
+ }
224
+ const VERSION_PATTERN_REGEXP = /^([\d^=v<>~]|[*xX]$)/;
225
+ function isRequiredVersion(str) {
226
+ return VERSION_PATTERN_REGEXP.test(str);
227
+ }
228
+ const simpleJoinRemoteEntry = (rPath, rName) => {
229
+ if (!rPath) {
230
+ return rName;
231
+ }
232
+ const transformPath = (str) => {
233
+ if (str === ".") {
234
+ return "";
235
+ }
236
+ if (str.startsWith("./")) {
237
+ return str.replace("./", "");
238
+ }
239
+ if (str.startsWith("/")) {
240
+ const strWithoutSlash = str.slice(1);
241
+ if (strWithoutSlash.endsWith("/")) {
242
+ return strWithoutSlash.slice(0, -1);
243
+ }
244
+ return strWithoutSlash;
245
+ }
246
+ return str;
247
+ };
248
+ const transformedPath = transformPath(rPath);
249
+ if (!transformedPath) {
250
+ return rName;
251
+ }
252
+ if (transformedPath.endsWith("/")) {
253
+ return `${transformedPath}${rName}`;
254
+ }
255
+ return `${transformedPath}/${rName}`;
256
+ };
257
+ function inferAutoPublicPath(url2) {
258
+ return url2.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/");
259
+ }
260
+ function generateSnapshotFromManifest(manifest, options = {}) {
261
+ const { remotes = {}, overrides = {}, version } = options;
262
+ let remoteSnapshot;
263
+ const getPublicPath = () => {
264
+ if ("publicPath" in manifest.metaData) {
265
+ if (manifest.metaData.publicPath === "auto" && version) {
266
+ return inferAutoPublicPath(version);
267
+ }
268
+ return manifest.metaData.publicPath;
269
+ } else {
270
+ return manifest.metaData.getPublicPath;
271
+ }
272
+ };
273
+ const overridesKeys = Object.keys(overrides);
274
+ let remotesInfo = {};
275
+ if (!Object.keys(remotes).length) {
276
+ remotesInfo = manifest.remotes?.reduce((res2, next) => {
277
+ let matchedVersion;
278
+ const name = next.federationContainerName;
279
+ if (overridesKeys.includes(name)) {
280
+ matchedVersion = overrides[name];
281
+ } else {
282
+ if ("version" in next) {
283
+ matchedVersion = next.version;
284
+ } else {
285
+ matchedVersion = next.entry;
286
+ }
287
+ }
288
+ res2[name] = {
289
+ matchedVersion
290
+ };
291
+ return res2;
292
+ }, {}) || {};
293
+ }
294
+ Object.keys(remotes).forEach((key) => remotesInfo[key] = {
295
+ // overrides will override dependencies
296
+ matchedVersion: overridesKeys.includes(key) ? overrides[key] : remotes[key]
297
+ });
298
+ const { remoteEntry: { path: remoteEntryPath, name: remoteEntryName, type: remoteEntryType }, types: remoteTypes = { path: "", name: "", zip: "", api: "" }, buildInfo: { buildVersion }, globalName, ssrRemoteEntry } = manifest.metaData;
299
+ const { exposes } = manifest;
300
+ let basicRemoteSnapshot = {
301
+ version: version ? version : "",
302
+ buildVersion,
303
+ globalName,
304
+ remoteEntry: simpleJoinRemoteEntry(remoteEntryPath, remoteEntryName),
305
+ remoteEntryType,
306
+ remoteTypes: simpleJoinRemoteEntry(remoteTypes.path, remoteTypes.name),
307
+ remoteTypesZip: remoteTypes.zip || "",
308
+ remoteTypesAPI: remoteTypes.api || "",
309
+ remotesInfo,
310
+ shared: manifest?.shared.map((item) => ({
311
+ assets: item.assets,
312
+ sharedName: item.name,
313
+ version: item.version
314
+ })),
315
+ modules: exposes?.map((expose) => ({
316
+ moduleName: expose.name,
317
+ modulePath: expose.path,
318
+ assets: expose.assets
319
+ }))
320
+ };
321
+ if (manifest.metaData?.prefetchInterface) {
322
+ const prefetchInterface = manifest.metaData.prefetchInterface;
323
+ basicRemoteSnapshot = {
324
+ ...basicRemoteSnapshot,
325
+ prefetchInterface
326
+ };
327
+ }
328
+ if (manifest.metaData?.prefetchEntry) {
329
+ const { path: path2, name, type } = manifest.metaData.prefetchEntry;
330
+ basicRemoteSnapshot = {
331
+ ...basicRemoteSnapshot,
332
+ prefetchEntry: simpleJoinRemoteEntry(path2, name),
333
+ prefetchEntryType: type
334
+ };
335
+ }
336
+ if ("publicPath" in manifest.metaData) {
337
+ remoteSnapshot = {
338
+ ...basicRemoteSnapshot,
339
+ publicPath: getPublicPath(),
340
+ ssrPublicPath: manifest.metaData.ssrPublicPath
341
+ };
342
+ } else {
343
+ remoteSnapshot = {
344
+ ...basicRemoteSnapshot,
345
+ getPublicPath: getPublicPath()
346
+ };
347
+ }
348
+ if (ssrRemoteEntry) {
349
+ const fullSSRRemoteEntry = simpleJoinRemoteEntry(ssrRemoteEntry.path, ssrRemoteEntry.name);
350
+ remoteSnapshot.ssrRemoteEntry = fullSSRRemoteEntry;
351
+ remoteSnapshot.ssrRemoteEntryType = ssrRemoteEntry.type || "commonjs-module";
352
+ }
353
+ return remoteSnapshot;
354
+ }
355
+ function isManifestProvider(moduleInfo) {
356
+ if ("remoteEntry" in moduleInfo && moduleInfo.remoteEntry.includes(MANIFEST_EXT)) {
357
+ return true;
358
+ } else {
359
+ return false;
360
+ }
361
+ }
362
+ function getManifestFileName(manifestOptions) {
363
+ if (!manifestOptions) {
364
+ return {
365
+ statsFileName: StatsFileName,
366
+ manifestFileName: ManifestFileName
367
+ };
368
+ }
369
+ let filePath = typeof manifestOptions === "boolean" ? "" : manifestOptions.filePath || "";
370
+ let fileName = typeof manifestOptions === "boolean" ? "" : manifestOptions.fileName || "";
371
+ const JSON_EXT = ".json";
372
+ const addExt = (name) => {
373
+ if (name.endsWith(JSON_EXT)) {
374
+ return name;
375
+ }
376
+ return `${name}${JSON_EXT}`;
377
+ };
378
+ const insertSuffix = (name, suffix) => {
379
+ return name.replace(JSON_EXT, `${suffix}${JSON_EXT}`);
380
+ };
381
+ const manifestFileName = fileName ? addExt(fileName) : ManifestFileName;
382
+ const statsFileName = fileName ? insertSuffix(manifestFileName, "-stats") : StatsFileName;
383
+ return {
384
+ statsFileName: simpleJoinRemoteEntry(filePath, statsFileName),
385
+ manifestFileName: simpleJoinRemoteEntry(filePath, manifestFileName)
386
+ };
387
+ }
388
+ const PREFIX = "[ Module Federation ]";
389
+ const DEFAULT_DELEGATE = console;
390
+ const LOGGER_STACK_SKIP_TOKENS = [
391
+ "logger.ts",
392
+ "logger.js",
393
+ "captureStackTrace",
394
+ "Logger.emit",
395
+ "Logger.log",
396
+ "Logger.info",
397
+ "Logger.warn",
398
+ "Logger.error",
399
+ "Logger.debug"
400
+ ];
401
+ function captureStackTrace() {
402
+ try {
403
+ const stack = new Error().stack;
404
+ if (!stack) {
405
+ return void 0;
406
+ }
407
+ const [, ...rawLines] = stack.split("\n");
408
+ const filtered = rawLines.filter((line) => !LOGGER_STACK_SKIP_TOKENS.some((token) => line.includes(token)));
409
+ if (!filtered.length) {
410
+ return void 0;
411
+ }
412
+ const stackPreview = filtered.slice(0, 5).join("\n");
413
+ return `Stack trace:
414
+ ${stackPreview}`;
415
+ } catch {
416
+ return void 0;
417
+ }
418
+ }
419
+ class Logger {
420
+ constructor(prefix, delegate = DEFAULT_DELEGATE) {
421
+ this.prefix = prefix;
422
+ this.delegate = delegate ?? DEFAULT_DELEGATE;
423
+ }
424
+ setPrefix(prefix) {
425
+ this.prefix = prefix;
426
+ }
427
+ setDelegate(delegate) {
428
+ this.delegate = delegate ?? DEFAULT_DELEGATE;
429
+ }
430
+ emit(method, args) {
431
+ const delegate = this.delegate;
432
+ const debugMode = isDebugMode();
433
+ const stackTrace = debugMode ? captureStackTrace() : void 0;
434
+ const enrichedArgs = stackTrace ? [...args, stackTrace] : args;
435
+ const order = (() => {
436
+ switch (method) {
437
+ case "log":
438
+ return ["log", "info"];
439
+ case "info":
440
+ return ["info", "log"];
441
+ case "warn":
442
+ return ["warn", "info", "log"];
443
+ case "error":
444
+ return ["error", "warn", "log"];
445
+ case "debug":
446
+ default:
447
+ return ["debug", "log"];
448
+ }
449
+ })();
450
+ for (const candidate of order) {
451
+ const handler = delegate[candidate];
452
+ if (typeof handler === "function") {
453
+ handler.call(delegate, this.prefix, ...enrichedArgs);
454
+ return;
455
+ }
456
+ }
457
+ for (const candidate of order) {
458
+ const handler = DEFAULT_DELEGATE[candidate];
459
+ if (typeof handler === "function") {
460
+ handler.call(DEFAULT_DELEGATE, this.prefix, ...enrichedArgs);
461
+ return;
462
+ }
463
+ }
464
+ }
465
+ log(...args) {
466
+ this.emit("log", args);
467
+ }
468
+ warn(...args) {
469
+ this.emit("warn", args);
470
+ }
471
+ error(...args) {
472
+ this.emit("error", args);
473
+ }
474
+ success(...args) {
475
+ this.emit("info", args);
476
+ }
477
+ info(...args) {
478
+ this.emit("info", args);
479
+ }
480
+ ready(...args) {
481
+ this.emit("info", args);
482
+ }
483
+ debug(...args) {
484
+ if (isDebugMode()) {
485
+ this.emit("debug", args);
486
+ }
487
+ }
488
+ }
489
+ function createLogger(prefix) {
490
+ return new Logger(prefix);
491
+ }
492
+ function createInfrastructureLogger(prefix) {
493
+ const infrastructureLogger2 = new Logger(prefix);
494
+ Object.defineProperty(infrastructureLogger2, "__mf_infrastructure_logger__", {
495
+ value: true,
496
+ enumerable: false,
497
+ configurable: false
498
+ });
499
+ return infrastructureLogger2;
500
+ }
501
+ function bindLoggerToCompiler(loggerInstance, compiler, name) {
502
+ if (!loggerInstance.__mf_infrastructure_logger__) {
503
+ return;
504
+ }
505
+ if (!compiler?.getInfrastructureLogger) {
506
+ return;
507
+ }
508
+ try {
509
+ const infrastructureLogger2 = compiler.getInfrastructureLogger(name);
510
+ if (infrastructureLogger2 && typeof infrastructureLogger2 === "object" && (typeof infrastructureLogger2.log === "function" || typeof infrastructureLogger2.info === "function" || typeof infrastructureLogger2.warn === "function" || typeof infrastructureLogger2.error === "function")) {
511
+ loggerInstance.setDelegate(infrastructureLogger2);
512
+ }
513
+ } catch {
514
+ loggerInstance.setDelegate(void 0);
515
+ }
516
+ }
517
+ const logger$1 = createLogger(PREFIX);
518
+ const infrastructureLogger = createInfrastructureLogger(PREFIX);
519
+ async function safeWrapper$1(callback, disableWarn) {
520
+ try {
521
+ const res2 = await callback();
522
+ return res2;
523
+ } catch (e) {
524
+ !disableWarn && warn$1(e);
525
+ return;
526
+ }
527
+ }
528
+ function isStaticResourcesEqual$1(url1, url2) {
529
+ const REG_EXP = /^(https?:)?\/\//i;
530
+ const relativeUrl1 = url1.replace(REG_EXP, "").replace(/\/$/, "");
531
+ const relativeUrl2 = url2.replace(REG_EXP, "").replace(/\/$/, "");
532
+ return relativeUrl1 === relativeUrl2;
533
+ }
534
+ function createScript(info) {
535
+ let script2 = null;
536
+ let needAttach = true;
537
+ let timeout = 2e4;
538
+ let timeoutId;
539
+ const scripts = document.getElementsByTagName("script");
540
+ for (let i = 0; i < scripts.length; i++) {
541
+ const s = scripts[i];
542
+ const scriptSrc = s.getAttribute("src");
543
+ if (scriptSrc && isStaticResourcesEqual$1(scriptSrc, info.url)) {
544
+ script2 = s;
545
+ needAttach = false;
546
+ break;
547
+ }
548
+ }
549
+ if (!script2) {
550
+ const attrs2 = info.attrs;
551
+ script2 = document.createElement("script");
552
+ script2.type = attrs2?.["type"] === "module" ? "module" : "text/javascript";
553
+ let createScriptRes = void 0;
554
+ if (info.createScriptHook) {
555
+ createScriptRes = info.createScriptHook(info.url, info.attrs);
556
+ if (createScriptRes instanceof HTMLScriptElement) {
557
+ script2 = createScriptRes;
558
+ } else if (typeof createScriptRes === "object") {
559
+ if ("script" in createScriptRes && createScriptRes.script) {
560
+ script2 = createScriptRes.script;
561
+ }
562
+ if ("timeout" in createScriptRes && createScriptRes.timeout) {
563
+ timeout = createScriptRes.timeout;
564
+ }
565
+ }
566
+ }
567
+ if (!script2.src) {
568
+ script2.src = info.url;
569
+ }
570
+ if (attrs2 && !createScriptRes) {
571
+ Object.keys(attrs2).forEach((name) => {
572
+ if (script2) {
573
+ if (name === "async" || name === "defer") {
574
+ script2[name] = attrs2[name];
575
+ } else if (!script2.getAttribute(name)) {
576
+ script2.setAttribute(name, attrs2[name]);
577
+ }
578
+ }
579
+ });
580
+ }
581
+ }
582
+ const onScriptComplete = async (prev, event) => {
583
+ clearTimeout(timeoutId);
584
+ const onScriptCompleteCallback = () => {
585
+ if (event?.type === "error") {
586
+ info?.onErrorCallback && info?.onErrorCallback(event);
587
+ } else {
588
+ info?.cb && info?.cb();
589
+ }
590
+ };
591
+ if (script2) {
592
+ script2.onerror = null;
593
+ script2.onload = null;
594
+ safeWrapper$1(() => {
595
+ const { needDeleteScript = true } = info;
596
+ if (needDeleteScript) {
597
+ script2?.parentNode && script2.parentNode.removeChild(script2);
598
+ }
599
+ });
600
+ if (prev && typeof prev === "function") {
601
+ const result = prev(event);
602
+ if (result instanceof Promise) {
603
+ const res2 = await result;
604
+ onScriptCompleteCallback();
605
+ return res2;
606
+ }
607
+ onScriptCompleteCallback();
608
+ return result;
609
+ }
610
+ }
611
+ onScriptCompleteCallback();
612
+ };
613
+ script2.onerror = onScriptComplete.bind(null, script2.onerror);
614
+ script2.onload = onScriptComplete.bind(null, script2.onload);
615
+ timeoutId = setTimeout(() => {
616
+ onScriptComplete(null, new Error(`Remote script "${info.url}" time-outed.`));
617
+ }, timeout);
618
+ return { script: script2, needAttach };
619
+ }
620
+ function createLink(info) {
621
+ let link = null;
622
+ let needAttach = true;
623
+ const links = document.getElementsByTagName("link");
624
+ for (let i = 0; i < links.length; i++) {
625
+ const l = links[i];
626
+ const linkHref = l.getAttribute("href");
627
+ const linkRel = l.getAttribute("rel");
628
+ if (linkHref && isStaticResourcesEqual$1(linkHref, info.url) && linkRel === info.attrs["rel"]) {
629
+ link = l;
630
+ needAttach = false;
631
+ break;
632
+ }
633
+ }
634
+ if (!link) {
635
+ link = document.createElement("link");
636
+ link.setAttribute("href", info.url);
637
+ let createLinkRes = void 0;
638
+ const attrs2 = info.attrs;
639
+ if (info.createLinkHook) {
640
+ createLinkRes = info.createLinkHook(info.url, attrs2);
641
+ if (createLinkRes instanceof HTMLLinkElement) {
642
+ link = createLinkRes;
643
+ }
644
+ }
645
+ if (attrs2 && !createLinkRes) {
646
+ Object.keys(attrs2).forEach((name) => {
647
+ if (link && !link.getAttribute(name)) {
648
+ link.setAttribute(name, attrs2[name]);
649
+ }
650
+ });
651
+ }
652
+ }
653
+ const onLinkComplete = (prev, event) => {
654
+ const onLinkCompleteCallback = () => {
655
+ if (event?.type === "error") {
656
+ info?.onErrorCallback && info?.onErrorCallback(event);
657
+ } else {
658
+ info?.cb && info?.cb();
659
+ }
660
+ };
661
+ if (link) {
662
+ link.onerror = null;
663
+ link.onload = null;
664
+ safeWrapper$1(() => {
665
+ const { needDeleteLink = true } = info;
666
+ if (needDeleteLink) {
667
+ link?.parentNode && link.parentNode.removeChild(link);
668
+ }
669
+ });
670
+ if (prev) {
671
+ const res2 = prev(event);
672
+ onLinkCompleteCallback();
673
+ return res2;
674
+ }
675
+ }
676
+ onLinkCompleteCallback();
677
+ };
678
+ link.onerror = onLinkComplete.bind(null, link.onerror);
679
+ link.onload = onLinkComplete.bind(null, link.onload);
680
+ return { link, needAttach };
681
+ }
682
+ function loadScript(url2, info) {
683
+ const { attrs: attrs2 = {}, createScriptHook } = info;
684
+ return new Promise((resolve, reject) => {
685
+ const { script: script2, needAttach } = createScript({
686
+ url: url2,
687
+ cb: resolve,
688
+ onErrorCallback: reject,
689
+ attrs: {
690
+ fetchpriority: "high",
691
+ ...attrs2
692
+ },
693
+ createScriptHook,
694
+ needDeleteScript: true
695
+ });
696
+ needAttach && document.head.appendChild(script2);
697
+ });
698
+ }
699
+ const sdkImportCache = /* @__PURE__ */ new Map();
700
+ function importNodeModule(name) {
701
+ if (!name) {
702
+ throw new Error("import specifier is required");
703
+ }
704
+ if (sdkImportCache.has(name)) {
705
+ return sdkImportCache.get(name);
706
+ }
707
+ const importModule = new Function("name", `return import(name)`);
708
+ const promise = importModule(name).then((res2) => res2).catch((error2) => {
709
+ console.error(`Error importing module ${name}:`, error2);
710
+ sdkImportCache.delete(name);
711
+ throw error2;
712
+ });
713
+ sdkImportCache.set(name, promise);
714
+ return promise;
715
+ }
716
+ const loadNodeFetch = async () => {
717
+ const fetchModule = await importNodeModule("node-fetch");
718
+ return fetchModule.default || fetchModule;
719
+ };
720
+ const lazyLoaderHookFetch = async (input, init, loaderHook2) => {
721
+ const hook = (url2, init2) => {
722
+ return loaderHook2.lifecycle.fetch.emit(url2, init2);
723
+ };
724
+ const res2 = await hook(input, init || {});
725
+ if (!res2 || !(res2 instanceof Response)) {
726
+ const fetchFunction = typeof fetch === "undefined" ? await loadNodeFetch() : fetch;
727
+ return fetchFunction(input, init || {});
728
+ }
729
+ return res2;
730
+ };
731
+ const createScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web" ? (url, cb, attrs, loaderHook) => {
732
+ if (loaderHook?.createScriptHook) {
733
+ const hookResult = loaderHook.createScriptHook(url);
734
+ if (hookResult && typeof hookResult === "object" && "url" in hookResult) {
735
+ url = hookResult.url;
736
+ }
737
+ }
738
+ let urlObj;
739
+ try {
740
+ urlObj = new URL(url);
741
+ } catch (e) {
742
+ console.error("Error constructing URL:", e);
743
+ cb(new Error(`Invalid URL: ${e}`));
744
+ return;
745
+ }
746
+ const getFetch = async () => {
747
+ if (loaderHook?.fetch) {
748
+ return (input, init) => lazyLoaderHookFetch(input, init, loaderHook);
749
+ }
750
+ return typeof fetch === "undefined" ? loadNodeFetch() : fetch;
751
+ };
752
+ const handleScriptFetch = async (f, urlObj) => {
753
+ try {
754
+ const res = await f(urlObj.href);
755
+ const data = await res.text();
756
+ const [path, vm] = await Promise.all([
757
+ importNodeModule("path"),
758
+ importNodeModule("vm")
759
+ ]);
760
+ const scriptContext = { exports: {}, module: { exports: {} } };
761
+ const urlDirname = urlObj.pathname.split("/").slice(0, -1).join("/");
762
+ const filename = path.basename(urlObj.pathname);
763
+ const script = new vm.Script(`(function(exports, module, require, __dirname, __filename) {${data}
764
+ })`, {
765
+ filename,
766
+ importModuleDynamically: (
767
+ //@ts-ignore
768
+ vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ?? importNodeModule
769
+ )
770
+ });
771
+ script.runInThisContext()(scriptContext.exports, scriptContext.module, eval("require"), urlDirname, filename);
772
+ const exportedInterface = scriptContext.module.exports || scriptContext.exports;
773
+ if (attrs && exportedInterface && attrs["globalName"]) {
774
+ const container = exportedInterface[attrs["globalName"]] || exportedInterface;
775
+ cb(void 0, container);
776
+ return;
777
+ }
778
+ cb(void 0, exportedInterface);
779
+ } catch (e) {
780
+ cb(e instanceof Error ? e : new Error(`Script execution error: ${e}`));
781
+ }
782
+ };
783
+ getFetch().then(async (f2) => {
784
+ if (attrs?.["type"] === "esm" || attrs?.["type"] === "module") {
785
+ return loadModule(urlObj.href, {
786
+ fetch: f2,
787
+ vm: await importNodeModule("vm")
788
+ }).then(async (module) => {
789
+ await module.evaluate();
790
+ cb(void 0, module.namespace);
791
+ }).catch((e) => {
792
+ cb(e instanceof Error ? e : new Error(`Script execution error: ${e}`));
793
+ });
794
+ }
795
+ handleScriptFetch(f2, urlObj);
796
+ }).catch((err) => {
797
+ cb(err);
798
+ });
799
+ } : (url2, cb2, attrs2, loaderHook2) => {
800
+ cb2(new Error("createScriptNode is disabled in non-Node.js environment"));
801
+ };
802
+ const loadScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web" ? (url2, info) => {
803
+ return new Promise((resolve, reject) => {
804
+ createScriptNode(url2, (error2, scriptContext2) => {
805
+ if (error2) {
806
+ reject(error2);
807
+ } else {
808
+ const remoteEntryKey = info?.attrs?.["globalName"] || `__FEDERATION_${info?.attrs?.["name"]}:custom__`;
809
+ const entryExports = globalThis[remoteEntryKey] = scriptContext2;
810
+ resolve(entryExports);
811
+ }
812
+ }, info.attrs, info.loaderHook);
813
+ });
814
+ } : (url2, info) => {
815
+ throw new Error("loadScriptNode is disabled in non-Node.js environment");
816
+ };
817
+ const esmModuleCache = /* @__PURE__ */ new Map();
818
+ async function loadModule(url2, options) {
819
+ if (esmModuleCache.has(url2)) {
820
+ return esmModuleCache.get(url2);
821
+ }
822
+ const { fetch: fetch2, vm: vm2 } = options;
823
+ const response = await fetch2(url2);
824
+ const code = await response.text();
825
+ const module = new vm2.SourceTextModule(code, {
826
+ // @ts-ignore
827
+ importModuleDynamically: async (specifier, script2) => {
828
+ const resolvedUrl = new URL(specifier, url2).href;
829
+ return loadModule(resolvedUrl, options);
830
+ }
831
+ });
832
+ esmModuleCache.set(url2, module);
833
+ await module.link(async (specifier) => {
834
+ const resolvedUrl = new URL(specifier, url2).href;
835
+ const module2 = await loadModule(resolvedUrl, options);
836
+ return module2;
837
+ });
838
+ return module;
839
+ }
840
+ function normalizeOptions(enableDefault, defaultOptions, key) {
841
+ return function(options) {
842
+ if (options === false) {
843
+ return false;
844
+ }
845
+ if (typeof options === "undefined") {
846
+ if (enableDefault) {
847
+ return defaultOptions;
848
+ } else {
849
+ return false;
850
+ }
851
+ }
852
+ if (options === true) {
853
+ return defaultOptions;
854
+ }
855
+ if (options && typeof options === "object") {
856
+ return {
857
+ ...defaultOptions,
858
+ ...options
859
+ };
860
+ }
861
+ throw new Error(`Unexpected type for \`${key}\`, expect boolean/undefined/object, got: ${typeof options}`);
862
+ };
863
+ }
864
+ const createModuleFederationConfig = (options) => {
865
+ return options;
866
+ };
867
+ index_cjs$1.BROWSER_LOG_KEY = BROWSER_LOG_KEY;
868
+ index_cjs$1.ENCODE_NAME_PREFIX = ENCODE_NAME_PREFIX;
869
+ index_cjs$1.EncodedNameTransformMap = EncodedNameTransformMap;
870
+ index_cjs$1.FederationModuleManifest = FederationModuleManifest;
871
+ index_cjs$1.MANIFEST_EXT = MANIFEST_EXT;
872
+ index_cjs$1.MFModuleType = MFModuleType;
873
+ index_cjs$1.MFPrefetchCommon = MFPrefetchCommon;
874
+ index_cjs$1.MODULE_DEVTOOL_IDENTIFIER = MODULE_DEVTOOL_IDENTIFIER;
875
+ index_cjs$1.ManifestFileName = ManifestFileName;
876
+ index_cjs$1.NameTransformMap = NameTransformMap;
877
+ index_cjs$1.NameTransformSymbol = NameTransformSymbol;
878
+ index_cjs$1.SEPARATOR = SEPARATOR;
879
+ index_cjs$1.StatsFileName = StatsFileName;
880
+ index_cjs$1.TEMP_DIR = TEMP_DIR;
881
+ index_cjs$1.assert = assert$1;
882
+ index_cjs$1.bindLoggerToCompiler = bindLoggerToCompiler;
883
+ index_cjs$1.composeKeyWithSeparator = composeKeyWithSeparator;
884
+ index_cjs$1.containerPlugin = ContainerPlugin;
885
+ index_cjs$1.containerReferencePlugin = ContainerReferencePlugin;
886
+ index_cjs$1.createInfrastructureLogger = createInfrastructureLogger;
887
+ index_cjs$1.createLink = createLink;
888
+ index_cjs$1.createLogger = createLogger;
889
+ index_cjs$1.createModuleFederationConfig = createModuleFederationConfig;
890
+ index_cjs$1.createScript = createScript;
891
+ index_cjs$1.createScriptNode = createScriptNode;
892
+ index_cjs$1.decodeName = decodeName;
893
+ index_cjs$1.encodeName = encodeName;
894
+ index_cjs$1.error = error$1;
895
+ index_cjs$1.generateExposeFilename = generateExposeFilename;
896
+ index_cjs$1.generateShareFilename = generateShareFilename;
897
+ index_cjs$1.generateSnapshotFromManifest = generateSnapshotFromManifest;
898
+ index_cjs$1.getManifestFileName = getManifestFileName;
899
+ index_cjs$1.getProcessEnv = getProcessEnv;
900
+ index_cjs$1.getResourceUrl = getResourceUrl;
901
+ index_cjs$1.inferAutoPublicPath = inferAutoPublicPath;
902
+ index_cjs$1.infrastructureLogger = infrastructureLogger;
903
+ index_cjs$1.isBrowserEnv = isBrowserEnv;
904
+ index_cjs$1.isDebugMode = isDebugMode;
905
+ index_cjs$1.isManifestProvider = isManifestProvider;
906
+ index_cjs$1.isReactNativeEnv = isReactNativeEnv;
907
+ index_cjs$1.isRequiredVersion = isRequiredVersion;
908
+ index_cjs$1.isStaticResourcesEqual = isStaticResourcesEqual$1;
909
+ index_cjs$1.loadScript = loadScript;
910
+ index_cjs$1.loadScriptNode = loadScriptNode;
911
+ index_cjs$1.logger = logger$1;
912
+ index_cjs$1.moduleFederationPlugin = ModuleFederationPlugin;
913
+ index_cjs$1.normalizeOptions = normalizeOptions;
914
+ index_cjs$1.parseEntry = parseEntry;
915
+ index_cjs$1.safeToString = safeToString;
916
+ index_cjs$1.safeWrapper = safeWrapper$1;
917
+ index_cjs$1.sharePlugin = SharePlugin;
918
+ index_cjs$1.simpleJoinRemoteEntry = simpleJoinRemoteEntry;
919
+ index_cjs$1.warn = warn$1;
920
+
921
+ var index_cjs = {};
922
+
923
+ const RUNTIME_001 = 'RUNTIME-001';
924
+ const RUNTIME_002 = 'RUNTIME-002';
925
+ const RUNTIME_003 = 'RUNTIME-003';
926
+ const RUNTIME_004 = 'RUNTIME-004';
927
+ const RUNTIME_005 = 'RUNTIME-005';
928
+ const RUNTIME_006 = 'RUNTIME-006';
929
+ const RUNTIME_007 = 'RUNTIME-007';
930
+ const RUNTIME_008 = 'RUNTIME-008';
931
+ const RUNTIME_009 = 'RUNTIME-009';
932
+ const TYPE_001 = 'TYPE-001';
933
+ const BUILD_001 = 'BUILD-001';
934
+ const BUILD_002 = 'BUILD-002';
935
+
936
+ const getDocsUrl = (errorCode) => {
937
+ const type = errorCode.split('-')[0].toLowerCase();
938
+ return `View the docs to see how to solve: https://module-federation.io/guide/troubleshooting/${type}/${errorCode}`;
939
+ };
940
+ const getShortErrorMsg = (errorCode, errorDescMap, args, originalErrorMsg) => {
941
+ const msg = [`${[errorDescMap[errorCode]]} #${errorCode}`];
942
+ args && msg.push(`args: ${JSON.stringify(args)}`);
943
+ msg.push(getDocsUrl(errorCode));
944
+ originalErrorMsg && msg.push(`Original Error Message:\n ${originalErrorMsg}`);
945
+ return msg.join('\n');
946
+ };
947
+
948
+ const runtimeDescMap = {
949
+ [RUNTIME_001]: 'Failed to get remoteEntry exports.',
950
+ [RUNTIME_002]: 'The remote entry interface does not contain "init"',
951
+ [RUNTIME_003]: 'Failed to get manifest.',
952
+ [RUNTIME_004]: 'Failed to locate remote.',
953
+ [RUNTIME_005]: 'Invalid loadShareSync function call from bundler runtime',
954
+ [RUNTIME_006]: 'Invalid loadShareSync function call from runtime',
955
+ [RUNTIME_007]: 'Failed to get remote snapshot.',
956
+ [RUNTIME_008]: 'Failed to load script resources.',
957
+ [RUNTIME_009]: 'Please call createInstance first.',
958
+ };
959
+ const typeDescMap = {
960
+ [TYPE_001]: 'Failed to generate type declaration. Execute the below cmd to reproduce and fix the error.',
961
+ };
962
+ const buildDescMap = {
963
+ [BUILD_001]: 'Failed to find expose module.',
964
+ [BUILD_002]: 'PublicPath is required in prod mode.',
965
+ };
966
+ const errorDescMap = {
967
+ ...runtimeDescMap,
968
+ ...typeDescMap,
969
+ ...buildDescMap,
970
+ };
971
+
972
+ index_cjs.BUILD_001 = BUILD_001;
973
+ index_cjs.BUILD_002 = BUILD_002;
974
+ index_cjs.RUNTIME_001 = RUNTIME_001;
975
+ index_cjs.RUNTIME_002 = RUNTIME_002;
976
+ index_cjs.RUNTIME_003 = RUNTIME_003;
977
+ index_cjs.RUNTIME_004 = RUNTIME_004;
978
+ index_cjs.RUNTIME_005 = RUNTIME_005;
979
+ index_cjs.RUNTIME_006 = RUNTIME_006;
980
+ index_cjs.RUNTIME_007 = RUNTIME_007;
981
+ index_cjs.RUNTIME_008 = RUNTIME_008;
982
+ index_cjs.RUNTIME_009 = RUNTIME_009;
983
+ index_cjs.TYPE_001 = TYPE_001;
984
+ index_cjs.buildDescMap = buildDescMap;
985
+ index_cjs.errorDescMap = errorDescMap;
986
+ index_cjs.getShortErrorMsg = getShortErrorMsg;
987
+ index_cjs.runtimeDescMap = runtimeDescMap;
988
+ index_cjs.typeDescMap = typeDescMap;
989
+
990
+ var sdk = index_cjs$1;
991
+ var errorCodes = index_cjs;
992
+
993
+ const LOG_CATEGORY = '[ Federation Runtime ]';
994
+ // FIXME: pre-bundle ?
995
+ const logger = sdk.createLogger(LOG_CATEGORY);
996
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
997
+ function assert(condition, msg) {
998
+ if (!condition) {
999
+ error(msg);
1000
+ }
1001
+ }
1002
+ function error(msg) {
1003
+ if (msg instanceof Error) {
1004
+ // Check if the message already starts with the log category to avoid duplication
1005
+ if (!msg.message.startsWith(LOG_CATEGORY)) {
1006
+ msg.message = `${LOG_CATEGORY}: ${msg.message}`;
1007
+ }
1008
+ throw msg;
1009
+ }
1010
+ throw new Error(`${LOG_CATEGORY}: ${msg}`);
1011
+ }
1012
+ function warn(msg) {
1013
+ if (msg instanceof Error) {
1014
+ // Check if the message already starts with the log category to avoid duplication
1015
+ if (!msg.message.startsWith(LOG_CATEGORY)) {
1016
+ msg.message = `${LOG_CATEGORY}: ${msg.message}`;
1017
+ }
1018
+ logger.warn(msg);
1019
+ }
1020
+ else {
1021
+ logger.warn(msg);
1022
+ }
1023
+ }
1024
+
1025
+ function addUniqueItem(arr, item) {
1026
+ if (arr.findIndex((name) => name === item) === -1) {
1027
+ arr.push(item);
1028
+ }
1029
+ return arr;
1030
+ }
1031
+ function getFMId(remoteInfo) {
1032
+ if ('version' in remoteInfo && remoteInfo.version) {
1033
+ return `${remoteInfo.name}:${remoteInfo.version}`;
1034
+ }
1035
+ else if ('entry' in remoteInfo && remoteInfo.entry) {
1036
+ return `${remoteInfo.name}:${remoteInfo.entry}`;
1037
+ }
1038
+ else {
1039
+ return `${remoteInfo.name}`;
1040
+ }
1041
+ }
1042
+ function isRemoteInfoWithEntry(remote) {
1043
+ return typeof remote.entry !== 'undefined';
1044
+ }
1045
+ function isPureRemoteEntry(remote) {
1046
+ return !remote.entry.includes('.json');
1047
+ }
1048
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1049
+ async function safeWrapper(callback, disableWarn) {
1050
+ try {
1051
+ const res = await callback();
1052
+ return res;
1053
+ }
1054
+ catch (e) {
1055
+ !disableWarn && warn(e);
1056
+ return;
1057
+ }
1058
+ }
1059
+ function isObject(val) {
1060
+ return val && typeof val === 'object';
1061
+ }
1062
+ const objectToString = Object.prototype.toString;
1063
+ // eslint-disable-next-line @typescript-eslint/ban-types
1064
+ function isPlainObject(val) {
1065
+ return objectToString.call(val) === '[object Object]';
1066
+ }
1067
+ function isStaticResourcesEqual(url1, url2) {
1068
+ const REG_EXP = /^(https?:)?\/\//i;
1069
+ // Transform url1 and url2 into relative paths
1070
+ const relativeUrl1 = url1.replace(REG_EXP, '').replace(/\/$/, '');
1071
+ const relativeUrl2 = url2.replace(REG_EXP, '').replace(/\/$/, '');
1072
+ // Check if the relative paths are identical
1073
+ return relativeUrl1 === relativeUrl2;
1074
+ }
1075
+ function arrayOptions(options) {
1076
+ return Array.isArray(options) ? options : [options];
1077
+ }
1078
+ function getRemoteEntryInfoFromSnapshot(snapshot) {
1079
+ const defaultRemoteEntryInfo = {
1080
+ url: '',
1081
+ type: 'global',
1082
+ globalName: '',
1083
+ };
1084
+ if (sdk.isBrowserEnv() || sdk.isReactNativeEnv()) {
1085
+ return 'remoteEntry' in snapshot
1086
+ ? {
1087
+ url: snapshot.remoteEntry,
1088
+ type: snapshot.remoteEntryType,
1089
+ globalName: snapshot.globalName,
1090
+ }
1091
+ : defaultRemoteEntryInfo;
1092
+ }
1093
+ if ('ssrRemoteEntry' in snapshot) {
1094
+ return {
1095
+ url: snapshot.ssrRemoteEntry || defaultRemoteEntryInfo.url,
1096
+ type: snapshot.ssrRemoteEntryType || defaultRemoteEntryInfo.type,
1097
+ globalName: snapshot.globalName,
1098
+ };
1099
+ }
1100
+ return defaultRemoteEntryInfo;
1101
+ }
1102
+ const processModuleAlias = (name, subPath) => {
1103
+ // @host/ ./button -> @host/button
1104
+ let moduleName;
1105
+ if (name.endsWith('/')) {
1106
+ moduleName = name.slice(0, -1);
1107
+ }
1108
+ else {
1109
+ moduleName = name;
1110
+ }
1111
+ if (subPath.startsWith('.')) {
1112
+ subPath = subPath.slice(1);
1113
+ }
1114
+ moduleName = moduleName + subPath;
1115
+ return moduleName;
1116
+ };
1117
+
1118
+ const CurrentGlobal = typeof globalThis === 'object' ? globalThis : window;
1119
+ const nativeGlobal = (() => {
1120
+ try {
1121
+ // get real window (incase of sandbox)
1122
+ return document.defaultView;
1123
+ }
1124
+ catch {
1125
+ // node env
1126
+ return CurrentGlobal;
1127
+ }
1128
+ })();
1129
+ const Global = nativeGlobal;
1130
+ function definePropertyGlobalVal(target, key, val) {
1131
+ Object.defineProperty(target, key, {
1132
+ value: val,
1133
+ configurable: false,
1134
+ writable: true,
1135
+ });
1136
+ }
1137
+ function includeOwnProperty(target, key) {
1138
+ return Object.hasOwnProperty.call(target, key);
1139
+ }
1140
+ // This section is to prevent encapsulation by certain microfrontend frameworks. Due to reuse policies, sandbox escapes.
1141
+ // The sandbox in the microfrontend does not replicate the value of 'configurable'.
1142
+ // If there is no loading content on the global object, this section defines the loading object.
1143
+ if (!includeOwnProperty(CurrentGlobal, '__GLOBAL_LOADING_REMOTE_ENTRY__')) {
1144
+ definePropertyGlobalVal(CurrentGlobal, '__GLOBAL_LOADING_REMOTE_ENTRY__', {});
1145
+ }
1146
+ const globalLoading = CurrentGlobal.__GLOBAL_LOADING_REMOTE_ENTRY__;
1147
+ function setGlobalDefaultVal(target) {
1148
+ if (includeOwnProperty(target, '__VMOK__') &&
1149
+ !includeOwnProperty(target, '__FEDERATION__')) {
1150
+ definePropertyGlobalVal(target, '__FEDERATION__', target.__VMOK__);
1151
+ }
1152
+ if (!includeOwnProperty(target, '__FEDERATION__')) {
1153
+ definePropertyGlobalVal(target, '__FEDERATION__', {
1154
+ __GLOBAL_PLUGIN__: [],
1155
+ __INSTANCES__: [],
1156
+ moduleInfo: {},
1157
+ __SHARE__: {},
1158
+ __MANIFEST_LOADING__: {},
1159
+ __PRELOADED_MAP__: new Map(),
1160
+ });
1161
+ definePropertyGlobalVal(target, '__VMOK__', target.__FEDERATION__);
1162
+ }
1163
+ target.__FEDERATION__.__GLOBAL_PLUGIN__ ??= [];
1164
+ target.__FEDERATION__.__INSTANCES__ ??= [];
1165
+ target.__FEDERATION__.moduleInfo ??= {};
1166
+ target.__FEDERATION__.__SHARE__ ??= {};
1167
+ target.__FEDERATION__.__MANIFEST_LOADING__ ??= {};
1168
+ target.__FEDERATION__.__PRELOADED_MAP__ ??= new Map();
1169
+ }
1170
+ setGlobalDefaultVal(CurrentGlobal);
1171
+ setGlobalDefaultVal(nativeGlobal);
1172
+ function resetFederationGlobalInfo() {
1173
+ CurrentGlobal.__FEDERATION__.__GLOBAL_PLUGIN__ = [];
1174
+ CurrentGlobal.__FEDERATION__.__INSTANCES__ = [];
1175
+ CurrentGlobal.__FEDERATION__.moduleInfo = {};
1176
+ CurrentGlobal.__FEDERATION__.__SHARE__ = {};
1177
+ CurrentGlobal.__FEDERATION__.__MANIFEST_LOADING__ = {};
1178
+ Object.keys(globalLoading).forEach((key) => {
1179
+ delete globalLoading[key];
1180
+ });
1181
+ }
1182
+ function setGlobalFederationInstance(FederationInstance) {
1183
+ CurrentGlobal.__FEDERATION__.__INSTANCES__.push(FederationInstance);
1184
+ }
1185
+ function getGlobalFederationConstructor() {
1186
+ return CurrentGlobal.__FEDERATION__.__DEBUG_CONSTRUCTOR__;
1187
+ }
1188
+ function setGlobalFederationConstructor(FederationConstructor, isDebug = sdk.isDebugMode()) {
1189
+ if (isDebug) {
1190
+ CurrentGlobal.__FEDERATION__.__DEBUG_CONSTRUCTOR__ = FederationConstructor;
1191
+ CurrentGlobal.__FEDERATION__.__DEBUG_CONSTRUCTOR_VERSION__ = "0.21.6";
1192
+ }
1193
+ }
1194
+ // eslint-disable-next-line @typescript-eslint/ban-types
1195
+ function getInfoWithoutType(target, key) {
1196
+ if (typeof key === 'string') {
1197
+ const keyRes = target[key];
1198
+ if (keyRes) {
1199
+ return {
1200
+ value: target[key],
1201
+ key: key,
1202
+ };
1203
+ }
1204
+ else {
1205
+ const targetKeys = Object.keys(target);
1206
+ for (const targetKey of targetKeys) {
1207
+ const [targetTypeOrName, _] = targetKey.split(':');
1208
+ const nKey = `${targetTypeOrName}:${key}`;
1209
+ const typeWithKeyRes = target[nKey];
1210
+ if (typeWithKeyRes) {
1211
+ return {
1212
+ value: typeWithKeyRes,
1213
+ key: nKey,
1214
+ };
1215
+ }
1216
+ }
1217
+ return {
1218
+ value: undefined,
1219
+ key: key,
1220
+ };
1221
+ }
1222
+ }
1223
+ else {
1224
+ throw new Error('key must be string');
1225
+ }
1226
+ }
1227
+ const getGlobalSnapshot = () => nativeGlobal.__FEDERATION__.moduleInfo;
1228
+ const getTargetSnapshotInfoByModuleInfo = (moduleInfo, snapshot) => {
1229
+ // Check if the remote is included in the hostSnapshot
1230
+ const moduleKey = getFMId(moduleInfo);
1231
+ const getModuleInfo = getInfoWithoutType(snapshot, moduleKey).value;
1232
+ // The remoteSnapshot might not include a version
1233
+ if (getModuleInfo &&
1234
+ !getModuleInfo.version &&
1235
+ 'version' in moduleInfo &&
1236
+ moduleInfo['version']) {
1237
+ getModuleInfo.version = moduleInfo['version'];
1238
+ }
1239
+ if (getModuleInfo) {
1240
+ return getModuleInfo;
1241
+ }
1242
+ // If the remote is not included in the hostSnapshot, deploy a micro app snapshot
1243
+ if ('version' in moduleInfo && moduleInfo['version']) {
1244
+ const { version, ...resModuleInfo } = moduleInfo;
1245
+ const moduleKeyWithoutVersion = getFMId(resModuleInfo);
1246
+ const getModuleInfoWithoutVersion = getInfoWithoutType(nativeGlobal.__FEDERATION__.moduleInfo, moduleKeyWithoutVersion).value;
1247
+ if (getModuleInfoWithoutVersion?.version === version) {
1248
+ return getModuleInfoWithoutVersion;
1249
+ }
1250
+ }
1251
+ return;
1252
+ };
1253
+ const getGlobalSnapshotInfoByModuleInfo = (moduleInfo) => getTargetSnapshotInfoByModuleInfo(moduleInfo, nativeGlobal.__FEDERATION__.moduleInfo);
1254
+ const setGlobalSnapshotInfoByModuleInfo = (remoteInfo, moduleDetailInfo) => {
1255
+ const moduleKey = getFMId(remoteInfo);
1256
+ nativeGlobal.__FEDERATION__.moduleInfo[moduleKey] = moduleDetailInfo;
1257
+ return nativeGlobal.__FEDERATION__.moduleInfo;
1258
+ };
1259
+ const addGlobalSnapshot = (moduleInfos) => {
1260
+ nativeGlobal.__FEDERATION__.moduleInfo = {
1261
+ ...nativeGlobal.__FEDERATION__.moduleInfo,
1262
+ ...moduleInfos,
1263
+ };
1264
+ return () => {
1265
+ const keys = Object.keys(moduleInfos);
1266
+ for (const key of keys) {
1267
+ delete nativeGlobal.__FEDERATION__.moduleInfo[key];
1268
+ }
1269
+ };
1270
+ };
1271
+ const getRemoteEntryExports = (name, globalName) => {
1272
+ const remoteEntryKey = globalName || `__FEDERATION_${name}:custom__`;
1273
+ const entryExports = CurrentGlobal[remoteEntryKey];
1274
+ return {
1275
+ remoteEntryKey,
1276
+ entryExports,
1277
+ };
1278
+ };
1279
+ // This function is used to register global plugins.
1280
+ // It iterates over the provided plugins and checks if they are already registered.
1281
+ // If a plugin is not registered, it is added to the global plugins.
1282
+ // If a plugin is already registered, a warning message is logged.
1283
+ const registerGlobalPlugins = (plugins) => {
1284
+ const { __GLOBAL_PLUGIN__ } = nativeGlobal.__FEDERATION__;
1285
+ plugins.forEach((plugin) => {
1286
+ if (__GLOBAL_PLUGIN__.findIndex((p) => p.name === plugin.name) === -1) {
1287
+ __GLOBAL_PLUGIN__.push(plugin);
1288
+ }
1289
+ else {
1290
+ warn(`The plugin ${plugin.name} has been registered.`);
1291
+ }
1292
+ });
1293
+ };
1294
+ const getGlobalHostPlugins = () => nativeGlobal.__FEDERATION__.__GLOBAL_PLUGIN__;
1295
+ const getPreloaded = (id) => CurrentGlobal.__FEDERATION__.__PRELOADED_MAP__.get(id);
1296
+ const setPreloaded = (id) => CurrentGlobal.__FEDERATION__.__PRELOADED_MAP__.set(id, true);
1297
+
1298
+ const DEFAULT_SCOPE = 'default';
1299
+ const DEFAULT_REMOTE_TYPE = 'global';
1300
+
1301
+ // fork from https://github.com/originjs/vite-plugin-federation/blob/v1.1.12/packages/lib/src/utils/semver/index.ts
1302
+ // those constants are based on https://www.rubydoc.info/gems/semantic_range/3.0.0/SemanticRange#BUILDIDENTIFIER-constant
1303
+ // Copyright (c)
1304
+ // vite-plugin-federation is licensed under Mulan PSL v2.
1305
+ // You can use this software according to the terms and conditions of the Mulan PSL v2.
1306
+ // You may obtain a copy of Mulan PSL v2 at:
1307
+ // http://license.coscl.org.cn/MulanPSL2
1308
+ // 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.
1309
+ // See the Mulan PSL v2 for more details.
1310
+ const buildIdentifier = '[0-9A-Za-z-]+';
1311
+ const build = `(?:\\+(${buildIdentifier}(?:\\.${buildIdentifier})*))`;
1312
+ const numericIdentifier = '0|[1-9]\\d*';
1313
+ const numericIdentifierLoose = '[0-9]+';
1314
+ const nonNumericIdentifier = '\\d*[a-zA-Z-][a-zA-Z0-9-]*';
1315
+ const preReleaseIdentifierLoose = `(?:${numericIdentifierLoose}|${nonNumericIdentifier})`;
1316
+ const preReleaseLoose = `(?:-?(${preReleaseIdentifierLoose}(?:\\.${preReleaseIdentifierLoose})*))`;
1317
+ const preReleaseIdentifier = `(?:${numericIdentifier}|${nonNumericIdentifier})`;
1318
+ const preRelease = `(?:-(${preReleaseIdentifier}(?:\\.${preReleaseIdentifier})*))`;
1319
+ const xRangeIdentifier = `${numericIdentifier}|x|X|\\*`;
1320
+ const xRangePlain = `[v=\\s]*(${xRangeIdentifier})(?:\\.(${xRangeIdentifier})(?:\\.(${xRangeIdentifier})(?:${preRelease})?${build}?)?)?`;
1321
+ const hyphenRange = `^\\s*(${xRangePlain})\\s+-\\s+(${xRangePlain})\\s*$`;
1322
+ const mainVersionLoose = `(${numericIdentifierLoose})\\.(${numericIdentifierLoose})\\.(${numericIdentifierLoose})`;
1323
+ const loosePlain = `[v=\\s]*${mainVersionLoose}${preReleaseLoose}?${build}?`;
1324
+ const gtlt = '((?:<|>)?=?)';
1325
+ const comparatorTrim = `(\\s*)${gtlt}\\s*(${loosePlain}|${xRangePlain})`;
1326
+ const loneTilde = '(?:~>?)';
1327
+ const tildeTrim = `(\\s*)${loneTilde}\\s+`;
1328
+ const loneCaret = '(?:\\^)';
1329
+ const caretTrim = `(\\s*)${loneCaret}\\s+`;
1330
+ const star = '(<|>)?=?\\s*\\*';
1331
+ const caret = `^${loneCaret}${xRangePlain}$`;
1332
+ const mainVersion = `(${numericIdentifier})\\.(${numericIdentifier})\\.(${numericIdentifier})`;
1333
+ const fullPlain = `v?${mainVersion}${preRelease}?${build}?`;
1334
+ const tilde = `^${loneTilde}${xRangePlain}$`;
1335
+ const xRange = `^${gtlt}\\s*${xRangePlain}$`;
1336
+ const comparator = `^${gtlt}\\s*(${fullPlain})$|^$`;
1337
+ // copy from semver package
1338
+ const gte0 = '^\\s*>=\\s*0.0.0\\s*$';
1339
+
1340
+ // fork from https://github.com/originjs/vite-plugin-federation/blob/v1.1.12/packages/lib/src/utils/semver/index.ts
1341
+ // Copyright (c)
1342
+ // vite-plugin-federation is licensed under Mulan PSL v2.
1343
+ // You can use this software according to the terms and conditions of the Mulan PSL v2.
1344
+ // You may obtain a copy of Mulan PSL v2 at:
1345
+ // http://license.coscl.org.cn/MulanPSL2
1346
+ // 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.
1347
+ // See the Mulan PSL v2 for more details.
1348
+ function parseRegex(source) {
1349
+ return new RegExp(source);
1350
+ }
1351
+ function isXVersion(version) {
1352
+ return !version || version.toLowerCase() === 'x' || version === '*';
1353
+ }
1354
+ function pipe(...fns) {
1355
+ return (x) => fns.reduce((v, f) => f(v), x);
1356
+ }
1357
+ function extractComparator(comparatorString) {
1358
+ return comparatorString.match(parseRegex(comparator));
1359
+ }
1360
+ function combineVersion(major, minor, patch, preRelease) {
1361
+ const mainVersion = `${major}.${minor}.${patch}`;
1362
+ if (preRelease) {
1363
+ return `${mainVersion}-${preRelease}`;
1364
+ }
1365
+ return mainVersion;
1366
+ }
1367
+
1368
+ // fork from https://github.com/originjs/vite-plugin-federation/blob/v1.1.12/packages/lib/src/utils/semver/index.ts
1369
+ // Copyright (c)
1370
+ // vite-plugin-federation is licensed under Mulan PSL v2.
1371
+ // You can use this software according to the terms and conditions of the Mulan PSL v2.
1372
+ // You may obtain a copy of Mulan PSL v2 at:
1373
+ // http://license.coscl.org.cn/MulanPSL2
1374
+ // 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.
1375
+ // See the Mulan PSL v2 for more details.
1376
+ function parseHyphen(range) {
1377
+ return range.replace(parseRegex(hyphenRange), (_range, from, fromMajor, fromMinor, fromPatch, _fromPreRelease, _fromBuild, to, toMajor, toMinor, toPatch, toPreRelease) => {
1378
+ if (isXVersion(fromMajor)) {
1379
+ from = '';
1380
+ }
1381
+ else if (isXVersion(fromMinor)) {
1382
+ from = `>=${fromMajor}.0.0`;
1383
+ }
1384
+ else if (isXVersion(fromPatch)) {
1385
+ from = `>=${fromMajor}.${fromMinor}.0`;
1386
+ }
1387
+ else {
1388
+ from = `>=${from}`;
1389
+ }
1390
+ if (isXVersion(toMajor)) {
1391
+ to = '';
1392
+ }
1393
+ else if (isXVersion(toMinor)) {
1394
+ to = `<${Number(toMajor) + 1}.0.0-0`;
1395
+ }
1396
+ else if (isXVersion(toPatch)) {
1397
+ to = `<${toMajor}.${Number(toMinor) + 1}.0-0`;
1398
+ }
1399
+ else if (toPreRelease) {
1400
+ to = `<=${toMajor}.${toMinor}.${toPatch}-${toPreRelease}`;
1401
+ }
1402
+ else {
1403
+ to = `<=${to}`;
1404
+ }
1405
+ return `${from} ${to}`.trim();
1406
+ });
1407
+ }
1408
+ function parseComparatorTrim(range) {
1409
+ return range.replace(parseRegex(comparatorTrim), '$1$2$3');
1410
+ }
1411
+ function parseTildeTrim(range) {
1412
+ return range.replace(parseRegex(tildeTrim), '$1~');
1413
+ }
1414
+ function parseCaretTrim(range) {
1415
+ return range.replace(parseRegex(caretTrim), '$1^');
1416
+ }
1417
+ function parseCarets(range) {
1418
+ return range
1419
+ .trim()
1420
+ .split(/\s+/)
1421
+ .map((rangeVersion) => rangeVersion.replace(parseRegex(caret), (_, major, minor, patch, preRelease) => {
1422
+ if (isXVersion(major)) {
1423
+ return '';
1424
+ }
1425
+ else if (isXVersion(minor)) {
1426
+ return `>=${major}.0.0 <${Number(major) + 1}.0.0-0`;
1427
+ }
1428
+ else if (isXVersion(patch)) {
1429
+ if (major === '0') {
1430
+ return `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0-0`;
1431
+ }
1432
+ else {
1433
+ return `>=${major}.${minor}.0 <${Number(major) + 1}.0.0-0`;
1434
+ }
1435
+ }
1436
+ else if (preRelease) {
1437
+ if (major === '0') {
1438
+ if (minor === '0') {
1439
+ return `>=${major}.${minor}.${patch}-${preRelease} <${major}.${minor}.${Number(patch) + 1}-0`;
1440
+ }
1441
+ else {
1442
+ return `>=${major}.${minor}.${patch}-${preRelease} <${major}.${Number(minor) + 1}.0-0`;
1443
+ }
1444
+ }
1445
+ else {
1446
+ return `>=${major}.${minor}.${patch}-${preRelease} <${Number(major) + 1}.0.0-0`;
1447
+ }
1448
+ }
1449
+ else {
1450
+ if (major === '0') {
1451
+ if (minor === '0') {
1452
+ return `>=${major}.${minor}.${patch} <${major}.${minor}.${Number(patch) + 1}-0`;
1453
+ }
1454
+ else {
1455
+ return `>=${major}.${minor}.${patch} <${major}.${Number(minor) + 1}.0-0`;
1456
+ }
1457
+ }
1458
+ return `>=${major}.${minor}.${patch} <${Number(major) + 1}.0.0-0`;
1459
+ }
1460
+ }))
1461
+ .join(' ');
1462
+ }
1463
+ function parseTildes(range) {
1464
+ return range
1465
+ .trim()
1466
+ .split(/\s+/)
1467
+ .map((rangeVersion) => rangeVersion.replace(parseRegex(tilde), (_, major, minor, patch, preRelease) => {
1468
+ if (isXVersion(major)) {
1469
+ return '';
1470
+ }
1471
+ else if (isXVersion(minor)) {
1472
+ return `>=${major}.0.0 <${Number(major) + 1}.0.0-0`;
1473
+ }
1474
+ else if (isXVersion(patch)) {
1475
+ return `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0-0`;
1476
+ }
1477
+ else if (preRelease) {
1478
+ return `>=${major}.${minor}.${patch}-${preRelease} <${major}.${Number(minor) + 1}.0-0`;
1479
+ }
1480
+ return `>=${major}.${minor}.${patch} <${major}.${Number(minor) + 1}.0-0`;
1481
+ }))
1482
+ .join(' ');
1483
+ }
1484
+ function parseXRanges(range) {
1485
+ return range
1486
+ .split(/\s+/)
1487
+ .map((rangeVersion) => rangeVersion
1488
+ .trim()
1489
+ .replace(parseRegex(xRange), (ret, gtlt, major, minor, patch, preRelease) => {
1490
+ const isXMajor = isXVersion(major);
1491
+ const isXMinor = isXMajor || isXVersion(minor);
1492
+ const isXPatch = isXMinor || isXVersion(patch);
1493
+ if (gtlt === '=' && isXPatch) {
1494
+ gtlt = '';
1495
+ }
1496
+ preRelease = '';
1497
+ if (isXMajor) {
1498
+ if (gtlt === '>' || gtlt === '<') {
1499
+ // nothing is allowed
1500
+ return '<0.0.0-0';
1501
+ }
1502
+ else {
1503
+ // nothing is forbidden
1504
+ return '*';
1505
+ }
1506
+ }
1507
+ else if (gtlt && isXPatch) {
1508
+ // replace X with 0
1509
+ if (isXMinor) {
1510
+ minor = 0;
1511
+ }
1512
+ patch = 0;
1513
+ if (gtlt === '>') {
1514
+ // >1 => >=2.0.0
1515
+ // >1.2 => >=1.3.0
1516
+ gtlt = '>=';
1517
+ if (isXMinor) {
1518
+ major = Number(major) + 1;
1519
+ minor = 0;
1520
+ patch = 0;
1521
+ }
1522
+ else {
1523
+ minor = Number(minor) + 1;
1524
+ patch = 0;
1525
+ }
1526
+ }
1527
+ else if (gtlt === '<=') {
1528
+ // <=0.7.x is actually <0.8.0, since any 0.7.x should pass
1529
+ // Similarly, <=7.x is actually <8.0.0, etc.
1530
+ gtlt = '<';
1531
+ if (isXMinor) {
1532
+ major = Number(major) + 1;
1533
+ }
1534
+ else {
1535
+ minor = Number(minor) + 1;
1536
+ }
1537
+ }
1538
+ if (gtlt === '<') {
1539
+ preRelease = '-0';
1540
+ }
1541
+ return `${gtlt + major}.${minor}.${patch}${preRelease}`;
1542
+ }
1543
+ else if (isXMinor) {
1544
+ return `>=${major}.0.0${preRelease} <${Number(major) + 1}.0.0-0`;
1545
+ }
1546
+ else if (isXPatch) {
1547
+ return `>=${major}.${minor}.0${preRelease} <${major}.${Number(minor) + 1}.0-0`;
1548
+ }
1549
+ return ret;
1550
+ }))
1551
+ .join(' ');
1552
+ }
1553
+ function parseStar(range) {
1554
+ return range.trim().replace(parseRegex(star), '');
1555
+ }
1556
+ function parseGTE0(comparatorString) {
1557
+ return comparatorString.trim().replace(parseRegex(gte0), '');
1558
+ }
1559
+
1560
+ // fork from https://github.com/originjs/vite-plugin-federation/blob/v1.1.12/packages/lib/src/utils/semver/index.ts
1561
+ // Copyright (c)
1562
+ // vite-plugin-federation is licensed under Mulan PSL v2.
1563
+ // You can use this software according to the terms and conditions of the Mulan PSL v2.
1564
+ // You may obtain a copy of Mulan PSL v2 at:
1565
+ // http://license.coscl.org.cn/MulanPSL2
1566
+ // 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.
1567
+ // See the Mulan PSL v2 for more details.
1568
+ function compareAtom(rangeAtom, versionAtom) {
1569
+ rangeAtom = Number(rangeAtom) || rangeAtom;
1570
+ versionAtom = Number(versionAtom) || versionAtom;
1571
+ if (rangeAtom > versionAtom) {
1572
+ return 1;
1573
+ }
1574
+ if (rangeAtom === versionAtom) {
1575
+ return 0;
1576
+ }
1577
+ return -1;
1578
+ }
1579
+ function comparePreRelease(rangeAtom, versionAtom) {
1580
+ const { preRelease: rangePreRelease } = rangeAtom;
1581
+ const { preRelease: versionPreRelease } = versionAtom;
1582
+ if (rangePreRelease === undefined && Boolean(versionPreRelease)) {
1583
+ return 1;
1584
+ }
1585
+ if (Boolean(rangePreRelease) && versionPreRelease === undefined) {
1586
+ return -1;
1587
+ }
1588
+ if (rangePreRelease === undefined && versionPreRelease === undefined) {
1589
+ return 0;
1590
+ }
1591
+ for (let i = 0, n = rangePreRelease.length; i <= n; i++) {
1592
+ const rangeElement = rangePreRelease[i];
1593
+ const versionElement = versionPreRelease[i];
1594
+ if (rangeElement === versionElement) {
1595
+ continue;
1596
+ }
1597
+ if (rangeElement === undefined && versionElement === undefined) {
1598
+ return 0;
1599
+ }
1600
+ if (!rangeElement) {
1601
+ return 1;
1602
+ }
1603
+ if (!versionElement) {
1604
+ return -1;
1605
+ }
1606
+ return compareAtom(rangeElement, versionElement);
1607
+ }
1608
+ return 0;
1609
+ }
1610
+ function compareVersion(rangeAtom, versionAtom) {
1611
+ return (compareAtom(rangeAtom.major, versionAtom.major) ||
1612
+ compareAtom(rangeAtom.minor, versionAtom.minor) ||
1613
+ compareAtom(rangeAtom.patch, versionAtom.patch) ||
1614
+ comparePreRelease(rangeAtom, versionAtom));
1615
+ }
1616
+ function eq(rangeAtom, versionAtom) {
1617
+ return rangeAtom.version === versionAtom.version;
1618
+ }
1619
+ function compare(rangeAtom, versionAtom) {
1620
+ switch (rangeAtom.operator) {
1621
+ case '':
1622
+ case '=':
1623
+ return eq(rangeAtom, versionAtom);
1624
+ case '>':
1625
+ return compareVersion(rangeAtom, versionAtom) < 0;
1626
+ case '>=':
1627
+ return (eq(rangeAtom, versionAtom) || compareVersion(rangeAtom, versionAtom) < 0);
1628
+ case '<':
1629
+ return compareVersion(rangeAtom, versionAtom) > 0;
1630
+ case '<=':
1631
+ return (eq(rangeAtom, versionAtom) || compareVersion(rangeAtom, versionAtom) > 0);
1632
+ case undefined: {
1633
+ // mean * or x -> all versions
1634
+ return true;
1635
+ }
1636
+ default:
1637
+ return false;
1638
+ }
1639
+ }
1640
+
1641
+ // fork from https://github.com/originjs/vite-plugin-federation/blob/v1.1.12/packages/lib/src/utils/semver/index.ts
1642
+ // Copyright (c)
1643
+ // vite-plugin-federation is licensed under Mulan PSL v2.
1644
+ // You can use this software according to the terms and conditions of the Mulan PSL v2.
1645
+ // You may obtain a copy of Mulan PSL v2 at:
1646
+ // http://license.coscl.org.cn/MulanPSL2
1647
+ // 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.
1648
+ // See the Mulan PSL v2 for more details.
1649
+ function parseComparatorString(range) {
1650
+ return pipe(
1651
+ // handle caret
1652
+ // ^ --> * (any, kinda silly)
1653
+ // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
1654
+ // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
1655
+ // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
1656
+ // ^1.2.3 --> >=1.2.3 <2.0.0-0
1657
+ // ^1.2.0 --> >=1.2.0 <2.0.0-0
1658
+ parseCarets,
1659
+ // handle tilde
1660
+ // ~, ~> --> * (any, kinda silly)
1661
+ // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
1662
+ // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
1663
+ // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
1664
+ // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
1665
+ // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
1666
+ parseTildes, parseXRanges, parseStar)(range);
1667
+ }
1668
+ function parseRange(range) {
1669
+ return pipe(
1670
+ // handle hyphenRange
1671
+ // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
1672
+ parseHyphen,
1673
+ // handle trim comparator
1674
+ // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
1675
+ parseComparatorTrim,
1676
+ // handle trim tilde
1677
+ // `~ 1.2.3` => `~1.2.3`
1678
+ parseTildeTrim,
1679
+ // handle trim caret
1680
+ // `^ 1.2.3` => `^1.2.3`
1681
+ parseCaretTrim)(range.trim())
1682
+ .split(/\s+/)
1683
+ .join(' ');
1684
+ }
1685
+ function satisfy(version, range) {
1686
+ if (!version) {
1687
+ return false;
1688
+ }
1689
+ // Extract version details once
1690
+ const extractedVersion = extractComparator(version);
1691
+ if (!extractedVersion) {
1692
+ // If the version string is invalid, it can't satisfy any range
1693
+ return false;
1694
+ }
1695
+ const [, versionOperator, , versionMajor, versionMinor, versionPatch, versionPreRelease,] = extractedVersion;
1696
+ const versionAtom = {
1697
+ operator: versionOperator,
1698
+ version: combineVersion(versionMajor, versionMinor, versionPatch, versionPreRelease), // exclude build atom
1699
+ major: versionMajor,
1700
+ minor: versionMinor,
1701
+ patch: versionPatch,
1702
+ preRelease: versionPreRelease?.split('.'),
1703
+ };
1704
+ // Split the range by || to handle OR conditions
1705
+ const orRanges = range.split('||');
1706
+ for (const orRange of orRanges) {
1707
+ const trimmedOrRange = orRange.trim();
1708
+ if (!trimmedOrRange) {
1709
+ // An empty range string signifies wildcard *, satisfy any valid version
1710
+ // (We already checked if the version itself is valid)
1711
+ return true;
1712
+ }
1713
+ // Handle simple wildcards explicitly before complex parsing
1714
+ if (trimmedOrRange === '*' || trimmedOrRange === 'x') {
1715
+ return true;
1716
+ }
1717
+ try {
1718
+ // Apply existing parsing logic to the current OR sub-range
1719
+ const parsedSubRange = parseRange(trimmedOrRange); // Handles hyphens, trims etc.
1720
+ // Check if the result of initial parsing is empty, which can happen
1721
+ // for some wildcard cases handled by parseRange/parseComparatorString.
1722
+ // E.g. `parseStar` used in `parseComparatorString` returns ''.
1723
+ if (!parsedSubRange.trim()) {
1724
+ // If parsing results in empty string, treat as wildcard match
1725
+ return true;
1726
+ }
1727
+ const parsedComparatorString = parsedSubRange
1728
+ .split(' ')
1729
+ .map((rangeVersion) => parseComparatorString(rangeVersion)) // Expands ^, ~
1730
+ .join(' ');
1731
+ // Check again if the comparator string became empty after specific parsing like ^ or ~
1732
+ if (!parsedComparatorString.trim()) {
1733
+ return true;
1734
+ }
1735
+ // Split the sub-range by space for implicit AND conditions
1736
+ const comparators = parsedComparatorString
1737
+ .split(/\s+/)
1738
+ .map((comparator) => parseGTE0(comparator))
1739
+ // Filter out empty strings that might result from multiple spaces
1740
+ .filter(Boolean);
1741
+ // If a sub-range becomes empty after parsing (e.g., invalid characters),
1742
+ // it cannot be satisfied. This check might be redundant now but kept for safety.
1743
+ if (comparators.length === 0) {
1744
+ continue;
1745
+ }
1746
+ let subRangeSatisfied = true;
1747
+ for (const comparator of comparators) {
1748
+ const extractedComparator = extractComparator(comparator);
1749
+ // If any part of the AND sub-range is invalid, the sub-range is not satisfied
1750
+ if (!extractedComparator) {
1751
+ subRangeSatisfied = false;
1752
+ break;
1753
+ }
1754
+ const [, rangeOperator, , rangeMajor, rangeMinor, rangePatch, rangePreRelease,] = extractedComparator;
1755
+ const rangeAtom = {
1756
+ operator: rangeOperator,
1757
+ version: combineVersion(rangeMajor, rangeMinor, rangePatch, rangePreRelease),
1758
+ major: rangeMajor,
1759
+ minor: rangeMinor,
1760
+ patch: rangePatch,
1761
+ preRelease: rangePreRelease?.split('.'),
1762
+ };
1763
+ // Check if the version satisfies this specific comparator in the AND chain
1764
+ if (!compare(rangeAtom, versionAtom)) {
1765
+ subRangeSatisfied = false; // This part of the AND condition failed
1766
+ break; // No need to check further comparators in this sub-range
1767
+ }
1768
+ }
1769
+ // If all AND conditions within this OR sub-range were met, the overall range is satisfied
1770
+ if (subRangeSatisfied) {
1771
+ return true;
1772
+ }
1773
+ }
1774
+ catch (e) {
1775
+ // Log error and treat this sub-range as unsatisfied
1776
+ console.error(`[semver] Error processing range part "${trimmedOrRange}":`, e);
1777
+ continue;
1778
+ }
1779
+ }
1780
+ // If none of the OR sub-ranges were satisfied
1781
+ return false;
1782
+ }
1783
+
1784
+ function formatShare(shareArgs, from, name, shareStrategy) {
1785
+ let get;
1786
+ if ('get' in shareArgs) {
1787
+ // eslint-disable-next-line prefer-destructuring
1788
+ get = shareArgs.get;
1789
+ }
1790
+ else if ('lib' in shareArgs) {
1791
+ get = () => Promise.resolve(shareArgs.lib);
1792
+ }
1793
+ else {
1794
+ get = () => Promise.resolve(() => {
1795
+ throw new Error(`Can not get shared '${name}'!`);
1796
+ });
1797
+ }
1798
+ return {
1799
+ deps: [],
1800
+ useIn: [],
1801
+ from,
1802
+ loading: null,
1803
+ ...shareArgs,
1804
+ shareConfig: {
1805
+ requiredVersion: `^${shareArgs.version}`,
1806
+ singleton: false,
1807
+ eager: false,
1808
+ strictVersion: false,
1809
+ ...shareArgs.shareConfig,
1810
+ },
1811
+ get,
1812
+ loaded: shareArgs?.loaded || 'lib' in shareArgs ? true : undefined,
1813
+ version: shareArgs.version ?? '0',
1814
+ scope: Array.isArray(shareArgs.scope)
1815
+ ? shareArgs.scope
1816
+ : [shareArgs.scope ?? 'default'],
1817
+ strategy: (shareArgs.strategy ?? shareStrategy) || 'version-first',
1818
+ };
1819
+ }
1820
+ function formatShareConfigs(globalOptions, userOptions) {
1821
+ const shareArgs = userOptions.shared || {};
1822
+ const from = userOptions.name;
1823
+ const shareInfos = Object.keys(shareArgs).reduce((res, pkgName) => {
1824
+ const arrayShareArgs = arrayOptions(shareArgs[pkgName]);
1825
+ res[pkgName] = res[pkgName] || [];
1826
+ arrayShareArgs.forEach((shareConfig) => {
1827
+ res[pkgName].push(formatShare(shareConfig, from, pkgName, userOptions.shareStrategy));
1828
+ });
1829
+ return res;
1830
+ }, {});
1831
+ const shared = {
1832
+ ...globalOptions.shared,
1833
+ };
1834
+ Object.keys(shareInfos).forEach((shareKey) => {
1835
+ if (!shared[shareKey]) {
1836
+ shared[shareKey] = shareInfos[shareKey];
1837
+ }
1838
+ else {
1839
+ shareInfos[shareKey].forEach((newUserSharedOptions) => {
1840
+ const isSameVersion = shared[shareKey].find((sharedVal) => sharedVal.version === newUserSharedOptions.version);
1841
+ if (!isSameVersion) {
1842
+ shared[shareKey].push(newUserSharedOptions);
1843
+ }
1844
+ });
1845
+ }
1846
+ });
1847
+ return { shared, shareInfos };
1848
+ }
1849
+ function versionLt(a, b) {
1850
+ const transformInvalidVersion = (version) => {
1851
+ const isNumberVersion = !Number.isNaN(Number(version));
1852
+ if (isNumberVersion) {
1853
+ const splitArr = version.split('.');
1854
+ let validVersion = version;
1855
+ for (let i = 0; i < 3 - splitArr.length; i++) {
1856
+ validVersion += '.0';
1857
+ }
1858
+ return validVersion;
1859
+ }
1860
+ return version;
1861
+ };
1862
+ if (satisfy(transformInvalidVersion(a), `<=${transformInvalidVersion(b)}`)) {
1863
+ return true;
1864
+ }
1865
+ else {
1866
+ return false;
1867
+ }
1868
+ }
1869
+ const findVersion = (shareVersionMap, cb) => {
1870
+ const callback = cb ||
1871
+ function (prev, cur) {
1872
+ return versionLt(prev, cur);
1873
+ };
1874
+ return Object.keys(shareVersionMap).reduce((prev, cur) => {
1875
+ if (!prev) {
1876
+ return cur;
1877
+ }
1878
+ if (callback(prev, cur)) {
1879
+ return cur;
1880
+ }
1881
+ // default version is '0' https://github.com/webpack/webpack/blob/main/lib/sharing/ProvideSharedModule.js#L136
1882
+ if (prev === '0') {
1883
+ return cur;
1884
+ }
1885
+ return prev;
1886
+ }, 0);
1887
+ };
1888
+ const isLoaded = (shared) => {
1889
+ return Boolean(shared.loaded) || typeof shared.lib === 'function';
1890
+ };
1891
+ const isLoading = (shared) => {
1892
+ return Boolean(shared.loading);
1893
+ };
1894
+ function findSingletonVersionOrderByVersion(shareScopeMap, scope, pkgName) {
1895
+ const versions = shareScopeMap[scope][pkgName];
1896
+ const callback = function (prev, cur) {
1897
+ return !isLoaded(versions[prev]) && versionLt(prev, cur);
1898
+ };
1899
+ return findVersion(shareScopeMap[scope][pkgName], callback);
1900
+ }
1901
+ function findSingletonVersionOrderByLoaded(shareScopeMap, scope, pkgName) {
1902
+ const versions = shareScopeMap[scope][pkgName];
1903
+ const callback = function (prev, cur) {
1904
+ const isLoadingOrLoaded = (shared) => {
1905
+ return isLoaded(shared) || isLoading(shared);
1906
+ };
1907
+ if (isLoadingOrLoaded(versions[cur])) {
1908
+ if (isLoadingOrLoaded(versions[prev])) {
1909
+ return Boolean(versionLt(prev, cur));
1910
+ }
1911
+ else {
1912
+ return true;
1913
+ }
1914
+ }
1915
+ if (isLoadingOrLoaded(versions[prev])) {
1916
+ return false;
1917
+ }
1918
+ return versionLt(prev, cur);
1919
+ };
1920
+ return findVersion(shareScopeMap[scope][pkgName], callback);
1921
+ }
1922
+ function getFindShareFunction(strategy) {
1923
+ if (strategy === 'loaded-first') {
1924
+ return findSingletonVersionOrderByLoaded;
1925
+ }
1926
+ return findSingletonVersionOrderByVersion;
1927
+ }
1928
+ function getRegisteredShare(localShareScopeMap, pkgName, shareInfo, resolveShare) {
1929
+ if (!localShareScopeMap) {
1930
+ return;
1931
+ }
1932
+ const { shareConfig, scope = DEFAULT_SCOPE, strategy } = shareInfo;
1933
+ const scopes = Array.isArray(scope) ? scope : [scope];
1934
+ for (const sc of scopes) {
1935
+ if (shareConfig &&
1936
+ localShareScopeMap[sc] &&
1937
+ localShareScopeMap[sc][pkgName]) {
1938
+ const { requiredVersion } = shareConfig;
1939
+ const findShareFunction = getFindShareFunction(strategy);
1940
+ const maxOrSingletonVersion = findShareFunction(localShareScopeMap, sc, pkgName);
1941
+ //@ts-ignore
1942
+ const defaultResolver = () => {
1943
+ if (shareConfig.singleton) {
1944
+ if (typeof requiredVersion === 'string' &&
1945
+ !satisfy(maxOrSingletonVersion, requiredVersion)) {
1946
+ const msg = `Version ${maxOrSingletonVersion} from ${maxOrSingletonVersion &&
1947
+ localShareScopeMap[sc][pkgName][maxOrSingletonVersion].from} of shared singleton module ${pkgName} does not satisfy the requirement of ${shareInfo.from} which needs ${requiredVersion})`;
1948
+ if (shareConfig.strictVersion) {
1949
+ error(msg);
1950
+ }
1951
+ else {
1952
+ warn(msg);
1953
+ }
1954
+ }
1955
+ return localShareScopeMap[sc][pkgName][maxOrSingletonVersion];
1956
+ }
1957
+ else {
1958
+ if (requiredVersion === false || requiredVersion === '*') {
1959
+ return localShareScopeMap[sc][pkgName][maxOrSingletonVersion];
1960
+ }
1961
+ if (satisfy(maxOrSingletonVersion, requiredVersion)) {
1962
+ return localShareScopeMap[sc][pkgName][maxOrSingletonVersion];
1963
+ }
1964
+ for (const [versionKey, versionValue] of Object.entries(localShareScopeMap[sc][pkgName])) {
1965
+ if (satisfy(versionKey, requiredVersion)) {
1966
+ return versionValue;
1967
+ }
1968
+ }
1969
+ }
1970
+ };
1971
+ const params = {
1972
+ shareScopeMap: localShareScopeMap,
1973
+ scope: sc,
1974
+ pkgName,
1975
+ version: maxOrSingletonVersion,
1976
+ GlobalFederation: Global.__FEDERATION__,
1977
+ resolver: defaultResolver,
1978
+ };
1979
+ const resolveShared = resolveShare.emit(params) || params;
1980
+ return resolveShared.resolver();
1981
+ }
1982
+ }
1983
+ }
1984
+ function getGlobalShareScope() {
1985
+ return Global.__FEDERATION__.__SHARE__;
1986
+ }
1987
+ function getTargetSharedOptions(options) {
1988
+ const { pkgName, extraOptions, shareInfos } = options;
1989
+ const defaultResolver = (sharedOptions) => {
1990
+ if (!sharedOptions) {
1991
+ return undefined;
1992
+ }
1993
+ const shareVersionMap = {};
1994
+ sharedOptions.forEach((shared) => {
1995
+ shareVersionMap[shared.version] = shared;
1996
+ });
1997
+ const callback = function (prev, cur) {
1998
+ return !isLoaded(shareVersionMap[prev]) && versionLt(prev, cur);
1999
+ };
2000
+ const maxVersion = findVersion(shareVersionMap, callback);
2001
+ return shareVersionMap[maxVersion];
2002
+ };
2003
+ const resolver = extraOptions?.resolver ?? defaultResolver;
2004
+ return Object.assign({}, resolver(shareInfos[pkgName]), extraOptions?.customShareInfo);
2005
+ }
2006
+
2007
+ function getBuilderId$1() {
2008
+ //@ts-ignore
2009
+ return typeof FEDERATION_BUILD_IDENTIFIER !== 'undefined'
2010
+ ? //@ts-ignore
2011
+ FEDERATION_BUILD_IDENTIFIER
2012
+ : '';
2013
+ }
2014
+
2015
+ // Function to match a remote with its name and expose
2016
+ // id: pkgName(@federation/app1) + expose(button) = @federation/app1/button
2017
+ // id: alias(app1) + expose(button) = app1/button
2018
+ // id: alias(app1/utils) + expose(loadash/sort) = app1/utils/loadash/sort
2019
+ function matchRemoteWithNameAndExpose(remotes, id) {
2020
+ for (const remote of remotes) {
2021
+ // match pkgName
2022
+ const isNameMatched = id.startsWith(remote.name);
2023
+ let expose = id.replace(remote.name, '');
2024
+ if (isNameMatched) {
2025
+ if (expose.startsWith('/')) {
2026
+ const pkgNameOrAlias = remote.name;
2027
+ expose = `.${expose}`;
2028
+ return {
2029
+ pkgNameOrAlias,
2030
+ expose,
2031
+ remote,
2032
+ };
2033
+ }
2034
+ else if (expose === '') {
2035
+ return {
2036
+ pkgNameOrAlias: remote.name,
2037
+ expose: '.',
2038
+ remote,
2039
+ };
2040
+ }
2041
+ }
2042
+ // match alias
2043
+ const isAliasMatched = remote.alias && id.startsWith(remote.alias);
2044
+ let exposeWithAlias = remote.alias && id.replace(remote.alias, '');
2045
+ if (remote.alias && isAliasMatched) {
2046
+ if (exposeWithAlias && exposeWithAlias.startsWith('/')) {
2047
+ const pkgNameOrAlias = remote.alias;
2048
+ exposeWithAlias = `.${exposeWithAlias}`;
2049
+ return {
2050
+ pkgNameOrAlias,
2051
+ expose: exposeWithAlias,
2052
+ remote,
2053
+ };
2054
+ }
2055
+ else if (exposeWithAlias === '') {
2056
+ return {
2057
+ pkgNameOrAlias: remote.alias,
2058
+ expose: '.',
2059
+ remote,
2060
+ };
2061
+ }
2062
+ }
2063
+ }
2064
+ return;
2065
+ }
2066
+ // Function to match a remote with its name or alias
2067
+ function matchRemote(remotes, nameOrAlias) {
2068
+ for (const remote of remotes) {
2069
+ const isNameMatched = nameOrAlias === remote.name;
2070
+ if (isNameMatched) {
2071
+ return remote;
2072
+ }
2073
+ const isAliasMatched = remote.alias && nameOrAlias === remote.alias;
2074
+ if (isAliasMatched) {
2075
+ return remote;
2076
+ }
2077
+ }
2078
+ return;
2079
+ }
2080
+
2081
+ function registerPlugins(plugins, instance) {
2082
+ const globalPlugins = getGlobalHostPlugins();
2083
+ const hookInstances = [
2084
+ instance.hooks,
2085
+ instance.remoteHandler.hooks,
2086
+ instance.sharedHandler.hooks,
2087
+ instance.snapshotHandler.hooks,
2088
+ instance.loaderHook,
2089
+ instance.bridgeHook,
2090
+ ];
2091
+ // Incorporate global plugins
2092
+ if (globalPlugins.length > 0) {
2093
+ globalPlugins.forEach((plugin) => {
2094
+ if (plugins?.find((item) => item.name !== plugin.name)) {
2095
+ plugins.push(plugin);
2096
+ }
2097
+ });
2098
+ }
2099
+ if (plugins && plugins.length > 0) {
2100
+ plugins.forEach((plugin) => {
2101
+ hookInstances.forEach((hookInstance) => {
2102
+ hookInstance.applyPlugin(plugin, instance);
2103
+ });
2104
+ });
2105
+ }
2106
+ return plugins;
2107
+ }
2108
+
2109
+ const importCallback = '.then(callbacks[0]).catch(callbacks[1])';
2110
+ async function loadEsmEntry({ entry, remoteEntryExports, }) {
2111
+ return new Promise((resolve, reject) => {
2112
+ try {
2113
+ if (!remoteEntryExports) {
2114
+ if (typeof FEDERATION_ALLOW_NEW_FUNCTION !== 'undefined') {
2115
+ new Function('callbacks', `import("${entry}")${importCallback}`)([
2116
+ resolve,
2117
+ reject,
2118
+ ]);
2119
+ }
2120
+ else {
2121
+ import(/* webpackIgnore: true */ /* @vite-ignore */ entry)
2122
+ .then(resolve)
2123
+ .catch(reject);
2124
+ }
2125
+ }
2126
+ else {
2127
+ resolve(remoteEntryExports);
2128
+ }
2129
+ }
2130
+ catch (e) {
2131
+ reject(e);
2132
+ }
2133
+ });
2134
+ }
2135
+ async function loadSystemJsEntry({ entry, remoteEntryExports, }) {
2136
+ return new Promise((resolve, reject) => {
2137
+ try {
2138
+ if (!remoteEntryExports) {
2139
+ //@ts-ignore
2140
+ if (typeof __system_context__ === 'undefined') {
2141
+ //@ts-ignore
2142
+ System.import(entry).then(resolve).catch(reject);
2143
+ }
2144
+ else {
2145
+ new Function('callbacks', `System.import("${entry}")${importCallback}`)([resolve, reject]);
2146
+ }
2147
+ }
2148
+ else {
2149
+ resolve(remoteEntryExports);
2150
+ }
2151
+ }
2152
+ catch (e) {
2153
+ reject(e);
2154
+ }
2155
+ });
2156
+ }
2157
+ function handleRemoteEntryLoaded(name, globalName, entry) {
2158
+ const { remoteEntryKey, entryExports } = getRemoteEntryExports(name, globalName);
2159
+ assert(entryExports, errorCodes.getShortErrorMsg(errorCodes.RUNTIME_001, errorCodes.runtimeDescMap, {
2160
+ remoteName: name,
2161
+ remoteEntryUrl: entry,
2162
+ remoteEntryKey,
2163
+ }));
2164
+ return entryExports;
2165
+ }
2166
+ async function loadEntryScript({ name, globalName, entry, loaderHook, getEntryUrl, }) {
2167
+ const { entryExports: remoteEntryExports } = getRemoteEntryExports(name, globalName);
2168
+ if (remoteEntryExports) {
2169
+ return remoteEntryExports;
2170
+ }
2171
+ // if getEntryUrl is passed, use the getEntryUrl to get the entry url
2172
+ const url = getEntryUrl ? getEntryUrl(entry) : entry;
2173
+ return sdk.loadScript(url, {
2174
+ attrs: {},
2175
+ createScriptHook: (url, attrs) => {
2176
+ const res = loaderHook.lifecycle.createScript.emit({ url, attrs });
2177
+ if (!res)
2178
+ return;
2179
+ if (res instanceof HTMLScriptElement) {
2180
+ return res;
2181
+ }
2182
+ if ('script' in res || 'timeout' in res) {
2183
+ return res;
2184
+ }
2185
+ return;
2186
+ },
2187
+ })
2188
+ .then(() => {
2189
+ return handleRemoteEntryLoaded(name, globalName, entry);
2190
+ })
2191
+ .catch((e) => {
2192
+ assert(undefined, errorCodes.getShortErrorMsg(errorCodes.RUNTIME_008, errorCodes.runtimeDescMap, {
2193
+ remoteName: name,
2194
+ resourceUrl: entry,
2195
+ }));
2196
+ throw e;
2197
+ });
2198
+ }
2199
+ async function loadEntryDom({ remoteInfo, remoteEntryExports, loaderHook, getEntryUrl, }) {
2200
+ const { entry, entryGlobalName: globalName, name, type } = remoteInfo;
2201
+ switch (type) {
2202
+ case 'esm':
2203
+ case 'module':
2204
+ return loadEsmEntry({ entry, remoteEntryExports });
2205
+ case 'system':
2206
+ return loadSystemJsEntry({ entry, remoteEntryExports });
2207
+ default:
2208
+ return loadEntryScript({
2209
+ entry,
2210
+ globalName,
2211
+ name,
2212
+ loaderHook,
2213
+ getEntryUrl,
2214
+ });
2215
+ }
2216
+ }
2217
+ async function loadEntryNode({ remoteInfo, loaderHook, }) {
2218
+ const { entry, entryGlobalName: globalName, name, type } = remoteInfo;
2219
+ const { entryExports: remoteEntryExports } = getRemoteEntryExports(name, globalName);
2220
+ if (remoteEntryExports) {
2221
+ return remoteEntryExports;
2222
+ }
2223
+ return sdk.loadScriptNode(entry, {
2224
+ attrs: { name, globalName, type },
2225
+ loaderHook: {
2226
+ createScriptHook: (url, attrs = {}) => {
2227
+ const res = loaderHook.lifecycle.createScript.emit({ url, attrs });
2228
+ if (!res)
2229
+ return;
2230
+ if ('url' in res) {
2231
+ return res;
2232
+ }
2233
+ return;
2234
+ },
2235
+ },
2236
+ })
2237
+ .then(() => {
2238
+ return handleRemoteEntryLoaded(name, globalName, entry);
2239
+ })
2240
+ .catch((e) => {
2241
+ throw e;
2242
+ });
2243
+ }
2244
+ function getRemoteEntryUniqueKey(remoteInfo) {
2245
+ const { entry, name } = remoteInfo;
2246
+ return sdk.composeKeyWithSeparator(name, entry);
2247
+ }
2248
+ async function getRemoteEntry(params) {
2249
+ const { origin, remoteEntryExports, remoteInfo, getEntryUrl, _inErrorHandling = false, } = params;
2250
+ const uniqueKey = getRemoteEntryUniqueKey(remoteInfo);
2251
+ if (remoteEntryExports) {
2252
+ return remoteEntryExports;
2253
+ }
2254
+ if (!globalLoading[uniqueKey]) {
2255
+ const loadEntryHook = origin.remoteHandler.hooks.lifecycle.loadEntry;
2256
+ const loaderHook = origin.loaderHook;
2257
+ globalLoading[uniqueKey] = loadEntryHook
2258
+ .emit({
2259
+ loaderHook,
2260
+ remoteInfo,
2261
+ remoteEntryExports,
2262
+ })
2263
+ .then((res) => {
2264
+ if (res) {
2265
+ return res;
2266
+ }
2267
+ // Use ENV_TARGET if defined, otherwise fallback to isBrowserEnv, must keep this
2268
+ const isWebEnvironment = typeof ENV_TARGET !== 'undefined'
2269
+ ? ENV_TARGET === 'web'
2270
+ : sdk.isBrowserEnv();
2271
+ return isWebEnvironment
2272
+ ? loadEntryDom({
2273
+ remoteInfo,
2274
+ remoteEntryExports,
2275
+ loaderHook,
2276
+ getEntryUrl,
2277
+ })
2278
+ : loadEntryNode({ remoteInfo, loaderHook });
2279
+ })
2280
+ .catch(async (err) => {
2281
+ const uniqueKey = getRemoteEntryUniqueKey(remoteInfo);
2282
+ const isScriptLoadError = err instanceof Error && err.message.includes(errorCodes.RUNTIME_008);
2283
+ if (isScriptLoadError && !_inErrorHandling) {
2284
+ const wrappedGetRemoteEntry = (params) => {
2285
+ return getRemoteEntry({ ...params, _inErrorHandling: true });
2286
+ };
2287
+ const RemoteEntryExports = await origin.loaderHook.lifecycle.loadEntryError.emit({
2288
+ getRemoteEntry: wrappedGetRemoteEntry,
2289
+ origin,
2290
+ remoteInfo: remoteInfo,
2291
+ remoteEntryExports,
2292
+ globalLoading,
2293
+ uniqueKey,
2294
+ });
2295
+ if (RemoteEntryExports) {
2296
+ return RemoteEntryExports;
2297
+ }
2298
+ }
2299
+ throw err;
2300
+ });
2301
+ }
2302
+ return globalLoading[uniqueKey];
2303
+ }
2304
+ function getRemoteInfo(remote) {
2305
+ return {
2306
+ ...remote,
2307
+ entry: 'entry' in remote ? remote.entry : '',
2308
+ type: remote.type || DEFAULT_REMOTE_TYPE,
2309
+ entryGlobalName: remote.entryGlobalName || remote.name,
2310
+ shareScope: remote.shareScope || DEFAULT_SCOPE,
2311
+ };
2312
+ }
2313
+
2314
+ function defaultPreloadArgs(preloadConfig) {
2315
+ return {
2316
+ resourceCategory: 'sync',
2317
+ share: true,
2318
+ depsRemote: true,
2319
+ prefetchInterface: false,
2320
+ ...preloadConfig,
2321
+ };
2322
+ }
2323
+ function formatPreloadArgs(remotes, preloadArgs) {
2324
+ return preloadArgs.map((args) => {
2325
+ const remoteInfo = matchRemote(remotes, args.nameOrAlias);
2326
+ assert(remoteInfo, `Unable to preload ${args.nameOrAlias} as it is not included in ${!remoteInfo &&
2327
+ sdk.safeToString({
2328
+ remoteInfo,
2329
+ remotes,
2330
+ })}`);
2331
+ return {
2332
+ remote: remoteInfo,
2333
+ preloadConfig: defaultPreloadArgs(args),
2334
+ };
2335
+ });
2336
+ }
2337
+ function normalizePreloadExposes(exposes) {
2338
+ if (!exposes) {
2339
+ return [];
2340
+ }
2341
+ return exposes.map((expose) => {
2342
+ if (expose === '.') {
2343
+ return expose;
2344
+ }
2345
+ if (expose.startsWith('./')) {
2346
+ return expose.replace('./', '');
2347
+ }
2348
+ return expose;
2349
+ });
2350
+ }
2351
+ function preloadAssets(remoteInfo, host, assets,
2352
+ // It is used to distinguish preload from load remote parallel loading
2353
+ useLinkPreload = true) {
2354
+ const { cssAssets, jsAssetsWithoutEntry, entryAssets } = assets;
2355
+ if (host.options.inBrowser) {
2356
+ entryAssets.forEach((asset) => {
2357
+ const { moduleInfo } = asset;
2358
+ const module = host.moduleCache.get(remoteInfo.name);
2359
+ if (module) {
2360
+ getRemoteEntry({
2361
+ origin: host,
2362
+ remoteInfo: moduleInfo,
2363
+ remoteEntryExports: module.remoteEntryExports,
2364
+ });
2365
+ }
2366
+ else {
2367
+ getRemoteEntry({
2368
+ origin: host,
2369
+ remoteInfo: moduleInfo,
2370
+ remoteEntryExports: undefined,
2371
+ });
2372
+ }
2373
+ });
2374
+ if (useLinkPreload) {
2375
+ const defaultAttrs = {
2376
+ rel: 'preload',
2377
+ as: 'style',
2378
+ };
2379
+ cssAssets.forEach((cssUrl) => {
2380
+ const { link: cssEl, needAttach } = sdk.createLink({
2381
+ url: cssUrl,
2382
+ cb: () => {
2383
+ // noop
2384
+ },
2385
+ attrs: defaultAttrs,
2386
+ createLinkHook: (url, attrs) => {
2387
+ const res = host.loaderHook.lifecycle.createLink.emit({
2388
+ url,
2389
+ attrs,
2390
+ });
2391
+ if (res instanceof HTMLLinkElement) {
2392
+ return res;
2393
+ }
2394
+ return;
2395
+ },
2396
+ });
2397
+ needAttach && document.head.appendChild(cssEl);
2398
+ });
2399
+ }
2400
+ else {
2401
+ const defaultAttrs = {
2402
+ rel: 'stylesheet',
2403
+ type: 'text/css',
2404
+ };
2405
+ cssAssets.forEach((cssUrl) => {
2406
+ const { link: cssEl, needAttach } = sdk.createLink({
2407
+ url: cssUrl,
2408
+ cb: () => {
2409
+ // noop
2410
+ },
2411
+ attrs: defaultAttrs,
2412
+ createLinkHook: (url, attrs) => {
2413
+ const res = host.loaderHook.lifecycle.createLink.emit({
2414
+ url,
2415
+ attrs,
2416
+ });
2417
+ if (res instanceof HTMLLinkElement) {
2418
+ return res;
2419
+ }
2420
+ return;
2421
+ },
2422
+ needDeleteLink: false,
2423
+ });
2424
+ needAttach && document.head.appendChild(cssEl);
2425
+ });
2426
+ }
2427
+ if (useLinkPreload) {
2428
+ const defaultAttrs = {
2429
+ rel: 'preload',
2430
+ as: 'script',
2431
+ };
2432
+ jsAssetsWithoutEntry.forEach((jsUrl) => {
2433
+ const { link: linkEl, needAttach } = sdk.createLink({
2434
+ url: jsUrl,
2435
+ cb: () => {
2436
+ // noop
2437
+ },
2438
+ attrs: defaultAttrs,
2439
+ createLinkHook: (url, attrs) => {
2440
+ const res = host.loaderHook.lifecycle.createLink.emit({
2441
+ url,
2442
+ attrs,
2443
+ });
2444
+ if (res instanceof HTMLLinkElement) {
2445
+ return res;
2446
+ }
2447
+ return;
2448
+ },
2449
+ });
2450
+ needAttach && document.head.appendChild(linkEl);
2451
+ });
2452
+ }
2453
+ else {
2454
+ const defaultAttrs = {
2455
+ fetchpriority: 'high',
2456
+ type: remoteInfo?.type === 'module' ? 'module' : 'text/javascript',
2457
+ };
2458
+ jsAssetsWithoutEntry.forEach((jsUrl) => {
2459
+ const { script: scriptEl, needAttach } = sdk.createScript({
2460
+ url: jsUrl,
2461
+ cb: () => {
2462
+ // noop
2463
+ },
2464
+ attrs: defaultAttrs,
2465
+ createScriptHook: (url, attrs) => {
2466
+ const res = host.loaderHook.lifecycle.createScript.emit({
2467
+ url,
2468
+ attrs,
2469
+ });
2470
+ if (res instanceof HTMLScriptElement) {
2471
+ return res;
2472
+ }
2473
+ return;
2474
+ },
2475
+ needDeleteScript: true,
2476
+ });
2477
+ needAttach && document.head.appendChild(scriptEl);
2478
+ });
2479
+ }
2480
+ }
2481
+ }
2482
+
2483
+ const ShareUtils = {
2484
+ getRegisteredShare,
2485
+ getGlobalShareScope,
2486
+ };
2487
+ const GlobalUtils = {
2488
+ Global,
2489
+ nativeGlobal,
2490
+ resetFederationGlobalInfo,
2491
+ setGlobalFederationInstance,
2492
+ getGlobalFederationConstructor,
2493
+ setGlobalFederationConstructor,
2494
+ getInfoWithoutType,
2495
+ getGlobalSnapshot,
2496
+ getTargetSnapshotInfoByModuleInfo,
2497
+ getGlobalSnapshotInfoByModuleInfo,
2498
+ setGlobalSnapshotInfoByModuleInfo,
2499
+ addGlobalSnapshot,
2500
+ getRemoteEntryExports,
2501
+ registerGlobalPlugins,
2502
+ getGlobalHostPlugins,
2503
+ getPreloaded,
2504
+ setPreloaded,
2505
+ };
2506
+ var helpers = {
2507
+ global: GlobalUtils,
2508
+ share: ShareUtils,
2509
+ utils: {
2510
+ matchRemoteWithNameAndExpose,
2511
+ preloadAssets,
2512
+ getRemoteInfo,
2513
+ },
2514
+ };
2515
+
2516
+ class Module {
2517
+ constructor({ remoteInfo, host, }) {
2518
+ this.inited = false;
2519
+ this.lib = undefined;
2520
+ this.remoteInfo = remoteInfo;
2521
+ this.host = host;
2522
+ }
2523
+ async getEntry() {
2524
+ if (this.remoteEntryExports) {
2525
+ return this.remoteEntryExports;
2526
+ }
2527
+ let remoteEntryExports;
2528
+ remoteEntryExports = await getRemoteEntry({
2529
+ origin: this.host,
2530
+ remoteInfo: this.remoteInfo,
2531
+ remoteEntryExports: this.remoteEntryExports,
2532
+ });
2533
+ assert(remoteEntryExports, `remoteEntryExports is undefined \n ${sdk.safeToString(this.remoteInfo)}`);
2534
+ this.remoteEntryExports = remoteEntryExports;
2535
+ return this.remoteEntryExports;
2536
+ }
2537
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
2538
+ async get(id, expose, options, remoteSnapshot) {
2539
+ const { loadFactory = true } = options || { loadFactory: true };
2540
+ // Get remoteEntry.js
2541
+ const remoteEntryExports = await this.getEntry();
2542
+ if (!this.inited) {
2543
+ const localShareScopeMap = this.host.shareScopeMap;
2544
+ const shareScopeKeys = Array.isArray(this.remoteInfo.shareScope)
2545
+ ? this.remoteInfo.shareScope
2546
+ : [this.remoteInfo.shareScope];
2547
+ if (!shareScopeKeys.length) {
2548
+ shareScopeKeys.push('default');
2549
+ }
2550
+ shareScopeKeys.forEach((shareScopeKey) => {
2551
+ if (!localShareScopeMap[shareScopeKey]) {
2552
+ localShareScopeMap[shareScopeKey] = {};
2553
+ }
2554
+ });
2555
+ // TODO: compate legacy init params, should use shareScopeMap if exist
2556
+ const shareScope = localShareScopeMap[shareScopeKeys[0]];
2557
+ const initScope = [];
2558
+ const remoteEntryInitOptions = {
2559
+ version: this.remoteInfo.version || '',
2560
+ shareScopeKeys: Array.isArray(this.remoteInfo.shareScope)
2561
+ ? shareScopeKeys
2562
+ : this.remoteInfo.shareScope || 'default',
2563
+ };
2564
+ // Help to find host instance
2565
+ Object.defineProperty(remoteEntryInitOptions, 'shareScopeMap', {
2566
+ value: localShareScopeMap,
2567
+ // remoteEntryInitOptions will be traversed and assigned during container init, ,so this attribute is not allowed to be traversed
2568
+ enumerable: false,
2569
+ });
2570
+ const initContainerOptions = await this.host.hooks.lifecycle.beforeInitContainer.emit({
2571
+ shareScope,
2572
+ // @ts-ignore shareScopeMap will be set by Object.defineProperty
2573
+ remoteEntryInitOptions,
2574
+ initScope,
2575
+ remoteInfo: this.remoteInfo,
2576
+ origin: this.host,
2577
+ });
2578
+ if (typeof remoteEntryExports?.init === 'undefined') {
2579
+ error(errorCodes.getShortErrorMsg(errorCodes.RUNTIME_002, errorCodes.runtimeDescMap, {
2580
+ hostName: this.host.name,
2581
+ remoteName: this.remoteInfo.name,
2582
+ remoteEntryUrl: this.remoteInfo.entry,
2583
+ remoteEntryKey: this.remoteInfo.entryGlobalName,
2584
+ }));
2585
+ }
2586
+ await remoteEntryExports.init(initContainerOptions.shareScope, initContainerOptions.initScope, initContainerOptions.remoteEntryInitOptions);
2587
+ await this.host.hooks.lifecycle.initContainer.emit({
2588
+ ...initContainerOptions,
2589
+ id,
2590
+ remoteSnapshot,
2591
+ remoteEntryExports,
2592
+ });
2593
+ }
2594
+ this.lib = remoteEntryExports;
2595
+ this.inited = true;
2596
+ let moduleFactory;
2597
+ moduleFactory = await this.host.loaderHook.lifecycle.getModuleFactory.emit({
2598
+ remoteEntryExports,
2599
+ expose,
2600
+ moduleInfo: this.remoteInfo,
2601
+ });
2602
+ // get exposeGetter
2603
+ if (!moduleFactory) {
2604
+ moduleFactory = await remoteEntryExports.get(expose);
2605
+ }
2606
+ assert(moduleFactory, `${getFMId(this.remoteInfo)} remote don't export ${expose}.`);
2607
+ // keep symbol for module name always one format
2608
+ const symbolName = processModuleAlias(this.remoteInfo.name, expose);
2609
+ const wrapModuleFactory = this.wraperFactory(moduleFactory, symbolName);
2610
+ if (!loadFactory) {
2611
+ return wrapModuleFactory;
2612
+ }
2613
+ const exposeContent = await wrapModuleFactory();
2614
+ return exposeContent;
2615
+ }
2616
+ wraperFactory(moduleFactory, id) {
2617
+ function defineModuleId(res, id) {
2618
+ if (res &&
2619
+ typeof res === 'object' &&
2620
+ Object.isExtensible(res) &&
2621
+ !Object.getOwnPropertyDescriptor(res, Symbol.for('mf_module_id'))) {
2622
+ Object.defineProperty(res, Symbol.for('mf_module_id'), {
2623
+ value: id,
2624
+ enumerable: false,
2625
+ });
2626
+ }
2627
+ }
2628
+ if (moduleFactory instanceof Promise) {
2629
+ return async () => {
2630
+ const res = await moduleFactory();
2631
+ // This parameter is used for bridge debugging
2632
+ defineModuleId(res, id);
2633
+ return res;
2634
+ };
2635
+ }
2636
+ else {
2637
+ return () => {
2638
+ const res = moduleFactory();
2639
+ // This parameter is used for bridge debugging
2640
+ defineModuleId(res, id);
2641
+ return res;
2642
+ };
2643
+ }
2644
+ }
2645
+ }
2646
+
2647
+ class SyncHook {
2648
+ constructor(type) {
2649
+ this.type = '';
2650
+ this.listeners = new Set();
2651
+ if (type) {
2652
+ this.type = type;
2653
+ }
2654
+ }
2655
+ on(fn) {
2656
+ if (typeof fn === 'function') {
2657
+ this.listeners.add(fn);
2658
+ }
2659
+ }
2660
+ once(fn) {
2661
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
2662
+ const self = this;
2663
+ this.on(function wrapper(...args) {
2664
+ self.remove(wrapper);
2665
+ // eslint-disable-next-line prefer-spread
2666
+ return fn.apply(null, args);
2667
+ });
2668
+ }
2669
+ emit(...data) {
2670
+ let result;
2671
+ if (this.listeners.size > 0) {
2672
+ // eslint-disable-next-line prefer-spread
2673
+ this.listeners.forEach((fn) => {
2674
+ result = fn(...data);
2675
+ });
2676
+ }
2677
+ return result;
2678
+ }
2679
+ remove(fn) {
2680
+ this.listeners.delete(fn);
2681
+ }
2682
+ removeAll() {
2683
+ this.listeners.clear();
2684
+ }
2685
+ }
2686
+
2687
+ class AsyncHook extends SyncHook {
2688
+ emit(...data) {
2689
+ let result;
2690
+ const ls = Array.from(this.listeners);
2691
+ if (ls.length > 0) {
2692
+ let i = 0;
2693
+ const call = (prev) => {
2694
+ if (prev === false) {
2695
+ return false; // Abort process
2696
+ }
2697
+ else if (i < ls.length) {
2698
+ return Promise.resolve(ls[i++].apply(null, data)).then(call);
2699
+ }
2700
+ else {
2701
+ return prev;
2702
+ }
2703
+ };
2704
+ result = call();
2705
+ }
2706
+ return Promise.resolve(result);
2707
+ }
2708
+ }
2709
+
2710
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
2711
+ function checkReturnData(originalData, returnedData) {
2712
+ if (!isObject(returnedData)) {
2713
+ return false;
2714
+ }
2715
+ if (originalData !== returnedData) {
2716
+ // eslint-disable-next-line no-restricted-syntax
2717
+ for (const key in originalData) {
2718
+ if (!(key in returnedData)) {
2719
+ return false;
2720
+ }
2721
+ }
2722
+ }
2723
+ return true;
2724
+ }
2725
+ class SyncWaterfallHook extends SyncHook {
2726
+ constructor(type) {
2727
+ super();
2728
+ this.onerror = error;
2729
+ this.type = type;
2730
+ }
2731
+ emit(data) {
2732
+ if (!isObject(data)) {
2733
+ error(`The data for the "${this.type}" hook should be an object.`);
2734
+ }
2735
+ for (const fn of this.listeners) {
2736
+ try {
2737
+ const tempData = fn(data);
2738
+ if (checkReturnData(data, tempData)) {
2739
+ data = tempData;
2740
+ }
2741
+ else {
2742
+ this.onerror(`A plugin returned an unacceptable value for the "${this.type}" type.`);
2743
+ break;
2744
+ }
2745
+ }
2746
+ catch (e) {
2747
+ warn(e);
2748
+ this.onerror(e);
2749
+ }
2750
+ }
2751
+ return data;
2752
+ }
2753
+ }
2754
+
2755
+ class AsyncWaterfallHook extends SyncHook {
2756
+ constructor(type) {
2757
+ super();
2758
+ this.onerror = error;
2759
+ this.type = type;
2760
+ }
2761
+ emit(data) {
2762
+ if (!isObject(data)) {
2763
+ error(`The response data for the "${this.type}" hook must be an object.`);
2764
+ }
2765
+ const ls = Array.from(this.listeners);
2766
+ if (ls.length > 0) {
2767
+ let i = 0;
2768
+ const processError = (e) => {
2769
+ warn(e);
2770
+ this.onerror(e);
2771
+ return data;
2772
+ };
2773
+ const call = (prevData) => {
2774
+ if (checkReturnData(data, prevData)) {
2775
+ data = prevData;
2776
+ if (i < ls.length) {
2777
+ try {
2778
+ return Promise.resolve(ls[i++](data)).then(call, processError);
2779
+ }
2780
+ catch (e) {
2781
+ return processError(e);
2782
+ }
2783
+ }
2784
+ }
2785
+ else {
2786
+ this.onerror(`A plugin returned an incorrect value for the "${this.type}" type.`);
2787
+ }
2788
+ return data;
2789
+ };
2790
+ return Promise.resolve(call(data));
2791
+ }
2792
+ return Promise.resolve(data);
2793
+ }
2794
+ }
2795
+
2796
+ class PluginSystem {
2797
+ constructor(lifecycle) {
2798
+ this.registerPlugins = {};
2799
+ this.lifecycle = lifecycle;
2800
+ this.lifecycleKeys = Object.keys(lifecycle);
2801
+ }
2802
+ applyPlugin(plugin, instance) {
2803
+ assert(isPlainObject(plugin), 'Plugin configuration is invalid.');
2804
+ // The plugin's name is mandatory and must be unique
2805
+ const pluginName = plugin.name;
2806
+ assert(pluginName, 'A name must be provided by the plugin.');
2807
+ if (!this.registerPlugins[pluginName]) {
2808
+ this.registerPlugins[pluginName] = plugin;
2809
+ plugin.apply?.(instance);
2810
+ Object.keys(this.lifecycle).forEach((key) => {
2811
+ const pluginLife = plugin[key];
2812
+ if (pluginLife) {
2813
+ this.lifecycle[key].on(pluginLife);
2814
+ }
2815
+ });
2816
+ }
2817
+ }
2818
+ removePlugin(pluginName) {
2819
+ assert(pluginName, 'A name is required.');
2820
+ const plugin = this.registerPlugins[pluginName];
2821
+ assert(plugin, `The plugin "${pluginName}" is not registered.`);
2822
+ Object.keys(plugin).forEach((key) => {
2823
+ if (key !== 'name') {
2824
+ this.lifecycle[key].remove(plugin[key]);
2825
+ }
2826
+ });
2827
+ }
2828
+ }
2829
+
2830
+ function assignRemoteInfo(remoteInfo, remoteSnapshot) {
2831
+ const remoteEntryInfo = getRemoteEntryInfoFromSnapshot(remoteSnapshot);
2832
+ if (!remoteEntryInfo.url) {
2833
+ error(`The attribute remoteEntry of ${remoteInfo.name} must not be undefined.`);
2834
+ }
2835
+ let entryUrl = sdk.getResourceUrl(remoteSnapshot, remoteEntryInfo.url);
2836
+ if (!sdk.isBrowserEnv() && !entryUrl.startsWith('http')) {
2837
+ entryUrl = `https:${entryUrl}`;
2838
+ }
2839
+ remoteInfo.type = remoteEntryInfo.type;
2840
+ remoteInfo.entryGlobalName = remoteEntryInfo.globalName;
2841
+ remoteInfo.entry = entryUrl;
2842
+ remoteInfo.version = remoteSnapshot.version;
2843
+ remoteInfo.buildVersion = remoteSnapshot.buildVersion;
2844
+ }
2845
+ function snapshotPlugin() {
2846
+ return {
2847
+ name: 'snapshot-plugin',
2848
+ async afterResolve(args) {
2849
+ const { remote, pkgNameOrAlias, expose, origin, remoteInfo, id } = args;
2850
+ if (!isRemoteInfoWithEntry(remote) || !isPureRemoteEntry(remote)) {
2851
+ const { remoteSnapshot, globalSnapshot } = await origin.snapshotHandler.loadRemoteSnapshotInfo({
2852
+ moduleInfo: remote,
2853
+ id,
2854
+ });
2855
+ assignRemoteInfo(remoteInfo, remoteSnapshot);
2856
+ // preloading assets
2857
+ const preloadOptions = {
2858
+ remote,
2859
+ preloadConfig: {
2860
+ nameOrAlias: pkgNameOrAlias,
2861
+ exposes: [expose],
2862
+ resourceCategory: 'sync',
2863
+ share: false,
2864
+ depsRemote: false,
2865
+ },
2866
+ };
2867
+ const assets = await origin.remoteHandler.hooks.lifecycle.generatePreloadAssets.emit({
2868
+ origin,
2869
+ preloadOptions,
2870
+ remoteInfo,
2871
+ remote,
2872
+ remoteSnapshot,
2873
+ globalSnapshot,
2874
+ });
2875
+ if (assets) {
2876
+ preloadAssets(remoteInfo, origin, assets, false);
2877
+ }
2878
+ return {
2879
+ ...args,
2880
+ remoteSnapshot,
2881
+ };
2882
+ }
2883
+ return args;
2884
+ },
2885
+ };
2886
+ }
2887
+
2888
+ // name
2889
+ // name:version
2890
+ function splitId(id) {
2891
+ const splitInfo = id.split(':');
2892
+ if (splitInfo.length === 1) {
2893
+ return {
2894
+ name: splitInfo[0],
2895
+ version: undefined,
2896
+ };
2897
+ }
2898
+ else if (splitInfo.length === 2) {
2899
+ return {
2900
+ name: splitInfo[0],
2901
+ version: splitInfo[1],
2902
+ };
2903
+ }
2904
+ else {
2905
+ return {
2906
+ name: splitInfo[1],
2907
+ version: splitInfo[2],
2908
+ };
2909
+ }
2910
+ }
2911
+ // Traverse all nodes in moduleInfo and traverse the entire snapshot
2912
+ function traverseModuleInfo(globalSnapshot, remoteInfo, traverse, isRoot, memo = {}, remoteSnapshot) {
2913
+ const id = getFMId(remoteInfo);
2914
+ const { value: snapshotValue } = getInfoWithoutType(globalSnapshot, id);
2915
+ const effectiveRemoteSnapshot = remoteSnapshot || snapshotValue;
2916
+ if (effectiveRemoteSnapshot && !sdk.isManifestProvider(effectiveRemoteSnapshot)) {
2917
+ traverse(effectiveRemoteSnapshot, remoteInfo, isRoot);
2918
+ if (effectiveRemoteSnapshot.remotesInfo) {
2919
+ const remoteKeys = Object.keys(effectiveRemoteSnapshot.remotesInfo);
2920
+ for (const key of remoteKeys) {
2921
+ if (memo[key]) {
2922
+ continue;
2923
+ }
2924
+ memo[key] = true;
2925
+ const subRemoteInfo = splitId(key);
2926
+ const remoteValue = effectiveRemoteSnapshot.remotesInfo[key];
2927
+ traverseModuleInfo(globalSnapshot, {
2928
+ name: subRemoteInfo.name,
2929
+ version: remoteValue.matchedVersion,
2930
+ }, traverse, false, memo, undefined);
2931
+ }
2932
+ }
2933
+ }
2934
+ }
2935
+ const isExisted = (type, url) => {
2936
+ return document.querySelector(`${type}[${type === 'link' ? 'href' : 'src'}="${url}"]`);
2937
+ };
2938
+ // eslint-disable-next-line max-lines-per-function
2939
+ function generatePreloadAssets(origin, preloadOptions, remote, globalSnapshot, remoteSnapshot) {
2940
+ const cssAssets = [];
2941
+ const jsAssets = [];
2942
+ const entryAssets = [];
2943
+ const loadedSharedJsAssets = new Set();
2944
+ const loadedSharedCssAssets = new Set();
2945
+ const { options } = origin;
2946
+ const { preloadConfig: rootPreloadConfig } = preloadOptions;
2947
+ const { depsRemote } = rootPreloadConfig;
2948
+ const memo = {};
2949
+ traverseModuleInfo(globalSnapshot, remote, (moduleInfoSnapshot, remoteInfo, isRoot) => {
2950
+ let preloadConfig;
2951
+ if (isRoot) {
2952
+ preloadConfig = rootPreloadConfig;
2953
+ }
2954
+ else {
2955
+ if (Array.isArray(depsRemote)) {
2956
+ // eslint-disable-next-line array-callback-return
2957
+ const findPreloadConfig = depsRemote.find((remoteConfig) => {
2958
+ if (remoteConfig.nameOrAlias === remoteInfo.name ||
2959
+ remoteConfig.nameOrAlias === remoteInfo.alias) {
2960
+ return true;
2961
+ }
2962
+ return false;
2963
+ });
2964
+ if (!findPreloadConfig) {
2965
+ return;
2966
+ }
2967
+ preloadConfig = defaultPreloadArgs(findPreloadConfig);
2968
+ }
2969
+ else if (depsRemote === true) {
2970
+ preloadConfig = rootPreloadConfig;
2971
+ }
2972
+ else {
2973
+ return;
2974
+ }
2975
+ }
2976
+ const remoteEntryUrl = sdk.getResourceUrl(moduleInfoSnapshot, getRemoteEntryInfoFromSnapshot(moduleInfoSnapshot).url);
2977
+ if (remoteEntryUrl) {
2978
+ entryAssets.push({
2979
+ name: remoteInfo.name,
2980
+ moduleInfo: {
2981
+ name: remoteInfo.name,
2982
+ entry: remoteEntryUrl,
2983
+ type: 'remoteEntryType' in moduleInfoSnapshot
2984
+ ? moduleInfoSnapshot.remoteEntryType
2985
+ : 'global',
2986
+ entryGlobalName: 'globalName' in moduleInfoSnapshot
2987
+ ? moduleInfoSnapshot.globalName
2988
+ : remoteInfo.name,
2989
+ shareScope: '',
2990
+ version: 'version' in moduleInfoSnapshot
2991
+ ? moduleInfoSnapshot.version
2992
+ : undefined,
2993
+ },
2994
+ url: remoteEntryUrl,
2995
+ });
2996
+ }
2997
+ let moduleAssetsInfo = 'modules' in moduleInfoSnapshot ? moduleInfoSnapshot.modules : [];
2998
+ const normalizedPreloadExposes = normalizePreloadExposes(preloadConfig.exposes);
2999
+ if (normalizedPreloadExposes.length && 'modules' in moduleInfoSnapshot) {
3000
+ moduleAssetsInfo = moduleInfoSnapshot?.modules?.reduce((assets, moduleAssetInfo) => {
3001
+ if (normalizedPreloadExposes?.indexOf(moduleAssetInfo.moduleName) !==
3002
+ -1) {
3003
+ assets.push(moduleAssetInfo);
3004
+ }
3005
+ return assets;
3006
+ }, []);
3007
+ }
3008
+ function handleAssets(assets) {
3009
+ const assetsRes = assets.map((asset) => sdk.getResourceUrl(moduleInfoSnapshot, asset));
3010
+ if (preloadConfig.filter) {
3011
+ return assetsRes.filter(preloadConfig.filter);
3012
+ }
3013
+ return assetsRes;
3014
+ }
3015
+ if (moduleAssetsInfo) {
3016
+ const assetsLength = moduleAssetsInfo.length;
3017
+ for (let index = 0; index < assetsLength; index++) {
3018
+ const assetsInfo = moduleAssetsInfo[index];
3019
+ const exposeFullPath = `${remoteInfo.name}/${assetsInfo.moduleName}`;
3020
+ origin.remoteHandler.hooks.lifecycle.handlePreloadModule.emit({
3021
+ id: assetsInfo.moduleName === '.' ? remoteInfo.name : exposeFullPath,
3022
+ name: remoteInfo.name,
3023
+ remoteSnapshot: moduleInfoSnapshot,
3024
+ preloadConfig,
3025
+ remote: remoteInfo,
3026
+ origin,
3027
+ });
3028
+ const preloaded = getPreloaded(exposeFullPath);
3029
+ if (preloaded) {
3030
+ continue;
3031
+ }
3032
+ if (preloadConfig.resourceCategory === 'all') {
3033
+ cssAssets.push(...handleAssets(assetsInfo.assets.css.async));
3034
+ cssAssets.push(...handleAssets(assetsInfo.assets.css.sync));
3035
+ jsAssets.push(...handleAssets(assetsInfo.assets.js.async));
3036
+ jsAssets.push(...handleAssets(assetsInfo.assets.js.sync));
3037
+ // eslint-disable-next-line no-constant-condition
3038
+ }
3039
+ else if ((preloadConfig.resourceCategory = 'sync')) {
3040
+ cssAssets.push(...handleAssets(assetsInfo.assets.css.sync));
3041
+ jsAssets.push(...handleAssets(assetsInfo.assets.js.sync));
3042
+ }
3043
+ setPreloaded(exposeFullPath);
3044
+ }
3045
+ }
3046
+ }, true, memo, remoteSnapshot);
3047
+ if (remoteSnapshot.shared && remoteSnapshot.shared.length > 0) {
3048
+ const collectSharedAssets = (shareInfo, snapshotShared) => {
3049
+ const registeredShared = getRegisteredShare(origin.shareScopeMap, snapshotShared.sharedName, shareInfo, origin.sharedHandler.hooks.lifecycle.resolveShare);
3050
+ // 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.
3051
+ if (registeredShared && typeof registeredShared.lib === 'function') {
3052
+ snapshotShared.assets.js.sync.forEach((asset) => {
3053
+ loadedSharedJsAssets.add(asset);
3054
+ });
3055
+ snapshotShared.assets.css.sync.forEach((asset) => {
3056
+ loadedSharedCssAssets.add(asset);
3057
+ });
3058
+ }
3059
+ };
3060
+ remoteSnapshot.shared.forEach((shared) => {
3061
+ const shareInfos = options.shared?.[shared.sharedName];
3062
+ if (!shareInfos) {
3063
+ return;
3064
+ }
3065
+ // if no version, preload all shared
3066
+ const sharedOptions = shared.version
3067
+ ? shareInfos.find((s) => s.version === shared.version)
3068
+ : shareInfos;
3069
+ if (!sharedOptions) {
3070
+ return;
3071
+ }
3072
+ const arrayShareInfo = arrayOptions(sharedOptions);
3073
+ arrayShareInfo.forEach((s) => {
3074
+ collectSharedAssets(s, shared);
3075
+ });
3076
+ });
3077
+ }
3078
+ const needPreloadJsAssets = jsAssets.filter((asset) => !loadedSharedJsAssets.has(asset) && !isExisted('script', asset));
3079
+ const needPreloadCssAssets = cssAssets.filter((asset) => !loadedSharedCssAssets.has(asset) && !isExisted('link', asset));
3080
+ return {
3081
+ cssAssets: needPreloadCssAssets,
3082
+ jsAssetsWithoutEntry: needPreloadJsAssets,
3083
+ entryAssets: entryAssets.filter((entry) => !isExisted('script', entry.url)),
3084
+ };
3085
+ }
3086
+ const generatePreloadAssetsPlugin = function () {
3087
+ return {
3088
+ name: 'generate-preload-assets-plugin',
3089
+ async generatePreloadAssets(args) {
3090
+ const { origin, preloadOptions, remoteInfo, remote, globalSnapshot, remoteSnapshot, } = args;
3091
+ if (!sdk.isBrowserEnv()) {
3092
+ return {
3093
+ cssAssets: [],
3094
+ jsAssetsWithoutEntry: [],
3095
+ entryAssets: [],
3096
+ };
3097
+ }
3098
+ if (isRemoteInfoWithEntry(remote) && isPureRemoteEntry(remote)) {
3099
+ return {
3100
+ cssAssets: [],
3101
+ jsAssetsWithoutEntry: [],
3102
+ entryAssets: [
3103
+ {
3104
+ name: remote.name,
3105
+ url: remote.entry,
3106
+ moduleInfo: {
3107
+ name: remoteInfo.name,
3108
+ entry: remote.entry,
3109
+ type: remoteInfo.type || 'global',
3110
+ entryGlobalName: '',
3111
+ shareScope: '',
3112
+ },
3113
+ },
3114
+ ],
3115
+ };
3116
+ }
3117
+ assignRemoteInfo(remoteInfo, remoteSnapshot);
3118
+ const assets = generatePreloadAssets(origin, preloadOptions, remoteInfo, globalSnapshot, remoteSnapshot);
3119
+ return assets;
3120
+ },
3121
+ };
3122
+ };
3123
+
3124
+ function getGlobalRemoteInfo(moduleInfo, origin) {
3125
+ const hostGlobalSnapshot = getGlobalSnapshotInfoByModuleInfo({
3126
+ name: origin.name,
3127
+ version: origin.options.version,
3128
+ });
3129
+ // get remote detail info from global
3130
+ const globalRemoteInfo = hostGlobalSnapshot &&
3131
+ 'remotesInfo' in hostGlobalSnapshot &&
3132
+ hostGlobalSnapshot.remotesInfo &&
3133
+ getInfoWithoutType(hostGlobalSnapshot.remotesInfo, moduleInfo.name).value;
3134
+ if (globalRemoteInfo && globalRemoteInfo.matchedVersion) {
3135
+ return {
3136
+ hostGlobalSnapshot,
3137
+ globalSnapshot: getGlobalSnapshot(),
3138
+ remoteSnapshot: getGlobalSnapshotInfoByModuleInfo({
3139
+ name: moduleInfo.name,
3140
+ version: globalRemoteInfo.matchedVersion,
3141
+ }),
3142
+ };
3143
+ }
3144
+ return {
3145
+ hostGlobalSnapshot: undefined,
3146
+ globalSnapshot: getGlobalSnapshot(),
3147
+ remoteSnapshot: getGlobalSnapshotInfoByModuleInfo({
3148
+ name: moduleInfo.name,
3149
+ version: 'version' in moduleInfo ? moduleInfo.version : undefined,
3150
+ }),
3151
+ };
3152
+ }
3153
+ class SnapshotHandler {
3154
+ constructor(HostInstance) {
3155
+ this.loadingHostSnapshot = null;
3156
+ this.manifestCache = new Map();
3157
+ this.hooks = new PluginSystem({
3158
+ beforeLoadRemoteSnapshot: new AsyncHook('beforeLoadRemoteSnapshot'),
3159
+ loadSnapshot: new AsyncWaterfallHook('loadGlobalSnapshot'),
3160
+ loadRemoteSnapshot: new AsyncWaterfallHook('loadRemoteSnapshot'),
3161
+ afterLoadSnapshot: new AsyncWaterfallHook('afterLoadSnapshot'),
3162
+ });
3163
+ this.manifestLoading = Global.__FEDERATION__.__MANIFEST_LOADING__;
3164
+ this.HostInstance = HostInstance;
3165
+ this.loaderHook = HostInstance.loaderHook;
3166
+ }
3167
+ // eslint-disable-next-line max-lines-per-function
3168
+ async loadRemoteSnapshotInfo({ moduleInfo, id, expose, }) {
3169
+ const { options } = this.HostInstance;
3170
+ await this.hooks.lifecycle.beforeLoadRemoteSnapshot.emit({
3171
+ options,
3172
+ moduleInfo,
3173
+ });
3174
+ let hostSnapshot = getGlobalSnapshotInfoByModuleInfo({
3175
+ name: this.HostInstance.options.name,
3176
+ version: this.HostInstance.options.version,
3177
+ });
3178
+ if (!hostSnapshot) {
3179
+ hostSnapshot = {
3180
+ version: this.HostInstance.options.version || '',
3181
+ remoteEntry: '',
3182
+ remotesInfo: {},
3183
+ };
3184
+ addGlobalSnapshot({
3185
+ [this.HostInstance.options.name]: hostSnapshot,
3186
+ });
3187
+ }
3188
+ // 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.
3189
+ // 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.
3190
+ if (hostSnapshot &&
3191
+ 'remotesInfo' in hostSnapshot &&
3192
+ !getInfoWithoutType(hostSnapshot.remotesInfo, moduleInfo.name).value) {
3193
+ if ('version' in moduleInfo || 'entry' in moduleInfo) {
3194
+ hostSnapshot.remotesInfo = {
3195
+ ...hostSnapshot?.remotesInfo,
3196
+ [moduleInfo.name]: {
3197
+ matchedVersion: 'version' in moduleInfo ? moduleInfo.version : moduleInfo.entry,
3198
+ },
3199
+ };
3200
+ }
3201
+ }
3202
+ const { hostGlobalSnapshot, remoteSnapshot, globalSnapshot } = this.getGlobalRemoteInfo(moduleInfo);
3203
+ const { remoteSnapshot: globalRemoteSnapshot, globalSnapshot: globalSnapshotRes, } = await this.hooks.lifecycle.loadSnapshot.emit({
3204
+ options,
3205
+ moduleInfo,
3206
+ hostGlobalSnapshot,
3207
+ remoteSnapshot,
3208
+ globalSnapshot,
3209
+ });
3210
+ let mSnapshot;
3211
+ let gSnapshot;
3212
+ // global snapshot includes manifest or module info includes manifest
3213
+ if (globalRemoteSnapshot) {
3214
+ if (sdk.isManifestProvider(globalRemoteSnapshot)) {
3215
+ const remoteEntry = sdk.isBrowserEnv()
3216
+ ? globalRemoteSnapshot.remoteEntry
3217
+ : globalRemoteSnapshot.ssrRemoteEntry ||
3218
+ globalRemoteSnapshot.remoteEntry ||
3219
+ '';
3220
+ const moduleSnapshot = await this.getManifestJson(remoteEntry, moduleInfo, {});
3221
+ // eslint-disable-next-line @typescript-eslint/no-shadow
3222
+ const globalSnapshotRes = setGlobalSnapshotInfoByModuleInfo({
3223
+ ...moduleInfo,
3224
+ // The global remote may be overridden
3225
+ // Therefore, set the snapshot key to the global address of the actual request
3226
+ entry: remoteEntry,
3227
+ }, moduleSnapshot);
3228
+ mSnapshot = moduleSnapshot;
3229
+ gSnapshot = globalSnapshotRes;
3230
+ }
3231
+ else {
3232
+ const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
3233
+ options: this.HostInstance.options,
3234
+ moduleInfo,
3235
+ remoteSnapshot: globalRemoteSnapshot,
3236
+ from: 'global',
3237
+ });
3238
+ mSnapshot = remoteSnapshotRes;
3239
+ gSnapshot = globalSnapshotRes;
3240
+ }
3241
+ }
3242
+ else {
3243
+ if (isRemoteInfoWithEntry(moduleInfo)) {
3244
+ // get from manifest.json and merge remote info from remote server
3245
+ const moduleSnapshot = await this.getManifestJson(moduleInfo.entry, moduleInfo, {});
3246
+ // eslint-disable-next-line @typescript-eslint/no-shadow
3247
+ const globalSnapshotRes = setGlobalSnapshotInfoByModuleInfo(moduleInfo, moduleSnapshot);
3248
+ const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
3249
+ options: this.HostInstance.options,
3250
+ moduleInfo,
3251
+ remoteSnapshot: moduleSnapshot,
3252
+ from: 'global',
3253
+ });
3254
+ mSnapshot = remoteSnapshotRes;
3255
+ gSnapshot = globalSnapshotRes;
3256
+ }
3257
+ else {
3258
+ error(errorCodes.getShortErrorMsg(errorCodes.RUNTIME_007, errorCodes.runtimeDescMap, {
3259
+ hostName: moduleInfo.name,
3260
+ hostVersion: moduleInfo.version,
3261
+ globalSnapshot: JSON.stringify(globalSnapshotRes),
3262
+ }));
3263
+ }
3264
+ }
3265
+ await this.hooks.lifecycle.afterLoadSnapshot.emit({
3266
+ id,
3267
+ host: this.HostInstance,
3268
+ options,
3269
+ moduleInfo,
3270
+ remoteSnapshot: mSnapshot,
3271
+ });
3272
+ return {
3273
+ remoteSnapshot: mSnapshot,
3274
+ globalSnapshot: gSnapshot,
3275
+ };
3276
+ }
3277
+ getGlobalRemoteInfo(moduleInfo) {
3278
+ return getGlobalRemoteInfo(moduleInfo, this.HostInstance);
3279
+ }
3280
+ async getManifestJson(manifestUrl, moduleInfo, extraOptions) {
3281
+ const getManifest = async () => {
3282
+ let manifestJson = this.manifestCache.get(manifestUrl);
3283
+ if (manifestJson) {
3284
+ return manifestJson;
3285
+ }
3286
+ try {
3287
+ let res = await this.loaderHook.lifecycle.fetch.emit(manifestUrl, {});
3288
+ if (!res || !(res instanceof Response)) {
3289
+ res = await fetch(manifestUrl, {});
3290
+ }
3291
+ manifestJson = (await res.json());
3292
+ }
3293
+ catch (err) {
3294
+ manifestJson =
3295
+ (await this.HostInstance.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({
3296
+ id: manifestUrl,
3297
+ error: err,
3298
+ from: 'runtime',
3299
+ lifecycle: 'afterResolve',
3300
+ origin: this.HostInstance,
3301
+ }));
3302
+ if (!manifestJson) {
3303
+ delete this.manifestLoading[manifestUrl];
3304
+ error(errorCodes.getShortErrorMsg(errorCodes.RUNTIME_003, errorCodes.runtimeDescMap, {
3305
+ manifestUrl,
3306
+ moduleName: moduleInfo.name,
3307
+ hostName: this.HostInstance.options.name,
3308
+ }, `${err}`));
3309
+ }
3310
+ }
3311
+ assert(manifestJson.metaData && manifestJson.exposes && manifestJson.shared, `${manifestUrl} is not a federation manifest`);
3312
+ this.manifestCache.set(manifestUrl, manifestJson);
3313
+ return manifestJson;
3314
+ };
3315
+ const asyncLoadProcess = async () => {
3316
+ const manifestJson = await getManifest();
3317
+ const remoteSnapshot = sdk.generateSnapshotFromManifest(manifestJson, {
3318
+ version: manifestUrl,
3319
+ });
3320
+ const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
3321
+ options: this.HostInstance.options,
3322
+ moduleInfo,
3323
+ manifestJson,
3324
+ remoteSnapshot,
3325
+ manifestUrl,
3326
+ from: 'manifest',
3327
+ });
3328
+ return remoteSnapshotRes;
3329
+ };
3330
+ if (!this.manifestLoading[manifestUrl]) {
3331
+ this.manifestLoading[manifestUrl] = asyncLoadProcess().then((res) => res);
3332
+ }
3333
+ return this.manifestLoading[manifestUrl];
3334
+ }
3335
+ }
3336
+
3337
+ class SharedHandler {
3338
+ constructor(host) {
3339
+ this.hooks = new PluginSystem({
3340
+ afterResolve: new AsyncWaterfallHook('afterResolve'),
3341
+ beforeLoadShare: new AsyncWaterfallHook('beforeLoadShare'),
3342
+ // not used yet
3343
+ loadShare: new AsyncHook(),
3344
+ resolveShare: new SyncWaterfallHook('resolveShare'),
3345
+ // maybe will change, temporarily for internal use only
3346
+ initContainerShareScopeMap: new SyncWaterfallHook('initContainerShareScopeMap'),
3347
+ });
3348
+ this.host = host;
3349
+ this.shareScopeMap = {};
3350
+ this.initTokens = {};
3351
+ this._setGlobalShareScopeMap(host.options);
3352
+ }
3353
+ // register shared in shareScopeMap
3354
+ registerShared(globalOptions, userOptions) {
3355
+ const { shareInfos, shared } = formatShareConfigs(globalOptions, userOptions);
3356
+ const sharedKeys = Object.keys(shareInfos);
3357
+ sharedKeys.forEach((sharedKey) => {
3358
+ const sharedVals = shareInfos[sharedKey];
3359
+ sharedVals.forEach((sharedVal) => {
3360
+ sharedVal.scope.forEach((sc) => {
3361
+ const registeredShared = this.shareScopeMap[sc]?.[sharedKey];
3362
+ if (!registeredShared) {
3363
+ this.setShared({
3364
+ pkgName: sharedKey,
3365
+ lib: sharedVal.lib,
3366
+ get: sharedVal.get,
3367
+ loaded: sharedVal.loaded || Boolean(sharedVal.lib),
3368
+ shared: sharedVal,
3369
+ from: userOptions.name,
3370
+ });
3371
+ }
3372
+ });
3373
+ });
3374
+ });
3375
+ return {
3376
+ shareInfos,
3377
+ shared,
3378
+ };
3379
+ }
3380
+ async loadShare(pkgName, extraOptions) {
3381
+ const { host } = this;
3382
+ // This function performs the following steps:
3383
+ // 1. Checks if the currently loaded share already exists, if not, it throws an error
3384
+ // 2. Searches globally for a matching share, if found, it uses it directly
3385
+ // 3. If not found, it retrieves it from the current share and stores the obtained share globally.
3386
+ const shareOptions = getTargetSharedOptions({
3387
+ pkgName,
3388
+ extraOptions,
3389
+ shareInfos: host.options.shared,
3390
+ });
3391
+ if (shareOptions?.scope) {
3392
+ await Promise.all(shareOptions.scope.map(async (shareScope) => {
3393
+ await Promise.all(this.initializeSharing(shareScope, {
3394
+ strategy: shareOptions.strategy,
3395
+ }));
3396
+ return;
3397
+ }));
3398
+ }
3399
+ const loadShareRes = await this.hooks.lifecycle.beforeLoadShare.emit({
3400
+ pkgName,
3401
+ shareInfo: shareOptions,
3402
+ shared: host.options.shared,
3403
+ origin: host,
3404
+ });
3405
+ const { shareInfo: shareOptionsRes } = loadShareRes;
3406
+ // Assert that shareInfoRes exists, if not, throw an error
3407
+ assert(shareOptionsRes, `Cannot find ${pkgName} Share in the ${host.options.name}. Please ensure that the ${pkgName} Share parameters have been injected`);
3408
+ // Retrieve from cache
3409
+ const registeredShared = getRegisteredShare(this.shareScopeMap, pkgName, shareOptionsRes, this.hooks.lifecycle.resolveShare);
3410
+ const addUseIn = (shared) => {
3411
+ if (!shared.useIn) {
3412
+ shared.useIn = [];
3413
+ }
3414
+ addUniqueItem(shared.useIn, host.options.name);
3415
+ };
3416
+ if (registeredShared && registeredShared.lib) {
3417
+ addUseIn(registeredShared);
3418
+ return registeredShared.lib;
3419
+ }
3420
+ else if (registeredShared &&
3421
+ registeredShared.loading &&
3422
+ !registeredShared.loaded) {
3423
+ const factory = await registeredShared.loading;
3424
+ registeredShared.loaded = true;
3425
+ if (!registeredShared.lib) {
3426
+ registeredShared.lib = factory;
3427
+ }
3428
+ addUseIn(registeredShared);
3429
+ return factory;
3430
+ }
3431
+ else if (registeredShared) {
3432
+ const asyncLoadProcess = async () => {
3433
+ const factory = await registeredShared.get();
3434
+ addUseIn(registeredShared);
3435
+ registeredShared.loaded = true;
3436
+ registeredShared.lib = factory;
3437
+ return factory;
3438
+ };
3439
+ const loading = asyncLoadProcess();
3440
+ this.setShared({
3441
+ pkgName,
3442
+ loaded: false,
3443
+ shared: registeredShared,
3444
+ from: host.options.name,
3445
+ lib: null,
3446
+ loading,
3447
+ });
3448
+ return loading;
3449
+ }
3450
+ else {
3451
+ if (extraOptions?.customShareInfo) {
3452
+ return false;
3453
+ }
3454
+ const asyncLoadProcess = async () => {
3455
+ const factory = await shareOptionsRes.get();
3456
+ shareOptionsRes.lib = factory;
3457
+ shareOptionsRes.loaded = true;
3458
+ addUseIn(shareOptionsRes);
3459
+ const gShared = getRegisteredShare(this.shareScopeMap, pkgName, shareOptionsRes, this.hooks.lifecycle.resolveShare);
3460
+ if (gShared) {
3461
+ gShared.lib = factory;
3462
+ gShared.loaded = true;
3463
+ gShared.from = shareOptionsRes.from;
3464
+ }
3465
+ return factory;
3466
+ };
3467
+ const loading = asyncLoadProcess();
3468
+ this.setShared({
3469
+ pkgName,
3470
+ loaded: false,
3471
+ shared: shareOptionsRes,
3472
+ from: host.options.name,
3473
+ lib: null,
3474
+ loading,
3475
+ });
3476
+ return loading;
3477
+ }
3478
+ }
3479
+ /**
3480
+ * This function initializes the sharing sequence (executed only once per share scope).
3481
+ * It accepts one argument, the name of the share scope.
3482
+ * If the share scope does not exist, it creates one.
3483
+ */
3484
+ // eslint-disable-next-line @typescript-eslint/member-ordering
3485
+ initializeSharing(shareScopeName = DEFAULT_SCOPE, extraOptions) {
3486
+ const { host } = this;
3487
+ const from = extraOptions?.from;
3488
+ const strategy = extraOptions?.strategy;
3489
+ let initScope = extraOptions?.initScope;
3490
+ const promises = [];
3491
+ if (from !== 'build') {
3492
+ const { initTokens } = this;
3493
+ if (!initScope)
3494
+ initScope = [];
3495
+ let initToken = initTokens[shareScopeName];
3496
+ if (!initToken)
3497
+ initToken = initTokens[shareScopeName] = { from: this.host.name };
3498
+ if (initScope.indexOf(initToken) >= 0)
3499
+ return promises;
3500
+ initScope.push(initToken);
3501
+ }
3502
+ const shareScope = this.shareScopeMap;
3503
+ const hostName = host.options.name;
3504
+ // Creates a new share scope if necessary
3505
+ if (!shareScope[shareScopeName]) {
3506
+ shareScope[shareScopeName] = {};
3507
+ }
3508
+ // Executes all initialization snippets from all accessible modules
3509
+ const scope = shareScope[shareScopeName];
3510
+ const register = (name, shared) => {
3511
+ const { version, eager } = shared;
3512
+ scope[name] = scope[name] || {};
3513
+ const versions = scope[name];
3514
+ const activeVersion = versions[version];
3515
+ const activeVersionEager = Boolean(activeVersion &&
3516
+ (activeVersion.eager || activeVersion.shareConfig?.eager));
3517
+ if (!activeVersion ||
3518
+ (activeVersion.strategy !== 'loaded-first' &&
3519
+ !activeVersion.loaded &&
3520
+ (Boolean(!eager) !== !activeVersionEager
3521
+ ? eager
3522
+ : hostName > activeVersion.from))) {
3523
+ versions[version] = shared;
3524
+ }
3525
+ };
3526
+ const initFn = (mod) => mod && mod.init && mod.init(shareScope[shareScopeName], initScope);
3527
+ const initRemoteModule = async (key) => {
3528
+ const { module } = await host.remoteHandler.getRemoteModuleAndOptions({
3529
+ id: key,
3530
+ });
3531
+ if (module.getEntry) {
3532
+ let remoteEntryExports;
3533
+ try {
3534
+ remoteEntryExports = await module.getEntry();
3535
+ }
3536
+ catch (error) {
3537
+ remoteEntryExports =
3538
+ (await host.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({
3539
+ id: key,
3540
+ error,
3541
+ from: 'runtime',
3542
+ lifecycle: 'beforeLoadShare',
3543
+ origin: host,
3544
+ }));
3545
+ }
3546
+ if (!module.inited) {
3547
+ await initFn(remoteEntryExports);
3548
+ module.inited = true;
3549
+ }
3550
+ }
3551
+ };
3552
+ Object.keys(host.options.shared).forEach((shareName) => {
3553
+ const sharedArr = host.options.shared[shareName];
3554
+ sharedArr.forEach((shared) => {
3555
+ if (shared.scope.includes(shareScopeName)) {
3556
+ register(shareName, shared);
3557
+ }
3558
+ });
3559
+ });
3560
+ // TODO: strategy==='version-first' need to be removed in the future
3561
+ if (host.options.shareStrategy === 'version-first' ||
3562
+ strategy === 'version-first') {
3563
+ host.options.remotes.forEach((remote) => {
3564
+ if (remote.shareScope === shareScopeName) {
3565
+ promises.push(initRemoteModule(remote.name));
3566
+ }
3567
+ });
3568
+ }
3569
+ return promises;
3570
+ }
3571
+ // The lib function will only be available if the shared set by eager or runtime init is set or the shared is successfully loaded.
3572
+ // 1. If the loaded shared already exists globally, then it will be reused
3573
+ // 2. If lib exists in local shared, it will be used directly
3574
+ // 3. If the local get returns something other than Promise, then it will be used directly
3575
+ loadShareSync(pkgName, extraOptions) {
3576
+ const { host } = this;
3577
+ const shareOptions = getTargetSharedOptions({
3578
+ pkgName,
3579
+ extraOptions,
3580
+ shareInfos: host.options.shared,
3581
+ });
3582
+ if (shareOptions?.scope) {
3583
+ shareOptions.scope.forEach((shareScope) => {
3584
+ this.initializeSharing(shareScope, { strategy: shareOptions.strategy });
3585
+ });
3586
+ }
3587
+ const registeredShared = getRegisteredShare(this.shareScopeMap, pkgName, shareOptions, this.hooks.lifecycle.resolveShare);
3588
+ const addUseIn = (shared) => {
3589
+ if (!shared.useIn) {
3590
+ shared.useIn = [];
3591
+ }
3592
+ addUniqueItem(shared.useIn, host.options.name);
3593
+ };
3594
+ if (registeredShared) {
3595
+ if (typeof registeredShared.lib === 'function') {
3596
+ addUseIn(registeredShared);
3597
+ if (!registeredShared.loaded) {
3598
+ registeredShared.loaded = true;
3599
+ if (registeredShared.from === host.options.name) {
3600
+ shareOptions.loaded = true;
3601
+ }
3602
+ }
3603
+ return registeredShared.lib;
3604
+ }
3605
+ if (typeof registeredShared.get === 'function') {
3606
+ const module = registeredShared.get();
3607
+ if (!(module instanceof Promise)) {
3608
+ addUseIn(registeredShared);
3609
+ this.setShared({
3610
+ pkgName,
3611
+ loaded: true,
3612
+ from: host.options.name,
3613
+ lib: module,
3614
+ shared: registeredShared,
3615
+ });
3616
+ return module;
3617
+ }
3618
+ }
3619
+ }
3620
+ if (shareOptions.lib) {
3621
+ if (!shareOptions.loaded) {
3622
+ shareOptions.loaded = true;
3623
+ }
3624
+ return shareOptions.lib;
3625
+ }
3626
+ if (shareOptions.get) {
3627
+ const module = shareOptions.get();
3628
+ if (module instanceof Promise) {
3629
+ const errorCode = extraOptions?.from === 'build' ? errorCodes.RUNTIME_005 : errorCodes.RUNTIME_006;
3630
+ throw new Error(errorCodes.getShortErrorMsg(errorCode, errorCodes.runtimeDescMap, {
3631
+ hostName: host.options.name,
3632
+ sharedPkgName: pkgName,
3633
+ }));
3634
+ }
3635
+ shareOptions.lib = module;
3636
+ this.setShared({
3637
+ pkgName,
3638
+ loaded: true,
3639
+ from: host.options.name,
3640
+ lib: shareOptions.lib,
3641
+ shared: shareOptions,
3642
+ });
3643
+ return shareOptions.lib;
3644
+ }
3645
+ throw new Error(errorCodes.getShortErrorMsg(errorCodes.RUNTIME_006, errorCodes.runtimeDescMap, {
3646
+ hostName: host.options.name,
3647
+ sharedPkgName: pkgName,
3648
+ }));
3649
+ }
3650
+ initShareScopeMap(scopeName, shareScope, extraOptions = {}) {
3651
+ const { host } = this;
3652
+ this.shareScopeMap[scopeName] = shareScope;
3653
+ this.hooks.lifecycle.initContainerShareScopeMap.emit({
3654
+ shareScope,
3655
+ options: host.options,
3656
+ origin: host,
3657
+ scopeName,
3658
+ hostShareScopeMap: extraOptions.hostShareScopeMap,
3659
+ });
3660
+ }
3661
+ setShared({ pkgName, shared, from, lib, loading, loaded, get, }) {
3662
+ const { version, scope = 'default', ...shareInfo } = shared;
3663
+ const scopes = Array.isArray(scope) ? scope : [scope];
3664
+ scopes.forEach((sc) => {
3665
+ if (!this.shareScopeMap[sc]) {
3666
+ this.shareScopeMap[sc] = {};
3667
+ }
3668
+ if (!this.shareScopeMap[sc][pkgName]) {
3669
+ this.shareScopeMap[sc][pkgName] = {};
3670
+ }
3671
+ if (!this.shareScopeMap[sc][pkgName][version]) {
3672
+ this.shareScopeMap[sc][pkgName][version] = {
3673
+ version,
3674
+ scope: [sc],
3675
+ ...shareInfo,
3676
+ lib,
3677
+ loaded,
3678
+ loading,
3679
+ };
3680
+ if (get) {
3681
+ this.shareScopeMap[sc][pkgName][version].get = get;
3682
+ }
3683
+ return;
3684
+ }
3685
+ const registeredShared = this.shareScopeMap[sc][pkgName][version];
3686
+ if (loading && !registeredShared.loading) {
3687
+ registeredShared.loading = loading;
3688
+ }
3689
+ if (loaded && !registeredShared.loaded) {
3690
+ registeredShared.loaded = loaded;
3691
+ }
3692
+ if (from && registeredShared.from !== from) {
3693
+ registeredShared.from = from;
3694
+ }
3695
+ });
3696
+ }
3697
+ _setGlobalShareScopeMap(hostOptions) {
3698
+ const globalShareScopeMap = getGlobalShareScope();
3699
+ const identifier = hostOptions.id || hostOptions.name;
3700
+ if (identifier && !globalShareScopeMap[identifier]) {
3701
+ globalShareScopeMap[identifier] = this.shareScopeMap;
3702
+ }
3703
+ }
3704
+ }
3705
+
3706
+ class RemoteHandler {
3707
+ constructor(host) {
3708
+ this.hooks = new PluginSystem({
3709
+ beforeRegisterRemote: new SyncWaterfallHook('beforeRegisterRemote'),
3710
+ registerRemote: new SyncWaterfallHook('registerRemote'),
3711
+ beforeRequest: new AsyncWaterfallHook('beforeRequest'),
3712
+ onLoad: new AsyncHook('onLoad'),
3713
+ handlePreloadModule: new SyncHook('handlePreloadModule'),
3714
+ errorLoadRemote: new AsyncHook('errorLoadRemote'),
3715
+ beforePreloadRemote: new AsyncHook('beforePreloadRemote'),
3716
+ generatePreloadAssets: new AsyncHook('generatePreloadAssets'),
3717
+ // not used yet
3718
+ afterPreloadRemote: new AsyncHook(),
3719
+ loadEntry: new AsyncHook(),
3720
+ });
3721
+ this.host = host;
3722
+ this.idToRemoteMap = {};
3723
+ }
3724
+ formatAndRegisterRemote(globalOptions, userOptions) {
3725
+ const userRemotes = userOptions.remotes || [];
3726
+ return userRemotes.reduce((res, remote) => {
3727
+ this.registerRemote(remote, res, { force: false });
3728
+ return res;
3729
+ }, globalOptions.remotes);
3730
+ }
3731
+ setIdToRemoteMap(id, remoteMatchInfo) {
3732
+ const { remote, expose } = remoteMatchInfo;
3733
+ const { name, alias } = remote;
3734
+ this.idToRemoteMap[id] = { name: remote.name, expose };
3735
+ if (alias && id.startsWith(name)) {
3736
+ const idWithAlias = id.replace(name, alias);
3737
+ this.idToRemoteMap[idWithAlias] = { name: remote.name, expose };
3738
+ return;
3739
+ }
3740
+ if (alias && id.startsWith(alias)) {
3741
+ const idWithName = id.replace(alias, name);
3742
+ this.idToRemoteMap[idWithName] = { name: remote.name, expose };
3743
+ }
3744
+ }
3745
+ // eslint-disable-next-line max-lines-per-function
3746
+ // eslint-disable-next-line @typescript-eslint/member-ordering
3747
+ async loadRemote(id, options) {
3748
+ const { host } = this;
3749
+ try {
3750
+ const { loadFactory = true } = options || {
3751
+ loadFactory: true,
3752
+ };
3753
+ // 1. Validate the parameters of the retrieved module. There are two module request methods: pkgName + expose and alias + expose.
3754
+ // 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.
3755
+ // 3. Retrieve the detailed information of the current module from global (remoteEntry address, expose resource address)
3756
+ // 4. After retrieving remoteEntry, call the init of the module, and then retrieve the exported content of the module through get
3757
+ // id: pkgName(@federation/app1) + expose(button) = @federation/app1/button
3758
+ // id: alias(app1) + expose(button) = app1/button
3759
+ // id: alias(app1/utils) + expose(loadash/sort) = app1/utils/loadash/sort
3760
+ const { module, moduleOptions, remoteMatchInfo } = await this.getRemoteModuleAndOptions({
3761
+ id,
3762
+ });
3763
+ const { pkgNameOrAlias, remote, expose, id: idRes, remoteSnapshot, } = remoteMatchInfo;
3764
+ const moduleOrFactory = (await module.get(idRes, expose, options, remoteSnapshot));
3765
+ const moduleWrapper = await this.hooks.lifecycle.onLoad.emit({
3766
+ id: idRes,
3767
+ pkgNameOrAlias,
3768
+ expose,
3769
+ exposeModule: loadFactory ? moduleOrFactory : undefined,
3770
+ exposeModuleFactory: loadFactory ? undefined : moduleOrFactory,
3771
+ remote,
3772
+ options: moduleOptions,
3773
+ moduleInstance: module,
3774
+ origin: host,
3775
+ });
3776
+ this.setIdToRemoteMap(id, remoteMatchInfo);
3777
+ if (typeof moduleWrapper === 'function') {
3778
+ return moduleWrapper;
3779
+ }
3780
+ return moduleOrFactory;
3781
+ }
3782
+ catch (error) {
3783
+ const { from = 'runtime' } = options || { from: 'runtime' };
3784
+ const failOver = await this.hooks.lifecycle.errorLoadRemote.emit({
3785
+ id,
3786
+ error,
3787
+ from,
3788
+ lifecycle: 'onLoad',
3789
+ origin: host,
3790
+ });
3791
+ if (!failOver) {
3792
+ throw error;
3793
+ }
3794
+ return failOver;
3795
+ }
3796
+ }
3797
+ // eslint-disable-next-line @typescript-eslint/member-ordering
3798
+ async preloadRemote(preloadOptions) {
3799
+ const { host } = this;
3800
+ await this.hooks.lifecycle.beforePreloadRemote.emit({
3801
+ preloadOps: preloadOptions,
3802
+ options: host.options,
3803
+ origin: host,
3804
+ });
3805
+ const preloadOps = formatPreloadArgs(host.options.remotes, preloadOptions);
3806
+ await Promise.all(preloadOps.map(async (ops) => {
3807
+ const { remote } = ops;
3808
+ const remoteInfo = getRemoteInfo(remote);
3809
+ const { globalSnapshot, remoteSnapshot } = await host.snapshotHandler.loadRemoteSnapshotInfo({
3810
+ moduleInfo: remote,
3811
+ });
3812
+ const assets = await this.hooks.lifecycle.generatePreloadAssets.emit({
3813
+ origin: host,
3814
+ preloadOptions: ops,
3815
+ remote,
3816
+ remoteInfo,
3817
+ globalSnapshot,
3818
+ remoteSnapshot,
3819
+ });
3820
+ if (!assets) {
3821
+ return;
3822
+ }
3823
+ preloadAssets(remoteInfo, host, assets);
3824
+ }));
3825
+ }
3826
+ registerRemotes(remotes, options) {
3827
+ const { host } = this;
3828
+ remotes.forEach((remote) => {
3829
+ this.registerRemote(remote, host.options.remotes, {
3830
+ force: options?.force,
3831
+ });
3832
+ });
3833
+ }
3834
+ async getRemoteModuleAndOptions(options) {
3835
+ const { host } = this;
3836
+ const { id } = options;
3837
+ let loadRemoteArgs;
3838
+ try {
3839
+ loadRemoteArgs = await this.hooks.lifecycle.beforeRequest.emit({
3840
+ id,
3841
+ options: host.options,
3842
+ origin: host,
3843
+ });
3844
+ }
3845
+ catch (error) {
3846
+ loadRemoteArgs = (await this.hooks.lifecycle.errorLoadRemote.emit({
3847
+ id,
3848
+ options: host.options,
3849
+ origin: host,
3850
+ from: 'runtime',
3851
+ error,
3852
+ lifecycle: 'beforeRequest',
3853
+ }));
3854
+ if (!loadRemoteArgs) {
3855
+ throw error;
3856
+ }
3857
+ }
3858
+ const { id: idRes } = loadRemoteArgs;
3859
+ const remoteSplitInfo = matchRemoteWithNameAndExpose(host.options.remotes, idRes);
3860
+ assert(remoteSplitInfo, errorCodes.getShortErrorMsg(errorCodes.RUNTIME_004, errorCodes.runtimeDescMap, {
3861
+ hostName: host.options.name,
3862
+ requestId: idRes,
3863
+ }));
3864
+ const { remote: rawRemote } = remoteSplitInfo;
3865
+ const remoteInfo = getRemoteInfo(rawRemote);
3866
+ const matchInfo = await host.sharedHandler.hooks.lifecycle.afterResolve.emit({
3867
+ id: idRes,
3868
+ ...remoteSplitInfo,
3869
+ options: host.options,
3870
+ origin: host,
3871
+ remoteInfo,
3872
+ });
3873
+ const { remote, expose } = matchInfo;
3874
+ assert(remote && expose, `The 'beforeRequest' hook was executed, but it failed to return the correct 'remote' and 'expose' values while loading ${idRes}.`);
3875
+ let module = host.moduleCache.get(remote.name);
3876
+ const moduleOptions = {
3877
+ host: host,
3878
+ remoteInfo,
3879
+ };
3880
+ if (!module) {
3881
+ module = new Module(moduleOptions);
3882
+ host.moduleCache.set(remote.name, module);
3883
+ }
3884
+ return {
3885
+ module,
3886
+ moduleOptions,
3887
+ remoteMatchInfo: matchInfo,
3888
+ };
3889
+ }
3890
+ registerRemote(remote, targetRemotes, options) {
3891
+ const { host } = this;
3892
+ const normalizeRemote = () => {
3893
+ if (remote.alias) {
3894
+ // Validate if alias equals the prefix of remote.name and remote.alias, if so, throw an error
3895
+ // As multi-level path references cannot guarantee unique names, alias being a prefix of remote.name is not supported
3896
+ const findEqual = targetRemotes.find((item) => remote.alias &&
3897
+ (item.name.startsWith(remote.alias) ||
3898
+ item.alias?.startsWith(remote.alias)));
3899
+ assert(!findEqual, `The alias ${remote.alias} of remote ${remote.name} is not allowed to be the prefix of ${findEqual && findEqual.name} name or alias`);
3900
+ }
3901
+ // Set the remote entry to a complete path
3902
+ if ('entry' in remote) {
3903
+ if (sdk.isBrowserEnv() && !remote.entry.startsWith('http')) {
3904
+ remote.entry = new URL(remote.entry, window.location.origin).href;
3905
+ }
3906
+ }
3907
+ if (!remote.shareScope) {
3908
+ remote.shareScope = DEFAULT_SCOPE;
3909
+ }
3910
+ if (!remote.type) {
3911
+ remote.type = DEFAULT_REMOTE_TYPE;
3912
+ }
3913
+ };
3914
+ this.hooks.lifecycle.beforeRegisterRemote.emit({ remote, origin: host });
3915
+ const registeredRemote = targetRemotes.find((item) => item.name === remote.name);
3916
+ if (!registeredRemote) {
3917
+ normalizeRemote();
3918
+ targetRemotes.push(remote);
3919
+ this.hooks.lifecycle.registerRemote.emit({ remote, origin: host });
3920
+ }
3921
+ else {
3922
+ const messages = [
3923
+ `The remote "${remote.name}" is already registered.`,
3924
+ 'Please note that overriding it may cause unexpected errors.',
3925
+ ];
3926
+ if (options?.force) {
3927
+ // remove registered remote
3928
+ this.removeRemote(registeredRemote);
3929
+ normalizeRemote();
3930
+ targetRemotes.push(remote);
3931
+ this.hooks.lifecycle.registerRemote.emit({ remote, origin: host });
3932
+ sdk.warn(messages.join(' '));
3933
+ }
3934
+ }
3935
+ }
3936
+ removeRemote(remote) {
3937
+ try {
3938
+ const { host } = this;
3939
+ const { name } = remote;
3940
+ const remoteIndex = host.options.remotes.findIndex((item) => item.name === name);
3941
+ if (remoteIndex !== -1) {
3942
+ host.options.remotes.splice(remoteIndex, 1);
3943
+ }
3944
+ const loadedModule = host.moduleCache.get(remote.name);
3945
+ if (loadedModule) {
3946
+ const remoteInfo = loadedModule.remoteInfo;
3947
+ const key = remoteInfo.entryGlobalName;
3948
+ if (CurrentGlobal[key]) {
3949
+ if (Object.getOwnPropertyDescriptor(CurrentGlobal, key)?.configurable) {
3950
+ delete CurrentGlobal[key];
3951
+ }
3952
+ else {
3953
+ // @ts-ignore
3954
+ CurrentGlobal[key] = undefined;
3955
+ }
3956
+ }
3957
+ const remoteEntryUniqueKey = getRemoteEntryUniqueKey(loadedModule.remoteInfo);
3958
+ if (globalLoading[remoteEntryUniqueKey]) {
3959
+ delete globalLoading[remoteEntryUniqueKey];
3960
+ }
3961
+ host.snapshotHandler.manifestCache.delete(remoteInfo.entry);
3962
+ // delete unloaded shared and instance
3963
+ let remoteInsId = remoteInfo.buildVersion
3964
+ ? sdk.composeKeyWithSeparator(remoteInfo.name, remoteInfo.buildVersion)
3965
+ : remoteInfo.name;
3966
+ const remoteInsIndex = CurrentGlobal.__FEDERATION__.__INSTANCES__.findIndex((ins) => {
3967
+ if (remoteInfo.buildVersion) {
3968
+ return ins.options.id === remoteInsId;
3969
+ }
3970
+ else {
3971
+ return ins.name === remoteInsId;
3972
+ }
3973
+ });
3974
+ if (remoteInsIndex !== -1) {
3975
+ const remoteIns = CurrentGlobal.__FEDERATION__.__INSTANCES__[remoteInsIndex];
3976
+ remoteInsId = remoteIns.options.id || remoteInsId;
3977
+ const globalShareScopeMap = getGlobalShareScope();
3978
+ let isAllSharedNotUsed = true;
3979
+ const needDeleteKeys = [];
3980
+ Object.keys(globalShareScopeMap).forEach((instId) => {
3981
+ const shareScopeMap = globalShareScopeMap[instId];
3982
+ shareScopeMap &&
3983
+ Object.keys(shareScopeMap).forEach((shareScope) => {
3984
+ const shareScopeVal = shareScopeMap[shareScope];
3985
+ shareScopeVal &&
3986
+ Object.keys(shareScopeVal).forEach((shareName) => {
3987
+ const sharedPkgs = shareScopeVal[shareName];
3988
+ sharedPkgs &&
3989
+ Object.keys(sharedPkgs).forEach((shareVersion) => {
3990
+ const shared = sharedPkgs[shareVersion];
3991
+ if (shared &&
3992
+ typeof shared === 'object' &&
3993
+ shared.from === remoteInfo.name) {
3994
+ if (shared.loaded || shared.loading) {
3995
+ shared.useIn = shared.useIn.filter((usedHostName) => usedHostName !== remoteInfo.name);
3996
+ if (shared.useIn.length) {
3997
+ isAllSharedNotUsed = false;
3998
+ }
3999
+ else {
4000
+ needDeleteKeys.push([
4001
+ instId,
4002
+ shareScope,
4003
+ shareName,
4004
+ shareVersion,
4005
+ ]);
4006
+ }
4007
+ }
4008
+ else {
4009
+ needDeleteKeys.push([
4010
+ instId,
4011
+ shareScope,
4012
+ shareName,
4013
+ shareVersion,
4014
+ ]);
4015
+ }
4016
+ }
4017
+ });
4018
+ });
4019
+ });
4020
+ });
4021
+ if (isAllSharedNotUsed) {
4022
+ remoteIns.shareScopeMap = {};
4023
+ delete globalShareScopeMap[remoteInsId];
4024
+ }
4025
+ needDeleteKeys.forEach(([insId, shareScope, shareName, shareVersion]) => {
4026
+ delete globalShareScopeMap[insId]?.[shareScope]?.[shareName]?.[shareVersion];
4027
+ });
4028
+ CurrentGlobal.__FEDERATION__.__INSTANCES__.splice(remoteInsIndex, 1);
4029
+ }
4030
+ const { hostGlobalSnapshot } = getGlobalRemoteInfo(remote, host);
4031
+ if (hostGlobalSnapshot) {
4032
+ const remoteKey = hostGlobalSnapshot &&
4033
+ 'remotesInfo' in hostGlobalSnapshot &&
4034
+ hostGlobalSnapshot.remotesInfo &&
4035
+ getInfoWithoutType(hostGlobalSnapshot.remotesInfo, remote.name).key;
4036
+ if (remoteKey) {
4037
+ delete hostGlobalSnapshot.remotesInfo[remoteKey];
4038
+ if (
4039
+ //eslint-disable-next-line no-extra-boolean-cast
4040
+ Boolean(Global.__FEDERATION__.__MANIFEST_LOADING__[remoteKey])) {
4041
+ delete Global.__FEDERATION__.__MANIFEST_LOADING__[remoteKey];
4042
+ }
4043
+ }
4044
+ }
4045
+ host.moduleCache.delete(remote.name);
4046
+ }
4047
+ }
4048
+ catch (err) {
4049
+ logger.log('removeRemote fail: ', err);
4050
+ }
4051
+ }
4052
+ }
4053
+
4054
+ const USE_SNAPSHOT = typeof FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN === 'boolean'
4055
+ ? !FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN
4056
+ : true; // Default to true (use snapshot) when not explicitly defined
4057
+ class ModuleFederation {
4058
+ constructor(userOptions) {
4059
+ this.hooks = new PluginSystem({
4060
+ beforeInit: new SyncWaterfallHook('beforeInit'),
4061
+ init: new SyncHook(),
4062
+ // maybe will change, temporarily for internal use only
4063
+ beforeInitContainer: new AsyncWaterfallHook('beforeInitContainer'),
4064
+ // maybe will change, temporarily for internal use only
4065
+ initContainer: new AsyncWaterfallHook('initContainer'),
4066
+ });
4067
+ this.version = "0.21.6";
4068
+ this.moduleCache = new Map();
4069
+ this.loaderHook = new PluginSystem({
4070
+ // FIXME: may not be suitable , not open to the public yet
4071
+ getModuleInfo: new SyncHook(),
4072
+ createScript: new SyncHook(),
4073
+ createLink: new SyncHook(),
4074
+ fetch: new AsyncHook(),
4075
+ loadEntryError: new AsyncHook(),
4076
+ getModuleFactory: new AsyncHook(),
4077
+ });
4078
+ this.bridgeHook = new PluginSystem({
4079
+ beforeBridgeRender: new SyncHook(),
4080
+ afterBridgeRender: new SyncHook(),
4081
+ beforeBridgeDestroy: new SyncHook(),
4082
+ afterBridgeDestroy: new SyncHook(),
4083
+ });
4084
+ const plugins = USE_SNAPSHOT
4085
+ ? [snapshotPlugin(), generatePreloadAssetsPlugin()]
4086
+ : [];
4087
+ // TODO: Validate the details of the options
4088
+ // Initialize options with default values
4089
+ const defaultOptions = {
4090
+ id: getBuilderId$1(),
4091
+ name: userOptions.name,
4092
+ plugins,
4093
+ remotes: [],
4094
+ shared: {},
4095
+ inBrowser: sdk.isBrowserEnv(),
4096
+ };
4097
+ this.name = userOptions.name;
4098
+ this.options = defaultOptions;
4099
+ this.snapshotHandler = new SnapshotHandler(this);
4100
+ this.sharedHandler = new SharedHandler(this);
4101
+ this.remoteHandler = new RemoteHandler(this);
4102
+ this.shareScopeMap = this.sharedHandler.shareScopeMap;
4103
+ this.registerPlugins([
4104
+ ...defaultOptions.plugins,
4105
+ ...(userOptions.plugins || []),
4106
+ ]);
4107
+ this.options = this.formatOptions(defaultOptions, userOptions);
4108
+ }
4109
+ initOptions(userOptions) {
4110
+ this.registerPlugins(userOptions.plugins);
4111
+ const options = this.formatOptions(this.options, userOptions);
4112
+ this.options = options;
4113
+ return options;
4114
+ }
4115
+ async loadShare(pkgName, extraOptions) {
4116
+ return this.sharedHandler.loadShare(pkgName, extraOptions);
4117
+ }
4118
+ // The lib function will only be available if the shared set by eager or runtime init is set or the shared is successfully loaded.
4119
+ // 1. If the loaded shared already exists globally, then it will be reused
4120
+ // 2. If lib exists in local shared, it will be used directly
4121
+ // 3. If the local get returns something other than Promise, then it will be used directly
4122
+ loadShareSync(pkgName, extraOptions) {
4123
+ return this.sharedHandler.loadShareSync(pkgName, extraOptions);
4124
+ }
4125
+ initializeSharing(shareScopeName = DEFAULT_SCOPE, extraOptions) {
4126
+ return this.sharedHandler.initializeSharing(shareScopeName, extraOptions);
4127
+ }
4128
+ initRawContainer(name, url, container) {
4129
+ const remoteInfo = getRemoteInfo({ name, entry: url });
4130
+ const module = new Module({ host: this, remoteInfo });
4131
+ module.remoteEntryExports = container;
4132
+ this.moduleCache.set(name, module);
4133
+ return module;
4134
+ }
4135
+ // eslint-disable-next-line max-lines-per-function
4136
+ // eslint-disable-next-line @typescript-eslint/member-ordering
4137
+ async loadRemote(id, options) {
4138
+ return this.remoteHandler.loadRemote(id, options);
4139
+ }
4140
+ // eslint-disable-next-line @typescript-eslint/member-ordering
4141
+ async preloadRemote(preloadOptions) {
4142
+ return this.remoteHandler.preloadRemote(preloadOptions);
4143
+ }
4144
+ initShareScopeMap(scopeName, shareScope, extraOptions = {}) {
4145
+ this.sharedHandler.initShareScopeMap(scopeName, shareScope, extraOptions);
4146
+ }
4147
+ formatOptions(globalOptions, userOptions) {
4148
+ const { shared } = formatShareConfigs(globalOptions, userOptions);
4149
+ const { userOptions: userOptionsRes, options: globalOptionsRes } = this.hooks.lifecycle.beforeInit.emit({
4150
+ origin: this,
4151
+ userOptions,
4152
+ options: globalOptions,
4153
+ shareInfo: shared,
4154
+ });
4155
+ const remotes = this.remoteHandler.formatAndRegisterRemote(globalOptionsRes, userOptionsRes);
4156
+ const { shared: handledShared } = this.sharedHandler.registerShared(globalOptionsRes, userOptionsRes);
4157
+ const plugins = [...globalOptionsRes.plugins];
4158
+ if (userOptionsRes.plugins) {
4159
+ userOptionsRes.plugins.forEach((plugin) => {
4160
+ if (!plugins.includes(plugin)) {
4161
+ plugins.push(plugin);
4162
+ }
4163
+ });
4164
+ }
4165
+ const optionsRes = {
4166
+ ...globalOptions,
4167
+ ...userOptions,
4168
+ plugins,
4169
+ remotes,
4170
+ shared: handledShared,
4171
+ };
4172
+ this.hooks.lifecycle.init.emit({
4173
+ origin: this,
4174
+ options: optionsRes,
4175
+ });
4176
+ return optionsRes;
4177
+ }
4178
+ registerPlugins(plugins) {
4179
+ const pluginRes = registerPlugins(plugins, this);
4180
+ // Merge plugin
4181
+ this.options.plugins = this.options.plugins.reduce((res, plugin) => {
4182
+ if (!plugin)
4183
+ return res;
4184
+ if (res && !res.find((item) => item.name === plugin.name)) {
4185
+ res.push(plugin);
4186
+ }
4187
+ return res;
4188
+ }, pluginRes || []);
4189
+ }
4190
+ registerRemotes(remotes, options) {
4191
+ return this.remoteHandler.registerRemotes(remotes, options);
4192
+ }
4193
+ registerShared(shared) {
4194
+ this.sharedHandler.registerShared(this.options, {
4195
+ ...this.options,
4196
+ shared,
4197
+ });
4198
+ }
4199
+ }
4200
+
4201
+ var index = /*#__PURE__*/Object.freeze({
4202
+ __proto__: null
4203
+ });
4204
+
4205
+ index_cjs$2.loadScript = sdk.loadScript;
4206
+ index_cjs$2.loadScriptNode = sdk.loadScriptNode;
4207
+ index_cjs$2.CurrentGlobal = CurrentGlobal;
4208
+ index_cjs$2.Global = Global;
4209
+ index_cjs$2.Module = Module;
4210
+ index_cjs$2.ModuleFederation = ModuleFederation;
4211
+ index_cjs$2.addGlobalSnapshot = addGlobalSnapshot;
4212
+ index_cjs$2.assert = assert;
4213
+ index_cjs$2.getGlobalFederationConstructor = getGlobalFederationConstructor;
4214
+ index_cjs$2.getGlobalSnapshot = getGlobalSnapshot;
4215
+ index_cjs$2.getInfoWithoutType = getInfoWithoutType;
4216
+ index_cjs$2.getRegisteredShare = getRegisteredShare;
4217
+ index_cjs$2.getRemoteEntry = getRemoteEntry;
4218
+ index_cjs$2.getRemoteInfo = getRemoteInfo;
4219
+ index_cjs$2.helpers = helpers;
4220
+ index_cjs$2.isStaticResourcesEqual = isStaticResourcesEqual;
4221
+ index_cjs$2.matchRemoteWithNameAndExpose = matchRemoteWithNameAndExpose;
4222
+ index_cjs$2.registerGlobalPlugins = registerGlobalPlugins;
4223
+ index_cjs$2.resetFederationGlobalInfo = resetFederationGlobalInfo;
4224
+ index_cjs$2.safeWrapper = safeWrapper;
4225
+ index_cjs$2.satisfy = satisfy;
4226
+ index_cjs$2.setGlobalFederationConstructor = setGlobalFederationConstructor;
4227
+ index_cjs$2.setGlobalFederationInstance = setGlobalFederationInstance;
4228
+ index_cjs$2.types = index;
4229
+
4230
+ var utils_cjs = {};
4231
+
4232
+ var runtimeCore$1 = index_cjs$2;
4233
+
4234
+ // injected by bundler, so it can not use runtime-core stuff
4235
+ function getBuilderId() {
4236
+ //@ts-ignore
4237
+ return typeof FEDERATION_BUILD_IDENTIFIER !== 'undefined'
4238
+ ? //@ts-ignore
4239
+ FEDERATION_BUILD_IDENTIFIER
4240
+ : '';
4241
+ }
4242
+ function getGlobalFederationInstance(name, version) {
4243
+ const buildId = getBuilderId();
4244
+ return runtimeCore$1.CurrentGlobal.__FEDERATION__.__INSTANCES__.find((GMInstance) => {
4245
+ if (buildId && GMInstance.options.id === buildId) {
4246
+ return true;
4247
+ }
4248
+ if (GMInstance.options.name === name &&
4249
+ !GMInstance.options.version &&
4250
+ !version) {
4251
+ return true;
4252
+ }
4253
+ if (GMInstance.options.name === name &&
4254
+ version &&
4255
+ GMInstance.options.version === version) {
4256
+ return true;
4257
+ }
4258
+ return false;
4259
+ });
4260
+ }
4261
+
4262
+ utils_cjs.getGlobalFederationInstance = getGlobalFederationInstance;
4263
+
4264
+ var runtimeCore = index_cjs$2;
4265
+ var utils = utils_cjs;
4266
+
4267
+ function createInstance(options) {
4268
+ // Retrieve debug constructor
4269
+ const ModuleFederationConstructor = runtimeCore.getGlobalFederationConstructor() || runtimeCore.ModuleFederation;
4270
+ const instance = new ModuleFederationConstructor(options);
4271
+ runtimeCore.setGlobalFederationInstance(instance);
4272
+ return instance;
4273
+ }
4274
+ let FederationInstance = null;
4275
+ /**
4276
+ * @deprecated Use createInstance or getInstance instead
4277
+ */
4278
+ function init$1(options) {
4279
+ // Retrieve the same instance with the same name
4280
+ const instance = utils.getGlobalFederationInstance(options.name, options.version);
4281
+ if (!instance) {
4282
+ FederationInstance = createInstance(options);
4283
+ return FederationInstance;
4284
+ }
4285
+ else {
4286
+ // Merge options
4287
+ instance.initOptions(options);
4288
+ if (!FederationInstance) {
4289
+ FederationInstance = instance;
4290
+ }
4291
+ return instance;
4292
+ }
4293
+ }
4294
+ // Inject for debug
4295
+ runtimeCore.setGlobalFederationConstructor(runtimeCore.ModuleFederation);
4296
+
4297
+ runtimeCore.Module;
4298
+ runtimeCore.ModuleFederation;
4299
+ runtimeCore.getRemoteEntry;
4300
+ runtimeCore.getRemoteInfo;
4301
+ runtimeCore.loadScript;
4302
+ runtimeCore.loadScriptNode;
4303
+ runtimeCore.registerGlobalPlugins;
4304
+ var init_1 = init$1;
4305
+
4306
+ const importMap = {
4307
+
4308
+ "react": async () => {
4309
+ let pkg = await __vitePreload(() => import('./assets/index-VBwl8x_k.js').then(n => n.i),true?__vite__mapDeps([0,1]):void 0);
4310
+ return pkg;
4311
+ }
4312
+ ,
4313
+ "react-dom": async () => {
4314
+ let pkg = await __vitePreload(() => import('./assets/index-B3WVNJTz.js').then(n => n.i),true?__vite__mapDeps([2,1,3,4]):void 0);
4315
+ return pkg;
4316
+ }
4317
+
4318
+ };
4319
+ const usedShared = {
4320
+
4321
+ "react": {
4322
+ name: "react",
4323
+ version: "18.3.1",
4324
+ scope: ["default"],
4325
+ loaded: false,
4326
+ from: "UtilityMonitor",
4327
+ async get () {
4328
+ usedShared["react"].loaded = true;
4329
+ const {"react": pkgDynamicImport} = importMap;
4330
+ const res = await pkgDynamicImport();
4331
+ const exportModule = {...res};
4332
+ // All npm packages pre-built by vite will be converted to esm
4333
+ Object.defineProperty(exportModule, "__esModule", {
4334
+ value: true,
4335
+ enumerable: false
4336
+ });
4337
+ return function () {
4338
+ return exportModule
4339
+ }
4340
+ },
4341
+ shareConfig: {
4342
+ singleton: true,
4343
+ requiredVersion: "^18.3.1",
4344
+
4345
+ }
4346
+ }
4347
+ ,
4348
+ "react-dom": {
4349
+ name: "react-dom",
4350
+ version: "18.3.1",
4351
+ scope: ["default"],
4352
+ loaded: false,
4353
+ from: "UtilityMonitor",
4354
+ async get () {
4355
+ usedShared["react-dom"].loaded = true;
4356
+ const {"react-dom": pkgDynamicImport} = importMap;
4357
+ const res = await pkgDynamicImport();
4358
+ const exportModule = {...res};
4359
+ // All npm packages pre-built by vite will be converted to esm
4360
+ Object.defineProperty(exportModule, "__esModule", {
4361
+ value: true,
4362
+ enumerable: false
4363
+ });
4364
+ return function () {
4365
+ return exportModule
4366
+ }
4367
+ },
4368
+ shareConfig: {
4369
+ singleton: true,
4370
+ requiredVersion: "^18.3.1",
4371
+
4372
+ }
4373
+ }
4374
+
4375
+ };
4376
+ const usedRemotes = [
4377
+ ];
4378
+
4379
+ const initTokens = {};
4380
+ const shareScopeName = "default";
4381
+ const mfName = "UtilityMonitor";
4382
+ async function init(shared = {}, initScope = []) {
4383
+ const initRes = init_1({
4384
+ name: mfName,
4385
+ remotes: usedRemotes,
4386
+ shared: usedShared,
4387
+ plugins: [],
4388
+ shareStrategy: 'version-first'
4389
+ });
4390
+ // handling circular init calls
4391
+ var initToken = initTokens[shareScopeName];
4392
+ if (!initToken)
4393
+ initToken = initTokens[shareScopeName] = { from: mfName };
4394
+ if (initScope.indexOf(initToken) >= 0) return;
4395
+ initScope.push(initToken);
4396
+ initRes.initShareScopeMap('default', shared);
4397
+ try {
4398
+ await Promise.all(await initRes.initializeSharing('default', {
4399
+ strategy: 'version-first',
4400
+ from: "build",
4401
+ initScope
4402
+ }));
4403
+ } catch (e) {
4404
+ console.error(e);
4405
+ }
4406
+ UtilityMonitor__mf_v__runtimeInit__mf_v__.initResolve(initRes);
4407
+ return initRes
4408
+ }
4409
+
4410
+ function getExposes(moduleName) {
4411
+ if (!(moduleName in exposesMap)) throw new Error(`Module ${moduleName} does not exist in container.`)
4412
+ return (exposesMap[moduleName])().then(res => () => res)
4413
+ }
4414
+
4415
+ export { getExposes as get, init };