|
1 | 1 | import { ModuleContextValueType } from '../constants'; |
2 | 2 |
|
| 3 | +type RemoteInfo = { |
| 4 | + exposes: { |
| 5 | + path: string, |
| 6 | + assets?: { |
| 7 | + css?: { |
| 8 | + sync?: string[], |
| 9 | + async?: string[] |
| 10 | + } |
| 11 | + } |
| 12 | + }[] |
| 13 | +} |
| 14 | + |
| 15 | +const remoteInfoCache: Record<string, RemoteInfo | null> = {}; |
| 16 | + |
| 17 | +const loadRemoteInfo = async (url: string) => { |
| 18 | + if (!url.endsWith('/mf-manifest.json')) { |
| 19 | + return null; |
| 20 | + } |
| 21 | + |
| 22 | + if (remoteInfoCache[url]) { |
| 23 | + return remoteInfoCache[url]; |
| 24 | + } |
| 25 | + const res = await fetch(url); |
| 26 | + if (res.status === 200) { |
| 27 | + const info: RemoteInfo = await res.json(); |
| 28 | + remoteInfoCache[url] = info; |
| 29 | + return info; |
| 30 | + } |
| 31 | + if (res.status === 404) { |
| 32 | + remoteInfoCache[url] = null; |
| 33 | + return null; |
| 34 | + } |
| 35 | + throw new Error(`Could not load remote info from ${url}`); |
| 36 | +} |
| 37 | + |
3 | 38 | export const collectCssChunks = async (modules: ModuleContextValueType) => { |
4 | | - const instance = globalThis.moduleFederationRuntime.getInstance(); |
5 | | - const p = Object.values(modules).map((module) => { |
6 | | - const info = instance.snapshotHandler.manifestCache.get(module.url); |
| 39 | + const p = Object.values(modules).map(async (module) => { |
| 40 | + const info = await loadRemoteInfo(module.url); |
7 | 41 |
|
8 | 42 | const chunks: string[] = []; |
9 | 43 | info?.exposes.forEach((exposes) => { |
10 | | - if (exposes.path && module.modules.has(exposes.path)) { |
| 44 | + if (module.modules.has(exposes.path)) { |
11 | 45 | const { sync = [], async = [] } = exposes.assets?.css ?? {}; |
12 | 46 | [...sync, ...async].forEach((chunk) => { |
13 | 47 | const url = new URL(chunk, module.url); |
14 | | - chunks.push(`<link rel="stylesheet" href="${url}">`); |
| 48 | + chunks.push(`<link rel="stylesheet" href="${url}">`) |
15 | 49 | }); |
16 | 50 | } |
17 | | - }); |
| 51 | + }) |
18 | 52 | return chunks; |
19 | | - }); |
20 | | - return p.flat().join(''); |
| 53 | + }) |
| 54 | + const r = await Promise.allSettled(p); |
| 55 | + return r.flatMap((v) => v.status === 'fulfilled' ? v.value : []).join('') |
21 | 56 | }; |
0 commit comments