@module-federation/bridge-react 0.0.0-next-20241113100451 → 0.0.0-next-20241113115843

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