remote-reload-utils 0.0.8 → 0.0.10

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/main.js CHANGED
@@ -1,4 +1,168 @@
1
1
  import { createInstance } from "@module-federation/enhanced/runtime";
2
+ async function loadReactVersion(version) {
3
+ const runtime = await createInstance({
4
+ name: `react_${version}_runtime`,
5
+ remotes: [
6
+ {
7
+ name: `react@${version}`,
8
+ entry: `https://cdn.jsdelivr.net/npm/react@${version}/umd/react.production.min.js`,
9
+ type: 'var',
10
+ entryGlobalName: 'React'
11
+ },
12
+ {
13
+ name: `react-dom@${version}`,
14
+ entry: `https://cdn.jsdelivr.net/npm/react-dom@${version}/umd/react-dom.production.min.js`,
15
+ type: 'var',
16
+ entryGlobalName: 'ReactDOM'
17
+ }
18
+ ]
19
+ });
20
+ const React = await runtime.loadRemote(`react@${version}`);
21
+ const ReactDOM = await runtime.loadRemote(`react-dom@${version}`);
22
+ return {
23
+ React,
24
+ ReactDOM
25
+ };
26
+ }
27
+ function parseVersion(version) {
28
+ const cleaned = version.replace(/^v/i, '');
29
+ const parts = cleaned.split(/[-+]/);
30
+ const [major, minor, patch] = parts[0].split('.').map(Number);
31
+ return {
32
+ major: isNaN(major) ? 0 : major,
33
+ minor: isNaN(minor) ? 0 : minor,
34
+ patch: isNaN(patch) ? 0 : patch,
35
+ prerelease: parts[1],
36
+ build: parts[2],
37
+ raw: cleaned
38
+ };
39
+ }
40
+ function compareVersions(v1, v2) {
41
+ const p1 = parseVersion(v1);
42
+ const p2 = parseVersion(v2);
43
+ if (p1.major !== p2.major) return p1.major - p2.major;
44
+ if (p1.minor !== p2.minor) return p1.minor - p2.minor;
45
+ if (p1.patch !== p2.patch) return p1.patch - p2.patch;
46
+ if (p1.prerelease && !p2.prerelease) return -1;
47
+ if (!p1.prerelease && p2.prerelease) return 1;
48
+ if (p1.prerelease && p2.prerelease) return p1.prerelease.localeCompare(p2.prerelease);
49
+ return 0;
50
+ }
51
+ function satisfiesVersion(current, required) {
52
+ const opMatch = required.match(/^(>=|<=|>|<|=|~|\^)?/);
53
+ const operator = opMatch?.[1] || '=';
54
+ const version = required.replace(/^(>=|<=|>|<|=|~|\^)/, '');
55
+ const cmp = compareVersions(current, version);
56
+ switch(operator){
57
+ case '>':
58
+ return cmp > 0;
59
+ case '>=':
60
+ return cmp >= 0;
61
+ case '<':
62
+ return cmp < 0;
63
+ case '<=':
64
+ return cmp <= 0;
65
+ case '=':
66
+ case '':
67
+ return 0 === cmp;
68
+ case '^':
69
+ return parseVersion(current).major === parseVersion(version).major && (parseVersion(current).major > 0 || parseVersion(current).minor === parseVersion(version).minor);
70
+ case '~':
71
+ return parseVersion(current).major === parseVersion(version).major && parseVersion(current).minor === parseVersion(version).minor;
72
+ default:
73
+ return 0 === cmp;
74
+ }
75
+ }
76
+ function checkVersionCompatibility(currentVersion, requiredVersion, packageName) {
77
+ const isCompatible = satisfiesVersion(currentVersion, requiredVersion);
78
+ const current = parseVersion(currentVersion);
79
+ const required = parseVersion(requiredVersion);
80
+ let message;
81
+ let suggestion;
82
+ let severity;
83
+ if (isCompatible) {
84
+ message = `${packageName}@${currentVersion} 满足要求 ${requiredVersion}`;
85
+ severity = 'info';
86
+ } else {
87
+ const cmp = compareVersions(currentVersion, requiredVersion);
88
+ if (cmp < 0) {
89
+ message = `${packageName}@${currentVersion} 版本过低,需要 ${requiredVersion}`;
90
+ severity = 'error';
91
+ current.patch;
92
+ current.major, current.minor;
93
+ suggestion = `建议升级到 ${current.major}.${current.minor}.x 或更高版本`;
94
+ } else {
95
+ message = `${packageName}@${currentVersion} 版本过高,需要 ${requiredVersion}`;
96
+ severity = 'warning';
97
+ suggestion = `建议降级到 ${required.major}.${required.minor}.x 或匹配主版本的兼容版本`;
98
+ }
99
+ }
100
+ return {
101
+ compatible: isCompatible,
102
+ currentVersion,
103
+ requiredVersion,
104
+ suggestion,
105
+ severity,
106
+ message
107
+ };
108
+ }
109
+ function findCompatibleVersion(availableVersions, range) {
110
+ let candidates = availableVersions;
111
+ if (range.exact) candidates = candidates.filter((v)=>v === range.exact);
112
+ else {
113
+ if (range.min) candidates = candidates.filter((v)=>compareVersions(v, range.min) >= 0);
114
+ if (range.max) candidates = candidates.filter((v)=>compareVersions(v, range.max) <= 0);
115
+ }
116
+ if (0 === candidates.length) return null;
117
+ return candidates.sort((a, b)=>compareVersions(b, a))[0];
118
+ }
119
+ function getCompatibleReactVersions(hostVersion) {
120
+ const host = parseVersion(hostVersion);
121
+ const versions = [];
122
+ for(let i = host.major; i >= 15; i--)for(let j = 0; j <= 5; j++){
123
+ const version = `${i}.${j}.0`;
124
+ if (checkVersionCompatibility(version, `^${host.major}.0.0`, 'react').compatible) versions.push(version);
125
+ }
126
+ const uniqueVersions = [];
127
+ const seen = new Set();
128
+ for (const v of versions)if (!seen.has(v)) {
129
+ seen.add(v);
130
+ uniqueVersions.push(v);
131
+ }
132
+ return uniqueVersions;
133
+ }
134
+ async function fetchAvailableVersions(pkg) {
135
+ try {
136
+ const res = await fetch(`https://registry.npmjs.org/${pkg}`);
137
+ if (!res.ok) return [];
138
+ const data = await res.json();
139
+ return Object.keys(data.versions || {});
140
+ } catch {
141
+ return [];
142
+ }
143
+ }
144
+ function sortVersions(versions, order = 'desc') {
145
+ return [
146
+ ...versions
147
+ ].sort((a, b)=>{
148
+ const cmp = compareVersions(a, b);
149
+ return 'desc' === order ? -cmp : cmp;
150
+ });
151
+ }
152
+ function getLatestVersion(versions) {
153
+ if (0 === versions.length) return null;
154
+ return sortVersions(versions, 'desc')[0];
155
+ }
156
+ function getStableVersions(versions) {
157
+ return versions.filter((v)=>!v.includes('alpha') && !v.includes('beta') && !v.includes('rc'));
158
+ }
159
+ function extractMajorVersion(version) {
160
+ return parseVersion(version).major;
161
+ }
162
+ function isPrerelease(version) {
163
+ const v = parseVersion(version);
164
+ return !!v.prerelease;
165
+ }
2
166
  const fallbackPlugin = ()=>({
3
167
  name: 'fallback-plugin',
4
168
  errorLoadRemote (args) {
@@ -7,29 +171,95 @@ const fallbackPlugin = ()=>({
7
171
  return fallback;
8
172
  }
9
173
  });
174
+ const DEFAULT_CDN_TEMPLATES = [
175
+ 'https://cdn.jsdelivr.net/npm/{pkg}@{version}/dist/remoteEntry.js',
176
+ 'https://unpkg.com/{pkg}@{version}/dist/remoteEntry.js'
177
+ ];
178
+ const DEFAULT_SHARED_CONFIG = {
179
+ react: {
180
+ shareConfig: {
181
+ singleton: true,
182
+ eager: true,
183
+ requiredVersion: false
184
+ }
185
+ },
186
+ 'react-dom': {
187
+ shareConfig: {
188
+ singleton: true,
189
+ eager: true,
190
+ requiredVersion: false
191
+ }
192
+ }
193
+ };
10
194
  async function fetchLatestVersion(pkg) {
11
195
  const res = await fetch(`https://registry.npmjs.org/${pkg}`);
12
- if (!res.ok) throw new Error(`无法获取 ${pkg} 的版本信息`);
196
+ if (!res.ok) throw new Error(`[MF] 无法获取 ${pkg} 的版本信息,状态码:${res.status}`);
13
197
  const data = await res.json();
14
- return data['dist-tags']?.latest;
198
+ const latest = data['dist-tags']?.latest;
199
+ if (!latest) throw new Error(`[MF] 无法从 NPM 获取 ${pkg} 的 latest tag`);
200
+ return latest;
15
201
  }
16
202
  function getVersionCache() {
17
203
  try {
18
- return JSON.parse(localStorage.getItem('mf-multi-version') || '{}');
19
- } catch {
204
+ const cacheStr = localStorage.getItem('mf-multi-version');
205
+ return cacheStr ? JSON.parse(cacheStr) : {};
206
+ } catch (e) {
207
+ console.error('[MF Cache] 读取缓存失败:', e);
20
208
  return {};
21
209
  }
22
210
  }
23
211
  function setVersionCache(pkg, version) {
24
- const cache = getVersionCache();
25
- cache[pkg] = cache[pkg] || {};
26
- cache[pkg][version] = {
27
- timestamp: Date.now()
212
+ try {
213
+ const cache = getVersionCache();
214
+ cache[pkg] = cache[pkg] || {};
215
+ cache[pkg][version] = {
216
+ timestamp: Date.now()
217
+ };
218
+ localStorage.setItem('mf-multi-version', JSON.stringify(cache));
219
+ } catch (e) {
220
+ console.error('[MF Cache] 写入缓存失败:', e);
221
+ }
222
+ }
223
+ function buildCdnUrls(pkg, version) {
224
+ return DEFAULT_CDN_TEMPLATES.map((template)=>template.replace('{pkg}', pkg).replace('{version}', version));
225
+ }
226
+ async function tryLoadRemote(scopeName, url, retries, delay, sharedConfig, plugins) {
227
+ let lastError;
228
+ for(let i = 0; i < retries; i++)try {
229
+ const mf = createInstance({
230
+ name: 'host',
231
+ remotes: [
232
+ {
233
+ name: scopeName,
234
+ entry: url
235
+ }
236
+ ],
237
+ shared: sharedConfig,
238
+ plugins: [
239
+ ...plugins,
240
+ fallbackPlugin()
241
+ ]
242
+ });
243
+ return {
244
+ scopeName,
245
+ mf
246
+ };
247
+ } catch (e) {
248
+ lastError = e;
249
+ console.warn(`[MF] URL ${url} 加载失败,第 ${i + 1} 次重试...`);
250
+ if (i < retries - 1) await new Promise((res)=>setTimeout(res, delay));
251
+ }
252
+ throw new Error(`[MF] URL ${url} 经过 ${retries} 次重试仍加载失败。`, {
253
+ cause: lastError
254
+ });
255
+ }
256
+ function getFinalSharedConfig(customShared) {
257
+ return {
258
+ ...DEFAULT_SHARED_CONFIG,
259
+ ...customShared || {}
28
260
  };
29
- localStorage.setItem('mf-multi-version', JSON.stringify(cache));
30
261
  }
31
- async function loadRemoteMultiVersion(options, plugins) {
32
- const { name, pkg, version = 'latest', retries = 3, delay = 1000, localFallback, cacheTTL = 86400000, revalidate = true } = options;
262
+ async function resolveFinalVersion(pkg, version, cacheTTL, revalidate) {
33
263
  let finalVersion = version;
34
264
  if ('latest' === version) {
35
265
  const cache = getVersionCache();
@@ -38,56 +268,420 @@ async function loadRemoteMultiVersion(options, plugins) {
38
268
  if (latestCached && Date.now() - versions[latestCached].timestamp < cacheTTL) {
39
269
  finalVersion = latestCached;
40
270
  if (revalidate) fetchLatestVersion(pkg).then((latest)=>{
41
- if (latest !== latestCached) setVersionCache(pkg, latest);
42
- }).catch(()=>{});
271
+ if (latest !== latestCached) {
272
+ console.log(`[MF] 发现 ${pkg} 新版本 ${latest},已更新缓存。`);
273
+ setVersionCache(pkg, latest);
274
+ }
275
+ }).catch((e)=>console.error(`[MF] 异步检查最新版本失败:`, e));
43
276
  } else {
44
277
  finalVersion = await fetchLatestVersion(pkg);
45
278
  setVersionCache(pkg, finalVersion);
46
279
  }
47
280
  }
48
- const scopeName = `${name}`;
49
- const urls = [
50
- `https://cdn.jsdelivr.net/npm/${pkg}@${finalVersion}/dist/remoteEntry.js`,
51
- `https://unpkg.com/${pkg}@${finalVersion}/dist/remoteEntry.js`
52
- ];
281
+ return finalVersion;
282
+ }
283
+ function buildFinalUrls(pkg, version, localFallback) {
284
+ const urls = buildCdnUrls(pkg, version);
53
285
  if (localFallback) urls.push(localFallback);
54
- for (const url of urls)for(let i = 0; i < retries; i++)try {
55
- const mf = createInstance({
56
- name: 'host',
57
- remotes: [
58
- {
59
- name: scopeName,
60
- entry: url
61
- }
62
- ],
63
- shared: {
64
- react: {
65
- shareConfig: {
66
- singleton: true,
67
- eager: true,
68
- requiredVersion: false
69
- }
70
- },
71
- 'react-dom': {
72
- shareConfig: {
73
- singleton: true,
74
- eager: true,
75
- requiredVersion: false
76
- }
286
+ return urls;
287
+ }
288
+ async function loadRemoteMultiVersion(options, plugins) {
289
+ const { name, pkg, version = 'latest', retries = 3, delay = 1000, localFallback, cacheTTL = 86400000, revalidate = true, shared: customShared } = options;
290
+ const finalVersion = await resolveFinalVersion(pkg, version, cacheTTL, revalidate);
291
+ const scopeName = `${name}`;
292
+ const urls = buildFinalUrls(pkg, finalVersion, localFallback);
293
+ const finalSharedConfig = getFinalSharedConfig(customShared);
294
+ for (const url of urls)try {
295
+ return await tryLoadRemote(scopeName, url, retries, delay, finalSharedConfig, plugins);
296
+ } catch (e) {
297
+ console.warn(`[MF] 切换 CDN 路径:${url} 失败,尝试下一个...`, e);
298
+ }
299
+ throw new Error(`[MF] 所有加载源 (${urls.length} 个) 均加载失败。`);
300
+ }
301
+ const preloadCache = {};
302
+ const PRELOAD_CACHE_TTL = 300000;
303
+ function getCachedPreload(pkg, version) {
304
+ const cached = preloadCache[pkg];
305
+ if (!cached) return null;
306
+ if (cached.version !== version) return null;
307
+ if (Date.now() - cached.timestamp > PRELOAD_CACHE_TTL) {
308
+ delete preloadCache[pkg];
309
+ return null;
310
+ }
311
+ return {
312
+ scopeName: cached.scopeName,
313
+ mf: cached.mf
314
+ };
315
+ }
316
+ function setCachedPreload(pkg, version, scopeName, mf) {
317
+ preloadCache[pkg] = {
318
+ version,
319
+ scopeName,
320
+ mf,
321
+ timestamp: Date.now()
322
+ };
323
+ }
324
+ function executeWhenIdle(callback) {
325
+ if ('undefined' != typeof requestIdleCallback) requestIdleCallback(()=>callback());
326
+ else setTimeout(callback, 1);
327
+ }
328
+ async function preloadRemote(options) {
329
+ const { pkg, version = 'latest', priority = 'idle', force = false } = options;
330
+ if (!force) {
331
+ const cached = getCachedPreload(pkg, version);
332
+ if (cached) return cached;
333
+ }
334
+ const preloadTask = async ()=>{
335
+ try {
336
+ const { scopeName, mf } = await loadRemoteMultiVersion(options, []);
337
+ setCachedPreload(pkg, version, scopeName, mf);
338
+ return {
339
+ scopeName,
340
+ mf
341
+ };
342
+ } catch (e) {
343
+ console.warn(`[MF Preload] 预加载失败 ${pkg}@${version}:`, e);
344
+ return null;
345
+ }
346
+ };
347
+ if ('high' === priority) return preloadTask();
348
+ return new Promise((resolve)=>{
349
+ executeWhenIdle(async ()=>{
350
+ const result = await preloadTask();
351
+ resolve(result);
352
+ });
353
+ });
354
+ }
355
+ function preloadRemoteList(optionsList, onProgress) {
356
+ let loaded = 0;
357
+ const total = optionsList.length;
358
+ const promises = optionsList.map((options)=>preloadRemote(options).then((result)=>{
359
+ loaded++;
360
+ onProgress?.(loaded, total);
361
+ return result;
362
+ }));
363
+ return Promise.all(promises);
364
+ }
365
+ function cancelPreload(pkg) {
366
+ const cached = preloadCache[pkg];
367
+ if (cached) delete preloadCache[pkg];
368
+ }
369
+ function clearPreloadCache() {
370
+ Object.keys(preloadCache).forEach((pkg)=>delete preloadCache[pkg]);
371
+ }
372
+ function getPreloadStatus(pkg) {
373
+ const cached = preloadCache[pkg];
374
+ if (!cached) return null;
375
+ return {
376
+ loaded: true,
377
+ timestamp: cached.timestamp
378
+ };
379
+ }
380
+ const remoteInstances = new Map();
381
+ function generateInstanceKey(name, pkg, version) {
382
+ return `${name}::${pkg}@${version}`;
383
+ }
384
+ async function unloadRemote(options) {
385
+ const { name, pkg, version = '*', clearCache = false } = options;
386
+ const keysToDelete = [];
387
+ remoteInstances.forEach((instance, key)=>{
388
+ const versionMatch = '*' === version || instance.version === version;
389
+ const pkgMatch = instance.pkg === pkg;
390
+ const nameMatch = instance.name === name;
391
+ if (nameMatch && pkgMatch && versionMatch) keysToDelete.push(key);
392
+ });
393
+ for (const key of keysToDelete){
394
+ const instance = remoteInstances.get(key);
395
+ if (instance) {
396
+ await cleanupInstance(instance);
397
+ remoteInstances.delete(key);
398
+ }
399
+ }
400
+ if (clearCache) clearVersionCache(pkg, version);
401
+ return keysToDelete.length > 0;
402
+ }
403
+ async function cleanupInstance(instance) {
404
+ try {
405
+ instance.loadedModules.clear();
406
+ if (instance.mf && 'function' == typeof instance.mf.cleanup) await instance.mf.cleanup();
407
+ console.log(`[MF Unload] 已卸载 ${instance.pkg}@${instance.version}`);
408
+ } catch (e) {
409
+ console.warn(`[MF Unload] 卸载时出错 ${instance.pkg}:`, e);
410
+ }
411
+ }
412
+ function clearVersionCache(pkg, version) {
413
+ try {
414
+ const cacheKey = 'mf-multi-version';
415
+ const cacheStr = localStorage.getItem(cacheKey);
416
+ if (!cacheStr) return;
417
+ const cache = JSON.parse(cacheStr);
418
+ if (!cache[pkg]) return;
419
+ if ('*' === version) delete cache[pkg];
420
+ else delete cache[pkg][version];
421
+ localStorage.setItem(cacheKey, JSON.stringify(cache));
422
+ console.log(`[MF Unload] 已清除版本缓存 ${pkg}@${version}`);
423
+ } catch (e) {
424
+ console.warn('[MF Unload] 清除缓存失败:', e);
425
+ }
426
+ }
427
+ function registerRemoteInstance(name, scopeName, pkg, version, mf) {
428
+ const key = generateInstanceKey(name, pkg, version);
429
+ const instance = {
430
+ name,
431
+ scopeName,
432
+ pkg,
433
+ version,
434
+ mf,
435
+ loadedModules: new Set(),
436
+ timestamp: Date.now()
437
+ };
438
+ remoteInstances.set(key, instance);
439
+ return key;
440
+ }
441
+ function registerLoadedModule(key, moduleId) {
442
+ const instance = remoteInstances.get(key);
443
+ if (instance) instance.loadedModules.add(moduleId);
444
+ }
445
+ function unloadAll(clearAllCache = false) {
446
+ return new Promise((resolve)=>{
447
+ const keys = Array.from(remoteInstances.keys());
448
+ if (0 === keys.length) return void resolve();
449
+ let completed = 0;
450
+ keys.forEach(async (key)=>{
451
+ const instance = remoteInstances.get(key);
452
+ if (instance) {
453
+ await cleanupInstance(instance);
454
+ remoteInstances.delete(key);
455
+ }
456
+ completed++;
457
+ if (completed >= keys.length) {
458
+ if (clearAllCache) try {
459
+ localStorage.removeItem('mf-multi-version');
460
+ } catch (e) {
461
+ console.warn('[MF Unload] 清除所有缓存失败:', e);
77
462
  }
78
- },
79
- plugins: [
80
- ...plugins,
81
- fallbackPlugin()
82
- ]
463
+ resolve();
464
+ }
83
465
  });
466
+ });
467
+ }
468
+ function getLoadedRemotes() {
469
+ const result = [];
470
+ remoteInstances.forEach((instance)=>{
471
+ result.push({
472
+ name: instance.name,
473
+ pkg: instance.pkg,
474
+ version: instance.version,
475
+ loadedModules: instance.loadedModules.size,
476
+ timestamp: instance.timestamp
477
+ });
478
+ });
479
+ return result;
480
+ }
481
+ function isRemoteLoaded(name, pkg, version) {
482
+ const key = generateInstanceKey(name, pkg, version || '*');
483
+ return remoteInstances.has(key);
484
+ }
485
+ const CDN_URLS = [
486
+ 'https://cdn.jsdelivr.net/npm/{pkg}@{version}/dist/remoteEntry.js',
487
+ 'https://unpkg.com/{pkg}@{version}/dist/remoteEntry.js'
488
+ ];
489
+ async function checkCdnAccess(cdnUrl) {
490
+ const start = performance.now();
491
+ try {
492
+ const controller = new AbortController();
493
+ const timeout = setTimeout(()=>controller.abort(), 5000);
494
+ const res = await fetch(cdnUrl, {
495
+ method: 'HEAD',
496
+ signal: controller.signal
497
+ });
498
+ clearTimeout(timeout);
499
+ const latency = Math.round(performance.now() - start);
84
500
  return {
85
- scopeName,
86
- mf
501
+ reachable: res.ok,
502
+ latency
503
+ };
504
+ } catch (e) {
505
+ const latency = Math.round(performance.now() - start);
506
+ return {
507
+ reachable: false,
508
+ latency
87
509
  };
510
+ }
511
+ }
512
+ async function health_fetchLatestVersion(pkg) {
513
+ try {
514
+ const res = await fetch(`https://registry.npmjs.org/${pkg}`);
515
+ if (!res.ok) return null;
516
+ const data = await res.json();
517
+ return data['dist-tags']?.latest || null;
88
518
  } catch {
89
- await new Promise((res)=>setTimeout(res, delay));
519
+ return null;
520
+ }
521
+ }
522
+ async function checkRemoteHealth(options) {
523
+ const { pkg, version = 'latest' } = options;
524
+ const actualVersion = 'latest' === version ? await health_fetchLatestVersion(pkg) || version : version;
525
+ const results = [];
526
+ for (const template of CDN_URLS){
527
+ const url = template.replace('{pkg}', pkg).replace('{version}', actualVersion);
528
+ const result = await checkCdnAccess(url);
529
+ results.push({
530
+ cdn: url,
531
+ ...result
532
+ });
533
+ }
534
+ const workingCdn = results.find((r)=>r.reachable);
535
+ const bestCdn = results.sort((a, b)=>a.latency - b.latency)[0];
536
+ let status = 'unhealthy';
537
+ if (workingCdn) status = bestCdn.latency < 1000 ? 'healthy' : 'degraded';
538
+ return {
539
+ pkg,
540
+ version: actualVersion,
541
+ status,
542
+ latency: bestCdn?.latency || 0,
543
+ cdn: bestCdn?.cdn || '',
544
+ details: {
545
+ cdnReachable: !!workingCdn,
546
+ remoteEntryValid: false,
547
+ modulesLoadable: false
548
+ }
549
+ };
550
+ }
551
+ async function checkModuleLoadable(scopeName, modulePath, mf) {
552
+ try {
553
+ if (!mf || 'function' != typeof mf.loadRemote) return false;
554
+ const mod = await mf.loadRemote(`${scopeName}/${modulePath}`);
555
+ return null != mod;
556
+ } catch {
557
+ return false;
558
+ }
559
+ }
560
+ async function getRemoteHealthReport(remotes) {
561
+ const results = await Promise.all(remotes.map((r)=>checkRemoteHealth(r)));
562
+ let overall = 'healthy';
563
+ if (results.some((r)=>'unhealthy' === r.status)) overall = 'unhealthy';
564
+ else if (results.some((r)=>'degraded' === r.status)) overall = 'degraded';
565
+ return {
566
+ timestamp: Date.now(),
567
+ overall,
568
+ remotes: results
569
+ };
570
+ }
571
+ function formatHealthStatus(status) {
572
+ const icons = {
573
+ healthy: '🟢',
574
+ degraded: '🟡',
575
+ unhealthy: '🔴'
576
+ };
577
+ return `${icons[status]} ${status}`;
578
+ }
579
+ class EventBusClass {
580
+ listeners = new Map();
581
+ eventHistory = new Map();
582
+ maxHistorySize = 100;
583
+ generateId() {
584
+ return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
585
+ }
586
+ on(event, callback, options) {
587
+ const onceValue = options?.once ?? false;
588
+ if (!this.listeners.has(event)) this.listeners.set(event, new Set());
589
+ const subscription = {
590
+ callback,
591
+ once: onceValue,
592
+ filter: options?.filter
593
+ };
594
+ this.listeners.get(event).add(subscription);
595
+ return ()=>{
596
+ this.off(event, callback);
597
+ };
90
598
  }
91
- throw new Error(`[MF] 所有 CDN 加载失败: ${urls.join(', ')}`);
599
+ once(event, callback) {
600
+ return this.on(event, callback, {
601
+ once: true
602
+ });
603
+ }
604
+ off(event, callback) {
605
+ if (!this.listeners.has(event)) return;
606
+ if (callback) {
607
+ const subscriptions = this.listeners.get(event);
608
+ subscriptions.forEach((sub)=>{
609
+ if (sub.callback === callback) subscriptions.delete(sub);
610
+ });
611
+ } else this.listeners.delete(event);
612
+ }
613
+ emit(event, data, meta) {
614
+ const eventMeta = {
615
+ timestamp: Date.now(),
616
+ source: meta?.source,
617
+ id: meta?.id || this.generateId()
618
+ };
619
+ this.addToHistory(event, data, eventMeta);
620
+ const subscriptions = this.listeners.get(event);
621
+ if (!subscriptions) return;
622
+ const toRemove = [];
623
+ subscriptions.forEach((sub)=>{
624
+ if (sub.filter && !sub.filter(data, eventMeta)) return;
625
+ try {
626
+ sub.callback(data, eventMeta);
627
+ } catch (e) {
628
+ console.error(`[MF EventBus] 事件 ${event} 处理出错:`, e);
629
+ }
630
+ if (sub.once) toRemove.push(sub);
631
+ });
632
+ toRemove.forEach((sub)=>subscriptions.delete(sub));
633
+ }
634
+ addToHistory(event, data, meta) {
635
+ if (!this.eventHistory.has(event)) this.eventHistory.set(event, []);
636
+ const history = this.eventHistory.get(event);
637
+ history.push({
638
+ data,
639
+ meta
640
+ });
641
+ if (history.length > this.maxHistorySize) history.shift();
642
+ }
643
+ getHistory(event) {
644
+ return this.eventHistory.get(event) || [];
645
+ }
646
+ getEvents() {
647
+ return Array.from(this.listeners.keys());
648
+ }
649
+ getListenerCount(event) {
650
+ return this.listeners.get(event)?.size || 0;
651
+ }
652
+ hasListeners(event) {
653
+ return this.listeners.has(event) && this.listeners.get(event).size > 0;
654
+ }
655
+ clear(event) {
656
+ if (event) {
657
+ this.listeners.delete(event);
658
+ this.eventHistory.delete(event);
659
+ } else {
660
+ this.listeners.clear();
661
+ this.eventHistory.clear();
662
+ }
663
+ }
664
+ listenerExists(event, callback) {
665
+ const subscriptions = this.listeners.get(event);
666
+ if (!subscriptions) return false;
667
+ let exists = false;
668
+ subscriptions.forEach((sub)=>{
669
+ if (sub.callback === callback) exists = true;
670
+ });
671
+ return exists;
672
+ }
673
+ emitAsync(event, data, meta) {
674
+ return new Promise((resolve)=>{
675
+ this.emit(event, data, meta);
676
+ resolve();
677
+ });
678
+ }
679
+ static create() {
680
+ return new EventBusClass();
681
+ }
682
+ }
683
+ const eventBus = EventBusClass.create();
684
+ function createEventBus() {
685
+ return EventBusClass.create();
92
686
  }
93
- export { loadRemoteMultiVersion };
687
+ export { buildCdnUrls, buildFinalUrls, cancelPreload, checkModuleLoadable, checkRemoteHealth, checkVersionCompatibility, clearPreloadCache, compareVersions, createEventBus, eventBus, extractMajorVersion, fallbackPlugin, fetchAvailableVersions, fetchLatestVersion, findCompatibleVersion, formatHealthStatus, getCompatibleReactVersions, getFinalSharedConfig, getLatestVersion, getLoadedRemotes, getPreloadStatus, getRemoteHealthReport, getStableVersions, getVersionCache, isPrerelease, isRemoteLoaded, loadReactVersion, loadRemoteMultiVersion, parseVersion, preloadRemote, preloadRemoteList, registerLoadedModule, registerRemoteInstance, resolveFinalVersion, satisfiesVersion, setVersionCache, sortVersions, tryLoadRemote, unloadAll, unloadRemote };