remote-components 0.3.4 → 0.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/host/html.cjs +471 -413
- package/dist/host/html.cjs.map +1 -1
- package/dist/host/html.js +471 -413
- package/dist/host/html.js.map +1 -1
- package/dist/host/nextjs/app/client-only.cjs +245 -131
- package/dist/host/nextjs/app/client-only.cjs.map +1 -1
- package/dist/host/nextjs/app/client-only.js +245 -131
- package/dist/host/nextjs/app/client-only.js.map +1 -1
- package/dist/host/nextjs/app.cjs +34 -2
- package/dist/host/nextjs/app.cjs.map +1 -1
- package/dist/host/nextjs/app.js +35 -3
- package/dist/host/nextjs/app.js.map +1 -1
- package/dist/host/react.cjs +245 -131
- package/dist/host/react.cjs.map +1 -1
- package/dist/host/react.js +245 -131
- package/dist/host/react.js.map +1 -1
- package/dist/internal/host/nextjs/app-client.cjs +38 -24
- package/dist/internal/host/nextjs/app-client.cjs.map +1 -1
- package/dist/internal/host/nextjs/app-client.js +38 -24
- package/dist/internal/host/nextjs/app-client.js.map +1 -1
- package/dist/internal/host/nextjs/remote-component-links.cjs +24 -13
- package/dist/internal/host/nextjs/remote-component-links.cjs.map +1 -1
- package/dist/internal/host/nextjs/remote-component-links.d.ts +3 -0
- package/dist/internal/host/nextjs/remote-component-links.js +24 -13
- package/dist/internal/host/nextjs/remote-component-links.js.map +1 -1
- package/dist/internal/host/shared/lifecycle.cjs +69 -0
- package/dist/internal/host/shared/lifecycle.cjs.map +1 -0
- package/dist/internal/host/shared/lifecycle.d.ts +34 -0
- package/dist/internal/host/shared/lifecycle.js +44 -0
- package/dist/internal/host/shared/lifecycle.js.map +1 -0
- package/dist/internal/host/shared/pipeline.cjs +222 -0
- package/dist/internal/host/shared/pipeline.cjs.map +1 -0
- package/dist/internal/host/shared/pipeline.d.ts +153 -0
- package/dist/internal/host/shared/pipeline.js +200 -0
- package/dist/internal/host/shared/pipeline.js.map +1 -0
- package/dist/internal/runtime/turbopack/patterns.cjs +1 -1
- package/dist/internal/runtime/turbopack/patterns.cjs.map +1 -1
- package/dist/internal/runtime/turbopack/patterns.js +1 -1
- package/dist/internal/runtime/turbopack/patterns.js.map +1 -1
- package/dist/internal/runtime/turbopack/remote-scope-setup.cjs.map +1 -1
- package/dist/internal/runtime/turbopack/remote-scope-setup.js.map +1 -1
- package/package.json +2 -2
package/dist/host/html.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/constants.ts","../../src/runtime/url/protected-rc-fallback.ts","../../src/utils/abort.ts","../../src/utils/error.ts","../../src/utils/logger.ts","../../src/utils/index.ts","../../src/runtime/constants.ts","../../src/runtime/namespace.ts","../../src/runtime/patterns.ts","../../src/runtime/turbopack/remote-scope.ts","../../src/config/webpack/apply-shared-modules.ts","../../src/config/webpack/next-client-pages-loader.ts","../../src/host/shared/remote-image-loader.ts","../../src/host/shared/polyfill.tsx","../../src/host/shared/shared-module-resolver.ts","../../src/runtime/loaders/script-loader.ts","../../src/host/html/runtime/webpack.ts","../../src/runtime/turbopack/patterns.ts","../../src/runtime/turbopack/chunk-loader.ts","../../src/runtime/turbopack/shared-modules.ts","../../src/runtime/turbopack/module.ts","../../src/runtime/turbopack/remote-scope-setup.ts","../../src/host/html/runtime/turbopack.ts","../../src/runtime/loaders/static-loader.ts","../../src/host/html/runtime/script.ts","../../src/host/html/index.tsx","../../src/host/server/fetch-with-hooks.ts","../../src/host/server/fetch-headers.ts","../../src/host/server/get-client-or-server-url.ts","../../src/host/shared/state.ts","../../src/host/utils/resolve-name-from-src.ts","../../src/runtime/html/html-spec.ts","../../src/runtime/html/rewrite-srcset.ts","../../src/runtime/html/apply-origin.ts","../../src/runtime/html/parse-remote-html.ts","../../src/runtime/metadata.ts","../../src/runtime/rsc.ts","../../src/runtime/url/resolve-client-url.ts","../../src/runtime/url/default-resolve-client-url.ts","../../src/host/html/attach-styles.ts","../../src/host/html/runtime/index.ts"],"sourcesContent":["export const RC_PROTECTED_REMOTE_FETCH_PATHNAME = '/rc-fetch-protected-remote';\n\nexport const MISSING_SHARED_MODULES_MESSAGE =\n 'Remote Components shared modules not found. Did you forget to wrap your config with `withRemoteComponentsConfig` on both host and remote?';\n\nexport const CORS_DOCS_URL =\n 'https://vercel.com/docs/remote-components/concepts/cors-external-urls#accessing-cross-site-protected-remote-components';\n","import { RC_PROTECTED_REMOTE_FETCH_PATHNAME } from '#internal/utils/constants';\n\n/**\n * Generates a fallback URL that proxies the request through the host's protected remote fetch endpoint\n */\nexport function generateProtectedRcFallbackSrc(url: string): string {\n return `${RC_PROTECTED_REMOTE_FETCH_PATHNAME}?url=${encodeURIComponent(url)}`;\n}\n\nexport function isProxiedUrl(url: string): boolean {\n try {\n return (\n new URL(url, location.href).pathname ===\n RC_PROTECTED_REMOTE_FETCH_PATHNAME\n );\n } catch {\n return false;\n }\n}\n","/**\n * Type guard to check if an error is an AbortError.\n * Handles cross-environment differences (Node.js, browsers, JSDOM).\n */\nexport function isAbortError(error: unknown): error is DOMException {\n if (error instanceof DOMException && error.name === 'AbortError') {\n return true;\n }\n\n // Handle Node.js native AbortError which may not be instanceof global DOMException\n if (\n error !== null &&\n typeof error === 'object' &&\n 'name' in error &&\n error.name === 'AbortError' &&\n 'message' in error &&\n typeof (error as { message: unknown }).message === 'string'\n ) {\n // Additional check: verify it has DOMException-like structure\n const e = error as { code?: unknown; constructor?: { name?: string } };\n return typeof e.code === 'number' || e.constructor?.name === 'DOMException';\n }\n\n return false;\n}\n","import { isProxiedUrl } from '#internal/runtime/url/protected-rc-fallback';\nimport { isAbortError } from '#internal/utils/abort';\nimport {\n CORS_DOCS_URL,\n RC_PROTECTED_REMOTE_FETCH_PATHNAME,\n} from '#internal/utils/constants';\n\nexport class RemoteComponentsError extends Error {\n code = 'REMOTE_COMPONENTS_ERROR';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'RemoteComponentsError';\n }\n}\n\nexport function multipleRemoteComponentsError(url: string | undefined) {\n return new RemoteComponentsError(\n `Multiple Remote Components found at \"${url}\". When a page exposes multiple Remote Components you must specify the \"name\" prop to select which one to load.`,\n );\n}\n\nexport function failedToFetchRemoteComponentError(\n url: string,\n { status, statusText }: { status: number; statusText: string },\n help: string = 'Is the URL correct and accessible?',\n) {\n return new RemoteComponentsError(\n `Failed to fetch Remote Component from \"${url}\". ${help}`,\n { cause: new Error(`${status} ${statusText}`) },\n );\n}\n\nexport async function errorFromFailedFetch(\n originalUrl: string,\n resolvedUrl: URL,\n res: Response | null | undefined,\n): Promise<RemoteComponentsError> {\n const isProxied = isProxiedUrl(resolvedUrl.href);\n\n if (isProxied && res) {\n const body = await res.text().catch(() => '');\n return failedProxyFetchError(\n originalUrl,\n resolvedUrl.href,\n res.status,\n body,\n );\n }\n\n const fallback = failedToFetchRemoteComponentError(\n originalUrl,\n res ?? { status: 0, statusText: 'No Response' },\n );\n\n if (!res) return fallback;\n\n try {\n const body = await res.text();\n const parser = new DOMParser();\n const doc = parser.parseFromString(body, 'text/html');\n const errorTemplate = doc.querySelector(\n 'template[data-next-error-message]',\n );\n const errorMessage = errorTemplate?.getAttribute('data-next-error-message');\n if (errorMessage) {\n const error = new RemoteComponentsError(errorMessage);\n const errorStack = errorTemplate?.getAttribute('data-next-error-stack');\n if (errorStack) {\n error.stack = errorStack;\n }\n return error;\n }\n } catch (parseError) {\n // Re-throw abort errors, ignore parse errors\n if (isAbortError(parseError)) throw parseError;\n }\n\n return fallback;\n}\n\nexport function failedProxiedAssetError(\n kind: 'chunk' | 'script',\n url: string,\n resolvedUrl: string,\n): RemoteComponentsError {\n return new RemoteComponentsError(\n `Failed to load ${kind} \"${url}\" via proxy \"${resolvedUrl}\". ` +\n `Ensure withRemoteComponentsHostProxy middleware is configured, \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" is in the matcher, ` +\n `and the remote URL is included in allowedProxyUrls. ` +\n `See: ${CORS_DOCS_URL}`,\n );\n}\n\nexport function failedProxyFetchError(\n originalUrl: string,\n proxyUrl: string,\n status: number,\n responseBody?: string,\n): RemoteComponentsError {\n if (status === 404) {\n return new RemoteComponentsError(\n `Could not proxy the request to \"${originalUrl}\" — the proxy endpoint \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" returned 404.\\n\\n` +\n `The host server needs middleware or a route that handles \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\".\\n\\n` +\n `Proxying requires two pieces:\\n` +\n ` 1. resolveClientUrl={routeThroughHostProxy} on <RemoteComponent>\\n` +\n ` 2. Middleware or a route for \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" on the host server\\n\\n` +\n `Docs: ${CORS_DOCS_URL}`,\n );\n }\n if (status === 403) {\n const detail = responseBody ? ` ${responseBody}` : '';\n return new RemoteComponentsError(\n `Proxied request to \"${proxyUrl}\" was forbidden.${detail} ` +\n `See: ${CORS_DOCS_URL}`,\n );\n }\n return new RemoteComponentsError(\n `Proxied request for \"${originalUrl}\" via \"${proxyUrl}\" failed with status ${status}. ` +\n `See: ${CORS_DOCS_URL}`,\n );\n}\n","import { CORS_DOCS_URL } from '#internal/utils/constants';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\nexport type LogLocation =\n | 'ChunkLoader'\n | 'ChunkDispatcher'\n | 'ComponentLoader'\n | 'ModuleDispatcher'\n | 'RemoteScope'\n | 'SharedModules'\n | 'WebpackRuntime'\n | 'TurbopackModule'\n | 'StaticLoader'\n | 'ScriptLoader'\n | 'Polyfill'\n | 'HtmlRemote'\n | 'HtmlHost'\n | 'Config'\n | 'NextAppRouter'\n | 'NextAppRouterCompat'\n | 'FetchRemoteComponent'\n | 'SharedModuleResolver';\n\nconst PREFIX = 'remote-components';\nconst DEBUG =\n (typeof window !== 'undefined' &&\n localStorage.getItem('RC_DEBUG') === 'true') ||\n (typeof process !== 'undefined' && process.env.RC_DEBUG === 'true');\n\nexport function logDebug(location: LogLocation, message: string) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.debug(`[${PREFIX}:${location}]: ${message}`);\n }\n}\n\nexport function logInfo(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.info(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logWarn(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.warn(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logError(\n location: LogLocation,\n message: string,\n cause?: unknown,\n) {\n // eslint-disable-next-line no-console\n console.error(\n new RemoteComponentsError(`[${PREFIX}:${location}]: ${message}`, {\n cause,\n }),\n );\n}\n\n/**\n * Logs a warning when a cross-origin asset request fails, guiding users\n * to configure the proxy middleware and resolveClientUrl on their host.\n */\nexport function warnCrossOriginFetchError(\n logLocation: LogLocation,\n url: string | URL,\n): void {\n try {\n const parsed = typeof url === 'string' ? new URL(url) : url;\n if (typeof location === 'undefined' || parsed.origin === location.origin) {\n return;\n }\n logWarn(\n logLocation,\n `Failed to fetch cross-origin resource \"${parsed.href}\". ` +\n 'To load assets from a protected deployment, two steps are required: ' +\n '(1) configure withRemoteComponentsHostProxy middleware in your host with the remote URL in allowedProxyUrls, ' +\n 'and (2) provide a resolveClientUrl prop that rewrites cross-origin asset URLs to go through the proxy. ' +\n `See: ${CORS_DOCS_URL}`,\n );\n } catch {\n // URL parsing failed — skip the warning\n }\n}\n","export function escapeString(str: string) {\n return str.replace(/[^a-z0-9]/g, '_');\n}\n\n/**\n * Computes the origin-qualified scoped name for a bundle. Same-origin\n * remotes keep the plain name; cross-origin remotes append the escaped\n * host (hostname + port) to avoid collisions between bundles that share\n * a name but are served from different origins.\n *\n * Used on both the server (to rewrite RSC flight data) and the client\n * (to create and look up RemoteScopes). Both sides must produce the\n * same value for a given remote.\n */\nexport function computeScopedName(\n name: string,\n options: { remoteHost: string; isCrossOrigin: boolean },\n): string {\n return options.isCrossOrigin\n ? `${name}_${escapeString(options.remoteHost.toLowerCase())}`\n : name;\n}\n\nexport const attrToProp = {\n fetchpriority: 'fetchPriority',\n crossorigin: 'crossOrigin',\n imagesrcset: 'imageSrcSet',\n imagesizes: 'imageSizes',\n srcset: 'srcSet',\n} as Record<string, string>;\n","import { escapeString } from '#internal/utils';\n\nexport const DEFAULT_BUNDLE_NAME = '__vercel_remote_bundle';\nexport const DEFAULT_COMPONENT_NAME = '__vercel_remote_component';\nexport const DEFAULT_ROUTE = '/';\n\nexport const RUNTIME_WEBPACK = 'webpack';\nexport const RUNTIME_TURBOPACK = 'turbopack';\nexport const RUNTIME_SCRIPT = 'script';\n\nexport function getBundleKey(bundle: string): string {\n return escapeString(bundle);\n}\n\nexport type Runtime =\n | typeof RUNTIME_WEBPACK\n | typeof RUNTIME_TURBOPACK\n | typeof RUNTIME_SCRIPT;\n","import type { RemoteScope } from '#internal/runtime/turbopack/remote-scope';\nimport type {\n GlobalScope,\n MountOrUnmountFunction,\n MountUnmountFunctions,\n} from '#internal/runtime/types';\n\n/**\n * Typed namespace for all remote-components runtime state.\n *\n * Consolidates scattered `globalThis` globals into a single object at\n * `globalThis.__remote_components__`. Each property corresponds to a\n * previously independent global — see inline `@see` tags for the original\n * global name. Code that previously read from those globals still works\n * because each migration writes through to both the namespace and the\n * legacy global (pointing at the same underlying object).\n */\nexport interface RemoteComponentsNamespace {\n /** @see `__remote_component_scopes__` */\n scopes: Map<string, RemoteScope>;\n /** @see `__remote_components_turbopack_chunk_loader_promise__` */\n chunkCache: Record<string, Promise<unknown>>;\n /** @see `__remote_script_entrypoint_mount__` */\n mountFns: Record<string, Set<MountOrUnmountFunction>>;\n /** @see `__remote_script_entrypoint_unmount__` */\n unmountFns: Record<string, Set<MountOrUnmountFunction>>;\n /** @see `__remote_bundle_url__` */\n bundleUrls: Record<string, string | URL>;\n /** @see `__rc_module_registry__` */\n moduleRegistry: Record<string, unknown>;\n /** @see `__webpack_require_type__` */\n dispatcherRuntime: string | undefined;\n /** @see `__remote_component_host_shared_modules__` */\n hostSharedModules: Record<string, () => Promise<unknown>>;\n /** @see `__remote_next_css__` */\n cssCache: Record<string, ChildNode[]>;\n /** @see `__remote_components_shadowroot_*` */\n shadowRoots: Record<string, ShadowRoot | null>;\n}\n\n/** Prefix for legacy per-key shadow root globals (`__remote_components_shadowroot_*`). */\nconst SHADOW_ROOT_PREFIX = '__remote_components_shadowroot_';\n\n/**\n * Backward-compat aliases for globals used in <=0.3.3.\n *\n * Only includes object/Map values that can be aliased by reference.\n * Primitives (`dispatcherRuntime`) must use write-through at their call sites.\n * Dynamic-key shadow root globals are adopted separately in `getNamespace()`.\n */\nconst LEGACY_ALIASES: ReadonlyArray<{\n global: string;\n prop: keyof RemoteComponentsNamespace;\n}> = [\n { global: '__remote_component_scopes__', prop: 'scopes' },\n {\n global: '__remote_components_turbopack_chunk_loader_promise__',\n prop: 'chunkCache',\n },\n { global: '__remote_script_entrypoint_mount__', prop: 'mountFns' },\n { global: '__remote_script_entrypoint_unmount__', prop: 'unmountFns' },\n { global: '__remote_bundle_url__', prop: 'bundleUrls' },\n { global: '__rc_module_registry__', prop: 'moduleRegistry' },\n {\n global: '__remote_component_host_shared_modules__',\n prop: 'hostSharedModules',\n },\n { global: '__remote_next_css__', prop: 'cssCache' },\n];\n\n/**\n * Returns the single shared `RemoteComponentsNamespace` instance, creating\n * it on first access. The namespace lives at `globalThis.__remote_components__`\n * so every module in the page shares the same state regardless of how many\n * copies of the library are loaded.\n *\n * On first initialization this function also handles backward compatibility\n * with legacy globals:\n * 1. **Adopt**: if a legacy global already exists (written by older code before\n * the namespace was created), its value becomes the initial namespace value.\n * 2. **Alias**: legacy globals are assigned to point at the namespace's objects,\n * so older code that reads the legacy global sees the same reference.\n */\nexport function getNamespace(): RemoteComponentsNamespace {\n const g = globalThis as GlobalScope & MountUnmountFunctions;\n const existing = g.__remote_components__;\n if (existing) {\n return existing;\n }\n\n const ns: RemoteComponentsNamespace = {\n scopes: new Map(),\n chunkCache: {},\n mountFns: {},\n unmountFns: {},\n bundleUrls: {},\n moduleRegistry: {},\n dispatcherRuntime: undefined,\n hostSharedModules: {},\n cssCache: {},\n shadowRoots: {},\n };\n\n // Adopt any pre-existing legacy globals, then alias them to the namespace.\n const nsRecord = ns as unknown as Record<string, unknown>;\n for (const { global, prop } of LEGACY_ALIASES) {\n const legacyValue = (g as Record<string, unknown>)[global];\n if (legacyValue != null) {\n nsRecord[prop] = legacyValue;\n }\n (g as Record<string, unknown>)[global] = ns[prop];\n }\n\n // Adopt per-key shadow root globals used in <=0.3.3\n // (e.g. `globalThis.__remote_components_shadowroot_<key> = root`).\n const gRecord = g as Record<string, unknown>;\n for (const key of Object.keys(gRecord)) {\n if (key.startsWith(SHADOW_ROOT_PREFIX)) {\n const suffix = key.slice(SHADOW_ROOT_PREFIX.length);\n ns.shadowRoots[suffix] = gRecord[key] as ShadowRoot | null;\n delete gRecord[key];\n }\n }\n\n g.__remote_components__ = ns;\n return ns;\n}\n","export const REMOTE_COMPONENT_REGEX =\n /(?<prefix>.*?)\\[(?<bundle>[^\\]]+)\\](?:%20| )(?<id>.+)/;\n\n// Matches Next.js bundle-prefixed paths like /_next/[bundle-name] /static/...\n// Used to strip the bundle identifier before loading scripts via the standard /_next/ path.\nexport const NEXT_BUNDLE_PATH_RE = /\\/_next\\/\\[.+\\](?:%20| )/;\n\n/** Collapse duplicate path separators (`//`) while preserving protocol (`://`). */\nconst DOUBLE_SLASH_RE = /(?<!:)\\/\\//g;\nexport function collapseDoubleSlashes(path: string): string {\n return path.replace(DOUBLE_SLASH_RE, '/');\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { getBundleKey, type Runtime } from '#internal/runtime/constants';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport { REMOTE_COMPONENT_REGEX } from '#internal/runtime/patterns';\nimport { computeScopedName } from '#internal/utils';\nimport { logDebug, logWarn } from '#internal/utils/logger';\n\n/**\n * Encapsulates all per-remote state so that two remotes sharing the same\n * bundle name but served from different origins never collide.\n *\n * A scope is created once per `setupRemoteScope` call and threaded\n * directly through internal code paths (chunk loading, module resolution,\n * shared modules). Global dispatchers (`__webpack_require__`,\n * `__webpack_chunk_load__`) only exist for external callers (RSC runtime)\n * and resolve the correct scope via the registry.\n */\nexport interface RemoteScope {\n /** Plain bundle name (e.g. \"remote-component-registry\") */\n name: string;\n /** Origin-qualified key — unique even when two remotes share a name */\n scopedName: string;\n /** Escaped key used as suffix for TURBOPACK_ globals */\n globalKey: string;\n /** Base URL for resolving relative chunk paths */\n url: URL;\n /** Bundler runtime type */\n runtime: Runtime;\n /** Proxy callback for routing chunks through the host */\n resolveClientUrl?: InternalResolveClientUrl;\n /** Per-scope cache of executed Turbopack module exports */\n moduleCache: Record<string, unknown>;\n /** Per-scope shared modules provided by the host (React, etc.) */\n sharedModules: Record<string, unknown>;\n /** Per-scope globalThis substitute passed to module initializers as `g` */\n moduleGlobal: Record<string, unknown>;\n /**\n * Webpack's bundle-scoped require function, populated from\n * `__remote_webpack_require__[bundleName]` for webpack remotes.\n * Undefined for turbopack remotes.\n */\n webpackRequire?: ((id: string | number) => unknown) & {\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n type?: string;\n };\n /**\n * Flat array of captured turbopack module entries: [scriptEl, id, factory, ...].\n * Populated by the push interceptor in handleTurbopackChunk. This is the\n * primary source of truth for getTurbopackModules — immune to the turbopack\n * runtime replacing the TURBOPACK global (canary builds use a deferred-loading\n * pattern that swaps the array for an immediate-processing dispatcher).\n */\n turbopackModules: unknown[];\n}\n\nfunction getRegistry(): Map<string, RemoteScope> {\n return getNamespace().scopes;\n}\n\nexport function createScope(\n name: string,\n url: URL,\n runtime: Runtime,\n resolveClientUrl?: InternalResolveClientUrl,\n): RemoteScope {\n const isCrossOrigin = url.origin !== location.origin;\n const scopedName = computeScopedName(name, {\n remoteHost: url.host,\n isCrossOrigin,\n });\n const globalKey = getBundleKey(scopedName);\n return {\n name,\n scopedName,\n globalKey,\n url,\n runtime,\n resolveClientUrl,\n moduleCache: {},\n sharedModules: {},\n moduleGlobal: {},\n turbopackModules: [],\n };\n}\n\nexport function registerScope(scope: RemoteScope): void {\n const registry = getRegistry();\n registry.set(scope.scopedName, scope);\n\n // Also register under the plain name so hosts without server-side RSC\n // rewriting (static/HTML hosts) can look up cross-origin scopes by\n // the bundle name that appears in unrewritten chunk/module IDs.\n if (scope.scopedName !== scope.name) {\n const existing = registry.get(scope.name);\n if (existing && existing.scopedName !== scope.scopedName) {\n logWarn(\n 'RemoteScope',\n `Plain name \"${scope.name}\" already registered by scope \"${existing.scopedName}\" — ` +\n `overwriting with \"${scope.scopedName}\". Static hosts will only resolve the latest one.`,\n );\n }\n registry.set(scope.name, scope);\n }\n\n logDebug(\n 'RemoteScope',\n `Registered scope \"${scope.scopedName}\" (${registry.size} total)`,\n );\n}\n\n/**\n * Resolves a scope by name. Accepts either the scoped name (used by Next.js\n * hosts that rewrite RSC data server-side) or the plain bundle name (used by\n * static/HTML hosts where chunks arrive unrewritten).\n */\nexport function getScope(name: string): RemoteScope | undefined {\n return getRegistry().get(name);\n}\n\n/** Formats a `[scopedName] path` string for use in chunk/module IDs. */\nexport function formatRemoteId(scope: RemoteScope, path: string): string {\n return `[${scope.scopedName}] ${path}`;\n}\n\n/**\n * Parses the `[bundle] path` format used in chunk/module IDs.\n * Uses REMOTE_COMPONENT_REGEX (the same pattern used by the module dispatcher\n * and script loader) so the two parsing paths can never diverge.\n */\nexport function parseRemoteId(id: string): {\n bundle: string;\n path: string;\n prefix: string;\n} {\n const groups = REMOTE_COMPONENT_REGEX.exec(id)?.groups;\n if (groups?.bundle && groups.id) {\n return {\n bundle: groups.bundle,\n path: groups.id,\n prefix: groups.prefix ?? '',\n };\n }\n return { bundle: 'default', path: id, prefix: '' };\n}\n","// Webpack shared module patching\n// used in multiple remote component host types\n// multiple host types includes: HTML custom element for remote components and Next.js host application\n// we are using this shared function to patch a Webpack module map\n// to use shared modules between the host application and the remote component\n\nimport { getScope } from '#internal/runtime/turbopack/remote-scope';\nimport { logDebug, logWarn } from '#internal/utils/logger';\n\nconst DEDUPLICATION_SKIPPED =\n 'shared module deduplication skipped. The remote may load its own copy of shared dependencies.';\n\nexport function applySharedModules(\n bundle: string,\n resolve: Record<string, unknown>,\n) {\n logDebug(\n 'SharedModules',\n `applySharedModules called for bundle: \"${bundle}\"`,\n );\n logDebug(\n 'SharedModules',\n `Shared modules to resolve: ${Object.keys(resolve)}`,\n );\n\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string) => unknown) & {\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n } & Record<string, string[]>;\n\n // Prefer scope-based access when available.\n const scope = getScope(bundle);\n // @legacy(v0.3.4) — fall back to global __remote_webpack_require__ for hosts that\n // haven't run setupWebpackRuntime yet (e.g. HTML host's inline path).\n // Remove once all host types go through the shared pipeline (Phase 5).\n const webpackBundle =\n scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];\n\n if (webpackBundle) {\n const modulePaths = Object.keys(\n self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {},\n );\n logDebug(\n 'SharedModules',\n `Available module paths for bundle \"${bundle}\": ${modulePaths}`,\n );\n\n // patch all modules in the bundle to use the shared modules\n for (const [key, value] of Object.entries(resolve)) {\n const exactIds = modulePaths.filter((p) => p === key);\n const ids =\n exactIds.length > 0\n ? exactIds\n : modulePaths.filter((p) => p.includes(key));\n\n if (ids.length === 0) {\n logDebug(\n 'SharedModules',\n `No matching module path found for shared module \"${key}\"`,\n );\n }\n\n for (const id of ids) {\n if (webpackBundle.m) {\n // if we have a module map, we need to use the mapped id\n // this is required for production builds where the module ids are module id numbers\n const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id]\n ? `${self.__remote_webpack_module_map__[bundle][id]}`\n : id;\n if (resolvedId !== id) {\n logDebug(\n 'SharedModules',\n `Mapped module id: \"${id}\" -> \"${resolvedId}\"`,\n );\n }\n // create a mock module which exports the shared module\n webpackBundle.m[resolvedId] = (module) => {\n module.exports = value;\n };\n } else {\n logWarn(\n 'SharedModules',\n `webpackBundle.m is not available for bundle \"${bundle}\" — ${DEDUPLICATION_SKIPPED}`,\n );\n }\n }\n }\n } else {\n logWarn(\n 'SharedModules',\n `No webpack require found for bundle \"${bundle}\" — ${DEDUPLICATION_SKIPPED}`,\n );\n logDebug(\n 'SharedModules',\n `Available bundles: ${Object.keys(self.__remote_webpack_require__ ?? {})}`,\n );\n }\n}\n","import { getNamespace } from '#internal/runtime/namespace';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\n// module loader for Next.js Pages Router\nexport function nextClientPagesLoader(\n bundle: string,\n route: string,\n styleContainer: HTMLHeadElement | ShadowRoot | null = document.head,\n) {\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string | number) => unknown) & {\n c?: Record<\n string | number,\n { id: string; parents: string[]; children: string[] }\n >;\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n type?: 'turbopack' | 'webpack';\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n // Next.js client pages loader reference storage\n __NEXT_P?: [\n (\n | [\n string,\n () => { default?: React.ComponentType<Record<string, unknown>> },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n ];\n };\n\n // temporarily remove the original Next.js CSS loader\n const nextCssOriginal = document.querySelector(\n `[id=\"__next_css__DO_NOT_USE__\"]:not([data-bundle=\"${bundle}\"][data-route=\"${route}\"])`,\n );\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.removeChild(nextCssOriginal);\n }\n\n // create a new Next.js CSS loader element\n const nextCss = document.createElement('noscript');\n nextCss.id = '__next_css__DO_NOT_USE__';\n nextCss.setAttribute('data-bundle', bundle);\n nextCss.setAttribute('data-route', route);\n const nextCssEnd = document.createElement('noscript');\n nextCssEnd.id = '__next_css__DO_NOT_USE_END__';\n nextCssEnd.setAttribute('data-bundle', bundle);\n nextCssEnd.setAttribute('data-route', route);\n document.head.appendChild(nextCssEnd);\n document.head.appendChild(nextCss);\n\n // find the page component loader chunk\n const componentLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}!`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}!`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // find the app loader chunk\n const appLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // if we didn't find the component loader or app loader, throw an error\n if (!(componentLoaderChunk && appLoaderChunk)) {\n throw new RemoteComponentsError(\n `Next.js client pages loader not found in bundle \"${bundle}\".`,\n );\n }\n\n // temporarily store the original __NEXT_P reference\n // this is required to avoid conflicts with the Next.js client pages loader\n // which uses the same global variable to store the page components\n const __NEXT_P_ORIGINAL = self.__NEXT_P;\n const selfOriginal = self;\n delete selfOriginal.__NEXT_P;\n\n // load the component and app loader chunks\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? componentLoaderChunk\n : `[${bundle}] ${componentLoaderChunk}`,\n );\n if (\n typeof appLoaderChunk === 'string' ||\n (typeof appLoaderChunk === 'number' && appLoaderChunk !== -1)\n ) {\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? appLoaderChunk\n : `[${bundle}] ${appLoaderChunk}`,\n );\n }\n\n // if we have the __NEXT_P global variable, we can extract the component and app\n if (self.__NEXT_P) {\n const [, componentLoader] = self.__NEXT_P[0] ?? [\n undefined,\n () => ({ default: null }),\n ];\n const [, appLoader] = self.__NEXT_P[2] ?? [\n undefined,\n () => ({\n default: null,\n }),\n ];\n const { default: Component } = componentLoader();\n const { default: App } = appLoader();\n\n const cssCache = getNamespace().cssCache;\n\n if (!cssCache[bundle]) {\n // load the CSS files from the remote bundle\n const cssRE = /\\.s?css$/;\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {})\n .filter((id) => cssRE.test(id))\n .forEach((id) => {\n self.__remote_webpack_require__?.[bundle]?.(id);\n });\n\n Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {})\n .filter((path) => cssRE.test(path))\n .forEach((path) => {\n const id = self.__remote_webpack_module_map__?.[bundle]?.[path];\n if (id) {\n self.__remote_webpack_require__?.[bundle]?.(id);\n }\n });\n\n const elements = [];\n let node = nextCss.previousSibling;\n while (node && node !== nextCssEnd) {\n elements.push(node);\n node.remove();\n node = nextCss.previousSibling;\n }\n cssCache[bundle] = elements;\n }\n\n // if the styleContainer is provided, we need to move the styles to it\n if (styleContainer) {\n const elements = cssCache[bundle];\n elements.forEach((el) => {\n styleContainer.appendChild(el.cloneNode(true));\n });\n } else {\n // if no styleContainer is provided, we need to move the styles back to the head\n const elements = cssCache[bundle];\n elements.forEach((el) => {\n document.head.appendChild(el);\n });\n }\n\n // restore the original __NEXT_P reference\n delete self.__NEXT_P;\n self.__NEXT_P = __NEXT_P_ORIGINAL;\n\n // restore the original Next.js CSS loader\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.appendChild(nextCssOriginal);\n }\n\n nextCss.remove();\n nextCssEnd.remove();\n\n return { Component, App };\n }\n\n return { Component: null, App: null };\n}\n","import { getScope } from '#internal/runtime/turbopack/remote-scope';\nimport type { InternalResolveClientUrl } from '#internal/runtime/url/resolve-client-url';\n\n/**\n * Replacement for `next/dist/shared/lib/image-loader`.\n *\n * Uses `config.path` (which includes the remote's asset prefix, e.g.\n * `/vc-ap-xxx/_next/image`) to generate URLs that match the server-rendered\n * HTML and avoid hydration mismatches. Under the microfrontends proxy these\n * relative paths are routed to the correct app.\n *\n * For cross-origin deployments (standalone host on a different domain),\n * `config.path` is a relative path that would incorrectly resolve to the host\n * origin, so we prefix it with the remote origin to produce an absolute URL\n * pointing at the remote's optimizer.\n *\n * When `resolveClientUrl` is provided (deployment protection), the final URL\n * is routed through the host's proxy.\n */\nexport function createRemoteImageLoader(\n bundle: string,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n const loader = Object.assign(\n ({\n config,\n src,\n width,\n quality,\n }: {\n config: { path?: string };\n src: string;\n width: number;\n quality?: number;\n }) => {\n const q = quality ?? 75;\n const remoteOrigin = getScope(bundle)?.url.origin ?? '';\n const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;\n const basePath = isCrossOrigin\n ? `${remoteOrigin}${config.path ?? '/_next/image'}`\n : (config.path ?? `${remoteOrigin}/_next/image`);\n const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;\n return resolveClientUrl?.(url) ?? url;\n },\n // Signals to getImgProps that this is a default loader (not a user-defined\n // one), enabling srcSet generation with device/image sizes from the config.\n { __next_img_default: true as const },\n );\n return loader;\n}\n","import type { LinkProps } from 'next/link';\nimport { createRemoteImageLoader } from '#internal/host/shared/remote-image-loader';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport type { InternalResolveClientUrl } from '#internal/runtime/url/resolve-client-url';\nimport { logWarn } from '#internal/utils/logger';\n\n// polyfill Next.js App Router client API (minimal)\n// implementations are minimal and do not cover all use cases\n// developer can override these shared modules from configuration\nexport function sharedPolyfills(\n shared?: Record<string, () => Promise<unknown>>,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n const hostShared = getNamespace().hostSharedModules;\n const polyfill = {\n 'next/dist/client/components/navigation':\n hostShared['next/navigation'] ??\n shared?.['next/navigation'] ??\n (() =>\n Promise.resolve({\n useRouter() {\n return {\n push: (routerUrl: string) => {\n history.pushState({}, '', routerUrl);\n },\n replace: (routerUrl: string) => {\n history.replaceState({}, '', routerUrl);\n },\n back: () => {\n history.back();\n },\n };\n },\n usePathname() {\n return location.pathname;\n },\n useParams() {\n return {};\n },\n useSearchParams() {\n return new URLSearchParams(location.search);\n },\n useSelectedLayoutSegment() {\n return null;\n },\n useSelectedLayoutSegments() {\n return [];\n },\n __esModule: true,\n })),\n 'next/dist/client/app-dir/link':\n hostShared['next/link'] ??\n shared?.['next/link'] ??\n (() =>\n Promise.resolve({\n default: ({\n scroll: _,\n replace,\n prefetch,\n onNavigate,\n children,\n ...props\n }: React.PropsWithChildren<LinkProps>) => {\n if (prefetch) {\n logWarn(\n 'Polyfill',\n 'Next.js Link prefetch is not supported in remote components',\n );\n }\n return (\n <a\n {...props}\n href={props.href as string}\n onClick={(e) => {\n e.preventDefault();\n let preventDefaulted = false;\n e.preventDefault = () => {\n preventDefaulted = true;\n e.defaultPrevented = true;\n };\n if (typeof props.onClick === 'function') {\n props.onClick(e);\n }\n onNavigate?.(e);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (preventDefaulted) {\n return;\n }\n if (replace) {\n history.replaceState({}, '', props.href as string);\n } else {\n history.pushState({}, '', props.href as string);\n }\n }}\n suppressHydrationWarning\n >\n {children ?? null}\n </a>\n );\n },\n useLinkStatus() {\n return { pending: false };\n },\n __esModule: true,\n })),\n 'next/dist/client/app-dir/form':\n hostShared['next/form'] ??\n shared?.['next/form'] ??\n (() =>\n Promise.resolve({\n default: () => {\n // TODO: implement <Form> component for non-Next.js host applications\n throw new Error('Next.js <Form> component not implemented');\n },\n __esModule: true,\n })),\n // Instead of replacing next/image entirely, we let the real Next.js Image\n // component load from the remote bundle and only replace its default loader.\n // This gives us full next/image fidelity (fill, priority, srcSet, blur\n // placeholders, error handling) while routing image optimization through the\n // remote app's /_next/image endpoint.\n 'next/dist/shared/lib/image-loader':\n hostShared['next/dist/shared/lib/image-loader'] ??\n shared?.['next/dist/shared/lib/image-loader'] ??\n ((bundle: string) =>\n Promise.resolve({\n default: createRemoteImageLoader(bundle, resolveClientUrl),\n __esModule: true,\n })),\n 'next/dist/client/script':\n hostShared['next/script'] ??\n shared?.['next/script'] ??\n (() =>\n Promise.resolve({\n // TODO: implement <Script> component for non-Next.js host applications\n // do not throw an error for now\n default: () => null,\n __esModule: true,\n })),\n 'next/router':\n hostShared['next/router'] ??\n shared?.['next/router'] ??\n (() =>\n // TODO: incomplete implementation\n Promise.resolve({\n useRouter() {\n return {\n push: (routerUrl: string) => {\n history.pushState({}, '', routerUrl);\n },\n replace: (routerUrl: string) => {\n history.replaceState({}, '', routerUrl);\n },\n back: () => {\n history.back();\n },\n };\n },\n __esModule: true,\n })),\n 'next/dist/build/polyfills/process': () =>\n Promise.resolve({\n default: {\n env: {\n NODE_ENV: 'production',\n },\n },\n __esModule: true,\n }),\n } as Record<string, () => Promise<unknown>>;\n\n polyfill['next/navigation'] = polyfill[\n 'next/dist/client/components/navigation'\n ] as () => Promise<unknown>;\n polyfill['next/link'] = polyfill[\n 'next/dist/client/app-dir/link'\n ] as () => Promise<unknown>;\n polyfill['next/form'] = polyfill[\n 'next/dist/client/app-dir/form'\n ] as () => Promise<unknown>;\n polyfill['next/dist/esm/shared/lib/image-loader'] = polyfill[\n 'next/dist/shared/lib/image-loader'\n ] as () => Promise<unknown>;\n polyfill['next/script'] = polyfill[\n 'next/dist/client/script'\n ] as () => Promise<unknown>;\n\n return polyfill;\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { sharedPolyfills } from '#internal/host/shared/polyfill';\nimport type { LogLocation } from '#internal/utils/logger';\nimport { logDebug } from '#internal/utils/logger';\n\n/**\n * The core React packages that are always shared between host and remote.\n * These correspond to the `/react/*.js` and `/react-dom/*.js` path keys\n * used in the webpack module resolution map.\n */\nexport const CORE_REACT_SHARED_KEYS = [\n 'react',\n 'react/jsx-dev-runtime',\n 'react/jsx-runtime',\n 'react-dom',\n 'react-dom/client',\n] as const;\n\n/**\n * Maps each core React package to its webpack-style path key.\n * For example, `react` maps to `/react/index.js`.\n */\nexport const CORE_REACT_PATH_MAP: Record<string, string> = {\n react: '/react/index.js',\n 'react/jsx-dev-runtime': '/react/jsx-dev-runtime.js',\n 'react/jsx-runtime': '/react/jsx-runtime.js',\n 'react-dom': '/react-dom/index.js',\n 'react-dom/client': '/react-dom/client.js',\n};\n\n/**\n * The vendorShared record used by the Next.js config to map React packages\n * to their webpack path-key string literals. Derived from CORE_REACT_PATH_MAP\n * but excludes `react-dom/client` to match the existing config behavior.\n */\nexport const VENDOR_SHARED: Record<string, string> = Object.fromEntries(\n Object.entries(CORE_REACT_PATH_MAP)\n .filter(([key]) => key !== 'react-dom/client')\n .map(([key, path]) => [key, `'${path}'`]),\n);\n\ntype SharedModuleFactory = (bundle?: string) => Promise<unknown>;\n\n/**\n * Builds the `coreShared` map for the Turbopack runtime's\n * `initializeSharedModules`. Each entry is an async factory that dynamically\n * imports the corresponding React package. User-provided shared modules\n * override core entries (e.g. to supply a pinned React version).\n */\nexport function buildCoreShared(\n userShared?: Record<string, SharedModuleFactory>,\n): Record<string, SharedModuleFactory> {\n return {\n react: async () => (await import('react')).default,\n 'react-dom': async () => (await import('react-dom')).default,\n 'react/jsx-dev-runtime': async () =>\n (await import('react/jsx-dev-runtime')).default,\n 'react/jsx-runtime': async () =>\n (await import('react/jsx-runtime')).default,\n 'react-dom/client': async () => (await import('react-dom/client')).default,\n ...userShared,\n };\n}\n\ninterface HostSharedGlobals {\n __remote_component_host_shared_modules__?: Record<\n string,\n SharedModuleFactory\n >;\n __remote_component_shared__?: Record<string, SharedModuleFactory>;\n}\n\n/**\n * Builds the merged host shared modules map with a consistent merge priority:\n * 1. Polyfills (lowest priority — fallback implementations)\n * 2. Global host shared modules (`__remote_component_host_shared_modules__`)\n * 3. User-provided shared modules (highest priority — explicit overrides)\n *\n * Some callers also include `__remote_component_shared__` (the pages router\n * global). Pass `includeRemoteComponentShared: true` to include it at the end.\n */\nexport function buildHostShared(\n userShared?: Record<string, SharedModuleFactory>,\n resolveClientUrl?: InternalResolveClientUrl,\n options?: { includeRemoteComponentShared?: boolean },\n): Record<string, SharedModuleFactory> {\n const self = globalThis as typeof globalThis & HostSharedGlobals;\n const result: Record<string, SharedModuleFactory> = {\n ...sharedPolyfills(userShared, resolveClientUrl),\n ...self.__remote_component_host_shared_modules__,\n ...userShared,\n };\n if (options?.includeRemoteComponentShared) {\n Object.assign(result, self.__remote_component_shared__);\n }\n return result;\n}\n\n/**\n * React module instances keyed by their webpack path, e.g.\n * `{ '/react/index.js': React }`. Passed into `buildWebpackResolve` so it\n * can populate the resolve map without importing React itself.\n */\nexport interface ReactModules {\n '/react/index.js': unknown;\n '/react/jsx-dev-runtime.js': unknown;\n '/react/jsx-runtime.js': unknown;\n '/react-dom/index.js': unknown;\n '/react-dom/client.js': unknown;\n}\n\n/**\n * Builds the `resolve` map passed to `applySharedModules` for the webpack\n * runtime. Combines:\n * - Static React module path keys (`/react/index.js`, etc.)\n * - Remote shared modules matched against host shared, with `(ssr)/` prefix stripped\n *\n * After building the map, resolves any factory functions by awaiting them\n * with the given bundle name.\n */\nexport async function buildWebpackResolve(\n hostShared: Record<string, SharedModuleFactory | unknown>,\n remoteShared: Record<string, string | number>,\n bundle: string,\n reactModules: ReactModules,\n callerTag: LogLocation = 'SharedModuleResolver',\n): Promise<Record<string, unknown>> {\n const resolve: Record<string, unknown> = {\n ...reactModules,\n ...Object.entries(remoteShared).reduce<Record<string, unknown>>(\n (acc, [key, value]) => {\n if (typeof hostShared[value] !== 'undefined') {\n acc[key.replace(/^\\(ssr\\)\\/(?<relative>\\.\\/)?/, '')] =\n hostShared[value];\n } else {\n logDebug(\n callerTag,\n `Remote requests \"${value}\" but host doesn't provide it`,\n );\n }\n return acc;\n },\n {},\n ),\n };\n await Promise.all(\n Object.entries(resolve).map(async ([key, value]) => {\n if (typeof value === 'function') {\n resolve[key] = await value(bundle);\n }\n return Promise.resolve(value);\n }),\n );\n return resolve;\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { NEXT_BUNDLE_PATH_RE } from '#internal/runtime/patterns';\nimport { isProxiedUrl } from '#internal/runtime/url/protected-rc-fallback';\nimport {\n failedProxiedAssetError,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport { warnCrossOriginFetchError } from '#internal/utils/logger';\n\n/**\n * Loads external scripts for remote components\n */\nexport async function loadScripts(\n scripts: { src: string }[],\n resolveClientUrl?: InternalResolveClientUrl,\n): Promise<void> {\n await Promise.all(\n scripts.map((script) => {\n return new Promise<void>((resolve, reject) => {\n const newSrc = new URL(\n // remove the remote component bundle name identifier from the script src\n script.src.replace(NEXT_BUNDLE_PATH_RE, '/_next/'),\n location.origin,\n ).href;\n\n const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;\n\n const alreadyLoaded = Array.from(\n document.querySelectorAll<HTMLScriptElement>('script[src]'),\n ).some((s) => s.src === resolvedSrc);\n if (alreadyLoaded) {\n resolve();\n return;\n }\n\n const newScript = document.createElement('script');\n newScript.onload = () => resolve();\n newScript.onerror = () => {\n const isProxied = isProxiedUrl(resolvedSrc);\n if (isProxied) {\n reject(failedProxiedAssetError('script', newSrc, resolvedSrc));\n } else {\n warnCrossOriginFetchError('ScriptLoader', newSrc);\n reject(\n new RemoteComponentsError(\n `Failed to load <script src=\"${newSrc}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n }\n };\n newScript.src = resolvedSrc;\n newScript.async = true;\n document.head.appendChild(newScript);\n });\n }),\n );\n}\n","import { applySharedModules } from '#internal/config/webpack/apply-shared-modules';\nimport { nextClientPagesLoader } from '#internal/config/webpack/next-client-pages-loader';\nimport type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n buildHostShared,\n buildWebpackResolve,\n} from '#internal/host/shared/shared-module-resolver';\nimport { loadScripts } from '#internal/runtime/loaders/script-loader';\nimport { NEXT_BUNDLE_PATH_RE } from '#internal/runtime/patterns';\nimport type { MountUnmountFunctions, RSCKey } from '#internal/runtime/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\n// initializer for the webpack runtime to be able to access modules\n// required to run exposed client components of the remote component\nexport async function webpackRuntime(\n bundle: string,\n shared?: Record<string, () => Promise<unknown>>,\n remoteShared?: Record<string, string | number>,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack runtime globals\n __webpack_require__: (remoteId: string) => unknown;\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string) => unknown) & {\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n // conditional flag to disable webpack exec\n __DISABLE_WEBPACK_EXEC__?: Record<string, boolean>;\n // webpack chunk loading function\n __webpack_chunk_load__: () => Promise<[]>;\n __webpack_require_type__: 'webpack' | 'turbopack';\n } & MountUnmountFunctions &\n Record<RSCKey, string[]>;\n\n // disable webpack exec to prevent automatically executing the entry module\n if (!self.__DISABLE_WEBPACK_EXEC__) {\n self.__DISABLE_WEBPACK_EXEC__ = {};\n }\n self.__DISABLE_WEBPACK_EXEC__[bundle] = true;\n // add a custom webpack require function to load remote components from multiple bundles / zones\n if (\n typeof self.__webpack_require__ !== 'function' &&\n self.__webpack_require_type__ !== 'turbopack'\n ) {\n self.__webpack_require__ = (remoteId: string) => {\n const re = /\\[(?<bundle>[^\\]]+)\\] (?<id>.*)/;\n const match = re.exec(remoteId);\n const remoteBundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && remoteBundle)) {\n throw new RemoteComponentsError(\n `Remote Component module \"${remoteId}\" not found. Did you forget to wrap the Next.js config with \\`withRemoteComponentsConfig\\` on both host and remote?`,\n );\n }\n if (\n typeof self.__remote_webpack_require__?.[remoteBundle] !== 'function'\n ) {\n throw new RemoteComponentsError(\n `Remote Components are not available in \"${remoteBundle}\". Did you forget to wrap the Next.js config with \\`withRemoteComponentsConfig\\` on both host and remote?`,\n );\n }\n return self.__remote_webpack_require__[remoteBundle](id);\n };\n // not used but required by react-server-dom-webpack\n self.__webpack_chunk_load__ = () => {\n return Promise.resolve([]);\n };\n }\n // we can only import react-server-dom-webpack after initializing the __webpack_require__ and __webpack_chunk_load__ functions\n const {\n default: { createFromReadableStream },\n } = await import('react-server-dom-webpack/client.browser');\n\n async function preloadScripts(\n scripts: HTMLScriptElement[],\n url: URL,\n remoteBundle: string,\n _: string,\n ) {\n // Build absolute src URLs for each script and remove originals from the\n // parsed doc to prevent re-execution when the doc is later inserted into\n // the shadow DOM.\n const scriptSrcs = scripts.flatMap((script) => {\n const scriptSrc =\n script.getAttribute('src') || script.getAttribute('data-src');\n script.parentElement?.removeChild(script);\n if (!scriptSrc) return [];\n return [\n {\n src: new URL(scriptSrc.replace(NEXT_BUNDLE_PATH_RE, '/_next/'), url)\n .href,\n },\n ];\n });\n\n await loadScripts(scriptSrcs, resolveClientUrl);\n\n const hostShared = buildHostShared(shared, resolveClientUrl);\n const resolve = await buildWebpackResolve(\n hostShared,\n remoteShared ?? {},\n remoteBundle,\n {\n '/react/index.js': (await import('react')).default,\n '/react/jsx-dev-runtime.js': (await import('react/jsx-dev-runtime'))\n .default,\n '/react/jsx-runtime.js': (await import('react/jsx-runtime')).default,\n '/react-dom/index.js': (await import('react-dom')).default,\n '/react-dom/client.js': (await import('react-dom/client')).default,\n },\n 'WebpackRuntime',\n );\n\n // apply shared modules to the bundle\n applySharedModules(remoteBundle, resolve);\n }\n\n return {\n self,\n createFromReadableStream,\n applySharedModules,\n nextClientPagesLoader,\n preloadScripts,\n };\n}\n","/**\n * Regex patterns for parsing Turbopack's minified and development code.\n *\n * Turbopack outputs different variable names in dev vs production builds:\n * - Development: __turbopack_context__, parentImport, chunk, self\n * - Minified: e, t, etc.\n *\n * Module IDs are numeric in Next.js 16+ (e.g. `984803`) but full string paths in\n * Next.js 15.x dev mode (e.g. `\"[project]/.../react/index.js [app-client] (ecmascript)\"`).\n * ID-capturing patterns match `\"quoted string\"|digits` via the shared\n * `MODULE_ID_PATTERN` fragment. Use `extractGroup()` to both match and strip quotes\n * in one step.\n */\n\n/** Reusable fragment that matches a turbopack module ID: quoted string or numeric. */\nconst MODULE_ID_PATTERN = '\"[^\"]+\"|[0-9]+';\n\n/** Strips surrounding double-quotes from a captured regex value. */\nfunction stripQuotes(value: string): string {\n if (value.startsWith('\"') && value.endsWith('\"')) {\n return value.slice(1, -1);\n }\n return value;\n}\n\n/**\n * Runs a regex against `input` and returns the named capture group with\n * quotes stripped, or `undefined` if there's no match.\n */\nexport function extractGroup(\n re: RegExp,\n input: string,\n group: string,\n): string | undefined {\n const raw = re.exec(input)?.groups?.[group];\n return raw ? stripQuotes(raw) : undefined;\n}\n\n/**\n * Matches: self.TURBOPACK_REMOTE_SHARED or e.TURBOPACK_REMOTE_SHARED\n *\n * @example\n * // Development:\n * \"self.TURBOPACK_REMOTE_SHARED=await __turbopack_context__.A(984803)\"\n *\n * // Minified:\n * \"e.TURBOPACK_REMOTE_SHARED=await e.A(984803)\"\n */\nexport const REMOTE_SHARED_MARKER_RE =\n /(?:self|[a-z])\\.TURBOPACK_REMOTE_SHARED/;\n\n/**\n * Extracts the module ID from a TURBOPACK_REMOTE_SHARED assignment.\n *\n * Captures:\n * - `sharedModuleId`: The module ID (may be quoted for string paths).\n *\n * @example\n * // Next.js 16:\n * \"self.TURBOPACK_REMOTE_SHARED=await __turbopack_context__.A(984803)\"\n * // -> sharedModuleId = \"984803\"\n *\n * // Next.js 15.x (string IDs, spaces around `=`):\n * 'self.TURBOPACK_REMOTE_SHARED = await __turbopack_context__.A(\"[project]/...app-remote.tsx [app-client] (ecmascript, async loader)\")'\n * // -> sharedModuleId = \"[project]/...app-remote.tsx [app-client] (ecmascript, async loader)\"\n *\n * // Minified:\n * \"t.TURBOPACK_REMOTE_SHARED=await e.A(123456)\"\n * // -> sharedModuleId = \"123456\"\n */\nexport const REMOTE_SHARED_ASSIGNMENT_RE = new RegExp(\n `\\\\.TURBOPACK_REMOTE_SHARED\\\\s*=\\\\s*await (?:__turbopack_context__|[a-z])\\\\.A\\\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\\\)`,\n);\n\n/**\n * Matches async module loader calls: ctx.A(moduleId)\n *\n * Captures:\n * - `asyncSharedModuleId`: The module ID (may be quoted).\n *\n * @example\n * // Next.js 16:\n * \"() => __turbopack_context__.A(460400)\"\n * // -> asyncSharedModuleId = \"460400\"\n *\n * // Next.js 15.x:\n * '() => __turbopack_context__.A(\"[project]/.../react/index.js [app-client] (ecmascript, async loader)\")'\n * // -> asyncSharedModuleId = \"[project]/.../react/index.js [app-client] (ecmascript, async loader)\"\n *\n * // Minified:\n * \"() => e.A(460400)\"\n * // -> asyncSharedModuleId = \"460400\"\n */\nexport const ASYNC_MODULE_LOADER_RE = new RegExp(\n `(?:__turbopack_context__|e)\\\\.A\\\\((?<asyncSharedModuleId>${MODULE_ID_PATTERN})\\\\)`,\n);\n\n/**\n * Extracts the final module ID from an async module `.v()` callback.\n * The callback always ends by calling its argument (parentImport / single-letter\n * variable) with the real module ID. This matches that final call regardless of\n * surrounding structure (whitespace, `return` statements, block vs expression bodies).\n *\n * Handles both Promise.resolve (no extra chunks) and Promise.all (with chunks).\n *\n * Captures:\n * - `sharedModuleId`: The module ID (may be quoted).\n *\n * @example\n * // Next.js 16 minified (Promise.resolve):\n * \"e=>{e.v(e=>Promise.resolve().then(()=>e(633334)))}\"\n * // -> sharedModuleId = \"633334\"\n *\n * // Next.js 16 minified (Promise.all):\n * \"e=>{e.v(t=>Promise.all([\\\"chunk.js\\\"].map(t=>e.l(t))).then(()=>t(633334)))}\"\n * // -> sharedModuleId = \"633334\"\n *\n * // Next.js 15.x development (multi-line):\n * '(__turbopack_context__) => {\\n__turbopack_context__.v((parentImport) => {\\n return Promise.resolve().then(() => {\\n return parentImport(\"[project]/.../react/index.js [app-client] (ecmascript)\");\\n });\\n});\\n}'\n * // -> sharedModuleId = \"[project]/.../react/index.js [app-client] (ecmascript)\"\n */\nexport const ASYNC_MODULE_CALLBACK_RE = new RegExp(\n `(?:parentImport|[a-z])\\\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\\\)`,\n);\n\n/**\n * Detects Turbopack runtime global usage in a chunk.\n *\n * Matches either dot-notation or bracket-notation access off `globalThis` or `self`:\n * - globalThis.TURBOPACK / self.TURBOPACK\n * - globalThis[\"TURBOPACK\"] / self['TURBOPACK'] (whitespace tolerated)\n */\nexport const TURBOPACK_GLOBAL_RE =\n /(?:globalThis|self)\\s*(?:\\.TURBOPACK|\\[\\s*[\"']TURBOPACK[\"']\\s*\\])/;\n","import { RUNTIME_WEBPACK } from '#internal/runtime/constants';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport { collapseDoubleSlashes } from '#internal/runtime/patterns';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { isProxiedUrl } from '#internal/runtime/url/protected-rc-fallback';\nimport {\n failedProxiedAssetError,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport {\n logDebug,\n logWarn,\n warnCrossOriginFetchError,\n} from '#internal/utils/logger';\nimport { TURBOPACK_GLOBAL_RE } from './patterns';\nimport {\n formatRemoteId,\n getScope,\n parseRemoteId,\n type RemoteScope,\n} from './remote-scope';\n\n/**\n * Loads a chunk using a specific scope. All state (base URL, proxy callback,\n * TURBOPACK global key) comes from the scope — no global lookups needed.\n *\n * This is the primary chunk loader called directly from:\n * - setupRemoteScope (initial chunks)\n * - TurbopackContext.l (module-level chunk loading)\n * - handleTurbopackChunk (CHUNK_LIST additional chunks)\n *\n * The global chunk dedup cache is keyed by absolute URL, so different origins\n * naturally get separate cache entries even when sharing a bundle name.\n */\nexport function loadChunkWithScope(\n scope: RemoteScope,\n chunkId: string,\n): Promise<unknown> | undefined {\n logDebug(\n 'ChunkLoader',\n `loadChunkWithScope: \"${chunkId}\" (scope: \"${scope.scopedName}\")`,\n );\n const self = globalThis as GlobalScope;\n const ns = getNamespace();\n\n const { bundle, path, prefix } = parseRemoteId(chunkId);\n\n // Skip webpack runtime chunks\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : scope.runtime;\n if (remoteRuntime === RUNTIME_WEBPACK) {\n return Promise.resolve(undefined);\n }\n\n const rawPath = path ? collapseDoubleSlashes(`${prefix}${path}`) : '/';\n const url = new URL(rawPath, scope.url).href;\n\n if (url.endsWith('.css')) {\n return;\n }\n\n if (ns.chunkCache[url]) {\n logDebug('ChunkLoader', `Cache hit for \"${chunkId}\" (url=\"${url}\")`);\n return ns.chunkCache[url];\n }\n\n const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;\n if (resolvedUrl !== url) {\n logDebug('ChunkLoader', `Proxied chunk URL: \"${url}\" → \"${resolvedUrl}\"`);\n }\n\n ns.chunkCache[url] = new Promise((resolve, reject) => {\n fetch(resolvedUrl)\n .then((res) => res.text())\n .then((code) => {\n const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);\n if (hasTurbopack) {\n return handleTurbopackChunk(code, scope, url);\n }\n // Chunk doesn't contain Turbopack globals — nothing to process\n })\n .then(resolve)\n .catch((error) => {\n const isProxied = isProxiedUrl(resolvedUrl);\n if (isProxied) {\n reject(failedProxiedAssetError('chunk', url, resolvedUrl));\n } else {\n warnCrossOriginFetchError('ChunkLoader', url);\n reject(error);\n }\n });\n });\n\n return ns.chunkCache[url];\n}\n\n/**\n * Creates the global `__webpack_chunk_load__` dispatcher.\n * This is a thin wrapper called only by external code (React's RSC runtime).\n * It parses the chunkId, resolves the correct scope, and delegates to\n * `loadChunkWithScope`.\n */\nexport function createChunkDispatcher(): (\n chunkId: string,\n scriptBundle?: string,\n) => Promise<unknown> | undefined {\n return function __chunk_dispatcher__(chunkId: string, scriptBundle?: string) {\n logDebug('ChunkDispatcher', `Dispatching chunk: \"${chunkId}\"`);\n\n const { bundle } = parseRemoteId(chunkId);\n const bundleName = bundle || scriptBundle || 'default';\n\n // Works with both the scoped name (Next.js hosts with server-side\n // rewriting) and the plain bundle name (static/HTML hosts).\n const scope = getScope(bundleName);\n\n logDebug(\n 'ChunkDispatcher',\n `Scope resolution: bundle=\"${bundleName}\", scope=${scope?.scopedName ?? 'null'}`,\n );\n\n if (!scope) {\n logWarn('ChunkDispatcher', `No scope found for bundle \"${bundleName}\"`);\n return Promise.resolve(undefined);\n }\n\n return loadChunkWithScope(scope, chunkId);\n };\n}\n\n/**\n * Handles Turbopack chunk loading by transforming the chunk code to isolate\n * global variables per bundle and dynamically loading the transformed script.\n * Receives scope directly — no global state lookups needed.\n */\nasync function handleTurbopackChunk(\n code: string,\n scope: RemoteScope,\n url: string,\n): Promise<void> {\n // skip this chunk as it is not needed for remote components\n if (/importScripts\\(\\.\\.\\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {\n const preloadLinks = document.querySelectorAll(\n `link[rel=\"preload\"][href=\"${new URL(url).pathname}\"]`,\n );\n preloadLinks.forEach((preloadLink) => preloadLink.remove());\n return;\n }\n\n const self = globalThis as GlobalScope;\n const { globalKey } = scope;\n\n // replace global variables with scope-specific ones to prevent collisions\n // between multiple remote component bundles\n const transformedCode = code\n .replace(\n /globalThis\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `globalThis[\"TURBOPACK_${globalKey}\"]`,\n )\n .replace(\n /self\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `self[\"TURBOPACK_${globalKey}\"]`,\n )\n .replace(/globalThis\\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`)\n .replace(/self\\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`)\n .replace(\n /TURBOPACK_WORKER_LOCATION/g,\n `TURBOPACK_WORKER_LOCATION_${globalKey}`,\n )\n .replace(\n /TURBOPACK_NEXT_CHUNK_URLS/g,\n `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`,\n )\n .replace(\n /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,\n `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`,\n )\n .replace(/__next_require__/g, `__${globalKey}_next_require__`)\n .replace(\n /\\/\\/# sourceMappingURL=(?<name>.+)(?<optional>\\._)?\\.js\\.map/g,\n `//# sourceMappingURL=${new URL('.', new URL(url, scope.url)).href}$1$2.js.map`,\n );\n\n // Initialize TURBOPACK bundle as a real Array with a push interceptor.\n // Must be a true Array instance so Next.js 15.x turbopack runtimes whose\n // module-system IIFE guards with `Array.isArray(globalThis.TURBOPACK)`\n // don't bail out after we rewrite the global name.\n //\n // The interceptor captures module entries into scope.turbopackModules —\n // a flat array we control. We use Object.defineProperty to intercept\n // when the turbopack runtime replaces the global with a deferred-loading\n // dispatcher (canary builds), wrapping the replacement's push too.\n //\n // The scope is reused across loads of different components from the same\n // remote (see setupRemoteScope), so subsequent loads accumulate into\n // the same turbopackModules array. Chunk cache deduplication means\n // handleTurbopackChunk only runs once per unique chunk URL — all captured\n // modules remain available for any component that needs them.\n if (!self[`TURBOPACK_${globalKey}`]) {\n const wrapPush = <T extends { push?: (...args: unknown[]) => unknown }>(\n target: T,\n ): T => {\n const originalPush = target.push;\n if (typeof originalPush !== 'function') return target;\n target.push = (...items: unknown[]) => {\n for (const item of items) {\n if (Array.isArray(item)) {\n for (const entry of item) {\n scope.turbopackModules.push(entry);\n }\n } else {\n scope.turbopackModules.push(item);\n }\n }\n return originalPush.apply(target, items);\n };\n return target;\n };\n\n const globalProp = `TURBOPACK_${globalKey}`;\n let currentValue: unknown = wrapPush([] as unknown[]);\n Object.defineProperty(self, globalProp, {\n get() {\n return currentValue;\n },\n set(newValue: unknown) {\n // When the turbopack runtime replaces the array with a dispatcher,\n // wrap the new object's push so we keep capturing module entries.\n if (newValue && typeof newValue === 'object') {\n wrapPush(newValue as { push?: (...args: unknown[]) => unknown });\n }\n currentValue = newValue;\n },\n configurable: true,\n enumerable: true,\n });\n }\n\n // load the script dynamically using a Blob URL\n await new Promise<void>((scriptResolve, scriptReject) => {\n const blob = new Blob([transformedCode], {\n type: 'application/javascript; charset=UTF-8',\n });\n const scriptUrl = URL.createObjectURL(blob);\n const script = document.createElement('script');\n script.setAttribute('data-turbopack-src', url);\n script.src = scriptUrl;\n script.async = true;\n script.onload = () => {\n URL.revokeObjectURL(scriptUrl);\n scriptResolve(undefined);\n script.remove();\n };\n script.onerror = () => {\n URL.revokeObjectURL(scriptUrl);\n scriptReject(\n new RemoteComponentsError(\n `Failed to load <script src=\"${script.src}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n script.remove();\n };\n document.head.appendChild(script);\n });\n\n // process any additional chunks that were registered during script execution\n // These CHUNK_LIST chunks load directly via scope — no global dispatch needed.\n const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`] as\n | { chunks: string[] }[]\n | undefined;\n const loadChunkPromises: (Promise<unknown> | undefined)[] = [];\n while (chunkLists?.length) {\n const { chunks } = chunkLists.shift() ?? { chunks: [] };\n if (chunks.length > 0) {\n for (const id of chunks) {\n const baseUrl = url.slice(0, url.indexOf('/_next'));\n const chunkLoadResult = loadChunkWithScope(\n scope,\n formatRemoteId(scope, `${baseUrl}/_next/${id}`),\n );\n if (chunkLoadResult) {\n loadChunkPromises.push(chunkLoadResult);\n }\n }\n }\n }\n if (loadChunkPromises.length > 0) {\n await Promise.all(loadChunkPromises);\n }\n}\n","import type { GlobalScope } from '#internal/runtime/types';\nimport { logDebug, logError, logWarn } from '#internal/utils/logger';\nimport { findModuleInit, handleTurbopackModule } from './module';\nimport {\n ASYNC_MODULE_CALLBACK_RE,\n ASYNC_MODULE_LOADER_RE,\n extractGroup,\n REMOTE_SHARED_ASSIGNMENT_RE,\n REMOTE_SHARED_MARKER_RE,\n} from './patterns';\nimport { formatRemoteId, type RemoteScope } from './remote-scope';\n\nconst DEDUPLICATION_WARNING =\n 'This module will not be deduplicated — the remote may load its own copy, ' +\n 'which can cause duplicate instance errors (e.g. invalid hook calls if React is loaded twice).';\n\n/**\n * Returns the flat module list for a scope.\n *\n * The primary source is `scope.turbopackModules` — a flat array populated by\n * the push interceptor in handleTurbopackChunk. This is immune to the\n * turbopack runtime replacing the TURBOPACK global (canary builds swap the\n * array for a deferred-loading dispatcher object).\n *\n * Falls back to reading the global for pre-populated bundles where the push\n * interceptor was never installed.\n */\nexport function getTurbopackModules(scope: RemoteScope): unknown[] | undefined {\n if (scope.turbopackModules.length > 0) {\n return scope.turbopackModules;\n }\n\n // Fallback: read the global for pre-populated bundles or legacy setups.\n const self = globalThis as GlobalScope;\n const raw = self[`TURBOPACK_${scope.globalKey}`];\n if (!raw) return undefined;\n\n if (Array.isArray(raw)) {\n return (raw as unknown[]).flat();\n }\n return Object.entries(raw as Record<string, unknown>).flat();\n}\n\n/**\n * Initializes shared modules between the host application and remote components.\n * This enables sharing of common dependencies like React to avoid duplicate instances.\n *\n * The function works by:\n * 1. Looking for a shared module initializer in the Turbopack bundle\n * 2. Extracting module IDs from the initializer\n * 3. Loading the corresponding host modules and mapping them to the remote's expected IDs\n */\nexport async function initializeSharedModules(\n scope: RemoteScope,\n hostShared: Record<string, (bundle?: string) => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n // biome-ignore lint/suspicious/noConfusingVoidType: Runtime is undefined but in TS land service it is void\n): Promise<void[]> {\n const allModules = getTurbopackModules(scope);\n\n logDebug(\n 'SharedModules',\n `initializeSharedModules: scope=\"${scope.scopedName}\", ` +\n `allModules=${allModules ? allModules.length : 'null'}, ` +\n `hostShared=[${Object.keys(hostShared).join(', ')}], ` +\n `remoteShared=${JSON.stringify(remoteShared)}`,\n );\n\n let sharedModuleInitializer: Promise<{\n shared: Record<string, string | (() => Promise<unknown>)>;\n }> | null = null;\n\n // find the shared module initializer in the Turbopack bundle\n if (allModules) {\n // find the shared module initializer module id by looking for\n // a function that contains the TURBOPACK_REMOTE_SHARED pattern\n const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {\n if (typeof idOrFunc !== 'function') {\n return false;\n }\n const funcCode = idOrFunc.toString();\n return REMOTE_SHARED_MARKER_RE.test(funcCode);\n });\n\n // if found, extract the shared module initializer\n // first element in the array is always the source script element\n if (sharedModuleInitializerIndex > 0) {\n const sharedModuleInitializerCode = (\n allModules[sharedModuleInitializerIndex] as () => unknown\n ).toString();\n const sharedModuleInitializerId = allModules[\n sharedModuleInitializerIndex - 1\n ] as string | number;\n // extract the shared module id from the function code\n const sharedModuleId = extractGroup(\n REMOTE_SHARED_ASSIGNMENT_RE,\n sharedModuleInitializerCode,\n 'sharedModuleId',\n );\n // load the shared module initializer using the extracted module id\n if (sharedModuleId) {\n const { default: sharedModuleInitializerInstance } =\n handleTurbopackModule(\n scope,\n sharedModuleId,\n formatRemoteId(scope, String(sharedModuleInitializerId)),\n ) as {\n default: Promise<{\n shared: Record<string, string | (() => Promise<unknown>)>;\n }>;\n };\n sharedModuleInitializer = sharedModuleInitializerInstance;\n }\n }\n\n // if we have a shared module initializer, load the shared modules from the host application\n if (sharedModuleInitializer) {\n const { shared } = await sharedModuleInitializer;\n // map shared module ids to their initializer functions\n const sharedModuleIds = extractSharedModuleIds(shared, scope);\n logDebug(\n 'SharedModules',\n `Resolved shared modules for scope=\"${scope.scopedName}\": ${JSON.stringify(sharedModuleIds)}`,\n );\n\n // load shared modules from the host application\n return Promise.all(\n Object.entries(sharedModuleIds).map(async ([id, module]) => {\n if (hostShared[module]) {\n scope.sharedModules[id] = await hostShared[module](scope.name);\n } else {\n logError(\n 'SharedModules',\n `Host shared module \"${module}\" not found for ID ${id}. ${DEDUPLICATION_WARNING}`,\n );\n }\n }),\n );\n }\n\n logWarn(\n 'SharedModules',\n `No shared module initializer found in bundle for scope=\"${scope.scopedName}\" — falling back to remoteShared mapping`,\n );\n } else {\n logWarn(\n 'SharedModules',\n `No TURBOPACK modules found for scope=\"${scope.scopedName}\" (TURBOPACK_${scope.globalKey} is empty)`,\n );\n }\n\n // fallback: ensure that the shared modules are initialized using remoteShared mapping\n return Promise.all(\n Object.entries(remoteShared).map(async ([id, module]) => {\n if (hostShared[module]) {\n const normalizedId = id.replace('[app-ssr]', '[app-client]');\n scope.sharedModules[normalizedId] = await hostShared[module](\n scope.name,\n );\n } else {\n logError(\n 'SharedModules',\n `Shared module \"${module}\" not found for \"${scope.name}\". ${DEDUPLICATION_WARNING}`,\n );\n }\n }),\n );\n}\n\n/**\n * Extracts shared module IDs from the shared module initializer functions.\n * This parses the minified Turbopack code to find the module ID mappings.\n */\nfunction extractSharedModuleIds(\n shared: Record<string, string | (() => Promise<unknown>)>,\n scope: RemoteScope,\n): Record<string, string> {\n return Object.entries(shared)\n .filter(([, value]) => typeof value === 'function')\n .reduce<Record<string, string>>((acc, [key, value]) => {\n const asyncSharedModuleId = extractGroup(\n ASYNC_MODULE_LOADER_RE,\n value.toString(),\n 'asyncSharedModuleId',\n );\n\n if (asyncSharedModuleId) {\n const asyncSharedModule = findModuleInit(\n getTurbopackModules(scope),\n asyncSharedModuleId,\n );\n if (asyncSharedModule) {\n const sharedModuleId = extractGroup(\n ASYNC_MODULE_CALLBACK_RE,\n asyncSharedModule.toString(),\n 'sharedModuleId',\n );\n // map the shared module id to the actual module name\n acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(\n '__remote_shared_module_',\n '',\n );\n }\n }\n return acc;\n }, {});\n}\n\n/**\n * Returns a shared module for the given scope and module ID.\n * Shared modules are common dependencies like React that are provided by the host.\n */\nexport function getSharedModule(\n scope: RemoteScope,\n id: string | number,\n): unknown {\n const idStr = String(id);\n\n // Exact match first (covers both string and numeric IDs)\n if (scope.sharedModules[idStr] !== undefined) {\n return scope.sharedModules[idStr];\n }\n\n // Fallback: the id may be a bundle-prefixed string like \"[bundle] /react/index.js\"\n // that contains the shared module key as a suffix. Only match when the key\n // appears as a complete suffix segment to avoid \"react\" matching \"react-dom\".\n for (const [key, value] of Object.entries(scope.sharedModules)) {\n if (typeof value !== 'undefined' && idStr !== key && idStr.endsWith(key)) {\n return value;\n }\n }\n\n return null;\n}\n","import { logError } from '#internal/utils/logger';\nimport { loadChunkWithScope } from './chunk-loader';\nimport { formatRemoteId, type RemoteScope } from './remote-scope';\nimport { getSharedModule, getTurbopackModules } from './shared-modules';\n\n/**\n * Function signature for Turbopack module initializers.\n * These functions are generated by Turbopack and initialize module exports.\n */\nexport type TurbopackModuleInit = (\n turbopackContext: TurbopackContext,\n module: { exports: Record<string, unknown> },\n exports: Record<string, unknown>,\n) => void;\n\n/**\n * The context object passed to Turbopack module initializers.\n * This provides the runtime API that modules use for imports, exports, and HMR.\n */\ninterface TurbopackContext {\n /** HMR (Hot Module Replacement) - not implemented for remote components */\n k: {\n register(): void;\n registerExports(): void;\n signature(): (fn: unknown) => unknown;\n };\n /** ESM exports setup */\n s: (\n bindings:\n | Record<string, () => unknown>\n | [...([string, () => unknown] | [string, number, () => unknown])],\n esmId?: string | number,\n ) => void;\n /** Import module */\n i: (importId: string | number) => Record<string, unknown> | undefined;\n /** Require module */\n r: (requireId: string) => unknown;\n /** Value exports */\n v: (value: unknown) => void;\n /** Async module initializer */\n a: (\n mod: (\n handleDeps: unknown,\n setResult: (value: unknown) => void,\n ) => Promise<void>,\n ) => Promise<void>;\n /** Async module loader */\n A: (Aid: string) => Promise<unknown>;\n /**\n * Dynamic import tracking. Called in production chunks after ctx.s() to\n * register async/dynamic module relationships. e.g. t.j(importedMod, 58790)\n */\n j: (module: unknown, esmId?: string | number) => void;\n /** Chunk loader */\n l: (url: string) => Promise<unknown> | undefined;\n /** Global object for this bundle */\n g: unknown;\n /** Module object */\n m: { exports: Record<string, unknown> };\n /** Exports object */\n e: Record<string, unknown>;\n}\n\n/**\n * Turbopack pushes chunks as flat arrays in one of two shapes:\n *\n * Module chunk (common case):\n * [scriptElement, id1, factory1, id2, factory2, ...]\n * - index 0: the script Element (document.currentScript) or undefined\n * - alternating pairs: numeric ID (prod) or path string (dev), then factory function\n *\n * Runtime manifest (bootstrapper only, no module factories):\n * [scriptElement, { otherChunks: [...], runtimeModuleIds: [...] }]\n *\n * Newer Next.js canary versions may also store modules as a plain object\n * { [moduleId]: factory } rather than as an array.\n */\ntype BundleModules =\n | (\n | Element\n | string\n | number\n | TurbopackModuleInit\n | Record<string, TurbopackModuleInit>\n | null\n | undefined\n )[]\n | Record<string, TurbopackModuleInit>\n | undefined;\n\n/**\n * Resolves a module within a scope: checks shared modules first, then\n * falls back to Turbopack module resolution. This is the scope-local\n * equivalent of the global __webpack_require__ dispatcher.\n */\nexport function requireModule(\n scope: RemoteScope,\n moduleId: string | number,\n fullId?: string,\n): unknown {\n const idStr = String(moduleId);\n\n // moduleCache is checked first inside handleTurbopackModule too, but\n // checking here avoids the shared-module lookup on every re-entry.\n if (scope.moduleCache[idStr]) return scope.moduleCache[idStr];\n\n // Shared modules are NOT cached in moduleCache because ctx.s() also\n // uses moduleCache for esmId lookups. Caching the host's frozen module\n // object here would cause ctx.s() to attempt Object.defineProperty on\n // it, failing with \"Cannot redefine property\" for non-configurable\n // exports. Keeping shared modules in their own map avoids the collision.\n const sharedModule = getSharedModule(scope, moduleId);\n if (sharedModule) return sharedModule;\n\n return handleTurbopackModule(\n scope,\n idStr,\n fullId ?? formatRemoteId(scope, idStr),\n );\n}\n\n/**\n * Handles Turbopack module resolution and execution.\n * Finds a module in the Turbopack bundle, executes its initializer with a\n * custom runtime context, and returns the module exports.\n */\nexport function handleTurbopackModule(\n scope: RemoteScope,\n moduleId: string,\n id: string,\n): unknown {\n // Cache check must come before module init lookup. Module initializers\n // re-enter handleTurbopackModule for their own imports, so without this\n // guard circular dependencies would infinite-loop.\n if (scope.moduleCache[moduleId]) {\n return scope.moduleCache[moduleId];\n }\n\n const modules = getTurbopackModules(scope) as BundleModules;\n\n // Log only if bundle is completely missing (critical error)\n if (!modules) {\n logError(\n 'TurbopackModule',\n `TURBOPACK_${scope.globalKey} is undefined (scope: \"${scope.scopedName}\")`,\n );\n }\n\n const moduleInit = findModuleInit(modules, moduleId);\n const exports = {} as Record<string, unknown>;\n const moduleExports = { exports };\n\n if (typeof moduleInit !== 'function') {\n throw new Error(\n `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`,\n );\n }\n\n // store a reference to the module exports in the cache before execution\n // to handle circular dependencies\n scope.moduleCache[moduleId] = moduleExports.exports;\n\n // execute the module initializer with our custom Turbopack context\n moduleInit(\n createTurbopackContext(\n scope,\n exports,\n moduleExports,\n modules,\n moduleInit,\n id,\n ),\n moduleExports,\n exports,\n );\n\n // update the cache with the final exports (may have changed during execution)\n if (scope.moduleCache[moduleId] !== moduleExports.exports) {\n scope.moduleCache[moduleId] = moduleExports.exports;\n }\n\n return moduleExports.exports;\n}\n\n/**\n * Finds the module initializer function for a given ID in the Turbopack bundle.\n * Handles all bundle shapes: flat array, object map, nested arrays, and\n * embedded object entries within arrays. Performs exact match first, then\n * falls back to startsWith for dev-mode IDs with appended qualifiers.\n */\nexport function findModuleInit(\n modules: BundleModules | unknown[] | undefined,\n moduleId: string,\n): TurbopackModuleInit | undefined {\n if (!modules || typeof modules !== 'object') return;\n\n // Object format: { [id]: factory } (newer Next.js canary builds)\n if (!Array.isArray(modules)) {\n const key =\n moduleId in modules\n ? moduleId\n : Object.keys(modules).find((k) => k.startsWith(moduleId));\n return key !== undefined ? modules[key] : undefined;\n }\n\n const flat = modules.flat();\n\n // Two-pass ID search: exact match first to avoid prefix false positives.\n // The startsWith fallback handles dev-mode IDs with appended qualifiers\n // such as \"[project]/path.tsx [app-client] (ecmascript, async loader)\".\n let idx = flat.findIndex((e) => String(e) === String(moduleId));\n if (idx < 0) {\n idx = flat.findIndex(\n (e) => typeof e === 'string' && e.startsWith(moduleId),\n );\n }\n if (idx >= 0) {\n // Factory is the first function entry that follows the module ID\n return flat\n .slice(idx + 1)\n .find((e): e is TurbopackModuleInit => typeof e === 'function');\n }\n\n // Embedded object map: entries of the form { [moduleId]: factory }\n for (const entry of flat) {\n if (!entry || typeof entry !== 'object') continue;\n const obj = entry as Record<string, TurbopackModuleInit>;\n if (moduleId in obj) return obj[moduleId];\n const prefixKey = Object.keys(obj).find((k) => k.startsWith(moduleId));\n if (prefixKey) return obj[prefixKey];\n }\n return undefined;\n}\n\n/**\n * Creates the Turbopack context object that provides the runtime API for modules.\n * All context methods close over the scope directly — no global dispatch needed\n * for internal module-to-module calls.\n */\nfunction createTurbopackContext(\n scope: RemoteScope,\n exports: Record<string, unknown>,\n moduleExports: { exports: Record<string, unknown> },\n modules: BundleModules,\n moduleInit: TurbopackModuleInit,\n id: string,\n): TurbopackContext {\n /** Scope-local require: shared modules → turbopack module resolution. */\n const scopedRequire = (moduleId: string | number): unknown =>\n requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));\n\n return {\n // HMR not implemented for Remote Components\n k: {\n register() {\n // omit\n },\n registerExports() {\n // omit\n },\n signature() {\n return (fn: unknown) => fn;\n },\n },\n\n // ESM exports setup\n s(\n bindings:\n | Record<string, () => unknown>\n | [...([string, () => unknown] | [string, number, () => unknown])],\n esmId?: string | number,\n ) {\n let mod = exports;\n if (typeof esmId === 'string' || typeof esmId === 'number') {\n if (!scope.moduleCache[esmId]) {\n scope.moduleCache[esmId] = {} as Record<string, unknown>;\n }\n mod = scope.moduleCache[esmId] as Record<string, unknown>;\n }\n\n Object.defineProperty(mod, '__esModule', { value: true });\n if (Array.isArray(bindings)) {\n let i = 0;\n while (i < bindings.length) {\n const propName = bindings[i++] as string;\n const tagOrFunc = bindings[i++];\n if (typeof tagOrFunc === 'number') {\n Object.defineProperty(mod, propName, {\n value: bindings[i++],\n enumerable: true,\n writable: false,\n });\n } else {\n const getterFn = tagOrFunc as () => unknown;\n if (typeof bindings[i] === 'function') {\n const setterFn = bindings[i++] as (v: unknown) => unknown;\n Object.defineProperty(mod, propName, {\n get: getterFn,\n set: setterFn,\n enumerable: true,\n });\n } else {\n Object.defineProperty(mod, propName, {\n get: getterFn,\n enumerable: true,\n });\n }\n }\n }\n }\n },\n\n // import — resolves directly via scope, no global dispatch\n i(importId: string | number) {\n let mod: Record<string, unknown> | undefined;\n if (typeof importId === 'string') {\n // parse export syntax if present (e.g., \"module <export foo as bar>\")\n const { exportSource, exportName } =\n /\\s+<export (?<exportSource>.*?) as (?<exportName>.*?)>$/.exec(\n importId,\n )?.groups ?? {};\n const normalizedId = importId.replace(\n /\\s+<export(?<specifier>.*)>$/,\n '',\n );\n mod = scopedRequire(normalizedId) as\n | Record<string, unknown>\n | undefined;\n // map the requested export to the module exports\n if (\n mod &&\n exportSource &&\n exportName &&\n (exportSource === '*' || typeof mod[exportSource] !== 'undefined') &&\n typeof mod[exportName] === 'undefined'\n ) {\n if (exportSource === '*') {\n mod[exportName] = mod;\n } else {\n mod[exportName] = mod[exportSource];\n }\n }\n } else {\n mod = scopedRequire(importId) as Record<string, unknown> | undefined;\n }\n\n if (typeof mod !== 'object' || mod === null) {\n mod = { default: mod };\n } else if (\n !('default' in mod) &&\n // ES module namespace objects have a null prototype, so calling\n // mod.toString() directly throws. Use Object.prototype.toString\n // to safely detect them.\n Object.prototype.toString.call(mod) !== '[object Module]'\n ) {\n try {\n mod.default = mod;\n } catch {\n // ignore if mod is not extensible\n }\n }\n return mod;\n },\n\n // require — resolves directly via scope\n r(requireId: string) {\n return scopedRequire(requireId);\n },\n\n // value exports\n v(value: unknown) {\n if (typeof value === 'function') {\n exports.default = value((vid: string | number) => scopedRequire(vid));\n } else {\n moduleExports.exports = value as Record<string, unknown>;\n }\n },\n\n // async module initializer\n async a(\n mod: (\n handleDeps: unknown,\n setResult: (value: unknown) => void,\n ) => Promise<void>,\n ) {\n let result;\n await mod(\n () => {\n // not implemented\n },\n (value) => (result = value),\n );\n exports.default = result;\n },\n\n // async module loader — resolves directly via scope\n async A(Aid: string) {\n const mod = scopedRequire(Aid) as {\n default: (\n parentImport: (parentId: string) => unknown,\n ) => Promise<unknown>;\n };\n return mod.default((parentId: string) => scopedRequire(parentId));\n },\n\n // dynamic import tracking — no-op for remote components\n j() {\n // omit\n },\n\n // chunk loader — loads directly via scope, no global dispatch\n l(url: string) {\n // find the script tag that loaded the current module to determine base URL\n const flatModules = Array.isArray(modules) ? modules : [];\n const moduleInitIndex = flatModules.indexOf(moduleInit);\n if (moduleInitIndex !== -1) {\n const scriptIndex = flatModules\n .slice(0, moduleInitIndex)\n .findLastIndex((bundleEntry) => bundleEntry instanceof Element);\n if (scriptIndex !== -1) {\n const script = flatModules[scriptIndex] as HTMLScriptElement;\n const scriptSrc = script.getAttribute('data-turbopack-src') || '';\n const nextIndex = scriptSrc.indexOf('/_next');\n const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : '';\n const chunkUrl = `${baseUrl}/_next/${url}`;\n return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));\n }\n }\n throw new Error(\n `Failed to load Turbopack chunk \"${url}\" for module \"${id}\". Check the URL is correct.`,\n );\n },\n\n // globalThis substitute shared across all modules in this scope\n g: scope.moduleGlobal,\n m: moduleExports,\n e: exports,\n };\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n RUNTIME_TURBOPACK,\n RUNTIME_WEBPACK,\n type Runtime,\n} from '#internal/runtime/constants';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport { REMOTE_COMPONENT_REGEX } from '#internal/runtime/patterns';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\nimport { logDebug, logWarn } from '#internal/utils/logger';\nimport { createChunkDispatcher, loadChunkWithScope } from './chunk-loader';\nimport { requireModule } from './module';\nimport {\n createScope,\n getScope,\n type RemoteScope,\n registerScope,\n} from './remote-scope';\n\n/**\n * Sets up the bundler runtime environment for remote components.\n *\n * Creates a RemoteScope that encapsulates all per-remote state (base URL,\n * proxy callback, module cache, shared modules) and registers it in the\n * global scope registry. Global dispatchers (__webpack_require__,\n * __webpack_chunk_load__) are set once and route to the correct scope.\n *\n * Shared module initialization is NOT performed here — callers must invoke\n * `initializeSharedModules` separately after this function returns. This\n * separation ensures shared modules are initialized after turbopack chunks\n * are loaded (so the primary bundle-introspection path is used), avoiding\n * the fallback that keys shared modules by file path instead of numeric ID.\n *\n * @returns The scope (newly created or reused) for the bundle.\n */\nexport async function setupRemoteScope(\n runtime: Runtime,\n scripts: { src: string | null }[] = [],\n url: URL = new URL(location.href),\n bundle?: string,\n resolveClientUrl?: InternalResolveClientUrl,\n): Promise<RemoteScope> {\n const self = globalThis as GlobalScope;\n const ns = getNamespace();\n const bundleName = bundle ?? 'default';\n\n // When the same remote loads a second component (e.g. switching from basic\n // to styled), reuse the existing scope. The chunk cache is keyed by URL and\n // returns cached promises without re-running handleTurbopackChunk, so\n // turbopackModules, moduleCache, and sharedModules from the first load are\n // all still valid. Only resolveClientUrl may have changed.\n const existingScope = getScope(bundleName);\n if (existingScope && existingScope.url.origin === url.origin) {\n logDebug(\n 'WebpackRuntime',\n `Reusing scope \"${existingScope.scopedName}\" (turbopackModules=${existingScope.turbopackModules.length})`,\n );\n existingScope.resolveClientUrl = resolveClientUrl;\n\n // Still load scripts — chunk cache deduplicates already-loaded chunks,\n // and a different component may reference additional chunks.\n if (runtime === RUNTIME_TURBOPACK) {\n await Promise.allSettled(\n scripts.map((script) =>\n script.src\n ? loadChunkWithScope(existingScope, script.src)\n : Promise.resolve(undefined),\n ),\n );\n }\n return existingScope;\n }\n\n const scope = createScope(bundleName, url, runtime, resolveClientUrl);\n registerScope(scope);\n\n // For webpack remotes the remote's own scripts have already loaded (via\n // loadScripts in component-loader) and populated __remote_webpack_require__\n // under the plain bundle name. Capture the reference on the scope so\n // downstream code (applySharedModules, module dispatcher) can use it\n // without reaching into the global.\n if (\n runtime === RUNTIME_WEBPACK &&\n self.__remote_webpack_require__?.[bundleName]\n ) {\n scope.webpackRequire = self.__remote_webpack_require__[bundleName];\n }\n\n ns.bundleUrls[bundleName] = url;\n // Also register under scopedName so webpack hosts (patch-require.ts) can\n // resolve cross-origin remotes whose bundle identifiers were rewritten.\n if (scope.scopedName !== bundleName) {\n ns.bundleUrls[scope.scopedName] = url;\n }\n self.__webpack_get_script_filename__ = () => null;\n\n const willCreateDispatchers =\n typeof self.__webpack_require__ !== 'function' ||\n ns.dispatcherRuntime !== 'turbopack';\n\n if (willCreateDispatchers) {\n // preserve original webpack functions for fallback\n if (\n !self.__original_webpack_require__ &&\n !self.__original_webpack_chunk_load__\n ) {\n self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;\n self.__original_webpack_require__ = self.__webpack_require__;\n }\n\n self.__webpack_chunk_load__ = createChunkDispatcher();\n self.__webpack_require__ = createModuleDispatcher(runtime);\n // Write-through needed: dispatcherRuntime is a primitive string,\n // so the legacy global can't be aliased by reference in getNamespace().\n ns.dispatcherRuntime = runtime;\n self.__webpack_require_type__ = runtime;\n\n // @legacy(v0.3.4) — __remote_webpack_require__ write-through for turbopack remotes.\n // Needed by PatchRequirePlugin which reads this global at runtime.\n // Remove once PatchRequirePlugin reads from scope.\n if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {\n self.__remote_webpack_require__[bundleName] =\n self.__webpack_require__ as (remoteId: string | number) => unknown;\n self.__remote_webpack_require__[bundleName].type = 'turbopack';\n }\n }\n\n // @legacy(v0.3.4) — __remote_webpack_require__ scoped-name alias.\n // Ensures PatchRequirePlugin can find webpack remotes under rewritten\n // bundle identifiers. Remove once PatchRequirePlugin reads from scope.\n if (\n self.__remote_webpack_require__?.[bundleName] &&\n scope.scopedName !== bundleName\n ) {\n self.__remote_webpack_require__[scope.scopedName] =\n self.__remote_webpack_require__[bundleName];\n }\n\n // load all initial chunks directly via scope — no global dispatch needed\n if (runtime === RUNTIME_TURBOPACK) {\n const results = await Promise.allSettled(\n scripts.map((script) => {\n if (script.src) {\n return loadChunkWithScope(scope, script.src);\n }\n return Promise.resolve(undefined);\n }),\n );\n\n for (const result of results) {\n if (result.status === 'rejected') {\n logWarn(\n 'WebpackRuntime',\n `Initial chunk load failed: ${String(result.reason)}`,\n );\n }\n }\n }\n\n return scope;\n}\n\n/**\n * Creates the global module dispatcher for __webpack_require__.\n * Called by external code (React's RSC runtime) that doesn't have access to\n * a scope. Parses the module ID to find the correct scope and delegates\n * to scope-local module resolution.\n */\nfunction createModuleDispatcher(runtime: Runtime): (id: string) => unknown {\n return (id: string) => {\n const self = globalThis as GlobalScope;\n const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)\n ?.groups ?? {\n bundle: 'default',\n id,\n };\n const bundleName = bundle ?? 'default';\n const remoteRuntime = self.__remote_webpack_require__?.[bundleName]\n ? self.__remote_webpack_require__[bundleName]?.type || 'webpack'\n : runtime;\n\n logDebug(\n 'ModuleDispatcher',\n `Resolving \"${id}\" (bundle: \"${bundleName}\", runtime: \"${remoteRuntime}\")`,\n );\n\n try {\n // for webpack remotes, prefer scope-based dispatch then fall back to global\n if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {\n const scope = getScope(bundle);\n if (scope?.webpackRequire) return scope.webpackRequire(moduleId);\n // @legacy(v0.3.4) — global fallback for hosts that populated\n // __remote_webpack_require__ without calling setupWebpackRuntime.\n return self.__remote_webpack_require__?.[bundle]?.(moduleId);\n }\n\n // Look up scope by parsed bundle name. Works with both the scoped\n // name (Next.js hosts with server-side rewriting) and the plain\n // bundle name (static/HTML hosts with unrewritten chunks).\n const scope = getScope(bundleName);\n if (scope) {\n return requireModule(scope, moduleId ?? id, id);\n }\n\n throw new Error(\n `Module \"${id}\" not found — no scope for bundle \"${bundleName}\".`,\n );\n } catch (requireError) {\n logWarn(\n 'ModuleDispatcher',\n `Module require failed: ${String(requireError)}`,\n );\n if (typeof self.__original_webpack_require__ !== 'function') {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundleName}\".`,\n {\n cause: requireError instanceof Error ? requireError : undefined,\n },\n );\n }\n try {\n logDebug(\n 'ModuleDispatcher',\n 'Falling back to original webpack require',\n );\n return self.__original_webpack_require__(id);\n } catch (originalError) {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundleName}\".`,\n { cause: originalError instanceof Error ? originalError : undefined },\n );\n }\n }\n };\n}\n","import { applySharedModules } from '#internal/config/webpack/apply-shared-modules';\nimport { nextClientPagesLoader } from '#internal/config/webpack/next-client-pages-loader';\nimport type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n buildCoreShared,\n buildHostShared,\n} from '#internal/host/shared/shared-module-resolver';\nimport { setupRemoteScope } from '#internal/runtime/turbopack/remote-scope-setup';\nimport { initializeSharedModules } from '#internal/runtime/turbopack/shared-modules';\nimport type { MountUnmountFunctions, RSCKey } from '#internal/runtime/types';\n\n// initializer for the turbopack runtime to be able to access modules\n// required to run exposed client components of the remote component\nexport async function turbopackRuntime(\n url: URL,\n bundle?: string,\n shared?: Record<string, () => Promise<unknown>>,\n remoteShared?: Record<string, string>,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack runtime globals\n __webpack_require__: (remoteId: string) => unknown;\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string) => unknown) & {\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n // conditional flag to disable webpack exec\n __DISABLE_WEBPACK_EXEC__: boolean;\n // webpack chunk loading function\n __webpack_chunk_load__: () => Promise<[]>;\n } & MountUnmountFunctions &\n Record<RSCKey, string[]>;\n\n const hostShared = buildHostShared(shared, resolveClientUrl, {\n includeRemoteComponentShared: true,\n });\n\n // Phase 1: Set up globals (__webpack_require__, __webpack_chunk_load__).\n // Called with empty scripts because we need the globals to exist before\n // importing react-server-dom-webpack. Shared module initialization is\n // deferred to preloadScripts where turbopack chunks are actually loaded.\n await setupRemoteScope('turbopack', [], url, bundle, resolveClientUrl);\n\n // we can only import react-server-dom-webpack after initializing the __webpack_require__ and __webpack_chunk_load__ functions\n const {\n default: { createFromReadableStream },\n } = await import('react-server-dom-webpack/client.browser');\n\n async function preloadScripts(scripts: HTMLScriptElement[], __: URL) {\n // Phase 2: Load turbopack chunks (scope is reused from phase 1).\n const scope = await setupRemoteScope(\n 'turbopack',\n scripts.map((script) => ({\n src:\n script.getAttribute('src') ||\n script.getAttribute('data-src') ||\n script.src,\n })),\n url,\n bundle,\n resolveClientUrl,\n );\n\n // Phase 3: Initialize shared modules now that turbopackModules is\n // populated. This uses the primary bundle-introspection path which\n // maps shared modules by numeric turbopack ID — unlike the fallback\n // path that uses file-path keys which can't match at runtime.\n await initializeSharedModules(\n scope,\n buildCoreShared(hostShared),\n remoteShared ?? {},\n );\n }\n\n return {\n self,\n createFromReadableStream,\n applySharedModules,\n nextClientPagesLoader,\n preloadScripts,\n };\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport type { MountOrUnmountFunction } from '#internal/runtime/types';\nimport { logError, warnCrossOriginFetchError } from '#internal/utils/logger';\n\ntype ScriptMod = {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n default?: {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n };\n};\n\n/**\n * Fetches an ES module via the resolveClientUrl callback, rewrites its\n * relative imports to also go through the callback, then loads it by injecting a\n * wrapper <script type=\"module\"> tag. The module's namespace is captured via\n * a temporary global and returned.\n *\n * This is needed when a direct import() of a cross-origin module fails due to\n * CORS restrictions or Vercel preview-deployment auth. A simple URL rewrite\n * doesn't work for import() because relative imports inside the module would\n * resolve against the rewritten URL instead of the original remote origin.\n */\nasync function importViaCallback<T>(\n absoluteSrc: string,\n resolveClientUrl: InternalResolveClientUrl,\n): Promise<T> {\n const resolvedUrl = resolveClientUrl(absoluteSrc) ?? absoluteSrc;\n const fetchUrl = new URL(resolvedUrl, location.href).href;\n const response = await fetch(fetchUrl);\n if (!response.ok) throw new Error(`Proxied fetch failed: ${response.status}`);\n\n // Restore import.meta.url to the original module URL so any code that\n // relies on it (e.g. for asset resolution) gets the right value.\n // Rewrite relative imports to absolute URLs resolved through the callback so\n // that transitive dependencies also bypass CORS/auth.\n const content = (await response.text())\n .replace(/import\\.meta\\.url/g, JSON.stringify(absoluteSrc))\n .replace(\n /\\b(from|import)\\s*([\"'])(\\.\\.?\\/[^\"']+)\\2/g,\n (_, keyword, quote, relativePath) => {\n const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;\n const resolvedImportUrl = new URL(\n resolveClientUrl(absoluteImportUrl) ?? absoluteImportUrl,\n location.href,\n ).href;\n return `${keyword} ${quote}${resolvedImportUrl}${quote}`;\n },\n );\n const moduleBlobUrl = URL.createObjectURL(\n new Blob([content], { type: 'text/javascript' }),\n );\n const wrapperContent = [\n `import*as m from${JSON.stringify(moduleBlobUrl)};`,\n `globalThis.__rc_module_registry__=globalThis.__rc_module_registry__||{};`,\n `globalThis.__rc_module_registry__[${JSON.stringify(absoluteSrc)}]=m;`,\n ].join('');\n const wrapperBlobUrl = URL.createObjectURL(\n new Blob([wrapperContent], { type: 'text/javascript' }),\n );\n const scriptEl = document.createElement('script');\n scriptEl.type = 'module';\n scriptEl.src = wrapperBlobUrl;\n try {\n await new Promise<void>((resolve, reject) => {\n scriptEl.onload = () => resolve();\n scriptEl.onerror = () =>\n reject(new Error(`Failed to load module for ${absoluteSrc}`));\n document.head.appendChild(scriptEl);\n });\n } finally {\n scriptEl.remove();\n URL.revokeObjectURL(moduleBlobUrl);\n URL.revokeObjectURL(wrapperBlobUrl);\n }\n const registry = getNamespace().moduleRegistry as Record<string, T>;\n const mod = registry[absoluteSrc] ?? ({} as T);\n delete registry[absoluteSrc];\n return mod;\n}\n\nasync function importDirectly<T>(absoluteSrc: string): Promise<T> {\n try {\n return (await import(\n /* @vite-ignore */\n /* webpackIgnore: true */ absoluteSrc\n )) as T;\n } catch (importError) {\n if (!absoluteSrc.startsWith('blob:')) {\n warnCrossOriginFetchError('StaticLoader', absoluteSrc);\n }\n throw importError;\n }\n}\n\nfunction resolveScriptSrc(script: HTMLScriptElement, url: URL): string {\n const rawSrc =\n typeof script.getAttribute === 'function'\n ? (script.getAttribute('src') ?? script.src)\n : script.src;\n if (!rawSrc && script.textContent) {\n return URL.createObjectURL(\n new Blob(\n [script.textContent.replace(/import\\.meta\\.url/g, JSON.stringify(url))],\n { type: 'text/javascript' },\n ),\n );\n }\n return rawSrc;\n}\n\nexport async function loadStaticRemoteComponent(\n scripts: HTMLScriptElement[],\n url: URL,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n const ns = getNamespace();\n\n if (ns.mountFns[url.href]) {\n ns.mountFns[url.href] = new Set();\n }\n if (ns.unmountFns[url.href]) {\n ns.unmountFns[url.href] = new Set();\n }\n const mountUnmountSets = await Promise.all(\n scripts.map(async (script) => {\n try {\n const src = resolveScriptSrc(script, url);\n const absoluteSrc = new URL(src, url).href;\n const mod: ScriptMod = resolveClientUrl\n ? await importViaCallback<ScriptMod>(absoluteSrc, resolveClientUrl)\n : await importDirectly<ScriptMod>(absoluteSrc);\n // revoke the object URL if we created one for inline script content\n if (src.startsWith('blob:')) {\n URL.revokeObjectURL(src);\n }\n if (\n typeof mod.mount === 'function' ||\n typeof mod.default?.mount === 'function'\n ) {\n if (!ns.mountFns[url.href]) {\n ns.mountFns[url.href] = new Set();\n }\n ns.mountFns[url.href]?.add(\n mod.mount ||\n mod.default?.mount ||\n (() => {\n // noop\n }),\n );\n }\n if (\n typeof mod.unmount === 'function' ||\n typeof mod.default?.unmount === 'function'\n ) {\n if (!ns.unmountFns[url.href]) {\n ns.unmountFns[url.href] = new Set();\n }\n ns.unmountFns[url.href]?.add(\n mod.unmount ||\n mod.default?.unmount ||\n (() => {\n // noop\n }),\n );\n }\n return {\n mount: mod.mount || mod.default?.mount,\n unmount: mod.unmount || mod.default?.unmount,\n };\n } catch (e) {\n logError(\n 'StaticLoader',\n `Error loading remote component script from \"${script.src || url.href}\".`,\n e,\n );\n return {\n mount: undefined,\n unmount: undefined,\n };\n }\n }),\n );\n return mountUnmountSets.reduce(\n (acc, { mount, unmount }) => {\n if (typeof mount === 'function') {\n acc.mount.add(mount);\n }\n if (typeof unmount === 'function') {\n acc.unmount.add(unmount);\n }\n return acc;\n },\n {\n mount: new Set<MountOrUnmountFunction>(),\n unmount: new Set<MountOrUnmountFunction>(),\n },\n );\n}\n","// initializer for the script runtime\n\nimport type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { loadStaticRemoteComponent } from '#internal/runtime/loaders/static-loader';\nimport type { MountUnmountFunctions, RSCKey } from '#internal/runtime/types';\n\n// required to run exposed client components of the remote component\nexport function scriptRuntime(resolveClientUrl?: InternalResolveClientUrl) {\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack runtime globals\n __webpack_require__: (remoteId: string) => unknown;\n } & MountUnmountFunctions &\n Record<RSCKey, string[]>;\n\n return {\n self,\n createFromReadableStream: () => Promise.resolve(null),\n applySharedModules: () => Promise.resolve(),\n nextClientPagesLoader: () => ({\n Component: null,\n App: null,\n }),\n preloadScripts: (scripts: HTMLScriptElement[], url: URL) =>\n loadStaticRemoteComponent(scripts, url, resolveClientUrl),\n };\n}\n","import { startTransition, useLayoutEffect } from 'react';\nimport { hydrateRoot } from 'react-dom/client';\nimport { fetchWithHooks } from '#internal/host/server/fetch-with-hooks';\nimport { getClientOrServerUrl } from '#internal/host/server/get-client-or-server-url';\nimport type {\n ConsumeClientConfig,\n ConsumeServerConfig,\n} from '#internal/host/shared/config';\nimport type { HostState } from '#internal/host/shared/state';\nimport { createHostState } from '#internal/host/shared/state';\nimport { resolveNameFromSrc } from '#internal/host/utils/resolve-name-from-src';\nimport {\n DEFAULT_BUNDLE_NAME,\n DEFAULT_COMPONENT_NAME,\n} from '#internal/runtime/constants';\nimport { applyOriginToNodes } from '#internal/runtime/html/apply-origin';\nimport { parseRemoteComponentDocument } from '#internal/runtime/html/parse-remote-html';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport { createRSCStream } from '#internal/runtime/rsc';\nimport type { RSCKey } from '#internal/runtime/types';\nimport { bindResolveClientUrl } from '#internal/runtime/url/default-resolve-client-url';\nimport { escapeString } from '#internal/utils';\nimport { isAbortError } from '#internal/utils/abort';\nimport {\n errorFromFailedFetch,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport { logError } from '#internal/utils/logger';\nimport { attachStyles } from './attach-styles';\nimport { getRuntime, type Runtime } from './runtime';\n\nif (typeof HTMLElement !== 'undefined') {\n /**\n * `<remote-component>` custom element — the HTML host implementation.\n *\n * Implements {@link ConsumeClientConfig}\n * via typed property accessors that reflect to/from DOM attributes.\n *\n * {@link ConsumeLifecycleCallbacks} are dispatched as DOM events:\n * `beforeload`, `load`, `error`, `change`.\n */\n class RemoteComponent extends HTMLElement implements ConsumeClientConfig {\n name: string = DEFAULT_COMPONENT_NAME;\n bundle: string = DEFAULT_BUNDLE_NAME;\n fallbackSlot?: HTMLSlotElement;\n __next: HTMLDivElement | null = null;\n fouc: HTMLStyleElement | null = null;\n hostState: HostState = createHostState();\n root?: ShadowRoot | null = null;\n reactRoot?: ReturnType<typeof hydrateRoot>;\n onRequest?: ConsumeServerConfig['onRequest'];\n onResponse?: ConsumeServerConfig['onResponse'];\n resolveClientUrl?: ConsumeClientConfig['resolveClientUrl'];\n\n // -- ConsumeServerConfig property accessors (attribute-reflected) --\n\n get src(): string | URL | undefined {\n return this.getAttribute('src') ?? undefined;\n }\n\n set src(value: string | URL | undefined) {\n if (value == null) {\n this.removeAttribute('src');\n } else {\n this.setAttribute('src', String(value));\n }\n }\n\n /** Always `true` — the HTML host always isolates via Shadow DOM. */\n get isolate(): boolean {\n return true;\n }\n\n get mode(): 'open' | 'closed' | undefined {\n const attr = this.getAttribute('mode');\n return attr === 'closed' ? 'closed' : 'open';\n }\n\n set mode(value: 'open' | 'closed' | undefined) {\n if (value) {\n this.setAttribute('mode', value);\n }\n }\n\n get reset(): boolean | undefined {\n return this.getAttribute('reset') !== null;\n }\n\n set reset(value: boolean | undefined) {\n if (value) {\n this.setAttribute('reset', '');\n } else {\n this.removeAttribute('reset');\n }\n }\n\n get credentials(): RequestCredentials | undefined {\n return (this.getAttribute('credentials') ||\n 'same-origin') as RequestCredentials;\n }\n\n set credentials(value: RequestCredentials | undefined) {\n if (value) {\n this.setAttribute('credentials', value);\n } else {\n this.removeAttribute('credentials');\n }\n }\n\n static get observedAttributes() {\n return ['src', 'name', 'mode'];\n }\n\n private dispatchLifecycleEvent(\n type: 'beforeload' | 'load' | 'error' | 'change',\n detail?: Record<string, unknown>,\n ) {\n const event = new Event(type, { bubbles: true, composed: true });\n if (detail) {\n Object.assign(event, detail);\n }\n this.dispatchEvent(event);\n }\n\n attributeChangedCallback(name: string, oldValue: string, newValue: string) {\n if ((name === 'src' || name === 'name') && oldValue !== newValue) {\n if (this.src) {\n this.load().catch((e) => {\n // AbortError is expected when loading is cancelled - don't log or dispatch\n if (isAbortError(e)) {\n return;\n }\n logError('HtmlHost', 'Error loading remote component.', e);\n this.dispatchLifecycleEvent('error', { error: e, src: this.src });\n this.hostState.stage = 'error';\n });\n }\n } else if (name === 'mode' && oldValue !== newValue && this.root) {\n // changing the shadow DOM mode is not supported\n // we need to recreate the shadow DOM and reload the component\n const newRoot = this.attachShadow({\n mode: newValue === 'closed' ? 'closed' : 'open',\n });\n // move all existing children to the new shadow root\n Array.from(this.root.children).forEach((child) => {\n newRoot.appendChild(child);\n });\n this.root = newRoot;\n // reload the remote component to apply the new shadow DOM\n this.load().catch((e) => {\n // AbortError is expected when loading is cancelled - don't log or dispatch\n if (isAbortError(e)) {\n return;\n }\n logError('HtmlHost', 'Error reloading remote component.', e);\n this.dispatchLifecycleEvent('error', { error: e, src: this.src });\n });\n }\n }\n\n async load() {\n // wait for the current call stack to finish\n await new Promise((resolve) => {\n (typeof queueMicrotask === 'function'\n ? queueMicrotask\n : requestAnimationFrame)(() => {\n resolve(undefined);\n });\n });\n\n // Abort any in-progress load so the latest src always wins.\n if (this.hostState.stage === 'loading') {\n this.hostState.abortController?.abort();\n this.hostState.stage = 'idle';\n // The aborted load may have already appended partial content to the shadow DOM\n // (styles, component children) before reaching an isCurrentLoad() check.\n // Clear it now so the new load starts from a clean state. Skip this when a\n // React root exists — that means a previous load completed successfully and\n // we'll take the startTransition re-render path instead.\n if (this.root && !this.reactRoot) {\n this.root.innerHTML = '';\n this.fouc = null;\n this.fallbackSlot = document.createElement('slot');\n this.root.appendChild(this.fallbackSlot);\n }\n }\n\n if (!this.root) {\n this.root = this.attachShadow({\n mode: this.mode === 'closed' ? 'closed' : 'open',\n });\n\n // create a slot element to allow the remote component to use the default slot\n this.fallbackSlot = document.createElement('slot');\n this.root.appendChild(this.fallbackSlot);\n }\n\n this.name = this.getAttribute('name') || this.name;\n\n this.hostState.stage = 'loading';\n const src = this.src;\n\n // Create AbortController for this load operation\n this.hostState.abortController = new AbortController();\n const signal = this.hostState.abortController.signal;\n\n // Returns true if this is still the active load — the signal hasn't been\n // aborted by a newer load() call, and the src hasn't changed in the meantime.\n // Checking the signal (not just the src) handles the case where the user\n // cycles back to the same src (e.g. styled → basic → styled): both loads\n // share the same src string, so a src-only check would pass for both,\n // causing double renders.\n const isCurrentLoad = () => !signal.aborted && this.src === src;\n\n // Resets stage to 'idle' for expected cancellations (AbortError). Real\n // errors are thrown and caught by attributeChangedCallback which sets\n // stage to 'error'. Only resets if no newer load() has superseded this\n // one — a new load replaces the abortController so the signal comparison\n // fails, preventing us from clobbering the new load's stage.\n const abandonLoad = () => {\n if (\n this.hostState.abortController?.signal === signal &&\n this.hostState.stage === 'loading'\n ) {\n this.hostState.stage = 'idle';\n }\n };\n\n this.dispatchLifecycleEvent('beforeload', { src });\n\n const remoteComponentChild =\n this.querySelector('div#__REMOTE_COMPONENT__') ||\n this.querySelector('div[data-bundle][data-route]');\n\n if (!src && !remoteComponentChild) {\n throw new RemoteComponentsError('\"src\" attribute is required');\n }\n\n let url: URL | null = null;\n let html = this.innerHTML;\n\n if (src) {\n url = getClientOrServerUrl(src, window.location.href);\n this.name = resolveNameFromSrc(src, this.name);\n }\n\n const resolveClientUrl = url\n ? bindResolveClientUrl(this.resolveClientUrl, url.href)\n : undefined;\n\n if (!remoteComponentChild && url) {\n // fetch the remote component\n const fetchInit = {\n credentials: this.credentials || 'same-origin',\n } as RequestInit;\n\n const resolvedUrl = new URL(\n resolveClientUrl?.(url.href) ?? url.href,\n window.location.href,\n );\n let res: Response;\n try {\n res = await fetchWithHooks(resolvedUrl, fetchInit, {\n onRequest: this.onRequest,\n onResponse: this.onResponse,\n abortController: this.hostState.abortController,\n });\n } catch (e) {\n if (isAbortError(e)) {\n return abandonLoad();\n }\n throw e;\n }\n\n if (!res || !res.ok) {\n throw await errorFromFailedFetch(url.href, resolvedUrl, res);\n }\n\n // get the full HTML content as a string - race with abort signal\n try {\n html = await res.text();\n } catch (e) {\n if (isAbortError(e)) {\n return abandonLoad();\n }\n throw e;\n }\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n }\n\n // create a virtual element which will be used to parse the HTML and extract the component and RSC flight data\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, 'text/html');\n\n const parsed = parseRemoteComponentDocument(\n doc,\n this.name,\n url ?? new URL(window.location.href),\n );\n const {\n component,\n name: resolvedName,\n isRemoteComponent,\n metadata: parsedMetadata,\n nextData,\n rsc,\n remoteShared,\n } = parsed;\n\n // when using a Next.js Pages Router remote application in development mode\n // we hide the remote component to prevent flickering\n // until the CSS is loaded for the remote component\n if (nextData && nextData.buildId === 'development' && !this.reactRoot) {\n this.fouc = document.createElement('style');\n this.fouc.textContent = `:host { display: none; }`;\n this.root.appendChild(this.fouc);\n }\n\n this.name = resolvedName;\n this.bundle = parsedMetadata.bundle;\n\n if (url) {\n getNamespace().bundleUrls[this.bundle] = url;\n }\n\n // add remote component metadata information at the custom element\n const metadataEl = document.createElement('script');\n metadataEl.type = 'application/json';\n metadataEl.setAttribute('data-remote-component', '');\n const metadataObj = {\n name: this.name,\n bundle: this.bundle,\n route: parsedMetadata.route,\n runtime: parsedMetadata.runtime,\n };\n metadataEl.textContent = JSON.stringify(metadataObj);\n\n if (\n this.previousElementSibling?.getAttribute('data-remote-component') !==\n null\n ) {\n this.previousElementSibling?.remove();\n }\n this.parentElement?.insertBefore(metadataEl, this);\n\n if ('__remote_components_missing_shared__' in remoteShared) {\n throw new RemoteComponentsError(\n remoteShared.__remote_components_missing_shared__,\n );\n }\n\n if (this.hostState.prevIsRemoteComponent) {\n if (this.hostState.prevUrl) {\n const prevUrl = this.hostState.prevUrl;\n const nsUnmount = getNamespace();\n if (nsUnmount.unmountFns[prevUrl.href]) {\n // call unmount() for all registered unmount functions for the previous remote component\n await Promise.all(\n Array.from(nsUnmount.unmountFns[prevUrl.href] ?? []).map(\n async (unmount) => {\n try {\n await unmount(this.root);\n } catch (e) {\n logError(\n 'HtmlHost',\n `Error while calling unmount() for Remote Component from ${prevUrl.href}.`,\n e,\n );\n }\n },\n ),\n );\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n }\n }\n this.root.innerHTML = '';\n }\n // Dispatch change event if this is not the first load\n if (this.hostState.prevSrc !== undefined) {\n this.dispatchLifecycleEvent('change', {\n previousSrc: this.hostState.prevSrc,\n nextSrc: src,\n previousName: this.hostState.prevName,\n nextName: this.name,\n });\n }\n\n this.hostState.prevUrl = url ?? new URL(window.location.href);\n this.hostState.prevIsRemoteComponent = isRemoteComponent;\n this.hostState.prevSrc = src;\n this.hostState.prevName = this.name;\n\n // store the original loading content of the custom element\n // this is required to remove the loading content after the remote component is loaded\n const removable = Array.from(this.childNodes);\n\n // reference to all link elements in the remote component\n const links = doc.querySelectorAll<HTMLLinkElement>('link[href]');\n\n const remoteComponentSrc = this.src ? String(this.src) : null;\n\n // Bound function for attaching styles — used both initially and in React effects\n const doAttachStyles = () =>\n attachStyles({\n doc,\n component,\n links,\n signal: undefined, // Effects run after load, no abort needed\n baseUrl: url?.href,\n remoteComponentSrc,\n root: this.root ?? null,\n resolveClientUrl,\n });\n\n if (!this.reactRoot) {\n // ensure all styles are loaded before hydrating to prevent FOUC\n await attachStyles({\n doc,\n component,\n links,\n signal,\n baseUrl: url?.href,\n remoteComponentSrc,\n root: this.root,\n resolveClientUrl,\n });\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n }\n\n // update all relative URLs to absolute URLs based on the remote component URL\n applyOriginToNodes(\n doc,\n url ?? new URL(window.location.href),\n resolveClientUrl,\n );\n\n if (!this.reactRoot) {\n // attach the remote component content to the shadow DOM\n Array.from(component.children).forEach((el) => {\n if (!isRemoteComponent && el.tagName.toLowerCase() === 'script') {\n const newScript = document.createElement('script');\n // copy all attributes\n for (const attr of el.attributes) {\n if (attr.name === 'src') {\n const absoluteSrc = new URL(\n attr.value,\n url ?? window.location.origin,\n ).href;\n newScript.setAttribute(\n attr.name,\n resolveClientUrl?.(absoluteSrc) ?? absoluteSrc,\n );\n } else {\n newScript.setAttribute(attr.name, attr.value);\n }\n }\n newScript.textContent = el.textContent;\n if (remoteComponentSrc) {\n newScript.setAttribute(\n 'data-remote-component-src',\n remoteComponentSrc,\n );\n }\n this.root?.appendChild(newScript);\n } else {\n const newEl = el.cloneNode(true) as HTMLElement;\n for (const attr of el.attributes) {\n if (attr.name.startsWith('on')) {\n newEl.setAttribute(attr.name, attr.value);\n }\n }\n this.root?.appendChild(newEl);\n }\n });\n }\n\n // clear the loading content of the shadow DOM root\n for (const el of removable) {\n el.parentElement?.removeChild(el);\n }\n this.fallbackSlot?.remove();\n\n // function to apply the reset styles to the shadow DOM\n const applyReset = () => {\n if (\n this.reset &&\n !this.root?.querySelector('link[data-remote-components-reset]')\n ) {\n // all initial styles to reset inherited styles leaking from the host page\n const allInitial = document.createElement('link');\n allInitial.setAttribute('data-remote-components-reset', '');\n const css = `:host { all: initial; }`;\n const allInitialHref = URL.createObjectURL(\n new Blob([css], { type: 'text/css' }),\n );\n allInitial.href = allInitialHref;\n allInitial.rel = 'stylesheet';\n // we need to revoke the object URL after the stylesheet is loaded to free up memory\n allInitial.onload = () => {\n URL.revokeObjectURL(allInitialHref);\n allInitial.removeAttribute('onload');\n };\n allInitial.onerror = () => {\n URL.revokeObjectURL(allInitialHref);\n allInitial.removeAttribute('onload');\n };\n this.root?.prepend(allInitial);\n } else if (\n !this.reset &&\n this.root?.querySelector('link[data-remote-components-reset]')\n ) {\n this.root\n .querySelector('link[data-remote-components-reset]')\n ?.remove();\n }\n };\n\n // apply the reset styles if required and not already applied\n if (!this.reactRoot) {\n applyReset();\n }\n\n const {\n self,\n createFromReadableStream,\n nextClientPagesLoader,\n preloadScripts,\n } = await getRuntime(\n metadataObj.runtime as Runtime,\n url ?? new URL(window.location.href),\n this.bundle,\n {\n react: async () => (await import('react')).default,\n 'react/jsx-dev-runtime': async () =>\n (await import('react/jsx-dev-runtime')).default,\n 'react/jsx-runtime': async () =>\n (await import('react/jsx-runtime')).default,\n 'react-dom': async () => (await import('react-dom')).default,\n 'react-dom/client': async () =>\n (await import('react-dom/client')).default,\n },\n remoteShared,\n resolveClientUrl,\n );\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n\n const scripts = isRemoteComponent\n ? component.querySelectorAll<HTMLScriptElement>('script')\n : doc.querySelectorAll<HTMLScriptElement>(\n 'script[src],script[data-src],script[data-remote-component-entrypoint]',\n );\n if (!url) {\n url = new URL(\n component.getAttribute('data-route') ?? '/',\n window.location.href,\n );\n }\n\n await preloadScripts(Array.from(scripts), url, this.bundle, this.name);\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n\n // remove all script elements from the shadow DOM to prevent re-execution of scripts\n if (isRemoteComponent) {\n Array.from(component.children).forEach((child) => {\n if (child.tagName === 'SCRIPT') {\n child.remove();\n }\n });\n }\n\n // cleanup previous remote component instances when a new remote component is loaded\n // this is required when the src attribute is changed to load a new remote component\n const doCleanup = () => {\n if (this.root && remoteComponentSrc) {\n const selector = `[data-remote-component-src]:not([data-remote-component-src=\"${remoteComponentSrc}\"])`;\n const prevCleanup = [\n ...this.root.querySelectorAll(selector),\n ...document.body.querySelectorAll(selector),\n ] as HTMLElement[];\n\n if (prevCleanup.length > 0) {\n prevCleanup.forEach((prev) => {\n prev.remove();\n });\n }\n }\n };\n\n // using RSC hydration if the RSC flight data is available\n if (rsc) {\n // remove the RSC flight data script element\n rsc.parentElement?.removeChild(rsc);\n\n // reload the RSC flight data script to eval it's content\n const rscName = `__remote_component_rsc_${escapeString(\n url.href,\n )}_${escapeString(this.name)}`;\n const rscClone = document.createElement('script');\n rscClone.id = `${rscName}_rsc`;\n rscClone.textContent =\n rsc.textContent?.replace(\n new RegExp(`self\\\\[\"${this.name}\"\\\\]`, 'g'),\n `self[\"${rscName}\"]`,\n ) ?? '';\n document.body.appendChild(rscClone);\n\n let cache: React.ReactNode;\n // React component to convert the RSC flight data into a React component\n const RemoteComponentFromReadableStream = ({\n name,\n initial,\n }: {\n name: string;\n initial: boolean;\n }) => {\n // convert the RSC flight data array into a ReadableStream\n // get the RSC flight data from the global scope\n // the RSC flight data is stored in an array\n // fallback to an empty RSC payload if the data is not found\n const stream = createRSCStream(\n rscName,\n self[rscName as RSCKey] ?? [`0:[null]\\n`],\n );\n const Component =\n cache ??\n // cache the component to avoid reloading the RSC flight data\n (cache = createFromReadableStream(stream) as React.ReactNode);\n\n useLayoutEffect(() => {\n // clear the RSC flight data from the global scope to free up memory\n if (self[name as RSCKey]) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete self[name as RSCKey];\n }\n const rscScript = document.getElementById(`${name}_rsc`);\n if (rscScript) {\n rscScript.remove();\n }\n\n doCleanup();\n applyReset();\n if (!initial) {\n doAttachStyles().catch((e: unknown) => {\n logError('HtmlHost', 'Error attaching styles.', e);\n });\n }\n if (isCurrentLoad()) {\n this.hostState.stage = 'loaded';\n }\n\n this.dispatchLifecycleEvent('load', { src: this.src });\n }, [initial, name]);\n\n // React can handle the component reference and will wait for the component to be ready\n return Component;\n };\n\n // when we already have a React root, we just need to render the new component\n if (this.reactRoot) {\n const root = this.reactRoot;\n startTransition(() => {\n root.render(\n <RemoteComponentFromReadableStream\n initial={false}\n name={this.name}\n />,\n );\n });\n return;\n }\n\n // hydrate the remote component using the RSC flight data\n this.reactRoot = hydrateRoot(\n // hydrateRoot expects a document or element, but it works for the shadow DOM too\n // @ts-expect-error support for shadow DOM\n this.root,\n <RemoteComponentFromReadableStream initial name={this.name} />,\n );\n } else if (nextData) {\n // using Next.js client pages loader if the Next.js hydration data is available\n const { Component, App } = nextClientPagesLoader(\n this.bundle,\n nextData.page ?? '/',\n this.root,\n );\n\n // if we have the component, we can hydrate it\n if (Component) {\n const RemoteComponentFromNext = ((\n NextApp: ReturnType<typeof nextClientPagesLoader>['App'],\n NextComponent: NonNullable<\n ReturnType<typeof nextClientPagesLoader>['Component']\n >,\n remoteComponent = this,\n ) =>\n function RemoteComponentNext({ initial }: { initial: boolean }) {\n useLayoutEffect(() => {\n doCleanup();\n if (!initial) {\n applyReset();\n doAttachStyles().catch((e: unknown) => {\n logError('HtmlHost', 'Error attaching styles.', e);\n });\n }\n if (isCurrentLoad()) {\n remoteComponent.hostState.stage = 'loaded';\n }\n\n remoteComponent.dispatchLifecycleEvent('load', {\n src: remoteComponent.src,\n });\n }, [initial, remoteComponent]);\n\n return NextApp ? (\n <NextApp Component={NextComponent} {...nextData.props} />\n ) : (\n <NextComponent {...nextData.props} />\n );\n })(App, Component, this);\n\n // when we already have a React root, we just need to render the new component\n if (this.reactRoot) {\n const root = this.reactRoot;\n startTransition(() => {\n root.render(<RemoteComponentFromNext initial={false} />);\n doCleanup();\n if (isCurrentLoad()) {\n this.hostState.stage = 'loaded';\n }\n });\n return;\n }\n\n // hydrate the remote component using the Next.js pages router\n this.reactRoot = hydrateRoot(\n // hydrateRoot expects a document or element, but it works for the shadow DOM too\n // @ts-expect-error support for shadow DOM\n this.root,\n <RemoteComponentFromNext initial />,\n );\n }\n\n // remove the FOUC workaround style element to show the remote component\n // this is only for development mode\n if (this.fouc) {\n this.root.removeChild(this.fouc);\n }\n } else if (getNamespace().mountFns[url.href]) {\n // using script entrypoint when no RSC or Next.js data is available\n await Promise.all(\n Array.from(getNamespace().mountFns[url.href] ?? []).map(\n async (mount) => {\n try {\n await mount(this.root);\n } catch (e) {\n logError(\n 'HtmlHost',\n `Error while calling mount() for Remote Component from ${url.href}.`,\n e,\n );\n }\n },\n ),\n );\n\n this.dispatchLifecycleEvent('load', { src: this.src });\n } else {\n this.dispatchLifecycleEvent('load', { src: this.src });\n }\n\n if (isCurrentLoad()) {\n this.hostState.stage = 'loaded';\n }\n }\n }\n\n // register the custom element\n customElements.define('remote-component', RemoteComponent);\n}\n\nexport function registerSharedModules(\n modules: Record<string, () => Promise<unknown>> = {},\n) {\n const ns = getNamespace();\n Object.entries(modules).forEach(([key, value]) => {\n ns.hostSharedModules[key] = value;\n });\n}\n","import type {\n HookOptions,\n OnRequestHook,\n OnResponseHook,\n} from '#internal/host/shared/fetch-interceptors';\nimport { warnCrossOriginFetchError } from '#internal/utils/logger';\nimport { remoteFetchHeaders } from './fetch-headers';\n\n/**\n * Options for fetching with request/response hooks.\n */\ninterface FetchWithHooksOptions {\n /** Hook to intercept the request before fetching */\n onRequest?: OnRequestHook;\n /** Hook to process the response after fetching */\n onResponse?: OnResponseHook;\n /** AbortController to cancel loading - aborts will throw AbortError */\n abortController?: AbortController;\n}\n\n/**\n * Performs a fetch with optional request and response lifecycle hooks.\n *\n * This utility centralizes the logic for:\n * 1. Calling onRequest hook - if it returns a Response, use it instead of fetching\n * 2. Performing the actual fetch if onRequest didn't provide a response\n * 3. Calling onResponse hook - if it returns a Response, use that transformed response\n *\n * Hooks receive an AbortSignal and abort function to cancel loading at any point.\n * When aborted, throws AbortError (DOMException with name 'AbortError').\n *\n * @param url - The URL to fetch\n * @param init - The fetch init options\n * @param options - Optional hooks for request/response interception and AbortController\n * @returns The response (never null - throws on abort)\n * @throws DOMException with name 'AbortError' if loading is aborted\n *\n * @example\n * const controller = new AbortController();\n * try {\n * const response = await fetchWithHooks(url, fetchInit, {\n * abortController: controller,\n * onResponse: async (url, response, { abort }) => {\n * if (response.redirected) {\n * abort(); // Throws AbortError\n * }\n * },\n * });\n * } catch (error) {\n * if (error.name === 'AbortError') {\n * console.log('Loading was aborted');\n * }\n * }\n */\nasync function fetchWithWarning(\n url: URL,\n init: RequestInit,\n): Promise<Response> {\n try {\n return await fetch(url, init);\n } catch (error) {\n warnCrossOriginFetchError('FetchRemoteComponent', url);\n throw error;\n }\n}\n\nexport async function fetchWithHooks(\n url: URL,\n additionalInit: {\n credentials?: RequestCredentials;\n next?: {\n tags?: string[];\n };\n },\n options: FetchWithHooksOptions = {},\n): Promise<Response> {\n const {\n onRequest,\n onResponse,\n abortController = new AbortController(),\n } = options;\n const signal = abortController.signal;\n\n const hookOptions: HookOptions = {\n signal,\n abort: (reason?: unknown) => abortController.abort(reason),\n };\n\n // Include signal in fetch init for reactive abort support\n const init: RequestInit = {\n method: 'GET',\n headers: remoteFetchHeaders(),\n signal,\n ...additionalInit,\n };\n\n // Call onRequest hook if provided - may return a Response to skip fetching\n const res =\n (await onRequest?.(url, init, hookOptions)) ??\n (await fetchWithWarning(url, init));\n\n // Call onResponse hook if provided - may return a transformed Response\n return (await onResponse?.(url, res, hookOptions)) ?? res;\n}\n","/**\n * The headers to use when fetching the remote component.\n */\nexport function remoteFetchHeaders() {\n return {\n /**\n * Authenticates deployment protection for the remote. Needed for SSR and SSG clients.\n * If the remote component uses vercel deployment protection, ensure the host and remote vercel\n * projects share a common automation bypass secret, and the shared secret is used as the\n * VERCEL_AUTOMATION_BYPASS_SECRET env var in the host project.\n */\n ...(typeof process === 'object' &&\n typeof process.env === 'object' &&\n typeof process.env.VERCEL_AUTOMATION_BYPASS_SECRET === 'string'\n ? {\n 'x-vercel-protection-bypass':\n process.env.VERCEL_AUTOMATION_BYPASS_SECRET,\n }\n : {}),\n Accept: 'text/html',\n };\n}\n","export function getClientOrServerUrl(\n src: string | URL | undefined,\n serverFallback: string,\n): URL {\n const fallback =\n typeof location !== 'undefined' ? location.href : serverFallback;\n\n if (!src) {\n return new URL(fallback);\n }\n\n return typeof src === 'string' ? new URL(src, fallback) : src;\n}\n","/**\n * The lifecycle stages a host progresses through during a load cycle.\n *\n * ```\n * ┌─────────────────────────┐\n * │ (new load) │\n * ▼ │\n * idle ──▶ loading ──▶ loaded ─────────┘\n * ▲ │ │\n * │ ▼ │ (new load)\n * │ error ─────────┘\n * │\n * └── loading (abandoned / aborted)\n * ```\n *\n * - `idle` — No load has started, or a previous load was abandoned.\n * - `loading` — A fetch or hydration is in progress.\n * - `loaded` — The remote component rendered successfully.\n * - `error` — The load failed (the error itself is surfaced separately).\n *\n * Any non-idle stage transitions directly to `loading` when a new load starts.\n */\nexport type HostStage = 'idle' | 'loading' | 'loaded' | 'error';\n\n/**\n * Mutable state shared by every host implementation (HTML, React, Next.js\n * App Router).\n *\n * Each host stores a single `HostState` instance rather than scattering\n * individual properties/refs. This keeps the \"what changed since the last\n * load?\" tracking consistent across frameworks and makes it easy to test\n * state transitions in isolation.\n */\nexport interface HostState {\n /** Current lifecycle stage. */\n stage: HostStage;\n\n /** Source from the most-recent load. `undefined` before the first load. */\n prevSrc: string | URL | undefined;\n\n /** Resolved URL from the most-recent load. `undefined` before the first load. */\n prevUrl: URL | undefined;\n\n /** Component name from the most-recent load. `undefined` before the first load. */\n prevName: string | undefined;\n\n /** Whether the most-recent load was a remote component (vs. a plain page). */\n prevIsRemoteComponent: boolean;\n\n /**\n * `AbortController` for the in-flight load. Abort it to cancel a\n * superseded fetch. `undefined` when no load is active.\n */\n abortController: AbortController | undefined;\n}\n\n/** Creates a fresh `HostState` with all fields at their initial values. */\nexport function createHostState(): HostState {\n return {\n stage: 'idle',\n prevSrc: undefined,\n prevUrl: undefined,\n prevName: undefined,\n prevIsRemoteComponent: false,\n abortController: undefined,\n };\n}\n","/**\n * Extracts a component name from the URL hash of `src`, falling back to\n * `defaultName` when no hash is present.\n *\n * Both the HTML and React hosts use this to derive the component name\n * from patterns like `/components/header#my-component`.\n *\n * Parses the hash directly from the string rather than constructing a\n * full `URL`, so no SSR fallback base is needed.\n */\nexport function resolveNameFromSrc(\n src: string | URL | undefined,\n defaultName: string,\n): string {\n if (!src) {\n return defaultName;\n }\n\n const hash = typeof src === 'string' ? src : src.hash;\n const hashIndex = hash.indexOf('#');\n if (hashIndex < 0) {\n return defaultName;\n }\n\n const name = hash.slice(hashIndex + 1);\n return name || defaultName;\n}\n","/**\n * Pure constants for HTML element names, data attributes, and ID suffixes\n * used across both server-side (parse5) and browser (DOM) HTML processing.\n *\n * No imports, no runtime code — safe to use in any context.\n */\n\n/** Elements whose `src`, `href`, `srcset`, and `imagesrcset` need origin rewriting. */\nexport const ORIGIN_REWRITE_TAGS = [\n 'img',\n 'source',\n 'video',\n 'audio',\n 'track',\n 'iframe',\n 'embed',\n 'script',\n 'link',\n] as const;\n\n// ID suffixes appended to the component name to form element IDs.\nexport const ID_SUFFIX_RSC = '_rsc';\nexport const ID_SUFFIX_SSR = '_ssr';\nexport const ID_SUFFIX_SHARED = '_shared';\n\n// Data attributes written on the remote component wrapper element.\nexport const DATA_BUNDLE = 'data-bundle';\nexport const DATA_ROUTE = 'data-route';\nexport const DATA_RUNTIME = 'data-runtime';\nexport const DATA_TYPE = 'data-type';\nexport const DATA_SRC = 'data-src';\nexport const DATA_REMOTE_COMPONENTS_SHARED = 'data-remote-components-shared';\n\n// Well-known element identifiers.\nexport const TAG_REMOTE_COMPONENT = 'remote-component';\nexport const NEXT_DATA_ID = '__NEXT_DATA__';\nexport const REMOTE_NEXT_DATA_ID = '__REMOTE_NEXT_DATA__';\nexport const NEXT_CONTAINER_ID = '__next';\n","/**\n * Rewrites relative URLs in an HTML `srcset` or `imagesrcset` attribute value\n * to absolute URLs. Works identically in server (parse5) and browser (DOM) contexts.\n *\n * @param srcset - The raw srcset attribute value (comma-separated entries).\n * @param base - Base URL or origin to resolve relative URLs against.\n * @param resolve - Optional callback applied to each absolute URL (e.g. to proxy through a CDN).\n * @returns The rewritten srcset string with absolute (and optionally resolved) URLs.\n */\nexport function rewriteSrcset(\n srcset: string,\n base: URL | string,\n resolve?: (absoluteUrl: string) => string,\n): string {\n return srcset\n .split(',')\n .map((entry) => {\n const [url, descriptor] = entry.trim().split(/\\s+/);\n if (!url) return entry;\n\n const absoluteUrl = new URL(url, base).href;\n const resolvedUrl = resolve ? resolve(absoluteUrl) : absoluteUrl;\n return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;\n })\n .join(', ');\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { ORIGIN_REWRITE_TAGS } from './html-spec';\nimport { rewriteSrcset } from './rewrite-srcset';\n\nexport function applyOriginToNodes(\n doc: Document | HTMLElement,\n url: URL,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n if (url.origin !== location.origin) {\n const nodes = doc.querySelectorAll<HTMLImageElement>(\n ORIGIN_REWRITE_TAGS.map(\n (type) =>\n `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`,\n ).join(','),\n );\n nodes.forEach((node) => {\n if (\n node.hasAttribute('src') &&\n /^[./]+\\/?/.test(node.getAttribute('src') ?? '')\n ) {\n const absoluteSrc = new URL(node.getAttribute('src') ?? '/', url).href;\n // Script elements are handled by the loaders (script-loader, static-loader)\n // which apply the callback themselves. Only apply it here for non-script elements.\n const isScript = node.tagName.toLowerCase() === 'script';\n node.src = isScript\n ? absoluteSrc\n : (resolveClientUrl?.(absoluteSrc) ?? absoluteSrc);\n }\n if (\n node.hasAttribute('href') &&\n /^[./]+\\/?/.test(node.getAttribute('href') ?? '')\n ) {\n const absoluteHref = new URL(node.getAttribute('href') ?? '/', url)\n .href;\n node.setAttribute(\n 'href',\n resolveClientUrl?.(absoluteHref) ?? absoluteHref,\n );\n }\n if (node.hasAttribute('srcset')) {\n const raw = node.getAttribute('srcset');\n if (raw) {\n const resolve = resolveClientUrl\n ? (abs: string) => resolveClientUrl(abs) ?? abs\n : undefined;\n node.setAttribute('srcset', rewriteSrcset(raw, url, resolve));\n }\n }\n if (node.hasAttribute('imagesrcset')) {\n const raw = node.getAttribute('imagesrcset');\n if (raw) {\n const resolve = resolveClientUrl\n ? (abs: string) => resolveClientUrl(abs) ?? abs\n : undefined;\n node.setAttribute('imagesrcset', rewriteSrcset(raw, url, resolve));\n }\n }\n });\n }\n}\n","import type { NextData } from '#internal/host/server/types';\nimport {\n DEFAULT_COMPONENT_NAME,\n RUNTIME_SCRIPT,\n} from '#internal/runtime/constants';\nimport {\n buildMetadata,\n type RemoteComponentMetadata,\n} from '#internal/runtime/metadata';\nimport {\n multipleRemoteComponentsError,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport {\n DATA_BUNDLE,\n DATA_REMOTE_COMPONENTS_SHARED,\n DATA_ROUTE,\n DATA_RUNTIME,\n DATA_SRC,\n DATA_TYPE,\n ID_SUFFIX_RSC,\n ID_SUFFIX_SHARED,\n ID_SUFFIX_SSR,\n NEXT_CONTAINER_ID,\n NEXT_DATA_ID,\n REMOTE_NEXT_DATA_ID,\n TAG_REMOTE_COMPONENT,\n} from './html-spec';\n\nexport interface ParsedRemoteComponent {\n /** The DOM element representing the remote component content. */\n component: Element;\n /** Resolved name of the remote component (with _ssr suffix stripped). */\n name: string;\n /** Whether the component is a <remote-component> custom element. */\n isRemoteComponent: boolean;\n /** Component metadata: bundle, route, runtime. */\n metadata: RemoteComponentMetadata;\n /** Parsed __NEXT_DATA__ or __REMOTE_NEXT_DATA__, or null. */\n nextData: NextData | null;\n /** The RSC flight data script element, or null. */\n rsc: Element | null;\n /** Shared module map extracted from the component's shared data script. */\n remoteShared: Record<string, string>;\n /** Link elements extracted from the document (outside the component). */\n links: HTMLLinkElement[];\n /** Script elements extracted from the component or document. */\n scripts: HTMLScriptElement[];\n}\n\n/**\n * Validates that the document does not contain multiple unnamed remote components.\n * When multiple components exist, the consumer must specify a name to select one.\n */\nexport function validateSingleComponent(\n doc: Document,\n name: string,\n url: string,\n): void {\n if (\n (doc.querySelectorAll(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`).length > 1 &&\n !doc.querySelector(\n `div[${DATA_BUNDLE}][${DATA_ROUTE}][id^=\"${name}\"]`,\n )) ||\n (doc.querySelectorAll(`${TAG_REMOTE_COMPONENT}:not([src])`).length > 1 &&\n !doc.querySelector(`${TAG_REMOTE_COMPONENT}[name=\"${name}\"]`))\n ) {\n throw multipleRemoteComponentsError(url);\n }\n}\n\n/**\n * Finds the remote component element in the parsed HTML document using the\n * standard querySelector chain. Returns null if no component is found.\n */\nexport function findComponentElement(\n doc: Document,\n name: string,\n): Element | null {\n return (\n doc.querySelector(`div[${DATA_BUNDLE}][${DATA_ROUTE}][id^=\"${name}\"]`) ??\n doc.querySelector(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`) ??\n doc.querySelector(`div#${NEXT_CONTAINER_ID}`) ??\n doc.querySelector(`${TAG_REMOTE_COMPONENT}[name=\"${name}\"]:not([src])`) ??\n doc.querySelector(`${TAG_REMOTE_COMPONENT}:not([src])`)\n );\n}\n\n/**\n * Parses the __NEXT_DATA__ or __REMOTE_NEXT_DATA__ script element from the document.\n */\nexport function parseNextData(doc: Document): NextData | null {\n return JSON.parse(\n (\n doc.querySelector(`#${NEXT_DATA_ID}`) ??\n doc.querySelector(`#${REMOTE_NEXT_DATA_ID}`)\n )?.textContent ?? 'null',\n ) as NextData | null;\n}\n\n/**\n * Resolves the component name from the element's id attribute, the name attribute\n * (for <remote-component> elements), nextData, or a fallback value.\n * Strips the _ssr suffix from the id if present.\n */\nexport function resolveComponentName(\n component: Element | null,\n nextData: NextData | null,\n fallbackName: string,\n): { name: string; isRemoteComponent: boolean } {\n const isRemoteComponent =\n component?.tagName.toLowerCase() === TAG_REMOTE_COMPONENT;\n\n const name =\n component\n ?.getAttribute('id')\n ?.replace(new RegExp(`${ID_SUFFIX_SSR}$`), '') ||\n (isRemoteComponent && component?.getAttribute('name')) ||\n (nextData ? '__next' : fallbackName);\n\n return { name, isRemoteComponent };\n}\n\n/**\n * Extracts the shared module map from the document and removes the element.\n * Falls back to nextData's shared modules if available.\n */\nexport function extractRemoteShared(\n doc: Document,\n name: string,\n nextData: NextData | null,\n): Record<string, string> {\n const remoteSharedEl = doc.querySelector(\n `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`,\n );\n const remoteShared =\n nextData?.props.__REMOTE_COMPONENT__?.shared ??\n ((JSON.parse(remoteSharedEl?.textContent ?? '{}') ?? {}) as Record<\n string,\n string\n >);\n remoteSharedEl?.remove();\n return remoteShared;\n}\n\n/**\n * Validates that a remote component was found in the document and that it has\n * RSC data, Next.js data, or is a <remote-component> element.\n * Acts as a type assertion - narrows component to non-null on success.\n */\nexport function validateComponentFound(\n component: Element | null,\n rsc: Element | null,\n nextData: NextData | null,\n isRemoteComponent: boolean,\n url: string,\n name: string,\n): asserts component is Element {\n if (!component || !(rsc || nextData || isRemoteComponent)) {\n throw new RemoteComponentsError(\n `Remote Component not found on ${url}.${\n name !== DEFAULT_COMPONENT_NAME\n ? ` The name for the <RemoteComponent> is \"${name}\". Check <RemoteComponent> usage.`\n : ''\n } Did you forget to wrap the content in <RemoteComponent>?`,\n );\n }\n}\n\n/**\n * Extracts link elements from the document that are not inside the component.\n */\nexport function extractLinks(\n doc: Document,\n component: Element,\n): HTMLLinkElement[] {\n return Array.from(doc.querySelectorAll<HTMLLinkElement>('link[href]')).filter(\n (link) => !component.contains(link),\n );\n}\n\n/**\n * Extracts script elements from the component or document, depending on whether\n * the component is a <remote-component> custom element.\n */\nexport function extractScripts(\n doc: Document,\n component: Element,\n isRemoteComponent: boolean,\n): HTMLScriptElement[] {\n return Array.from(\n (isRemoteComponent ? component : doc).querySelectorAll<HTMLScriptElement>(\n `script[src],script[${DATA_SRC}]`,\n ),\n );\n}\n\n/**\n * Parses a remote component HTML document and extracts all data needed for\n * loading and hydrating the component. This is the main orchestrator that\n * calls the individual extraction functions.\n */\nexport function parseRemoteComponentDocument(\n doc: Document,\n name: string,\n url: URL,\n): ParsedRemoteComponent {\n validateSingleComponent(doc, name, url.href);\n\n const component = findComponentElement(doc, name);\n const nextData = parseNextData(doc);\n\n const { name: resolvedName, isRemoteComponent } = resolveComponentName(\n component,\n nextData,\n name,\n );\n\n const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);\n const metadata = buildMetadata(\n {\n name: resolvedName,\n bundle:\n component?.getAttribute(DATA_BUNDLE) ||\n nextData?.props.__REMOTE_COMPONENT__?.bundle,\n route: component?.getAttribute(DATA_ROUTE) ?? nextData?.page,\n runtime:\n component?.getAttribute(DATA_RUNTIME) ??\n nextData?.props.__REMOTE_COMPONENT__?.runtime ??\n RUNTIME_SCRIPT,\n id: component?.getAttribute('id'),\n type: component?.getAttribute(DATA_TYPE),\n },\n url,\n );\n const remoteShared = extractRemoteShared(doc, resolvedName, nextData);\n\n validateComponentFound(\n component,\n rsc,\n nextData,\n isRemoteComponent,\n url.href,\n resolvedName,\n );\n\n const links = extractLinks(doc, component);\n const scripts = extractScripts(doc, component, isRemoteComponent);\n\n return {\n component,\n name: resolvedName,\n isRemoteComponent,\n metadata,\n nextData,\n rsc,\n remoteShared,\n links,\n scripts,\n };\n}\n","import {\n DEFAULT_BUNDLE_NAME,\n DEFAULT_COMPONENT_NAME,\n DEFAULT_ROUTE,\n} from '#internal/runtime/constants';\n\n/**\n * Metadata embedded in the HTML response by a remote application.\n *\n * Extracted from a `<script type=\"application/json\" data-remote-component>`\n * element during both SSR parsing ({@link fetchRemoteComponent}) and\n * client-side parsing ({@link parseRemoteComponentDocument}).\n */\nexport interface RemoteComponentMetadata {\n name: string;\n bundle: string;\n route: string;\n runtime: 'webpack' | 'turbopack' | 'script';\n id: string;\n type: 'nextjs' | 'remote-component' | 'unknown';\n}\n\n/**\n * Raw attribute values before defaults are applied. Accepts nullable strings\n * so callers can pass DOM attributes or parsed JSON directly.\n */\nexport interface RawMetadataAttrs {\n name?: string | null;\n bundle?: string | null;\n route?: string | null;\n runtime?: string | null;\n id?: string | null;\n type?: string | null;\n}\n\nconst VALID_RUNTIMES: Set<string> = new Set(['webpack', 'turbopack', 'script']);\nconst VALID_TYPES: Set<string> = new Set([\n 'nextjs',\n 'remote-component',\n 'unknown',\n]);\n\nfunction isRuntime(value: string): value is RemoteComponentMetadata['runtime'] {\n return VALID_RUNTIMES.has(value);\n}\n\nfunction isComponentType(\n value: string,\n): value is RemoteComponentMetadata['type'] {\n return VALID_TYPES.has(value);\n}\n\nfunction toRuntime(\n value: string | null | undefined,\n): RemoteComponentMetadata['runtime'] {\n return value && isRuntime(value) ? value : 'webpack';\n}\n\nfunction toComponentType(\n value: string | null | undefined,\n): RemoteComponentMetadata['type'] {\n return value && isComponentType(value) ? value : 'unknown';\n}\n\n/**\n * Applies default values to raw metadata attributes and returns a fully\n * resolved {@link RemoteComponentMetadata}. When no bundle is provided, falls\n * back to the `NEXT_PUBLIC_MFE_CURRENT_APPLICATION` env var (the host's\n * application name), then `DEFAULT_BUNDLE_NAME`.\n */\nexport function buildMetadata(\n attrs: RawMetadataAttrs,\n url: URL,\n): RemoteComponentMetadata {\n const id = attrs.id || DEFAULT_COMPONENT_NAME;\n const bundle =\n attrs.bundle ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n DEFAULT_BUNDLE_NAME;\n return {\n name: attrs.name || id.replace(/_ssr$/, ''),\n bundle,\n route: attrs.route || url.pathname || DEFAULT_ROUTE,\n runtime: toRuntime(attrs.runtime),\n id,\n type: toComponentType(attrs.type),\n };\n}\n","import { ReadableStream } from 'web-streams-polyfill';\n\n/**\n * Fixes RSC payload arrays to be compatible with React JSX development runtime.\n * React elements in the wire format are 4-element arrays (`['$', type, key, props]`);\n * the dev runtime expects 7 elements with debug info in positions 4-6.\n */\nexport function fixPayload(payload: unknown): void {\n if (Array.isArray(payload)) {\n if (payload[0] === '$') {\n // React element — fix props recursively, then pad to 7 elements\n fixPayload(payload[3]);\n if (payload.length === 4) {\n payload.push(null, null, 1);\n }\n } else {\n for (const item of payload) {\n fixPayload(item);\n }\n }\n } else if (typeof payload === 'object' && payload !== null) {\n for (const key in payload) {\n fixPayload((payload as Record<string, unknown>)[key]);\n }\n }\n}\n\n/**\n * Parses raw RSC script chunks (the `self[\"name\"].push(\"...\")` format produced\n * by `<RemoteComponentData>`) into a flat array of flight-data strings.\n *\n * This is a pure function — it reads from `data` only, never from `globalThis`.\n */\nexport function buildRSCChunks(rscName: string, data: string[]): string[] {\n const chunks: string[] = [];\n\n for (const chunk of data) {\n for (const line of chunk.split('\\n')) {\n const match = /\\.push\\(\"(?<rsc>.*)\"\\);$/.exec(line);\n if (match?.groups?.rsc) {\n chunks.push(JSON.parse(`\"${match.groups.rsc}\"`) as string);\n }\n }\n }\n\n return chunks;\n}\n\n/**\n * Processes RSC flight data and creates a ReadableStream.\n *\n * First checks `data` for inline script chunks (parsed via {@link buildRSCChunks}),\n * merging them onto `globalThis[rscName]`. Then consumes the global array\n * (or falls back to an empty RSC payload) and pipes fixed chunks into the stream.\n */\nexport function createRSCStream(\n rscName: string,\n data: string[],\n): ReadableStream<Uint8Array> {\n return new ReadableStream({\n type: 'bytes',\n start(controller) {\n const encoder = new TextEncoder();\n const self = globalThis as typeof globalThis &\n Record<string, string[] | null>;\n\n // Parse inline script chunks and merge onto the global array\n if (data.length > 0) {\n const parsed = buildRSCChunks(rscName, data);\n if (parsed.length > 0) {\n self[rscName] = self[rscName] ?? [];\n self[rscName].push(...parsed);\n }\n }\n\n // Consume the global RSC flight data, falling back to an empty payload\n const allChunks = (self[rscName] ?? [`0:[null]\\n`]).join('');\n self[rscName] = null;\n\n // Process each line in the RSC flight data\n allChunks.split('\\n').forEach((chunk) => {\n if (chunk.length > 0) {\n const { before, id, prefix, payload } =\n /^(?<before>[^:]*?)?(?<id>[0-9a-zA-Z]+):(?<prefix>[A-Z])?(?<payload>\\[.*\\])/.exec(\n chunk,\n )?.groups ?? {};\n\n if (payload) {\n const jsonPayload = JSON.parse(payload) as unknown[];\n fixPayload(jsonPayload);\n const reconstruct = `${before ?? ''}${id}:${prefix ?? ''}${JSON.stringify(jsonPayload)}`;\n controller.enqueue(encoder.encode(`${reconstruct}\\n`));\n } else {\n controller.enqueue(encoder.encode(`${chunk}\\n`));\n }\n } else {\n controller.enqueue(encoder.encode(`${chunk}\\n`));\n }\n });\n controller.close();\n },\n });\n}\n","/**\n * Intercepts client-side URL resolution for remote component resources.\n * Called before each asset (script, stylesheet, chunk, module, image) is fetched.\n *\n * Return a new URL string to redirect the fetch (e.g., through a proxy),\n * or undefined to use the original URL.\n *\n * @param remoteSrc - The `src` of the remote component being loaded\n * @param url - The asset URL about to be fetched\n *\n * @example\n * // Proxy all assets from the remote's origin through the host\n * const resolveClientUrl = (remoteSrc, url) => {\n * const remoteOrigin = new URL(remoteSrc).origin;\n * const parsed = new URL(url);\n * if (parsed.origin !== location.origin && parsed.origin === remoteOrigin) {\n * return `/rc-fetch-protected-remote?url=${encodeURIComponent(url)}`;\n * }\n * };\n */\nexport type ResolveClientUrl = (\n remoteSrc: string,\n url: string,\n) => string | undefined;\n\n/**\n * Internal bound resolver — `ResolveClientUrl` with `remoteSrc` already applied.\n * Used by internal loaders that don't need to know the remote src.\n */\nexport type InternalResolveClientUrl = (url: string) => string | undefined;\n\n/**\n * Binds a `ResolveClientUrl` to a specific `remoteSrc`, producing an\n * `InternalResolveClientUrl` that only needs the asset URL.\n *\n * Only invokes the callback for URLs whose origin matches the remote\n * component's origin. Third-party scripts (e.g. `vercel.live` toolbar)\n * are left untouched. To proxy additional domains in the future, a\n * field or flag can be added to the host configuration.\n */\nexport function withRemoteSrc(\n resolveClientUrl: ResolveClientUrl,\n remoteSrc: string,\n): InternalResolveClientUrl {\n const remoteOrigin = parseOrigin(remoteSrc);\n return (url) => {\n const urlOrigin = parseOrigin(url);\n if (remoteOrigin && urlOrigin && urlOrigin !== remoteOrigin) {\n return undefined;\n }\n return resolveClientUrl(remoteSrc, url);\n };\n}\n\nfunction parseOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n","import {\n type InternalResolveClientUrl,\n type ResolveClientUrl,\n withRemoteSrc,\n} from './resolve-client-url';\n\nexport function bindResolveClientUrl(\n prop: ResolveClientUrl | undefined,\n remoteSrc: string,\n): InternalResolveClientUrl | undefined {\n return prop ? withRemoteSrc(prop, remoteSrc) : undefined;\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\ninterface AttachStylesOptions {\n /** The parsed document containing link and style elements */\n doc: Document;\n /** The component element to check if links are already contained */\n component: Element;\n /** Links from the document head */\n links: NodeListOf<HTMLLinkElement>;\n /** AbortSignal to cancel loading */\n signal: AbortSignal | undefined;\n /** Base URL for resolving relative hrefs */\n baseUrl: string | undefined;\n /** Source URL to set as data attribute */\n remoteComponentSrc: string | null;\n /** Root element to append styles to (ShadowRoot or Element) */\n root: ShadowRoot | Element | null;\n /** Callback to transform asset URLs before loading */\n resolveClientUrl?: InternalResolveClientUrl;\n}\n\n/**\n * Attaches link and style elements from a remote component document to the shadow root.\n * Handles abort signals efficiently with a single shared listener for all links.\n *\n * @throws DOMException with name 'AbortError' if signal is aborted\n * @throws RemoteComponentsError if a stylesheet fails to load\n */\nexport async function attachStyles({\n doc,\n component,\n links,\n signal,\n baseUrl,\n remoteComponentSrc,\n root,\n resolveClientUrl,\n}: AttachStylesOptions): Promise<void> {\n // Track appended links for cleanup on abort\n const appendedLinks: HTMLLinkElement[] = [];\n\n // Single shared abort promise - avoids N listeners for N links\n let abortReject: ((error: DOMException) => void) | null = null;\n const abortPromise = new Promise<never>((_, reject) => {\n abortReject = reject;\n });\n const abortHandler = () => {\n // Clean up all pending links on abort\n for (const link of appendedLinks) {\n link.onload = null;\n link.onerror = null;\n link.remove();\n }\n abortReject?.(new DOMException('Aborted', 'AbortError'));\n };\n signal?.addEventListener('abort', abortHandler, { once: true });\n\n try {\n // Attach each link element to the shadow DOM to load the styles\n await Promise.all(\n Array.from(links)\n .filter((link) => !component.contains(link))\n .map((link) => {\n const newLink = document.createElement('link');\n appendedLinks.push(newLink);\n\n const loadPromise = new Promise<void>((resolve, reject) => {\n if (link.rel === 'stylesheet') {\n // TODO: needs to be cancellable with a singular listener for the abort signal https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\n newLink.onload = () => resolve();\n newLink.onerror = () =>\n reject(\n new RemoteComponentsError(\n `Failed to load <link href=\"${link.href}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n } else {\n resolve();\n }\n });\n\n for (const attr of link.attributes) {\n if (attr.name === 'href') {\n const absoluteHref = new URL(\n attr.value,\n baseUrl ?? location.origin,\n ).href;\n newLink.setAttribute(\n attr.name,\n resolveClientUrl?.(absoluteHref) ?? absoluteHref,\n );\n } else {\n newLink.setAttribute(attr.name, attr.value);\n }\n }\n\n if (remoteComponentSrc) {\n newLink.setAttribute(\n 'data-remote-component-src',\n remoteComponentSrc,\n );\n }\n\n // TODO: needs to be cancellable with a singular listener for the abort signal https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\n root?.appendChild(newLink);\n\n // Race each link load against the shared abort promise\n return Promise.race([loadPromise, abortPromise]);\n }),\n );\n } finally {\n signal?.removeEventListener('abort', abortHandler);\n }\n\n // Attach inline styles from the document head\n const styles = doc.querySelectorAll<HTMLStyleElement>('style');\n for (const style of styles) {\n if (style.parentElement?.tagName.toLowerCase() === 'head') {\n const newStyle = document.createElement('style');\n newStyle.textContent = style.textContent;\n\n if (remoteComponentSrc) {\n newStyle.setAttribute('data-remote-component-src', remoteComponentSrc);\n }\n\n root?.appendChild(newStyle);\n }\n }\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\nexport type Runtime = 'webpack' | 'turbopack' | 'script' | 'unknown';\n\nexport async function getRuntime(\n type: Runtime,\n url: URL,\n bundle: string,\n shared?: Record<string, () => Promise<unknown>>,\n remoteShared?: Record<string, string>,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n // minimally mock process.env for browser environments\n if (typeof globalThis.process === 'undefined') {\n globalThis.process = {\n env: {},\n } as NodeJS.Process;\n }\n\n if (type === 'webpack') {\n const { webpackRuntime } = await import(`./webpack`);\n return webpackRuntime(bundle, shared, remoteShared, resolveClientUrl);\n } else if (type === 'turbopack') {\n const { turbopackRuntime } = await import(`./turbopack`);\n return turbopackRuntime(\n url,\n bundle,\n shared,\n remoteShared,\n resolveClientUrl,\n );\n } else if (type === 'script') {\n const { scriptRuntime } = await import(`./script`);\n return scriptRuntime(resolveClientUrl);\n }\n throw new RemoteComponentsError(\n `Remote Components runtime \"${type}\" is not supported. Supported runtimes are \"webpack\", \"turbopack\", and \"script\".`,\n );\n}\n"],"mappings":";;;;;;;;;;;AAAA,IAAa,oCAKA;AALb;AAAA;AAAA;AAAO,IAAM,qCAAqC;AAK3C,IAAM,gBACX;AAAA;AAAA;;;ACGK,SAAS,aAAa,KAAsB;AACj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G;AACnB,aAAK,UAAU,QAAQ;AAAA,MACzB;AAAA,IACF;AAAA,EACF;AAGA,iBAAe,OAAO,oBAAoB,eAAe;AAC3D;AAEO,SAAS,sBACd,UAAkD,CAAC,GACnD;AACA,QAAM,KAAK,aAAa;AACxB,SAAO,QAAQ,OAAO,EAAE,QAAQ,CAAC,CAAC,KAAK,KAAK,MAAM;AAChD,OAAG,kBAAkB,GAAG,IAAI;AAAA,EAC9B,CAAC;AACH;","names":["location","init_constants","init_constants","init_patterns","init_constants","init_patterns","init_patterns","scope","init_constants","init_constants","init_constants","init_constants","webpackRuntime","turbopackRuntime","scriptRuntime","jsx","nextClientPagesLoader"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/constants.ts","../../src/runtime/url/protected-rc-fallback.ts","../../src/utils/abort.ts","../../src/utils/error.ts","../../src/utils/logger.ts","../../src/utils/index.ts","../../src/runtime/constants.ts","../../src/runtime/namespace.ts","../../src/runtime/patterns.ts","../../src/runtime/turbopack/remote-scope.ts","../../src/host/shared/remote-image-loader.ts","../../src/host/shared/polyfill.tsx","../../src/host/shared/shared-module-resolver.ts","../../src/config/webpack/apply-shared-modules.ts","../../src/config/webpack/next-client-pages-loader.ts","../../src/runtime/turbopack/patterns.ts","../../src/runtime/turbopack/chunk-loader.ts","../../src/runtime/turbopack/shared-modules.ts","../../src/runtime/turbopack/module.ts","../../src/runtime/turbopack/remote-scope-setup.ts","../../src/runtime/loaders/script-loader.ts","../../src/runtime/loaders/static-loader.ts","../../src/host/html/runtime/webpack.ts","../../src/host/html/runtime/turbopack.ts","../../src/host/html/runtime/script.ts","../../src/host/html/index.tsx","../../src/host/server/fetch-with-hooks.ts","../../src/host/server/fetch-headers.ts","../../src/host/server/get-client-or-server-url.ts","../../src/host/shared/lifecycle.ts","../../src/host/shared/pipeline.ts","../../src/runtime/html/html-spec.ts","../../src/runtime/html/rewrite-srcset.ts","../../src/runtime/html/apply-origin.ts","../../src/runtime/html/parse-remote-html.ts","../../src/runtime/metadata.ts","../../src/runtime/loaders/component-loader.ts","../../src/runtime/rsc.ts","../../src/host/shared/state.ts","../../src/host/utils/resolve-name-from-src.ts","../../src/runtime/url/resolve-client-url.ts","../../src/runtime/url/default-resolve-client-url.ts","../../src/host/html/attach-styles.ts","../../src/host/html/runtime/index.ts"],"sourcesContent":["export const RC_PROTECTED_REMOTE_FETCH_PATHNAME = '/rc-fetch-protected-remote';\n\nexport const MISSING_SHARED_MODULES_MESSAGE =\n 'Remote Components shared modules not found. Did you forget to wrap your config with `withRemoteComponentsConfig` on both host and remote?';\n\nexport const CORS_DOCS_URL =\n 'https://vercel.com/docs/remote-components/concepts/cors-external-urls#accessing-cross-site-protected-remote-components';\n","import { RC_PROTECTED_REMOTE_FETCH_PATHNAME } from '#internal/utils/constants';\n\n/**\n * Generates a fallback URL that proxies the request through the host's protected remote fetch endpoint\n */\nexport function generateProtectedRcFallbackSrc(url: string): string {\n return `${RC_PROTECTED_REMOTE_FETCH_PATHNAME}?url=${encodeURIComponent(url)}`;\n}\n\nexport function isProxiedUrl(url: string): boolean {\n try {\n return (\n new URL(url, location.href).pathname ===\n RC_PROTECTED_REMOTE_FETCH_PATHNAME\n );\n } catch {\n return false;\n }\n}\n","/**\n * Type guard to check if an error is an AbortError.\n * Handles cross-environment differences (Node.js, browsers, JSDOM).\n */\nexport function isAbortError(error: unknown): error is DOMException {\n if (error instanceof DOMException && error.name === 'AbortError') {\n return true;\n }\n\n // Handle Node.js native AbortError which may not be instanceof global DOMException\n if (\n error !== null &&\n typeof error === 'object' &&\n 'name' in error &&\n error.name === 'AbortError' &&\n 'message' in error &&\n typeof (error as { message: unknown }).message === 'string'\n ) {\n // Additional check: verify it has DOMException-like structure\n const e = error as { code?: unknown; constructor?: { name?: string } };\n return typeof e.code === 'number' || e.constructor?.name === 'DOMException';\n }\n\n return false;\n}\n","import { isProxiedUrl } from '#internal/runtime/url/protected-rc-fallback';\nimport { isAbortError } from '#internal/utils/abort';\nimport {\n CORS_DOCS_URL,\n RC_PROTECTED_REMOTE_FETCH_PATHNAME,\n} from '#internal/utils/constants';\n\nexport class RemoteComponentsError extends Error {\n code = 'REMOTE_COMPONENTS_ERROR';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'RemoteComponentsError';\n }\n}\n\nexport function multipleRemoteComponentsError(url: string | undefined) {\n return new RemoteComponentsError(\n `Multiple Remote Components found at \"${url}\". When a page exposes multiple Remote Components you must specify the \"name\" prop to select which one to load.`,\n );\n}\n\nexport function failedToFetchRemoteComponentError(\n url: string,\n { status, statusText }: { status: number; statusText: string },\n help: string = 'Is the URL correct and accessible?',\n) {\n return new RemoteComponentsError(\n `Failed to fetch Remote Component from \"${url}\". ${help}`,\n { cause: new Error(`${status} ${statusText}`) },\n );\n}\n\nexport async function errorFromFailedFetch(\n originalUrl: string,\n resolvedUrl: URL,\n res: Response | null | undefined,\n): Promise<RemoteComponentsError> {\n const isProxied = isProxiedUrl(resolvedUrl.href);\n\n if (isProxied && res) {\n const body = await res.text().catch(() => '');\n return failedProxyFetchError(\n originalUrl,\n resolvedUrl.href,\n res.status,\n body,\n );\n }\n\n const fallback = failedToFetchRemoteComponentError(\n originalUrl,\n res ?? { status: 0, statusText: 'No Response' },\n );\n\n if (!res) return fallback;\n\n try {\n const body = await res.text();\n const parser = new DOMParser();\n const doc = parser.parseFromString(body, 'text/html');\n const errorTemplate = doc.querySelector(\n 'template[data-next-error-message]',\n );\n const errorMessage = errorTemplate?.getAttribute('data-next-error-message');\n if (errorMessage) {\n const error = new RemoteComponentsError(errorMessage);\n const errorStack = errorTemplate?.getAttribute('data-next-error-stack');\n if (errorStack) {\n error.stack = errorStack;\n }\n return error;\n }\n } catch (parseError) {\n // Re-throw abort errors, ignore parse errors\n if (isAbortError(parseError)) throw parseError;\n }\n\n return fallback;\n}\n\nexport function failedProxiedAssetError(\n kind: 'chunk' | 'script',\n url: string,\n resolvedUrl: string,\n): RemoteComponentsError {\n return new RemoteComponentsError(\n `Failed to load ${kind} \"${url}\" via proxy \"${resolvedUrl}\". ` +\n `Ensure withRemoteComponentsHostProxy middleware is configured, \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" is in the matcher, ` +\n `and the remote URL is included in allowedProxyUrls. ` +\n `See: ${CORS_DOCS_URL}`,\n );\n}\n\nexport function failedProxyFetchError(\n originalUrl: string,\n proxyUrl: string,\n status: number,\n responseBody?: string,\n): RemoteComponentsError {\n if (status === 404) {\n return new RemoteComponentsError(\n `Could not proxy the request to \"${originalUrl}\" — the proxy endpoint \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" returned 404.\\n\\n` +\n `The host server needs middleware or a route that handles \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\".\\n\\n` +\n `Proxying requires two pieces:\\n` +\n ` 1. resolveClientUrl={routeThroughHostProxy} on <RemoteComponent>\\n` +\n ` 2. Middleware or a route for \"${RC_PROTECTED_REMOTE_FETCH_PATHNAME}\" on the host server\\n\\n` +\n `Docs: ${CORS_DOCS_URL}`,\n );\n }\n if (status === 403) {\n const detail = responseBody ? ` ${responseBody}` : '';\n return new RemoteComponentsError(\n `Proxied request to \"${proxyUrl}\" was forbidden.${detail} ` +\n `See: ${CORS_DOCS_URL}`,\n );\n }\n return new RemoteComponentsError(\n `Proxied request for \"${originalUrl}\" via \"${proxyUrl}\" failed with status ${status}. ` +\n `See: ${CORS_DOCS_URL}`,\n );\n}\n","import { CORS_DOCS_URL } from '#internal/utils/constants';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\nexport type LogLocation =\n | 'ChunkLoader'\n | 'ChunkDispatcher'\n | 'ComponentLoader'\n | 'ModuleDispatcher'\n | 'RemoteScope'\n | 'SharedModules'\n | 'WebpackRuntime'\n | 'TurbopackModule'\n | 'StaticLoader'\n | 'ScriptLoader'\n | 'Polyfill'\n | 'HtmlRemote'\n | 'HtmlHost'\n | 'Config'\n | 'NextAppRouter'\n | 'NextAppRouterCompat'\n | 'FetchRemoteComponent'\n | 'SharedModuleResolver';\n\nconst PREFIX = 'remote-components';\nconst DEBUG =\n (typeof window !== 'undefined' &&\n localStorage.getItem('RC_DEBUG') === 'true') ||\n (typeof process !== 'undefined' && process.env.RC_DEBUG === 'true');\n\nexport function logDebug(location: LogLocation, message: string) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.debug(`[${PREFIX}:${location}]: ${message}`);\n }\n}\n\nexport function logInfo(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.info(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logWarn(location: LogLocation, message: string) {\n // eslint-disable-next-line no-console\n console.warn(`[${PREFIX}:${location}]: ${message}`);\n}\n\nexport function logError(\n location: LogLocation,\n message: string,\n cause?: unknown,\n) {\n // eslint-disable-next-line no-console\n console.error(\n new RemoteComponentsError(`[${PREFIX}:${location}]: ${message}`, {\n cause,\n }),\n );\n}\n\n/**\n * Logs a warning when a cross-origin asset request fails, guiding users\n * to configure the proxy middleware and resolveClientUrl on their host.\n */\nexport function warnCrossOriginFetchError(\n logLocation: LogLocation,\n url: string | URL,\n): void {\n try {\n const parsed = typeof url === 'string' ? new URL(url) : url;\n if (typeof location === 'undefined' || parsed.origin === location.origin) {\n return;\n }\n logWarn(\n logLocation,\n `Failed to fetch cross-origin resource \"${parsed.href}\". ` +\n 'To load assets from a protected deployment, two steps are required: ' +\n '(1) configure withRemoteComponentsHostProxy middleware in your host with the remote URL in allowedProxyUrls, ' +\n 'and (2) provide a resolveClientUrl prop that rewrites cross-origin asset URLs to go through the proxy. ' +\n `See: ${CORS_DOCS_URL}`,\n );\n } catch {\n // URL parsing failed — skip the warning\n }\n}\n","export function escapeString(str: string) {\n return str.replace(/[^a-z0-9]/g, '_');\n}\n\n/**\n * Computes the origin-qualified scoped name for a bundle. Same-origin\n * remotes keep the plain name; cross-origin remotes append the escaped\n * host (hostname + port) to avoid collisions between bundles that share\n * a name but are served from different origins.\n *\n * Used on both the server (to rewrite RSC flight data) and the client\n * (to create and look up RemoteScopes). Both sides must produce the\n * same value for a given remote.\n */\nexport function computeScopedName(\n name: string,\n options: { remoteHost: string; isCrossOrigin: boolean },\n): string {\n return options.isCrossOrigin\n ? `${name}_${escapeString(options.remoteHost.toLowerCase())}`\n : name;\n}\n\nexport const attrToProp = {\n fetchpriority: 'fetchPriority',\n crossorigin: 'crossOrigin',\n imagesrcset: 'imageSrcSet',\n imagesizes: 'imageSizes',\n srcset: 'srcSet',\n} as Record<string, string>;\n","import { escapeString } from '#internal/utils';\n\nexport const DEFAULT_BUNDLE_NAME = '__vercel_remote_bundle';\nexport const DEFAULT_COMPONENT_NAME = '__vercel_remote_component';\nexport const DEFAULT_ROUTE = '/';\n\nexport const RUNTIME_WEBPACK = 'webpack';\nexport const RUNTIME_TURBOPACK = 'turbopack';\nexport const RUNTIME_SCRIPT = 'script';\n\nexport function getBundleKey(bundle: string): string {\n return escapeString(bundle);\n}\n\nexport type Runtime =\n | typeof RUNTIME_WEBPACK\n | typeof RUNTIME_TURBOPACK\n | typeof RUNTIME_SCRIPT;\n","import type { RemoteScope } from '#internal/runtime/turbopack/remote-scope';\nimport type {\n GlobalScope,\n MountOrUnmountFunction,\n MountUnmountFunctions,\n} from '#internal/runtime/types';\n\n/**\n * Typed namespace for all remote-components runtime state.\n *\n * Consolidates scattered `globalThis` globals into a single object at\n * `globalThis.__remote_components__`. Each property corresponds to a\n * previously independent global — see inline `@see` tags for the original\n * global name. Code that previously read from those globals still works\n * because each migration writes through to both the namespace and the\n * legacy global (pointing at the same underlying object).\n */\nexport interface RemoteComponentsNamespace {\n /** @see `__remote_component_scopes__` */\n scopes: Map<string, RemoteScope>;\n /** @see `__remote_components_turbopack_chunk_loader_promise__` */\n chunkCache: Record<string, Promise<unknown>>;\n /** @see `__remote_script_entrypoint_mount__` */\n mountFns: Record<string, Set<MountOrUnmountFunction>>;\n /** @see `__remote_script_entrypoint_unmount__` */\n unmountFns: Record<string, Set<MountOrUnmountFunction>>;\n /** @see `__remote_bundle_url__` */\n bundleUrls: Record<string, string | URL>;\n /** @see `__rc_module_registry__` */\n moduleRegistry: Record<string, unknown>;\n /** @see `__webpack_require_type__` */\n dispatcherRuntime: string | undefined;\n /** @see `__remote_component_host_shared_modules__` */\n hostSharedModules: Record<string, () => Promise<unknown>>;\n /** @see `__remote_next_css__` */\n cssCache: Record<string, ChildNode[]>;\n /** @see `__remote_components_shadowroot_*` */\n shadowRoots: Record<string, ShadowRoot | null>;\n}\n\n/** Prefix for legacy per-key shadow root globals (`__remote_components_shadowroot_*`). */\nconst SHADOW_ROOT_PREFIX = '__remote_components_shadowroot_';\n\n/**\n * Backward-compat aliases for globals used in <=0.3.3.\n *\n * Only includes object/Map values that can be aliased by reference.\n * Primitives (`dispatcherRuntime`) must use write-through at their call sites.\n * Dynamic-key shadow root globals are adopted separately in `getNamespace()`.\n */\nconst LEGACY_ALIASES: ReadonlyArray<{\n global: string;\n prop: keyof RemoteComponentsNamespace;\n}> = [\n { global: '__remote_component_scopes__', prop: 'scopes' },\n {\n global: '__remote_components_turbopack_chunk_loader_promise__',\n prop: 'chunkCache',\n },\n { global: '__remote_script_entrypoint_mount__', prop: 'mountFns' },\n { global: '__remote_script_entrypoint_unmount__', prop: 'unmountFns' },\n { global: '__remote_bundle_url__', prop: 'bundleUrls' },\n { global: '__rc_module_registry__', prop: 'moduleRegistry' },\n {\n global: '__remote_component_host_shared_modules__',\n prop: 'hostSharedModules',\n },\n { global: '__remote_next_css__', prop: 'cssCache' },\n];\n\n/**\n * Returns the single shared `RemoteComponentsNamespace` instance, creating\n * it on first access. The namespace lives at `globalThis.__remote_components__`\n * so every module in the page shares the same state regardless of how many\n * copies of the library are loaded.\n *\n * On first initialization this function also handles backward compatibility\n * with legacy globals:\n * 1. **Adopt**: if a legacy global already exists (written by older code before\n * the namespace was created), its value becomes the initial namespace value.\n * 2. **Alias**: legacy globals are assigned to point at the namespace's objects,\n * so older code that reads the legacy global sees the same reference.\n */\nexport function getNamespace(): RemoteComponentsNamespace {\n const g = globalThis as GlobalScope & MountUnmountFunctions;\n const existing = g.__remote_components__;\n if (existing) {\n return existing;\n }\n\n const ns: RemoteComponentsNamespace = {\n scopes: new Map(),\n chunkCache: {},\n mountFns: {},\n unmountFns: {},\n bundleUrls: {},\n moduleRegistry: {},\n dispatcherRuntime: undefined,\n hostSharedModules: {},\n cssCache: {},\n shadowRoots: {},\n };\n\n // Adopt any pre-existing legacy globals, then alias them to the namespace.\n const nsRecord = ns as unknown as Record<string, unknown>;\n for (const { global, prop } of LEGACY_ALIASES) {\n const legacyValue = (g as Record<string, unknown>)[global];\n if (legacyValue != null) {\n nsRecord[prop] = legacyValue;\n }\n (g as Record<string, unknown>)[global] = ns[prop];\n }\n\n // Adopt per-key shadow root globals used in <=0.3.3\n // (e.g. `globalThis.__remote_components_shadowroot_<key> = root`).\n const gRecord = g as Record<string, unknown>;\n for (const key of Object.keys(gRecord)) {\n if (key.startsWith(SHADOW_ROOT_PREFIX)) {\n const suffix = key.slice(SHADOW_ROOT_PREFIX.length);\n ns.shadowRoots[suffix] = gRecord[key] as ShadowRoot | null;\n delete gRecord[key];\n }\n }\n\n g.__remote_components__ = ns;\n return ns;\n}\n","export const REMOTE_COMPONENT_REGEX =\n /(?<prefix>.*?)\\[(?<bundle>[^\\]]+)\\](?:%20| )(?<id>.+)/;\n\n// Matches Next.js bundle-prefixed paths like /_next/[bundle-name] /static/...\n// Used to strip the bundle identifier before loading scripts via the standard /_next/ path.\nexport const NEXT_BUNDLE_PATH_RE = /\\/_next\\/\\[.+\\](?:%20| )/;\n\n/** Collapse duplicate path separators (`//`) while preserving protocol (`://`). */\nconst DOUBLE_SLASH_RE = /(?<!:)\\/\\//g;\nexport function collapseDoubleSlashes(path: string): string {\n return path.replace(DOUBLE_SLASH_RE, '/');\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { getBundleKey, type Runtime } from '#internal/runtime/constants';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport { REMOTE_COMPONENT_REGEX } from '#internal/runtime/patterns';\nimport { computeScopedName } from '#internal/utils';\nimport { logDebug, logWarn } from '#internal/utils/logger';\n\n/**\n * Encapsulates all per-remote state so that two remotes sharing the same\n * bundle name but served from different origins never collide.\n *\n * A scope is created once per `setupRemoteScope` call and threaded\n * directly through internal code paths (chunk loading, module resolution,\n * shared modules). Global dispatchers (`__webpack_require__`,\n * `__webpack_chunk_load__`) only exist for external callers (RSC runtime)\n * and resolve the correct scope via the registry.\n */\nexport interface RemoteScope {\n /** Plain bundle name (e.g. \"remote-component-registry\") */\n name: string;\n /** Origin-qualified key — unique even when two remotes share a name */\n scopedName: string;\n /** Escaped key used as suffix for TURBOPACK_ globals */\n globalKey: string;\n /** Base URL for resolving relative chunk paths */\n url: URL;\n /** Bundler runtime type */\n runtime: Runtime;\n /** Proxy callback for routing chunks through the host */\n resolveClientUrl?: InternalResolveClientUrl;\n /** Per-scope cache of executed Turbopack module exports */\n moduleCache: Record<string, unknown>;\n /** Per-scope shared modules provided by the host (React, etc.) */\n sharedModules: Record<string, unknown>;\n /** Per-scope globalThis substitute passed to module initializers as `g` */\n moduleGlobal: Record<string, unknown>;\n /**\n * Webpack's bundle-scoped require function, populated from\n * `__remote_webpack_require__[bundleName]` for webpack remotes.\n * Undefined for turbopack remotes.\n */\n webpackRequire?: ((id: string | number) => unknown) & {\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n type?: string;\n };\n /**\n * Flat array of captured turbopack module entries: [scriptEl, id, factory, ...].\n * Populated by the push interceptor in handleTurbopackChunk. This is the\n * primary source of truth for getTurbopackModules — immune to the turbopack\n * runtime replacing the TURBOPACK global (canary builds use a deferred-loading\n * pattern that swaps the array for an immediate-processing dispatcher).\n */\n turbopackModules: unknown[];\n}\n\nfunction getRegistry(): Map<string, RemoteScope> {\n return getNamespace().scopes;\n}\n\nexport function createScope(\n name: string,\n url: URL,\n runtime: Runtime,\n resolveClientUrl?: InternalResolveClientUrl,\n): RemoteScope {\n const isCrossOrigin = url.origin !== location.origin;\n const scopedName = computeScopedName(name, {\n remoteHost: url.host,\n isCrossOrigin,\n });\n const globalKey = getBundleKey(scopedName);\n return {\n name,\n scopedName,\n globalKey,\n url,\n runtime,\n resolveClientUrl,\n moduleCache: {},\n sharedModules: {},\n moduleGlobal: {},\n turbopackModules: [],\n };\n}\n\nexport function registerScope(scope: RemoteScope): void {\n const registry = getRegistry();\n registry.set(scope.scopedName, scope);\n\n // Also register under the plain name so hosts without server-side RSC\n // rewriting (static/HTML hosts) can look up cross-origin scopes by\n // the bundle name that appears in unrewritten chunk/module IDs.\n if (scope.scopedName !== scope.name) {\n const existing = registry.get(scope.name);\n if (existing && existing.scopedName !== scope.scopedName) {\n logWarn(\n 'RemoteScope',\n `Plain name \"${scope.name}\" already registered by scope \"${existing.scopedName}\" — ` +\n `overwriting with \"${scope.scopedName}\". Static hosts will only resolve the latest one.`,\n );\n }\n registry.set(scope.name, scope);\n }\n\n logDebug(\n 'RemoteScope',\n `Registered scope \"${scope.scopedName}\" (${registry.size} total)`,\n );\n}\n\n/**\n * Resolves a scope by name. Accepts either the scoped name (used by Next.js\n * hosts that rewrite RSC data server-side) or the plain bundle name (used by\n * static/HTML hosts where chunks arrive unrewritten).\n */\nexport function getScope(name: string): RemoteScope | undefined {\n return getRegistry().get(name);\n}\n\n/** Formats a `[scopedName] path` string for use in chunk/module IDs. */\nexport function formatRemoteId(scope: RemoteScope, path: string): string {\n return `[${scope.scopedName}] ${path}`;\n}\n\n/**\n * Parses the `[bundle] path` format used in chunk/module IDs.\n * Uses REMOTE_COMPONENT_REGEX (the same pattern used by the module dispatcher\n * and script loader) so the two parsing paths can never diverge.\n */\nexport function parseRemoteId(id: string): {\n bundle: string;\n path: string;\n prefix: string;\n} {\n const groups = REMOTE_COMPONENT_REGEX.exec(id)?.groups;\n if (groups?.bundle && groups.id) {\n return {\n bundle: groups.bundle,\n path: groups.id,\n prefix: groups.prefix ?? '',\n };\n }\n return { bundle: 'default', path: id, prefix: '' };\n}\n","import { getScope } from '#internal/runtime/turbopack/remote-scope';\nimport type { InternalResolveClientUrl } from '#internal/runtime/url/resolve-client-url';\n\n/**\n * Replacement for `next/dist/shared/lib/image-loader`.\n *\n * Uses `config.path` (which includes the remote's asset prefix, e.g.\n * `/vc-ap-xxx/_next/image`) to generate URLs that match the server-rendered\n * HTML and avoid hydration mismatches. Under the microfrontends proxy these\n * relative paths are routed to the correct app.\n *\n * For cross-origin deployments (standalone host on a different domain),\n * `config.path` is a relative path that would incorrectly resolve to the host\n * origin, so we prefix it with the remote origin to produce an absolute URL\n * pointing at the remote's optimizer.\n *\n * When `resolveClientUrl` is provided (deployment protection), the final URL\n * is routed through the host's proxy.\n */\nexport function createRemoteImageLoader(\n bundle: string,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n const loader = Object.assign(\n ({\n config,\n src,\n width,\n quality,\n }: {\n config: { path?: string };\n src: string;\n width: number;\n quality?: number;\n }) => {\n const q = quality ?? 75;\n const remoteOrigin = getScope(bundle)?.url.origin ?? '';\n const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;\n const basePath = isCrossOrigin\n ? `${remoteOrigin}${config.path ?? '/_next/image'}`\n : (config.path ?? `${remoteOrigin}/_next/image`);\n const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;\n return resolveClientUrl?.(url) ?? url;\n },\n // Signals to getImgProps that this is a default loader (not a user-defined\n // one), enabling srcSet generation with device/image sizes from the config.\n { __next_img_default: true as const },\n );\n return loader;\n}\n","import type { LinkProps } from 'next/link';\nimport { createRemoteImageLoader } from '#internal/host/shared/remote-image-loader';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport type { InternalResolveClientUrl } from '#internal/runtime/url/resolve-client-url';\nimport { logWarn } from '#internal/utils/logger';\n\n// polyfill Next.js App Router client API (minimal)\n// implementations are minimal and do not cover all use cases\n// developer can override these shared modules from configuration\nexport function sharedPolyfills(\n shared?: Record<string, () => Promise<unknown>>,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n const hostShared = getNamespace().hostSharedModules;\n const polyfill = {\n 'next/dist/client/components/navigation':\n hostShared['next/navigation'] ??\n shared?.['next/navigation'] ??\n (() =>\n Promise.resolve({\n useRouter() {\n return {\n push: (routerUrl: string) => {\n history.pushState({}, '', routerUrl);\n },\n replace: (routerUrl: string) => {\n history.replaceState({}, '', routerUrl);\n },\n back: () => {\n history.back();\n },\n };\n },\n usePathname() {\n return location.pathname;\n },\n useParams() {\n return {};\n },\n useSearchParams() {\n return new URLSearchParams(location.search);\n },\n useSelectedLayoutSegment() {\n return null;\n },\n useSelectedLayoutSegments() {\n return [];\n },\n __esModule: true,\n })),\n 'next/dist/client/app-dir/link':\n hostShared['next/link'] ??\n shared?.['next/link'] ??\n (() =>\n Promise.resolve({\n default: ({\n scroll: _,\n replace,\n prefetch,\n onNavigate,\n children,\n ...props\n }: React.PropsWithChildren<LinkProps>) => {\n if (prefetch) {\n logWarn(\n 'Polyfill',\n 'Next.js Link prefetch is not supported in remote components',\n );\n }\n return (\n <a\n {...props}\n href={props.href as string}\n onClick={(e) => {\n e.preventDefault();\n let preventDefaulted = false;\n e.preventDefault = () => {\n preventDefaulted = true;\n e.defaultPrevented = true;\n };\n if (typeof props.onClick === 'function') {\n props.onClick(e);\n }\n onNavigate?.(e);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (preventDefaulted) {\n return;\n }\n if (replace) {\n history.replaceState({}, '', props.href as string);\n } else {\n history.pushState({}, '', props.href as string);\n }\n }}\n suppressHydrationWarning\n >\n {children ?? null}\n </a>\n );\n },\n useLinkStatus() {\n return { pending: false };\n },\n __esModule: true,\n })),\n 'next/dist/client/app-dir/form':\n hostShared['next/form'] ??\n shared?.['next/form'] ??\n (() =>\n Promise.resolve({\n default: () => {\n // TODO: implement <Form> component for non-Next.js host applications\n throw new Error('Next.js <Form> component not implemented');\n },\n __esModule: true,\n })),\n // Instead of replacing next/image entirely, we let the real Next.js Image\n // component load from the remote bundle and only replace its default loader.\n // This gives us full next/image fidelity (fill, priority, srcSet, blur\n // placeholders, error handling) while routing image optimization through the\n // remote app's /_next/image endpoint.\n 'next/dist/shared/lib/image-loader':\n hostShared['next/dist/shared/lib/image-loader'] ??\n shared?.['next/dist/shared/lib/image-loader'] ??\n ((bundle: string) =>\n Promise.resolve({\n default: createRemoteImageLoader(bundle, resolveClientUrl),\n __esModule: true,\n })),\n 'next/dist/client/script':\n hostShared['next/script'] ??\n shared?.['next/script'] ??\n (() =>\n Promise.resolve({\n // TODO: implement <Script> component for non-Next.js host applications\n // do not throw an error for now\n default: () => null,\n __esModule: true,\n })),\n 'next/router':\n hostShared['next/router'] ??\n shared?.['next/router'] ??\n (() =>\n // TODO: incomplete implementation\n Promise.resolve({\n useRouter() {\n return {\n push: (routerUrl: string) => {\n history.pushState({}, '', routerUrl);\n },\n replace: (routerUrl: string) => {\n history.replaceState({}, '', routerUrl);\n },\n back: () => {\n history.back();\n },\n };\n },\n __esModule: true,\n })),\n 'next/dist/build/polyfills/process': () =>\n Promise.resolve({\n default: {\n env: {\n NODE_ENV: 'production',\n },\n },\n __esModule: true,\n }),\n } as Record<string, () => Promise<unknown>>;\n\n polyfill['next/navigation'] = polyfill[\n 'next/dist/client/components/navigation'\n ] as () => Promise<unknown>;\n polyfill['next/link'] = polyfill[\n 'next/dist/client/app-dir/link'\n ] as () => Promise<unknown>;\n polyfill['next/form'] = polyfill[\n 'next/dist/client/app-dir/form'\n ] as () => Promise<unknown>;\n polyfill['next/dist/esm/shared/lib/image-loader'] = polyfill[\n 'next/dist/shared/lib/image-loader'\n ] as () => Promise<unknown>;\n polyfill['next/script'] = polyfill[\n 'next/dist/client/script'\n ] as () => Promise<unknown>;\n\n return polyfill;\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { sharedPolyfills } from '#internal/host/shared/polyfill';\nimport type { LogLocation } from '#internal/utils/logger';\nimport { logDebug } from '#internal/utils/logger';\n\n/**\n * The core React packages that are always shared between host and remote.\n * These correspond to the `/react/*.js` and `/react-dom/*.js` path keys\n * used in the webpack module resolution map.\n */\nexport const CORE_REACT_SHARED_KEYS = [\n 'react',\n 'react/jsx-dev-runtime',\n 'react/jsx-runtime',\n 'react-dom',\n 'react-dom/client',\n] as const;\n\n/**\n * Maps each core React package to its webpack-style path key.\n * For example, `react` maps to `/react/index.js`.\n */\nexport const CORE_REACT_PATH_MAP: Record<string, string> = {\n react: '/react/index.js',\n 'react/jsx-dev-runtime': '/react/jsx-dev-runtime.js',\n 'react/jsx-runtime': '/react/jsx-runtime.js',\n 'react-dom': '/react-dom/index.js',\n 'react-dom/client': '/react-dom/client.js',\n};\n\n/**\n * The vendorShared record used by the Next.js config to map React packages\n * to their webpack path-key string literals. Derived from CORE_REACT_PATH_MAP\n * but excludes `react-dom/client` to match the existing config behavior.\n */\nexport const VENDOR_SHARED: Record<string, string> = Object.fromEntries(\n Object.entries(CORE_REACT_PATH_MAP)\n .filter(([key]) => key !== 'react-dom/client')\n .map(([key, path]) => [key, `'${path}'`]),\n);\n\ntype SharedModuleFactory = (bundle?: string) => Promise<unknown>;\n\n/**\n * Builds the `coreShared` map for the Turbopack runtime's\n * `initializeSharedModules`. Each entry is an async factory that dynamically\n * imports the corresponding React package. User-provided shared modules\n * override core entries (e.g. to supply a pinned React version).\n */\nexport function buildCoreShared(\n userShared?: Record<string, SharedModuleFactory>,\n): Record<string, SharedModuleFactory> {\n return {\n react: async () => (await import('react')).default,\n 'react-dom': async () => (await import('react-dom')).default,\n 'react/jsx-dev-runtime': async () =>\n (await import('react/jsx-dev-runtime')).default,\n 'react/jsx-runtime': async () =>\n (await import('react/jsx-runtime')).default,\n 'react-dom/client': async () => (await import('react-dom/client')).default,\n ...userShared,\n };\n}\n\ninterface HostSharedGlobals {\n __remote_component_host_shared_modules__?: Record<\n string,\n SharedModuleFactory\n >;\n __remote_component_shared__?: Record<string, SharedModuleFactory>;\n}\n\n/**\n * Builds the merged host shared modules map with a consistent merge priority:\n * 1. Polyfills (lowest priority — fallback implementations)\n * 2. Global host shared modules (`__remote_component_host_shared_modules__`)\n * 3. User-provided shared modules (highest priority — explicit overrides)\n *\n * Some callers also include `__remote_component_shared__` (the pages router\n * global). Pass `includeRemoteComponentShared: true` to include it at the end.\n */\nexport function buildHostShared(\n userShared?: Record<string, SharedModuleFactory>,\n resolveClientUrl?: InternalResolveClientUrl,\n options?: { includeRemoteComponentShared?: boolean },\n): Record<string, SharedModuleFactory> {\n const self = globalThis as typeof globalThis & HostSharedGlobals;\n const result: Record<string, SharedModuleFactory> = {\n ...sharedPolyfills(userShared, resolveClientUrl),\n ...self.__remote_component_host_shared_modules__,\n ...userShared,\n };\n if (options?.includeRemoteComponentShared) {\n Object.assign(result, self.__remote_component_shared__);\n }\n return result;\n}\n\n/**\n * React module instances keyed by their webpack path, e.g.\n * `{ '/react/index.js': React }`. Passed into `buildWebpackResolve` so it\n * can populate the resolve map without importing React itself.\n */\nexport interface ReactModules {\n '/react/index.js': unknown;\n '/react/jsx-dev-runtime.js': unknown;\n '/react/jsx-runtime.js': unknown;\n '/react-dom/index.js': unknown;\n '/react-dom/client.js': unknown;\n}\n\n/**\n * Builds the `resolve` map passed to `applySharedModules` for the webpack\n * runtime. Combines:\n * - Static React module path keys (`/react/index.js`, etc.)\n * - Remote shared modules matched against host shared, with `(ssr)/` prefix stripped\n *\n * After building the map, resolves any factory functions by awaiting them\n * with the given bundle name.\n */\nexport async function buildWebpackResolve(\n hostShared: Record<string, SharedModuleFactory | unknown>,\n remoteShared: Record<string, string | number>,\n bundle: string,\n reactModules: ReactModules,\n callerTag: LogLocation = 'SharedModuleResolver',\n): Promise<Record<string, unknown>> {\n const resolve: Record<string, unknown> = {\n ...reactModules,\n ...Object.entries(remoteShared).reduce<Record<string, unknown>>(\n (acc, [key, value]) => {\n if (typeof hostShared[value] !== 'undefined') {\n acc[key.replace(/^\\(ssr\\)\\/(?<relative>\\.\\/)?/, '')] =\n hostShared[value];\n } else {\n logDebug(\n callerTag,\n `Remote requests \"${value}\" but host doesn't provide it`,\n );\n }\n return acc;\n },\n {},\n ),\n };\n await Promise.all(\n Object.entries(resolve).map(async ([key, value]) => {\n if (typeof value === 'function') {\n resolve[key] = await value(bundle);\n }\n return Promise.resolve(value);\n }),\n );\n return resolve;\n}\n","// Webpack shared module patching\n// used in multiple remote component host types\n// multiple host types includes: HTML custom element for remote components and Next.js host application\n// we are using this shared function to patch a Webpack module map\n// to use shared modules between the host application and the remote component\n\nimport { getScope } from '#internal/runtime/turbopack/remote-scope';\nimport { logDebug, logWarn } from '#internal/utils/logger';\n\nconst DEDUPLICATION_SKIPPED =\n 'shared module deduplication skipped. The remote may load its own copy of shared dependencies.';\n\nexport function applySharedModules(\n bundle: string,\n resolve: Record<string, unknown>,\n) {\n logDebug(\n 'SharedModules',\n `applySharedModules called for bundle: \"${bundle}\"`,\n );\n logDebug(\n 'SharedModules',\n `Shared modules to resolve: ${Object.keys(resolve)}`,\n );\n\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string) => unknown) & {\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n } & Record<string, string[]>;\n\n // Prefer scope-based access when available.\n const scope = getScope(bundle);\n // @legacy(v0.3.4) — fall back to global __remote_webpack_require__ for hosts that\n // haven't run setupWebpackRuntime yet (e.g. HTML host's inline path).\n // Remove once all host types go through the shared pipeline (Phase 5).\n const webpackBundle =\n scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];\n\n if (webpackBundle) {\n const modulePaths = Object.keys(\n self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {},\n );\n logDebug(\n 'SharedModules',\n `Available module paths for bundle \"${bundle}\": ${modulePaths}`,\n );\n\n // patch all modules in the bundle to use the shared modules\n for (const [key, value] of Object.entries(resolve)) {\n const exactIds = modulePaths.filter((p) => p === key);\n const ids =\n exactIds.length > 0\n ? exactIds\n : modulePaths.filter((p) => p.includes(key));\n\n if (ids.length === 0) {\n logDebug(\n 'SharedModules',\n `No matching module path found for shared module \"${key}\"`,\n );\n }\n\n for (const id of ids) {\n if (webpackBundle.m) {\n // if we have a module map, we need to use the mapped id\n // this is required for production builds where the module ids are module id numbers\n const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id]\n ? `${self.__remote_webpack_module_map__[bundle][id]}`\n : id;\n if (resolvedId !== id) {\n logDebug(\n 'SharedModules',\n `Mapped module id: \"${id}\" -> \"${resolvedId}\"`,\n );\n }\n // create a mock module which exports the shared module\n webpackBundle.m[resolvedId] = (module) => {\n module.exports = value;\n };\n } else {\n logWarn(\n 'SharedModules',\n `webpackBundle.m is not available for bundle \"${bundle}\" — ${DEDUPLICATION_SKIPPED}`,\n );\n }\n }\n }\n } else {\n logWarn(\n 'SharedModules',\n `No webpack require found for bundle \"${bundle}\" — ${DEDUPLICATION_SKIPPED}`,\n );\n logDebug(\n 'SharedModules',\n `Available bundles: ${Object.keys(self.__remote_webpack_require__ ?? {})}`,\n );\n }\n}\n","import { getNamespace } from '#internal/runtime/namespace';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\n// module loader for Next.js Pages Router\nexport function nextClientPagesLoader(\n bundle: string,\n route: string,\n styleContainer: HTMLHeadElement | ShadowRoot | null = document.head,\n) {\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string | number) => unknown) & {\n c?: Record<\n string | number,\n { id: string; parents: string[]; children: string[] }\n >;\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n type?: 'turbopack' | 'webpack';\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n // Next.js client pages loader reference storage\n __NEXT_P?: [\n (\n | [\n string,\n () => { default?: React.ComponentType<Record<string, unknown>> },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n ];\n };\n\n // temporarily remove the original Next.js CSS loader\n const nextCssOriginal = document.querySelector(\n `[id=\"__next_css__DO_NOT_USE__\"]:not([data-bundle=\"${bundle}\"][data-route=\"${route}\"])`,\n );\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.removeChild(nextCssOriginal);\n }\n\n // create a new Next.js CSS loader element\n const nextCss = document.createElement('noscript');\n nextCss.id = '__next_css__DO_NOT_USE__';\n nextCss.setAttribute('data-bundle', bundle);\n nextCss.setAttribute('data-route', route);\n const nextCssEnd = document.createElement('noscript');\n nextCssEnd.id = '__next_css__DO_NOT_USE_END__';\n nextCssEnd.setAttribute('data-bundle', bundle);\n nextCssEnd.setAttribute('data-route', route);\n document.head.appendChild(nextCssEnd);\n document.head.appendChild(nextCss);\n\n // find the page component loader chunk\n const componentLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}!`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}!`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // find the app loader chunk\n const appLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // if we didn't find the component loader or app loader, throw an error\n if (!(componentLoaderChunk && appLoaderChunk)) {\n throw new RemoteComponentsError(\n `Next.js client pages loader not found in bundle \"${bundle}\".`,\n );\n }\n\n // temporarily store the original __NEXT_P reference\n // this is required to avoid conflicts with the Next.js client pages loader\n // which uses the same global variable to store the page components\n const __NEXT_P_ORIGINAL = self.__NEXT_P;\n const selfOriginal = self;\n delete selfOriginal.__NEXT_P;\n\n // load the component and app loader chunks\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? componentLoaderChunk\n : `[${bundle}] ${componentLoaderChunk}`,\n );\n if (\n typeof appLoaderChunk === 'string' ||\n (typeof appLoaderChunk === 'number' && appLoaderChunk !== -1)\n ) {\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? appLoaderChunk\n : `[${bundle}] ${appLoaderChunk}`,\n );\n }\n\n // if we have the __NEXT_P global variable, we can extract the component and app\n if (self.__NEXT_P) {\n const [, componentLoader] = self.__NEXT_P[0] ?? [\n undefined,\n () => ({ default: null }),\n ];\n const [, appLoader] = self.__NEXT_P[2] ?? [\n undefined,\n () => ({\n default: null,\n }),\n ];\n const { default: Component } = componentLoader();\n const { default: App } = appLoader();\n\n const cssCache = getNamespace().cssCache;\n\n if (!cssCache[bundle]) {\n // load the CSS files from the remote bundle\n const cssRE = /\\.s?css$/;\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {})\n .filter((id) => cssRE.test(id))\n .forEach((id) => {\n self.__remote_webpack_require__?.[bundle]?.(id);\n });\n\n Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {})\n .filter((path) => cssRE.test(path))\n .forEach((path) => {\n const id = self.__remote_webpack_module_map__?.[bundle]?.[path];\n if (id) {\n self.__remote_webpack_require__?.[bundle]?.(id);\n }\n });\n\n const elements = [];\n let node = nextCss.previousSibling;\n while (node && node !== nextCssEnd) {\n elements.push(node);\n node.remove();\n node = nextCss.previousSibling;\n }\n cssCache[bundle] = elements;\n }\n\n // if the styleContainer is provided, we need to move the styles to it\n if (styleContainer) {\n const elements = cssCache[bundle];\n elements.forEach((el) => {\n styleContainer.appendChild(el.cloneNode(true));\n });\n } else {\n // if no styleContainer is provided, we need to move the styles back to the head\n const elements = cssCache[bundle];\n elements.forEach((el) => {\n document.head.appendChild(el);\n });\n }\n\n // restore the original __NEXT_P reference\n delete self.__NEXT_P;\n self.__NEXT_P = __NEXT_P_ORIGINAL;\n\n // restore the original Next.js CSS loader\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.appendChild(nextCssOriginal);\n }\n\n nextCss.remove();\n nextCssEnd.remove();\n\n return { Component, App };\n }\n\n return { Component: null, App: null };\n}\n","/**\n * Regex patterns for parsing Turbopack's minified and development code.\n *\n * Turbopack outputs different variable names in dev vs production builds:\n * - Development: __turbopack_context__, parentImport, chunk, self\n * - Minified: e, t, etc.\n *\n * Module IDs are numeric in Next.js 16+ (e.g. `984803`) but full string paths in\n * Next.js 15.x dev mode (e.g. `\"[project]/.../react/index.js [app-client] (ecmascript)\"`).\n * ID-capturing patterns match `\"quoted string\"|digits` via the shared\n * `MODULE_ID_PATTERN` fragment. Use `extractGroup()` to both match and strip quotes\n * in one step.\n */\n\n/** Reusable fragment that matches a turbopack module ID: quoted string or numeric. */\nconst MODULE_ID_PATTERN = '\"[^\"]+\"|[0-9]+';\n\n/** Strips surrounding double-quotes from a captured regex value. */\nfunction stripQuotes(value: string): string {\n if (value.startsWith('\"') && value.endsWith('\"')) {\n return value.slice(1, -1);\n }\n return value;\n}\n\n/**\n * Runs a regex against `input` and returns the named capture group with\n * quotes stripped, or `undefined` if there's no match.\n */\nexport function extractGroup(\n re: RegExp,\n input: string,\n group: string,\n): string | undefined {\n const raw = re.exec(input)?.groups?.[group];\n return raw ? stripQuotes(raw) : undefined;\n}\n\n/**\n * Matches: self.TURBOPACK_REMOTE_SHARED or e.TURBOPACK_REMOTE_SHARED\n *\n * @example\n * // Development:\n * \"self.TURBOPACK_REMOTE_SHARED=await __turbopack_context__.A(984803)\"\n *\n * // Minified:\n * \"e.TURBOPACK_REMOTE_SHARED=await e.A(984803)\"\n */\nexport const REMOTE_SHARED_MARKER_RE =\n /(?:self|[a-z])\\.TURBOPACK_REMOTE_SHARED/;\n\n/**\n * Extracts the module ID from a TURBOPACK_REMOTE_SHARED assignment.\n *\n * Captures:\n * - `sharedModuleId`: The module ID (may be quoted for string paths).\n *\n * @example\n * // Next.js 16:\n * \"self.TURBOPACK_REMOTE_SHARED=await __turbopack_context__.A(984803)\"\n * // -> sharedModuleId = \"984803\"\n *\n * // Next.js 15.x (string IDs, spaces around `=`):\n * 'self.TURBOPACK_REMOTE_SHARED = await __turbopack_context__.A(\"[project]/...app-remote.tsx [app-client] (ecmascript, async loader)\")'\n * // -> sharedModuleId = \"[project]/...app-remote.tsx [app-client] (ecmascript, async loader)\"\n *\n * // Minified:\n * \"t.TURBOPACK_REMOTE_SHARED=await e.A(123456)\"\n * // -> sharedModuleId = \"123456\"\n */\nexport const REMOTE_SHARED_ASSIGNMENT_RE = new RegExp(\n `\\\\.TURBOPACK_REMOTE_SHARED\\\\s*=\\\\s*await (?:__turbopack_context__|[a-z])\\\\.A\\\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\\\)`,\n);\n\n/**\n * Matches async module loader calls: ctx.A(moduleId)\n *\n * Captures:\n * - `asyncSharedModuleId`: The module ID (may be quoted).\n *\n * @example\n * // Next.js 16:\n * \"() => __turbopack_context__.A(460400)\"\n * // -> asyncSharedModuleId = \"460400\"\n *\n * // Next.js 15.x:\n * '() => __turbopack_context__.A(\"[project]/.../react/index.js [app-client] (ecmascript, async loader)\")'\n * // -> asyncSharedModuleId = \"[project]/.../react/index.js [app-client] (ecmascript, async loader)\"\n *\n * // Minified:\n * \"() => e.A(460400)\"\n * // -> asyncSharedModuleId = \"460400\"\n */\nexport const ASYNC_MODULE_LOADER_RE = new RegExp(\n `(?:__turbopack_context__|[a-z])\\\\.A\\\\((?<asyncSharedModuleId>${MODULE_ID_PATTERN})\\\\)`,\n);\n\n/**\n * Extracts the final module ID from an async module `.v()` callback.\n * The callback always ends by calling its argument (parentImport / single-letter\n * variable) with the real module ID. This matches that final call regardless of\n * surrounding structure (whitespace, `return` statements, block vs expression bodies).\n *\n * Handles both Promise.resolve (no extra chunks) and Promise.all (with chunks).\n *\n * Captures:\n * - `sharedModuleId`: The module ID (may be quoted).\n *\n * @example\n * // Next.js 16 minified (Promise.resolve):\n * \"e=>{e.v(e=>Promise.resolve().then(()=>e(633334)))}\"\n * // -> sharedModuleId = \"633334\"\n *\n * // Next.js 16 minified (Promise.all):\n * \"e=>{e.v(t=>Promise.all([\\\"chunk.js\\\"].map(t=>e.l(t))).then(()=>t(633334)))}\"\n * // -> sharedModuleId = \"633334\"\n *\n * // Next.js 15.x development (multi-line):\n * '(__turbopack_context__) => {\\n__turbopack_context__.v((parentImport) => {\\n return Promise.resolve().then(() => {\\n return parentImport(\"[project]/.../react/index.js [app-client] (ecmascript)\");\\n });\\n});\\n}'\n * // -> sharedModuleId = \"[project]/.../react/index.js [app-client] (ecmascript)\"\n */\nexport const ASYNC_MODULE_CALLBACK_RE = new RegExp(\n `(?:parentImport|[a-z])\\\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\\\)`,\n);\n\n/**\n * Detects Turbopack runtime global usage in a chunk.\n *\n * Matches either dot-notation or bracket-notation access off `globalThis` or `self`:\n * - globalThis.TURBOPACK / self.TURBOPACK\n * - globalThis[\"TURBOPACK\"] / self['TURBOPACK'] (whitespace tolerated)\n */\nexport const TURBOPACK_GLOBAL_RE =\n /(?:globalThis|self)\\s*(?:\\.TURBOPACK|\\[\\s*[\"']TURBOPACK[\"']\\s*\\])/;\n","import { RUNTIME_WEBPACK } from '#internal/runtime/constants';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport { collapseDoubleSlashes } from '#internal/runtime/patterns';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { isProxiedUrl } from '#internal/runtime/url/protected-rc-fallback';\nimport {\n failedProxiedAssetError,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport {\n logDebug,\n logWarn,\n warnCrossOriginFetchError,\n} from '#internal/utils/logger';\nimport { TURBOPACK_GLOBAL_RE } from './patterns';\nimport {\n formatRemoteId,\n getScope,\n parseRemoteId,\n type RemoteScope,\n} from './remote-scope';\n\n/**\n * Loads a chunk using a specific scope. All state (base URL, proxy callback,\n * TURBOPACK global key) comes from the scope — no global lookups needed.\n *\n * This is the primary chunk loader called directly from:\n * - setupRemoteScope (initial chunks)\n * - TurbopackContext.l (module-level chunk loading)\n * - handleTurbopackChunk (CHUNK_LIST additional chunks)\n *\n * The global chunk dedup cache is keyed by absolute URL, so different origins\n * naturally get separate cache entries even when sharing a bundle name.\n */\nexport function loadChunkWithScope(\n scope: RemoteScope,\n chunkId: string,\n): Promise<unknown> | undefined {\n logDebug(\n 'ChunkLoader',\n `loadChunkWithScope: \"${chunkId}\" (scope: \"${scope.scopedName}\")`,\n );\n const self = globalThis as GlobalScope;\n const ns = getNamespace();\n\n const { bundle, path, prefix } = parseRemoteId(chunkId);\n\n // Skip webpack runtime chunks\n const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? 'default']\n ? self.__remote_webpack_require__[bundle ?? 'default']?.type || 'webpack'\n : scope.runtime;\n if (remoteRuntime === RUNTIME_WEBPACK) {\n return Promise.resolve(undefined);\n }\n\n const rawPath = path ? collapseDoubleSlashes(`${prefix}${path}`) : '/';\n const url = new URL(rawPath, scope.url).href;\n\n if (url.endsWith('.css')) {\n return;\n }\n\n if (ns.chunkCache[url]) {\n logDebug('ChunkLoader', `Cache hit for \"${chunkId}\" (url=\"${url}\")`);\n return ns.chunkCache[url];\n }\n\n const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;\n if (resolvedUrl !== url) {\n logDebug('ChunkLoader', `Proxied chunk URL: \"${url}\" → \"${resolvedUrl}\"`);\n }\n\n ns.chunkCache[url] = new Promise((resolve, reject) => {\n fetch(resolvedUrl)\n .then((res) => res.text())\n .then((code) => {\n const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);\n if (hasTurbopack) {\n return handleTurbopackChunk(code, scope, url);\n }\n // Chunk doesn't contain Turbopack globals — nothing to process\n })\n .then(resolve)\n .catch((error) => {\n const isProxied = isProxiedUrl(resolvedUrl);\n if (isProxied) {\n reject(failedProxiedAssetError('chunk', url, resolvedUrl));\n } else {\n warnCrossOriginFetchError('ChunkLoader', url);\n reject(error);\n }\n });\n });\n\n return ns.chunkCache[url];\n}\n\n/**\n * Creates the global `__webpack_chunk_load__` dispatcher.\n * This is a thin wrapper called only by external code (React's RSC runtime).\n * It parses the chunkId, resolves the correct scope, and delegates to\n * `loadChunkWithScope`.\n */\nexport function createChunkDispatcher(): (\n chunkId: string,\n scriptBundle?: string,\n) => Promise<unknown> | undefined {\n return function __chunk_dispatcher__(chunkId: string, scriptBundle?: string) {\n logDebug('ChunkDispatcher', `Dispatching chunk: \"${chunkId}\"`);\n\n const { bundle } = parseRemoteId(chunkId);\n const bundleName = bundle || scriptBundle || 'default';\n\n // Works with both the scoped name (Next.js hosts with server-side\n // rewriting) and the plain bundle name (static/HTML hosts).\n const scope = getScope(bundleName);\n\n logDebug(\n 'ChunkDispatcher',\n `Scope resolution: bundle=\"${bundleName}\", scope=${scope?.scopedName ?? 'null'}`,\n );\n\n if (!scope) {\n logWarn('ChunkDispatcher', `No scope found for bundle \"${bundleName}\"`);\n return Promise.resolve(undefined);\n }\n\n return loadChunkWithScope(scope, chunkId);\n };\n}\n\n/**\n * Handles Turbopack chunk loading by transforming the chunk code to isolate\n * global variables per bundle and dynamically loading the transformed script.\n * Receives scope directly — no global state lookups needed.\n */\nasync function handleTurbopackChunk(\n code: string,\n scope: RemoteScope,\n url: string,\n): Promise<void> {\n // skip this chunk as it is not needed for remote components\n if (/importScripts\\(\\.\\.\\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {\n const preloadLinks = document.querySelectorAll(\n `link[rel=\"preload\"][href=\"${new URL(url).pathname}\"]`,\n );\n preloadLinks.forEach((preloadLink) => preloadLink.remove());\n return;\n }\n\n const self = globalThis as GlobalScope;\n const { globalKey } = scope;\n\n // replace global variables with scope-specific ones to prevent collisions\n // between multiple remote component bundles\n const transformedCode = code\n .replace(\n /globalThis\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `globalThis[\"TURBOPACK_${globalKey}\"]`,\n )\n .replace(\n /self\\[\\s*[\"']TURBOPACK[\"']\\s*\\]/g,\n `self[\"TURBOPACK_${globalKey}\"]`,\n )\n .replace(/globalThis\\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`)\n .replace(/self\\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`)\n .replace(\n /TURBOPACK_WORKER_LOCATION/g,\n `TURBOPACK_WORKER_LOCATION_${globalKey}`,\n )\n .replace(\n /TURBOPACK_NEXT_CHUNK_URLS/g,\n `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`,\n )\n .replace(\n /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,\n `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`,\n )\n .replace(/__next_require__/g, `__${globalKey}_next_require__`)\n .replace(\n /\\/\\/# sourceMappingURL=(?<name>.+)(?<optional>\\._)?\\.js\\.map/g,\n `//# sourceMappingURL=${new URL('.', new URL(url, scope.url)).href}$1$2.js.map`,\n );\n\n // Initialize TURBOPACK bundle as a real Array with a push interceptor.\n // Must be a true Array instance so Next.js 15.x turbopack runtimes whose\n // module-system IIFE guards with `Array.isArray(globalThis.TURBOPACK)`\n // don't bail out after we rewrite the global name.\n //\n // The interceptor captures module entries into scope.turbopackModules —\n // a flat array we control. We use Object.defineProperty to intercept\n // when the turbopack runtime replaces the global with a deferred-loading\n // dispatcher (canary builds), wrapping the replacement's push too.\n //\n // The scope is reused across loads of different components from the same\n // remote (see setupRemoteScope), so subsequent loads accumulate into\n // the same turbopackModules array. Chunk cache deduplication means\n // handleTurbopackChunk only runs once per unique chunk URL — all captured\n // modules remain available for any component that needs them.\n if (!self[`TURBOPACK_${globalKey}`]) {\n const wrapPush = <T extends { push?: (...args: unknown[]) => unknown }>(\n target: T,\n ): T => {\n const originalPush = target.push;\n if (typeof originalPush !== 'function') return target;\n target.push = (...items: unknown[]) => {\n for (const item of items) {\n if (Array.isArray(item)) {\n for (const entry of item) {\n scope.turbopackModules.push(entry);\n }\n } else {\n scope.turbopackModules.push(item);\n }\n }\n return originalPush.apply(target, items);\n };\n return target;\n };\n\n const globalProp = `TURBOPACK_${globalKey}`;\n let currentValue: unknown = wrapPush([] as unknown[]);\n Object.defineProperty(self, globalProp, {\n get() {\n return currentValue;\n },\n set(newValue: unknown) {\n // When the turbopack runtime replaces the array with a dispatcher,\n // wrap the new object's push so we keep capturing module entries.\n if (newValue && typeof newValue === 'object') {\n wrapPush(newValue as { push?: (...args: unknown[]) => unknown });\n }\n currentValue = newValue;\n },\n configurable: true,\n enumerable: true,\n });\n }\n\n // load the script dynamically using a Blob URL\n await new Promise<void>((scriptResolve, scriptReject) => {\n const blob = new Blob([transformedCode], {\n type: 'application/javascript; charset=UTF-8',\n });\n const scriptUrl = URL.createObjectURL(blob);\n const script = document.createElement('script');\n script.setAttribute('data-turbopack-src', url);\n script.src = scriptUrl;\n script.async = true;\n script.onload = () => {\n URL.revokeObjectURL(scriptUrl);\n scriptResolve(undefined);\n script.remove();\n };\n script.onerror = () => {\n URL.revokeObjectURL(scriptUrl);\n scriptReject(\n new RemoteComponentsError(\n `Failed to load <script src=\"${script.src}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n script.remove();\n };\n document.head.appendChild(script);\n });\n\n // process any additional chunks that were registered during script execution\n // These CHUNK_LIST chunks load directly via scope — no global dispatch needed.\n const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`] as\n | { chunks: string[] }[]\n | undefined;\n const loadChunkPromises: (Promise<unknown> | undefined)[] = [];\n while (chunkLists?.length) {\n const { chunks } = chunkLists.shift() ?? { chunks: [] };\n if (chunks.length > 0) {\n for (const id of chunks) {\n const baseUrl = url.slice(0, url.indexOf('/_next'));\n const chunkLoadResult = loadChunkWithScope(\n scope,\n formatRemoteId(scope, `${baseUrl}/_next/${id}`),\n );\n if (chunkLoadResult) {\n loadChunkPromises.push(chunkLoadResult);\n }\n }\n }\n }\n if (loadChunkPromises.length > 0) {\n await Promise.all(loadChunkPromises);\n }\n}\n","import type { GlobalScope } from '#internal/runtime/types';\nimport { logDebug, logError, logWarn } from '#internal/utils/logger';\nimport { findModuleInit, handleTurbopackModule } from './module';\nimport {\n ASYNC_MODULE_CALLBACK_RE,\n ASYNC_MODULE_LOADER_RE,\n extractGroup,\n REMOTE_SHARED_ASSIGNMENT_RE,\n REMOTE_SHARED_MARKER_RE,\n} from './patterns';\nimport { formatRemoteId, type RemoteScope } from './remote-scope';\n\nconst DEDUPLICATION_WARNING =\n 'This module will not be deduplicated — the remote may load its own copy, ' +\n 'which can cause duplicate instance errors (e.g. invalid hook calls if React is loaded twice).';\n\n/**\n * Returns the flat module list for a scope.\n *\n * The primary source is `scope.turbopackModules` — a flat array populated by\n * the push interceptor in handleTurbopackChunk. This is immune to the\n * turbopack runtime replacing the TURBOPACK global (canary builds swap the\n * array for a deferred-loading dispatcher object).\n *\n * Falls back to reading the global for pre-populated bundles where the push\n * interceptor was never installed.\n */\nexport function getTurbopackModules(scope: RemoteScope): unknown[] | undefined {\n if (scope.turbopackModules.length > 0) {\n return scope.turbopackModules;\n }\n\n // Fallback: read the global for pre-populated bundles or legacy setups.\n const self = globalThis as GlobalScope;\n const raw = self[`TURBOPACK_${scope.globalKey}`];\n if (!raw) return undefined;\n\n if (Array.isArray(raw)) {\n return (raw as unknown[]).flat();\n }\n return Object.entries(raw as Record<string, unknown>).flat();\n}\n\n/**\n * Initializes shared modules between the host application and remote components.\n * This enables sharing of common dependencies like React to avoid duplicate instances.\n *\n * The function works by:\n * 1. Looking for a shared module initializer in the Turbopack bundle\n * 2. Extracting module IDs from the initializer\n * 3. Loading the corresponding host modules and mapping them to the remote's expected IDs\n */\nexport async function initializeSharedModules(\n scope: RemoteScope,\n hostShared: Record<string, (bundle?: string) => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n // biome-ignore lint/suspicious/noConfusingVoidType: Runtime is undefined but in TS land service it is void\n): Promise<void[]> {\n const allModules = getTurbopackModules(scope);\n\n logDebug(\n 'SharedModules',\n `initializeSharedModules: scope=\"${scope.scopedName}\", ` +\n `allModules=${allModules ? allModules.length : 'null'}, ` +\n `hostShared=[${Object.keys(hostShared).join(', ')}], ` +\n `remoteShared=${JSON.stringify(remoteShared)}`,\n );\n\n let sharedModuleInitializer: Promise<{\n shared: Record<string, string | (() => Promise<unknown>)>;\n }> | null = null;\n\n // find the shared module initializer in the Turbopack bundle\n if (allModules) {\n // find the shared module initializer module id by looking for\n // a function that contains the TURBOPACK_REMOTE_SHARED pattern\n const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {\n if (typeof idOrFunc !== 'function') {\n return false;\n }\n const funcCode = idOrFunc.toString();\n return REMOTE_SHARED_MARKER_RE.test(funcCode);\n });\n\n // if found, extract the shared module initializer\n // first element in the array is always the source script element\n if (sharedModuleInitializerIndex > 0) {\n const sharedModuleInitializerCode = (\n allModules[sharedModuleInitializerIndex] as () => unknown\n ).toString();\n const sharedModuleInitializerId = allModules[\n sharedModuleInitializerIndex - 1\n ] as string | number;\n // extract the shared module id from the function code\n const sharedModuleId = extractGroup(\n REMOTE_SHARED_ASSIGNMENT_RE,\n sharedModuleInitializerCode,\n 'sharedModuleId',\n );\n // load the shared module initializer using the extracted module id\n if (sharedModuleId) {\n const { default: sharedModuleInitializerInstance } =\n handleTurbopackModule(\n scope,\n sharedModuleId,\n formatRemoteId(scope, String(sharedModuleInitializerId)),\n ) as {\n default: Promise<{\n shared: Record<string, string | (() => Promise<unknown>)>;\n }>;\n };\n sharedModuleInitializer = sharedModuleInitializerInstance;\n }\n }\n\n // if we have a shared module initializer, load the shared modules from the host application\n if (sharedModuleInitializer) {\n const { shared } = await sharedModuleInitializer;\n // map shared module ids to their initializer functions\n const sharedModuleIds = extractSharedModuleIds(shared, scope);\n logDebug(\n 'SharedModules',\n `Resolved shared modules for scope=\"${scope.scopedName}\": ${JSON.stringify(sharedModuleIds)}`,\n );\n\n // load shared modules from the host application\n return Promise.all(\n Object.entries(sharedModuleIds).map(async ([id, module]) => {\n if (hostShared[module]) {\n scope.sharedModules[id] = await hostShared[module](scope.name);\n } else {\n logError(\n 'SharedModules',\n `Host shared module \"${module}\" not found for ID ${id}. ${DEDUPLICATION_WARNING}`,\n );\n }\n }),\n );\n }\n\n logWarn(\n 'SharedModules',\n `No shared module initializer found in bundle for scope=\"${scope.scopedName}\" — falling back to remoteShared mapping`,\n );\n } else {\n logWarn(\n 'SharedModules',\n `No TURBOPACK modules found for scope=\"${scope.scopedName}\" (TURBOPACK_${scope.globalKey} is empty)`,\n );\n }\n\n // fallback: ensure that the shared modules are initialized using remoteShared mapping\n return Promise.all(\n Object.entries(remoteShared).map(async ([id, module]) => {\n if (hostShared[module]) {\n const normalizedId = id.replace('[app-ssr]', '[app-client]');\n scope.sharedModules[normalizedId] = await hostShared[module](\n scope.name,\n );\n } else {\n logError(\n 'SharedModules',\n `Shared module \"${module}\" not found for \"${scope.name}\". ${DEDUPLICATION_WARNING}`,\n );\n }\n }),\n );\n}\n\n/**\n * Extracts shared module IDs from the shared module initializer functions.\n * This parses the minified Turbopack code to find the module ID mappings.\n */\nfunction extractSharedModuleIds(\n shared: Record<string, string | (() => Promise<unknown>)>,\n scope: RemoteScope,\n): Record<string, string> {\n return Object.entries(shared)\n .filter(([, value]) => typeof value === 'function')\n .reduce<Record<string, string>>((acc, [key, value]) => {\n const asyncSharedModuleId = extractGroup(\n ASYNC_MODULE_LOADER_RE,\n value.toString(),\n 'asyncSharedModuleId',\n );\n\n if (asyncSharedModuleId) {\n const asyncSharedModule = findModuleInit(\n getTurbopackModules(scope),\n asyncSharedModuleId,\n );\n if (asyncSharedModule) {\n const sharedModuleId = extractGroup(\n ASYNC_MODULE_CALLBACK_RE,\n asyncSharedModule.toString(),\n 'sharedModuleId',\n );\n // map the shared module id to the actual module name\n acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(\n '__remote_shared_module_',\n '',\n );\n }\n }\n return acc;\n }, {});\n}\n\n/**\n * Returns a shared module for the given scope and module ID.\n * Shared modules are common dependencies like React that are provided by the host.\n */\nexport function getSharedModule(\n scope: RemoteScope,\n id: string | number,\n): unknown {\n const idStr = String(id);\n\n // Exact match first (covers both string and numeric IDs)\n if (scope.sharedModules[idStr] !== undefined) {\n return scope.sharedModules[idStr];\n }\n\n // Fallback: the id may be a bundle-prefixed string like \"[bundle] /react/index.js\"\n // that contains the shared module key as a suffix. Only match when the key\n // appears as a complete suffix segment to avoid \"react\" matching \"react-dom\".\n for (const [key, value] of Object.entries(scope.sharedModules)) {\n if (typeof value !== 'undefined' && idStr !== key && idStr.endsWith(key)) {\n return value;\n }\n }\n\n return null;\n}\n","import { logError } from '#internal/utils/logger';\nimport { loadChunkWithScope } from './chunk-loader';\nimport { formatRemoteId, type RemoteScope } from './remote-scope';\nimport { getSharedModule, getTurbopackModules } from './shared-modules';\n\n/**\n * Function signature for Turbopack module initializers.\n * These functions are generated by Turbopack and initialize module exports.\n */\nexport type TurbopackModuleInit = (\n turbopackContext: TurbopackContext,\n module: { exports: Record<string, unknown> },\n exports: Record<string, unknown>,\n) => void;\n\n/**\n * The context object passed to Turbopack module initializers.\n * This provides the runtime API that modules use for imports, exports, and HMR.\n */\ninterface TurbopackContext {\n /** HMR (Hot Module Replacement) - not implemented for remote components */\n k: {\n register(): void;\n registerExports(): void;\n signature(): (fn: unknown) => unknown;\n };\n /** ESM exports setup */\n s: (\n bindings:\n | Record<string, () => unknown>\n | [...([string, () => unknown] | [string, number, () => unknown])],\n esmId?: string | number,\n ) => void;\n /** Import module */\n i: (importId: string | number) => Record<string, unknown> | undefined;\n /** Require module */\n r: (requireId: string) => unknown;\n /** Value exports */\n v: (value: unknown) => void;\n /** Async module initializer */\n a: (\n mod: (\n handleDeps: unknown,\n setResult: (value: unknown) => void,\n ) => Promise<void>,\n ) => Promise<void>;\n /** Async module loader */\n A: (Aid: string) => Promise<unknown>;\n /**\n * Dynamic import tracking. Called in production chunks after ctx.s() to\n * register async/dynamic module relationships. e.g. t.j(importedMod, 58790)\n */\n j: (module: unknown, esmId?: string | number) => void;\n /** Chunk loader */\n l: (url: string) => Promise<unknown> | undefined;\n /** Global object for this bundle */\n g: unknown;\n /** Module object */\n m: { exports: Record<string, unknown> };\n /** Exports object */\n e: Record<string, unknown>;\n}\n\n/**\n * Turbopack pushes chunks as flat arrays in one of two shapes:\n *\n * Module chunk (common case):\n * [scriptElement, id1, factory1, id2, factory2, ...]\n * - index 0: the script Element (document.currentScript) or undefined\n * - alternating pairs: numeric ID (prod) or path string (dev), then factory function\n *\n * Runtime manifest (bootstrapper only, no module factories):\n * [scriptElement, { otherChunks: [...], runtimeModuleIds: [...] }]\n *\n * Newer Next.js canary versions may also store modules as a plain object\n * { [moduleId]: factory } rather than as an array.\n */\ntype BundleModules =\n | (\n | Element\n | string\n | number\n | TurbopackModuleInit\n | Record<string, TurbopackModuleInit>\n | null\n | undefined\n )[]\n | Record<string, TurbopackModuleInit>\n | undefined;\n\n/**\n * Resolves a module within a scope: checks shared modules first, then\n * falls back to Turbopack module resolution. This is the scope-local\n * equivalent of the global __webpack_require__ dispatcher.\n */\nexport function requireModule(\n scope: RemoteScope,\n moduleId: string | number,\n fullId?: string,\n): unknown {\n const idStr = String(moduleId);\n\n // moduleCache is checked first inside handleTurbopackModule too, but\n // checking here avoids the shared-module lookup on every re-entry.\n if (scope.moduleCache[idStr]) return scope.moduleCache[idStr];\n\n // Shared modules are NOT cached in moduleCache because ctx.s() also\n // uses moduleCache for esmId lookups. Caching the host's frozen module\n // object here would cause ctx.s() to attempt Object.defineProperty on\n // it, failing with \"Cannot redefine property\" for non-configurable\n // exports. Keeping shared modules in their own map avoids the collision.\n const sharedModule = getSharedModule(scope, moduleId);\n if (sharedModule) return sharedModule;\n\n return handleTurbopackModule(\n scope,\n idStr,\n fullId ?? formatRemoteId(scope, idStr),\n );\n}\n\n/**\n * Handles Turbopack module resolution and execution.\n * Finds a module in the Turbopack bundle, executes its initializer with a\n * custom runtime context, and returns the module exports.\n */\nexport function handleTurbopackModule(\n scope: RemoteScope,\n moduleId: string,\n id: string,\n): unknown {\n // Cache check must come before module init lookup. Module initializers\n // re-enter handleTurbopackModule for their own imports, so without this\n // guard circular dependencies would infinite-loop.\n if (scope.moduleCache[moduleId]) {\n return scope.moduleCache[moduleId];\n }\n\n const modules = getTurbopackModules(scope) as BundleModules;\n\n // Log only if bundle is completely missing (critical error)\n if (!modules) {\n logError(\n 'TurbopackModule',\n `TURBOPACK_${scope.globalKey} is undefined (scope: \"${scope.scopedName}\")`,\n );\n }\n\n const moduleInit = findModuleInit(modules, moduleId);\n const exports = {} as Record<string, unknown>;\n const moduleExports = { exports };\n\n if (typeof moduleInit !== 'function') {\n throw new Error(\n `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`,\n );\n }\n\n // store a reference to the module exports in the cache before execution\n // to handle circular dependencies\n scope.moduleCache[moduleId] = moduleExports.exports;\n\n // execute the module initializer with our custom Turbopack context\n moduleInit(\n createTurbopackContext(\n scope,\n exports,\n moduleExports,\n modules,\n moduleInit,\n id,\n ),\n moduleExports,\n exports,\n );\n\n // update the cache with the final exports (may have changed during execution)\n if (scope.moduleCache[moduleId] !== moduleExports.exports) {\n scope.moduleCache[moduleId] = moduleExports.exports;\n }\n\n return moduleExports.exports;\n}\n\n/**\n * Finds the module initializer function for a given ID in the Turbopack bundle.\n * Handles all bundle shapes: flat array, object map, nested arrays, and\n * embedded object entries within arrays. Performs exact match first, then\n * falls back to startsWith for dev-mode IDs with appended qualifiers.\n */\nexport function findModuleInit(\n modules: BundleModules | unknown[] | undefined,\n moduleId: string,\n): TurbopackModuleInit | undefined {\n if (!modules || typeof modules !== 'object') return;\n\n // Object format: { [id]: factory } (newer Next.js canary builds)\n if (!Array.isArray(modules)) {\n const key =\n moduleId in modules\n ? moduleId\n : Object.keys(modules).find((k) => k.startsWith(moduleId));\n return key !== undefined ? modules[key] : undefined;\n }\n\n const flat = modules.flat();\n\n // Two-pass ID search: exact match first to avoid prefix false positives.\n // The startsWith fallback handles dev-mode IDs with appended qualifiers\n // such as \"[project]/path.tsx [app-client] (ecmascript, async loader)\".\n let idx = flat.findIndex((e) => String(e) === String(moduleId));\n if (idx < 0) {\n idx = flat.findIndex(\n (e) => typeof e === 'string' && e.startsWith(moduleId),\n );\n }\n if (idx >= 0) {\n // Factory is the first function entry that follows the module ID\n return flat\n .slice(idx + 1)\n .find((e): e is TurbopackModuleInit => typeof e === 'function');\n }\n\n // Embedded object map: entries of the form { [moduleId]: factory }\n for (const entry of flat) {\n if (!entry || typeof entry !== 'object') continue;\n const obj = entry as Record<string, TurbopackModuleInit>;\n if (moduleId in obj) return obj[moduleId];\n const prefixKey = Object.keys(obj).find((k) => k.startsWith(moduleId));\n if (prefixKey) return obj[prefixKey];\n }\n return undefined;\n}\n\n/**\n * Creates the Turbopack context object that provides the runtime API for modules.\n * All context methods close over the scope directly — no global dispatch needed\n * for internal module-to-module calls.\n */\nfunction createTurbopackContext(\n scope: RemoteScope,\n exports: Record<string, unknown>,\n moduleExports: { exports: Record<string, unknown> },\n modules: BundleModules,\n moduleInit: TurbopackModuleInit,\n id: string,\n): TurbopackContext {\n /** Scope-local require: shared modules → turbopack module resolution. */\n const scopedRequire = (moduleId: string | number): unknown =>\n requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));\n\n return {\n // HMR not implemented for Remote Components\n k: {\n register() {\n // omit\n },\n registerExports() {\n // omit\n },\n signature() {\n return (fn: unknown) => fn;\n },\n },\n\n // ESM exports setup\n s(\n bindings:\n | Record<string, () => unknown>\n | [...([string, () => unknown] | [string, number, () => unknown])],\n esmId?: string | number,\n ) {\n let mod = exports;\n if (typeof esmId === 'string' || typeof esmId === 'number') {\n if (!scope.moduleCache[esmId]) {\n scope.moduleCache[esmId] = {} as Record<string, unknown>;\n }\n mod = scope.moduleCache[esmId] as Record<string, unknown>;\n }\n\n Object.defineProperty(mod, '__esModule', { value: true });\n if (Array.isArray(bindings)) {\n let i = 0;\n while (i < bindings.length) {\n const propName = bindings[i++] as string;\n const tagOrFunc = bindings[i++];\n if (typeof tagOrFunc === 'number') {\n Object.defineProperty(mod, propName, {\n value: bindings[i++],\n enumerable: true,\n writable: false,\n });\n } else {\n const getterFn = tagOrFunc as () => unknown;\n if (typeof bindings[i] === 'function') {\n const setterFn = bindings[i++] as (v: unknown) => unknown;\n Object.defineProperty(mod, propName, {\n get: getterFn,\n set: setterFn,\n enumerable: true,\n });\n } else {\n Object.defineProperty(mod, propName, {\n get: getterFn,\n enumerable: true,\n });\n }\n }\n }\n }\n },\n\n // import — resolves directly via scope, no global dispatch\n i(importId: string | number) {\n let mod: Record<string, unknown> | undefined;\n if (typeof importId === 'string') {\n // parse export syntax if present (e.g., \"module <export foo as bar>\")\n const { exportSource, exportName } =\n /\\s+<export (?<exportSource>.*?) as (?<exportName>.*?)>$/.exec(\n importId,\n )?.groups ?? {};\n const normalizedId = importId.replace(\n /\\s+<export(?<specifier>.*)>$/,\n '',\n );\n mod = scopedRequire(normalizedId) as\n | Record<string, unknown>\n | undefined;\n // map the requested export to the module exports\n if (\n mod &&\n exportSource &&\n exportName &&\n (exportSource === '*' || typeof mod[exportSource] !== 'undefined') &&\n typeof mod[exportName] === 'undefined'\n ) {\n if (exportSource === '*') {\n mod[exportName] = mod;\n } else {\n mod[exportName] = mod[exportSource];\n }\n }\n } else {\n mod = scopedRequire(importId) as Record<string, unknown> | undefined;\n }\n\n if (typeof mod !== 'object' || mod === null) {\n mod = { default: mod };\n } else if (\n !('default' in mod) &&\n // ES module namespace objects have a null prototype, so calling\n // mod.toString() directly throws. Use Object.prototype.toString\n // to safely detect them.\n Object.prototype.toString.call(mod) !== '[object Module]'\n ) {\n try {\n mod.default = mod;\n } catch {\n // ignore if mod is not extensible\n }\n }\n return mod;\n },\n\n // require — resolves directly via scope\n r(requireId: string) {\n return scopedRequire(requireId);\n },\n\n // value exports\n v(value: unknown) {\n if (typeof value === 'function') {\n exports.default = value((vid: string | number) => scopedRequire(vid));\n } else {\n moduleExports.exports = value as Record<string, unknown>;\n }\n },\n\n // async module initializer\n async a(\n mod: (\n handleDeps: unknown,\n setResult: (value: unknown) => void,\n ) => Promise<void>,\n ) {\n let result;\n await mod(\n () => {\n // not implemented\n },\n (value) => (result = value),\n );\n exports.default = result;\n },\n\n // async module loader — resolves directly via scope\n async A(Aid: string) {\n const mod = scopedRequire(Aid) as {\n default: (\n parentImport: (parentId: string) => unknown,\n ) => Promise<unknown>;\n };\n return mod.default((parentId: string) => scopedRequire(parentId));\n },\n\n // dynamic import tracking — no-op for remote components\n j() {\n // omit\n },\n\n // chunk loader — loads directly via scope, no global dispatch\n l(url: string) {\n // find the script tag that loaded the current module to determine base URL\n const flatModules = Array.isArray(modules) ? modules : [];\n const moduleInitIndex = flatModules.indexOf(moduleInit);\n if (moduleInitIndex !== -1) {\n const scriptIndex = flatModules\n .slice(0, moduleInitIndex)\n .findLastIndex((bundleEntry) => bundleEntry instanceof Element);\n if (scriptIndex !== -1) {\n const script = flatModules[scriptIndex] as HTMLScriptElement;\n const scriptSrc = script.getAttribute('data-turbopack-src') || '';\n const nextIndex = scriptSrc.indexOf('/_next');\n const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : '';\n const chunkUrl = `${baseUrl}/_next/${url}`;\n return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));\n }\n }\n throw new Error(\n `Failed to load Turbopack chunk \"${url}\" for module \"${id}\". Check the URL is correct.`,\n );\n },\n\n // globalThis substitute shared across all modules in this scope\n g: scope.moduleGlobal,\n m: moduleExports,\n e: exports,\n };\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n RUNTIME_TURBOPACK,\n RUNTIME_WEBPACK,\n type Runtime,\n} from '#internal/runtime/constants';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport { REMOTE_COMPONENT_REGEX } from '#internal/runtime/patterns';\nimport type { GlobalScope } from '#internal/runtime/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\nimport { logDebug, logWarn } from '#internal/utils/logger';\nimport { createChunkDispatcher, loadChunkWithScope } from './chunk-loader';\nimport { requireModule } from './module';\nimport {\n createScope,\n getScope,\n type RemoteScope,\n registerScope,\n} from './remote-scope';\n\n/**\n * Sets up the bundler runtime environment for remote components.\n *\n * Creates a RemoteScope that encapsulates all per-remote state (base URL,\n * proxy callback, module cache, shared modules) and registers it in the\n * global scope registry. Global dispatchers (__webpack_require__,\n * __webpack_chunk_load__) are set once and route to the correct scope.\n *\n * Shared module initialization is NOT performed here — callers must invoke\n * `initializeSharedModules` separately after this function returns. This\n * separation ensures shared modules are initialized after turbopack chunks\n * are loaded (so the primary bundle-introspection path is used), avoiding\n * the fallback that keys shared modules by file path instead of numeric ID.\n *\n * @returns The scope (newly created or reused) for the bundle.\n */\nexport async function setupRemoteScope(\n runtime: Runtime,\n scripts: { src: string | null }[] = [],\n url: URL = new URL(location.href),\n bundle?: string,\n resolveClientUrl?: InternalResolveClientUrl,\n): Promise<RemoteScope> {\n const self = globalThis as GlobalScope;\n const ns = getNamespace();\n const bundleName = bundle ?? 'default';\n\n // When the same remote loads a second component (e.g. switching from basic\n // to styled), reuse the existing scope. The chunk cache is keyed by URL and\n // returns cached promises without re-running handleTurbopackChunk, so\n // turbopackModules, moduleCache, and sharedModules from the first load are\n // all still valid. Only resolveClientUrl may have changed.\n //\n // Origin-only comparison is sufficient because bundleName already identifies\n // a specific remote — different paths on the same origin would be a different\n // bundle with a different name, so getScope() wouldn't return a match.\n const existingScope = getScope(bundleName);\n if (existingScope && existingScope.url.origin === url.origin) {\n logDebug(\n 'WebpackRuntime',\n `Reusing scope \"${existingScope.scopedName}\" (turbopackModules=${existingScope.turbopackModules.length})`,\n );\n existingScope.resolveClientUrl = resolveClientUrl;\n\n // Still load scripts — chunk cache deduplicates already-loaded chunks,\n // and a different component may reference additional chunks.\n if (runtime === RUNTIME_TURBOPACK) {\n await Promise.allSettled(\n scripts.map((script) =>\n script.src\n ? loadChunkWithScope(existingScope, script.src)\n : Promise.resolve(undefined),\n ),\n );\n }\n return existingScope;\n }\n\n const scope = createScope(bundleName, url, runtime, resolveClientUrl);\n registerScope(scope);\n\n // For webpack remotes the remote's own scripts have already loaded (via\n // loadScripts in component-loader) and populated __remote_webpack_require__\n // under the plain bundle name. Capture the reference on the scope so\n // downstream code (applySharedModules, module dispatcher) can use it\n // without reaching into the global.\n if (\n runtime === RUNTIME_WEBPACK &&\n self.__remote_webpack_require__?.[bundleName]\n ) {\n scope.webpackRequire = self.__remote_webpack_require__[bundleName];\n }\n\n ns.bundleUrls[bundleName] = url;\n // Also register under scopedName so webpack hosts (patch-require.ts) can\n // resolve cross-origin remotes whose bundle identifiers were rewritten.\n if (scope.scopedName !== bundleName) {\n ns.bundleUrls[scope.scopedName] = url;\n }\n self.__webpack_get_script_filename__ = () => null;\n\n const willCreateDispatchers =\n typeof self.__webpack_require__ !== 'function' ||\n ns.dispatcherRuntime !== 'turbopack';\n\n if (willCreateDispatchers) {\n // preserve original webpack functions for fallback\n if (\n !self.__original_webpack_require__ &&\n !self.__original_webpack_chunk_load__\n ) {\n self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;\n self.__original_webpack_require__ = self.__webpack_require__;\n }\n\n self.__webpack_chunk_load__ = createChunkDispatcher();\n self.__webpack_require__ = createModuleDispatcher(runtime);\n // Write-through needed: dispatcherRuntime is a primitive string,\n // so the legacy global can't be aliased by reference in getNamespace().\n ns.dispatcherRuntime = runtime;\n self.__webpack_require_type__ = runtime;\n\n // @legacy(v0.3.4) — __remote_webpack_require__ write-through for turbopack remotes.\n // Needed by PatchRequirePlugin which reads this global at runtime.\n // Remove once PatchRequirePlugin reads from scope.\n if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {\n self.__remote_webpack_require__[bundleName] =\n self.__webpack_require__ as (remoteId: string | number) => unknown;\n self.__remote_webpack_require__[bundleName].type = 'turbopack';\n }\n }\n\n // @legacy(v0.3.4) — __remote_webpack_require__ scoped-name alias.\n // Ensures PatchRequirePlugin can find webpack remotes under rewritten\n // bundle identifiers. Remove once PatchRequirePlugin reads from scope.\n if (\n self.__remote_webpack_require__?.[bundleName] &&\n scope.scopedName !== bundleName\n ) {\n self.__remote_webpack_require__[scope.scopedName] =\n self.__remote_webpack_require__[bundleName];\n }\n\n // load all initial chunks directly via scope — no global dispatch needed\n if (runtime === RUNTIME_TURBOPACK) {\n const results = await Promise.allSettled(\n scripts.map((script) => {\n if (script.src) {\n return loadChunkWithScope(scope, script.src);\n }\n return Promise.resolve(undefined);\n }),\n );\n\n for (const result of results) {\n if (result.status === 'rejected') {\n logWarn(\n 'WebpackRuntime',\n `Initial chunk load failed: ${String(result.reason)}`,\n );\n }\n }\n }\n\n return scope;\n}\n\n/**\n * Creates the global module dispatcher for __webpack_require__.\n * Called by external code (React's RSC runtime) that doesn't have access to\n * a scope. Parses the module ID to find the correct scope and delegates\n * to scope-local module resolution.\n */\nfunction createModuleDispatcher(runtime: Runtime): (id: string) => unknown {\n return (id: string) => {\n const self = globalThis as GlobalScope;\n const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)\n ?.groups ?? {\n bundle: 'default',\n id,\n };\n const bundleName = bundle ?? 'default';\n const remoteRuntime = self.__remote_webpack_require__?.[bundleName]\n ? self.__remote_webpack_require__[bundleName]?.type || 'webpack'\n : runtime;\n\n logDebug(\n 'ModuleDispatcher',\n `Resolving \"${id}\" (bundle: \"${bundleName}\", runtime: \"${remoteRuntime}\")`,\n );\n\n try {\n // for webpack remotes, prefer scope-based dispatch then fall back to global\n if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {\n const scope = getScope(bundle);\n if (scope?.webpackRequire) return scope.webpackRequire(moduleId);\n // @legacy(v0.3.4) — global fallback for hosts that populated\n // __remote_webpack_require__ without calling setupWebpackRuntime.\n return self.__remote_webpack_require__?.[bundle]?.(moduleId);\n }\n\n // Look up scope by parsed bundle name. Works with both the scoped\n // name (Next.js hosts with server-side rewriting) and the plain\n // bundle name (static/HTML hosts with unrewritten chunks).\n const scope = getScope(bundleName);\n if (scope) {\n return requireModule(scope, moduleId ?? id, id);\n }\n\n throw new Error(\n `Module \"${id}\" not found — no scope for bundle \"${bundleName}\".`,\n );\n } catch (requireError) {\n logWarn(\n 'ModuleDispatcher',\n `Module require failed: ${String(requireError)}`,\n );\n if (typeof self.__original_webpack_require__ !== 'function') {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundleName}\".`,\n {\n cause: requireError instanceof Error ? requireError : undefined,\n },\n );\n }\n try {\n logDebug(\n 'ModuleDispatcher',\n 'Falling back to original webpack require',\n );\n return self.__original_webpack_require__(id);\n } catch (originalError) {\n throw new RemoteComponentsError(\n `Module \"${id}\" not found in remote component bundle \"${bundleName}\".`,\n { cause: originalError instanceof Error ? originalError : undefined },\n );\n }\n }\n };\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { NEXT_BUNDLE_PATH_RE } from '#internal/runtime/patterns';\nimport { isProxiedUrl } from '#internal/runtime/url/protected-rc-fallback';\nimport {\n failedProxiedAssetError,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport { warnCrossOriginFetchError } from '#internal/utils/logger';\n\n/**\n * Loads external scripts for remote components\n */\nexport async function loadScripts(\n scripts: { src: string }[],\n resolveClientUrl?: InternalResolveClientUrl,\n): Promise<void> {\n await Promise.all(\n scripts.map((script) => {\n return new Promise<void>((resolve, reject) => {\n const newSrc = new URL(\n // remove the remote component bundle name identifier from the script src\n script.src.replace(NEXT_BUNDLE_PATH_RE, '/_next/'),\n location.origin,\n ).href;\n\n const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;\n\n const alreadyLoaded = Array.from(\n document.querySelectorAll<HTMLScriptElement>('script[src]'),\n ).some((s) => s.src === resolvedSrc);\n if (alreadyLoaded) {\n resolve();\n return;\n }\n\n const newScript = document.createElement('script');\n newScript.onload = () => resolve();\n newScript.onerror = () => {\n const isProxied = isProxiedUrl(resolvedSrc);\n if (isProxied) {\n reject(failedProxiedAssetError('script', newSrc, resolvedSrc));\n } else {\n warnCrossOriginFetchError('ScriptLoader', newSrc);\n reject(\n new RemoteComponentsError(\n `Failed to load <script src=\"${newSrc}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n }\n };\n newScript.src = resolvedSrc;\n newScript.async = true;\n document.head.appendChild(newScript);\n });\n }),\n );\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport type { MountOrUnmountFunction } from '#internal/runtime/types';\nimport { logError, warnCrossOriginFetchError } from '#internal/utils/logger';\n\ntype ScriptMod = {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n default?: {\n mount?: MountOrUnmountFunction;\n unmount?: MountOrUnmountFunction;\n };\n};\n\n/**\n * Fetches an ES module via the resolveClientUrl callback, rewrites its\n * relative imports to also go through the callback, then loads it by injecting a\n * wrapper <script type=\"module\"> tag. The module's namespace is captured via\n * a temporary global and returned.\n *\n * This is needed when a direct import() of a cross-origin module fails due to\n * CORS restrictions or Vercel preview-deployment auth. A simple URL rewrite\n * doesn't work for import() because relative imports inside the module would\n * resolve against the rewritten URL instead of the original remote origin.\n */\nasync function importViaCallback<T>(\n absoluteSrc: string,\n resolveClientUrl: InternalResolveClientUrl,\n): Promise<T> {\n const resolvedUrl = resolveClientUrl(absoluteSrc) ?? absoluteSrc;\n const fetchUrl = new URL(resolvedUrl, location.href).href;\n const response = await fetch(fetchUrl);\n if (!response.ok) throw new Error(`Proxied fetch failed: ${response.status}`);\n\n // Restore import.meta.url to the original module URL so any code that\n // relies on it (e.g. for asset resolution) gets the right value.\n // Rewrite relative imports to absolute URLs resolved through the callback so\n // that transitive dependencies also bypass CORS/auth.\n const content = (await response.text())\n .replace(/import\\.meta\\.url/g, JSON.stringify(absoluteSrc))\n .replace(\n /\\b(from|import)\\s*([\"'])(\\.\\.?\\/[^\"']+)\\2/g,\n (_, keyword, quote, relativePath) => {\n const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;\n const resolvedImportUrl = new URL(\n resolveClientUrl(absoluteImportUrl) ?? absoluteImportUrl,\n location.href,\n ).href;\n return `${keyword} ${quote}${resolvedImportUrl}${quote}`;\n },\n );\n const moduleBlobUrl = URL.createObjectURL(\n new Blob([content], { type: 'text/javascript' }),\n );\n const wrapperContent = [\n `import*as m from${JSON.stringify(moduleBlobUrl)};`,\n `globalThis.__rc_module_registry__=globalThis.__rc_module_registry__||{};`,\n `globalThis.__rc_module_registry__[${JSON.stringify(absoluteSrc)}]=m;`,\n ].join('');\n const wrapperBlobUrl = URL.createObjectURL(\n new Blob([wrapperContent], { type: 'text/javascript' }),\n );\n const scriptEl = document.createElement('script');\n scriptEl.type = 'module';\n scriptEl.src = wrapperBlobUrl;\n try {\n await new Promise<void>((resolve, reject) => {\n scriptEl.onload = () => resolve();\n scriptEl.onerror = () =>\n reject(new Error(`Failed to load module for ${absoluteSrc}`));\n document.head.appendChild(scriptEl);\n });\n } finally {\n scriptEl.remove();\n URL.revokeObjectURL(moduleBlobUrl);\n URL.revokeObjectURL(wrapperBlobUrl);\n }\n const registry = getNamespace().moduleRegistry as Record<string, T>;\n const mod = registry[absoluteSrc] ?? ({} as T);\n delete registry[absoluteSrc];\n return mod;\n}\n\nasync function importDirectly<T>(absoluteSrc: string): Promise<T> {\n try {\n return (await import(\n /* @vite-ignore */\n /* webpackIgnore: true */ absoluteSrc\n )) as T;\n } catch (importError) {\n if (!absoluteSrc.startsWith('blob:')) {\n warnCrossOriginFetchError('StaticLoader', absoluteSrc);\n }\n throw importError;\n }\n}\n\nfunction resolveScriptSrc(script: HTMLScriptElement, url: URL): string {\n const rawSrc =\n typeof script.getAttribute === 'function'\n ? (script.getAttribute('src') ?? script.src)\n : script.src;\n if (!rawSrc && script.textContent) {\n return URL.createObjectURL(\n new Blob(\n [script.textContent.replace(/import\\.meta\\.url/g, JSON.stringify(url))],\n { type: 'text/javascript' },\n ),\n );\n }\n return rawSrc;\n}\n\nexport async function loadStaticRemoteComponent(\n scripts: HTMLScriptElement[],\n url: URL,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n const ns = getNamespace();\n\n if (ns.mountFns[url.href]) {\n ns.mountFns[url.href] = new Set();\n }\n if (ns.unmountFns[url.href]) {\n ns.unmountFns[url.href] = new Set();\n }\n const mountUnmountSets = await Promise.all(\n scripts.map(async (script) => {\n try {\n const src = resolveScriptSrc(script, url);\n const absoluteSrc = new URL(src, url).href;\n const mod: ScriptMod = resolveClientUrl\n ? await importViaCallback<ScriptMod>(absoluteSrc, resolveClientUrl)\n : await importDirectly<ScriptMod>(absoluteSrc);\n // revoke the object URL if we created one for inline script content\n if (src.startsWith('blob:')) {\n URL.revokeObjectURL(src);\n }\n if (\n typeof mod.mount === 'function' ||\n typeof mod.default?.mount === 'function'\n ) {\n if (!ns.mountFns[url.href]) {\n ns.mountFns[url.href] = new Set();\n }\n ns.mountFns[url.href]?.add(\n mod.mount ||\n mod.default?.mount ||\n (() => {\n // noop\n }),\n );\n }\n if (\n typeof mod.unmount === 'function' ||\n typeof mod.default?.unmount === 'function'\n ) {\n if (!ns.unmountFns[url.href]) {\n ns.unmountFns[url.href] = new Set();\n }\n ns.unmountFns[url.href]?.add(\n mod.unmount ||\n mod.default?.unmount ||\n (() => {\n // noop\n }),\n );\n }\n return {\n mount: mod.mount || mod.default?.mount,\n unmount: mod.unmount || mod.default?.unmount,\n };\n } catch (e) {\n logError(\n 'StaticLoader',\n `Error loading remote component script from \"${script.src || url.href}\".`,\n e,\n );\n return {\n mount: undefined,\n unmount: undefined,\n };\n }\n }),\n );\n return mountUnmountSets.reduce(\n (acc, { mount, unmount }) => {\n if (typeof mount === 'function') {\n acc.mount.add(mount);\n }\n if (typeof unmount === 'function') {\n acc.unmount.add(unmount);\n }\n return acc;\n },\n {\n mount: new Set<MountOrUnmountFunction>(),\n unmount: new Set<MountOrUnmountFunction>(),\n },\n );\n}\n","import { applySharedModules } from '#internal/config/webpack/apply-shared-modules';\nimport { nextClientPagesLoader } from '#internal/config/webpack/next-client-pages-loader';\nimport type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n buildHostShared,\n buildWebpackResolve,\n} from '#internal/host/shared/shared-module-resolver';\nimport { loadScripts } from '#internal/runtime/loaders/script-loader';\nimport { NEXT_BUNDLE_PATH_RE } from '#internal/runtime/patterns';\nimport type { MountUnmountFunctions, RSCKey } from '#internal/runtime/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\n// initializer for the webpack runtime to be able to access modules\n// required to run exposed client components of the remote component\nexport async function webpackRuntime(\n bundle: string,\n shared?: Record<string, () => Promise<unknown>>,\n remoteShared?: Record<string, string | number>,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack runtime globals\n __webpack_require__: (remoteId: string) => unknown;\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string) => unknown) & {\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n // conditional flag to disable webpack exec\n __DISABLE_WEBPACK_EXEC__?: Record<string, boolean>;\n // webpack chunk loading function\n __webpack_chunk_load__: () => Promise<[]>;\n __webpack_require_type__: 'webpack' | 'turbopack';\n } & MountUnmountFunctions &\n Record<RSCKey, string[]>;\n\n // disable webpack exec to prevent automatically executing the entry module\n if (!self.__DISABLE_WEBPACK_EXEC__) {\n self.__DISABLE_WEBPACK_EXEC__ = {};\n }\n self.__DISABLE_WEBPACK_EXEC__[bundle] = true;\n // add a custom webpack require function to load remote components from multiple bundles / zones\n if (\n typeof self.__webpack_require__ !== 'function' &&\n self.__webpack_require_type__ !== 'turbopack'\n ) {\n self.__webpack_require__ = (remoteId: string) => {\n const re = /\\[(?<bundle>[^\\]]+)\\] (?<id>.*)/;\n const match = re.exec(remoteId);\n const remoteBundle = match?.groups?.bundle;\n const id = match?.groups?.id;\n if (!(id && remoteBundle)) {\n throw new RemoteComponentsError(\n `Remote Component module \"${remoteId}\" not found. Did you forget to wrap the Next.js config with \\`withRemoteComponentsConfig\\` on both host and remote?`,\n );\n }\n if (\n typeof self.__remote_webpack_require__?.[remoteBundle] !== 'function'\n ) {\n throw new RemoteComponentsError(\n `Remote Components are not available in \"${remoteBundle}\". Did you forget to wrap the Next.js config with \\`withRemoteComponentsConfig\\` on both host and remote?`,\n );\n }\n return self.__remote_webpack_require__[remoteBundle](id);\n };\n // not used but required by react-server-dom-webpack\n self.__webpack_chunk_load__ = () => {\n return Promise.resolve([]);\n };\n }\n // we can only import react-server-dom-webpack after initializing the __webpack_require__ and __webpack_chunk_load__ functions\n const {\n default: { createFromReadableStream },\n } = await import('react-server-dom-webpack/client.browser');\n\n async function preloadScripts(\n scripts: HTMLScriptElement[],\n url: URL,\n remoteBundle: string,\n _: string,\n ) {\n // Build absolute src URLs for each script and remove originals from the\n // parsed doc to prevent re-execution when the doc is later inserted into\n // the shadow DOM.\n const scriptSrcs = scripts.flatMap((script) => {\n const scriptSrc =\n script.getAttribute('src') || script.getAttribute('data-src');\n script.parentElement?.removeChild(script);\n if (!scriptSrc) return [];\n return [\n {\n src: new URL(scriptSrc.replace(NEXT_BUNDLE_PATH_RE, '/_next/'), url)\n .href,\n },\n ];\n });\n\n await loadScripts(scriptSrcs, resolveClientUrl);\n\n const hostShared = buildHostShared(shared, resolveClientUrl);\n const resolve = await buildWebpackResolve(\n hostShared,\n remoteShared ?? {},\n remoteBundle,\n {\n '/react/index.js': (await import('react')).default,\n '/react/jsx-dev-runtime.js': (await import('react/jsx-dev-runtime'))\n .default,\n '/react/jsx-runtime.js': (await import('react/jsx-runtime')).default,\n '/react-dom/index.js': (await import('react-dom')).default,\n '/react-dom/client.js': (await import('react-dom/client')).default,\n },\n 'WebpackRuntime',\n );\n\n // apply shared modules to the bundle\n applySharedModules(remoteBundle, resolve);\n }\n\n return {\n self,\n createFromReadableStream,\n applySharedModules,\n nextClientPagesLoader,\n preloadScripts,\n };\n}\n","import { applySharedModules } from '#internal/config/webpack/apply-shared-modules';\nimport { nextClientPagesLoader } from '#internal/config/webpack/next-client-pages-loader';\nimport type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport {\n buildCoreShared,\n buildHostShared,\n} from '#internal/host/shared/shared-module-resolver';\nimport { setupRemoteScope } from '#internal/runtime/turbopack/remote-scope-setup';\nimport { initializeSharedModules } from '#internal/runtime/turbopack/shared-modules';\nimport type { MountUnmountFunctions, RSCKey } from '#internal/runtime/types';\n\n// initializer for the turbopack runtime to be able to access modules\n// required to run exposed client components of the remote component\nexport async function turbopackRuntime(\n url: URL,\n bundle?: string,\n shared?: Record<string, () => Promise<unknown>>,\n remoteShared?: Record<string, string>,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack runtime globals\n __webpack_require__: (remoteId: string) => unknown;\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string) => unknown) & {\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n // conditional flag to disable webpack exec\n __DISABLE_WEBPACK_EXEC__: boolean;\n // webpack chunk loading function\n __webpack_chunk_load__: () => Promise<[]>;\n } & MountUnmountFunctions &\n Record<RSCKey, string[]>;\n\n const hostShared = buildHostShared(shared, resolveClientUrl, {\n includeRemoteComponentShared: true,\n });\n\n // Phase 1: Set up globals (__webpack_require__, __webpack_chunk_load__).\n // Called with empty scripts because we need the globals to exist before\n // importing react-server-dom-webpack. Shared module initialization is\n // deferred to preloadScripts where turbopack chunks are actually loaded.\n await setupRemoteScope('turbopack', [], url, bundle, resolveClientUrl);\n\n // we can only import react-server-dom-webpack after initializing the __webpack_require__ and __webpack_chunk_load__ functions\n const {\n default: { createFromReadableStream },\n } = await import('react-server-dom-webpack/client.browser');\n\n async function preloadScripts(scripts: HTMLScriptElement[], __: URL) {\n // Phase 2: Load turbopack chunks (scope is reused from phase 1).\n const scope = await setupRemoteScope(\n 'turbopack',\n scripts.map((script) => ({\n src:\n script.getAttribute('src') ||\n script.getAttribute('data-src') ||\n script.src,\n })),\n url,\n bundle,\n resolveClientUrl,\n );\n\n // Phase 3: Initialize shared modules now that turbopackModules is\n // populated. This uses the primary bundle-introspection path which\n // maps shared modules by numeric turbopack ID — unlike the fallback\n // path that uses file-path keys which can't match at runtime.\n await initializeSharedModules(\n scope,\n buildCoreShared(hostShared),\n remoteShared ?? {},\n );\n }\n\n return {\n self,\n createFromReadableStream,\n applySharedModules,\n nextClientPagesLoader,\n preloadScripts,\n };\n}\n","// initializer for the script runtime\n\nimport type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { loadStaticRemoteComponent } from '#internal/runtime/loaders/static-loader';\nimport type { MountUnmountFunctions, RSCKey } from '#internal/runtime/types';\n\n// required to run exposed client components of the remote component\nexport function scriptRuntime(resolveClientUrl?: InternalResolveClientUrl) {\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack runtime globals\n __webpack_require__: (remoteId: string) => unknown;\n } & MountUnmountFunctions &\n Record<RSCKey, string[]>;\n\n return {\n self,\n createFromReadableStream: () => Promise.resolve(null),\n applySharedModules: () => Promise.resolve(),\n nextClientPagesLoader: () => ({\n Component: null,\n App: null,\n }),\n preloadScripts: (scripts: HTMLScriptElement[], url: URL) =>\n loadStaticRemoteComponent(scripts, url, resolveClientUrl),\n };\n}\n","import { startTransition, useLayoutEffect } from 'react';\nimport { hydrateRoot } from 'react-dom/client';\nimport { fetchWithHooks } from '#internal/host/server/fetch-with-hooks';\nimport { getClientOrServerUrl } from '#internal/host/server/get-client-or-server-url';\nimport type {\n ConsumeClientConfig,\n ConsumeServerConfig,\n} from '#internal/host/shared/config';\nimport {\n type LifecycleEmitter,\n makeEventEmitter,\n} from '#internal/host/shared/lifecycle';\nimport { preparePipeline } from '#internal/host/shared/pipeline';\nimport type { HostState } from '#internal/host/shared/state';\nimport { createHostState } from '#internal/host/shared/state';\nimport { resolveNameFromSrc } from '#internal/host/utils/resolve-name-from-src';\nimport {\n DEFAULT_BUNDLE_NAME,\n DEFAULT_COMPONENT_NAME,\n} from '#internal/runtime/constants';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport { createRSCStream } from '#internal/runtime/rsc';\nimport type { RSCKey } from '#internal/runtime/types';\nimport { bindResolveClientUrl } from '#internal/runtime/url/default-resolve-client-url';\nimport { escapeString } from '#internal/utils';\nimport { isAbortError } from '#internal/utils/abort';\nimport {\n errorFromFailedFetch,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport { logError } from '#internal/utils/logger';\nimport { attachStyles } from './attach-styles';\nimport { getRuntime, type Runtime } from './runtime';\n\nif (typeof HTMLElement !== 'undefined') {\n /**\n * `<remote-component>` custom element — the HTML host implementation.\n *\n * Implements {@link ConsumeClientConfig}\n * via typed property accessors that reflect to/from DOM attributes.\n *\n * {@link ConsumeLifecycleCallbacks} are dispatched as DOM events:\n * `beforeload`, `load`, `error`, `change`.\n */\n class RemoteComponent extends HTMLElement implements ConsumeClientConfig {\n name: string = DEFAULT_COMPONENT_NAME;\n bundle: string = DEFAULT_BUNDLE_NAME;\n fallbackSlot?: HTMLSlotElement;\n __next: HTMLDivElement | null = null;\n fouc: HTMLStyleElement | null = null;\n hostState: HostState = createHostState();\n root?: ShadowRoot | null = null;\n reactRoot?: ReturnType<typeof hydrateRoot>;\n emitter: LifecycleEmitter = makeEventEmitter(this);\n onRequest?: ConsumeServerConfig['onRequest'];\n onResponse?: ConsumeServerConfig['onResponse'];\n resolveClientUrl?: ConsumeClientConfig['resolveClientUrl'];\n\n // -- ConsumeServerConfig property accessors (attribute-reflected) --\n\n get src(): string | URL | undefined {\n return this.getAttribute('src') ?? undefined;\n }\n\n set src(value: string | URL | undefined) {\n if (value == null) {\n this.removeAttribute('src');\n } else {\n this.setAttribute('src', String(value));\n }\n }\n\n /** Always `true` — the HTML host always isolates via Shadow DOM. */\n get isolate(): boolean {\n return true;\n }\n\n get mode(): 'open' | 'closed' | undefined {\n const attr = this.getAttribute('mode');\n return attr === 'closed' ? 'closed' : 'open';\n }\n\n set mode(value: 'open' | 'closed' | undefined) {\n if (value) {\n this.setAttribute('mode', value);\n }\n }\n\n get reset(): boolean | undefined {\n return this.getAttribute('reset') !== null;\n }\n\n set reset(value: boolean | undefined) {\n if (value) {\n this.setAttribute('reset', '');\n } else {\n this.removeAttribute('reset');\n }\n }\n\n get credentials(): RequestCredentials | undefined {\n return (this.getAttribute('credentials') ||\n 'same-origin') as RequestCredentials;\n }\n\n set credentials(value: RequestCredentials | undefined) {\n if (value) {\n this.setAttribute('credentials', value);\n } else {\n this.removeAttribute('credentials');\n }\n }\n\n static get observedAttributes() {\n return ['src', 'name', 'mode'];\n }\n\n attributeChangedCallback(name: string, oldValue: string, newValue: string) {\n if ((name === 'src' || name === 'name') && oldValue !== newValue) {\n if (this.src) {\n this.load().catch((e) => {\n // AbortError is expected when loading is cancelled - don't log or dispatch\n if (isAbortError(e)) {\n return;\n }\n logError('HtmlHost', 'Error loading remote component.', e);\n this.emitter.error(e, this.src);\n this.hostState.stage = 'error';\n });\n }\n } else if (name === 'mode' && oldValue !== newValue && this.root) {\n // changing the shadow DOM mode is not supported\n // we need to recreate the shadow DOM and reload the component\n const newRoot = this.attachShadow({\n mode: newValue === 'closed' ? 'closed' : 'open',\n });\n // move all existing children to the new shadow root\n Array.from(this.root.children).forEach((child) => {\n newRoot.appendChild(child);\n });\n this.root = newRoot;\n // reload the remote component to apply the new shadow DOM\n this.load().catch((e) => {\n // AbortError is expected when loading is cancelled - don't log or dispatch\n if (isAbortError(e)) {\n return;\n }\n logError('HtmlHost', 'Error reloading remote component.', e);\n this.emitter.error(e, this.src);\n });\n }\n }\n\n async load() {\n // wait for the current call stack to finish\n await new Promise((resolve) => {\n (typeof queueMicrotask === 'function'\n ? queueMicrotask\n : requestAnimationFrame)(() => {\n resolve(undefined);\n });\n });\n\n // Abort any in-progress load so the latest src always wins.\n if (this.hostState.stage === 'loading') {\n this.hostState.abortController?.abort();\n this.hostState.stage = 'idle';\n // The aborted load may have already appended partial content to the shadow DOM\n // (styles, component children) before reaching an isCurrentLoad() check.\n // Clear it now so the new load starts from a clean state. Skip this when a\n // React root exists — that means a previous load completed successfully and\n // we'll take the startTransition re-render path instead.\n if (this.root && !this.reactRoot) {\n this.root.innerHTML = '';\n this.fouc = null;\n this.fallbackSlot = document.createElement('slot');\n this.root.appendChild(this.fallbackSlot);\n }\n }\n\n if (!this.root) {\n this.root = this.attachShadow({\n mode: this.mode === 'closed' ? 'closed' : 'open',\n });\n\n // create a slot element to allow the remote component to use the default slot\n this.fallbackSlot = document.createElement('slot');\n this.root.appendChild(this.fallbackSlot);\n }\n\n this.name = this.getAttribute('name') || this.name;\n\n this.hostState.stage = 'loading';\n const src = this.src;\n\n // Create AbortController for this load operation\n this.hostState.abortController = new AbortController();\n const signal = this.hostState.abortController.signal;\n\n // Returns true if this is still the active load — the signal hasn't been\n // aborted by a newer load() call, and the src hasn't changed in the meantime.\n // Checking the signal (not just the src) handles the case where the user\n // cycles back to the same src (e.g. styled → basic → styled): both loads\n // share the same src string, so a src-only check would pass for both,\n // causing double renders.\n const isCurrentLoad = () => !signal.aborted && this.src === src;\n\n // Resets stage to 'idle' for expected cancellations (AbortError). Real\n // errors are thrown and caught by attributeChangedCallback which sets\n // stage to 'error'. Only resets if no newer load() has superseded this\n // one — a new load replaces the abortController so the signal comparison\n // fails, preventing us from clobbering the new load's stage.\n const abandonLoad = () => {\n if (\n this.hostState.abortController?.signal === signal &&\n this.hostState.stage === 'loading'\n ) {\n this.hostState.stage = 'idle';\n }\n };\n\n this.emitter.beforeLoad(src ?? '');\n\n const remoteComponentChild =\n this.querySelector('div#__REMOTE_COMPONENT__') ||\n this.querySelector('div[data-bundle][data-route]');\n\n if (!src && !remoteComponentChild) {\n throw new RemoteComponentsError('\"src\" attribute is required');\n }\n\n let url: URL | null = null;\n let html = this.innerHTML;\n\n if (src) {\n url = getClientOrServerUrl(src, window.location.href);\n this.name = resolveNameFromSrc(src, this.name);\n }\n\n const resolveClientUrl = url\n ? bindResolveClientUrl(this.resolveClientUrl, url.href)\n : undefined;\n\n if (!remoteComponentChild && url) {\n // fetch the remote component\n const fetchInit = {\n credentials: this.credentials || 'same-origin',\n } as RequestInit;\n\n const resolvedUrl = new URL(\n resolveClientUrl?.(url.href) ?? url.href,\n window.location.href,\n );\n let res: Response;\n try {\n res = await fetchWithHooks(resolvedUrl, fetchInit, {\n onRequest: this.onRequest,\n onResponse: this.onResponse,\n abortController: this.hostState.abortController,\n });\n } catch (e) {\n if (isAbortError(e)) {\n return abandonLoad();\n }\n throw e;\n }\n\n if (!res || !res.ok) {\n throw await errorFromFailedFetch(url.href, resolvedUrl, res);\n }\n\n // get the full HTML content as a string - race with abort signal\n try {\n html = await res.text();\n } catch (e) {\n if (isAbortError(e)) {\n return abandonLoad();\n }\n throw e;\n }\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n }\n\n const effectiveUrl = url ?? new URL(window.location.href);\n const { doc, parsed } = preparePipeline({\n html,\n name: this.name,\n url: effectiveUrl,\n shared: {},\n resolveClientUrl,\n });\n const {\n component,\n name: resolvedName,\n isRemoteComponent,\n metadata: parsedMetadata,\n nextData,\n rsc,\n remoteShared,\n } = parsed;\n\n // when using a Next.js Pages Router remote application in development mode\n // we hide the remote component to prevent flickering\n // until the CSS is loaded for the remote component\n if (nextData && nextData.buildId === 'development' && !this.reactRoot) {\n this.fouc = document.createElement('style');\n this.fouc.textContent = `:host { display: none; }`;\n this.root.appendChild(this.fouc);\n }\n\n this.name = resolvedName;\n this.bundle = parsedMetadata.bundle;\n\n if (url) {\n getNamespace().bundleUrls[this.bundle] = url;\n }\n\n // add remote component metadata information at the custom element\n const metadataEl = document.createElement('script');\n metadataEl.type = 'application/json';\n metadataEl.setAttribute('data-remote-component', '');\n const metadataObj = {\n name: this.name,\n bundle: this.bundle,\n route: parsedMetadata.route,\n runtime: parsedMetadata.runtime,\n };\n metadataEl.textContent = JSON.stringify(metadataObj);\n\n if (\n this.previousElementSibling?.getAttribute('data-remote-component') !==\n null\n ) {\n this.previousElementSibling?.remove();\n }\n this.parentElement?.insertBefore(metadataEl, this);\n\n if (this.hostState.prevIsRemoteComponent) {\n if (this.hostState.prevUrl) {\n const prevUrl = this.hostState.prevUrl;\n const nsUnmount = getNamespace();\n if (nsUnmount.unmountFns[prevUrl.href]) {\n // call unmount() for all registered unmount functions for the previous remote component\n await Promise.all(\n Array.from(nsUnmount.unmountFns[prevUrl.href] ?? []).map(\n async (unmount) => {\n try {\n await unmount(this.root);\n } catch (e) {\n logError(\n 'HtmlHost',\n `Error while calling unmount() for Remote Component from ${prevUrl.href}.`,\n e,\n );\n }\n },\n ),\n );\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n }\n }\n this.root.innerHTML = '';\n }\n // Dispatch change event if this is not the first load\n if (this.hostState.prevSrc !== undefined) {\n this.emitter.change({\n previousSrc: this.hostState.prevSrc ?? null,\n nextSrc: src ?? null,\n previousName: this.hostState.prevName,\n nextName: this.name,\n });\n }\n\n this.hostState.prevUrl = effectiveUrl;\n this.hostState.prevIsRemoteComponent = isRemoteComponent;\n this.hostState.prevSrc = src;\n this.hostState.prevName = this.name;\n\n // store the original loading content of the custom element\n // this is required to remove the loading content after the remote component is loaded\n const removable = Array.from(this.childNodes);\n\n // reference to all link elements in the remote component\n const links = doc.querySelectorAll<HTMLLinkElement>('link[href]');\n\n const remoteComponentSrc = this.src ? String(this.src) : null;\n\n // Bound function for attaching styles — used both initially and in React effects\n const doAttachStyles = () =>\n attachStyles({\n doc,\n component,\n links,\n signal: undefined, // Effects run after load, no abort needed\n baseUrl: url?.href,\n remoteComponentSrc,\n root: this.root ?? null,\n resolveClientUrl,\n });\n\n if (!this.reactRoot) {\n // ensure all styles are loaded before hydrating to prevent FOUC\n await attachStyles({\n doc,\n component,\n links,\n signal,\n baseUrl: url?.href,\n remoteComponentSrc,\n root: this.root,\n resolveClientUrl,\n });\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n }\n\n if (!this.reactRoot) {\n // attach the remote component content to the shadow DOM\n Array.from(component.children).forEach((el) => {\n if (!isRemoteComponent && el.tagName.toLowerCase() === 'script') {\n const newScript = document.createElement('script');\n // copy all attributes\n for (const attr of el.attributes) {\n if (attr.name === 'src') {\n const absoluteSrc = new URL(\n attr.value,\n url ?? window.location.origin,\n ).href;\n newScript.setAttribute(\n attr.name,\n resolveClientUrl?.(absoluteSrc) ?? absoluteSrc,\n );\n } else {\n newScript.setAttribute(attr.name, attr.value);\n }\n }\n newScript.textContent = el.textContent;\n if (remoteComponentSrc) {\n newScript.setAttribute(\n 'data-remote-component-src',\n remoteComponentSrc,\n );\n }\n this.root?.appendChild(newScript);\n } else {\n const newEl = el.cloneNode(true) as HTMLElement;\n for (const attr of el.attributes) {\n if (attr.name.startsWith('on')) {\n newEl.setAttribute(attr.name, attr.value);\n }\n }\n this.root?.appendChild(newEl);\n }\n });\n }\n\n // clear the loading content of the shadow DOM root\n for (const el of removable) {\n el.parentElement?.removeChild(el);\n }\n this.fallbackSlot?.remove();\n\n // function to apply the reset styles to the shadow DOM\n const applyReset = () => {\n if (\n this.reset &&\n !this.root?.querySelector('link[data-remote-components-reset]')\n ) {\n // all initial styles to reset inherited styles leaking from the host page\n const allInitial = document.createElement('link');\n allInitial.setAttribute('data-remote-components-reset', '');\n const css = `:host { all: initial; }`;\n const allInitialHref = URL.createObjectURL(\n new Blob([css], { type: 'text/css' }),\n );\n allInitial.href = allInitialHref;\n allInitial.rel = 'stylesheet';\n // we need to revoke the object URL after the stylesheet is loaded to free up memory\n allInitial.onload = () => {\n URL.revokeObjectURL(allInitialHref);\n allInitial.removeAttribute('onload');\n };\n allInitial.onerror = () => {\n URL.revokeObjectURL(allInitialHref);\n allInitial.removeAttribute('onload');\n };\n this.root?.prepend(allInitial);\n } else if (\n !this.reset &&\n this.root?.querySelector('link[data-remote-components-reset]')\n ) {\n this.root\n .querySelector('link[data-remote-components-reset]')\n ?.remove();\n }\n };\n\n // apply the reset styles if required and not already applied\n if (!this.reactRoot) {\n applyReset();\n }\n\n const {\n self,\n createFromReadableStream,\n nextClientPagesLoader,\n preloadScripts,\n } = await getRuntime(\n metadataObj.runtime as Runtime,\n effectiveUrl,\n this.bundle,\n {\n react: async () => (await import('react')).default,\n 'react/jsx-dev-runtime': async () =>\n (await import('react/jsx-dev-runtime')).default,\n 'react/jsx-runtime': async () =>\n (await import('react/jsx-runtime')).default,\n 'react-dom': async () => (await import('react-dom')).default,\n 'react-dom/client': async () =>\n (await import('react-dom/client')).default,\n },\n remoteShared,\n resolveClientUrl,\n );\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n\n const scripts = isRemoteComponent\n ? component.querySelectorAll<HTMLScriptElement>('script')\n : doc.querySelectorAll<HTMLScriptElement>(\n 'script[src],script[data-src],script[data-remote-component-entrypoint]',\n );\n if (!url) {\n url = new URL(\n component.getAttribute('data-route') ?? '/',\n window.location.href,\n );\n }\n\n await preloadScripts(Array.from(scripts), url, this.bundle, this.name);\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n\n // remove all script elements from the shadow DOM to prevent re-execution of scripts\n if (isRemoteComponent) {\n Array.from(component.children).forEach((child) => {\n if (child.tagName === 'SCRIPT') {\n child.remove();\n }\n });\n }\n\n // cleanup previous remote component instances when a new remote component is loaded\n // this is required when the src attribute is changed to load a new remote component\n const doCleanup = () => {\n if (this.root && remoteComponentSrc) {\n const selector = `[data-remote-component-src]:not([data-remote-component-src=\"${remoteComponentSrc}\"])`;\n const prevCleanup = [\n ...this.root.querySelectorAll(selector),\n ...document.body.querySelectorAll(selector),\n ] as HTMLElement[];\n\n if (prevCleanup.length > 0) {\n prevCleanup.forEach((prev) => {\n prev.remove();\n });\n }\n }\n };\n\n // using RSC hydration if the RSC flight data is available\n if (rsc) {\n // remove the RSC flight data script element\n rsc.parentElement?.removeChild(rsc);\n\n // reload the RSC flight data script to eval it's content\n const rscName = `__remote_component_rsc_${escapeString(\n url.href,\n )}_${escapeString(this.name)}`;\n const rscClone = document.createElement('script');\n rscClone.id = `${rscName}_rsc`;\n rscClone.textContent =\n rsc.textContent?.replace(\n new RegExp(`self\\\\[\"${this.name}\"\\\\]`, 'g'),\n `self[\"${rscName}\"]`,\n ) ?? '';\n document.body.appendChild(rscClone);\n\n let cache: React.ReactNode;\n // React component to convert the RSC flight data into a React component\n const RemoteComponentFromReadableStream = ({\n name,\n initial,\n }: {\n name: string;\n initial: boolean;\n }) => {\n // convert the RSC flight data array into a ReadableStream\n // get the RSC flight data from the global scope\n // the RSC flight data is stored in an array\n // fallback to an empty RSC payload if the data is not found\n const stream = createRSCStream(\n rscName,\n self[rscName as RSCKey] ?? [`0:[null]\\n`],\n );\n const Component =\n cache ??\n // cache the component to avoid reloading the RSC flight data\n (cache = createFromReadableStream(stream) as React.ReactNode);\n\n useLayoutEffect(() => {\n // clear the RSC flight data from the global scope to free up memory\n if (self[name as RSCKey]) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete self[name as RSCKey];\n }\n const rscScript = document.getElementById(`${name}_rsc`);\n if (rscScript) {\n rscScript.remove();\n }\n\n doCleanup();\n applyReset();\n if (!initial) {\n doAttachStyles().catch((e: unknown) => {\n logError('HtmlHost', 'Error attaching styles.', e);\n });\n }\n if (isCurrentLoad()) {\n this.hostState.stage = 'loaded';\n }\n\n this.emitter.load(this.src ?? '');\n }, [initial, name]);\n\n // React can handle the component reference and will wait for the component to be ready\n return Component;\n };\n\n // when we already have a React root, we just need to render the new component\n if (this.reactRoot) {\n const root = this.reactRoot;\n startTransition(() => {\n root.render(\n <RemoteComponentFromReadableStream\n initial={false}\n name={this.name}\n />,\n );\n });\n return;\n }\n\n // hydrate the remote component using the RSC flight data\n this.reactRoot = hydrateRoot(\n // hydrateRoot expects a document or element, but it works for the shadow DOM too\n // @ts-expect-error support for shadow DOM\n this.root,\n <RemoteComponentFromReadableStream initial name={this.name} />,\n );\n } else if (nextData) {\n // using Next.js client pages loader if the Next.js hydration data is available\n const { Component, App } = nextClientPagesLoader(\n this.bundle,\n nextData.page ?? '/',\n this.root,\n );\n\n // if we have the component, we can hydrate it\n if (Component) {\n const RemoteComponentFromNext = ((\n NextApp: ReturnType<typeof nextClientPagesLoader>['App'],\n NextComponent: NonNullable<\n ReturnType<typeof nextClientPagesLoader>['Component']\n >,\n remoteComponent = this,\n ) =>\n function RemoteComponentNext({ initial }: { initial: boolean }) {\n useLayoutEffect(() => {\n doCleanup();\n if (!initial) {\n applyReset();\n doAttachStyles().catch((e: unknown) => {\n logError('HtmlHost', 'Error attaching styles.', e);\n });\n }\n if (isCurrentLoad()) {\n remoteComponent.hostState.stage = 'loaded';\n }\n\n remoteComponent.emitter.load(remoteComponent.src ?? '');\n }, [initial, remoteComponent]);\n\n return NextApp ? (\n <NextApp Component={NextComponent} {...nextData.props} />\n ) : (\n <NextComponent {...nextData.props} />\n );\n })(App, Component, this);\n\n // when we already have a React root, we just need to render the new component\n if (this.reactRoot) {\n const root = this.reactRoot;\n startTransition(() => {\n root.render(<RemoteComponentFromNext initial={false} />);\n doCleanup();\n if (isCurrentLoad()) {\n this.hostState.stage = 'loaded';\n }\n });\n return;\n }\n\n // hydrate the remote component using the Next.js pages router\n this.reactRoot = hydrateRoot(\n // hydrateRoot expects a document or element, but it works for the shadow DOM too\n // @ts-expect-error support for shadow DOM\n this.root,\n <RemoteComponentFromNext initial />,\n );\n }\n\n // remove the FOUC workaround style element to show the remote component\n // this is only for development mode\n if (this.fouc) {\n this.root.removeChild(this.fouc);\n }\n } else if (getNamespace().mountFns[url.href]) {\n // using script entrypoint when no RSC or Next.js data is available\n await Promise.all(\n Array.from(getNamespace().mountFns[url.href] ?? []).map(\n async (mount) => {\n try {\n await mount(this.root);\n } catch (e) {\n logError(\n 'HtmlHost',\n `Error while calling mount() for Remote Component from ${url.href}.`,\n e,\n );\n }\n },\n ),\n );\n\n this.emitter.load(this.src ?? '');\n } else {\n this.emitter.load(this.src ?? '');\n }\n\n if (isCurrentLoad()) {\n this.hostState.stage = 'loaded';\n }\n }\n }\n\n // register the custom element\n customElements.define('remote-component', RemoteComponent);\n}\n\nexport function registerSharedModules(\n modules: Record<string, () => Promise<unknown>> = {},\n) {\n const ns = getNamespace();\n Object.entries(modules).forEach(([key, value]) => {\n ns.hostSharedModules[key] = value;\n });\n}\n","import type {\n HookOptions,\n OnRequestHook,\n OnResponseHook,\n} from '#internal/host/shared/fetch-interceptors';\nimport { warnCrossOriginFetchError } from '#internal/utils/logger';\nimport { remoteFetchHeaders } from './fetch-headers';\n\n/**\n * Options for fetching with request/response hooks.\n */\ninterface FetchWithHooksOptions {\n /** Hook to intercept the request before fetching */\n onRequest?: OnRequestHook;\n /** Hook to process the response after fetching */\n onResponse?: OnResponseHook;\n /** AbortController to cancel loading - aborts will throw AbortError */\n abortController?: AbortController;\n}\n\n/**\n * Performs a fetch with optional request and response lifecycle hooks.\n *\n * This utility centralizes the logic for:\n * 1. Calling onRequest hook - if it returns a Response, use it instead of fetching\n * 2. Performing the actual fetch if onRequest didn't provide a response\n * 3. Calling onResponse hook - if it returns a Response, use that transformed response\n *\n * Hooks receive an AbortSignal and abort function to cancel loading at any point.\n * When aborted, throws AbortError (DOMException with name 'AbortError').\n *\n * @param url - The URL to fetch\n * @param init - The fetch init options\n * @param options - Optional hooks for request/response interception and AbortController\n * @returns The response (never null - throws on abort)\n * @throws DOMException with name 'AbortError' if loading is aborted\n *\n * @example\n * const controller = new AbortController();\n * try {\n * const response = await fetchWithHooks(url, fetchInit, {\n * abortController: controller,\n * onResponse: async (url, response, { abort }) => {\n * if (response.redirected) {\n * abort(); // Throws AbortError\n * }\n * },\n * });\n * } catch (error) {\n * if (error.name === 'AbortError') {\n * console.log('Loading was aborted');\n * }\n * }\n */\nasync function fetchWithWarning(\n url: URL,\n init: RequestInit,\n): Promise<Response> {\n try {\n return await fetch(url, init);\n } catch (error) {\n warnCrossOriginFetchError('FetchRemoteComponent', url);\n throw error;\n }\n}\n\nexport async function fetchWithHooks(\n url: URL,\n additionalInit: {\n credentials?: RequestCredentials;\n next?: {\n tags?: string[];\n };\n },\n options: FetchWithHooksOptions = {},\n): Promise<Response> {\n const {\n onRequest,\n onResponse,\n abortController = new AbortController(),\n } = options;\n const signal = abortController.signal;\n\n const hookOptions: HookOptions = {\n signal,\n abort: (reason?: unknown) => abortController.abort(reason),\n };\n\n // Include signal in fetch init for reactive abort support\n const init: RequestInit = {\n method: 'GET',\n headers: remoteFetchHeaders(),\n signal,\n ...additionalInit,\n };\n\n // Call onRequest hook if provided - may return a Response to skip fetching\n const res =\n (await onRequest?.(url, init, hookOptions)) ??\n (await fetchWithWarning(url, init));\n\n // Call onResponse hook if provided - may return a transformed Response\n return (await onResponse?.(url, res, hookOptions)) ?? res;\n}\n","/**\n * The headers to use when fetching the remote component.\n */\nexport function remoteFetchHeaders() {\n return {\n /**\n * Authenticates deployment protection for the remote. Needed for SSR and SSG clients.\n * If the remote component uses vercel deployment protection, ensure the host and remote vercel\n * projects share a common automation bypass secret, and the shared secret is used as the\n * VERCEL_AUTOMATION_BYPASS_SECRET env var in the host project.\n */\n ...(typeof process === 'object' &&\n typeof process.env === 'object' &&\n typeof process.env.VERCEL_AUTOMATION_BYPASS_SECRET === 'string'\n ? {\n 'x-vercel-protection-bypass':\n process.env.VERCEL_AUTOMATION_BYPASS_SECRET,\n }\n : {}),\n Accept: 'text/html',\n };\n}\n","export function getClientOrServerUrl(\n src: string | URL | undefined,\n serverFallback: string,\n): URL {\n const fallback =\n typeof location !== 'undefined' ? location.href : serverFallback;\n\n if (!src) {\n return new URL(fallback);\n }\n\n return typeof src === 'string' ? new URL(src, fallback) : src;\n}\n","import type { ChangeInfo, ConsumeLifecycleCallbacks } from './config';\n\n/**\n * Unified lifecycle event emitter used by the host loading pipeline.\n *\n * Hosts create an emitter that matches their eventing model — React hosts\n * wrap callback props via {@link makeReactEmitter}, while the HTML custom\n * element dispatches DOM events via {@link makeEventEmitter}. The pipeline\n * calls emitter methods at the appropriate phases without knowing which\n * host is driving the load.\n */\nexport interface LifecycleEmitter {\n beforeLoad(src: string | URL): void;\n load(src: string | URL): void;\n error(error: unknown, src?: string | URL): void;\n change(info: ChangeInfo): void;\n}\n\n/**\n * Wraps React-style callback props into a {@link LifecycleEmitter}.\n *\n * Missing callbacks are silently ignored — this is the normal case for\n * hosts that only subscribe to a subset of events.\n */\nexport function makeReactEmitter(\n callbacks: ConsumeLifecycleCallbacks,\n): LifecycleEmitter {\n return {\n beforeLoad(src) {\n callbacks.onBeforeLoad?.(src);\n },\n load(src) {\n callbacks.onLoad?.(src);\n },\n error(error, _src?) {\n callbacks.onError?.(error);\n },\n change(info) {\n callbacks.onChange?.(info);\n },\n };\n}\n\n/**\n * Wraps a DOM element into a {@link LifecycleEmitter} by dispatching\n * `CustomEvent`s with `bubbles: true` and `composed: true` (crosses\n * Shadow DOM boundaries).\n */\nexport function makeEventEmitter(element: HTMLElement): LifecycleEmitter {\n function dispatch(\n type: 'beforeload' | 'load' | 'error' | 'change',\n detail?: Record<string, unknown>,\n ) {\n const event = new Event(type, { bubbles: true, composed: true });\n if (detail) {\n Object.assign(event, detail);\n }\n element.dispatchEvent(event);\n }\n\n return {\n beforeLoad(src) {\n dispatch('beforeload', { src });\n },\n load(src) {\n dispatch('load', { src });\n },\n error(error, src?) {\n dispatch('error', src != null ? { error, src } : { error });\n },\n change(info) {\n dispatch('change', info as unknown as Record<string, unknown>);\n },\n };\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport type { ScriptDescriptor } from '#internal/host/shared/asset-descriptors';\nimport type { ConsumeLoaderPayload } from '#internal/host/shared/server-handoff';\nimport { buildHostShared } from '#internal/host/shared/shared-module-resolver';\nimport { applyOriginToNodes } from '#internal/runtime/html/apply-origin';\nimport {\n type ParsedRemoteComponent,\n parseRemoteComponentDocument,\n} from '#internal/runtime/html/parse-remote-html';\nimport { loadRemoteComponent } from '#internal/runtime/loaders/component-loader';\nimport { loadStaticRemoteComponent } from '#internal/runtime/loaders/static-loader';\nimport type { RemoteComponentMetadata } from '#internal/runtime/metadata';\nimport {\n collapseDoubleSlashes,\n REMOTE_COMPONENT_REGEX,\n} from '#internal/runtime/patterns';\nimport type { MountOrUnmountFunction } from '#internal/runtime/types';\nimport { escapeString } from '#internal/utils';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\ntype SharedModuleMap = Record<string, (bundle?: string) => Promise<unknown>>;\n\n/**\n * Input for {@link runPipeline} — the full post-fetch pipeline that starts\n * from raw HTML.\n */\nexport interface PipelineInput {\n /** Resolved URL of the remote component. */\n url: URL;\n /** Raw HTML string returned by the remote. */\n html: string;\n /** Component name hint (may be refined during parsing). */\n name: string;\n /** Abort signal — the pipeline checks this between async steps. */\n signal: AbortSignal;\n /** Host-provided shared module factories (resolved or promise). */\n shared: Promise<SharedModuleMap> | SharedModuleMap;\n /** URL rewriter for client-side asset URLs. */\n resolveClientUrl?: InternalResolveClientUrl;\n /** Shadow root or element to mount into (for script-based components). */\n container?: ShadowRoot | HTMLElement | null;\n}\n\n/**\n * Input for {@link runPipelineFromParsed} — the pipeline entry point for\n * hosts that receive pre-parsed SSR data (e.g. the App Router client).\n */\nexport interface ParsedPipelineInput {\n /** Resolved URL of the remote component. */\n url: URL;\n /** Component name. */\n name: string;\n /** Abort signal. */\n signal: AbortSignal;\n /** Pre-resolved loader payload from the server component. */\n payload: ConsumeLoaderPayload;\n /** Host-provided shared module factories (resolved or promise). */\n shared: Promise<SharedModuleMap> | SharedModuleMap;\n /** Remote-requested shared modules. */\n remoteShared?: Record<string, string>;\n /** URL rewriter for client-side asset URLs. */\n resolveClientUrl?: InternalResolveClientUrl;\n /** Shadow root or element to mount into. */\n container?: ShadowRoot | HTMLElement | null;\n /** Optional RSC name override (used by App Router for scoped RSC data). */\n rscName?: string;\n}\n\n/**\n * Successful dynamic component load — the component is a React element tree\n * ready to render.\n */\nexport interface PipelineLoaded {\n status: 'loaded';\n component: React.ReactNode;\n metadata: RemoteComponentMetadata;\n parsed: ParsedRemoteComponent;\n doc: Document;\n}\n\n/**\n * Successful static component load — mount/unmount functions are returned\n * for the host to call.\n */\nexport interface PipelineStatic {\n status: 'static';\n mount: Set<MountOrUnmountFunction>;\n unmount: Set<MountOrUnmountFunction>;\n metadata: RemoteComponentMetadata;\n parsed: ParsedRemoteComponent;\n doc: Document;\n}\n\n/** The load was aborted before it could complete. */\nexport interface PipelineAborted {\n status: 'aborted';\n}\n\n/** The load failed with an error. */\nexport interface PipelineError {\n status: 'error';\n error: Error;\n}\n\nexport type PipelineResult =\n | PipelineLoaded\n | PipelineStatic\n | PipelineAborted\n | PipelineError;\n\n/**\n * Intermediate result from {@link preparePipeline}. Hosts that need to run\n * framework-specific logic between parse and load (e.g. inline script\n * execution in the React host) use this to split the pipeline into two\n * phases.\n */\nexport interface PreparedPipeline {\n doc: Document;\n parsed: ParsedRemoteComponent;\n /** Script descriptors ready to pass to `loadRemoteComponent`. */\n scriptDescriptors: ScriptDescriptor[];\n}\n\n// ---------------------------------------------------------------------------\n// Pipeline phases\n// ---------------------------------------------------------------------------\n\n/**\n * Phase 1: Parse HTML, validate shared modules, and normalize URLs.\n *\n * This is the synchronous/cheap portion of the pipeline. Hosts that need to\n * inject logic between parse and load (e.g. executing inline scripts) call\n * this directly, then call {@link loadPrepared} when ready.\n */\nexport function preparePipeline(input: {\n html: string;\n name: string;\n url: URL;\n shared: SharedModuleMap;\n remoteShared?: Record<string, string>;\n resolveClientUrl?: InternalResolveClientUrl;\n}): PreparedPipeline {\n const parser = new DOMParser();\n const doc = parser.parseFromString(input.html, 'text/html');\n\n const parsed = parseRemoteComponentDocument(doc, input.name, input.url);\n\n // Validate shared modules — surface errors early before any script loading.\n // Only check *remote* shared modules here. The host-side marker\n // (`__remote_components_missing_shared__` in `input.shared`) is a callable\n // error signal that the host may intentionally leave in place when\n // `withRemoteComponentsConfig` is not used — blocking on it would break\n // framework-agnostic hosts that don't configure shared modules.\n const remoteShared = input.remoteShared ?? parsed.remoteShared;\n if ('__remote_components_missing_shared__' in remoteShared) {\n throw new RemoteComponentsError(\n remoteShared.__remote_components_missing_shared__,\n );\n }\n\n applyOriginToNodes(doc, input.url, input.resolveClientUrl);\n\n const scriptDescriptors = buildScriptDescriptors(parsed.scripts, input.url);\n\n return { doc, parsed, scriptDescriptors };\n}\n\n/**\n * Phase 2: Load the component from a prepared pipeline result.\n *\n * For dynamic components, delegates to `loadRemoteComponent`. For static\n * components (`isRemoteComponent`), delegates to `loadStaticRemoteComponent`.\n */\nexport async function loadPrepared(input: {\n prepared: PreparedPipeline;\n url: URL;\n signal: AbortSignal;\n shared: Promise<SharedModuleMap> | SharedModuleMap;\n resolveClientUrl?: InternalResolveClientUrl;\n container?: ShadowRoot | HTMLElement | null;\n rscName?: string;\n}): Promise<PipelineResult> {\n const { prepared, url, signal, resolveClientUrl, container, rscName } = input;\n const { doc, parsed, scriptDescriptors } = prepared;\n\n if (signal.aborted) {\n return { status: 'aborted' };\n }\n\n const userShared = await input.shared;\n if (signal.aborted) {\n return { status: 'aborted' };\n }\n\n if (parsed.isRemoteComponent) {\n return loadStaticPath({\n parsed,\n doc,\n url,\n resolveClientUrl,\n });\n }\n\n return loadDynamicPath({\n parsed,\n doc,\n url,\n scriptDescriptors,\n shared: userShared,\n resolveClientUrl,\n container,\n rscName,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Full pipeline entry points\n// ---------------------------------------------------------------------------\n\n/**\n * Full post-fetch pipeline: parse → validate → normalize → load.\n *\n * Use this when starting from a raw HTML string (React host, HTML host).\n */\nexport async function runPipeline(\n input: PipelineInput,\n): Promise<PipelineResult> {\n try {\n const userShared = await input.shared;\n if (input.signal.aborted) {\n return { status: 'aborted' };\n }\n\n const prepared = preparePipeline({\n html: input.html,\n name: input.name,\n url: input.url,\n shared: userShared,\n resolveClientUrl: input.resolveClientUrl,\n });\n\n return await loadPrepared({\n prepared,\n url: input.url,\n signal: input.signal,\n shared: userShared,\n resolveClientUrl: input.resolveClientUrl,\n container: input.container,\n });\n } catch (error) {\n return {\n status: 'error',\n error:\n error instanceof Error\n ? error\n : new RemoteComponentsError(String(error)),\n };\n }\n}\n\n/**\n * Pipeline entry point for pre-parsed SSR data (App Router client).\n *\n * Skips HTML parsing and goes straight to `loadRemoteComponent` with the\n * pre-resolved payload from the server component.\n */\nexport async function runPipelineFromParsed(\n input: ParsedPipelineInput,\n): Promise<\n | { status: 'loaded'; component: React.ReactNode }\n | PipelineAborted\n | PipelineError\n> {\n try {\n if (input.signal.aborted) {\n return { status: 'aborted' };\n }\n\n const remoteShared = input.remoteShared ?? input.payload.remoteShared ?? {};\n\n if ('__remote_components_missing_shared__' in remoteShared) {\n throw new RemoteComponentsError(\n remoteShared.__remote_components_missing_shared__,\n );\n }\n\n const result = await loadRemoteComponent({\n url: input.url,\n name: input.name,\n rscName: input.rscName,\n bundle: input.payload.bundle,\n route: input.payload.route,\n runtime: input.payload.runtime,\n data: input.payload.data,\n nextData: input.payload.nextData,\n scripts: input.payload.scripts,\n shared: input.shared,\n remoteShared,\n container: input.container,\n resolveClientUrl: input.resolveClientUrl,\n });\n\n if (input.signal.aborted) {\n return { status: 'aborted' };\n }\n\n if (result.error) {\n return { status: 'error', error: result.error };\n }\n return { status: 'loaded', component: result.component };\n } catch (error) {\n return {\n status: 'error',\n error:\n error instanceof Error\n ? error\n : new RemoteComponentsError(String(error)),\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts parsed `<script>` elements into the `ScriptDescriptor[]` format\n * expected by `loadRemoteComponent`. Handles the `[bundle] id` URL format\n * and collapses double slashes.\n */\nfunction buildScriptDescriptors(\n scripts: HTMLScriptElement[],\n url: URL,\n): ScriptDescriptor[] {\n return scripts.map((script) => {\n const scriptSrc =\n script.getAttribute('data-src') ||\n script.getAttribute('src') ||\n script.src;\n const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(scriptSrc)\n ?.groups ?? {\n prefix: undefined,\n id: scriptSrc,\n };\n return {\n src: new URL(collapseDoubleSlashes(`${prefix ?? ''}${path}`), url).href,\n };\n });\n}\n\nasync function loadStaticPath(input: {\n parsed: ParsedRemoteComponent;\n doc: Document;\n url: URL;\n resolveClientUrl?: InternalResolveClientUrl;\n}): Promise<PipelineStatic> {\n const { parsed, doc, url, resolveClientUrl } = input;\n const scripts = Array.from(\n parsed.component.querySelectorAll<HTMLScriptElement>('script'),\n );\n const { mount, unmount } = await loadStaticRemoteComponent(\n scripts,\n url,\n resolveClientUrl,\n );\n return {\n status: 'static',\n mount,\n unmount,\n metadata: parsed.metadata,\n parsed,\n doc,\n };\n}\n\nasync function loadDynamicPath(input: {\n parsed: ParsedRemoteComponent;\n doc: Document;\n url: URL;\n scriptDescriptors: ScriptDescriptor[];\n shared: SharedModuleMap;\n resolveClientUrl?: InternalResolveClientUrl;\n container?: ShadowRoot | HTMLElement | null;\n rscName?: string;\n}): Promise<PipelineLoaded | PipelineError> {\n const {\n parsed,\n doc,\n url,\n scriptDescriptors,\n shared,\n resolveClientUrl,\n container,\n } = input;\n\n const rscName =\n input.rscName ??\n (parsed.rsc\n ? `__remote_component_rsc_${escapeString(url.href)}_${escapeString(parsed.name)}`\n : undefined);\n\n const rscData = parsed.rsc\n ? (parsed.rsc.textContent || '').split('\\n').filter(Boolean)\n : [];\n\n const result = await loadRemoteComponent({\n url,\n name: parsed.name,\n rscName,\n bundle: parsed.metadata.bundle,\n route: parsed.metadata.route,\n runtime: parsed.metadata.runtime,\n data: rscData,\n nextData: parsed.nextData,\n scripts: scriptDescriptors,\n shared: buildHostShared(shared, resolveClientUrl),\n remoteShared: parsed.remoteShared,\n container,\n resolveClientUrl,\n });\n\n if (result.error) {\n return { status: 'error', error: result.error };\n }\n return {\n status: 'loaded',\n component: result.component,\n metadata: parsed.metadata,\n parsed,\n doc,\n };\n}\n","/**\n * Pure constants for HTML element names, data attributes, and ID suffixes\n * used across both server-side (parse5) and browser (DOM) HTML processing.\n *\n * No imports, no runtime code — safe to use in any context.\n */\n\n/** Elements whose `src`, `href`, `srcset`, and `imagesrcset` need origin rewriting. */\nexport const ORIGIN_REWRITE_TAGS = [\n 'img',\n 'source',\n 'video',\n 'audio',\n 'track',\n 'iframe',\n 'embed',\n 'script',\n 'link',\n] as const;\n\n// ID suffixes appended to the component name to form element IDs.\nexport const ID_SUFFIX_RSC = '_rsc';\nexport const ID_SUFFIX_SSR = '_ssr';\nexport const ID_SUFFIX_SHARED = '_shared';\n\n// Data attributes written on the remote component wrapper element.\nexport const DATA_BUNDLE = 'data-bundle';\nexport const DATA_ROUTE = 'data-route';\nexport const DATA_RUNTIME = 'data-runtime';\nexport const DATA_TYPE = 'data-type';\nexport const DATA_SRC = 'data-src';\nexport const DATA_REMOTE_COMPONENTS_SHARED = 'data-remote-components-shared';\n\n// Well-known element identifiers.\nexport const TAG_REMOTE_COMPONENT = 'remote-component';\nexport const NEXT_DATA_ID = '__NEXT_DATA__';\nexport const REMOTE_NEXT_DATA_ID = '__REMOTE_NEXT_DATA__';\nexport const NEXT_CONTAINER_ID = '__next';\n","/**\n * Rewrites relative URLs in an HTML `srcset` or `imagesrcset` attribute value\n * to absolute URLs. Works identically in server (parse5) and browser (DOM) contexts.\n *\n * @param srcset - The raw srcset attribute value (comma-separated entries).\n * @param base - Base URL or origin to resolve relative URLs against.\n * @param resolve - Optional callback applied to each absolute URL (e.g. to proxy through a CDN).\n * @returns The rewritten srcset string with absolute (and optionally resolved) URLs.\n */\nexport function rewriteSrcset(\n srcset: string,\n base: URL | string,\n resolve?: (absoluteUrl: string) => string,\n): string {\n return srcset\n .split(',')\n .map((entry) => {\n const [url, descriptor] = entry.trim().split(/\\s+/);\n if (!url) return entry;\n\n const absoluteUrl = new URL(url, base).href;\n const resolvedUrl = resolve ? resolve(absoluteUrl) : absoluteUrl;\n return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;\n })\n .join(', ');\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { ORIGIN_REWRITE_TAGS } from './html-spec';\nimport { rewriteSrcset } from './rewrite-srcset';\n\nexport function applyOriginToNodes(\n doc: Document | HTMLElement,\n url: URL,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n if (url.origin !== location.origin) {\n const nodes = doc.querySelectorAll<HTMLImageElement>(\n ORIGIN_REWRITE_TAGS.map(\n (type) =>\n `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`,\n ).join(','),\n );\n nodes.forEach((node) => {\n if (\n node.hasAttribute('src') &&\n /^[./]+\\/?/.test(node.getAttribute('src') ?? '')\n ) {\n const absoluteSrc = new URL(node.getAttribute('src') ?? '/', url).href;\n // Script elements are handled by the loaders (script-loader, static-loader)\n // which apply the callback themselves. Only apply it here for non-script elements.\n const isScript = node.tagName.toLowerCase() === 'script';\n node.src = isScript\n ? absoluteSrc\n : (resolveClientUrl?.(absoluteSrc) ?? absoluteSrc);\n }\n if (\n node.hasAttribute('href') &&\n /^[./]+\\/?/.test(node.getAttribute('href') ?? '')\n ) {\n const absoluteHref = new URL(node.getAttribute('href') ?? '/', url)\n .href;\n node.setAttribute(\n 'href',\n resolveClientUrl?.(absoluteHref) ?? absoluteHref,\n );\n }\n if (node.hasAttribute('srcset')) {\n const raw = node.getAttribute('srcset');\n if (raw) {\n const resolve = resolveClientUrl\n ? (abs: string) => resolveClientUrl(abs) ?? abs\n : undefined;\n node.setAttribute('srcset', rewriteSrcset(raw, url, resolve));\n }\n }\n if (node.hasAttribute('imagesrcset')) {\n const raw = node.getAttribute('imagesrcset');\n if (raw) {\n const resolve = resolveClientUrl\n ? (abs: string) => resolveClientUrl(abs) ?? abs\n : undefined;\n node.setAttribute('imagesrcset', rewriteSrcset(raw, url, resolve));\n }\n }\n });\n }\n}\n","import type { NextData } from '#internal/host/server/types';\nimport {\n DEFAULT_COMPONENT_NAME,\n RUNTIME_SCRIPT,\n} from '#internal/runtime/constants';\nimport {\n buildMetadata,\n type RemoteComponentMetadata,\n} from '#internal/runtime/metadata';\nimport {\n multipleRemoteComponentsError,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport {\n DATA_BUNDLE,\n DATA_REMOTE_COMPONENTS_SHARED,\n DATA_ROUTE,\n DATA_RUNTIME,\n DATA_SRC,\n DATA_TYPE,\n ID_SUFFIX_RSC,\n ID_SUFFIX_SHARED,\n ID_SUFFIX_SSR,\n NEXT_CONTAINER_ID,\n NEXT_DATA_ID,\n REMOTE_NEXT_DATA_ID,\n TAG_REMOTE_COMPONENT,\n} from './html-spec';\n\nexport interface ParsedRemoteComponent {\n /** The DOM element representing the remote component content. */\n component: Element;\n /** Resolved name of the remote component (with _ssr suffix stripped). */\n name: string;\n /** Whether the component is a <remote-component> custom element. */\n isRemoteComponent: boolean;\n /** Component metadata: bundle, route, runtime. */\n metadata: RemoteComponentMetadata;\n /** Parsed __NEXT_DATA__ or __REMOTE_NEXT_DATA__, or null. */\n nextData: NextData | null;\n /** The RSC flight data script element, or null. */\n rsc: Element | null;\n /** Shared module map extracted from the component's shared data script. */\n remoteShared: Record<string, string>;\n /** Link elements extracted from the document (outside the component). */\n links: HTMLLinkElement[];\n /** Script elements extracted from the component or document. */\n scripts: HTMLScriptElement[];\n}\n\n/**\n * Validates that the document does not contain multiple unnamed remote components.\n * When multiple components exist, the consumer must specify a name to select one.\n */\nexport function validateSingleComponent(\n doc: Document,\n name: string,\n url: string,\n): void {\n if (\n (doc.querySelectorAll(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`).length > 1 &&\n !doc.querySelector(\n `div[${DATA_BUNDLE}][${DATA_ROUTE}][id^=\"${name}\"]`,\n )) ||\n (doc.querySelectorAll(`${TAG_REMOTE_COMPONENT}:not([src])`).length > 1 &&\n !doc.querySelector(`${TAG_REMOTE_COMPONENT}[name=\"${name}\"]`))\n ) {\n throw multipleRemoteComponentsError(url);\n }\n}\n\n/**\n * Finds the remote component element in the parsed HTML document using the\n * standard querySelector chain. Returns null if no component is found.\n */\nexport function findComponentElement(\n doc: Document,\n name: string,\n): Element | null {\n return (\n doc.querySelector(`div[${DATA_BUNDLE}][${DATA_ROUTE}][id^=\"${name}\"]`) ??\n doc.querySelector(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`) ??\n doc.querySelector(`div#${NEXT_CONTAINER_ID}`) ??\n doc.querySelector(`${TAG_REMOTE_COMPONENT}[name=\"${name}\"]:not([src])`) ??\n doc.querySelector(`${TAG_REMOTE_COMPONENT}:not([src])`)\n );\n}\n\n/**\n * Parses the __NEXT_DATA__ or __REMOTE_NEXT_DATA__ script element from the document.\n */\nexport function parseNextData(doc: Document): NextData | null {\n return JSON.parse(\n (\n doc.querySelector(`#${NEXT_DATA_ID}`) ??\n doc.querySelector(`#${REMOTE_NEXT_DATA_ID}`)\n )?.textContent ?? 'null',\n ) as NextData | null;\n}\n\n/**\n * Resolves the component name from the element's id attribute, the name attribute\n * (for <remote-component> elements), nextData, or a fallback value.\n * Strips the _ssr suffix from the id if present.\n */\nexport function resolveComponentName(\n component: Element | null,\n nextData: NextData | null,\n fallbackName: string,\n): { name: string; isRemoteComponent: boolean } {\n const isRemoteComponent =\n component?.tagName.toLowerCase() === TAG_REMOTE_COMPONENT;\n\n const name =\n component\n ?.getAttribute('id')\n ?.replace(new RegExp(`${ID_SUFFIX_SSR}$`), '') ||\n (isRemoteComponent && component?.getAttribute('name')) ||\n (nextData ? '__next' : fallbackName);\n\n return { name, isRemoteComponent };\n}\n\n/**\n * Extracts the shared module map from the document and removes the element.\n * Falls back to nextData's shared modules if available.\n */\nexport function extractRemoteShared(\n doc: Document,\n name: string,\n nextData: NextData | null,\n): Record<string, string> {\n const remoteSharedEl = doc.querySelector(\n `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`,\n );\n const remoteShared =\n nextData?.props.__REMOTE_COMPONENT__?.shared ??\n ((JSON.parse(remoteSharedEl?.textContent ?? '{}') ?? {}) as Record<\n string,\n string\n >);\n remoteSharedEl?.remove();\n return remoteShared;\n}\n\n/**\n * Validates that a remote component was found in the document and that it has\n * RSC data, Next.js data, or is a <remote-component> element.\n * Acts as a type assertion - narrows component to non-null on success.\n */\nexport function validateComponentFound(\n component: Element | null,\n rsc: Element | null,\n nextData: NextData | null,\n isRemoteComponent: boolean,\n url: string,\n name: string,\n): asserts component is Element {\n if (!component || !(rsc || nextData || isRemoteComponent)) {\n throw new RemoteComponentsError(\n `Remote Component not found on ${url}.${\n name !== DEFAULT_COMPONENT_NAME\n ? ` The name for the <RemoteComponent> is \"${name}\". Check <RemoteComponent> usage.`\n : ''\n } Did you forget to wrap the content in <RemoteComponent>?`,\n );\n }\n}\n\n/**\n * Extracts link elements from the document that are not inside the component.\n */\nexport function extractLinks(\n doc: Document,\n component: Element,\n): HTMLLinkElement[] {\n return Array.from(doc.querySelectorAll<HTMLLinkElement>('link[href]')).filter(\n (link) => !component.contains(link),\n );\n}\n\n/**\n * Extracts script elements from the component or document, depending on whether\n * the component is a <remote-component> custom element.\n */\nexport function extractScripts(\n doc: Document,\n component: Element,\n isRemoteComponent: boolean,\n): HTMLScriptElement[] {\n return Array.from(\n (isRemoteComponent ? component : doc).querySelectorAll<HTMLScriptElement>(\n `script[src],script[${DATA_SRC}]`,\n ),\n );\n}\n\n/**\n * Parses a remote component HTML document and extracts all data needed for\n * loading and hydrating the component. This is the main orchestrator that\n * calls the individual extraction functions.\n */\nexport function parseRemoteComponentDocument(\n doc: Document,\n name: string,\n url: URL,\n): ParsedRemoteComponent {\n validateSingleComponent(doc, name, url.href);\n\n const component = findComponentElement(doc, name);\n const nextData = parseNextData(doc);\n\n const { name: resolvedName, isRemoteComponent } = resolveComponentName(\n component,\n nextData,\n name,\n );\n\n const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);\n const metadata = buildMetadata(\n {\n name: resolvedName,\n bundle:\n component?.getAttribute(DATA_BUNDLE) ||\n nextData?.props.__REMOTE_COMPONENT__?.bundle,\n route: component?.getAttribute(DATA_ROUTE) ?? nextData?.page,\n runtime:\n component?.getAttribute(DATA_RUNTIME) ??\n nextData?.props.__REMOTE_COMPONENT__?.runtime ??\n RUNTIME_SCRIPT,\n id: component?.getAttribute('id'),\n type: component?.getAttribute(DATA_TYPE),\n },\n url,\n );\n const remoteShared = extractRemoteShared(doc, resolvedName, nextData);\n\n validateComponentFound(\n component,\n rsc,\n nextData,\n isRemoteComponent,\n url.href,\n resolvedName,\n );\n\n const links = extractLinks(doc, component);\n const scripts = extractScripts(doc, component, isRemoteComponent);\n\n return {\n component,\n name: resolvedName,\n isRemoteComponent,\n metadata,\n nextData,\n rsc,\n remoteShared,\n links,\n scripts,\n };\n}\n","import {\n DEFAULT_BUNDLE_NAME,\n DEFAULT_COMPONENT_NAME,\n DEFAULT_ROUTE,\n} from '#internal/runtime/constants';\n\n/**\n * Metadata embedded in the HTML response by a remote application.\n *\n * Extracted from a `<script type=\"application/json\" data-remote-component>`\n * element during both SSR parsing ({@link fetchRemoteComponent}) and\n * client-side parsing ({@link parseRemoteComponentDocument}).\n */\nexport interface RemoteComponentMetadata {\n name: string;\n bundle: string;\n route: string;\n runtime: 'webpack' | 'turbopack' | 'script';\n id: string;\n type: 'nextjs' | 'remote-component' | 'unknown';\n}\n\n/**\n * Raw attribute values before defaults are applied. Accepts nullable strings\n * so callers can pass DOM attributes or parsed JSON directly.\n */\nexport interface RawMetadataAttrs {\n name?: string | null;\n bundle?: string | null;\n route?: string | null;\n runtime?: string | null;\n id?: string | null;\n type?: string | null;\n}\n\nconst VALID_RUNTIMES: Set<string> = new Set(['webpack', 'turbopack', 'script']);\nconst VALID_TYPES: Set<string> = new Set([\n 'nextjs',\n 'remote-component',\n 'unknown',\n]);\n\nfunction isRuntime(value: string): value is RemoteComponentMetadata['runtime'] {\n return VALID_RUNTIMES.has(value);\n}\n\nfunction isComponentType(\n value: string,\n): value is RemoteComponentMetadata['type'] {\n return VALID_TYPES.has(value);\n}\n\nfunction toRuntime(\n value: string | null | undefined,\n): RemoteComponentMetadata['runtime'] {\n return value && isRuntime(value) ? value : 'webpack';\n}\n\nfunction toComponentType(\n value: string | null | undefined,\n): RemoteComponentMetadata['type'] {\n return value && isComponentType(value) ? value : 'unknown';\n}\n\n/**\n * Applies default values to raw metadata attributes and returns a fully\n * resolved {@link RemoteComponentMetadata}. When no bundle is provided, falls\n * back to the `NEXT_PUBLIC_MFE_CURRENT_APPLICATION` env var (the host's\n * application name), then `DEFAULT_BUNDLE_NAME`.\n */\nexport function buildMetadata(\n attrs: RawMetadataAttrs,\n url: URL,\n): RemoteComponentMetadata {\n const id = attrs.id || DEFAULT_COMPONENT_NAME;\n const bundle =\n attrs.bundle ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n DEFAULT_BUNDLE_NAME;\n return {\n name: attrs.name || id.replace(/_ssr$/, ''),\n bundle,\n route: attrs.route || url.pathname || DEFAULT_ROUTE,\n runtime: toRuntime(attrs.runtime),\n id,\n type: toComponentType(attrs.type),\n };\n}\n","import * as React from 'react';\nimport * as JSXDevRuntime from 'react/jsx-dev-runtime';\nimport * as JSXRuntime from 'react/jsx-runtime';\nimport * as ReactDOM from 'react-dom';\nimport * as ReactDOMClient from 'react-dom/client';\nimport { applySharedModules } from '#internal/config/webpack/apply-shared-modules';\nimport { nextClientPagesLoader } from '#internal/config/webpack/next-client-pages-loader';\nimport type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport type { ConsumeLoaderPayload } from '#internal/host/shared/server-handoff';\nimport {\n buildCoreShared,\n buildWebpackResolve,\n} from '#internal/host/shared/shared-module-resolver';\nimport { createRSCStream } from '#internal/runtime/rsc';\nimport { importRSCClientBrowser } from '#internal/runtime/rsc-imports';\nimport { setupRemoteScope } from '#internal/runtime/turbopack/remote-scope-setup';\nimport { initializeSharedModules } from '#internal/runtime/turbopack/shared-modules';\nimport type { GlobalScope, LoaderResult } from '#internal/runtime/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\nimport { logDebug, logWarn } from '#internal/utils/logger';\nimport { loadScripts } from './script-loader';\n\n/**\n * Props accepted by {@link loadRemoteComponent}.\n *\n * Extends {@link ConsumeLoaderPayload} (the SSR-resolved fields needed for\n * hydration) with loader-specific fields (`url`, `shared`, `container`, etc.).\n * `remoteShared` is narrowed from optional to required (defaults to `{}` at\n * the call site).\n */\nexport interface ConsumeLoaderProps extends ConsumeLoaderPayload {\n url: URL;\n shared:\n | Promise<Record<string, (bundle?: string) => Promise<unknown>>>\n | Record<string, (bundle?: string) => Promise<unknown>>;\n remoteShared: Record<string, string>;\n container?: HTMLHeadElement | ShadowRoot | null;\n rscName?: string;\n resolveClientUrl?: InternalResolveClientUrl;\n}\n\n/**\n * Main loader function that orchestrates the component loading process\n */\nexport async function loadRemoteComponent({\n url,\n name,\n rscName,\n bundle,\n route = '/',\n runtime = 'webpack',\n data,\n nextData,\n scripts = [],\n shared = Promise.resolve({}),\n remoteShared = {},\n container,\n resolveClientUrl,\n}: ConsumeLoaderProps): Promise<LoaderResult> {\n try {\n // Load scripts if using webpack runtime\n if (runtime === 'webpack') {\n const self = globalThis as GlobalScope;\n // disable webpack entrypoint execution for the remote\n if (!self.__DISABLE_WEBPACK_EXEC__) {\n self.__DISABLE_WEBPACK_EXEC__ = {};\n }\n // disable webpack entrypoint execution for the current remote bundle\n self.__DISABLE_WEBPACK_EXEC__[bundle] = true;\n await loadScripts(scripts, resolveClientUrl);\n }\n\n const hostShared = await shared;\n logDebug(\n 'ComponentLoader',\n `loadRemoteComponent: bundle=\"${bundle}\", name=\"${name}\"`,\n );\n logDebug(\n 'ComponentLoader',\n `Host shared modules available: ${Object.keys(hostShared)}`,\n );\n logDebug(\n 'ComponentLoader',\n `Remote shared modules requested: ${JSON.stringify(remoteShared)}`,\n );\n\n // Setup remote scope and load turbopack chunks\n const scope = await setupRemoteScope(\n runtime,\n scripts,\n url,\n bundle,\n resolveClientUrl,\n );\n\n // Initialize turbopack shared modules (React, etc.) now that chunks are loaded\n if (runtime === 'turbopack') {\n await initializeSharedModules(\n scope,\n buildCoreShared(hostShared),\n remoteShared,\n );\n }\n\n // Setup shared modules\n if (bundle) {\n const resolve = await buildWebpackResolve(\n hostShared,\n remoteShared,\n bundle,\n {\n '/react/index.js': React,\n '/react/jsx-dev-runtime.js': JSXDevRuntime,\n '/react/jsx-runtime.js': JSXRuntime,\n '/react-dom/index.js': ReactDOM,\n '/react-dom/client.js': ReactDOMClient,\n },\n 'ComponentLoader',\n );\n applySharedModules(bundle, resolve);\n } else {\n logWarn(\n 'ComponentLoader',\n 'No bundle specified, skipping shared module setup',\n );\n }\n\n // Load component based on data type\n if (data.length > 0) {\n return await loadRSCComponent(rscName ?? name, data);\n } else if (nextData) {\n return loadNextPagesComponent(bundle, route, nextData, name, container);\n }\n\n return loadRSCComponent(rscName ?? name, [`0:[null]\\n`]); // Fallback to empty RSC payload\n } catch (error) {\n return {\n component: null,\n error: new RemoteComponentsError(\n `Failed to load remote component \"${name}\".`,\n {\n cause: error instanceof Error ? error : new Error(String(error)),\n },\n ),\n };\n }\n}\n\n/**\n * Loads RSC (React Server Components) based component\n */\nasync function loadRSCComponent(\n rscName: string,\n data: string[],\n): Promise<LoaderResult> {\n const { createFromReadableStream } = await importRSCClientBrowser();\n if (typeof createFromReadableStream !== 'function') {\n throw new RemoteComponentsError(\n 'Failed to import \"react-server-dom-webpack\". Is Next.js installed correctly?',\n );\n }\n\n const stream = createRSCStream(rscName, data);\n const component = createFromReadableStream(stream);\n\n return { component };\n}\n\n/**\n * Loads Next.js Pages Router based component\n */\nfunction loadNextPagesComponent(\n bundle: string,\n route: string,\n nextData: NonNullable<ConsumeLoaderPayload['nextData']>,\n name: string,\n container?: HTMLHeadElement | ShadowRoot | null,\n): LoaderResult {\n const { Component, App } = nextClientPagesLoader(bundle, route, container);\n\n if (!Component) {\n throw new RemoteComponentsError(\n `Remote Component \"${name}\" is trying to load the component for route \"${route}\" but it is not available.`,\n );\n }\n\n // error tolerance when app component is not found\n const component = App\n ? React.createElement(App, { Component, ...nextData.props })\n : React.createElement(Component, nextData.props);\n\n return { component };\n}\n","import { ReadableStream } from 'web-streams-polyfill';\n\n/**\n * Fixes RSC payload arrays to be compatible with React JSX development runtime.\n * React elements in the wire format are 4-element arrays (`['$', type, key, props]`);\n * the dev runtime expects 7 elements with debug info in positions 4-6.\n */\nexport function fixPayload(payload: unknown): void {\n if (Array.isArray(payload)) {\n if (payload[0] === '$') {\n // React element — fix props recursively, then pad to 7 elements\n fixPayload(payload[3]);\n if (payload.length === 4) {\n payload.push(null, null, 1);\n }\n } else {\n for (const item of payload) {\n fixPayload(item);\n }\n }\n } else if (typeof payload === 'object' && payload !== null) {\n for (const key in payload) {\n fixPayload((payload as Record<string, unknown>)[key]);\n }\n }\n}\n\n/**\n * Parses raw RSC script chunks (the `self[\"name\"].push(\"...\")` format produced\n * by `<RemoteComponentData>`) into a flat array of flight-data strings.\n *\n * This is a pure function — it reads from `data` only, never from `globalThis`.\n */\nexport function buildRSCChunks(rscName: string, data: string[]): string[] {\n const chunks: string[] = [];\n\n for (const chunk of data) {\n for (const line of chunk.split('\\n')) {\n const match = /\\.push\\(\"(?<rsc>.*)\"\\);$/.exec(line);\n if (match?.groups?.rsc) {\n chunks.push(JSON.parse(`\"${match.groups.rsc}\"`) as string);\n }\n }\n }\n\n return chunks;\n}\n\n/**\n * Processes RSC flight data and creates a ReadableStream.\n *\n * First checks `data` for inline script chunks (parsed via {@link buildRSCChunks}),\n * merging them onto `globalThis[rscName]`. Then consumes the global array\n * (or falls back to an empty RSC payload) and pipes fixed chunks into the stream.\n */\nexport function createRSCStream(\n rscName: string,\n data: string[],\n): ReadableStream<Uint8Array> {\n return new ReadableStream({\n type: 'bytes',\n start(controller) {\n const encoder = new TextEncoder();\n const self = globalThis as typeof globalThis &\n Record<string, string[] | null>;\n\n // Parse inline script chunks and merge onto the global array\n if (data.length > 0) {\n const parsed = buildRSCChunks(rscName, data);\n if (parsed.length > 0) {\n self[rscName] = self[rscName] ?? [];\n self[rscName].push(...parsed);\n }\n }\n\n // Consume the global RSC flight data, falling back to an empty payload\n const allChunks = (self[rscName] ?? [`0:[null]\\n`]).join('');\n self[rscName] = null;\n\n // Process each line in the RSC flight data\n allChunks.split('\\n').forEach((chunk) => {\n if (chunk.length > 0) {\n const { before, id, prefix, payload } =\n /^(?<before>[^:]*?)?(?<id>[0-9a-zA-Z]+):(?<prefix>[A-Z])?(?<payload>\\[.*\\])/.exec(\n chunk,\n )?.groups ?? {};\n\n if (payload) {\n const jsonPayload = JSON.parse(payload) as unknown[];\n fixPayload(jsonPayload);\n const reconstruct = `${before ?? ''}${id}:${prefix ?? ''}${JSON.stringify(jsonPayload)}`;\n controller.enqueue(encoder.encode(`${reconstruct}\\n`));\n } else {\n controller.enqueue(encoder.encode(`${chunk}\\n`));\n }\n } else {\n controller.enqueue(encoder.encode(`${chunk}\\n`));\n }\n });\n controller.close();\n },\n });\n}\n","/**\n * The lifecycle stages a host progresses through during a load cycle.\n *\n * ```\n * ┌─────────────────────────┐\n * │ (new load) │\n * ▼ │\n * idle ──▶ loading ──▶ loaded ─────────┘\n * ▲ │ │\n * │ ▼ │ (new load)\n * │ error ─────────┘\n * │\n * └── loading (abandoned / aborted)\n * ```\n *\n * - `idle` — No load has started, or a previous load was abandoned.\n * - `loading` — A fetch or hydration is in progress.\n * - `loaded` — The remote component rendered successfully.\n * - `error` — The load failed (the error itself is surfaced separately).\n *\n * Any non-idle stage transitions directly to `loading` when a new load starts.\n */\nexport type HostStage = 'idle' | 'loading' | 'loaded' | 'error';\n\n/**\n * Mutable state shared by every host implementation (HTML, React, Next.js\n * App Router).\n *\n * Each host stores a single `HostState` instance rather than scattering\n * individual properties/refs. This keeps the \"what changed since the last\n * load?\" tracking consistent across frameworks and makes it easy to test\n * state transitions in isolation.\n */\nexport interface HostState {\n /** Current lifecycle stage. */\n stage: HostStage;\n\n /** Source from the most-recent load. `undefined` before the first load. */\n prevSrc: string | URL | undefined;\n\n /** Resolved URL from the most-recent load. `undefined` before the first load. */\n prevUrl: URL | undefined;\n\n /** Component name from the most-recent load. `undefined` before the first load. */\n prevName: string | undefined;\n\n /** Whether the most-recent load was a remote component (vs. a plain page). */\n prevIsRemoteComponent: boolean;\n\n /**\n * `AbortController` for the in-flight load. Abort it to cancel a\n * superseded fetch. `undefined` when no load is active.\n */\n abortController: AbortController | undefined;\n}\n\n/** Creates a fresh `HostState` with all fields at their initial values. */\nexport function createHostState(): HostState {\n return {\n stage: 'idle',\n prevSrc: undefined,\n prevUrl: undefined,\n prevName: undefined,\n prevIsRemoteComponent: false,\n abortController: undefined,\n };\n}\n","/**\n * Extracts a component name from the URL hash of `src`, falling back to\n * `defaultName` when no hash is present.\n *\n * Both the HTML and React hosts use this to derive the component name\n * from patterns like `/components/header#my-component`.\n *\n * Parses the hash directly from the string rather than constructing a\n * full `URL`, so no SSR fallback base is needed.\n */\nexport function resolveNameFromSrc(\n src: string | URL | undefined,\n defaultName: string,\n): string {\n if (!src) {\n return defaultName;\n }\n\n const hash = typeof src === 'string' ? src : src.hash;\n const hashIndex = hash.indexOf('#');\n if (hashIndex < 0) {\n return defaultName;\n }\n\n const name = hash.slice(hashIndex + 1);\n return name || defaultName;\n}\n","/**\n * Intercepts client-side URL resolution for remote component resources.\n * Called before each asset (script, stylesheet, chunk, module, image) is fetched.\n *\n * Return a new URL string to redirect the fetch (e.g., through a proxy),\n * or undefined to use the original URL.\n *\n * @param remoteSrc - The `src` of the remote component being loaded\n * @param url - The asset URL about to be fetched\n *\n * @example\n * // Proxy all assets from the remote's origin through the host\n * const resolveClientUrl = (remoteSrc, url) => {\n * const remoteOrigin = new URL(remoteSrc).origin;\n * const parsed = new URL(url);\n * if (parsed.origin !== location.origin && parsed.origin === remoteOrigin) {\n * return `/rc-fetch-protected-remote?url=${encodeURIComponent(url)}`;\n * }\n * };\n */\nexport type ResolveClientUrl = (\n remoteSrc: string,\n url: string,\n) => string | undefined;\n\n/**\n * Internal bound resolver — `ResolveClientUrl` with `remoteSrc` already applied.\n * Used by internal loaders that don't need to know the remote src.\n */\nexport type InternalResolveClientUrl = (url: string) => string | undefined;\n\n/**\n * Binds a `ResolveClientUrl` to a specific `remoteSrc`, producing an\n * `InternalResolveClientUrl` that only needs the asset URL.\n *\n * Only invokes the callback for URLs whose origin matches the remote\n * component's origin. Third-party scripts (e.g. `vercel.live` toolbar)\n * are left untouched. To proxy additional domains in the future, a\n * field or flag can be added to the host configuration.\n */\nexport function withRemoteSrc(\n resolveClientUrl: ResolveClientUrl,\n remoteSrc: string,\n): InternalResolveClientUrl {\n const remoteOrigin = parseOrigin(remoteSrc);\n return (url) => {\n const urlOrigin = parseOrigin(url);\n if (remoteOrigin && urlOrigin && urlOrigin !== remoteOrigin) {\n return undefined;\n }\n return resolveClientUrl(remoteSrc, url);\n };\n}\n\nfunction parseOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n","import {\n type InternalResolveClientUrl,\n type ResolveClientUrl,\n withRemoteSrc,\n} from './resolve-client-url';\n\nexport function bindResolveClientUrl(\n prop: ResolveClientUrl | undefined,\n remoteSrc: string,\n): InternalResolveClientUrl | undefined {\n return prop ? withRemoteSrc(prop, remoteSrc) : undefined;\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\ninterface AttachStylesOptions {\n /** The parsed document containing link and style elements */\n doc: Document;\n /** The component element to check if links are already contained */\n component: Element;\n /** Links from the document head */\n links: NodeListOf<HTMLLinkElement>;\n /** AbortSignal to cancel loading */\n signal: AbortSignal | undefined;\n /** Base URL for resolving relative hrefs */\n baseUrl: string | undefined;\n /** Source URL to set as data attribute */\n remoteComponentSrc: string | null;\n /** Root element to append styles to (ShadowRoot or Element) */\n root: ShadowRoot | Element | null;\n /** Callback to transform asset URLs before loading */\n resolveClientUrl?: InternalResolveClientUrl;\n}\n\n/**\n * Attaches link and style elements from a remote component document to the shadow root.\n * Handles abort signals efficiently with a single shared listener for all links.\n *\n * @throws DOMException with name 'AbortError' if signal is aborted\n * @throws RemoteComponentsError if a stylesheet fails to load\n */\nexport async function attachStyles({\n doc,\n component,\n links,\n signal,\n baseUrl,\n remoteComponentSrc,\n root,\n resolveClientUrl,\n}: AttachStylesOptions): Promise<void> {\n // Track appended links for cleanup on abort\n const appendedLinks: HTMLLinkElement[] = [];\n\n // Single shared abort promise - avoids N listeners for N links\n let abortReject: ((error: DOMException) => void) | null = null;\n const abortPromise = new Promise<never>((_, reject) => {\n abortReject = reject;\n });\n const abortHandler = () => {\n // Clean up all pending links on abort\n for (const link of appendedLinks) {\n link.onload = null;\n link.onerror = null;\n link.remove();\n }\n abortReject?.(new DOMException('Aborted', 'AbortError'));\n };\n signal?.addEventListener('abort', abortHandler, { once: true });\n\n try {\n // Attach each link element to the shadow DOM to load the styles\n await Promise.all(\n Array.from(links)\n .filter((link) => !component.contains(link))\n .map((link) => {\n const newLink = document.createElement('link');\n appendedLinks.push(newLink);\n\n const loadPromise = new Promise<void>((resolve, reject) => {\n if (link.rel === 'stylesheet') {\n // TODO: needs to be cancellable with a singular listener for the abort signal https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\n newLink.onload = () => resolve();\n newLink.onerror = () =>\n reject(\n new RemoteComponentsError(\n `Failed to load <link href=\"${link.href}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n } else {\n resolve();\n }\n });\n\n for (const attr of link.attributes) {\n if (attr.name === 'href') {\n const absoluteHref = new URL(\n attr.value,\n baseUrl ?? location.origin,\n ).href;\n newLink.setAttribute(\n attr.name,\n resolveClientUrl?.(absoluteHref) ?? absoluteHref,\n );\n } else {\n newLink.setAttribute(attr.name, attr.value);\n }\n }\n\n if (remoteComponentSrc) {\n newLink.setAttribute(\n 'data-remote-component-src',\n remoteComponentSrc,\n );\n }\n\n // TODO: needs to be cancellable with a singular listener for the abort signal https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\n root?.appendChild(newLink);\n\n // Race each link load against the shared abort promise\n return Promise.race([loadPromise, abortPromise]);\n }),\n );\n } finally {\n signal?.removeEventListener('abort', abortHandler);\n }\n\n // Attach inline styles from the document head\n const styles = doc.querySelectorAll<HTMLStyleElement>('style');\n for (const style of styles) {\n if (style.parentElement?.tagName.toLowerCase() === 'head') {\n const newStyle = document.createElement('style');\n newStyle.textContent = style.textContent;\n\n if (remoteComponentSrc) {\n newStyle.setAttribute('data-remote-component-src', remoteComponentSrc);\n }\n\n root?.appendChild(newStyle);\n }\n }\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\nexport type Runtime = 'webpack' | 'turbopack' | 'script' | 'unknown';\n\nexport async function getRuntime(\n type: Runtime,\n url: URL,\n bundle: string,\n shared?: Record<string, () => Promise<unknown>>,\n remoteShared?: Record<string, string>,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n // minimally mock process.env for browser environments\n if (typeof globalThis.process === 'undefined') {\n globalThis.process = {\n env: {},\n } as NodeJS.Process;\n }\n\n if (type === 'webpack') {\n const { webpackRuntime } = await import(`./webpack`);\n return webpackRuntime(bundle, shared, remoteShared, resolveClientUrl);\n } else if (type === 'turbopack') {\n const { turbopackRuntime } = await import(`./turbopack`);\n return turbopackRuntime(\n url,\n bundle,\n shared,\n remoteShared,\n resolveClientUrl,\n );\n } else if (type === 'script') {\n const { scriptRuntime } = await import(`./script`);\n return scriptRuntime(resolveClientUrl);\n }\n throw new RemoteComponentsError(\n `Remote Components runtime \"${type}\" is not supported. Supported runtimes are \"webpack\", \"turbopack\", and \"script\".`,\n );\n}\n"],"mappings":";;;;;;;;;;;AAAA,IAAa,oCAKA;AALb;AAAA;AAAA;AAAO,IAAM,qCAAqC;AAK3C,IAAM,gBACX;AAAA;AAAA;;;ACGK,SAAS,aAAa,KAAsB;AACjD,MAAI;AACF,WACE,IAAI,IAAI,KAAK,SAAS,IAAI,EAAE,aAC5B;AAAA,EAEJ,QAAE;AACA,WAAO;AAAA,EACT;AACF;AAlBA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIO,SAAS,aAAa,OAAuC;AAClE,MAAI,iBAAiB,gBAAgB,MAAM,SAAS,cAAc;AAChE,WAAO;AAAA,EACT;AAGA,MACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACV,MAAM,SAAS,gBACf,aAAa,SACb,OAAQ,MAA+B,YAAY,UACnD;AAEA,UAAM,IAAI;AACV,WAAO,OAAO,EAAE,SAAS,YAAY,EAAE,aAAa,SAAS;AAAA,EAC/D;AAEA,SAAO;AACT;AAxBA;AAAA;AAAA;AAAA;AAAA;;;ACgBO,SAAS,8BAA8B,KAAyB;AACrE,SAAO,IAAI;AAAA,IACT,wCAAwC;AAAA,E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YAAY,KAAK,IAAI;AAAA,QACjC;AAAA,MACF,WAAW,aAAa,EAAE,SAAS,IAAI,IAAI,GAAG;AAE5C,cAAM,QAAQ;AAAA,UACZ,MAAM,KAAK,aAAa,EAAE,SAAS,IAAI,IAAI,KAAK,CAAC,CAAC,EAAE;AAAA,YAClD,OAAO,UAAU;AACf,kBAAI;AACF,sBAAM,MAAM,KAAK,IAAI;AAAA,cACvB,SAAS,GAAP;AACA;AAAA,kBACE;AAAA,kBACA,yDAAyD,IAAI;AAAA,kBAC7D;AAAA,gBACF;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAEA,aAAK,QAAQ,KAAK,KAAK,OAAO,EAAE;AAAA,MAClC,OAAO;AACL,aAAK,QAAQ,KAAK,KAAK,OAAO,EAAE;AAAA,MAClC;AAEA,UAAI,cAAc,GAAG;AACnB,aAAK,UAAU,QAAQ;AAAA,MACzB;AAAA,IACF;AAAA,EACF;AAGA,iBAAe,OAAO,oBAAoB,eAAe;AAC3D;AAEO,SAAS,sBACd,UAAkD,CAAC,GACnD;AACA,QAAM,KAAK,aAAa;AACxB,SAAO,QAAQ,OAAO,EAAE,QAAQ,CAAC,CAAC,KAAK,KAAK,MAAM;AAChD,OAAG,kBAAkB,GAAG,IAAI;AAAA,EAC9B,CAAC;AACH;","names":["location","init_constants","init_constants","init_patterns","init_constants","init_patterns","init_patterns","scope","init_constants","init_constants","init_constants","init_constants","webpackRuntime","turbopackRuntime","scriptRuntime","jsx","nextClientPagesLoader"]}
|