Unverified Commit cac5128f authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

feat(turbopack): emit and consume federation manifests

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent d0e36d05
...@@ -9479,6 +9479,7 @@ dependencies = [ ...@@ -9479,6 +9479,7 @@ dependencies = [
"turbopack-resolve", "turbopack-resolve",
"turbopack-static", "turbopack-static",
"turbopack-wasm", "turbopack-wasm",
"url",
] ]
[[package]] [[package]]
......
This diff is collapsed.
...@@ -2759,6 +2759,18 @@ impl Project { ...@@ -2759,6 +2759,18 @@ impl Project {
Ok(any_output_changed(roots, path, false)) Ok(any_output_changed(roots, path, false))
} }
/// Federation's browser entry, lazy chunks, CSS, and manifest are written under the
/// server output root rather than the regular client filesystem. Track them there
/// without excluding CSS, so dev subscriptions see exposed-module changes.
#[turbo_tasks::function]
pub async fn federation_changed(
self: Vc<Self>,
roots: Vc<OutputAssets>,
) -> Result<Vc<Completion>> {
let path = self.node_root().owned().await?;
Ok(any_output_changed(roots, path, false))
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn client_main_modules(self: Vc<Self>) -> Result<Vc<GraphEntries>> { pub async fn client_main_modules(self: Vc<Self>) -> Result<Vc<GraphEntries>> {
let pages_project = self.pages_project(); let pages_project = self.pages_project();
......
...@@ -108,6 +108,32 @@ module.exports = { ...@@ -108,6 +108,32 @@ module.exports = {
} }
``` ```
## Consuming a manifest
Turbopack can load an enhanced Module Federation remote from its manifest URL, without knowing the remote's global container name in advance:
```js filename="next.config.js"
module.exports = {
experimental: {
turbopackModuleFederation: {
remotes: {
catalog:
'https://catalog.example.com/_next/static/mf-manifest.json?v=1',
checkout: {
manifest: 'https://checkout.example.com/mf-manifest.json',
shareScope: 'default',
},
legacy: 'legacy@https://legacy.example.com/remoteEntry.js',
},
},
},
}
```
A string without `globalName@` is treated as a manifest only when it is an `http:` or `https:` URL whose pathname ends in `.json`. Query strings and fragments are supported; credentials in manifest URLs are rejected. An object must specify **either** `manifest` **or** `external`, not both. A script remote still uses `globalName@url`. Invalid or unreachable manifests fail with an upstream runtime diagnostic rather than silently falling back to a script.
Manifest files are fetched by the browser, so a cross-origin producer must send an appropriate `Access-Control-Allow-Origin` header for the manifest. Default `shareStrategy: 'version-first'` initializes configured remotes before choosing shared versions; an unreachable optional manifest can therefore block sharing. Use `shareStrategy: 'loaded-first'` when optional remotes should not delay initial sharing.
## Exposing modules ## Exposing modules
Set a container `name`, a `filename`, and the modules to expose. The unhashed remote entry is served from `/_next/static/<filename>`. Its content-hashed lazy chunks use the isolated `/_next/static/chunks/mf/` directory. Set a container `name`, a `filename`, and the modules to expose. The unhashed remote entry is served from `/_next/static/<filename>`. Its content-hashed lazy chunks use the isolated `/_next/static/chunks/mf/` directory.
...@@ -149,6 +175,30 @@ module.exports = nextConfig ...@@ -149,6 +175,30 @@ module.exports = nextConfig
The filename defaults to `<name>.js`. It must be a relative path and cannot contain `..`, a query string, or a URL. Exposed modules are loaded lazily from separate chunks. The filename defaults to `<name>.js`. It must be a relative path and cannot contain `..`, a query string, or a URL. Exposed modules are loaded lazily from separate chunks.
A producer also emits `/_next/static/mf-manifest.json` automatically in development and production. It lists the remote entry, configured shared modules and remotes, and each exposed module's actual synchronous and asynchronous JavaScript/CSS assets. Host-only configurations do not emit a manifest. These asset paths are relative to the manifest's `/_next/static/` directory; the enhanced runtime resolves `publicPath: 'auto'` from the manifest URL, including when the producer runs on another origin.
To permit a different-origin browser host to fetch this one file, add a response header in the producer's normal Next.js configuration (restrict the origin to the trusted host):
```js filename="next.config.js"
module.exports = {
async headers() {
return [
{
source: '/_next/static/mf-manifest.json',
headers: [
{
key: 'Access-Control-Allow-Origin',
value: 'https://storefront.example.com',
},
],
},
]
},
}
```
For CDN deployments, configure the same header on the CDN response for the manifest. This does not change the CORS policy of other Next.js assets.
## Sharing modules ## Sharing modules
The `shared` option uses webpack-compatible share keys and configuration: The `shared` option uses webpack-compatible share keys and configuration:
...@@ -260,7 +310,30 @@ export async function loadCatalog(url: string) { ...@@ -260,7 +310,30 @@ export async function loadCatalog(url: string) {
} }
``` ```
When multiple federated apps share a page, use `getInstance((instance) => instance.name === 'storefront')` to select your app's instance rather than relying on the no-argument accessor. If you set `implementation: 'custom-runtime'`, import these APIs from `custom-runtime/runtime` instead of the default runtime package. Dynamic registration and `loadRemote()` support script entries. Upstream `preloadRemote()` requires a manifest; it does not preload a script-only webpack v1 remote without one. For a manifest-backed remote, the upstream runtime can also preload its exposed assets before importing the module:
```tsx filename="app/preload-catalog.tsx"
'use client'
import { getInstance } from '@module-federation/runtime-tools/runtime'
export async function preloadCatalog() {
const instance = getInstance()
if (!instance) throw new Error('Federation is not initialized yet')
instance.registerRemotes([
{
name: 'catalog',
entry: 'https://catalog.example.com/_next/static/mf-manifest.json',
},
])
await instance.preloadRemote([
{ nameOrAlias: 'catalog', exposes: ['./product'], resourceCategory: 'all' },
])
return instance.loadRemote('catalog/product')
}
```
When multiple federated apps share a page, use `getInstance((instance) => instance.name === 'storefront')` to select your app's instance rather than relying on the no-argument accessor. If you set `implementation: 'custom-runtime'`, import these APIs from `custom-runtime/runtime` instead of the default runtime package. Dynamic registration and `loadRemote()` support both script and manifest entries. Upstream `preloadRemote()` requires a manifest; it does not preload a script-only webpack v1 remote without one.
## Runtime behavior and limitations ## Runtime behavior and limitations
......
...@@ -185,6 +185,20 @@ function isJSONSerializable(value: unknown, seen = new Set<object>()): boolean { ...@@ -185,6 +185,20 @@ function isJSONSerializable(value: unknown, seen = new Set<object>()): boolean {
return valid return valid
} }
const zTurbopackModuleFederationManifestUrl = z.string().refine((value) => {
try {
const url = new URL(value)
return (
(url.protocol === 'http:' || url.protocol === 'https:') &&
!url.username &&
!url.password &&
url.pathname.endsWith('.json')
)
} catch {
return false
}
}, 'Manifest must be an http(s) URL whose pathname ends in .json, without credentials')
const zTurbopackModuleFederationRemoteConfig = z.union([ const zTurbopackModuleFederationRemoteConfig = z.union([
z.string(), z.string(),
z.array(z.string()), z.array(z.string()),
...@@ -192,6 +206,10 @@ const zTurbopackModuleFederationRemoteConfig = z.union([ ...@@ -192,6 +206,10 @@ const zTurbopackModuleFederationRemoteConfig = z.union([
external: z.union([z.string(), z.array(z.string())]), external: z.union([z.string(), z.array(z.string())]),
shareScope: z.string().optional(), shareScope: z.string().optional(),
}), }),
z.strictObject({
manifest: zTurbopackModuleFederationManifestUrl,
shareScope: z.string().optional(),
}),
]) ])
const zTurbopackModuleFederationExposeConfig = z.union([ const zTurbopackModuleFederationExposeConfig = z.union([
......
...@@ -311,6 +311,10 @@ export type TurbopackModuleFederationRemoteConfig = ...@@ -311,6 +311,10 @@ export type TurbopackModuleFederationRemoteConfig =
external: string | string[] external: string | string[]
shareScope?: string shareScope?: string
} }
| {
manifest: string
shareScope?: string
}
export type TurbopackModuleFederationExposeConfig = export type TurbopackModuleFederationExposeConfig =
| string | string
......
...@@ -770,7 +770,18 @@ export async function handleEntrypoints({ ...@@ -770,7 +770,18 @@ export async function handleEntrypoints({
key, key,
/** includeIssues=*/ false, /** includeIssues=*/ false,
moduleFederation, moduleFederation,
() => ({ type: HMR_MESSAGE_SENT_TO_BROWSER.CLIENT_CHANGES }), async () => {
const updatedEndpoint = await moduleFederation.writeToDisk()
dev?.hooks.handleWrittenEndpoint(key, updatedEndpoint, false)
processIssues(
currentEntryIssues,
key,
updatedEndpoint,
false,
logErrors
)
return { type: HMR_MESSAGE_SENT_TO_BROWSER.CLIENT_CHANGES }
},
(error) => ({ (error) => ({
type: HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE, type: HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE,
data: `error in Module Federation subscription: ${error}`, data: `error in Module Federation subscription: ${error}`,
......
...@@ -4,11 +4,20 @@ import { useEffect, useState } from 'react' ...@@ -4,11 +4,20 @@ import { useEffect, useState } from 'react'
export function RemoteMessage() { export function RemoteMessage() {
const [message, setMessage] = useState('loading') const [message, setMessage] = useState('loading')
const [lazyMessage, setLazyMessage] = useState('loading')
useEffect(() => { useEffect(() => {
// @ts-expect-error -- provided by Module Federation at runtime // @ts-expect-error -- provided by Module Federation at runtime
import('nextRemote/message').then((module) => setMessage(module.message)) import('nextRemote/message').then(async (module) => {
setMessage(module.message)
setLazyMessage(await module.lazyMessage())
})
}, []) }, [])
return <p id="remote-message">{message}</p> return (
<>
<p id="remote-message">{message}</p>
<p id="remote-lazy-message">{lazyMessage}</p>
</>
)
} }
...@@ -2,13 +2,18 @@ ...@@ -2,13 +2,18 @@
import React from 'react' import React from 'react'
import { value } from 'shared-value' import { value } from 'shared-value'
import './component.css'
export default function NextRemoteComponent() { export default function NextRemoteComponent() {
const [label] = React.useState('React hook from Next.js remote') const [label] = React.useState('React hook from Next.js remote')
return React.createElement( return React.createElement(
React.Fragment, React.Fragment,
null, null,
React.createElement('p', { id: 'next-remote-react' }, label), React.createElement(
'p',
{ id: 'next-remote-react', className: 'next-remote-component' },
label
),
React.createElement('p', { id: 'next-remote-shared-value' }, value) React.createElement('p', { id: 'next-remote-shared-value' }, value)
) )
} }
export const late = 'nested lazy from Next.js remote'
import { used } from './dependency' import { used } from './dependency'
export const message = used export const message = used
export async function lazyMessage() {
const { late } = await import('./late.js')
return late
}
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
async headers() {
// Manifest URLs are fetched across origins by the enhanced runtime (unlike script tags).
return [
{
source: '/_next/static/mf-manifest.json',
headers: [{ key: 'Access-Control-Allow-Origin', value: '*' }],
},
]
},
experimental: { experimental: {
turbopackModuleFederation: { turbopackModuleFederation: {
name: 'nextRemote', name: 'nextRemote',
...@@ -7,6 +16,7 @@ const nextConfig = { ...@@ -7,6 +16,7 @@ const nextConfig = {
exposes: { exposes: {
'./message': './lib/message.js', './message': './lib/message.js',
'./component': './lib/component.js', './component': './lib/component.js',
'./composite': ['./lib/component.css', './lib/message.js'],
}, },
shared: { shared: {
react: { singleton: true, eager: true, requiredVersion: false }, react: { singleton: true, eager: true, requiredVersion: false },
......
import type { ChildProcess } from 'child_process' import type { ChildProcess } from 'child_process'
import type { Server } from 'http' import type { Server } from 'http'
import { writeFile } from 'fs/promises' import { readFile, writeFile } from 'fs/promises'
import { join } from 'path' import { join } from 'path'
import execa from 'execa' import execa from 'execa'
import { isNextDeploy, nextTestSetup } from 'e2e-utils' import { isNextDeploy, nextTestSetup } from 'e2e-utils'
...@@ -145,8 +145,79 @@ describeTurbopack('turbopack module federation between Next.js apps', () => { ...@@ -145,8 +145,79 @@ describeTurbopack('turbopack module federation between Next.js apps', () => {
expect(await browser.elementByCss('#remote-message').text()).toBe( expect(await browser.elementByCss('#remote-message').text()).toBe(
'hello from Next.js' 'hello from Next.js'
) )
expect(await browser.elementByCss('#remote-lazy-message').text()).toBe(
'nested lazy from Next.js remote'
)
}, 15_000) }, 15_000)
const manifestResponse = await fetch(
`${remoteOrigin}/_next/static/mf-manifest.json`
)
expect(manifestResponse.status).toBe(200)
const manifest = (await manifestResponse.json()) as {
id: string
metaData: {
publicPath: string
remoteEntry: { name: string; path: string; type: string }
}
shared: Array<{ name: string; version: string; singleton: boolean }>
remotes: unknown[]
exposes: Array<{
path: string
assets: Record<'js' | 'css', { sync: string[]; async: string[] }>
}>
}
expect(manifest.id).toBe('nextRemote')
expect(manifest.metaData).toMatchObject({
publicPath: 'auto',
remoteEntry: { name: 'nextRemote.js', path: 'nested', type: 'global' },
})
expect(manifest.shared.map((item) => item.name).sort()).toEqual([
'react',
'shared-value',
])
expect(
manifest.shared.find((item) => item.name === 'shared-value')
).toMatchObject({
version: '1.0.0',
singleton: true,
})
expect(manifest.remotes).toEqual([])
expect(manifest.exposes.map((expose) => expose.path).sort()).toEqual([
'./component',
'./composite',
'./message',
])
expect(
manifest.exposes.find((expose) => expose.path === './component')?.assets
.css.sync.length
).toBeGreaterThan(0)
expect(
manifest.exposes.find((expose) => expose.path === './message')?.assets.js
.async.length
).toBeGreaterThan(0)
const composite = manifest.exposes.find(
(expose) => expose.path === './composite'
)
expect(composite?.assets.js.sync.length).toBeGreaterThan(0)
expect(composite?.assets.css.sync.length).toBeGreaterThan(0)
for (const expose of manifest.exposes) {
expect(expose.assets.js.sync.length).toBeGreaterThan(0)
for (const type of ['js', 'css'] as const) {
for (const file of [
...expose.assets[type].sync,
...expose.assets[type].async,
]) {
expect(file).toMatch(/^chunks\/mf\//)
expect(file).not.toContain('..')
const assetResponse = await fetch(
new URL(file, `${remoteOrigin}/_next/static/`)
)
expect(assetResponse.status).toBe(200)
}
}
}
// The exposed module lives in its own async chunk, fetched from the producer's origin // The exposed module lives in its own async chunk, fetched from the producer's origin
// rather than from the host that loaded the remote entry. // rather than from the host that loaded the remote entry.
const remoteChunks = await browser.eval( const remoteChunks = await browser.eval(
...@@ -248,4 +319,77 @@ describeTurbopack('turbopack module federation between Next.js apps', () => { ...@@ -248,4 +319,77 @@ describeTurbopack('turbopack module federation between Next.js apps', () => {
) )
}, 15_000) }, 15_000)
}) })
if (isNextDev) {
it('updates the manifest assets when an exposed lazy module changes', async () => {
await writeFile(
join(next.testDir, 'remote/lib/late.js'),
"export const late = 'manifest refresh marker'\n"
)
expect(
await readFile(join(next.testDir, 'remote/lib/late.js'), 'utf8')
).toContain('manifest refresh marker')
await retry(async () => {
const response = await fetch(
`${remoteOrigin}/_next/static/mf-manifest.json`,
{ cache: 'no-store' }
)
expect(response.status).toBe(200)
const manifest = (await response.json()) as {
exposes: Array<{
path: string
assets: { js: { async: string[] } }
}>
}
const chunks = manifest.exposes.find(
(expose) => expose.path === './message'
)?.assets.js.async
expect(chunks?.length).toBeGreaterThan(0)
const contents = await Promise.all(
chunks!.map(async (file) =>
(
await fetch(new URL(file, `${remoteOrigin}/_next/static/`), {
cache: 'no-store',
})
).text()
)
)
expect(contents.join('\n')).toContain('manifest refresh marker')
}, 20_000)
})
it('refreshes manifest CSS assets when an exposed style changes', async () => {
await writeFile(
join(next.testDir, 'remote/lib/component.css'),
'.next-remote-component { color: fuchsia; }\n'
)
await retry(async () => {
const response = await fetch(
`${remoteOrigin}/_next/static/mf-manifest.json`,
{ cache: 'no-store' }
)
expect(response.status).toBe(200)
const manifest = (await response.json()) as {
exposes: Array<{
path: string
assets: { css: { sync: string[] } }
}>
}
const chunks = manifest.exposes.find(
(expose) => expose.path === './component'
)?.assets.css.sync
expect(chunks?.length).toBeGreaterThan(0)
const contents = await Promise.all(
chunks!.map(async (file) =>
(
await fetch(new URL(file, `${remoteOrigin}/_next/static/`), {
cache: 'no-store',
})
).text()
)
)
expect(contents.join('\n')).toMatch(/fuchsia|#f0f/i)
}, 20_000)
})
}
}) })
...@@ -5,6 +5,18 @@ import('nextRemote/message').then(({ message }) => { ...@@ -5,6 +5,18 @@ import('nextRemote/message').then(({ message }) => {
document.getElementById('webpack-message').textContent = message document.getElementById('webpack-message').textContent = message
}) })
const composite = document.createElement('p')
composite.id = 'manifest-composite'
document.body.appendChild(composite)
import('nextRemote/composite').then(
({ message }) => {
composite.textContent = message
},
(error) => {
composite.textContent = `error: ${error?.message || error}`
}
)
const mount = document.createElement('div') const mount = document.createElement('div')
document.body.appendChild(mount) document.body.appendChild(mount)
import('nextRemote/component').then( import('nextRemote/component').then(
......
...@@ -28,6 +28,7 @@ await new Promise((resolve, reject) => { ...@@ -28,6 +28,7 @@ await new Promise((resolve, reject) => {
context, context,
target: worker ? 'webworker' : 'web', target: worker ? 'webworker' : 'web',
entry: isRemote ? {} : './rspack-react.js', entry: isRemote ? {} : './rspack-react.js',
module: { rules: [{ test: /\.css$/, type: 'css' }] },
output: { output: {
path: outputPath, path: outputPath,
publicPath: isRemote publicPath: isRemote
...@@ -51,9 +52,12 @@ await new Promise((resolve, reject) => { ...@@ -51,9 +52,12 @@ await new Promise((resolve, reject) => {
? { ? {
name: worker ? 'workerCatalog' : 'catalog', name: worker ? 'workerCatalog' : 'catalog',
filename: 'remoteEntry.js', filename: 'remoteEntry.js',
manifest: !worker,
exposes: { exposes: {
'./component': './component.js', './component': worker
'./message': './message.js', ? './component.js'
: './rspack-component.js',
'./message': worker ? './message.js' : './rspack-message.js',
}, },
shared: worker shared: worker
? {} ? {}
......
'use client'
import { useEffect, useState } from 'react'
// This component is copied only into the Rspack-v2 Next host fixture. The webpack-v1
// fixture shares its base files, but intentionally has no manifest remotes.
export function ManifestImports() {
const [fromString, setFromString] = useState('loading')
const [fromObject, setFromObject] = useState('loading')
useEffect(() => {
async function load() {
// @ts-expect-error -- resolved by the manifest URL in the isolated Next host config
const first = await import('catalogManifest/message')
// @ts-expect-error -- resolved by the manifest object in the isolated Next host config
const second = await import('catalogObject/message')
setFromString(first.message)
setFromObject(second.message)
}
load().catch((error) => setFromString(`error: ${error.message}`))
}, [])
return (
<>
<p id="manifest-import-string">{fromString}</p>
<p id="manifest-import-object">{fromObject}</p>
</>
)
}
import type { ChildProcess } from 'child_process' import type { ChildProcess } from 'child_process'
import type { Server } from 'http' import { createServer, type Server } from 'http'
import { mkdir, readFile, rm, symlink, writeFile } from 'fs/promises' import { mkdir, readFile, rm, symlink, writeFile } from 'fs/promises'
import { join } from 'path' import { join } from 'path'
import execa from 'execa' import execa from 'execa'
import express from 'express'
import { isNextDeploy, nextTestSetup } from 'e2e-utils' import { isNextDeploy, nextTestSetup } from 'e2e-utils'
import { import {
fetchViaHTTP, fetchViaHTTP,
...@@ -74,7 +75,34 @@ async function buildRspack( ...@@ -74,7 +75,34 @@ async function buildRspack(
nodeExecutable, nodeExecutable,
[target, kind, context, output, url, worker ? 'worker' : 'browser'], [target, kind, context, output, url, worker ? 'worker' : 'browser'],
{ cwd: testDir } { cwd: testDir }
).catch((error) => {
throw new Error(
`Rspack build failed: ${error.stderr || error.stdout || error.message}`
) )
})
}
async function startCorsStaticServer(
dir: string,
port: number
): Promise<Server> {
const app = express()
app.use((request, response, next) => {
if (request.path.endsWith('.json')) {
response.setHeader('Access-Control-Allow-Origin', '*')
}
next()
})
app.use(express.static(dir))
const server = createServer(app)
await new Promise<void>((resolve, reject) => {
server.once('error', reject)
server.listen(port, () => {
server.off('error', reject)
resolve()
})
})
return server
} }
function stopStaticServer(server: Server) { function stopStaticServer(server: Server) {
...@@ -116,6 +144,24 @@ describeTurbopack('Turbopack host and Rspack v2 remote', () => { ...@@ -116,6 +144,24 @@ describeTurbopack('Turbopack host and Rspack v2 remote', () => {
`export const value = 'default shared fallback'` `export const value = 'default shared fallback'`
) )
const context = join(next.testDir, 'remote') const context = join(next.testDir, 'remote')
await Promise.all([
writeFile(
join(context, 'rspack-component.js'),
"import './rspack-style.css'; export { default } from './component.js'\n"
),
writeFile(
join(context, 'rspack-style.css'),
'.rspack-remote { color: royalblue }\n'
),
writeFile(
join(context, 'rspack-message.js'),
"export * from './message.js'; export async function lazy() { return (await import('./rspack-late.js')).late }\n"
),
writeFile(
join(context, 'rspack-late.js'),
"export const late = 'nested lazy from Rspack remote'\n"
),
])
await buildRspack( await buildRspack(
next.testDir, next.testDir,
'remote', 'remote',
...@@ -131,9 +177,26 @@ describeTurbopack('Turbopack host and Rspack v2 remote', () => { ...@@ -131,9 +177,26 @@ describeTurbopack('Turbopack host and Rspack v2 remote', () => {
remoteOrigin, remoteOrigin,
true true
) )
remoteServer = await startStaticServer(remoteOutput, undefined, port) await writeFile(
join(remoteOutput, 'browser', 'invalid-manifest.json'),
JSON.stringify({ exposes: [] })
)
remoteServer = await startCorsStaticServer(remoteOutput, port)
process.env.MF_REMOTE_ORIGIN = remoteOrigin process.env.MF_REMOTE_ORIGIN = remoteOrigin
process.env.NEXT_PUBLIC_MF_REMOTE_ORIGIN = remoteOrigin process.env.NEXT_PUBLIC_MF_REMOTE_ORIGIN = remoteOrigin
process.env.MF_REMOTE_MANIFEST = `${remoteOrigin}/browser/mf-manifest.json`
process.env.NEXT_PUBLIC_MF_REMOTE_MANIFEST = process.env.MF_REMOTE_MANIFEST
await writeFile(
join(next.testDir, 'app', 'manifest-import.tsx'),
await readFile(join(__dirname, 'manifest-host.tsx'))
)
await writeFile(
join(next.testDir, 'app', 'page.tsx'),
`import { RemoteMessage } from './remote-message'
import { ManifestImports } from './manifest-import'
export default function Page() { return <><RemoteMessage /><ManifestImports /></> }
`
)
await next.start() await next.start()
}) })
...@@ -144,6 +207,8 @@ describeTurbopack('Turbopack host and Rspack v2 remote', () => { ...@@ -144,6 +207,8 @@ describeTurbopack('Turbopack host and Rspack v2 remote', () => {
if (sharedPackage) await rm(sharedPackage, { recursive: true, force: true }) if (sharedPackage) await rm(sharedPackage, { recursive: true, force: true })
delete process.env.MF_REMOTE_ORIGIN delete process.env.MF_REMOTE_ORIGIN
delete process.env.NEXT_PUBLIC_MF_REMOTE_ORIGIN delete process.env.NEXT_PUBLIC_MF_REMOTE_ORIGIN
delete process.env.MF_REMOTE_MANIFEST
delete process.env.NEXT_PUBLIC_MF_REMOTE_MANIFEST
}) })
it('loads exposed JS, React and worker modules with shared versions', async () => { it('loads exposed JS, React and worker modules with shared versions', async () => {
...@@ -152,6 +217,27 @@ describeTurbopack('Turbopack host and Rspack v2 remote', () => { ...@@ -152,6 +217,27 @@ describeTurbopack('Turbopack host and Rspack v2 remote', () => {
expect(await browser.elementByCss('#remote-message').text()).toBe( expect(await browser.elementByCss('#remote-message').text()).toBe(
'hello from Turbopack host sharing' 'hello from Turbopack host sharing'
) )
expect(
await browser.elementByCss('#manifest-string-message').text()
).toBe('hello from Turbopack host sharing')
expect(
await browser.elementByCss('#manifest-object-message').text()
).toBe('hello from Turbopack host sharing')
expect(
await browser.elementByCss('#manifest-preloaded-message').text()
).toBe('hello from Turbopack host sharing')
expect(
await browser.elementByCss('#manifest-invalid-error').text()
).toMatch(/RUNTIME-013|not a valid federation manifest/)
expect(
await browser.elementByCss('#manifest-missing-error').text()
).toMatch(/RUNTIME-003|Failed to get manifest/)
expect(await browser.elementByCss('#manifest-import-string').text()).toBe(
'hello from Turbopack host sharing'
)
expect(await browser.elementByCss('#manifest-import-object').text()).toBe(
'hello from Turbopack host sharing'
)
expect(await browser.elementByCss('#remote-react-component').text()).toBe( expect(await browser.elementByCss('#remote-react-component').text()).toBe(
'next/dynamic from webpack remote' 'next/dynamic from webpack remote'
) )
...@@ -199,6 +285,39 @@ describeTurbopack('Turbopack host and Rspack v2 remote', () => { ...@@ -199,6 +285,39 @@ describeTurbopack('Turbopack host and Rspack v2 remote', () => {
`performance.getEntriesByType('resource').map((entry) => entry.name).filter((name) => name.startsWith(${JSON.stringify(remoteOrigin + '/browser/')}) && !name.endsWith('remoteEntry.js'))` `performance.getEntriesByType('resource').map((entry) => entry.name).filter((name) => name.startsWith(${JSON.stringify(remoteOrigin + '/browser/')}) && !name.endsWith('remoteEntry.js'))`
) )
expect(chunks).not.toEqual([]) expect(chunks).not.toEqual([])
const manifestUrl = `${remoteOrigin}/browser/mf-manifest.json`
const manifestResponse = await fetch(manifestUrl)
expect(manifestResponse.headers.get('access-control-allow-origin')).toBe(
'*'
)
const manifest = (await manifestResponse.json()) as {
exposes: Array<{
path: string
assets: Record<'js' | 'css', { sync: string[]; async: string[] }>
}>
}
const component = manifest.exposes.find(
(expose) => expose.path === './component'
)
const message = manifest.exposes.find(
(expose) => expose.path === './message'
)
expect(component?.assets.css.sync.length).toBeGreaterThan(0)
expect(message?.assets.js.async.length).toBeGreaterThan(0)
const resourceUrls = (await browser.eval(
`performance.getEntriesByType('resource').map((entry) => entry.name)`
)) as string[]
expect(
resourceUrls.some((url) => url.includes('/browser/mf-manifest.json'))
).toBe(true)
for (const file of [
...(component?.assets.css.sync || []),
...(message?.assets.js.async || []),
]) {
expect(resourceUrls.some((url) => url.includes(`/browser/${file}`))).toBe(
true
)
}
}) })
it('loads a rebuilt Rspack remote after a browser reload', async () => { it('loads a rebuilt Rspack remote after a browser reload', async () => {
...@@ -258,6 +377,7 @@ describeTurbopack('Rspack v2 host and Turbopack remote', () => { ...@@ -258,6 +377,7 @@ describeTurbopack('Rspack v2 host and Turbopack remote', () => {
}) })
let remoteServer: ChildProcess let remoteServer: ChildProcess
let remoteOrigin: string let remoteOrigin: string
let manifestUrl: string
let rspackHostServer: Server let rspackHostServer: Server
let rspackHostOrigin: string let rspackHostOrigin: string
...@@ -294,6 +414,7 @@ describeTurbopack('Rspack v2 host and Turbopack remote', () => { ...@@ -294,6 +414,7 @@ describeTurbopack('Rspack v2 host and Turbopack remote', () => {
throw new Error(`Remote server returned status ${response.status}`) throw new Error(`Remote server returned status ${response.status}`)
} }
process.env.MF_REMOTE_URL = `${remoteOrigin}/_next/static/nested/nextRemote.js` process.env.MF_REMOTE_URL = `${remoteOrigin}/_next/static/nested/nextRemote.js`
manifestUrl = `${remoteOrigin}/_next/static/mf-manifest.json`
const hostPort = await findPort() const hostPort = await findPort()
rspackHostOrigin = `http://localhost:${hostPort}` rspackHostOrigin = `http://localhost:${hostPort}`
...@@ -303,7 +424,7 @@ describeTurbopack('Rspack v2 host and Turbopack remote', () => { ...@@ -303,7 +424,7 @@ describeTurbopack('Rspack v2 host and Turbopack remote', () => {
'host', 'host',
join(next.testDir, 'webpack-host'), join(next.testDir, 'webpack-host'),
hostOutput, hostOutput,
process.env.MF_REMOTE_URL manifestUrl
) )
await writeFile( await writeFile(
join(hostOutput, 'index.html'), join(hostOutput, 'index.html'),
...@@ -322,11 +443,19 @@ describeTurbopack('Rspack v2 host and Turbopack remote', () => { ...@@ -322,11 +443,19 @@ describeTurbopack('Rspack v2 host and Turbopack remote', () => {
}) })
it('loads a Turbopack expose from an enhanced Rspack host', async () => { it('loads a Turbopack expose from an enhanced Rspack host', async () => {
const manifestResponse = await fetch(manifestUrl)
expect(manifestResponse.status).toBe(200)
expect(manifestResponse.headers.get('access-control-allow-origin')).toBe(
'*'
)
const browser = await next.browser('/', { baseUrl: rspackHostOrigin }) const browser = await next.browser('/', { baseUrl: rspackHostOrigin })
await retry(async () => { await retry(async () => {
expect(await browser.elementByCss('#webpack-message').text()).toBe( expect(await browser.elementByCss('#webpack-message').text()).toBe(
'hello from Next.js' 'hello from Next.js'
) )
expect(await browser.elementByCss('#manifest-composite').text()).toBe(
'hello from Next.js'
)
expect(await browser.elementByCss('#next-remote-react').text()).toBe( expect(await browser.elementByCss('#next-remote-react').text()).toBe(
'React hook from Next.js remote' 'React hook from Next.js remote'
) )
...@@ -338,5 +467,10 @@ describeTurbopack('Rspack v2 host and Turbopack remote', () => { ...@@ -338,5 +467,10 @@ describeTurbopack('Rspack v2 host and Turbopack remote', () => {
`performance.getEntriesByType('resource').map((entry) => entry.name).filter((name) => name.startsWith(${JSON.stringify(remoteOrigin + '/_next/static/chunks/mf/')}) && !name.endsWith('nextRemote.js'))` `performance.getEntriesByType('resource').map((entry) => entry.name).filter((name) => name.startsWith(${JSON.stringify(remoteOrigin + '/_next/static/chunks/mf/')}) && !name.endsWith('nextRemote.js'))`
) )
expect(assets).not.toEqual([]) expect(assets).not.toEqual([])
expect(
await browser.eval(
`performance.getEntriesByType('resource').some((entry) => entry.name.startsWith(${JSON.stringify(manifestUrl)}))`
)
).toBe(true)
}) })
}) })
...@@ -45,6 +45,41 @@ describeTurbopack('enhanced federation runtime configuration', () => { ...@@ -45,6 +45,41 @@ describeTurbopack('enhanced federation runtime configuration', () => {
} }
}) })
it('validates manifest URL objects without changing legacy script remotes', () => {
const { configSchema } = require('next/dist/server/config-schema') as {
configSchema: { safeParse: (value: unknown) => { success: boolean } }
}
const valid = (remote: unknown) =>
configSchema.safeParse({
experimental: {
turbopackModuleFederation: { remotes: { catalog: remote } },
},
}).success
expect(valid('https://example.com/mf-manifest.json?v=1#hash')).toBe(true)
expect(
valid({ manifest: 'https://example.com/mf-manifest.json?v=1#hash' })
).toBe(true)
expect(valid({ external: 'catalog@/remoteEntry.js' })).toBe(true)
for (const remote of [
{ manifest: 'file:///tmp/manifest.json' },
{ manifest: 'https://user:pass@example.com/mf.json' },
{ manifest: 'https://example.com/entry.js' },
{
manifest: 'https://example.com/mf.json',
external: 'catalog@/entry.js',
},
{},
]) {
expect(valid(remote)).toBe(false)
}
})
it('does not publish a producer manifest for a host-only configuration', async () => {
const response = await next.fetch('/_next/static/mf-manifest.json')
expect(response.status).toBe(404)
})
it('infers a host-only name from the project package and initializes one instance', async () => { it('infers a host-only name from the project package and initializes one instance', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
await retry(async () => { await retry(async () => {
......
...@@ -22,6 +22,13 @@ export function RemoteMessage() { ...@@ -22,6 +22,13 @@ export function RemoteMessage() {
const [runtimeIsolation, setRuntimeIsolation] = useState('loading') const [runtimeIsolation, setRuntimeIsolation] = useState('loading')
const [shareStrategy, setShareStrategy] = useState('loading') const [shareStrategy, setShareStrategy] = useState('loading')
const [dynamicMessage, setDynamicMessage] = useState('loading') const [dynamicMessage, setDynamicMessage] = useState('loading')
const [manifestMessage, setManifestMessage] = useState('not configured')
const [manifestObjectMessage, setManifestObjectMessage] =
useState('not configured')
const [preloadedMessage, setPreloadedMessage] = useState('not configured')
const [badManifestError, setBadManifestError] = useState('not configured')
const [missingManifestError, setMissingManifestError] =
useState('not configured')
const [fallbackRemoteMessage, setFallbackRemoteMessage] = useState('loading') const [fallbackRemoteMessage, setFallbackRemoteMessage] = useState('loading')
const [pluginMarker, setPluginMarker] = useState('loading') const [pluginMarker, setPluginMarker] = useState('loading')
const [hostShared, setHostShared] = useState('loading') const [hostShared, setHostShared] = useState('loading')
...@@ -93,6 +100,58 @@ export function RemoteMessage() { ...@@ -93,6 +100,58 @@ export function RemoteMessage() {
'dynamicCatalog/message' 'dynamicCatalog/message'
) )
setDynamicMessage(dynamicRemote?.message ?? 'missing') setDynamicMessage(dynamicRemote?.message ?? 'missing')
if (process.env.NEXT_PUBLIC_MF_REMOTE_MANIFEST) {
const fromString = await instance.loadRemote<typeof remote>(
'catalogManifest/message'
)
setManifestMessage(fromString?.message ?? 'missing')
const fromObject = await instance.loadRemote<typeof remote>(
'catalogObject/message'
)
setManifestObjectMessage(fromObject?.message ?? 'missing')
instance.registerRemotes([
{
name: 'dynamicManifest',
entry: `${process.env.NEXT_PUBLIC_MF_REMOTE_MANIFEST}?dynamic=1`,
},
])
await instance.preloadRemote([
{
nameOrAlias: 'dynamicManifest',
exposes: ['./message', './component'],
resourceCategory: 'all',
},
])
const preloaded = await instance.loadRemote<typeof remote>(
'dynamicManifest/message'
)
setPreloadedMessage(preloaded?.message ?? 'missing')
const base = process.env.NEXT_PUBLIC_MF_REMOTE_MANIFEST.replace(
/mf-manifest\.json$/,
''
)
// Invalid remotes should not poison version-first sharing in the real host.
const invalidHost = init({
name: 'invalidManifestHost',
remotes: [],
shared: {},
shareStrategy: 'loaded-first',
})
invalidHost.registerRemotes([
{ name: 'badManifest', entry: `${base}invalid-manifest.json` },
{ name: 'missingManifest', entry: `${base}missing-manifest.json` },
])
try {
await invalidHost.loadRemote('badManifest/message')
} catch (error) {
setBadManifestError((error as Error).message)
}
try {
await invalidHost.loadRemote('missingManifest/message')
} catch (error) {
setMissingManifestError((error as Error).message)
}
}
const other = init({ name: 'independentHost', remotes: [], shared: {} }) const other = init({ name: 'independentHost', remotes: [], shared: {} })
setRuntimeIsolation( setRuntimeIsolation(
getInstance((host) => host.name === 'nextHost') === instance && getInstance((host) => host.name === 'nextHost') === instance &&
...@@ -145,6 +204,11 @@ export function RemoteMessage() { ...@@ -145,6 +204,11 @@ export function RemoteMessage() {
<p id="enhanced-runtime-isolation">{runtimeIsolation}</p> <p id="enhanced-runtime-isolation">{runtimeIsolation}</p>
<p id="enhanced-share-strategy">{shareStrategy}</p> <p id="enhanced-share-strategy">{shareStrategy}</p>
<p id="enhanced-dynamic-message">{dynamicMessage}</p> <p id="enhanced-dynamic-message">{dynamicMessage}</p>
<p id="manifest-string-message">{manifestMessage}</p>
<p id="manifest-object-message">{manifestObjectMessage}</p>
<p id="manifest-preloaded-message">{preloadedMessage}</p>
<p id="manifest-invalid-error">{badManifestError}</p>
<p id="manifest-missing-error">{missingManifestError}</p>
<p id="enhanced-fallback-remote">{fallbackRemoteMessage}</p> <p id="enhanced-fallback-remote">{fallbackRemoteMessage}</p>
<p id="enhanced-plugin-marker">{pluginMarker}</p> <p id="enhanced-plugin-marker">{pluginMarker}</p>
<RemoteComponent /> <RemoteComponent />
......
...@@ -6,6 +6,15 @@ const nextConfig = { ...@@ -6,6 +6,15 @@ const nextConfig = {
runtimePlugins: [['./runtime-plugin.js', { marker: 'plugin ran' }]], runtimePlugins: [['./runtime-plugin.js', { marker: 'plugin ran' }]],
remotes: { remotes: {
catalog: `catalog@${process.env.MF_REMOTE_ORIGIN}/browser/remoteEntry.js`, catalog: `catalog@${process.env.MF_REMOTE_ORIGIN}/browser/remoteEntry.js`,
...(process.env.MF_REMOTE_MANIFEST
? {
catalogManifest: `${process.env.MF_REMOTE_MANIFEST}?v=1#hash`,
catalogObject: {
manifest: `${process.env.MF_REMOTE_MANIFEST}?v=2`,
shareScope: 'default',
},
}
: {}),
fallbackCatalog: [ fallbackCatalog: [
`missingCatalog@${process.env.MF_REMOTE_ORIGIN}/missing/remoteEntry.js`, `missingCatalog@${process.env.MF_REMOTE_ORIGIN}/missing/remoteEntry.js`,
`catalog@${process.env.MF_REMOTE_ORIGIN}/browser/remoteEntry.js`, `catalog@${process.env.MF_REMOTE_ORIGIN}/browser/remoteEntry.js`,
......
...@@ -24,6 +24,7 @@ serde_json = { workspace = true } ...@@ -24,6 +24,7 @@ serde_json = { workspace = true }
semver = { workspace = true } semver = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
tracing = { workspace = true } tracing = { workspace = true }
url = { workspace = true }
turbo-bincode = { workspace = true } turbo-bincode = { workspace = true }
turbo-rcstr = { workspace = true } turbo-rcstr = { workspace = true }
......
...@@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize}; ...@@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{NonLocalValue, OperationValue}; use turbo_tasks::{NonLocalValue, OperationValue};
use turbo_tasks_fs::{FileContent, FileSystemPath}; use turbo_tasks_fs::{FileContent, FileSystemPath};
use url::Url;
#[derive( #[derive(
Clone, Clone,
...@@ -49,7 +50,8 @@ impl ModuleFederationStringOrStrings { ...@@ -49,7 +50,8 @@ impl ModuleFederationStringOrStrings {
)] )]
#[serde(deny_unknown_fields, rename_all = "camelCase")] #[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct UnnormalizedModuleFederationRemoteOptions { pub struct UnnormalizedModuleFederationRemoteOptions {
pub external: ModuleFederationStringOrStrings, pub external: Option<ModuleFederationStringOrStrings>,
pub manifest: Option<RcStr>,
pub share_scope: Option<RcStr>, pub share_scope: Option<RcStr>,
} }
...@@ -364,6 +366,7 @@ pub struct ModuleFederationConfig { ...@@ -364,6 +366,7 @@ pub struct ModuleFederationConfig {
pub struct ModuleFederationRemote { pub struct ModuleFederationRemote {
pub request: RcStr, pub request: RcStr,
pub external: Vec<ModuleFederationRemoteExternal>, pub external: Vec<ModuleFederationRemoteExternal>,
pub manifest: Option<RcStr>,
pub share_scope: RcStr, pub share_scope: RcStr,
} }
...@@ -502,17 +505,40 @@ impl UnnormalizedModuleFederationConfig { ...@@ -502,17 +505,40 @@ impl UnnormalizedModuleFederationConfig {
if let Some(remotes) = self.remotes { if let Some(remotes) = self.remotes {
for (request, remote) in remotes.into_entries() { for (request, remote) in remotes.into_entries() {
let (external, remote_share_scope) = match remote { let (external, manifest, remote_share_scope) = match remote {
UnnormalizedModuleFederationRemote::String(external) => { UnnormalizedModuleFederationRemote::String(entry) => {
(vec![external], share_scope.clone()) if Url::parse(&entry).is_ok_and(|url| {
matches!(url.scheme(), "http" | "https") && url.has_host()
}) {
if !is_manifest_url(&entry) {
bail!(
"Module Federation bare remote must be an http(s) manifest \
URL ending in .json without credentials; use globalName@url \
for scripts"
);
} }
UnnormalizedModuleFederationRemote::Strings(external) => { (vec![], Some(entry), share_scope.clone())
(external, share_scope.clone()) } else {
(vec![entry], None, share_scope.clone())
} }
UnnormalizedModuleFederationRemote::Options(options) => ( }
options.external.into_vec(), UnnormalizedModuleFederationRemote::Strings(external) => {
options.share_scope.unwrap_or_else(|| share_scope.clone()), (external, None, share_scope.clone())
}
UnnormalizedModuleFederationRemote::Options(options) => {
let scope = options.share_scope.unwrap_or_else(|| share_scope.clone());
match (options.external, options.manifest) {
(Some(_), Some(_)) => bail!(
"Module Federation remote '{request}' cannot have both external \
and manifest"
),
(None, None) => bail!(
"Module Federation remote '{request}' needs external or manifest"
), ),
(Some(external), None) => (external.into_vec(), None, scope),
(None, Some(manifest)) => (vec![], Some(manifest), scope),
}
}
}; };
config.remotes.push(ModuleFederationRemote { config.remotes.push(ModuleFederationRemote {
request, request,
...@@ -520,6 +546,7 @@ impl UnnormalizedModuleFederationConfig { ...@@ -520,6 +546,7 @@ impl UnnormalizedModuleFederationConfig {
.into_iter() .into_iter()
.map(|external| parse_remote_external(&external)) .map(|external| parse_remote_external(&external))
.collect::<Result<_>>()?, .collect::<Result<_>>()?,
manifest,
share_scope: remote_share_scope, share_scope: remote_share_scope,
}); });
} }
...@@ -727,6 +754,21 @@ impl ModuleFederationConfig { ...@@ -727,6 +754,21 @@ impl ModuleFederationConfig {
if remote.request.is_empty() { if remote.request.is_empty() {
bail!("Module Federation remote request must not be empty"); bail!("Module Federation remote request must not be empty");
} }
if let Some(manifest) = &remote.manifest {
if !remote.external.is_empty() {
bail!(
"Module Federation remote '{}' cannot have both external and manifest",
remote.request
);
}
if !is_manifest_url(manifest) {
bail!(
"Module Federation manifest must be an http(s) URL whose pathname ends in \
.json, without credentials"
);
}
continue;
}
if remote.external.is_empty() { if remote.external.is_empty() {
bail!( bail!(
"Module Federation remote '{}' must have at least one external", "Module Federation remote '{}' must have at least one external",
...@@ -752,6 +794,16 @@ impl ModuleFederationConfig { ...@@ -752,6 +794,16 @@ impl ModuleFederationConfig {
} }
} }
fn is_manifest_url(value: &str) -> bool {
Url::parse(value).is_ok_and(|url| {
matches!(url.scheme(), "http" | "https")
&& url.has_host()
&& url.username().is_empty()
&& url.password().is_none()
&& url.path().ends_with(".json")
})
}
fn parse_remote_external(external: &str) -> Result<ModuleFederationRemoteExternal> { fn parse_remote_external(external: &str) -> Result<ModuleFederationRemoteExternal> {
let Some((global, url)) = external.split_once('@') else { let Some((global, url)) = external.split_once('@') else {
bail!("Module Federation script remote must use 'globalName@url', got '{external}'"); bail!("Module Federation script remote must use 'globalName@url', got '{external}'");
...@@ -815,6 +867,47 @@ mod tests { ...@@ -815,6 +867,47 @@ mod tests {
assert_eq!(config.remotes[0].share_scope, "catalog"); assert_eq!(config.remotes[0].share_scope, "catalog");
} }
#[test]
fn normalizes_manifest_remotes() {
let config: UnnormalizedModuleFederationConfig = serde_json::from_str(
r#"{"remotes":{
"catalog":"https://catalog.example.com/mf-manifest.json?v=1#hash",
"checkout":{"manifest":"http://checkout.example.com/manifest.json?c=1","shareScope":"feature"},
"legacy":"legacy@/remoteEntry.js"
}}"#,
)
.unwrap();
let config = config.normalize().unwrap();
assert_eq!(
config.remotes[0].manifest.as_deref(),
Some("https://catalog.example.com/mf-manifest.json?v=1#hash")
);
assert!(config.remotes[0].external.is_empty());
assert_eq!(
config.remotes[1].manifest.as_deref(),
Some("http://checkout.example.com/manifest.json?c=1")
);
assert_eq!(config.remotes[1].share_scope, "feature");
assert_eq!(config.remotes[2].external[0].global, "legacy");
}
#[test]
fn rejects_invalid_manifest_remotes() {
for json in [
r#"{"remotes":{"catalog":{"manifest":"file:///tmp/manifest.json"}}}"#,
r#"{"remotes":{"catalog":{"manifest":"https://remote.example.com/entry.js"}}}"#,
r#"{"remotes":{"catalog":{"manifest":"https://remote.example.com/mf.json","external":"catalog@/entry.js"}}}"#,
r#"{"remotes":{"catalog":{}}}"#,
r#"{"remotes":{"catalog":"https://remote.example.com/entry.js"}}"#,
r#"{"remotes":{"catalog":"https://user:pass@remote.example.com/mf.json"}}"#,
r#"{"remotes":{"catalog":{"manifest":"https://user:pass@remote.example.com/mf.json"}}}"#,
] {
let result = serde_json::from_str::<UnnormalizedModuleFederationConfig>(json)
.and_then(|config| config.normalize().map_err(serde::de::Error::custom));
assert!(result.is_err(), "{json}");
}
}
#[test] #[test]
fn rejects_unsupported_configuration() { fn rejects_unsupported_configuration() {
assert!( assert!(
......
...@@ -8,4 +8,4 @@ pub use config::*; ...@@ -8,4 +8,4 @@ pub use config::*;
pub use container::*; pub use container::*;
pub use remote::*; pub use remote::*;
pub use runtime::*; pub use runtime::*;
pub use shared::apply_shared_import_map; pub use shared::{apply_shared_import_map, shared_provider_version};
...@@ -36,12 +36,14 @@ async fn module_federation_remote_init_source( ...@@ -36,12 +36,14 @@ async fn module_federation_remote_init_source(
let code = format!( let code = format!(
r#" r#"
const candidates = {candidates}; const candidates = {candidates};
const manifestEntry = {manifest_entry};
const remoteName = {remote_name}; const remoteName = {remote_name};
const shareScope = {share_scope}; const shareScope = {share_scope};
async function getInstance() {{ async function getInstance() {{
if (typeof window === 'undefined' && typeof importScripts === 'undefined') {{ if (typeof window === 'undefined' && typeof importScripts === 'undefined') {{
throw new Error(`External script loading is only supported in browser client code: ${{candidates[0]?.[1]}}`); const transport = manifestEntry ? 'Manifest' : 'External script';
throw new Error(`${{transport}} loading is only supported in browser client code: ${{manifestEntry || candidates[0]?.[1]}}`);
}} }}
return (await import({runtime_request})).instance; return (await import({runtime_request})).instance;
}} }}
...@@ -61,6 +63,15 @@ export async function get(request, fullRequest) {{ ...@@ -61,6 +63,15 @@ export async function get(request, fullRequest) {{
}} }}
const failures = []; const failures = [];
const id = `${{remoteName}}${{request === '.' ? '' : '/' + request.replace(/^\.\//, '')}}`; const id = `${{remoteName}}${{request === '.' ? '' : '/' + request.replace(/^\.\//, '')}}`;
if (manifestEntry) {{
try {{
const namespace = await instance.loadRemote(id);
if (namespace == null) throw new Error(`Remote ${{remoteName}} returned no module for ${{request}}`);
return () => namespace;
}} catch (error) {{
throw new Error(`Failed to load federated module ${{fullRequest}} via manifest: ${{error?.message || error}}`);
}}
}}
for (let index = 0; index < candidates.length; index++) {{ for (let index = 0; index < candidates.length; index++) {{
const [entryGlobalName, entry] = candidates[index]; const [entryGlobalName, entry] = candidates[index];
if (index) {{ if (index) {{
...@@ -81,6 +92,7 @@ export async function get(request, fullRequest) {{ ...@@ -81,6 +92,7 @@ export async function get(request, fullRequest) {{
}} }}
"#, "#,
candidates = StringifyJs(&candidates), candidates = StringifyJs(&candidates),
manifest_entry = StringifyJs(&remote.manifest),
remote_name = StringifyJs(&remote.request), remote_name = StringifyJs(&remote.request),
share_scope = StringifyJs(&remote.share_scope), share_scope = StringifyJs(&remote.share_scope),
runtime_request = StringifyJs(FEDERATION_RUNTIME_REQUEST), runtime_request = StringifyJs(FEDERATION_RUNTIME_REQUEST),
......
...@@ -38,7 +38,14 @@ pub async fn module_federation_runtime_source( ...@@ -38,7 +38,14 @@ pub async fn module_federation_runtime_source(
let mut remotes = Vec::new(); let mut remotes = Vec::new();
for remote in &config.remotes { for remote in &config.remotes {
if let Some(external) = remote.external.first() { if let Some(manifest) = &remote.manifest {
remotes.push(format!(
"{{name:{},entry:{},shareScope:{}}}",
StringifyJs(&remote.request),
StringifyJs(manifest),
StringifyJs(&remote.share_scope),
));
} else if let Some(external) = remote.external.first() {
remotes.push(format!( remotes.push(format!(
"{{name:{},entry:{},entryGlobalName:{},type:'var',shareScope:{}}}", "{{name:{},entry:{},entryGlobalName:{},type:'var',shareScope:{}}}",
StringifyJs(&remote.request), StringifyJs(&remote.request),
......
...@@ -37,7 +37,7 @@ fn shared_package_name(shared: &ModuleFederationShared) -> Option<RcStr> { ...@@ -37,7 +37,7 @@ fn shared_package_name(shared: &ModuleFederationShared) -> Option<RcStr> {
}) })
} }
pub(crate) async fn shared_provider_version( pub async fn shared_provider_version(
project_path: &FileSystemPath, project_path: &FileSystemPath,
shared: &ModuleFederationShared, shared: &ModuleFederationShared,
) -> Result<RcStr> { ) -> Result<RcStr> {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment