remote-components 0.3.2 → 0.3.4

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.
Files changed (213) hide show
  1. package/dist/config/nextjs.cjs +122 -62
  2. package/dist/config/nextjs.cjs.map +1 -1
  3. package/dist/config/nextjs.js +116 -56
  4. package/dist/config/nextjs.js.map +1 -1
  5. package/dist/config/webpack.cjs +5 -1
  6. package/dist/config/webpack.cjs.map +1 -1
  7. package/dist/config/webpack.js +5 -1
  8. package/dist/config/webpack.js.map +1 -1
  9. package/dist/host/defaults/app.cjs +2 -5
  10. package/dist/host/defaults/app.cjs.map +1 -1
  11. package/dist/host/defaults/app.d.ts +1 -3
  12. package/dist/host/defaults/app.js +1 -4
  13. package/dist/host/defaults/app.js.map +1 -1
  14. package/dist/host/defaults/pages.cjs +2 -5
  15. package/dist/host/defaults/pages.cjs.map +1 -1
  16. package/dist/host/defaults/pages.d.ts +1 -3
  17. package/dist/host/defaults/pages.js +1 -4
  18. package/dist/host/defaults/pages.js.map +1 -1
  19. package/dist/host/defaults/shared.cjs +32 -0
  20. package/dist/host/defaults/shared.cjs.map +1 -0
  21. package/dist/host/defaults/shared.d.ts +3 -0
  22. package/dist/host/defaults/shared.js +8 -0
  23. package/dist/host/defaults/shared.js.map +1 -0
  24. package/dist/host/html.cjs +533 -351
  25. package/dist/host/html.cjs.map +1 -1
  26. package/dist/host/html.js +533 -351
  27. package/dist/host/html.js.map +1 -1
  28. package/dist/host/nextjs/app/client-only.cjs +494 -285
  29. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  30. package/dist/host/nextjs/app/client-only.js +468 -259
  31. package/dist/host/nextjs/app/client-only.js.map +1 -1
  32. package/dist/host/react.cjs +412 -241
  33. package/dist/host/react.cjs.map +1 -1
  34. package/dist/host/react.js +412 -241
  35. package/dist/host/react.js.map +1 -1
  36. package/dist/internal/config/webpack/apply-shared-modules.cjs +6 -4
  37. package/dist/internal/config/webpack/apply-shared-modules.cjs.map +1 -1
  38. package/dist/internal/config/webpack/apply-shared-modules.js +6 -4
  39. package/dist/internal/config/webpack/apply-shared-modules.js.map +1 -1
  40. package/dist/internal/config/webpack/next-client-pages-loader.cjs +6 -7
  41. package/dist/internal/config/webpack/next-client-pages-loader.cjs.map +1 -1
  42. package/dist/internal/config/webpack/next-client-pages-loader.js +6 -7
  43. package/dist/internal/config/webpack/next-client-pages-loader.js.map +1 -1
  44. package/dist/internal/host/nextjs/app-client.cjs +6 -22
  45. package/dist/internal/host/nextjs/app-client.cjs.map +1 -1
  46. package/dist/internal/host/nextjs/app-client.js +5 -11
  47. package/dist/internal/host/nextjs/app-client.js.map +1 -1
  48. package/dist/internal/host/nextjs/dom-flight.cjs +19 -39
  49. package/dist/internal/host/nextjs/dom-flight.cjs.map +1 -1
  50. package/dist/internal/host/nextjs/dom-flight.js +31 -39
  51. package/dist/internal/host/nextjs/dom-flight.js.map +1 -1
  52. package/dist/internal/host/nextjs/image-shared.cjs +39 -3
  53. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  54. package/dist/internal/host/nextjs/image-shared.d.ts +5 -10
  55. package/dist/internal/host/nextjs/image-shared.js +29 -3
  56. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  57. package/dist/internal/host/nextjs/shared-import.cjs +46 -0
  58. package/dist/internal/host/nextjs/shared-import.cjs.map +1 -0
  59. package/dist/internal/host/nextjs/shared-import.d.ts +3 -0
  60. package/dist/internal/host/nextjs/shared-import.js +12 -0
  61. package/dist/internal/host/nextjs/shared-import.js.map +1 -0
  62. package/dist/internal/host/server/fetch-remote-component.cjs +2 -1
  63. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  64. package/dist/internal/host/server/fetch-remote-component.js +2 -1
  65. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  66. package/dist/internal/host/shared/polyfill.cjs +8 -7
  67. package/dist/internal/host/shared/polyfill.cjs.map +1 -1
  68. package/dist/internal/host/shared/polyfill.js +8 -7
  69. package/dist/internal/host/shared/polyfill.js.map +1 -1
  70. package/dist/internal/host/shared/shared-module-resolver.cjs +117 -0
  71. package/dist/internal/host/shared/shared-module-resolver.cjs.map +1 -0
  72. package/dist/internal/host/shared/shared-module-resolver.d.ts +64 -0
  73. package/dist/internal/host/shared/shared-module-resolver.js +78 -0
  74. package/dist/internal/host/shared/shared-module-resolver.js.map +1 -0
  75. package/dist/internal/remote/nextjs/next-internals.cjs +53 -0
  76. package/dist/internal/remote/nextjs/next-internals.cjs.map +1 -0
  77. package/dist/internal/remote/nextjs/next-internals.d.ts +42 -0
  78. package/dist/internal/remote/nextjs/next-internals.js +26 -0
  79. package/dist/internal/remote/nextjs/next-internals.js.map +1 -0
  80. package/dist/internal/runtime/html/apply-origin.cjs +11 -32
  81. package/dist/internal/runtime/html/apply-origin.cjs.map +1 -1
  82. package/dist/internal/runtime/html/apply-origin.js +11 -32
  83. package/dist/internal/runtime/html/apply-origin.js.map +1 -1
  84. package/dist/internal/runtime/html/html-spec.cjs +78 -0
  85. package/dist/internal/runtime/html/html-spec.cjs.map +1 -0
  86. package/dist/internal/runtime/html/html-spec.d.ts +23 -0
  87. package/dist/internal/runtime/html/html-spec.js +41 -0
  88. package/dist/internal/runtime/html/html-spec.js.map +1 -0
  89. package/dist/internal/runtime/html/parse-remote-html.cjs +15 -12
  90. package/dist/internal/runtime/html/parse-remote-html.cjs.map +1 -1
  91. package/dist/internal/runtime/html/parse-remote-html.js +29 -12
  92. package/dist/internal/runtime/html/parse-remote-html.js.map +1 -1
  93. package/dist/internal/runtime/html/rewrite-srcset.cjs +38 -0
  94. package/dist/internal/runtime/html/rewrite-srcset.cjs.map +1 -0
  95. package/dist/internal/runtime/html/rewrite-srcset.d.ts +12 -0
  96. package/dist/internal/runtime/html/rewrite-srcset.js +14 -0
  97. package/dist/internal/runtime/html/rewrite-srcset.js.map +1 -0
  98. package/dist/internal/runtime/loaders/component-loader.cjs +25 -44
  99. package/dist/internal/runtime/loaders/component-loader.cjs.map +1 -1
  100. package/dist/internal/runtime/loaders/component-loader.d.ts +3 -1
  101. package/dist/internal/runtime/loaders/component-loader.js +28 -44
  102. package/dist/internal/runtime/loaders/component-loader.js.map +1 -1
  103. package/dist/internal/runtime/loaders/script-loader.cjs +7 -0
  104. package/dist/internal/runtime/loaders/script-loader.cjs.map +1 -1
  105. package/dist/internal/runtime/loaders/script-loader.js +7 -0
  106. package/dist/internal/runtime/loaders/script-loader.js.map +1 -1
  107. package/dist/internal/runtime/loaders/static-loader.cjs +15 -21
  108. package/dist/internal/runtime/loaders/static-loader.cjs.map +1 -1
  109. package/dist/internal/runtime/loaders/static-loader.d.ts +3 -1
  110. package/dist/internal/runtime/loaders/static-loader.js +15 -21
  111. package/dist/internal/runtime/loaders/static-loader.js.map +1 -1
  112. package/dist/internal/runtime/namespace.cjs +82 -0
  113. package/dist/internal/runtime/namespace.cjs.map +1 -0
  114. package/dist/internal/runtime/namespace.d.ts +5 -0
  115. package/dist/internal/runtime/namespace.js +58 -0
  116. package/dist/internal/runtime/namespace.js.map +1 -0
  117. package/dist/internal/runtime/rsc-imports.cjs +86 -0
  118. package/dist/internal/runtime/rsc-imports.cjs.map +1 -0
  119. package/dist/internal/runtime/rsc-imports.d.ts +39 -0
  120. package/dist/internal/runtime/rsc-imports.js +50 -0
  121. package/dist/internal/runtime/rsc-imports.js.map +1 -0
  122. package/dist/internal/{host/shared/resolved-data.cjs → runtime/rsc-runtime.cjs} +3 -3
  123. package/dist/internal/runtime/rsc-runtime.cjs.map +1 -0
  124. package/dist/internal/runtime/rsc-runtime.d.ts +37 -0
  125. package/dist/internal/runtime/rsc-runtime.js +1 -0
  126. package/dist/internal/runtime/rsc.cjs +23 -12
  127. package/dist/internal/runtime/rsc.cjs.map +1 -1
  128. package/dist/internal/runtime/rsc.d.ts +19 -2
  129. package/dist/internal/runtime/rsc.js +20 -11
  130. package/dist/internal/runtime/rsc.js.map +1 -1
  131. package/dist/internal/runtime/turbopack/chunk-loader.cjs +53 -35
  132. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  133. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +1 -1
  134. package/dist/internal/runtime/turbopack/chunk-loader.js +53 -35
  135. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  136. package/dist/internal/runtime/turbopack/module.cjs +19 -17
  137. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  138. package/dist/internal/runtime/turbopack/module.d.ts +23 -1
  139. package/dist/internal/runtime/turbopack/module.js +19 -18
  140. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  141. package/dist/internal/runtime/turbopack/patterns.cjs +26 -10
  142. package/dist/internal/runtime/turbopack/patterns.cjs.map +1 -1
  143. package/dist/internal/runtime/turbopack/patterns.d.ts +44 -49
  144. package/dist/internal/runtime/turbopack/patterns.js +23 -7
  145. package/dist/internal/runtime/turbopack/patterns.js.map +1 -1
  146. package/dist/internal/runtime/turbopack/{webpack-runtime.cjs → remote-scope-setup.cjs} +35 -32
  147. package/dist/internal/runtime/turbopack/remote-scope-setup.cjs.map +1 -0
  148. package/dist/internal/runtime/turbopack/remote-scope-setup.d.ts +25 -0
  149. package/dist/internal/runtime/turbopack/{webpack-runtime.js → remote-scope-setup.js} +36 -19
  150. package/dist/internal/runtime/turbopack/remote-scope-setup.js.map +1 -0
  151. package/dist/internal/runtime/turbopack/remote-scope.cjs +4 -6
  152. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -1
  153. package/dist/internal/runtime/turbopack/remote-scope.d.ts +20 -1
  154. package/dist/internal/runtime/turbopack/remote-scope.js +4 -6
  155. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -1
  156. package/dist/internal/runtime/turbopack/shared-modules.cjs +23 -15
  157. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  158. package/dist/internal/runtime/turbopack/shared-modules.d.ts +13 -1
  159. package/dist/internal/runtime/turbopack/shared-modules.js +25 -18
  160. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  161. package/dist/internal/runtime/types.cjs.map +1 -1
  162. package/dist/internal/runtime/types.d.ts +5 -41
  163. package/dist/internal/utils/logger.cjs +1 -1
  164. package/dist/internal/utils/logger.cjs.map +1 -1
  165. package/dist/internal/utils/logger.d.ts +2 -2
  166. package/dist/internal/utils/logger.js +1 -1
  167. package/dist/internal/utils/logger.js.map +1 -1
  168. package/dist/internal/utils/project-id-env.cjs +31 -0
  169. package/dist/internal/utils/project-id-env.cjs.map +1 -0
  170. package/dist/internal/utils/project-id-env.d.ts +7 -0
  171. package/dist/internal/utils/project-id-env.js +7 -0
  172. package/dist/internal/utils/project-id-env.js.map +1 -0
  173. package/dist/internal/utils/project-id.cjs +46 -0
  174. package/dist/internal/utils/project-id.cjs.map +1 -0
  175. package/dist/internal/utils/project-id.d.ts +8 -0
  176. package/dist/internal/utils/project-id.js +22 -0
  177. package/dist/internal/utils/project-id.js.map +1 -0
  178. package/dist/remote/defaults/app.cjs +2 -5
  179. package/dist/remote/defaults/app.cjs.map +1 -1
  180. package/dist/remote/defaults/app.d.ts +1 -3
  181. package/dist/remote/defaults/app.js +1 -4
  182. package/dist/remote/defaults/app.js.map +1 -1
  183. package/dist/remote/defaults/pages.cjs +2 -5
  184. package/dist/remote/defaults/pages.cjs.map +1 -1
  185. package/dist/remote/defaults/pages.d.ts +1 -3
  186. package/dist/remote/defaults/pages.js +1 -4
  187. package/dist/remote/defaults/pages.js.map +1 -1
  188. package/dist/remote/defaults/shared.cjs +32 -0
  189. package/dist/remote/defaults/shared.cjs.map +1 -0
  190. package/dist/remote/defaults/shared.d.ts +3 -0
  191. package/dist/remote/defaults/shared.js +8 -0
  192. package/dist/remote/defaults/shared.js.map +1 -0
  193. package/dist/remote/html.cjs +78 -22
  194. package/dist/remote/html.cjs.map +1 -1
  195. package/dist/remote/html.js +78 -22
  196. package/dist/remote/html.js.map +1 -1
  197. package/dist/remote/nextjs/app.cjs +16 -56
  198. package/dist/remote/nextjs/app.cjs.map +1 -1
  199. package/dist/remote/nextjs/app.js +26 -46
  200. package/dist/remote/nextjs/app.js.map +1 -1
  201. package/dist/remote/nextjs/pages.cjs +2 -1
  202. package/dist/remote/nextjs/pages.cjs.map +1 -1
  203. package/dist/remote/nextjs/pages.js +2 -1
  204. package/dist/remote/nextjs/pages.js.map +1 -1
  205. package/dist/types-59251814.d.ts +94 -0
  206. package/package.json +1 -1
  207. package/dist/internal/host/shared/resolved-data.cjs.map +0 -1
  208. package/dist/internal/host/shared/resolved-data.d.ts +0 -48
  209. package/dist/internal/host/shared/resolved-data.js +0 -1
  210. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +0 -1
  211. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +0 -23
  212. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +0 -1
  213. /package/dist/internal/{host/shared/resolved-data.js.map → runtime/rsc-runtime.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/utils/constants.ts","../../../../src/host/defaults/app.ts","../../../../src/host/nextjs/app-client-only.tsx","../../../../src/utils/index.ts","../../../../src/runtime/constants.ts","../../../../src/runtime/patterns.ts","../../../../src/utils/logger.ts","../../../../src/runtime/url/protected-rc-fallback.ts","../../../../src/utils/abort.ts","../../../../src/utils/error.ts","../../../../src/runtime/turbopack/remote-scope.ts","../../../../src/host/shared/remote-image-loader.ts","../../../../src/runtime/url/resolve-client-url.ts","../../../../src/runtime/url/default-resolve-client-url.ts","../../../../src/host/nextjs/image-shared.ts","../../../../src/host/react/index.tsx","../../../../src/host/server/fetch-headers.ts","../../../../src/host/server/fetch-with-hooks.ts","../../../../src/host/server/get-client-or-server-url.ts","../../../../src/host/shared/polyfill.tsx","../../../../src/host/shared/state.ts","../../../../src/host/utils/resolve-name-from-src.ts","../../../../src/runtime/html/apply-origin.ts","../../../../src/runtime/metadata.ts","../../../../src/runtime/html/parse-remote-html.ts","../../../../src/runtime/html/set-attributes-from-props.ts","../../../../src/runtime/loaders/component-loader.ts","../../../../src/config/webpack/apply-shared-modules.ts","../../../../src/config/webpack/next-client-pages-loader.ts","../../../../src/runtime/rsc.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/webpack-runtime.ts","../../../../src/runtime/loaders/script-loader.ts","../../../../src/runtime/loaders/static-loader.ts","../../../../src/host/react/hooks/use-resolve-client-url.ts","../../../../src/host/react/hooks/use-shadow-root.ts","../../../../src/host/react/utils/extract-remote-html.ts","../../../../src/host/nextjs/app-compat.tsx"],"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 { MISSING_SHARED_MODULES_MESSAGE } from '#internal/utils/constants';\n\nexport const shared: Record<string, () => Promise<unknown>> = {\n __remote_components_missing_shared__: () =>\n Promise.reject(new Error(MISSING_SHARED_MODULES_MESSAGE)),\n};\n","'use client';\n\nimport type React from 'react';\nimport { useMemo } from 'react';\nimport { createImageLoaderSharedEntries } from '#internal/host/nextjs/image-shared';\nimport { RemoteComponentsContext } from '#internal/host/react/context';\nimport type { ConsumeClientOnlyConfig } from '#internal/host/shared/config';\nimport type { ResolveClientUrl } from '#internal/runtime/url/resolve-client-url';\nimport {\n type ConsumeRemoteComponentProps,\n ConsumeRemoteComponent as ConsumeRemoteComponentReact,\n} from '#remote-components/host/react';\nimport { routerImpl } from './app-compat';\n\nasync function tryImportShared() {\n try {\n const { shared } = await import('#remote-components/host/defaults/app');\n return shared;\n } catch {\n return {};\n }\n}\n\nconst sharedModules = async (\n userShared?: ConsumeRemoteComponentProps['shared'],\n resolveClientUrl?: ResolveClientUrl,\n) => {\n const [resolvedShared, resolvedUserShared] = await Promise.all([\n tryImportShared(),\n userShared ?? Promise.resolve({}),\n ]);\n return {\n ...resolvedShared,\n 'next/router': routerImpl,\n ...createImageLoaderSharedEntries({ unbound: resolveClientUrl }),\n ...resolvedUserShared,\n };\n};\n\n/**\n * Provider for Next.js App Router hosts. Provides real Next.js implementations\n * of `next/image`, `next/navigation`, `next/link`, etc. to all nested\n * `<ConsumeRemoteComponent>` instances.\n *\n * Works in both Server and Client Components — set it up once in your layout\n * and use `<ConsumeRemoteComponent>` from `remote-components/react` everywhere:\n *\n * ```tsx\n * import { RemoteComponentsClientProvider } from 'remote-components/host/nextjs/app/client-only';\n *\n * <RemoteComponentsClientProvider resolveClientUrl={proxyClientRequestsThroughHost}>\n * {children}\n * </RemoteComponentsClientProvider>\n * ```\n */\nexport function RemoteComponentsClientProvider({\n shared,\n resolveClientUrl,\n children,\n ...props\n}: ConsumeClientOnlyConfig & { children: React.ReactNode }) {\n const mergedShared = useMemo(\n () => sharedModules(shared, resolveClientUrl),\n [shared, resolveClientUrl],\n );\n return (\n <RemoteComponentsContext\n value={{ shared: mergedShared, resolveClientUrl, ...props }}\n >\n {children}\n </RemoteComponentsContext>\n );\n}\n\n/**\n * `ConsumeRemoteComponent` for Next.js App Router hosts. Provides real Next.js\n * implementations of `next/image`, `next/navigation`, `next/link`, etc.\n *\n * The provider approach is recommended because it works in both Server and Client\n * Components — set up `RemoteComponentsClientProvider` from this module once in\n * your layout, and use `<ConsumeRemoteComponent>` from `remote-components/react`\n * everywhere. Import this component only when adding a provider is not practical.\n */\nexport function ConsumeRemoteComponent(props: ConsumeRemoteComponentProps) {\n if (typeof props.src !== 'string' && !(props.src instanceof URL)) {\n return props.children ?? null;\n }\n\n return (\n <ConsumeRemoteComponentReact\n {...props}\n shared={sharedModules(props.shared, props.resolveClientUrl)}\n />\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","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 { CORS_DOCS_URL } from '#internal/utils/constants';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\ntype 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\nconst PREFIX = 'remote-components';\nconst DEBUG =\n typeof window !== 'undefined' && localStorage.getItem('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","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 type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { getBundleKey, type Runtime } from '#internal/runtime/constants';\nimport { REMOTE_COMPONENT_REGEX } from '#internal/runtime/patterns';\nimport type { GlobalScope } from '#internal/runtime/types';\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 `setupWebpackRuntime` 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\nfunction getRegistry(): Map<string, RemoteScope> {\n const self = globalThis as GlobalScope;\n if (!self.__remote_component_scopes__) {\n self.__remote_component_scopes__ = new Map<string, unknown>();\n }\n return self.__remote_component_scopes__ as unknown as Map<\n string,\n RemoteScope\n >;\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 };\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","/**\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 { createRemoteImageLoader } from '#internal/host/shared/remote-image-loader';\nimport { getScope } from '#internal/runtime/turbopack/remote-scope';\nimport { bindResolveClientUrl } from '#internal/runtime/url/default-resolve-client-url';\nimport type {\n InternalResolveClientUrl,\n ResolveClientUrl,\n} from '#internal/runtime/url/resolve-client-url';\n\ntype SharedImageModule = (bundle: string) => Promise<unknown>;\n\nfunction resolveForBundle(\n unbound: ResolveClientUrl | undefined,\n bundle: string,\n): InternalResolveClientUrl | undefined {\n if (!unbound) return undefined;\n const remoteSrc = getScope(bundle)?.url.href ?? '';\n return bindResolveClientUrl(unbound, remoteSrc);\n}\n\n/**\n * Creates shared module entries for `next/dist/shared/lib/image-loader` (and\n * its ESM alias). These ensure that any code path in the remote's bundle that\n * directly imports the image loader — rather than going through the shared\n * `next/image` entry — still routes image optimization requests to the remote\n * and through the host's proxy when deployment protection is active.\n *\n * Pass `bound` when the resolver already has `remoteSrc` applied (App Router —\n * `useResolveClientUrl` returns the bound form). Pass `unbound` when only the\n * raw 2-arg `ResolveClientUrl` is available (Pages Router, client-only\n * provider) — binding is deferred until the bundle URL is known at resolution\n * time.\n */\nexport function createImageLoaderSharedEntries({\n bound,\n unbound,\n}: {\n bound?: InternalResolveClientUrl;\n unbound?: ResolveClientUrl;\n} = {}): Record<string, SharedImageModule> {\n const entry: SharedImageModule = (bundle: string) => {\n const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);\n return Promise.resolve({\n default: createRemoteImageLoader(bundle, resolveClientUrl),\n __esModule: true,\n });\n };\n return {\n 'next/dist/shared/lib/image-loader': entry,\n 'next/dist/esm/shared/lib/image-loader': entry,\n };\n}\n","import {\n startTransition,\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { useRemoteComponentsContext } from '#internal/host/react/context';\nimport { fetchWithHooks } from '#internal/host/server/fetch-with-hooks';\nimport { getClientOrServerUrl } from '#internal/host/server/get-client-or-server-url';\nimport type { ConsumeRemoteComponentConfig } from '#internal/host/shared/config';\nimport { sharedPolyfills } from '#internal/host/shared/polyfill';\nimport type { ConsumeServerData } from '#internal/host/shared/server-handoff';\nimport { createHostState } from '#internal/host/shared/state';\nimport { resolveNameFromSrc } from '#internal/host/utils/resolve-name-from-src';\nimport {\n DEFAULT_COMPONENT_NAME,\n DEFAULT_ROUTE,\n RUNTIME_SCRIPT,\n RUNTIME_WEBPACK,\n} from '#internal/runtime/constants';\nimport { applyOriginToNodes } from '#internal/runtime/html/apply-origin';\nimport { parseRemoteComponentDocument } from '#internal/runtime/html/parse-remote-html';\nimport { setAttributesFromProps } from '#internal/runtime/html/set-attributes-from-props';\nimport { loadRemoteComponent } from '#internal/runtime/loaders/component-loader';\nimport { loadStaticRemoteComponent } from '#internal/runtime/loaders/static-loader';\nimport {\n collapseDoubleSlashes,\n REMOTE_COMPONENT_REGEX,\n} from '#internal/runtime/patterns';\nimport { attrToProp, escapeString } from '#internal/utils';\nimport { isAbortError } from '#internal/utils/abort';\nimport {\n errorFromFailedFetch,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport type {\n MountOrUnmountFunction,\n MountUnmountFunctions,\n} from '#remote-components/runtime/types';\nimport { useResolveClientUrl } from './hooks/use-resolve-client-url';\nimport { useShadowRoot } from './hooks/use-shadow-root';\nimport {\n DUMMY_FALLBACK,\n getRemoteComponentHtml,\n} from './utils/extract-remote-html';\n\n/**\n * Props for the React remote component host.\n *\n * Extends {@link ConsumeRemoteComponentConfig} with `children` for loading fallback content.\n */\nexport interface ConsumeRemoteComponentProps\n extends ConsumeRemoteComponentConfig {\n /** Loading fallback content displayed while the remote component is being fetched. */\n children?: React.ReactNode;\n}\n\n/**\n * ConsumeRemoteComponent is a React component that fetches and renders a remote component.\n * It supports SSR and can isolate the remote component in a shadow DOM.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n *\n * @example\n *\n * Use the `<ConsumeRemoteComponent>` in your React application to consume a remote component from a remote application:\n *\n * ```tsx\n * import { ConsumeRemoteComponent } from 'remote-components/host/react';\n *\n * export default function App() {\n * return (\n * <>\n * <h1>Welcome to My App</h1>\n * <p>This page consumes a remote component from another application.</p>\n * <ConsumeRemoteComponent src=\"/nextjs-app-remote/components/header\" />\n * </>\n * );\n * }\n * ```\n *\n * To share modules, you can provide a shared module map with references to the shared modules:\n *\n * ```tsx\n * <ConsumeRemoteComponent\n * src=\"/nextjs-app-remote/components/header\"\n * shared={{\n * '@/components/provider': () => import('@/components/host-provider')\n * }}\n * />\n * ```\n */\nexport function ConsumeRemoteComponent({\n src,\n isolate,\n mode = 'open',\n reset,\n credentials: credentialsProp,\n name: nameProp = DEFAULT_COMPONENT_NAME,\n shared: sharedProp,\n children,\n onBeforeLoad,\n onLoad,\n onError,\n onChange,\n onRequest,\n onResponse,\n resolveClientUrl: resolveClientUrlProp,\n}: ConsumeRemoteComponentProps) {\n const instanceId = useId();\n\n const { credentials: contextCredentials, shared: contextShared } =\n useRemoteComponentsContext();\n const credentials = credentialsProp ?? contextCredentials ?? 'same-origin';\n const shared = sharedProp ?? contextShared ?? {};\n\n const name = useMemo(\n () => resolveNameFromSrc(src, nameProp),\n [src, nameProp],\n );\n\n const [data, setData] = useState<Omit<ConsumeServerData, 'children'> | null>(\n null,\n );\n\n const url = useMemo(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);\n\n const resolveClientUrl = useResolveClientUrl(resolveClientUrlProp, url.href);\n\n // for relative src paths, use just the pathname as the unique id.\n // for static urls, use the full url as the unique id as the path may not be unique.\n // this id needs to be the same for server and client side rendering.\n // note that if this needs to be more unique, can pass through the bundle as an id prop and ammend it to this id.\n const id =\n url.origin ===\n (typeof location !== 'undefined' ? location.origin : DUMMY_FALLBACK)\n ? url.pathname\n : url.href;\n\n //instanceId prevents multiple components with the same src from sharing a shadow root\n const keySuffix = `${escapeString(id)}_${escapeString(\n data?.name ?? name,\n )}_${escapeString(instanceId)}`;\n\n const [remoteComponent, setRemoteComponent] = useState<\n React.ReactNode | Error\n >(null);\n\n const { shadowRoot, shadowRootContainerRef } = useShadowRoot({\n isolate,\n mode,\n keySuffix,\n });\n\n const htmlRef = useRef<string | null>(\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n )?.shadowRoot?.innerHTML ??\n document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ??\n document.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`)\n ?.innerHTML ??\n document.querySelector('div[data-bundle][data-route]')?.innerHTML)\n : null,\n );\n const endTemplateRef = useRef<HTMLTemplateElement | null>(null);\n // collect initial content that needs to be removed after remote component renders\n const childrenRef = useRef(\n typeof document !== 'undefined'\n ? (() => {\n let el = document.querySelector(`template[id=\"${name}_start\"]`);\n const elements = [];\n while (el && el.id !== `${name}_end`) {\n if (\n el.id !== `${name}_start` &&\n !el.getAttribute('data-remote-component')\n ) {\n elements.push(el);\n }\n el = el.nextElementSibling as HTMLTemplateElement | null;\n }\n return elements;\n })()\n : [],\n );\n const hostStateRef = useRef(createHostState());\n const componentHydrationHtml = useRef<string | null>(null);\n const prevRemoteComponentContainerRef = useRef<HTMLDivElement | null>(null);\n const unmountRef = useRef<Set<MountOrUnmountFunction> | null>(null);\n\n // Clean up the shadow root cache on unmount to prevent memory leaks\n useLayoutEffect(() => {\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n return () => {\n delete (\n globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n >\n )[shadowRootKey];\n };\n }, [keySuffix]);\n\n useLayoutEffect(() => {\n // Clear initial content after remote component renders\n if (childrenRef.current.length > 0 && remoteComponent) {\n childrenRef.current.forEach((el) => {\n el.remove();\n });\n childrenRef.current = [];\n }\n }, [remoteComponent]);\n\n useLayoutEffect(() => {\n if (shadowRoot && remoteComponent) {\n const resetStyles = shadowRoot.querySelectorAll(\n 'style[data-remote-components-reset]',\n );\n // ensure we only have one reset style in the shadow root\n if (resetStyles.length > 1) {\n resetStyles.forEach((style, index) => {\n if (\n index > 0 &&\n style.getAttribute('data-remote-components-reset') !== 'react'\n ) {\n style.remove();\n }\n });\n }\n\n // clear the html ref after hydration\n htmlRef.current = null;\n\n // clear all nodes except links and styles until the start marker\n // the marker gets only rendered on hydration\n let el: ChildNode | null = shadowRoot.childNodes[0] ?? null;\n while (el && (!('id' in el) || el.id !== `${name}_start`)) {\n const nextEl = el.nextSibling;\n if (el.nodeName !== 'LINK' && el.nodeName !== 'STYLE') {\n el.parentNode?.removeChild(el);\n }\n el = nextEl;\n }\n }\n }, [shadowRoot, remoteComponent, name]);\n\n useEffect(() => {\n if (src && src !== hostStateRef.current.prevSrc) {\n const previousSrc = hostStateRef.current.prevSrc;\n const previousName = hostStateRef.current.prevName;\n hostStateRef.current.prevSrc = src;\n\n if (previousSrc !== null) {\n htmlRef.current = null;\n }\n\n // Abort any in-progress load so the latest src always wins.\n hostStateRef.current.abortController?.abort();\n hostStateRef.current.abortController = new AbortController();\n const { signal } = hostStateRef.current.abortController;\n\n onBeforeLoad?.(src);\n hostStateRef.current.stage = 'loading';\n\n startTransition(async () => {\n try {\n let html = getRemoteComponentHtml(\n htmlRef.current ??\n (endTemplateRef.current?.previousElementSibling?.tagName === 'div'\n ? endTemplateRef.current.previousElementSibling.innerHTML\n : ''),\n );\n\n if (!html && src) {\n // fetch the remote component\n const fetchInit = {\n credentials,\n } as RequestInit;\n\n const resolvedUrl = new URL(\n resolveClientUrl?.(url.href) ?? url.href,\n location.href,\n );\n const res = await fetchWithHooks(resolvedUrl, fetchInit, {\n onRequest,\n onResponse,\n abortController: hostStateRef.current.abortController,\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\n const remoteHtml = await res.text();\n if (signal.aborted) return;\n htmlRef.current = remoteHtml;\n html = getRemoteComponentHtml(remoteHtml);\n }\n\n if (signal.aborted) return;\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 {\n component,\n name: remoteName,\n isRemoteComponent,\n metadata,\n nextData,\n rsc,\n remoteShared,\n links: linkElements,\n scripts: scriptElements,\n } = parseRemoteComponentDocument(doc, name, url);\n\n if (hostStateRef.current.prevIsRemoteComponent) {\n if (shadowRoot) {\n shadowRoot.innerHTML = '';\n }\n const self = globalThis as typeof globalThis &\n MountUnmountFunctions;\n const prevUrl = hostStateRef.current.prevUrl;\n if (\n prevUrl &&\n self.__remote_script_entrypoint_unmount__?.[prevUrl.href]\n ) {\n const unmountPromises = Promise.all(\n Array.from(unmountRef.current ?? []).map(async (unmount) =>\n unmount(\n shadowRoot ?? prevRemoteComponentContainerRef.current,\n ),\n ),\n );\n unmountRef.current = null;\n await unmountPromises;\n }\n }\n hostStateRef.current.prevIsRemoteComponent = isRemoteComponent;\n hostStateRef.current.prevUrl = url;\n hostStateRef.current.prevName = remoteName;\n\n // update all relative URLs to absolute URLs based on the remote component URL\n applyOriginToNodes(doc, url, resolveClientUrl);\n\n const links = linkElements.map((link) => ({\n href: new URL(link.getAttribute('href') ?? link.href, url).href,\n ...link\n .getAttributeNames()\n .reduce<Record<string, string>>((acc, key) => {\n if (key !== 'href') {\n acc[attrToProp[key] ?? key] = link.getAttribute(key) ?? '';\n }\n return acc;\n }, {}),\n }));\n\n const scripts = scriptElements;\n\n // handle inline scripts in the remote component\n const inlineScripts = (\n isRemoteComponent ? component : doc\n ).querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])\",\n );\n\n if (!isRemoteComponent) {\n // Next.js Script support\n const self = globalThis as typeof globalThis & {\n __next_s: [string, Record<string, string>][];\n };\n const prevNextScripts = self.__next_s;\n const nextScripts = [] as [string, Record<string, string>][];\n // eslint-disable-next-line camelcase\n self.__next_s = nextScripts;\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 await Promise.all(\n Array.from(inlineScripts)\n .filter(\n (script) =>\n !(\n script.id.endsWith('_shared') &&\n script.getAttribute('type') === 'application/json' &&\n typeof script.getAttribute(\n 'data-remote-components-shared',\n ) === 'string'\n ),\n )\n .map((script) => {\n return new Promise((resolve) => {\n // only handle inline scripts with content, but not Next.js RSC scripts\n if (\n script.textContent &&\n !script.textContent.includes('self.__next_f=') &&\n !script.textContent.includes('self.__next_f.push')\n ) {\n // if script is inline javascript, then execute using blob\n if (\n !script.getAttribute('type') ||\n script.getAttribute('type') === 'text/javascript' ||\n script.getAttribute('type') === 'application/javascript'\n ) {\n const newScript = document.createElement('script');\n\n // scripts loaded from external sources needs this workaround\n const blob = new Blob([script.textContent], {\n type: 'application/javascript',\n });\n const blobUrl = URL.createObjectURL(blob);\n\n newScript.onload = () => {\n resolve(undefined);\n // script executed and safe to remove\n URL.revokeObjectURL(blobUrl);\n newScript.remove();\n };\n // on error we still want to resolve to not block the remote component loading\n newScript.onerror = () => {\n URL.revokeObjectURL(blobUrl);\n newScript.remove();\n resolve(undefined);\n };\n\n newScript.src = blobUrl;\n // TODO: needs to be cancellable https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\n document.body.appendChild(newScript);\n } else {\n resolve(undefined);\n document.body.appendChild(script);\n }\n } else {\n resolve(undefined);\n }\n });\n }),\n );\n // process the remote component Next.js Script container\n nextScripts.forEach(([scriptSrc, props]) => {\n const script = document.createElement('script');\n // when we have a script src, apply it (inline scripts have `0` as src)\n if (scriptSrc) {\n script.src = scriptSrc;\n }\n // apply Script props\n if (typeof props.children === 'string') {\n script.textContent = props.children;\n }\n setAttributesFromProps(script, props);\n document.head.appendChild(script);\n });\n // restore previous Next.js Script container\n // eslint-disable-next-line camelcase\n self.__next_s = prevNextScripts;\n }\n\n const rscName = rsc\n ? `__remote_component_rsc_${escapeString(id)}_${escapeString(\n remoteName,\n )}`\n : undefined;\n if (rsc) {\n rsc.textContent =\n rsc.textContent?.replace(\n new RegExp(`self\\\\[\"${remoteName}\"\\\\]`, 'g'),\n `self[\"${rscName}\"]`,\n ) ?? '';\n document.body.appendChild(rsc);\n }\n\n const newData = {\n ...metadata,\n links,\n remoteShared,\n src: typeof src === 'string' ? src : src.href,\n serverUrl: url.href,\n data: rsc\n ? (rsc.textContent || '').split('\\n').filter(Boolean)\n : [],\n };\n\n componentHydrationHtml.current = `${Array.from(\n doc.querySelectorAll('link,style'),\n )\n .map((link) => link.outerHTML)\n .join('')}${\n reset\n ? `<style data-remote-components-reset=\"\">:host { all: initial; }</style>`\n : ''\n }${component.innerHTML}`;\n\n const userShared = await shared;\n\n if ('__remote_components_missing_shared__' in userShared) {\n userShared.__remote_components_missing_shared__().catch((e) => {\n throw e;\n });\n } else if ('__remote_components_missing_shared__' in remoteShared) {\n throw new RemoteComponentsError(\n remoteShared.__remote_components_missing_shared__,\n );\n }\n\n if (isRemoteComponent) {\n // Only call onChange when not on first load (matching HTML implementation)\n if (previousSrc !== undefined) {\n onChange?.({\n previousSrc,\n nextSrc: src,\n previousName,\n nextName: remoteName,\n });\n }\n setData(newData);\n if (shadowRoot) {\n const shadowRootHtml = reset\n ? `<style data-remote-components-reset=\"\">:host { all: initial; }</style>${component.innerHTML}`\n : component.innerHTML;\n shadowRoot.innerHTML = shadowRootHtml;\n htmlRef.current = null;\n setRemoteComponent(null);\n const { mount, unmount } = await loadStaticRemoteComponent(\n Array.from(shadowRoot.querySelectorAll('script')),\n url,\n resolveClientUrl,\n );\n unmountRef.current = unmount;\n await Promise.all(\n Array.from(mount).map((mountFn) => mountFn(shadowRoot)),\n );\n onLoad?.(src);\n } else if (isolate === false) {\n setRemoteComponent(\n // TODO: remove wrapper div by converting HTML to RSC or React tree\n <div\n dangerouslySetInnerHTML={{ __html: component.innerHTML }}\n ref={prevRemoteComponentContainerRef}\n />,\n );\n htmlRef.current = null;\n const { mount, unmount } = await loadStaticRemoteComponent(\n Array.from(component.querySelectorAll('script')),\n url,\n resolveClientUrl,\n );\n unmountRef.current = unmount;\n await Promise.all(\n Array.from(mount).map((mountFn) =>\n mountFn(prevRemoteComponentContainerRef.current),\n ),\n );\n onLoad?.(src);\n }\n hostStateRef.current.stage = 'loaded';\n } else {\n const result = await loadRemoteComponent({\n url,\n name: remoteName,\n rscName,\n bundle: metadata.bundle,\n route: metadata.route,\n runtime: metadata.runtime,\n data: newData.data,\n nextData,\n scripts: Array.from(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(\n scriptSrc,\n )?.groups ?? {\n prefix: undefined,\n id: scriptSrc,\n };\n return {\n src: new URL(\n collapseDoubleSlashes(`${prefix ?? ''}${path}`),\n url,\n ).href,\n };\n }),\n shared: {\n ...sharedPolyfills(userShared, resolveClientUrl),\n ...userShared,\n },\n remoteShared,\n container: shadowRoot,\n resolveClientUrl,\n });\n if (rsc) {\n rsc.remove();\n }\n\n setData(newData);\n // Only call onChange when not on first load (matching HTML implementation)\n if (previousSrc !== undefined) {\n onChange?.({\n previousSrc,\n nextSrc: src,\n previousName,\n nextName: remoteName,\n });\n }\n if (result.error) {\n hostStateRef.current.stage = 'error';\n setRemoteComponent(result.error);\n onError?.(result.error);\n } else {\n hostStateRef.current.stage = 'loaded';\n setRemoteComponent(result.component);\n onLoad?.(src);\n }\n }\n } catch (error) {\n // AbortError is expected when loading is cancelled - exit cleanly\n if (isAbortError(error)) {\n hostStateRef.current.stage = 'idle';\n return;\n }\n hostStateRef.current.stage = 'error';\n setRemoteComponent(error as Error);\n onError?.(error);\n }\n });\n }\n }, [\n url,\n src,\n isolate,\n credentials,\n name,\n shared,\n shadowRoot,\n reset,\n id,\n onBeforeLoad,\n onLoad,\n onError,\n onChange,\n onRequest,\n onResponse,\n resolveClientUrl,\n ]);\n\n if (remoteComponent instanceof Error) {\n throw remoteComponent;\n }\n\n const metadataJson = (\n <script data-remote-component type=\"application/json\">\n {JSON.stringify({\n name: data?.name || name,\n bundle: data?.bundle || 'default',\n route: data?.route || DEFAULT_ROUTE,\n runtime: hostStateRef.current.prevIsRemoteComponent\n ? RUNTIME_SCRIPT\n : data?.runtime || RUNTIME_WEBPACK,\n })}\n </script>\n );\n const resetStyle = reset ? (\n <style data-remote-components-reset=\"react\">{`:host { all: initial; }`}</style>\n ) : null;\n const linksToRender: React.ReactNode[] | null =\n data?.links?.map((link) => (\n <link\n {...link}\n href={new URL(link.href as string, url).href}\n key={JSON.stringify(link)}\n />\n )) || null;\n const componentToRender = (\n <>\n {resetStyle}\n {linksToRender}\n {remoteComponent ?? children}\n </>\n );\n\n if (componentHydrationHtml.current && shadowRoot && !shadowRoot.innerHTML) {\n shadowRoot.innerHTML = componentHydrationHtml.current;\n componentHydrationHtml.current = null;\n\n if (hostStateRef.current.prevIsRemoteComponent) {\n // ensure we load static resources when hydrating a remote component in shadow DOM\n loadStaticRemoteComponent(\n Array.from(shadowRoot.querySelectorAll('script')),\n url,\n resolveClientUrl,\n )\n .then(({ mount }) => {\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(shadowRoot)),\n );\n })\n .then(() => {\n if (src) {\n onLoad?.(src);\n }\n })\n .catch((e) => {\n const error = new RemoteComponentsError(\n `Error mounting remote component from \"${url.href}\"`,\n {\n cause: e,\n },\n );\n setRemoteComponent(error);\n onError?.(error);\n });\n }\n }\n\n if (isolate !== false) {\n const shadowRemoteComponentHtml =\n shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ??\n shadowRoot?.querySelector('div[data-bundle][data-route]');\n if (shadowRemoteComponentHtml) {\n shadowRemoteComponentHtml.remove();\n }\n\n return (\n <>\n {metadataJson}\n <div\n data-remote-component-id={`shadowroot_${keySuffix}`}\n id={`shadowroot_${data?.name ?? name}`}\n ref={shadowRootContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode={mode}>\n {typeof document === 'undefined' ? (\n <div\n dangerouslySetInnerHTML={{\n __html: `<img\n alt=\"\" decoding=\"async\" style=\"display:none\"\n src=\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==\"\n onload=\"(function(el){\n const root = el.getRootNode();\n globalThis.__remote_components_shadowroot_${keySuffix} = root;\n el.parentElement.remove();\n })(this)\"\n />`,\n }}\n />\n ) : null}\n {resetStyle}\n {linksToRender}\n {children}\n </template>\n ) : null}\n {shadowRoot && remoteComponent\n ? createPortal(\n <>\n <template id={`${name}_start`} />\n {resetStyle}\n {linksToRender}\n {remoteComponent}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>,\n shadowRoot,\n )\n : null}\n </div>\n </>\n );\n }\n htmlRef.current = null;\n\n // render start/end markers for the remote component\n return (\n <>\n <template id={`${name}_start`} />\n {metadataJson}\n {componentToRender}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>\n );\n}\n\nexport type {\n HookOptions,\n OnRequestHook,\n OnResponseHook,\n} from '#internal/host/shared/fetch-interceptors';\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","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","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 { LinkProps } from 'next/link';\nimport { createRemoteImageLoader } from '#internal/host/shared/remote-image-loader';\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 self = globalThis as typeof globalThis & {\n __remote_component_host_shared_modules__?: Record<\n string,\n () => Promise<unknown>\n >;\n };\n const polyfill = {\n 'next/dist/client/components/navigation':\n self.__remote_component_host_shared_modules__?.['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 self.__remote_component_host_shared_modules__?.['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 self.__remote_component_host_shared_modules__?.['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 self.__remote_component_host_shared_modules__?.[\n 'next/dist/shared/lib/image-loader'\n ] ??\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 self.__remote_component_host_shared_modules__?.['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 self.__remote_component_host_shared_modules__?.['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","/**\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","import type { InternalResolveClientUrl } from '#internal/host/server/types';\n\nconst tagNames = [\n 'img',\n 'source',\n 'video',\n 'audio',\n 'track',\n 'iframe',\n 'embed',\n 'script',\n 'link',\n];\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 tagNames\n .map(\n (type) =>\n `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`,\n )\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 srcSet = node\n .getAttribute('srcset')\n ?.split(',')\n .map((entry) => {\n const [urlPart, descriptor] = entry.trim().split(/\\s+/);\n if (!urlPart) return entry;\n\n const absoluteUrl = new URL(urlPart, url).href;\n const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;\n return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;\n })\n .join(', ');\n if (srcSet) {\n node.setAttribute('srcset', srcSet);\n }\n }\n if (node.hasAttribute('imagesrcset')) {\n const srcSet = node\n .getAttribute('imagesrcset')\n ?.split(',')\n .map((entry) => {\n const [urlPart, descriptor] = entry.trim().split(/\\s+/);\n if (!urlPart) return entry;\n\n const absoluteUrl = new URL(urlPart, url).href;\n const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;\n return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;\n })\n .join(', ');\n if (srcSet) {\n node.setAttribute('imagesrcset', srcSet);\n }\n }\n });\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 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';\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(`div[data-bundle][data-route][id^=\"${name}\"]`)) ||\n (doc.querySelectorAll('remote-component:not([src])').length > 1 &&\n !doc.querySelector(`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') ??\n doc.querySelector(`remote-component[name=\"${name}\"]:not([src])`) ??\n doc.querySelector('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__') ??\n doc.querySelector('#__REMOTE_NEXT_DATA__')\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() === 'remote-component';\n\n const name =\n component?.getAttribute('id')?.replace(/_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}_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}_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","// extracted from Next.js source at https://github.com/vercel/next.js/blob/canary/packages/next/src/client/set-attributes-from-props.ts\n\nconst DOMAttributeNames: Record<string, string> = {\n acceptCharset: 'accept-charset',\n className: 'class',\n htmlFor: 'for',\n httpEquiv: 'http-equiv',\n noModule: 'noModule',\n};\n\nconst ignoreProps = [\n 'onLoad',\n 'onReady',\n 'dangerouslySetInnerHTML',\n 'children',\n 'onError',\n 'strategy',\n 'stylesheets',\n];\n\nfunction isBooleanScriptAttribute(\n attr: string,\n): attr is 'async' | 'defer' | 'noModule' {\n return ['async', 'defer', 'noModule'].includes(attr);\n}\n\nexport function setAttributesFromProps(el: HTMLElement, props: object) {\n for (const [p, value] of Object.entries(props)) {\n if (!Object.hasOwn(props, p)) continue;\n if (ignoreProps.includes(p)) continue;\n\n // we don't render undefined props to the DOM\n if (value === undefined) {\n continue;\n }\n\n const attr = DOMAttributeNames[p] || p.toLowerCase();\n\n if (el.tagName === 'SCRIPT' && isBooleanScriptAttribute(attr)) {\n // Correctly assign boolean script attributes\n // https://github.com/vercel/next.js/pull/20748\n (el as HTMLScriptElement)[attr] = Boolean(value);\n } else {\n el.setAttribute(attr, String(value));\n }\n\n // Remove falsy non-zero boolean attributes so they are correctly interpreted\n // (e.g. if we set them to false, this coerces to the string \"false\", which the browser interprets as true)\n if (\n value === false ||\n (el.tagName === 'SCRIPT' &&\n isBooleanScriptAttribute(attr) &&\n (!value || value === 'false'))\n ) {\n // Call setAttribute before, as we need to set and unset the attribute to override force async:\n // https://html.spec.whatwg.org/multipage/scripting.html#script-force-async\n el.setAttribute(attr, '');\n el.removeAttribute(attr);\n }\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 { createRSCStream } from '#internal/runtime/rsc';\nimport { setupWebpackRuntime } from '#internal/runtime/turbopack/webpack-runtime';\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 webpack runtime environment\n await setupWebpackRuntime(\n runtime,\n scripts,\n url,\n bundle,\n hostShared,\n remoteShared,\n resolveClientUrl,\n );\n\n // Setup shared modules\n if (bundle) {\n const resolve = {\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 ...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 'ComponentLoader',\n `Remote requests \"${value}\" but host doesn't provide it`,\n );\n }\n return acc;\n },\n {},\n ),\n } as Record<string, unknown>;\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 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\nasync function importCreateFromReadableStream(): Promise<unknown> {\n try {\n const { createFromReadableStream } = await import(\n 'next/dist/compiled/react-server-dom-webpack/client.browser'\n );\n return createFromReadableStream;\n } catch {\n const {\n default: { createFromReadableStream },\n } = await import('react-server-dom-webpack/client.browser');\n return createFromReadableStream;\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 // try to import react-server-dom-webpack from Next.js with a fallback\n const createFromReadableStream = await importCreateFromReadableStream();\n // remote components with RSC requires react-server-dom-webpack\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","// 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 { 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 // if we have the bundle\n if (self.__remote_webpack_require__?.[bundle]) {\n const modulePaths = Object.keys(\n self.__remote_webpack_module_map__?.[bundle] ??\n self.__remote_webpack_require__[bundle].m ??\n {},\n );\n logDebug(\n 'SharedModules',\n `Available module paths in __remote_webpack_require__[${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 const webpackBundle = self.__remote_webpack_require__[bundle];\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 { 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 // Next.js Pages Router CSS cache\n __remote_next_css__?: Record<string, ChildNode[]>;\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 if (!self.__remote_next_css__) {\n // eslint-disable-next-line camelcase\n self.__remote_next_css__ = {};\n }\n\n if (!self.__remote_next_css__[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 self.__remote_next_css__[bundle] = elements;\n }\n\n // if the styleContainer is provided, we need to move the styles to it\n if (styleContainer) {\n const elements = self.__remote_next_css__[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 = self.__remote_next_css__[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 { ReadableStream } from 'web-streams-polyfill';\n\n/**\n * Fixes RSC payload to make it compatible with React JSX development runtime\n */\nfunction fixPayload(payload: unknown): void {\n if (Array.isArray(payload)) {\n // if the current node is a React element, we need to fix the payload\n if (payload[0] === '$') {\n // fix the props (children or other React elements)\n fixPayload(payload[3]);\n if (payload.length === 4) {\n // add placeholder for the missing debug info\n payload.push(null, null, 1);\n }\n } else {\n // we are in an array, continue with visiting each item\n for (const item of payload) {\n fixPayload(item);\n }\n }\n } else if (typeof payload === 'object' && payload !== null) {\n // we are in an object, continue with visiting each property\n for (const key in payload) {\n fixPayload((payload as Record<string, unknown>)[key]);\n }\n }\n}\n\n/**\n * Processes RSC flight data and creates a ReadableStream\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 // when the remote component RSC scripts are not found or loaded\n // we need to load the RSC flight data parsing the chunks\n if (data.length > 0) {\n data.forEach((chunk) => {\n const lines = chunk.split('\\n');\n for (const line of lines) {\n const match = /\\.push\\(\"(?<rsc>.*)\"\\);$/.exec(line);\n if (match?.groups?.rsc) {\n self[rscName] = self[rscName] ?? [];\n self[rscName].push(JSON.parse(`\"${match.groups.rsc}\"`) as string);\n }\n }\n });\n }\n\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 allChunks = (self[rscName] ?? [`0:[null]\\n`]).join('');\n\n // clear the RSC flight data from the global scope\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 // parse the chunk to get the id, prefix and payload\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 // parse the payload to a JSON object\n const jsonPayload = JSON.parse(payload) as unknown[];\n // fix the payload to make it compatible with React JSX development runtime\n fixPayload(jsonPayload);\n // reconstruct the chunk to a string\n const reconstruct = `${before ?? ''}${id}:${prefix ?? ''}${JSON.stringify(jsonPayload)}`;\n // encode the chunk to a byte buffer\n controller.enqueue(encoder.encode(`${reconstruct}\\n`));\n } else {\n // add empty line before closing the stream\n controller.enqueue(encoder.encode(`${chunk}\\n`));\n }\n } else {\n // add empty line before closing the stream\n controller.enqueue(encoder.encode(`${chunk}\\n`));\n }\n });\n // close the stream when all chunks are enqueued\n controller.close();\n },\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 * These patterns use named capture groups and backreferences to ensure\n * consistency within a single match (e.g., if ctx is 'e', all uses of ctx must be 'e').\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 numeric module ID\n *\n * The minifier can assign any single-letter variable names to both the receiver and\n * the Turbopack context, so both are matched as `[a-z]`.\n *\n * @example\n * // Development:\n * \"self.TURBOPACK_REMOTE_SHARED=await __turbopack_context__.A(984803)\"\n * // -> { sharedModuleId: \"984803\" }\n *\n * // Minified (context as \"e\"):\n * \"t.TURBOPACK_REMOTE_SHARED=await e.A(123456)\"\n * // -> { sharedModuleId: \"123456\" }\n *\n * // Minified (context as \"t\"):\n * \"e.TURBOPACK_REMOTE_SHARED=await t.A(123456)\"\n * // -> { sharedModuleId: \"123456\" }\n */\nexport const REMOTE_SHARED_ASSIGNMENT_RE =\n /\\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\\.A\\((?<sharedModuleId>[0-9]+)\\)/;\n\n/**\n * Matches async module loader calls: ctx.A(moduleId)\n *\n * Captures:\n * - `asyncSharedModuleId`: The numeric module ID being loaded asynchronously\n *\n * @example\n * // Development:\n * \"() => __turbopack_context__.A(460400)\"\n * // -> { asyncSharedModuleId: \"460400\" }\n *\n * // Minified:\n * \"() => e.A(460400)\"\n * // -> { asyncSharedModuleId: \"460400\" }\n */\nexport const ASYNC_MODULE_LOADER_RE =\n /(?:__turbopack_context__|e)\\.A\\((?<asyncSharedModuleId>[0-9]+)\\)/;\n\n/**\n * Matches async module with Promise.resolve pattern.\n * Used for modules that can be loaded immediately without chunk loading.\n *\n * Captures:\n * - `ctx`: The context variable (__turbopack_context__ or e)\n * - `inner`: The inner callback variable (parentImport or e)\n * - `sharedModuleId`: The numeric module ID\n *\n * @example\n * // Development:\n * \"__turbopack_context__=>{__turbopack_context__.v(parentImport=>Promise.resolve().then(()=>parentImport(633334)))}\"\n * // -> { ctx: \"__turbopack_context__\", inner: \"parentImport\", sharedModuleId: \"633334\" }\n *\n * // Minified:\n * \"e=>{e.v(e=>Promise.resolve().then(()=>e(633334)))}\"\n * // -> { ctx: \"e\", inner: \"e\", sharedModuleId: \"633334\" }\n */\nexport const ASYNC_MODULE_RESOLVE_RE =\n /(?<ctx>__turbopack_context__|e)=>\\{\\k<ctx>\\.v\\((?<inner>parentImport|e)=>Promise\\.resolve\\(\\)\\.then\\(\\(\\)=>\\k<inner>\\((?<sharedModuleId>[0-9]+)\\)\\)\\)\\}/;\n\n/**\n * Matches async module with Promise.all pattern.\n * Used for modules that require loading additional chunks first.\n *\n * Captures:\n * - `ctx`: The context variable (__turbopack_context__ or e)\n * - `vCb`: The callback passed to .v() (parentImport or t)\n * - `mapCb`: The callback passed to .map() (chunk or t)\n * - `sharedModuleId`: The numeric module ID\n *\n * @example\n * // Development:\n * \"__turbopack_context__=>{__turbopack_context__.v(parentImport=>Promise.all([\\\"static/chunks/82dcf883b4ba22f0.js\\\"].map(chunk=>__turbopack_context__.l(chunk))).then(()=>parentImport(657407)))}\"\n * // -> { ctx: \"__turbopack_context__\", vCb: \"parentImport\", mapCb: \"chunk\", sharedModuleId: \"657407\" }\n *\n * // Minified:\n * \"e=>{e.v(t=>Promise.all([\\\"chunk.js\\\"].map(t=>e.l(t))).then(()=>t(633334)))}\"\n * // -> { ctx: \"e\", vCb: \"t\", mapCb: \"t\", sharedModuleId: \"633334\" }\n */\nexport const ASYNC_MODULE_ALL_RE =\n /(?<ctx>__turbopack_context__|e)=>\\{\\k<ctx>\\.v\\((?<vCb>parentImport|t)=>Promise\\.all\\(\\[\"[^\"]+\"\\]\\.map\\((?<mapCb>chunk|t)=>\\k<ctx>\\.l\\(\\k<mapCb>\\)\\)\\)\\.then\\(\\(\\)=>\\k<vCb>\\((?<sharedModuleId>[0-9]+)\\)\\)\\)\\}/;\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 { 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 * - setupWebpackRuntime (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\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 // Global dedup cache keyed by absolute URL\n if (!self.__remote_components_turbopack_chunk_loader_promise__) {\n self.__remote_components_turbopack_chunk_loader_promise__ = {};\n }\n if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {\n return self.__remote_components_turbopack_chunk_loader_promise__[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 self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(\n (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\n return self.__remote_components_turbopack_chunk_loader_promise__[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 with push interceptor\n if (!self[`TURBOPACK_${globalKey}`]) {\n const chunkData: unknown[][] = [];\n const turbopackObject = {\n push: (item: unknown) => {\n if (Array.isArray(item)) {\n chunkData.push(item);\n } else {\n chunkData.push([item]);\n }\n return chunkData.length;\n },\n __chunks__: chunkData,\n };\n self[`TURBOPACK_${globalKey}`] = turbopackObject as unknown as Record<\n string,\n unknown\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 { handleTurbopackModule } from './module';\nimport {\n ASYNC_MODULE_ALL_RE,\n ASYNC_MODULE_LOADER_RE,\n ASYNC_MODULE_RESOLVE_RE,\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 * Reads the TURBOPACK global for a scope, normalizing the push-based\n * `__chunks__` format into a flat module list when needed.\n */\nfunction getTurbopackModules(scope: RemoteScope): unknown[] | undefined {\n const self = globalThis as GlobalScope;\n const raw = self[`TURBOPACK_${scope.globalKey}`];\n if (!raw) return undefined;\n\n if (typeof raw === 'object' && '__chunks__' in (raw as object)) {\n return (raw as { __chunks__: unknown[][] }).__chunks__.flat();\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 } =\n REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ??\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 } =\n ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};\n\n if (asyncSharedModuleId) {\n const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);\n\n let asyncSharedModule: (() => unknown) | undefined;\n const turbopackModules = getTurbopackModules(scope) ?? [];\n const asyncSharedModuleIdIndex = turbopackModules.indexOf(\n asyncSharedModuleIdNumber,\n );\n if (\n asyncSharedModuleIdIndex !== -1 &&\n typeof turbopackModules[asyncSharedModuleIdIndex + 1] === 'function'\n ) {\n asyncSharedModule = turbopackModules[\n asyncSharedModuleIdIndex + 1\n ] as () => unknown;\n }\n if (asyncSharedModule) {\n const asyncSharedModuleCode = asyncSharedModule.toString();\n // Try both Promise.resolve and Promise.all patterns\n const { sharedModuleId } =\n ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ??\n ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ??\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 type { GlobalScope } from '#internal/runtime/types';\nimport { logError } from '#internal/utils/logger';\nimport { loadChunkWithScope } from './chunk-loader';\nimport { formatRemoteId, type RemoteScope } from './remote-scope';\nimport { getSharedModule } 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 const sharedModule = getSharedModule(scope, moduleId);\n if (sharedModule) {\n // Cache the shared module so subsequent lookups for the same id\n // resolve from moduleCache without re-scanning sharedModules.\n scope.moduleCache[idStr] = sharedModule;\n return sharedModule;\n }\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 const self = globalThis as GlobalScope;\n\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 raw = self[`TURBOPACK_${scope.globalKey}`];\n\n // Normalize the bundle global to a flat entry list. The chunk-loader push\n // interceptor stores modules as { __chunks__: [[Element, id, fn, ...], ...] }.\n let modules: BundleModules;\n if (raw && typeof raw === 'object' && '__chunks__' in raw) {\n modules = (\n raw as { __chunks__: unknown[][] }\n ).__chunks__.flat() as unknown as BundleModules;\n } else if (Array.isArray(raw)) {\n modules = (raw as unknown[]).flat() as unknown as BundleModules;\n } else {\n modules = raw as BundleModules;\n }\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 in the Turbopack bundle.\n */\nfunction findModuleInit(\n modules: BundleModules,\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 return flat.find((e): e is Record<string, TurbopackModuleInit> =>\n Boolean(e && typeof e === 'object' && moduleId in (e as object)),\n )?.[moduleId];\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 (!('default' in mod) && mod.toString() !== '[object Module]') {\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 { 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 { createScope, getScope, registerScope } from './remote-scope';\nimport { initializeSharedModules } from './shared-modules';\n\n/**\n * Sets up webpack 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 * @param runtime - The bundler runtime type ('webpack' or 'turbopack')\n * @param scripts - Initial script chunks to load for Turbopack runtime\n * @param url - Base URL for the remote component bundle\n * @param bundle - Bundle identifier (defaults to 'default')\n * @param shared - Host-provided shared modules (e.g., React)\n * @param remoteShared - Mapping of remote module IDs to shared module names\n */\nexport async function setupWebpackRuntime(\n runtime: Runtime,\n scripts: { src: string | null }[] = [],\n url: URL = new URL(location.href),\n bundle?: string,\n shared: Record<string, () => Promise<unknown>> = {},\n remoteShared: Record<string, string> = {},\n resolveClientUrl?: InternalResolveClientUrl,\n): Promise<void> {\n const self = globalThis as GlobalScope;\n const bundleName = bundle ?? 'default';\n\n // Create and register a scope for this remote\n const scope = createScope(bundleName, url, runtime, resolveClientUrl);\n registerScope(scope);\n\n // Still needed by patch-require.ts (webpack plugin that generates runtime\n // code as a string template — can't call getScope at build time) and the\n // HTML host (html/index.tsx writes this before setupWebpackRuntime runs).\n if (!self.__remote_bundle_url__) {\n self.__remote_bundle_url__ = {};\n }\n self.__remote_bundle_url__[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 self.__remote_bundle_url__[scope.scopedName] = url;\n }\n self.__webpack_get_script_filename__ = () => null;\n\n const willCreateDispatchers =\n typeof self.__webpack_require__ !== 'function' ||\n self.__webpack_require_type__ !== '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 self.__webpack_require_type__ = runtime;\n\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 // Alias __remote_webpack_require__ under the scoped name so the module\n // dispatcher can find it when RSC data uses the rewritten bundle identifier.\n // For turbopack remotes the entry was just created above; for webpack remotes\n // it was populated by the remote's own scripts under the plain name.\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 // initialize shared modules with core React dependencies\n const coreShared = {\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 ...shared,\n };\n await initializeSharedModules(scope, coreShared, remoteShared);\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, use the pre-loaded require function\n if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {\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 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 type {\n MountOrUnmountFunction,\n MountUnmountFunctions,\n} 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 = (\n globalThis as unknown as { __rc_module_registry__?: Record<string, T> }\n ).__rc_module_registry__;\n const mod = registry?.[absoluteSrc] ?? ({} as T);\n if (registry) 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 self = globalThis as typeof globalThis & MountUnmountFunctions;\n if (self.__remote_script_entrypoint_mount__?.[url.href]) {\n self.__remote_script_entrypoint_mount__[url.href] = new Set();\n }\n if (self.__remote_script_entrypoint_unmount__?.[url.href]) {\n self.__remote_script_entrypoint_unmount__[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 (!self.__remote_script_entrypoint_mount__) {\n // eslint-disable-next-line camelcase\n self.__remote_script_entrypoint_mount__ = {};\n }\n if (!self.__remote_script_entrypoint_mount__[url.href]) {\n self.__remote_script_entrypoint_mount__[url.href] = new Set();\n }\n self.__remote_script_entrypoint_mount__[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 (!self.__remote_script_entrypoint_unmount__) {\n // eslint-disable-next-line camelcase\n self.__remote_script_entrypoint_unmount__ = {};\n }\n if (!self.__remote_script_entrypoint_unmount__[url.href]) {\n self.__remote_script_entrypoint_unmount__[url.href] = new Set();\n }\n self.__remote_script_entrypoint_unmount__[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 { useMemo } from 'react';\nimport { useRemoteComponentsContext } from '#internal/host/react/context';\nimport { bindResolveClientUrl } from '#internal/runtime/url/default-resolve-client-url';\nimport type { ResolveClientUrl } from '#internal/runtime/url/resolve-client-url';\n\nexport function useResolveClientUrl(\n prop: ResolveClientUrl | undefined,\n urlHref: string,\n) {\n const { resolveClientUrl: contextValue } = useRemoteComponentsContext();\n const raw = prop ?? contextValue;\n return useMemo(() => bindResolveClientUrl(raw, urlHref), [raw, urlHref]);\n}\n","import { useLayoutEffect, useRef, useState } from 'react';\n\nexport interface GlobalThis {\n [key: `__remote_components_shadowroot_${string}`]: ShadowRoot | null;\n}\n\ninterface UseShadowRootOptions {\n /** Whether CSS isolation is enabled */\n isolate: boolean | undefined;\n /** Shadow DOM mode */\n mode: 'open' | 'closed';\n /** Unique key suffix for identifying this shadow root */\n keySuffix: string;\n}\n\ninterface UseShadowRootResult {\n /** The shadow root element, or null if not isolated */\n shadowRoot: ShadowRoot | null;\n /** Ref to attach to the shadow host container element */\n shadowRootContainerRef: React.RefObject<HTMLDivElement | null>;\n}\n\n/**\n * Manages shadow root lifecycle for CSS isolation.\n *\n * Handles:\n * - Initial shadow root discovery from SSR or declarative shadow DOM\n * - Creating shadow root as fallback for browsers without declarative shadow DOM support\n * - Cleanup when isolation is disabled\n * - Re-attachment when isolation is re-enabled\n */\nexport function useShadowRoot({\n isolate,\n mode,\n keySuffix,\n}: UseShadowRootOptions): UseShadowRootResult {\n const shadowRootContainerRef = useRef<HTMLDivElement | null>(null);\n\n const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(() => {\n const self = globalThis as unknown as GlobalThis;\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n const ssrShadowRoot =\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n )?.shadowRoot ??\n self[shadowRootKey] ??\n null)\n : null;\n // Clear the global reference after reading it\n self[shadowRootKey] = null;\n return ssrShadowRoot;\n });\n\n useLayoutEffect(() => {\n if (\n isolate !== false &&\n typeof document !== 'undefined' &&\n (!shadowRoot || !shadowRoot.isConnected)\n ) {\n const self: GlobalThis = globalThis;\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n\n let shadowRootElement: ShadowRoot | null = null;\n const element = document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n );\n shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;\n\n if (!shadowRootElement && element) {\n // Create a shadow root if it doesn't exist.\n // This is a fallback for browsers that don't support declarative shadow DOM.\n try {\n shadowRootElement = element.attachShadow({ mode });\n self[shadowRootKey] = shadowRootElement;\n } catch {\n // Do nothing if attachShadow fails because of existing shadow root\n }\n }\n\n if (shadowRootElement) {\n // Remove all nodes from the shadow root except links (preserves stylesheets)\n shadowRootElement.querySelectorAll('*:not(link)').forEach((node) => {\n node.remove();\n });\n setShadowRoot(shadowRootElement);\n }\n } else if (isolate === false && shadowRoot) {\n // Clear the global cache when disabling isolation (only when explicitly false)\n const self: GlobalThis = globalThis;\n const shadowRootKey =\n `__remote_components_shadowroot_${keySuffix}` as const;\n self[shadowRootKey] = null;\n setShadowRoot(null);\n }\n }, [isolate, shadowRoot, mode, keySuffix]);\n\n return { shadowRoot, shadowRootContainerRef };\n}\n","import { DEFAULT_COMPONENT_NAME } from '#internal/runtime/constants';\n\n/**\n * Dummy URL used as a fallback base for URL parsing when no real base URL is available.\n * This is used during SSR or when location is not defined.\n */\nexport const DUMMY_FALLBACK = 'http://remote-components-dummy-fallback';\n\n/**\n * Extracts the relevant HTML content from a remote component response.\n *\n * Handles multiple remote component formats:\n * - Next.js Pages Router SSR wrapper (`div[id^=\"__REMOTE_COMPONENT\"]`)\n * - App Router remote components (`div[data-bundle][data-route]`)\n * - Next.js pages (`div#__next`)\n * - Web component format (`remote-component:not([src])`)\n *\n * @param html - Raw HTML string from the remote component response\n * @returns Extracted HTML content with links and scripts, or empty string if not found\n */\nexport function getRemoteComponentHtml(html: string): string {\n if (typeof document === 'undefined') return html;\n\n const parser = new DOMParser();\n const temp = parser.parseFromString(html, 'text/html');\n\n // Used by the Next.js Pages Router remote as a wrapper\n const ssrRemoteComponentContainer = temp.querySelector(\n 'div[id^=\"__REMOTE_COMPONENT\"]',\n );\n if (ssrRemoteComponentContainer) {\n return ssrRemoteComponentContainer.innerHTML;\n }\n\n // Remote component content from various sources\n const remoteComponentContainer = temp.querySelectorAll(\n `div[data-bundle][data-route][data-runtime][id^=\"${DEFAULT_COMPONENT_NAME}\"],div[data-bundle][data-route],div#__next,remote-component:not([src])`,\n );\n if (remoteComponentContainer.length > 0) {\n return `${Array.from(temp.querySelectorAll('link,script'))\n .map((link) => link.outerHTML)\n .join('')}${Array.from(remoteComponentContainer)\n .map((container) => container.outerHTML)\n .join('')}`;\n }\n\n return '';\n}\n","import type { NavigateOptions } from 'next/dist/shared/lib/app-router-context.shared-runtime';\nimport { usePathname, useSearchParams } from 'next/navigation';\nimport { logWarn } from '#internal/utils/logger';\n\nexport const routerImpl = async () => {\n const { useRouter } = await import('next/navigation');\n return Promise.resolve({\n useRouter: () => {\n const router = useRouter();\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const query = Object.fromEntries(searchParams.entries());\n return {\n pathname,\n query,\n asPath: searchParams.toString()\n ? `${pathname}?${searchParams.toString()}`\n : pathname,\n push: (href: string, _: string, options?: NavigateOptions) => {\n router.push(href, options);\n return Promise.resolve(true);\n },\n replace: (href: string, _: string, options?: NavigateOptions) => {\n router.replace(href, options);\n return Promise.resolve(true);\n },\n refresh: () => Promise.resolve(router.refresh()),\n prefetch: async () => {\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.prefetch() in a remote component loaded in the Next.js App Router. prefetch() is a no-op in the App Router.',\n );\n return Promise.resolve();\n },\n back: () => {\n // there's no back() in the App Router\n if (typeof window !== 'undefined') {\n window.history.back();\n }\n },\n reload: () => {\n router.refresh();\n },\n beforePopState: () => {\n // there's no beforePopState() in the App Router\n },\n events: {\n on: () => {\n // there's no router.events in the App Router\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.events.on() in a remote component loaded in the Next.js App Router. events.on() is a no-op in the App Router.',\n );\n },\n off: () => {\n // there's no router.events in the App Router\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.events.off() in a remote component loaded in the Next.js App Router. events.off() is a no-op in the App Router.',\n );\n },\n emit: () => {\n // there's no router.events in the App Router\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.events.emit() in a remote component loaded in the Next.js App Router. events.emit() is a no-op in the App Router.',\n );\n },\n },\n };\n },\n });\n};\n"],"mappings":";;;;;;;;;;;;AAAA,IAAa,oCAEA,gCAGA;AALb;AAAA;AAAA;AAAO,IAAM,qCAAqC;AAE3C,IAAM,iCACX;AAEK,IAAM,gBACX;AAAA;AAAA;;;ACNF;AAAA;AAAA;AAAA;AAAA,IAEa;AAFb;AAAA;AAAA;AAAA;AAEO,IAAM,SAAiD;AAAA,MAC5D,sCAAsC,MACpC,QAAQ,OAAO,IAAI,MAAM,8BAA8B,CAAC;AAAA,IAC5D;AAAA;AAAA;;;ACFA,SAAS,WAAAA,gBAAe;;;ACHjB,SAAS,aAAa,KAAa;AACxC,SAAO,IAAI,QAAQ,cAAc,GAAG;AACtC;AAYO,SAAS,kBACd,MACA,SACQ;AACR,SAAO,QAAQ,gBACX,GAAG,QAAQ,aAAa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cACE;AAAA,cACA;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACH;;;AtCNI,gBAAAQ,YAAA;AApDJ,eAAe,kBAAkB;AAC/B,MAAI;AACF,UAAM,EAAE,QAAAC,QAAO,IAAI,MAAM;AACzB,WAAOA;AAAA,EACT,QAAE;AACA,WAAO,CAAC;AAAA,EACV;AACF;AAEA,IAAM,gBAAgB,OACpB,YACA,qBACG;AACH,QAAM,CAAC,gBAAgB,kBAAkB,IAAI,MAAM,QAAQ,IAAI;AAAA,IAC7D,gBAAgB;AAAA,IAChB,cAAc,QAAQ,QAAQ,CAAC,CAAC;AAAA,EAClC,CAAC;AACD,SAAO;AAAA,IACL,GAAG;AAAA,IACH,eAAe;AAAA,IACf,GAAG,+BAA+B,EAAE,SAAS,iBAAiB,CAAC;AAAA,IAC/D,GAAG;AAAA,EACL;AACF;AAkBO,SAAS,+BAA+B;AAAA,EAC7C,QAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAA4D;AAC1D,QAAM,eAAeC;AAAA,IACnB,MAAM,cAAcD,SAAQ,gBAAgB;AAAA,IAC5C,CAACA,SAAQ,gBAAgB;AAAA,EAC3B;AACA,SACE,gBAAAD;AAAA,IAAC;AAAA;AAAA,MACC,OAAO,EAAE,QAAQ,cAAc,kBAAkB,GAAG,MAAM;AAAA,MAEzD;AAAA;AAAA,EACH;AAEJ;AAWO,SAASG,wBAAuB,OAAoC;AACzE,MAAI,OAAO,MAAM,QAAQ,YAAY,EAAE,MAAM,eAAe,MAAM;AAChE,WAAO,MAAM,YAAY;AAAA,EAC3B;AAEA,SACE,gBAAAH;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ,QAAQ,cAAc,MAAM,QAAQ,MAAM,gBAAgB;AAAA;AAAA,EAC5D;AAEJ;","names":["useMemo","location","location","useLayoutEffect","useMemo","useRef","useState","useRemoteComponentsContext","shared","shared","shared","shared","jsx","createElement","useRemoteComponentsContext","shared","useMemo","useState","useRef","useLayoutEffect","jsx","shared","useMemo","ConsumeRemoteComponent"]}
1
+ {"version":3,"sources":["../../../../src/utils/constants.ts","../../../../src/host/defaults/shared.ts","../../../../src/host/defaults/app.ts","../../../../src/host/nextjs/app-client-only.tsx","../../../../src/host/nextjs/image-shared.ts","../../../../src/utils/index.ts","../../../../src/runtime/constants.ts","../../../../src/runtime/namespace.ts","../../../../src/runtime/patterns.ts","../../../../src/utils/logger.ts","../../../../src/runtime/url/protected-rc-fallback.ts","../../../../src/utils/abort.ts","../../../../src/utils/error.ts","../../../../src/runtime/turbopack/remote-scope.ts","../../../../src/host/shared/remote-image-loader.ts","../../../../src/runtime/url/resolve-client-url.ts","../../../../src/runtime/url/default-resolve-client-url.ts","../../../../src/host/nextjs/shared-import.ts","../../../../src/host/react/index.tsx","../../../../src/host/server/fetch-headers.ts","../../../../src/host/server/fetch-with-hooks.ts","../../../../src/host/server/get-client-or-server-url.ts","../../../../src/host/shared/polyfill.tsx","../../../../src/host/shared/shared-module-resolver.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/metadata.ts","../../../../src/runtime/html/parse-remote-html.ts","../../../../src/runtime/html/set-attributes-from-props.ts","../../../../src/runtime/loaders/component-loader.ts","../../../../src/config/webpack/apply-shared-modules.ts","../../../../src/config/webpack/next-client-pages-loader.ts","../../../../src/runtime/rsc.ts","../../../../src/runtime/rsc-imports.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/react/hooks/use-resolve-client-url.ts","../../../../src/host/react/hooks/use-shadow-root.ts","../../../../src/host/react/utils/extract-remote-html.ts","../../../../src/host/nextjs/app-compat.tsx"],"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 { MISSING_SHARED_MODULES_MESSAGE } from '#internal/utils/constants';\n\nexport const shared: Record<string, () => Promise<unknown>> = {\n __remote_components_missing_shared__: () =>\n Promise.reject(new Error(MISSING_SHARED_MODULES_MESSAGE)),\n};\n","export { shared } from './shared';\n","'use client';\n\nimport type React from 'react';\nimport { useMemo } from 'react';\nimport { createImageLoaderSharedEntries } from '#internal/host/nextjs/image-shared';\nimport { tryImportShared } from '#internal/host/nextjs/shared-import';\nimport { RemoteComponentsContext } from '#internal/host/react/context';\nimport type { ConsumeClientOnlyConfig } from '#internal/host/shared/config';\nimport type { ResolveClientUrl } from '#internal/runtime/url/resolve-client-url';\nimport {\n type ConsumeRemoteComponentProps,\n ConsumeRemoteComponent as ConsumeRemoteComponentReact,\n} from '#remote-components/host/react';\nimport { routerImpl } from './app-compat';\n\nconst sharedModules = async (\n userShared?: ConsumeRemoteComponentProps['shared'],\n resolveClientUrl?: ResolveClientUrl,\n) => {\n const [resolvedShared, resolvedUserShared] = await Promise.all([\n tryImportShared(),\n userShared ?? Promise.resolve({}),\n ]);\n return {\n ...resolvedShared,\n 'next/router': routerImpl,\n ...createImageLoaderSharedEntries({ unbound: resolveClientUrl }),\n ...resolvedUserShared,\n };\n};\n\n/**\n * Provider for Next.js App Router hosts. Provides real Next.js implementations\n * of `next/image`, `next/navigation`, `next/link`, etc. to all nested\n * `<ConsumeRemoteComponent>` instances.\n *\n * Works in both Server and Client Components — set it up once in your layout\n * and use `<ConsumeRemoteComponent>` from `remote-components/react` everywhere:\n *\n * ```tsx\n * import { RemoteComponentsClientProvider } from 'remote-components/host/nextjs/app/client-only';\n *\n * <RemoteComponentsClientProvider resolveClientUrl={proxyClientRequestsThroughHost}>\n * {children}\n * </RemoteComponentsClientProvider>\n * ```\n */\nexport function RemoteComponentsClientProvider({\n shared,\n resolveClientUrl,\n children,\n ...props\n}: ConsumeClientOnlyConfig & { children: React.ReactNode }) {\n const mergedShared = useMemo(\n () => sharedModules(shared, resolveClientUrl),\n [shared, resolveClientUrl],\n );\n return (\n <RemoteComponentsContext\n value={{ shared: mergedShared, resolveClientUrl, ...props }}\n >\n {children}\n </RemoteComponentsContext>\n );\n}\n\n/**\n * `ConsumeRemoteComponent` for Next.js App Router hosts. Provides real Next.js\n * implementations of `next/image`, `next/navigation`, `next/link`, etc.\n *\n * The provider approach is recommended because it works in both Server and Client\n * Components — set up `RemoteComponentsClientProvider` from this module once in\n * your layout, and use `<ConsumeRemoteComponent>` from `remote-components/react`\n * everywhere. Import this component only when adding a provider is not practical.\n */\nexport function ConsumeRemoteComponent(props: ConsumeRemoteComponentProps) {\n if (typeof props.src !== 'string' && !(props.src instanceof URL)) {\n return props.children ?? null;\n }\n\n return (\n <ConsumeRemoteComponentReact\n {...props}\n shared={sharedModules(props.shared, props.resolveClientUrl)}\n />\n );\n}\n","import { createElement, forwardRef } from 'react';\nimport { createRemoteImageLoader } from '#internal/host/shared/remote-image-loader';\nimport { getScope } from '#internal/runtime/turbopack/remote-scope';\nimport { bindResolveClientUrl } from '#internal/runtime/url/default-resolve-client-url';\nimport type {\n InternalResolveClientUrl,\n ResolveClientUrl,\n} from '#internal/runtime/url/resolve-client-url';\n\ntype SharedImageModule = (bundle: string) => Promise<unknown>;\n\nfunction resolveForBundle(\n unbound: ResolveClientUrl | undefined,\n bundle: string,\n): InternalResolveClientUrl | undefined {\n if (!unbound) return undefined;\n const remoteSrc = getScope(bundle)?.url.href ?? '';\n return bindResolveClientUrl(unbound, remoteSrc);\n}\n\n/**\n * Creates shared module entries for image-related modules that route\n * optimization requests through the remote's `/_next/image` endpoint.\n *\n * Pass `bound` when the resolver already has `remoteSrc` applied (App Router).\n * Pass `unbound` when only the raw 2-arg `ResolveClientUrl` is available\n * (Pages Router, client-only provider).\n */\nexport function createImageLoaderSharedEntries({\n bound,\n unbound,\n}: {\n bound?: InternalResolveClientUrl;\n unbound?: ResolveClientUrl;\n} = {}): Record<string, SharedImageModule> {\n const loaderEntry: SharedImageModule = (bundle: string) => {\n const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);\n return Promise.resolve({\n default: createRemoteImageLoader(bundle, resolveClientUrl),\n __esModule: true,\n });\n };\n\n // Cross-version compat: remotes <=0.2.x request `next/image` as a shared module.\n // Wraps the host's Image component with the remote image loader injected\n // via the `loader` prop. Can be removed once 0.2.x support is dropped.\n const imageEntry: SharedImageModule = async (bundle: string) => {\n const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);\n const rawLoader = createRemoteImageLoader(bundle, resolveClientUrl);\n // Wrap to match Next.js `ImageLoader` signature (no `config` param).\n // The raw loader expects `{ config, src, width, quality }` but the public\n // `loader` prop is called with `{ src, width, quality }` only.\n const remoteLoader = Object.assign(\n (p: { src: string; width: number; quality?: number }) =>\n rawLoader({ ...p, config: { path: '/_next/image' } }),\n { __next_img_default: true as const },\n );\n const mod = await import('next/image');\n const OriginalImage = mod.default;\n type ImageProps = Parameters<typeof OriginalImage>[0];\n const RemoteImage = forwardRef<HTMLImageElement, ImageProps>((props, ref) =>\n createElement(OriginalImage, {\n ...props,\n loader: props.loader ?? remoteLoader,\n ref,\n }),\n );\n RemoteImage.displayName = 'RemoteImage';\n return { ...mod, default: RemoteImage, __esModule: true };\n };\n\n return {\n 'next/dist/shared/lib/image-loader': loaderEntry,\n 'next/dist/esm/shared/lib/image-loader': loaderEntry,\n // Can be removed once 0.2.x support is dropped.\n 'next/image': imageEntry,\n // Can be removed once 0.2.x support is dropped.\n 'next/dist/client/image-component': imageEntry,\n // Can be removed once 0.2.x support is dropped.\n 'next/dist/api/image': imageEntry,\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 { 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","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 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","/**\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","export async function tryImportShared() {\n try {\n const { shared } = await import('#remote-components/host/defaults/app');\n return shared;\n } catch {\n return {};\n }\n}\n","import {\n startTransition,\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { useRemoteComponentsContext } from '#internal/host/react/context';\nimport { fetchWithHooks } from '#internal/host/server/fetch-with-hooks';\nimport { getClientOrServerUrl } from '#internal/host/server/get-client-or-server-url';\nimport type { ConsumeRemoteComponentConfig } from '#internal/host/shared/config';\nimport type { ConsumeServerData } from '#internal/host/shared/server-handoff';\nimport { buildHostShared } from '#internal/host/shared/shared-module-resolver';\nimport { createHostState } from '#internal/host/shared/state';\nimport { resolveNameFromSrc } from '#internal/host/utils/resolve-name-from-src';\nimport {\n DEFAULT_COMPONENT_NAME,\n DEFAULT_ROUTE,\n RUNTIME_SCRIPT,\n RUNTIME_WEBPACK,\n} from '#internal/runtime/constants';\nimport { applyOriginToNodes } from '#internal/runtime/html/apply-origin';\nimport { parseRemoteComponentDocument } from '#internal/runtime/html/parse-remote-html';\nimport { setAttributesFromProps } from '#internal/runtime/html/set-attributes-from-props';\nimport { loadRemoteComponent } from '#internal/runtime/loaders/component-loader';\nimport { loadStaticRemoteComponent } from '#internal/runtime/loaders/static-loader';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport {\n collapseDoubleSlashes,\n REMOTE_COMPONENT_REGEX,\n} from '#internal/runtime/patterns';\nimport { attrToProp, escapeString } from '#internal/utils';\nimport { isAbortError } from '#internal/utils/abort';\nimport {\n errorFromFailedFetch,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport type { MountOrUnmountFunction } from '#remote-components/runtime/types';\nimport { useResolveClientUrl } from './hooks/use-resolve-client-url';\nimport { useShadowRoot } from './hooks/use-shadow-root';\nimport {\n DUMMY_FALLBACK,\n getRemoteComponentHtml,\n} from './utils/extract-remote-html';\n\n/**\n * Props for the React remote component host.\n *\n * Extends {@link ConsumeRemoteComponentConfig} with `children` for loading fallback content.\n */\nexport interface ConsumeRemoteComponentProps\n extends ConsumeRemoteComponentConfig {\n /** Loading fallback content displayed while the remote component is being fetched. */\n children?: React.ReactNode;\n}\n\n/**\n * ConsumeRemoteComponent is a React component that fetches and renders a remote component.\n * It supports SSR and can isolate the remote component in a shadow DOM.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n *\n * @example\n *\n * Use the `<ConsumeRemoteComponent>` in your React application to consume a remote component from a remote application:\n *\n * ```tsx\n * import { ConsumeRemoteComponent } from 'remote-components/host/react';\n *\n * export default function App() {\n * return (\n * <>\n * <h1>Welcome to My App</h1>\n * <p>This page consumes a remote component from another application.</p>\n * <ConsumeRemoteComponent src=\"/nextjs-app-remote/components/header\" />\n * </>\n * );\n * }\n * ```\n *\n * To share modules, you can provide a shared module map with references to the shared modules:\n *\n * ```tsx\n * <ConsumeRemoteComponent\n * src=\"/nextjs-app-remote/components/header\"\n * shared={{\n * '@/components/provider': () => import('@/components/host-provider')\n * }}\n * />\n * ```\n */\nexport function ConsumeRemoteComponent({\n src,\n isolate,\n mode = 'open',\n reset,\n credentials: credentialsProp,\n name: nameProp = DEFAULT_COMPONENT_NAME,\n shared: sharedProp,\n children,\n onBeforeLoad,\n onLoad,\n onError,\n onChange,\n onRequest,\n onResponse,\n resolveClientUrl: resolveClientUrlProp,\n}: ConsumeRemoteComponentProps) {\n const instanceId = useId();\n\n const { credentials: contextCredentials, shared: contextShared } =\n useRemoteComponentsContext();\n const credentials = credentialsProp ?? contextCredentials ?? 'same-origin';\n const shared = sharedProp ?? contextShared ?? {};\n\n const name = useMemo(\n () => resolveNameFromSrc(src, nameProp),\n [src, nameProp],\n );\n\n const [data, setData] = useState<Omit<ConsumeServerData, 'children'> | null>(\n null,\n );\n\n const url = useMemo(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);\n\n const resolveClientUrl = useResolveClientUrl(resolveClientUrlProp, url.href);\n\n // for relative src paths, use just the pathname as the unique id.\n // for static urls, use the full url as the unique id as the path may not be unique.\n // this id needs to be the same for server and client side rendering.\n // note that if this needs to be more unique, can pass through the bundle as an id prop and ammend it to this id.\n const id =\n url.origin ===\n (typeof location !== 'undefined' ? location.origin : DUMMY_FALLBACK)\n ? url.pathname\n : url.href;\n\n //instanceId prevents multiple components with the same src from sharing a shadow root\n const keySuffix = `${escapeString(id)}_${escapeString(\n data?.name ?? name,\n )}_${escapeString(instanceId)}`;\n\n const [remoteComponent, setRemoteComponent] = useState<\n React.ReactNode | Error\n >(null);\n\n const { shadowRoot, shadowRootContainerRef } = useShadowRoot({\n isolate,\n mode,\n keySuffix,\n });\n\n const htmlRef = useRef<string | null>(\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n )?.shadowRoot?.innerHTML ??\n document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ??\n document.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`)\n ?.innerHTML ??\n document.querySelector('div[data-bundle][data-route]')?.innerHTML)\n : null,\n );\n const endTemplateRef = useRef<HTMLTemplateElement | null>(null);\n // collect initial content that needs to be removed after remote component renders\n const childrenRef = useRef(\n typeof document !== 'undefined'\n ? (() => {\n let el = document.querySelector(`template[id=\"${name}_start\"]`);\n const elements = [];\n while (el && el.id !== `${name}_end`) {\n if (\n el.id !== `${name}_start` &&\n !el.getAttribute('data-remote-component')\n ) {\n elements.push(el);\n }\n el = el.nextElementSibling as HTMLTemplateElement | null;\n }\n return elements;\n })()\n : [],\n );\n const hostStateRef = useRef(createHostState());\n const componentHydrationHtml = useRef<string | null>(null);\n const prevRemoteComponentContainerRef = useRef<HTMLDivElement | null>(null);\n const unmountRef = useRef<Set<MountOrUnmountFunction> | null>(null);\n\n // Clean up the shadow root cache on unmount to prevent memory leaks\n useLayoutEffect(() => {\n return () => {\n delete getNamespace().shadowRoots[keySuffix];\n };\n }, [keySuffix]);\n\n useLayoutEffect(() => {\n // Clear initial content after remote component renders\n if (childrenRef.current.length > 0 && remoteComponent) {\n childrenRef.current.forEach((el) => {\n el.remove();\n });\n childrenRef.current = [];\n }\n }, [remoteComponent]);\n\n useLayoutEffect(() => {\n if (shadowRoot && remoteComponent) {\n const resetStyles = shadowRoot.querySelectorAll(\n 'style[data-remote-components-reset]',\n );\n // ensure we only have one reset style in the shadow root\n if (resetStyles.length > 1) {\n resetStyles.forEach((style, index) => {\n if (\n index > 0 &&\n style.getAttribute('data-remote-components-reset') !== 'react'\n ) {\n style.remove();\n }\n });\n }\n\n // clear the html ref after hydration\n htmlRef.current = null;\n\n // clear all nodes except links and styles until the start marker\n // the marker gets only rendered on hydration\n let el: ChildNode | null = shadowRoot.childNodes[0] ?? null;\n while (el && (!('id' in el) || el.id !== `${name}_start`)) {\n const nextEl = el.nextSibling;\n if (el.nodeName !== 'LINK' && el.nodeName !== 'STYLE') {\n el.parentNode?.removeChild(el);\n }\n el = nextEl;\n }\n }\n }, [shadowRoot, remoteComponent, name]);\n\n useEffect(() => {\n if (src && src !== hostStateRef.current.prevSrc) {\n const previousSrc = hostStateRef.current.prevSrc;\n const previousName = hostStateRef.current.prevName;\n hostStateRef.current.prevSrc = src;\n\n if (previousSrc !== null) {\n htmlRef.current = null;\n }\n\n // Abort any in-progress load so the latest src always wins.\n hostStateRef.current.abortController?.abort();\n hostStateRef.current.abortController = new AbortController();\n const { signal } = hostStateRef.current.abortController;\n\n onBeforeLoad?.(src);\n hostStateRef.current.stage = 'loading';\n\n startTransition(async () => {\n try {\n let html = getRemoteComponentHtml(\n htmlRef.current ??\n (endTemplateRef.current?.previousElementSibling?.tagName === 'div'\n ? endTemplateRef.current.previousElementSibling.innerHTML\n : ''),\n );\n\n if (!html && src) {\n // fetch the remote component\n const fetchInit = {\n credentials,\n } as RequestInit;\n\n const resolvedUrl = new URL(\n resolveClientUrl?.(url.href) ?? url.href,\n location.href,\n );\n const res = await fetchWithHooks(resolvedUrl, fetchInit, {\n onRequest,\n onResponse,\n abortController: hostStateRef.current.abortController,\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\n const remoteHtml = await res.text();\n if (signal.aborted) return;\n htmlRef.current = remoteHtml;\n html = getRemoteComponentHtml(remoteHtml);\n }\n\n if (signal.aborted) return;\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 {\n component,\n name: remoteName,\n isRemoteComponent,\n metadata,\n nextData,\n rsc,\n remoteShared,\n links: linkElements,\n scripts: scriptElements,\n } = parseRemoteComponentDocument(doc, name, url);\n\n if (hostStateRef.current.prevIsRemoteComponent) {\n if (shadowRoot) {\n shadowRoot.innerHTML = '';\n }\n const prevUrl = hostStateRef.current.prevUrl;\n if (prevUrl && getNamespace().unmountFns[prevUrl.href]) {\n const unmountPromises = Promise.all(\n Array.from(unmountRef.current ?? []).map(async (unmount) =>\n unmount(\n shadowRoot ?? prevRemoteComponentContainerRef.current,\n ),\n ),\n );\n unmountRef.current = null;\n await unmountPromises;\n }\n }\n hostStateRef.current.prevIsRemoteComponent = isRemoteComponent;\n hostStateRef.current.prevUrl = url;\n hostStateRef.current.prevName = remoteName;\n\n // update all relative URLs to absolute URLs based on the remote component URL\n applyOriginToNodes(doc, url, resolveClientUrl);\n\n const links = linkElements.map((link) => ({\n href: new URL(link.getAttribute('href') ?? link.href, url).href,\n ...link\n .getAttributeNames()\n .reduce<Record<string, string>>((acc, key) => {\n if (key !== 'href') {\n acc[attrToProp[key] ?? key] = link.getAttribute(key) ?? '';\n }\n return acc;\n }, {}),\n }));\n\n const scripts = scriptElements;\n\n // handle inline scripts in the remote component\n const inlineScripts = (\n isRemoteComponent ? component : doc\n ).querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])\",\n );\n\n if (!isRemoteComponent) {\n // Next.js Script support\n const self = globalThis as typeof globalThis & {\n __next_s: [string, Record<string, string>][];\n };\n const prevNextScripts = self.__next_s;\n const nextScripts = [] as [string, Record<string, string>][];\n // eslint-disable-next-line camelcase\n self.__next_s = nextScripts;\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 await Promise.all(\n Array.from(inlineScripts)\n .filter(\n (script) =>\n !(\n script.id.endsWith('_shared') &&\n script.getAttribute('type') === 'application/json' &&\n typeof script.getAttribute(\n 'data-remote-components-shared',\n ) === 'string'\n ),\n )\n .map((script) => {\n return new Promise((resolve) => {\n // only handle inline scripts with content, but not Next.js RSC scripts\n if (\n script.textContent &&\n !script.textContent.includes('self.__next_f=') &&\n !script.textContent.includes('self.__next_f.push')\n ) {\n // if script is inline javascript, then execute using blob\n if (\n !script.getAttribute('type') ||\n script.getAttribute('type') === 'text/javascript' ||\n script.getAttribute('type') === 'application/javascript'\n ) {\n const newScript = document.createElement('script');\n\n // scripts loaded from external sources needs this workaround\n const blob = new Blob([script.textContent], {\n type: 'application/javascript',\n });\n const blobUrl = URL.createObjectURL(blob);\n\n newScript.onload = () => {\n resolve(undefined);\n // script executed and safe to remove\n URL.revokeObjectURL(blobUrl);\n newScript.remove();\n };\n // on error we still want to resolve to not block the remote component loading\n newScript.onerror = () => {\n URL.revokeObjectURL(blobUrl);\n newScript.remove();\n resolve(undefined);\n };\n\n newScript.src = blobUrl;\n // TODO: needs to be cancellable https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\n document.body.appendChild(newScript);\n } else {\n resolve(undefined);\n document.body.appendChild(script);\n }\n } else {\n resolve(undefined);\n }\n });\n }),\n );\n // process the remote component Next.js Script container\n nextScripts.forEach(([scriptSrc, props]) => {\n const script = document.createElement('script');\n // when we have a script src, apply it (inline scripts have `0` as src)\n if (scriptSrc) {\n script.src = scriptSrc;\n }\n // apply Script props\n if (typeof props.children === 'string') {\n script.textContent = props.children;\n }\n setAttributesFromProps(script, props);\n document.head.appendChild(script);\n });\n // restore previous Next.js Script container\n // eslint-disable-next-line camelcase\n self.__next_s = prevNextScripts;\n }\n\n const rscName = rsc\n ? `__remote_component_rsc_${escapeString(id)}_${escapeString(\n remoteName,\n )}`\n : undefined;\n if (rsc) {\n rsc.textContent =\n rsc.textContent?.replace(\n new RegExp(`self\\\\[\"${remoteName}\"\\\\]`, 'g'),\n `self[\"${rscName}\"]`,\n ) ?? '';\n document.body.appendChild(rsc);\n }\n\n const newData = {\n ...metadata,\n links,\n remoteShared,\n src: typeof src === 'string' ? src : src.href,\n serverUrl: url.href,\n data: rsc\n ? (rsc.textContent || '').split('\\n').filter(Boolean)\n : [],\n };\n\n componentHydrationHtml.current = `${Array.from(\n doc.querySelectorAll('link,style'),\n )\n .map((link) => link.outerHTML)\n .join('')}${\n reset\n ? `<style data-remote-components-reset=\"\">:host { all: initial; }</style>`\n : ''\n }${component.innerHTML}`;\n\n const userShared = await shared;\n\n if ('__remote_components_missing_shared__' in userShared) {\n userShared.__remote_components_missing_shared__().catch((e) => {\n throw e;\n });\n } else if ('__remote_components_missing_shared__' in remoteShared) {\n throw new RemoteComponentsError(\n remoteShared.__remote_components_missing_shared__,\n );\n }\n\n if (isRemoteComponent) {\n // Only call onChange when not on first load (matching HTML implementation)\n if (previousSrc !== undefined) {\n onChange?.({\n previousSrc,\n nextSrc: src,\n previousName,\n nextName: remoteName,\n });\n }\n setData(newData);\n if (shadowRoot) {\n const shadowRootHtml = reset\n ? `<style data-remote-components-reset=\"\">:host { all: initial; }</style>${component.innerHTML}`\n : component.innerHTML;\n shadowRoot.innerHTML = shadowRootHtml;\n htmlRef.current = null;\n setRemoteComponent(null);\n const { mount, unmount } = await loadStaticRemoteComponent(\n Array.from(shadowRoot.querySelectorAll('script')),\n url,\n resolveClientUrl,\n );\n unmountRef.current = unmount;\n await Promise.all(\n Array.from(mount).map((mountFn) => mountFn(shadowRoot)),\n );\n onLoad?.(src);\n } else if (isolate === false) {\n setRemoteComponent(\n // TODO: remove wrapper div by converting HTML to RSC or React tree\n <div\n dangerouslySetInnerHTML={{ __html: component.innerHTML }}\n ref={prevRemoteComponentContainerRef}\n />,\n );\n htmlRef.current = null;\n const { mount, unmount } = await loadStaticRemoteComponent(\n Array.from(component.querySelectorAll('script')),\n url,\n resolveClientUrl,\n );\n unmountRef.current = unmount;\n await Promise.all(\n Array.from(mount).map((mountFn) =>\n mountFn(prevRemoteComponentContainerRef.current),\n ),\n );\n onLoad?.(src);\n }\n hostStateRef.current.stage = 'loaded';\n } else {\n const result = await loadRemoteComponent({\n url,\n name: remoteName,\n rscName,\n bundle: metadata.bundle,\n route: metadata.route,\n runtime: metadata.runtime,\n data: newData.data,\n nextData,\n scripts: Array.from(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(\n scriptSrc,\n )?.groups ?? {\n prefix: undefined,\n id: scriptSrc,\n };\n return {\n src: new URL(\n collapseDoubleSlashes(`${prefix ?? ''}${path}`),\n url,\n ).href,\n };\n }),\n shared: buildHostShared(userShared, resolveClientUrl),\n remoteShared,\n container: shadowRoot,\n resolveClientUrl,\n });\n if (rsc) {\n rsc.remove();\n }\n\n setData(newData);\n // Only call onChange when not on first load (matching HTML implementation)\n if (previousSrc !== undefined) {\n onChange?.({\n previousSrc,\n nextSrc: src,\n previousName,\n nextName: remoteName,\n });\n }\n if (result.error) {\n hostStateRef.current.stage = 'error';\n setRemoteComponent(result.error);\n onError?.(result.error);\n } else {\n hostStateRef.current.stage = 'loaded';\n setRemoteComponent(result.component);\n onLoad?.(src);\n }\n }\n } catch (error) {\n // AbortError is expected when loading is cancelled - exit cleanly\n if (isAbortError(error)) {\n hostStateRef.current.stage = 'idle';\n return;\n }\n hostStateRef.current.stage = 'error';\n setRemoteComponent(error as Error);\n onError?.(error);\n }\n });\n }\n }, [\n url,\n src,\n isolate,\n credentials,\n name,\n shared,\n shadowRoot,\n reset,\n id,\n onBeforeLoad,\n onLoad,\n onError,\n onChange,\n onRequest,\n onResponse,\n resolveClientUrl,\n ]);\n\n if (remoteComponent instanceof Error) {\n throw remoteComponent;\n }\n\n const metadataJson = (\n <script data-remote-component type=\"application/json\">\n {JSON.stringify({\n name: data?.name || name,\n bundle: data?.bundle || 'default',\n route: data?.route || DEFAULT_ROUTE,\n runtime: hostStateRef.current.prevIsRemoteComponent\n ? RUNTIME_SCRIPT\n : data?.runtime || RUNTIME_WEBPACK,\n })}\n </script>\n );\n const resetStyle = reset ? (\n <style data-remote-components-reset=\"react\">{`:host { all: initial; }`}</style>\n ) : null;\n const linksToRender: React.ReactNode[] | null =\n data?.links?.map((link) => (\n <link\n {...link}\n href={new URL(link.href as string, url).href}\n key={JSON.stringify(link)}\n />\n )) || null;\n const componentToRender = (\n <>\n {resetStyle}\n {linksToRender}\n {remoteComponent ?? children}\n </>\n );\n\n if (componentHydrationHtml.current && shadowRoot && !shadowRoot.innerHTML) {\n shadowRoot.innerHTML = componentHydrationHtml.current;\n componentHydrationHtml.current = null;\n\n if (hostStateRef.current.prevIsRemoteComponent) {\n // ensure we load static resources when hydrating a remote component in shadow DOM\n loadStaticRemoteComponent(\n Array.from(shadowRoot.querySelectorAll('script')),\n url,\n resolveClientUrl,\n )\n .then(({ mount }) => {\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(shadowRoot)),\n );\n })\n .then(() => {\n if (src) {\n onLoad?.(src);\n }\n })\n .catch((e) => {\n const error = new RemoteComponentsError(\n `Error mounting remote component from \"${url.href}\"`,\n {\n cause: e,\n },\n );\n setRemoteComponent(error);\n onError?.(error);\n });\n }\n }\n\n if (isolate !== false) {\n const shadowRemoteComponentHtml =\n shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ??\n shadowRoot?.querySelector('div[data-bundle][data-route]');\n if (shadowRemoteComponentHtml) {\n shadowRemoteComponentHtml.remove();\n }\n\n return (\n <>\n {metadataJson}\n <div\n data-remote-component-id={`shadowroot_${keySuffix}`}\n id={`shadowroot_${data?.name ?? name}`}\n ref={shadowRootContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode={mode}>\n {typeof document === 'undefined' ? (\n <div\n dangerouslySetInnerHTML={{\n __html: `<img\n alt=\"\" decoding=\"async\" style=\"display:none\"\n src=\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==\"\n onload=\"(function(el){\n // Capture the shadow root during SSR hydration so the client-side\n // useShadowRoot hook can find it.\n const root = el.getRootNode();\n globalThis.__remote_components_shadowroot_${keySuffix}=root;\n el.parentElement.remove();\n })(this)\"\n />`,\n }}\n />\n ) : null}\n {resetStyle}\n {linksToRender}\n {children}\n </template>\n ) : null}\n {shadowRoot && remoteComponent\n ? createPortal(\n <>\n <template id={`${name}_start`} />\n {resetStyle}\n {linksToRender}\n {remoteComponent}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>,\n shadowRoot,\n )\n : null}\n </div>\n </>\n );\n }\n htmlRef.current = null;\n\n // render start/end markers for the remote component\n return (\n <>\n <template id={`${name}_start`} />\n {metadataJson}\n {componentToRender}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>\n );\n}\n\nexport type {\n HookOptions,\n OnRequestHook,\n OnResponseHook,\n} from '#internal/host/shared/fetch-interceptors';\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","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","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 { 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","/**\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 {\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 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","// extracted from Next.js source at https://github.com/vercel/next.js/blob/canary/packages/next/src/client/set-attributes-from-props.ts\n\nconst DOMAttributeNames: Record<string, string> = {\n acceptCharset: 'accept-charset',\n className: 'class',\n htmlFor: 'for',\n httpEquiv: 'http-equiv',\n noModule: 'noModule',\n};\n\nconst ignoreProps = [\n 'onLoad',\n 'onReady',\n 'dangerouslySetInnerHTML',\n 'children',\n 'onError',\n 'strategy',\n 'stylesheets',\n];\n\nfunction isBooleanScriptAttribute(\n attr: string,\n): attr is 'async' | 'defer' | 'noModule' {\n return ['async', 'defer', 'noModule'].includes(attr);\n}\n\nexport function setAttributesFromProps(el: HTMLElement, props: object) {\n for (const [p, value] of Object.entries(props)) {\n if (!Object.hasOwn(props, p)) continue;\n if (ignoreProps.includes(p)) continue;\n\n // we don't render undefined props to the DOM\n if (value === undefined) {\n continue;\n }\n\n const attr = DOMAttributeNames[p] || p.toLowerCase();\n\n if (el.tagName === 'SCRIPT' && isBooleanScriptAttribute(attr)) {\n // Correctly assign boolean script attributes\n // https://github.com/vercel/next.js/pull/20748\n (el as HTMLScriptElement)[attr] = Boolean(value);\n } else {\n el.setAttribute(attr, String(value));\n }\n\n // Remove falsy non-zero boolean attributes so they are correctly interpreted\n // (e.g. if we set them to false, this coerces to the string \"false\", which the browser interprets as true)\n if (\n value === false ||\n (el.tagName === 'SCRIPT' &&\n isBooleanScriptAttribute(attr) &&\n (!value || value === 'false'))\n ) {\n // Call setAttribute before, as we need to set and unset the attribute to override force async:\n // https://html.spec.whatwg.org/multipage/scripting.html#script-force-async\n el.setAttribute(attr, '');\n el.removeAttribute(attr);\n }\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","// 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 { 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 * Single import hub for all React Server Components runtime modules.\n *\n * Each function encapsulates the try/catch fallback chain that probes\n * Next.js internal paths first, then falls back to the public\n * `react-server-dom-webpack` / `react-server-dom-turbopack` packages.\n * This keeps version-specific import paths out of business logic.\n */\n\nimport type {\n RSCClientBrowserRuntime,\n RSCClientEdgeRuntime,\n RSCServerRuntime,\n} from './rsc-runtime';\n\n/**\n * Imports the RSC client for the **edge** runtime (server-side).\n * Used by `fetch-remote-component.ts` to deserialise RSC flight data.\n *\n * Tries the Next.js compiled path first, falls back to the bare\n * `react-server-dom-webpack/client.edge` module.\n */\nexport async function importRSCClientEdge(): Promise<RSCClientEdgeRuntime> {\n try {\n return await import(\n 'next/dist/compiled/react-server-dom-webpack/client.edge'\n );\n } catch {\n return await import('react-server-dom-webpack/client.edge');\n }\n}\n\n/**\n * Imports the RSC client for the **browser** runtime (client-side hydration).\n * Used by `component-loader.ts` to hydrate RSC streams in the browser.\n *\n * Tries the Next.js compiled path first, falls back to the bare\n * `react-server-dom-webpack/client.browser` module (which may use a\n * default export depending on the package version).\n */\nexport async function importRSCClientBrowser(): Promise<RSCClientBrowserRuntime> {\n try {\n return await import(\n 'next/dist/compiled/react-server-dom-webpack/client.browser'\n );\n } catch {\n const mod = await import('react-server-dom-webpack/client.browser');\n // Some versions export `createFromReadableStream` as a default export\n return (mod.default ?? mod) as RSCClientBrowserRuntime;\n }\n}\n\n/**\n * Imports the RSC **server** renderer for `ExposeRemoteComponent`.\n *\n * When `TURBOPACK` is set in the environment, imports from\n * `react-server-dom-turbopack`; otherwise uses `react-server-dom-webpack`.\n * Each variant tries the primary path first (`/server`), falling back to\n * the `.edge` entry point.\n */\nexport async function importRSCServer(): Promise<RSCServerRuntime> {\n const [primary, fallback] = await Promise.all(\n process.env.TURBOPACK\n ? [\n tryImport<RSCServerRuntime>(\n () => import('react-server-dom-turbopack/server'),\n ),\n tryImport<RSCServerRuntime>(\n () => import('react-server-dom-turbopack/server.edge'),\n ),\n ]\n : [\n tryImport<RSCServerRuntime>(\n () => import('react-server-dom-webpack/server'),\n ),\n tryImport<RSCServerRuntime>(\n () => import('react-server-dom-webpack/server.edge'),\n ),\n ],\n );\n\n return {\n renderToReadableStream:\n primary.renderToReadableStream ?? fallback.renderToReadableStream,\n };\n}\n\nasync function tryImport<T>(importer: () => Promise<T>): Promise<T> {\n try {\n return await importer();\n } catch {\n return {} as T;\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 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 { useMemo } from 'react';\nimport { useRemoteComponentsContext } from '#internal/host/react/context';\nimport { bindResolveClientUrl } from '#internal/runtime/url/default-resolve-client-url';\nimport type { ResolveClientUrl } from '#internal/runtime/url/resolve-client-url';\n\nexport function useResolveClientUrl(\n prop: ResolveClientUrl | undefined,\n urlHref: string,\n) {\n const { resolveClientUrl: contextValue } = useRemoteComponentsContext();\n const raw = prop ?? contextValue;\n return useMemo(() => bindResolveClientUrl(raw, urlHref), [raw, urlHref]);\n}\n","import { useLayoutEffect, useRef, useState } from 'react';\nimport { getNamespace } from '#internal/runtime/namespace';\n\ninterface UseShadowRootOptions {\n /** Whether CSS isolation is enabled */\n isolate: boolean | undefined;\n /** Shadow DOM mode */\n mode: 'open' | 'closed';\n /** Unique key suffix for identifying this shadow root */\n keySuffix: string;\n}\n\ninterface UseShadowRootResult {\n /** The shadow root element, or null if not isolated */\n shadowRoot: ShadowRoot | null;\n /** Ref to attach to the shadow host container element */\n shadowRootContainerRef: React.RefObject<HTMLDivElement | null>;\n}\n\n/**\n * Manages shadow root lifecycle for CSS isolation.\n *\n * Handles:\n * - Initial shadow root discovery from SSR or declarative shadow DOM\n * - Creating shadow root as fallback for browsers without declarative shadow DOM support\n * - Cleanup when isolation is disabled\n * - Re-attachment when isolation is re-enabled\n */\nexport function useShadowRoot({\n isolate,\n mode,\n keySuffix,\n}: UseShadowRootOptions): UseShadowRootResult {\n const shadowRootContainerRef = useRef<HTMLDivElement | null>(null);\n\n const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(() => {\n const shadowRoots = getNamespace().shadowRoots;\n const ssrShadowRoot =\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n )?.shadowRoot ??\n shadowRoots[keySuffix] ??\n null)\n : null;\n // Clear the reference after reading it\n shadowRoots[keySuffix] = null;\n return ssrShadowRoot;\n });\n\n useLayoutEffect(() => {\n const shadowRoots = getNamespace().shadowRoots;\n if (\n isolate !== false &&\n typeof document !== 'undefined' &&\n (!shadowRoot || !shadowRoot.isConnected)\n ) {\n let shadowRootElement: ShadowRoot | null = null;\n const element = document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n );\n shadowRootElement = shadowRoots[keySuffix] ?? element?.shadowRoot ?? null;\n\n if (!shadowRootElement && element) {\n // Create a shadow root if it doesn't exist.\n // This is a fallback for browsers that don't support declarative shadow DOM.\n try {\n shadowRootElement = element.attachShadow({ mode });\n shadowRoots[keySuffix] = shadowRootElement;\n } catch {\n // Do nothing if attachShadow fails because of existing shadow root\n }\n }\n\n if (shadowRootElement) {\n // Remove all nodes from the shadow root except links (preserves stylesheets)\n shadowRootElement.querySelectorAll('*:not(link)').forEach((node) => {\n node.remove();\n });\n setShadowRoot(shadowRootElement);\n }\n } else if (isolate === false && shadowRoot) {\n shadowRoots[keySuffix] = null;\n setShadowRoot(null);\n }\n }, [isolate, shadowRoot, mode, keySuffix]);\n\n return { shadowRoot, shadowRootContainerRef };\n}\n","import { DEFAULT_COMPONENT_NAME } from '#internal/runtime/constants';\n\n/**\n * Dummy URL used as a fallback base for URL parsing when no real base URL is available.\n * This is used during SSR or when location is not defined.\n */\nexport const DUMMY_FALLBACK = 'http://remote-components-dummy-fallback';\n\n/**\n * Extracts the relevant HTML content from a remote component response.\n *\n * Handles multiple remote component formats:\n * - Next.js Pages Router SSR wrapper (`div[id^=\"__REMOTE_COMPONENT\"]`)\n * - App Router remote components (`div[data-bundle][data-route]`)\n * - Next.js pages (`div#__next`)\n * - Web component format (`remote-component:not([src])`)\n *\n * @param html - Raw HTML string from the remote component response\n * @returns Extracted HTML content with links and scripts, or empty string if not found\n */\nexport function getRemoteComponentHtml(html: string): string {\n if (typeof document === 'undefined') return html;\n\n const parser = new DOMParser();\n const temp = parser.parseFromString(html, 'text/html');\n\n // Used by the Next.js Pages Router remote as a wrapper\n const ssrRemoteComponentContainer = temp.querySelector(\n 'div[id^=\"__REMOTE_COMPONENT\"]',\n );\n if (ssrRemoteComponentContainer) {\n return ssrRemoteComponentContainer.innerHTML;\n }\n\n // Remote component content from various sources\n const remoteComponentContainer = temp.querySelectorAll(\n `div[data-bundle][data-route][data-runtime][id^=\"${DEFAULT_COMPONENT_NAME}\"],div[data-bundle][data-route],div#__next,remote-component:not([src])`,\n );\n if (remoteComponentContainer.length > 0) {\n return `${Array.from(temp.querySelectorAll('link,script'))\n .map((link) => link.outerHTML)\n .join('')}${Array.from(remoteComponentContainer)\n .map((container) => container.outerHTML)\n .join('')}`;\n }\n\n return '';\n}\n","import type { NavigateOptions } from 'next/dist/shared/lib/app-router-context.shared-runtime';\nimport { usePathname, useSearchParams } from 'next/navigation';\nimport { logWarn } from '#internal/utils/logger';\n\nexport const routerImpl = async () => {\n const { useRouter } = await import('next/navigation');\n return Promise.resolve({\n useRouter: () => {\n const router = useRouter();\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const query = Object.fromEntries(searchParams.entries());\n return {\n pathname,\n query,\n asPath: searchParams.toString()\n ? `${pathname}?${searchParams.toString()}`\n : pathname,\n push: (href: string, _: string, options?: NavigateOptions) => {\n router.push(href, options);\n return Promise.resolve(true);\n },\n replace: (href: string, _: string, options?: NavigateOptions) => {\n router.replace(href, options);\n return Promise.resolve(true);\n },\n refresh: () => Promise.resolve(router.refresh()),\n prefetch: async () => {\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.prefetch() in a remote component loaded in the Next.js App Router. prefetch() is a no-op in the App Router.',\n );\n return Promise.resolve();\n },\n back: () => {\n // there's no back() in the App Router\n if (typeof window !== 'undefined') {\n window.history.back();\n }\n },\n reload: () => {\n router.refresh();\n },\n beforePopState: () => {\n // there's no beforePopState() in the App Router\n },\n events: {\n on: () => {\n // there's no router.events in the App Router\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.events.on() in a remote component loaded in the Next.js App Router. events.on() is a no-op in the App Router.',\n );\n },\n off: () => {\n // there's no router.events in the App Router\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.events.off() in a remote component loaded in the Next.js App Router. events.off() is a no-op in the App Router.',\n );\n },\n emit: () => {\n // there's no router.events in the App Router\n logWarn(\n 'NextAppRouterCompat',\n 'You are using router.events.emit() in a remote component loaded in the Next.js App Router. events.emit() is a no-op in the App Router.',\n );\n },\n },\n };\n },\n });\n};\n"],"mappings":";;;;;;;;;;;;AAAA,IAAa,oCAEA,gCAGA;AALb;AAAA;AAAA;AAAO,IAAM,qCAAqC;AAE3C,IAAM,iCACX;AAEK,IAAM,gBACX;AAAA;AAAA;;;ACNF,IAEa;AAFb;AAAA;AAAA;AAAA;AAEO,IAAM,SAAiD;AAAA,MAC5D,sCAAsC,MACpC,QAAQ,OAAO,IAAI,MAAM,8BAA8B,CAAC;AAAA,IAC5D;AAAA;AAAA;;;ACLA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGA,SAAS,WAAAA,gBAAe;;;ACHxB,SAAS,eAAe,kBAAkB;;;ACAnC,SAAS,aAAa,KAAa;AACxC,SAAO,IAAI,QAAQ,cAAc,GAAG;AACtC;AAYO,SAAS,kBACd,MACA,SACQ;AACR,SAAO,QAAQ,gBACX,GAAG,QAAQ,aAAa,QAAQ,WAAW,YAAY,CAAC,MACxD;AACN;AAEO,IAAM,aAAa;AAAA,EACxB,eAAe;AAAA,EACf,aAAa;AAAA,EACb,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,QAAQ;AACV;;;AC3BO,IAAM,sBAAsB;AAC5B,IAAM,yBAAyB;AAC/B,IAAM,gBAAgB;AAEtB,IAAM,kBAAkB;AACxB,IAAM,oB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ACA,KAAK,MAAM;AAET;AAAA,cACE;AAAA,cACA;AAAA,YACF;AAAA,UACF;AAAA,UACA,MAAM,MAAM;AAEV;AAAA,cACE;AAAA,cACA;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACH;;;A5CdI,gBAAAQ,YAAA;AA3CJ,IAAM,gBAAgB,OACpB,YACA,qBACG;AACH,QAAM,CAAC,gBAAgB,kBAAkB,IAAI,MAAM,QAAQ,IAAI;AAAA,IAC7D,gBAAgB;AAAA,IAChB,cAAc,QAAQ,QAAQ,CAAC,CAAC;AAAA,EAClC,CAAC;AACD,SAAO;AAAA,IACL,GAAG;AAAA,IACH,eAAe;AAAA,IACf,GAAG,+BAA+B,EAAE,SAAS,iBAAiB,CAAC;AAAA,IAC/D,GAAG;AAAA,EACL;AACF;AAkBO,SAAS,+BAA+B;AAAA,EAC7C,QAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAA4D;AAC1D,QAAM,eAAeC;AAAA,IACnB,MAAM,cAAcD,SAAQ,gBAAgB;AAAA,IAC5C,CAACA,SAAQ,gBAAgB;AAAA,EAC3B;AACA,SACE,gBAAAD;AAAA,IAAC;AAAA;AAAA,MACC,OAAO,EAAE,QAAQ,cAAc,kBAAkB,GAAG,MAAM;AAAA,MAEzD;AAAA;AAAA,EACH;AAEJ;AAWO,SAASG,wBAAuB,OAAoC;AACzE,MAAI,OAAO,MAAM,QAAQ,YAAY,EAAE,MAAM,eAAe,MAAM;AAChE,WAAO,MAAM,YAAY;AAAA,EAC3B;AAEA,SACE,gBAAAH;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ,QAAQ,cAAc,MAAM,QAAQ,MAAM,gBAAgB;AAAA;AAAA,EAC5D;AAEJ;","names":["useMemo","location","location","shared","useLayoutEffect","useMemo","useRef","useState","useRemoteComponentsContext","shared","shared","scope","shared","jsx","createElement","useRemoteComponentsContext","shared","useMemo","useState","useRef","useLayoutEffect","jsx","shared","useMemo","ConsumeRemoteComponent"]}