diff --git a/apps/rsbuild-ssr-host/src/routes/index.tsx b/apps/rsbuild-ssr-host/src/routes/index.tsx index 853bb51..78532e4 100644 --- a/apps/rsbuild-ssr-host/src/routes/index.tsx +++ b/apps/rsbuild-ssr-host/src/routes/index.tsx @@ -1,4 +1,8 @@ -import { getRemoteStylesheets, lazyRemote } from "@module-federation/tanstack/runtime"; +import { + dedupeRemoteStylesheets, + getRemoteStylesheets, + lazyRemote, +} from "@module-federation/tanstack/runtime"; import { createFileRoute } from "@tanstack/react-router"; import { RemoteBoundary } from "../components/RemoteBoundary"; import { ServerAnswers } from "../components/ServerAnswers"; @@ -9,12 +13,6 @@ const RsbuildStatusCard = lazyRemote(() => import("tanstack_rsbuild_ssr_remote/S const ViteStatusCard = lazyRemote(() => import("tanstack_vite_remote/StatusCard")); const ViteRouterCard = lazyRemote(() => import("tanstack_vite_remote/RouterCard")); -// Manifests of the remotes this route renders on the server. -const serverRenderedManifests = [ - "http://127.0.0.1:3004/mf-manifest.json", - "http://127.0.0.1:3001/mf-manifest.json", -]; - // Calls the Rsbuild SSR remote's server functions on the server: the remote's container // sends them to the remote's server, so the answers are in the initial HTML. The POST call // carries this host's name in its body. @@ -33,10 +31,14 @@ export const Route = createFileRoute("/")({ loader: async () => { const [stylesheets, remoteAnswer] = await Promise.all([ Promise.all( - serverRenderedManifests.map((manifest) => - getRemoteStylesheets(manifest, "./StatusCard").catch(() => []), + ["tanstack_rsbuild_ssr_remote/StatusCard", "tanstack_vite_remote/StatusCard"].map( + (specifier) => + getRemoteStylesheets(specifier, { + onError: (error) => + console.error(`Failed to resolve stylesheets for ${specifier}`, error), + }).catch(() => []), ), - ).then((lists) => lists.flat()), + ).then((lists) => dedupeRemoteStylesheets(...lists)), askRemoteServer(), RsbuildStatusCard.preload().catch(() => null), ViteStatusCard.preload().catch(() => null), diff --git a/apps/vite-host/src/routes/index.tsx b/apps/vite-host/src/routes/index.tsx index 26d0803..f609b82 100644 --- a/apps/vite-host/src/routes/index.tsx +++ b/apps/vite-host/src/routes/index.tsx @@ -1,4 +1,8 @@ -import { getRemoteStylesheets, lazyRemote } from "@module-federation/tanstack/runtime"; +import { + dedupeRemoteStylesheets, + getRemoteStylesheets, + lazyRemote, +} from "@module-federation/tanstack/runtime"; import { createFileRoute } from "@tanstack/react-router"; import { useEffect, useState } from "react"; import { RemoteBoundary } from "../components/RemoteBoundary"; @@ -11,12 +15,6 @@ const RemoteRouterCard = lazyRemote(() => import("tanstack_vite_remote/RouterCar const RsbuildStatusCard = lazyRemote(() => import("tanstack_rsbuild_remote/StatusCard")); const RsbuildSsrStatusCard = lazyRemote(() => import("tanstack_rsbuild_ssr_remote/StatusCard")); -// Manifests of the remotes this route renders on the server. -const serverRenderedManifests = [ - "http://127.0.0.1:3001/mf-manifest.json", - "http://127.0.0.1:3004/mf-manifest.json", -]; - // Calls the Rsbuild SSR remote's server functions on the server: the remote's container // sends them to the remote's server, so the answers are in the initial HTML. The POST call // carries this host's name in its body. @@ -35,10 +33,14 @@ export const Route = createFileRoute("/")({ loader: async () => { const [stylesheets, remoteAnswer] = await Promise.all([ Promise.all( - serverRenderedManifests.map((manifest) => - getRemoteStylesheets(manifest, "./StatusCard").catch(() => []), + ["tanstack_vite_remote/StatusCard", "tanstack_rsbuild_ssr_remote/StatusCard"].map( + (specifier) => + getRemoteStylesheets(specifier, { + onError: (error) => + console.error(`Failed to resolve stylesheets for ${specifier}`, error), + }).catch(() => []), ), - ).then((lists) => lists.flat()), + ).then((lists) => dedupeRemoteStylesheets(...lists)), askRemoteServer(), RemoteStatusCard.preload().catch(() => null), RemoteRouterCard.preload().catch(() => null), diff --git a/apps/vite-host/vite.config.ts b/apps/vite-host/vite.config.ts index 805fee3..83efc08 100644 --- a/apps/vite-host/vite.config.ts +++ b/apps/vite-host/vite.config.ts @@ -17,7 +17,7 @@ export default defineConfig({ tanstack_vite_remote: { type: "module", name: "tanstack_vite_remote", - entry: "http://127.0.0.1:3001/remoteEntry.js", + entry: "http://127.0.0.1:3001/mf-manifest.json", }, tanstack_rsbuild_remote: { type: "global", diff --git a/packages/tanstack/README.md b/packages/tanstack/README.md index 7d2d764..d2e734a 100644 --- a/packages/tanstack/README.md +++ b/packages/tanstack/README.md @@ -260,7 +260,9 @@ export const Route = createFileRoute("/")({ // response. Catch route-loader failures so an unavailable remote does not fail the route. loader: async () => { const [stylesheets] = await Promise.all([ - getRemoteStylesheets("https://remote.test/mf-manifest.json", "./StatusCard").catch(() => []), + getRemoteStylesheets("remote/StatusCard", { + onError: (error) => console.error("Remote stylesheet lookup failed", error), + }).catch(() => []), StatusCard.preload().catch(() => null), ]); return { stylesheets }; @@ -299,12 +301,26 @@ rendering or hydration recovery instead. its fallback. The import itself loads again after a failure too: `@module-federation/vite` 1.23.3+ retries failed server loads, and the Rsbuild adapter removes a failed remote module from Rspack's module cache. -- **`getRemoteStylesheets(manifestUrl, expose, { maxAgeMs })`** lists the - stylesheets the remote's manifest declares for an expose, as absolute URLs. A - remote's CSS otherwise loads with its JavaScript, after the HTML, so the - server-rendered markup would be unstyled until then. It works in the browser - and on the server, reuses a fetched manifest for 30 seconds (`maxAgeMs`), and - rejects when the manifest is unreachable or does not list the expose. +- **`getRemoteStylesheets("remote/Expose", options)`** resolves a configured Vite or + Rsbuild remote through the adapter and lists the stylesheets its manifest declares, + as absolute URLs. A remote's CSS otherwise loads with its JavaScript, after the HTML, + so the server-rendered markup would be unstyled until then. It works in the browser + and on the server, reuses a fetched manifest for 30 seconds (`maxAgeMs`), reports + failures through `onError`, and still rejects when the manifest is unreachable or does + not list the expose. The explicit `getRemoteStylesheets(manifestUrl, expose, options)` + form remains available when the manifest boundary is known by the caller. + + The adapter resolver matches a remote by its configured key, `name`, or `alias`, and + reads the manifest from the remote's entry: an entry that is already a `.json` manifest + is used as is, and any other entry, such as `remoteEntry.js`, maps to `mf-manifest.json` + in the same directory. A remote configured with several entries uses the first one. For + a different layout, build a resolver with + `createRemoteStylesheetResolver(remotes, { resolveManifestUrl })` and pass it as the + `resolveRemote` option. Without an adapter, such as in a unit test, the `remote/Expose` + form rejects with `RemoteStylesheetResolutionError` unless `resolveRemote` is passed. + +- **`dedupeRemoteStylesheets(...groups)`** removes duplicate stylesheet URLs while + preserving their first declaration order. Remote manifest fetches throw `RemoteFetchError` from the `runtime` entry. Its `code` distinguishes network, timeout, HTTP, response-size, and JSON parse diff --git a/packages/tanstack/package.json b/packages/tanstack/package.json index ad74f79..f9f0ab6 100644 --- a/packages/tanstack/package.json +++ b/packages/tanstack/package.json @@ -59,6 +59,16 @@ "default": "./dist/runtime.cjs" } }, + "./remote-stylesheet-resolver": { + "import": { + "types": "./dist/remote-stylesheet-resolver.d.ts", + "default": "./dist/remote-stylesheet-resolver.js" + }, + "require": { + "types": "./dist/remote-stylesheet-resolver.d.cts", + "default": "./dist/remote-stylesheet-resolver.cjs" + } + }, "./server-container-rpc": { "import": { "types": "./dist/server-container-rpc.d.ts", diff --git a/packages/tanstack/rslib.config.ts b/packages/tanstack/rslib.config.ts index d945739..3b2f1dc 100644 --- a/packages/tanstack/rslib.config.ts +++ b/packages/tanstack/rslib.config.ts @@ -5,6 +5,9 @@ const entry = { "node-entry-loader": "./src/node-entry-loader.ts", "remote-errors": "./src/remote-errors.ts", "remote-fetch": "./src/remote-fetch.ts", + "remote-stylesheet-adapter": "./src/remote-stylesheet-adapter.ts", + "remote-stylesheet-remotes": "./src/remote-stylesheet-remotes.ts", + "remote-stylesheet-resolver": "./src/remote-stylesheet-resolver.ts", rsbuild: "./src/rsbuild.ts", runtime: "./src/runtime.ts", "server-container": "./src/server-container.ts", diff --git a/packages/tanstack/src/remote-stylesheet-adapter.ts b/packages/tanstack/src/remote-stylesheet-adapter.ts new file mode 100644 index 0000000..f34006d --- /dev/null +++ b/packages/tanstack/src/remote-stylesheet-adapter.ts @@ -0,0 +1,28 @@ +import { normalizeRemoteStylesheetRemotes } from "./remote-stylesheet-remotes"; + +export const REMOTE_STYLESHEET_RESOLVER_MODULE = + "@module-federation/tanstack/remote-stylesheet-resolver"; + +export const RESOLVED_REMOTE_STYLESHEET_RESOLVER_MODULE = `\0${REMOTE_STYLESHEET_RESOLVER_MODULE}`; + +/** + * Generates the adapter-owned resolver module. The remote configuration is serialized at + * build time so server and browser bundles use the same manifest identity policy without a + * process-global federation runtime singleton. + * + * Only each remote's identity is serialized: its configured key, name, alias, and entry. + */ +export function createRemoteStylesheetResolverModule(remotes: unknown): string { + // A keyed remote stays keyed, so the key keeps resolving next to the name and alias. + const serializedRemotes = JSON.stringify( + normalizeRemoteStylesheetRemotes(remotes).map(({ info, key }) => + key === undefined ? info : { [key]: info }, + ), + ); + + return `import { createRemoteStylesheetResolver } from "@module-federation/tanstack/runtime"; + +export const resolveRemoteStylesheet = createRemoteStylesheetResolver(${serializedRemotes}); +export default resolveRemoteStylesheet; +`; +} diff --git a/packages/tanstack/src/remote-stylesheet-remotes.ts b/packages/tanstack/src/remote-stylesheet-remotes.ts new file mode 100644 index 0000000..3212f96 --- /dev/null +++ b/packages/tanstack/src/remote-stylesheet-remotes.ts @@ -0,0 +1,135 @@ +export type RemoteStylesheetRemoteConfig = { + entry?: string; + name?: string; + alias?: string; + external?: string | readonly string[]; + type?: string; + internalName?: string; + entryGlobalName?: string; + shareScope?: string | string[]; + [key: string]: unknown; +}; + +export type RemoteStylesheetRemoteValue = string | readonly string[] | RemoteStylesheetRemoteConfig; + +export type RemoteStylesheetRemotes = + | Record + | readonly ( + | string + | RemoteStylesheetRemoteConfig + | Record + )[]; + +export type RemoteStylesheetRemoteInfo = { + entry: string; + name: string; + alias?: string; +}; + +export type NormalizedRemote = { + /** Every name a `remote/Expose` specifier can use for this remote. */ + aliases: string[]; + info: RemoteStylesheetRemoteInfo; + /** The key the remote was configured under, when it had one. */ + key?: string; +}; + +const UNSUPPORTED_SHAPE = "Remote stylesheet remotes must use a supported Module Federation shape."; + +/** + * Normalizes the remote shapes Vite and Rspack accept: `name@entry` strings, `{ entry }` + * and `{ external }` objects, entry lists, and arrays of any of them. The adapters and the + * runtime resolver share this, so a build-time remote resolves the same way at run time. + * + * A remote with several entries resolves stylesheets from the first one: the others are + * fallbacks for loading the container, and a manifest is fetched from a single location. + */ +export function normalizeRemoteStylesheetRemotes(remotes: unknown): NormalizedRemote[] { + if (remotes == null) return []; + if (Array.isArray(remotes)) { + return remotes.flatMap((remote) => { + if (typeof remote === "string" || isRemoteConfig(remote)) { + return [normalizeRemote(undefined, remote)]; + } + if (isRecord(remote)) return normalizeRecord(remote); + throw new TypeError(UNSUPPORTED_SHAPE); + }); + } + if (!isRecord(remotes)) throw new TypeError(UNSUPPORTED_SHAPE); + return normalizeRecord(remotes); +} + +function normalizeRecord(remotes: Record): NormalizedRemote[] { + return Object.entries(remotes).map(([key, remote]) => normalizeRemote(key, remote)); +} + +function normalizeRemote(key: string | undefined, remote: unknown): NormalizedRemote { + if (typeof remote === "string") { + const parsed = parseNamedRemote(remote); + const name = parsed?.name ?? key; + if (!name) throw new TypeError(`A remote string must include a name: ${remote}`); + return { + aliases: uniqueStrings([key, name]), + info: { alias: aliasFromKey(key, name), entry: parsed?.entry ?? remote, name }, + key, + }; + } + + if (Array.isArray(remote)) { + const first = firstString(remote); + if (!first) throw new TypeError(`Remote "${key ?? "unknown"}" must define an entry.`); + return normalizeRemote(key, first); + } + + if (!isRecord(remote)) throw new TypeError(UNSUPPORTED_SHAPE); + + const source = typeof remote.entry === "string" ? remote.entry : firstString(remote.external); + const parsed = source ? parseNamedRemote(source) : undefined; + const name = (typeof remote.name === "string" ? remote.name : parsed?.name) ?? key; + if (!name) throw new TypeError("A configured remote must have a name."); + const entry = parsed?.entry ?? source; + if (!entry) throw new TypeError(`Remote "${name}" must define an entry or external URL.`); + const alias = typeof remote.alias === "string" ? remote.alias : undefined; + return { + aliases: uniqueStrings([key, name, parsed?.name, alias]), + info: { alias: alias ?? aliasFromKey(key, name), entry, name }, + key, + }; +} + +function aliasFromKey(key: string | undefined, name: string): string | undefined { + return key !== name ? key : undefined; +} + +function isRemoteConfig(value: unknown): value is RemoteStylesheetRemoteConfig { + if (!isRecord(value)) return false; + return ( + typeof value.entry === "string" || + typeof value.external === "string" || + Array.isArray(value.external) || + typeof value.name === "string" || + typeof value.alias === "string" + ); +} + +function isRecord(value: unknown): value is Record { + return Boolean(value && typeof value === "object" && !Array.isArray(value)); +} + +function firstString(value: unknown): string | undefined { + if (typeof value === "string") return value; + if (!Array.isArray(value)) return undefined; + return value.find((item): item is string => typeof item === "string" && item !== ""); +} + +function parseNamedRemote(remote: string): { entry: string; name: string } | undefined { + const match = /^([^/@]+)@(.+)$/.exec(remote); + const name = match?.[1]; + const entry = match?.[2]; + if (!name || !entry || (!entry.includes("://") && !entry.startsWith("/"))) return undefined; + return { entry, name }; +} + +function uniqueStrings(values: (string | undefined)[]): string[] { + return [...new Set(values.filter((value): value is string => Boolean(value)))]; +} diff --git a/packages/tanstack/src/remote-stylesheet-resolver-module.d.ts b/packages/tanstack/src/remote-stylesheet-resolver-module.d.ts new file mode 100644 index 0000000..a2b0af7 --- /dev/null +++ b/packages/tanstack/src/remote-stylesheet-resolver-module.d.ts @@ -0,0 +1,9 @@ +/** + * Type declaration for the package self-reference used as the adapter replacement point. + * The bundler replaces this module with the resolver generated from its remote configuration. + */ +declare module "@module-federation/tanstack/remote-stylesheet-resolver" { + export const resolveRemoteStylesheet: import("./runtime").RemoteStylesheetResolver; + const defaultResolver: import("./runtime").RemoteStylesheetResolver; + export default defaultResolver; +} diff --git a/packages/tanstack/src/remote-stylesheet-resolver.ts b/packages/tanstack/src/remote-stylesheet-resolver.ts new file mode 100644 index 0000000..363837e --- /dev/null +++ b/packages/tanstack/src/remote-stylesheet-resolver.ts @@ -0,0 +1,17 @@ +import { RemoteStylesheetResolutionError, type RemoteStylesheetResolver } from "./runtime"; + +/** + * Resolves a `remote/Expose` specifier through the active federation adapter. + * + * Vite and Rsbuild replace this module at build time with a resolver created from the + * adapter's configured remotes. The fallback keeps the package import type-safe and fails + * explicitly when the federation adapter is not installed in the bundler configuration. + */ +export const resolveRemoteStylesheet: RemoteStylesheetResolver = async (specifier) => { + throw new RemoteStylesheetResolutionError( + `No Module Federation adapter resolver is available for "${specifier}".`, + specifier, + ); +}; + +export default resolveRemoteStylesheet; diff --git a/packages/tanstack/src/rsbuild.ts b/packages/tanstack/src/rsbuild.ts index 6aea357..3775cc6 100644 --- a/packages/tanstack/src/rsbuild.ts +++ b/packages/tanstack/src/rsbuild.ts @@ -13,6 +13,10 @@ import { SERVER_FN_BASE_DEFINE, } from "./server-container"; import { defaultShared, eagerShared, resolveShared, tanstackStartSharedPackages } from "./shared"; +import { + createRemoteStylesheetResolverModule, + REMOTE_STYLESHEET_RESOLVER_MODULE, +} from "./remote-stylesheet-adapter"; type ModuleFederationOverride = Partial; @@ -72,7 +76,19 @@ export function tanstackStartModuleFederation({ const federationName = federation.name; if (!federationName) throw new Error("federation.name is required"); - const isHost = hasEntries(federation.remotes); + const serverOptions = server && server !== true ? server : undefined; + const { + chunkFilename, + entryFilename, + environment: serverEnvironment = "ssr", + forceCommonJsOutput = true, + ssrEntryLoader, + ...serverOverrides + } = serverOptions ?? {}; + const clientRemotes = clientOverrides.remotes ?? federation.remotes; + const serverRemotes = serverOverrides.remotes ?? federation.remotes; + + const isHost = hasEntries(clientRemotes) || hasEntries(serverRemotes); const isRemote = hasEntries(federation.exposes); const serverEnabled = server !== false; const exposesServerContainer = serverEnabled && isRemote; @@ -88,6 +104,7 @@ export function tanstackStartModuleFederation({ environment: clientEnvironment, target: "web", }), + remoteStylesheetResolverPlugin(clientRemotes, serverRemotes), ...(isHost ? [remoteRetryPlugin()] : []), clientCompatibilityPlugin({ chunkLoadingGlobal: chunkLoadingGlobal ?? `chunk_${federationName}`, @@ -100,15 +117,6 @@ export function tanstackStartModuleFederation({ if (!serverEnabled) return plugins; - const { - chunkFilename, - entryFilename, - environment: serverEnvironment = "ssr", - forceCommonJsOutput = true, - ssrEntryLoader, - ...serverOverrides - } = server === true ? {} : server; - if (exposesServerContainer) { const { remotes: _remotes, ...containerOptions } = { ...federation, ...serverOverrides }; plugins.push( @@ -164,6 +172,35 @@ export function tanstackStartModuleFederation({ return plugins; } +function remoteStylesheetResolverPlugin( + clientRemotes: ModuleFederationOptions["remotes"], + serverRemotes: ModuleFederationOptions["remotes"], +): RsbuildPlugin { + const clientModuleCode = createRemoteStylesheetResolverModule(clientRemotes); + const serverModuleCode = createRemoteStylesheetResolverModule(serverRemotes); + + return { + name: "tanstack-start-federation-remote-stylesheet-resolver", + setup(api) { + api.modifyBundlerChain((chain, { isServer, rspack }) => { + const moduleCode = isServer ? serverModuleCode : clientModuleCode; + chain.plugin("tanstack-start-remote-stylesheet-resolver").use( + new rspack.NormalModuleReplacementPlugin( + new RegExp(`^${escapeRegExp(REMOTE_STYLESHEET_RESOLVER_MODULE)}$`), + (resource) => { + resource.request = `data:text/javascript,${encodeURIComponent(moduleCode)}`; + }, + ), + ); + }); + }, + }; +} + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + export const pluginTanStackStartModuleFederation = tanstackStartModuleFederation; function isAbsoluteUrl(value: unknown): boolean { diff --git a/packages/tanstack/src/runtime.ts b/packages/tanstack/src/runtime.ts index 8f59311..88d07fb 100644 --- a/packages/tanstack/src/runtime.ts +++ b/packages/tanstack/src/runtime.ts @@ -1,10 +1,20 @@ import { createElement, lazy, type ComponentProps, type ComponentType } from "react"; import { fetchRemoteJson, type RemoteFetchOptions } from "./remote-fetch"; import type { RemoteErrorCode } from "./remote-errors"; +import { + normalizeRemoteStylesheetRemotes, + type RemoteStylesheetRemoteInfo, + type RemoteStylesheetRemotes, +} from "./remote-stylesheet-remotes"; export { RemoteFetchError } from "./remote-fetch"; export { REMOTE_ERROR_CODES, REMOTE_ERROR_DESCRIPTIONS } from "./remote-errors"; export type { RemoteFetchOptions, RemoteErrorCode }; +export type { + RemoteStylesheetRemoteConfig, + RemoteStylesheetRemoteInfo, + RemoteStylesheetRemotes, +} from "./remote-stylesheet-remotes"; export type LazyRemoteOptions = { /** How long a failed load stays failed before a render tries again, in milliseconds. Defaults to 5 seconds. */ @@ -75,8 +85,40 @@ export function lazyRemote>( export type RemoteStylesheetOptions = RemoteFetchOptions & { /** How long a fetched manifest is reused, in milliseconds. Defaults to 30 seconds. */ maxAgeMs?: number; + /** Resolves a `remote/Expose` specifier to the manifest that declares its assets. */ + resolveRemote?: RemoteStylesheetResolver; + /** Observes failures without converting a rejected stylesheet lookup into a success. */ + onError?: (error: unknown) => void | Promise; }; +export type RemoteStylesheetTarget = { + manifestUrl: string; + expose: string; +}; + +export type RemoteStylesheetResolver = ( + specifier: string, +) => RemoteStylesheetTarget | Promise; + +export type RemoteStylesheetResolverOptions = { + /** + * Converts the configured remote entry into the manifest URL used for CSS metadata. + * The default replaces the entry filename with `mf-manifest.json` unless the entry is + * already a JSON manifest. + */ + resolveManifestUrl?: (remote: RemoteStylesheetRemoteInfo) => string | Promise; +}; + +export class RemoteStylesheetResolutionError extends Error { + readonly specifier: string; + + constructor(message: string, specifier: string) { + super(message); + this.name = "RemoteStylesheetResolutionError"; + this.specifier = specifier; + } +} + type CssAssets = { async?: string[]; sync?: string[] }; type RemoteManifest = { @@ -85,35 +127,151 @@ type RemoteManifest = { }; const manifests = new Map(); +let adapterResolver: Promise | undefined; + +/** + * Creates the adapter-owned part of stylesheet lookup. It accepts the object form used by + * Vite and the `name@entry` string form used by Rsbuild, but does not inspect a global + * federation singleton. The caller can provide the adapter's manifest policy when a direct + * entry is not normalized to a sibling manifest by convention. + */ +export function createRemoteStylesheetResolver( + remotes: RemoteStylesheetRemotes = {}, + { resolveManifestUrl = defaultManifestUrl }: RemoteStylesheetResolverOptions = {}, +): RemoteStylesheetResolver { + const configured = normalizeRemoteStylesheetRemotes(remotes); + + return async (specifier) => { + const { remoteName, expose } = splitRemoteSpecifier(specifier); + const remote = configured.find(({ aliases }) => aliases.includes(remoteName)); + if (!remote) { + throw new RemoteStylesheetResolutionError( + `No configured remote matches "${remoteName}" in "${specifier}".`, + specifier, + ); + } + + const manifestUrl = await resolveManifestUrl(remote.info); + if (!manifestUrl) { + throw new RemoteStylesheetResolutionError( + `Could not resolve a manifest URL for remote "${remote.info.name}".`, + specifier, + ); + } + return { expose, manifestUrl }; + }; +} + +/** Deduplicates absolute stylesheet URLs while preserving their first declaration order. */ +export function dedupeRemoteStylesheets(...groups: readonly (readonly string[])[]): string[] { + return [...new Set(groups.flat())]; +} /** * Lists the stylesheets a remote's manifest declares for an exposed module, as absolute * URLs. Return them from a route loader and render them in the route's `head`, so markup * a remote rendered on the server is styled before the remote's JavaScript loads. * + * The `remote/Expose` form uses the active Vite or Rsbuild adapter resolver automatically. + * Pass `resolveRemote` to override it, or use the explicit `(manifestUrl, expose)` form. + * * Rejects when the manifest cannot be fetched or does not list `expose`. */ export async function getRemoteStylesheets( manifestUrl: string, expose: string, - { maxAgeMs = 30_000, fetchTimeoutMs, fetchMaxBytes }: RemoteStylesheetOptions = {}, + options?: RemoteStylesheetOptions, +): Promise; +export async function getRemoteStylesheets( + specifier: string, + options?: RemoteStylesheetOptions, +): Promise; +export async function getRemoteStylesheets( + target: string, + exposeOrOptions?: string | RemoteStylesheetOptions, + explicitOptions?: RemoteStylesheetOptions, ): Promise { - const manifest = await fetchManifest(manifestUrl, { - maxAgeMs, - fetchTimeoutMs, - fetchMaxBytes, - }); - const name = expose.replace(/^\.\//, ""); - const exposed = manifest.exposes?.find( - (candidate) => candidate.path === expose || candidate.name === name, + const options = + typeof exposeOrOptions === "string" ? (explicitOptions ?? {}) : (exposeOrOptions ?? {}); + + try { + const resolved = + typeof exposeOrOptions === "string" + ? { expose: exposeOrOptions, manifestUrl: target } + : await (options.resolveRemote ?? (await loadAdapterResolver()))(target); + + if (!resolved) { + throw new RemoteStylesheetResolutionError( + `Resolving "${target}" requires the resolveRemote option.`, + target, + ); + } + + const manifest = await fetchManifest(resolved.manifestUrl, options); + const name = resolved.expose.replace(/^\.\//, ""); + const exposed = manifest.exposes?.find( + (candidate) => candidate.path === resolved.expose || candidate.name === name, + ); + if (!exposed) { + throw new Error(`${resolved.manifestUrl} does not expose "${resolved.expose}".`); + } + + // "auto" means the assets sit next to the manifest. + const publicPath = manifest.metaData?.publicPath; + const base = new URL( + publicPath && publicPath !== "auto" ? publicPath : ".", + resolved.manifestUrl, + ); + const { async = [], sync = [] } = exposed.assets?.css ?? {}; + return dedupeRemoteStylesheets(sync, async).map((asset) => new URL(asset, base).href); + } catch (error) { + try { + const report = options.onError?.(error); + if (report) void Promise.resolve(report).catch(() => undefined); + } catch { + // Reporting must never replace the original stylesheet failure. + } + throw error; + } +} + +async function loadAdapterResolver(): Promise { + adapterResolver ??= import("@module-federation/tanstack/remote-stylesheet-resolver").then( + ({ resolveRemoteStylesheet }) => resolveRemoteStylesheet, ); - if (!exposed) throw new Error(`${manifestUrl} does not expose "${expose}".`); + return adapterResolver; +} - // "auto" means the assets sit next to the manifest. - const publicPath = manifest.metaData?.publicPath; - const base = new URL(publicPath && publicPath !== "auto" ? publicPath : ".", manifestUrl); - const { async = [], sync = [] } = exposed.assets?.css ?? {}; - return [...new Set([...sync, ...async])].map((asset) => new URL(asset, base).href); +function splitRemoteSpecifier(specifier: string): { expose: string; remoteName: string } { + const separator = specifier.indexOf("/"); + if (separator <= 0 || separator === specifier.length - 1) { + throw new RemoteStylesheetResolutionError( + `Expected a remote specifier in the form "remote/Expose", received "${specifier}".`, + specifier, + ); + } + const remoteName = specifier.slice(0, separator); + const rawExpose = specifier.slice(separator + 1); + return { + expose: rawExpose.startsWith(".") ? rawExpose : `./${rawExpose}`, + remoteName, + }; +} + +function defaultManifestUrl(remote: RemoteStylesheetRemoteInfo): string { + // Only the path names the file: a query or hash can mention `.json` without being one. + const suffixIndex = remote.entry.search(/[?#]/); + const path = suffixIndex < 0 ? remote.entry : remote.entry.slice(0, suffixIndex); + if (/\.json$/i.test(path)) return remote.entry; + + try { + const url = new URL(remote.entry); + url.pathname = url.pathname.replace(/[^/]*$/, "mf-manifest.json"); + return url.href; + } catch { + const suffix = suffixIndex < 0 ? "" : remote.entry.slice(suffixIndex); + return `${path.replace(/[^/]*$/, "mf-manifest.json")}${suffix}`; + } } interface ManifestCacheEntry { diff --git a/packages/tanstack/src/vite.ts b/packages/tanstack/src/vite.ts index 4215ad9..a74a8fa 100644 --- a/packages/tanstack/src/vite.ts +++ b/packages/tanstack/src/vite.ts @@ -9,6 +9,11 @@ import { SERVER_FN_BASE_DEFINE, } from "./server-container"; import { defaultShared, eagerShared, resolveShared } from "./shared"; +import { + createRemoteStylesheetResolverModule, + REMOTE_STYLESHEET_RESOLVER_MODULE, + RESOLVED_REMOTE_STYLESHEET_RESOLVER_MODULE, +} from "./remote-stylesheet-adapter"; import { viteVersionPlugin } from "./vite-compat"; export type TanStackStartModuleFederationOptions = Omit; @@ -18,6 +23,7 @@ export type TanStackStartModuleFederationOptions = Omit { "remote-errors.d.ts", "remote-fetch.d.cts", "remote-fetch.d.ts", + "remote-stylesheet-adapter.d.cts", + "remote-stylesheet-adapter.d.ts", + "remote-stylesheet-remotes.d.cts", + "remote-stylesheet-remotes.d.ts", + "remote-stylesheet-resolver.d.cts", + "remote-stylesheet-resolver.d.ts", "node-entry-loader.d.cts", "node-entry-loader.d.ts", "rsbuild.d.cts", @@ -54,6 +60,9 @@ test("npm package contains only runtime, metadata, and documentation files", () "node-entry-loader", "remote-errors", "remote-fetch", + "remote-stylesheet-adapter", + "remote-stylesheet-remotes", + "remote-stylesheet-resolver", "rsbuild", "runtime", "server-container", diff --git a/test/release-contracts.test.mjs b/test/release-contracts.test.mjs index 7644ff4..5137608 100644 --- a/test/release-contracts.test.mjs +++ b/test/release-contracts.test.mjs @@ -214,6 +214,59 @@ test("Vite dev servers inline each app's server function base in its client code assert.equal(inlined, 'const url = "/_serverFn/" + functionId;'); }); +test("Vite adapters inject the configured stylesheet resolver", () => { + const plugin = tanstackStartModuleFederation({ + name: "host", + remotes: { + remote: { + type: "module", + name: "remote", + entry: "https://remote.example/mf-manifest.json", + }, + }, + }).find(({ name }) => name === "tanstack-start-federation:remote-stylesheet-resolver"); + assert.ok(plugin); + assert.equal(plugin.enforce, "pre"); + const resolved = plugin.resolveId("@module-federation/tanstack/remote-stylesheet-resolver"); + assert.equal(resolved, "\0@module-federation/tanstack/remote-stylesheet-resolver"); + assert.match(plugin.load(resolved), /https:\/\/remote\.example\/mf-manifest\.json/); + // An installed package must stay in Vite's module graph, or the runtime's import of the + // resolver never reaches this plugin. + assert.deepEqual(plugin.configEnvironment("ssr"), { + optimizeDeps: { exclude: ["@module-federation/tanstack"] }, + resolve: { noExternal: ["@module-federation/tanstack"] }, + }); +}); + +test("adapter resolver modules keep a remote's key, name, and alias", async () => { + const plugin = tanstackStartModuleFederation({ + name: "host", + remotes: { + keyed: { + alias: "catalog", + entry: "https://remote.example/remoteEntry.js?token=abc", + name: "remote", + shareScope: "private", + type: "module", + }, + }, + }).find(({ name }) => name === "tanstack-start-federation:remote-stylesheet-resolver"); + const code = plugin.load("\0@module-federation/tanstack/remote-stylesheet-resolver"); + assert.doesNotMatch(code, /shareScope|private/); + + const remotes = JSON.parse(/createRemoteStylesheetResolver\((.*)\);/.exec(code)[1]); + const { createRemoteStylesheetResolver } = await import( + pathToFileURL(join(root, "packages", "tanstack", "dist", "runtime.js")).href + ); + const resolve = createRemoteStylesheetResolver(remotes); + for (const remote of ["keyed", "catalog", "remote"]) { + assert.deepEqual(await resolve(`${remote}/Card`), { + expose: "./Card", + manifestUrl: "https://remote.example/mf-manifest.json?token=abc", + }); + } +}); + test("Rsbuild shared defaults never mutate caller overrides", () => { const callerShared = { react: { eager: false, singleton: false } }; const before = structuredClone(callerShared); @@ -307,15 +360,119 @@ test("Rsbuild federation is browser-only by default", () => { tanstackStartRsbuildModuleFederation({ federation }).map(({ name }) => name); assert.deepEqual(pluginNames(rsbuildRemote), [ "rsbuild:module-federation-enhanced", + "tanstack-start-federation-remote-stylesheet-resolver", "tanstack-start-federation-client-compat", ]); assert.deepEqual(pluginNames(rsbuildHost), [ "rsbuild:module-federation-enhanced", + "tanstack-start-federation-remote-stylesheet-resolver", "tanstack-start-federation-remote-retry", "tanstack-start-federation-client-compat", ]); }); +test("Rsbuild adapters inject the configured stylesheet resolver", () => { + const plugin = tanstackStartRsbuildModuleFederation({ + federation: { + name: "host", + remotes: { base: "base@http://base/mf-manifest.json" }, + }, + client: { remotes: { client: "client@http://client/mf-manifest.json" } }, + server: { remotes: { server: "server@http://server/mf-manifest.json" } }, + }).find(({ name }) => name === "tanstack-start-federation-remote-stylesheet-resolver"); + assert.ok(plugin); + + let modifyBundlerChain; + plugin.setup({ + modifyBundlerChain: (handler) => { + modifyBundlerChain = handler; + }, + }); + assert.equal(typeof modifyBundlerChain, "function"); + + const chain = { + plugin(name) { + assert.equal(name, "tanstack-start-remote-stylesheet-resolver"); + return { + use(value) { + chain.replacement = value; + }, + }; + }, + }; + class NormalModuleReplacementPlugin { + constructor(resourceRegExp, newResource) { + this.resourceRegExp = resourceRegExp; + this.newResource = newResource; + } + } + + const injectedModule = (isServer) => { + chain.replacement = undefined; + modifyBundlerChain(chain, { isServer, rspack: { NormalModuleReplacementPlugin } }); + const replacement = chain.replacement; + assert.ok(replacement); + assert.ok( + replacement.resourceRegExp.test("@module-federation/tanstack/remote-stylesheet-resolver"), + ); + const resource = { + request: "@module-federation/tanstack/remote-stylesheet-resolver", + }; + replacement.newResource(resource); + assert.match(resource.request, /^data:text\/javascript,/); + return decodeURIComponent(resource.request.slice("data:text/javascript,".length)); + }; + + assert.match(injectedModule(false), /http:\/\/client\/mf-manifest\.json/); + assert.doesNotMatch(injectedModule(false), /http:\/\/server\/mf-manifest\.json/); + assert.match(injectedModule(true), /http:\/\/server\/mf-manifest\.json/); + assert.doesNotMatch(injectedModule(true), /http:\/\/client\/mf-manifest\.json/); +}); + +test("Rsbuild host detection honors client and server remote overrides", () => { + const plugins = tanstackStartRsbuildModuleFederation({ + federation: { name: "host", exposes: {} }, + client: { remotes: { client: "client@http://client/mf-manifest.json" } }, + server: { remotes: { server: "server@http://server/mf-manifest.json" } }, + }); + + assert.ok(plugins.some(({ name }) => name === "tanstack-start-federation-remote-retry")); + assert.equal( + plugins.filter(({ name }) => name === "rsbuild:module-federation-enhanced").length, + 2, + ); +}); + +test("Rsbuild stylesheet resolver normalizes external and array remotes", () => { + const plugin = tanstackStartRsbuildModuleFederation({ + federation: { + name: "host", + remotes: [ + { external: { external: ["array_remote@http://array/mf-manifest.json"] } }, + { external_remote: { external: "http://external/mf-manifest.json" } }, + ], + }, + }).find(({ name }) => name === "tanstack-start-federation-remote-stylesheet-resolver"); + let modifyBundlerChain; + plugin.setup({ modifyBundlerChain: (handler) => (modifyBundlerChain = handler) }); + + let replacement; + const chain = { plugin: () => ({ use: (value) => (replacement = value) }) }; + class NormalModuleReplacementPlugin { + constructor(_resourceRegExp, newResource) { + this.newResource = newResource; + } + } + modifyBundlerChain(chain, { isServer: false, rspack: { NormalModuleReplacementPlugin } }); + const resource = { + request: "@module-federation/tanstack/remote-stylesheet-resolver", + }; + replacement.newResource(resource); + const code = decodeURIComponent(resource.request.slice("data:text/javascript,".length)); + assert.match(code, /http:\/\/array\/mf-manifest\.json/); + assert.match(code, /http:\/\/external\/mf-manifest\.json/); +}); + test("Rsbuild remotes resolve browser chunks from their own origin", () => { const remoteClient = { name: "client", output: { publicPath: "/" } }; runHooks(clientCompat(rsbuildRemote)).onBeforeCreateCompiler({ bundlerConfigs: [remoteClient] }); @@ -370,6 +527,7 @@ test("Rsbuild SSR remotes ship a Node container with the browser assets", async plugins.map(({ name }) => name), [ "rsbuild:module-federation-enhanced", + "tanstack-start-federation-remote-stylesheet-resolver", "tanstack-start-federation-client-compat", "tanstack-start-federation-server-container", "tanstack-start-federation-server-container-functions", @@ -427,6 +585,7 @@ test("Rsbuild SSR hosts load remotes from an async-node CommonJS server", () => plugins.map(({ name }) => name), [ "rsbuild:module-federation-enhanced", + "tanstack-start-federation-remote-stylesheet-resolver", "tanstack-start-federation-remote-retry", "tanstack-start-federation-client-compat", "rsbuild:module-federation-enhanced", @@ -615,7 +774,7 @@ test("clean consumers resolve CJS and ESM entrypoints without the other adapter" ); }); -test("runtime subpaths load without a bundler adapter", () => { +test("runtime subpaths load without a bundler adapter", async () => { // Route code imports the runtime helpers, so React is always installed next to them. const consumer = createConsumer(["react"]); try { @@ -623,6 +782,9 @@ test("runtime subpaths load without a bundler adapter", () => { const runtime = consumerRequire("@module-federation/tanstack/runtime"); const loader = consumerRequire("@module-federation/tanstack/node-entry-loader"); const serverFunctions = consumerRequire("@module-federation/tanstack/server-functions"); + const stylesheetResolver = consumerRequire( + "@module-federation/tanstack/remote-stylesheet-resolver", + ); assert.equal(typeof runtime.getRemoteStylesheets, "function"); assert.equal(typeof runtime.lazyRemote, "function"); assert.equal(typeof runtime.RemoteFetchError, "function"); @@ -632,6 +794,20 @@ test("runtime subpaths load without a bundler adapter", () => { assert.equal(typeof loader.default, "function"); assert.equal(typeof loader.RemoteEntryError, "function"); assert.equal(typeof serverFunctions.RemoteServerFunctionError, "function"); + assert.equal(typeof stylesheetResolver.resolveRemoteStylesheet, "function"); + await assert.rejects( + stylesheetResolver.resolveRemoteStylesheet("remote/Card"), + /No Module Federation adapter resolver is available/, + ); + await assert.rejects( + runtime.getRemoteStylesheets("remote/Card"), + /No Module Federation adapter resolver is available/, + ); + assertConsumerImport( + consumer, + "@module-federation/tanstack/remote-stylesheet-resolver", + "resolveRemoteStylesheet", + ); } finally { rmSync(consumer, { force: true, recursive: true }); } @@ -646,12 +822,12 @@ test("runtime subpaths load without a bundler adapter", () => { } }); -function assertConsumerImport(consumer, specifier) { +function assertConsumerImport(consumer, specifier, exportName = "tanstackStartModuleFederation") { const entry = join(consumer, "consumer.mjs"); writeFileSync( entry, - `import { tanstackStartModuleFederation } from ${JSON.stringify(specifier)};\n` + - `if (typeof tanstackStartModuleFederation !== "function") process.exit(2);\n`, + `import { ${exportName} } from ${JSON.stringify(specifier)};\n` + + `if (typeof ${exportName} !== "function") process.exit(2);\n`, ); const result = spawnSync(process.execPath, [entry], { cwd: consumer, diff --git a/test/runtime.test.mjs b/test/runtime.test.mjs index 132a533..bffd999 100644 --- a/test/runtime.test.mjs +++ b/test/runtime.test.mjs @@ -14,9 +14,13 @@ const root = join(dirname(fileURLToPath(import.meta.url)), ".."); const dist = join(root, "packages", "tanstack", "dist"); const loaderUrl = pathToFileURL(join(dist, "node-entry-loader.js")).href; const { default: nodeEntryLoader, RemoteEntryError } = await import(loaderUrl); -const { getRemoteStylesheets, lazyRemote } = await import( - pathToFileURL(join(dist, "runtime.js")).href -); +const { + createRemoteStylesheetResolver, + dedupeRemoteStylesheets, + getRemoteStylesheets, + lazyRemote, + RemoteStylesheetResolutionError, +} = await import(pathToFileURL(join(dist, "runtime.js")).href); // The React copy the runtime resolves. const packageRequire = createRequire(join(root, "packages", "tanstack", "package.json")); const { createInstance } = packageRequire("@module-federation/runtime"); @@ -621,6 +625,160 @@ test("getRemoteStylesheets resolves an expose's CSS from its manifest", async () ]); }); +test("resolves stylesheet manifests from Vite and Rsbuild remote identities", async () => { + const viteManifest = JSON.stringify({ + exposes: [ + { + assets: { css: { sync: ["assets/card.css"] } }, + name: "StatusCard", + path: "./StatusCard", + }, + ], + metaData: { publicPath: "auto" }, + }); + const rsbuildManifest = viteManifest.replaceAll("StatusCard", "Card"); + serve("/resolver/vite/mf-manifest.json", viteManifest, "application/json"); + serve("/resolver/rsbuild/mf-manifest.json", rsbuildManifest, "application/json"); + + const viteResolver = createRemoteStylesheetResolver({ + vite_remote: { + entry: `${origin}/resolver/vite/remoteEntry.js`, + name: "vite_remote", + }, + }); + assert.deepEqual( + await getRemoteStylesheets("vite_remote/StatusCard", { + resolveRemote: viteResolver, + }), + [`${origin}/resolver/vite/assets/card.css`], + ); + + const rsbuildResolver = createRemoteStylesheetResolver({ + rsbuild_remote: `rsbuild_remote@${origin}/resolver/rsbuild/mf-manifest.json`, + }); + assert.deepEqual( + await getRemoteStylesheets("rsbuild_remote/./Card", { + resolveRemote: rsbuildResolver, + }), + [`${origin}/resolver/rsbuild/assets/card.css`], + ); + + const externalResolver = createRemoteStylesheetResolver({ + external_remote: { external: `${origin}/resolver/rsbuild/mf-manifest.json` }, + }); + assert.deepEqual( + await getRemoteStylesheets("external_remote/Card", { resolveRemote: externalResolver }), + [`${origin}/resolver/rsbuild/assets/card.css`], + ); + + const arrayResolver = createRemoteStylesheetResolver([ + { array_remote: `array_remote@${origin}/resolver/rsbuild/mf-manifest.json` }, + ]); + assert.deepEqual( + await getRemoteStylesheets("array_remote/Card", { resolveRemote: arrayResolver }), + [`${origin}/resolver/rsbuild/assets/card.css`], + ); + + const aliasResolver = createRemoteStylesheetResolver({ + keyed_remote: { + alias: "catalog", + entry: `${origin}/resolver/vite/mf-manifest.json`, + name: "vite_remote", + }, + }); + assert.deepEqual( + await getRemoteStylesheets("catalog/StatusCard", { resolveRemote: aliasResolver }), + [`${origin}/resolver/vite/assets/card.css`], + ); + + const customManifestResolver = createRemoteStylesheetResolver( + { + custom_remote: { + entry: `${origin}/resolver/custom/remoteEntry.js`, + name: "custom_remote", + }, + }, + { resolveManifestUrl: () => `${origin}/resolver/vite/mf-manifest.json` }, + ); + assert.deepEqual( + await getRemoteStylesheets("custom_remote/StatusCard", { + resolveRemote: customManifestResolver, + }), + [`${origin}/resolver/vite/assets/card.css`], + ); + + const signedEntryResolver = createRemoteStylesheetResolver({ + signed_remote: { + entry: `${origin}/resolver/signed/remoteEntry.js?token=abc#fragment`, + name: "signed_remote", + }, + }); + assert.equal( + (await signedEntryResolver("signed_remote/Card")).manifestUrl, + `${origin}/resolver/signed/mf-manifest.json?token=abc#fragment`, + ); + + // Only the path decides whether an entry is already a manifest. + const jsonQueryResolver = createRemoteStylesheetResolver({ + json_query: `${origin}/resolver/query/remoteEntry.js?v=build.json`, + manifest_query: `${origin}/resolver/query/custom-manifest.json?v=1#hash`, + relative: "/resolver/query/remoteEntry.js?next=a.json", + fallbacks: [ + `fallbacks@${origin}/resolver/first/remoteEntry.js`, + "fallbacks@https://b.test/x.js", + ], + }); + assert.equal( + (await jsonQueryResolver("json_query/Card")).manifestUrl, + `${origin}/resolver/query/mf-manifest.json?v=build.json`, + ); + assert.equal( + (await jsonQueryResolver("manifest_query/Card")).manifestUrl, + `${origin}/resolver/query/custom-manifest.json?v=1#hash`, + ); + assert.equal( + (await jsonQueryResolver("relative/Card")).manifestUrl, + "/resolver/query/mf-manifest.json?next=a.json", + ); + // A remote with fallback entries resolves stylesheets from the first one. + assert.equal( + (await jsonQueryResolver("fallbacks/Card")).manifestUrl, + `${origin}/resolver/first/mf-manifest.json`, + ); +}); + +test("reports identity resolution failures without hiding them", async () => { + const errors = []; + const resolver = createRemoteStylesheetResolver({ + remote: `${origin}/resolver/mf-manifest.json`, + }); + + await assert.rejects( + getRemoteStylesheets("missing/Card", { + onError: (error) => errors.push(error), + resolveRemote: resolver, + }), + (error) => { + assert.ok(error instanceof RemoteStylesheetResolutionError); + assert.equal(error.specifier, "missing/Card"); + return true; + }, + ); + assert.equal(errors.length, 1); + assert.equal(errors[0].specifier, "missing/Card"); +}); + +test("deduplicates stylesheet URLs while preserving first declaration order", () => { + assert.deepEqual( + dedupeRemoteStylesheets( + [`${origin}/shared.css`, `${origin}/card.css`], + [`${origin}/shared.css`, `${origin}/footer.css`], + [], + ), + [`${origin}/shared.css`, `${origin}/card.css`, `${origin}/footer.css`], + ); +}); + test("getRemoteStylesheets reuses manifests briefly and retries failures", async () => { const path = "/cache/mf-manifest.json"; const url = `${origin}${path}`;