|
| 1 | +import { register } from "node:module"; |
| 2 | +import { pathToFileURL } from "node:url"; |
| 3 | +import * as fs from 'node:fs/promises'; |
| 4 | +import * as path from 'node:path'; |
| 5 | +import { processHostInfo, processRemoteInfos, FederationInfo } from "@softarc/native-federation-runtime"; |
| 6 | +import { ImportMap, mergeImportMaps } from "@softarc/native-federation-runtime"; |
| 7 | +import { setImportMap } from "./import-map-store"; |
| 8 | + |
| 9 | +export type InitNodeFederationOptions = { |
| 10 | + relBundlePath: string; |
| 11 | +}; |
| 12 | + |
| 13 | +export async function initNodeFederation( |
| 14 | + remotesOrManifestUrl: Record<string, string> | string = {}, |
| 15 | + options: InitNodeFederationOptions |
| 16 | +): Promise<void> { |
| 17 | + const importMap = await createNodeImportMap(remotesOrManifestUrl, options); |
| 18 | + setImportMap(importMap); |
| 19 | + register(pathToFileURL('./federation-resolver.js').href); |
| 20 | +} |
| 21 | + |
| 22 | +async function createNodeImportMap( |
| 23 | + remotesOrManifestUrl: Record<string, string> | string = {}, |
| 24 | + options: InitNodeFederationOptions |
| 25 | +): Promise<ImportMap> { |
| 26 | + const remotes = |
| 27 | + typeof remotesOrManifestUrl === 'object' |
| 28 | + ? remotesOrManifestUrl |
| 29 | + : await loadFsManifest(options.relBundlePath, remotesOrManifestUrl); |
| 30 | + |
| 31 | + const hostInfo = await loadFsFederationInfo(options.relBundlePath); |
| 32 | + const hostImportMap = await processHostInfo(hostInfo, options.relBundlePath); |
| 33 | + const remotesImportMap = await processRemoteInfos(remotes); |
| 34 | + |
| 35 | + const importMap = mergeImportMaps(hostImportMap, remotesImportMap); |
| 36 | + |
| 37 | + return importMap; |
| 38 | +} |
| 39 | + |
| 40 | +async function loadFsManifest( |
| 41 | + relBundlePath: string, |
| 42 | + manifestName: string |
| 43 | +): Promise<Record<string, string>> { |
| 44 | + const manifestPath = path.join(relBundlePath, manifestName); |
| 45 | + const content = await fs.readFile(manifestPath, 'utf-8'); |
| 46 | + const manifest = JSON.parse(content) as Record<string, string>; |
| 47 | + return manifest; |
| 48 | +} |
| 49 | + |
| 50 | +async function loadFsFederationInfo( |
| 51 | + relBundlePath: string |
| 52 | +): Promise<FederationInfo> { |
| 53 | + const manifestPath = path.join(relBundlePath, 'remoteEntry.json'); |
| 54 | + const content = await fs.readFile(manifestPath, 'utf-8'); |
| 55 | + const manifest = JSON.parse(content) as FederationInfo; |
| 56 | + return manifest; |
| 57 | +} |
0 commit comments