remote-components 0.4.3 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/dist/{chunk-C5EYU7EQ.cjs → chunk-4MLJE6UP.cjs} +3 -3
  2. package/dist/{chunk-SECN7UAL.cjs → chunk-7OD5S534.cjs} +18 -18
  3. package/dist/{chunk-7XXO2DLF.cjs → chunk-I7VKDF3E.cjs} +115 -77
  4. package/dist/chunk-I7VKDF3E.cjs.map +1 -0
  5. package/dist/{chunk-55TEMSB5.js → chunk-JZRA6DPE.js} +116 -78
  6. package/dist/chunk-JZRA6DPE.js.map +1 -0
  7. package/dist/{chunk-HYVNEUIK.js → chunk-MJ2KYXGR.js} +3 -3
  8. package/dist/{chunk-KV5J7PNM.js → chunk-NZM2SI6U.js} +3 -3
  9. package/dist/{chunk-DGZVFKSQ.js → chunk-O4A6CJGI.js} +19 -11
  10. package/dist/chunk-O4A6CJGI.js.map +1 -0
  11. package/dist/{chunk-2W7JBTID.cjs → chunk-PNASFKWA.cjs} +39 -31
  12. package/dist/chunk-PNASFKWA.cjs.map +1 -0
  13. package/dist/{chunk-4NW46ZVD.js → chunk-PT3R275L.js} +93 -38
  14. package/dist/chunk-PT3R275L.js.map +1 -0
  15. package/dist/{chunk-4AH3KXDW.cjs → chunk-TWO3XB6H.cjs} +19 -19
  16. package/dist/{chunk-HMB3SIVJ.cjs → chunk-W5FSHVWU.cjs} +107 -52
  17. package/dist/chunk-W5FSHVWU.cjs.map +1 -0
  18. package/dist/{chunk-HL6BL5HY.js → chunk-WGSS7TJP.js} +2 -2
  19. package/dist/config/nextjs.cjs +98 -30
  20. package/dist/config/nextjs.cjs.map +1 -1
  21. package/dist/config/nextjs.d.ts +14 -1
  22. package/dist/config/nextjs.js +89 -21
  23. package/dist/config/nextjs.js.map +1 -1
  24. package/dist/host/html.cjs +19 -19
  25. package/dist/host/html.cjs.map +1 -1
  26. package/dist/host/html.js +7 -7
  27. package/dist/host/html.js.map +1 -1
  28. package/dist/host/nextjs/app/client-only.cjs +11 -11
  29. package/dist/host/nextjs/app/client-only.js +6 -6
  30. package/dist/host/nextjs/pages.cjs +32 -9
  31. package/dist/host/nextjs/pages.cjs.map +1 -1
  32. package/dist/host/nextjs/pages.js +39 -9
  33. package/dist/host/nextjs/pages.js.map +1 -1
  34. package/dist/host/react.cjs +7 -7
  35. package/dist/host/react.js +6 -6
  36. package/dist/internal/host/nextjs/app-client.d.ts +3 -1
  37. package/dist/internal/host/nextjs/dom-flight.cjs +17 -2
  38. package/dist/internal/host/nextjs/dom-flight.cjs.map +1 -1
  39. package/dist/internal/host/nextjs/dom-flight.d.ts +5 -1
  40. package/dist/internal/host/nextjs/dom-flight.js +18 -2
  41. package/dist/internal/host/nextjs/dom-flight.js.map +1 -1
  42. package/dist/internal/host/server/fetch-remote-component.cjs +4 -2
  43. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  44. package/dist/internal/host/server/fetch-remote-component.d.ts +2 -0
  45. package/dist/internal/host/server/fetch-remote-component.js +4 -2
  46. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  47. package/dist/internal/host/server/types.cjs.map +1 -1
  48. package/dist/internal/host/server/types.d.ts +4 -1
  49. package/dist/internal/host/shared/pipeline.cjs +7 -8
  50. package/dist/internal/host/shared/pipeline.cjs.map +1 -1
  51. package/dist/internal/host/shared/pipeline.d.ts +5 -3
  52. package/dist/internal/host/shared/pipeline.js +9 -8
  53. package/dist/internal/host/shared/pipeline.js.map +1 -1
  54. package/dist/internal/host/shared/shared-broker.cjs +51 -10
  55. package/dist/internal/host/shared/shared-broker.cjs.map +1 -1
  56. package/dist/internal/host/shared/shared-broker.d.ts +19 -3
  57. package/dist/internal/host/shared/shared-broker.js +48 -10
  58. package/dist/internal/host/shared/shared-broker.js.map +1 -1
  59. package/dist/internal/host/shared/shared-module-resolver.cjs.map +1 -1
  60. package/dist/internal/host/shared/shared-module-resolver.d.ts +2 -2
  61. package/dist/internal/host/shared/shared-module-resolver.js.map +1 -1
  62. package/dist/internal/remote/nextjs/app-client.cjs +28 -19
  63. package/dist/internal/remote/nextjs/app-client.cjs.map +1 -1
  64. package/dist/internal/remote/nextjs/app-client.d.ts +6 -1
  65. package/dist/internal/remote/nextjs/app-client.js +20 -11
  66. package/dist/internal/remote/nextjs/app-client.js.map +1 -1
  67. package/dist/internal/runtime/html/html-spec.cjs +6 -0
  68. package/dist/internal/runtime/html/html-spec.cjs.map +1 -1
  69. package/dist/internal/runtime/html/html-spec.d.ts +3 -1
  70. package/dist/internal/runtime/html/html-spec.js +4 -0
  71. package/dist/internal/runtime/html/html-spec.js.map +1 -1
  72. package/dist/internal/runtime/html/parse-remote-html.cjs +7 -1
  73. package/dist/internal/runtime/html/parse-remote-html.cjs.map +1 -1
  74. package/dist/internal/runtime/html/parse-remote-html.d.ts +5 -3
  75. package/dist/internal/runtime/html/parse-remote-html.js +9 -1
  76. package/dist/internal/runtime/html/parse-remote-html.js.map +1 -1
  77. package/dist/internal/runtime/loaders/component-loader.cjs.map +1 -1
  78. package/dist/internal/runtime/loaders/component-loader.d.ts +4 -2
  79. package/dist/internal/runtime/loaders/component-loader.js.map +1 -1
  80. package/dist/internal/runtime/turbopack/chunk-loader.cjs +39 -23
  81. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  82. package/dist/internal/runtime/turbopack/chunk-loader.js +39 -23
  83. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  84. package/dist/internal/runtime/turbopack/patterns.cjs +15 -5
  85. package/dist/internal/runtime/turbopack/patterns.cjs.map +1 -1
  86. package/dist/internal/runtime/turbopack/patterns.d.ts +10 -2
  87. package/dist/internal/runtime/turbopack/patterns.js +13 -4
  88. package/dist/internal/runtime/turbopack/patterns.js.map +1 -1
  89. package/dist/internal/runtime/turbopack/shared-modules.cjs +39 -10
  90. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  91. package/dist/internal/runtime/turbopack/shared-modules.d.ts +2 -2
  92. package/dist/internal/runtime/turbopack/shared-modules.js +43 -11
  93. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  94. package/dist/remote/defaults/app.cjs +4 -2
  95. package/dist/remote/defaults/app.cjs.map +1 -1
  96. package/dist/remote/defaults/app.d.ts +3 -1
  97. package/dist/remote/defaults/app.js +3 -2
  98. package/dist/remote/defaults/app.js.map +1 -1
  99. package/dist/remote/defaults/pages.cjs +4 -2
  100. package/dist/remote/defaults/pages.cjs.map +1 -1
  101. package/dist/remote/defaults/pages.d.ts +3 -1
  102. package/dist/remote/defaults/pages.js +3 -2
  103. package/dist/remote/defaults/pages.js.map +1 -1
  104. package/dist/remote/defaults/shared.cjs +5 -2
  105. package/dist/remote/defaults/shared.cjs.map +1 -1
  106. package/dist/remote/defaults/shared.d.ts +5 -1
  107. package/dist/remote/defaults/shared.js +3 -1
  108. package/dist/remote/defaults/shared.js.map +1 -1
  109. package/dist/remote/nextjs/pages.cjs +4 -1
  110. package/dist/remote/nextjs/pages.cjs.map +1 -1
  111. package/dist/remote/nextjs/pages.d.ts +5 -0
  112. package/dist/remote/nextjs/pages.js +8 -2
  113. package/dist/remote/nextjs/pages.js.map +1 -1
  114. package/dist/{server-handoff-8c89b856.d.ts → server-handoff-9e905049.d.ts} +2 -1
  115. package/dist/{turbopack-7F757Z7V.js → turbopack-55EJDSUT.js} +4 -4
  116. package/dist/turbopack-55EJDSUT.js.map +1 -0
  117. package/dist/{turbopack-DULMVTWV.cjs → turbopack-Q6KJAEOX.cjs} +11 -11
  118. package/dist/turbopack-Q6KJAEOX.cjs.map +1 -0
  119. package/dist/{webpack-WGVTKJ3W.js → webpack-AQ34DAJZ.js} +4 -4
  120. package/dist/webpack-AQ34DAJZ.js.map +1 -0
  121. package/dist/{webpack-6LXCB7WA.cjs → webpack-FWUNUWLF.cjs} +11 -11
  122. package/dist/webpack-FWUNUWLF.cjs.map +1 -0
  123. package/package.json +1 -1
  124. package/dist/chunk-2W7JBTID.cjs.map +0 -1
  125. package/dist/chunk-4NW46ZVD.js.map +0 -1
  126. package/dist/chunk-55TEMSB5.js.map +0 -1
  127. package/dist/chunk-7XXO2DLF.cjs.map +0 -1
  128. package/dist/chunk-DGZVFKSQ.js.map +0 -1
  129. package/dist/chunk-HMB3SIVJ.cjs.map +0 -1
  130. package/dist/turbopack-7F757Z7V.js.map +0 -1
  131. package/dist/turbopack-DULMVTWV.cjs.map +0 -1
  132. package/dist/webpack-6LXCB7WA.cjs.map +0 -1
  133. package/dist/webpack-WGVTKJ3W.js.map +0 -1
  134. /package/dist/{chunk-C5EYU7EQ.cjs.map → chunk-4MLJE6UP.cjs.map} +0 -0
  135. /package/dist/{chunk-SECN7UAL.cjs.map → chunk-7OD5S534.cjs.map} +0 -0
  136. /package/dist/{chunk-HYVNEUIK.js.map → chunk-MJ2KYXGR.js.map} +0 -0
  137. /package/dist/{chunk-KV5J7PNM.js.map → chunk-NZM2SI6U.js.map} +0 -0
  138. /package/dist/{chunk-4AH3KXDW.cjs.map → chunk-TWO3XB6H.cjs.map} +0 -0
  139. /package/dist/{chunk-HL6BL5HY.js.map → chunk-WGSS7TJP.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/host/html/index.tsx","../../src/host/html/attach-styles.ts","../../src/host/html/runtime/index.ts"],"sourcesContent":["import { startTransition, useLayoutEffect } from 'react';\nimport { hydrateRoot } from 'react-dom/client';\nimport { fetchWithHooks } from '#internal/host/server/fetch-with-hooks';\nimport { getClientOrServerUrl } from '#internal/host/server/get-client-or-server-url';\nimport type {\n ConsumeClientConfig,\n ConsumeServerConfig,\n} from '#internal/host/shared/config';\nimport {\n type LifecycleEmitter,\n makeEventEmitter,\n} from '#internal/host/shared/lifecycle';\nimport { preparePipeline } from '#internal/host/shared/pipeline';\nimport type { HostState } from '#internal/host/shared/state';\nimport { createHostState } from '#internal/host/shared/state';\nimport { resolveNameFromSrc } from '#internal/host/utils/resolve-name-from-src';\nimport {\n DEFAULT_BUNDLE_NAME,\n DEFAULT_COMPONENT_NAME,\n} from '#internal/runtime/constants';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport { createRSCStream } from '#internal/runtime/rsc';\nimport type { RSCKey } from '#internal/runtime/types';\nimport { bindResolveClientUrl } from '#internal/runtime/url/default-resolve-client-url';\nimport { escapeString } from '#internal/utils';\nimport { isAbortError } from '#internal/utils/abort';\nimport {\n errorFromFailedFetch,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport { logError } from '#internal/utils/logger';\nimport { attachStyles } from './attach-styles';\nimport { getRuntime, type Runtime } from './runtime';\n\nif (typeof HTMLElement !== 'undefined') {\n /**\n * `<remote-component>` custom element — the HTML host implementation.\n *\n * Implements {@link ConsumeClientConfig}\n * via typed property accessors that reflect to/from DOM attributes.\n *\n * {@link ConsumeLifecycleCallbacks} are dispatched as DOM events:\n * `beforeload`, `load`, `error`, `change`.\n */\n class RemoteComponent extends HTMLElement implements ConsumeClientConfig {\n name: string = DEFAULT_COMPONENT_NAME;\n bundle: string = DEFAULT_BUNDLE_NAME;\n fallbackSlot?: HTMLSlotElement;\n __next: HTMLDivElement | null = null;\n fouc: HTMLStyleElement | null = null;\n hostState: HostState = createHostState();\n root?: ShadowRoot | null = null;\n reactRoot?: ReturnType<typeof hydrateRoot>;\n emitter: LifecycleEmitter = makeEventEmitter(this);\n onRequest?: ConsumeServerConfig['onRequest'];\n onResponse?: ConsumeServerConfig['onResponse'];\n resolveClientUrl?: ConsumeClientConfig['resolveClientUrl'];\n\n // -- ConsumeServerConfig property accessors (attribute-reflected) --\n\n get src(): string | URL | undefined {\n return this.getAttribute('src') ?? undefined;\n }\n\n set src(value: string | URL | undefined) {\n if (value == null) {\n this.removeAttribute('src');\n } else {\n this.setAttribute('src', String(value));\n }\n }\n\n /** Always `true` — the HTML host always isolates via Shadow DOM. */\n get isolate(): boolean {\n return true;\n }\n\n get mode(): 'open' | 'closed' | undefined {\n const attr = this.getAttribute('mode');\n return attr === 'closed' ? 'closed' : 'open';\n }\n\n set mode(value: 'open' | 'closed' | undefined) {\n if (value) {\n this.setAttribute('mode', value);\n }\n }\n\n get reset(): boolean | undefined {\n return this.getAttribute('reset') !== null;\n }\n\n set reset(value: boolean | undefined) {\n if (value) {\n this.setAttribute('reset', '');\n } else {\n this.removeAttribute('reset');\n }\n }\n\n get credentials(): RequestCredentials | undefined {\n return (this.getAttribute('credentials') ||\n 'same-origin') as RequestCredentials;\n }\n\n set credentials(value: RequestCredentials | undefined) {\n if (value) {\n this.setAttribute('credentials', value);\n } else {\n this.removeAttribute('credentials');\n }\n }\n\n static get observedAttributes() {\n return ['src', 'name', 'mode'];\n }\n\n attributeChangedCallback(name: string, oldValue: string, newValue: string) {\n if ((name === 'src' || name === 'name') && oldValue !== newValue) {\n if (this.src) {\n this.load().catch((e) => {\n // AbortError is expected when loading is cancelled - don't log or dispatch\n if (isAbortError(e)) {\n return;\n }\n logError('HtmlHost', 'Error loading remote component.', e);\n this.emitter.error(e, this.src);\n this.hostState.stage = 'error';\n });\n }\n } else if (name === 'mode' && oldValue !== newValue && this.root) {\n // changing the shadow DOM mode is not supported\n // we need to recreate the shadow DOM and reload the component\n const newRoot = this.attachShadow({\n mode: newValue === 'closed' ? 'closed' : 'open',\n });\n // move all existing children to the new shadow root\n Array.from(this.root.children).forEach((child) => {\n newRoot.appendChild(child);\n });\n this.root = newRoot;\n // reload the remote component to apply the new shadow DOM\n this.load().catch((e) => {\n // AbortError is expected when loading is cancelled - don't log or dispatch\n if (isAbortError(e)) {\n return;\n }\n logError('HtmlHost', 'Error reloading remote component.', e);\n this.emitter.error(e, this.src);\n });\n }\n }\n\n async load() {\n // wait for the current call stack to finish\n await new Promise((resolve) => {\n (typeof queueMicrotask === 'function'\n ? queueMicrotask\n : requestAnimationFrame)(() => {\n resolve(undefined);\n });\n });\n\n // Abort any in-progress load so the latest src always wins.\n if (this.hostState.stage === 'loading') {\n this.hostState.abortController?.abort();\n this.hostState.stage = 'idle';\n // The aborted load may have already appended partial content to the shadow DOM\n // (styles, component children) before reaching an isCurrentLoad() check.\n // Clear it now so the new load starts from a clean state. Skip this when a\n // React root exists — that means a previous load completed successfully and\n // we'll take the startTransition re-render path instead.\n if (this.root && !this.reactRoot) {\n this.root.innerHTML = '';\n this.fouc = null;\n this.fallbackSlot = document.createElement('slot');\n this.root.appendChild(this.fallbackSlot);\n }\n }\n\n if (!this.root) {\n this.root = this.attachShadow({\n mode: this.mode === 'closed' ? 'closed' : 'open',\n });\n\n // create a slot element to allow the remote component to use the default slot\n this.fallbackSlot = document.createElement('slot');\n this.root.appendChild(this.fallbackSlot);\n }\n\n this.name = this.getAttribute('name') || this.name;\n\n this.hostState.stage = 'loading';\n const src = this.src;\n\n // Create AbortController for this load operation\n this.hostState.abortController = new AbortController();\n const signal = this.hostState.abortController.signal;\n\n // Returns true if this is still the active load — the signal hasn't been\n // aborted by a newer load() call, and the src hasn't changed in the meantime.\n // Checking the signal (not just the src) handles the case where the user\n // cycles back to the same src (e.g. styled → basic → styled): both loads\n // share the same src string, so a src-only check would pass for both,\n // causing double renders.\n const isCurrentLoad = () => !signal.aborted && this.src === src;\n\n // Resets stage to 'idle' for expected cancellations (AbortError). Real\n // errors are thrown and caught by attributeChangedCallback which sets\n // stage to 'error'. Only resets if no newer load() has superseded this\n // one — a new load replaces the abortController so the signal comparison\n // fails, preventing us from clobbering the new load's stage.\n const abandonLoad = () => {\n if (\n this.hostState.abortController?.signal === signal &&\n this.hostState.stage === 'loading'\n ) {\n this.hostState.stage = 'idle';\n }\n };\n\n this.emitter.beforeLoad(src ?? '');\n\n const remoteComponentChild =\n this.querySelector('div#__REMOTE_COMPONENT__') ||\n this.querySelector('div[data-bundle][data-route]');\n\n if (!src && !remoteComponentChild) {\n throw new RemoteComponentsError('\"src\" attribute is required');\n }\n\n let url: URL | null = null;\n let html = this.innerHTML;\n\n if (src) {\n url = getClientOrServerUrl(src, window.location.href);\n this.name = resolveNameFromSrc(src, this.name);\n }\n\n const resolveClientUrl = url\n ? bindResolveClientUrl(this.resolveClientUrl, url.href)\n : undefined;\n\n if (!remoteComponentChild && url) {\n // fetch the remote component\n const fetchInit = {\n credentials: this.credentials || 'same-origin',\n } as RequestInit;\n\n const resolvedUrl = new URL(\n resolveClientUrl?.(url.href) ?? url.href,\n window.location.href,\n );\n let res: Response;\n try {\n res = await fetchWithHooks(resolvedUrl, fetchInit, {\n onRequest: this.onRequest,\n onResponse: this.onResponse,\n abortController: this.hostState.abortController,\n });\n } catch (e) {\n if (isAbortError(e)) {\n return abandonLoad();\n }\n throw e;\n }\n\n if (!res || !res.ok) {\n throw await errorFromFailedFetch(url.href, resolvedUrl, res);\n }\n\n // get the full HTML content as a string - race with abort signal\n try {\n html = await res.text();\n } catch (e) {\n if (isAbortError(e)) {\n return abandonLoad();\n }\n throw e;\n }\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n }\n\n const effectiveUrl = url ?? new URL(window.location.href);\n const { doc, parsed } = preparePipeline({\n html,\n name: this.name,\n url: effectiveUrl,\n shared: {},\n resolveClientUrl,\n });\n const {\n component,\n name: resolvedName,\n isRemoteComponent,\n metadata: parsedMetadata,\n nextData,\n rsc,\n remoteShared,\n } = parsed;\n\n // when using a Next.js Pages Router remote application in development mode\n // we hide the remote component to prevent flickering\n // until the CSS is loaded for the remote component\n if (nextData && nextData.buildId === 'development' && !this.reactRoot) {\n this.fouc = document.createElement('style');\n this.fouc.textContent = `:host { display: none; }`;\n this.root.appendChild(this.fouc);\n }\n\n this.name = resolvedName;\n this.bundle = parsedMetadata.bundle;\n\n if (url) {\n getNamespace().bundleUrls[this.bundle] = url;\n }\n\n // add remote component metadata information at the custom element\n const metadataEl = document.createElement('script');\n metadataEl.type = 'application/json';\n metadataEl.setAttribute('data-remote-component', '');\n const metadataObj = {\n name: this.name,\n bundle: this.bundle,\n route: parsedMetadata.route,\n runtime: parsedMetadata.runtime,\n };\n metadataEl.textContent = JSON.stringify(metadataObj);\n\n if (\n this.previousElementSibling?.getAttribute('data-remote-component') !==\n null\n ) {\n this.previousElementSibling?.remove();\n }\n this.parentElement?.insertBefore(metadataEl, this);\n\n if (this.hostState.prevIsRemoteComponent) {\n if (this.hostState.prevUrl) {\n const prevUrl = this.hostState.prevUrl;\n const nsUnmount = getNamespace();\n if (nsUnmount.unmountFns[prevUrl.href]) {\n // call unmount() for all registered unmount functions for the previous remote component\n await Promise.all(\n Array.from(nsUnmount.unmountFns[prevUrl.href] ?? []).map(\n async (unmount) => {\n try {\n await unmount(this.root);\n } catch (e) {\n logError(\n 'HtmlHost',\n `Error while calling unmount() for Remote Component from ${prevUrl.href}.`,\n e,\n );\n }\n },\n ),\n );\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n }\n }\n this.root.innerHTML = '';\n }\n // Dispatch change event if this is not the first load\n if (this.hostState.prevSrc !== undefined) {\n this.emitter.change({\n previousSrc: this.hostState.prevSrc ?? null,\n nextSrc: src ?? null,\n previousName: this.hostState.prevName,\n nextName: this.name,\n });\n }\n\n this.hostState.prevUrl = effectiveUrl;\n this.hostState.prevIsRemoteComponent = isRemoteComponent;\n this.hostState.prevSrc = src;\n this.hostState.prevName = this.name;\n\n // store the original loading content of the custom element\n // this is required to remove the loading content after the remote component is loaded\n const removable = Array.from(this.childNodes);\n\n // reference to all link elements in the remote component\n const links = doc.querySelectorAll<HTMLLinkElement>('link[href]');\n\n const remoteComponentSrc = this.src ? String(this.src) : null;\n\n // Bound function for attaching styles — used both initially and in React effects\n const doAttachStyles = () =>\n attachStyles({\n doc,\n component,\n links,\n signal: undefined, // Effects run after load, no abort needed\n baseUrl: url?.href,\n remoteComponentSrc,\n root: this.root ?? null,\n resolveClientUrl,\n });\n\n if (!this.reactRoot) {\n // ensure all styles are loaded before hydrating to prevent FOUC\n await attachStyles({\n doc,\n component,\n links,\n signal,\n baseUrl: url?.href,\n remoteComponentSrc,\n root: this.root,\n resolveClientUrl,\n });\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n }\n\n if (!this.reactRoot) {\n // attach the remote component content to the shadow DOM\n Array.from(component.children).forEach((el) => {\n if (!isRemoteComponent && el.tagName.toLowerCase() === 'script') {\n const newScript = document.createElement('script');\n // copy all attributes\n for (const attr of el.attributes) {\n if (attr.name === 'src') {\n const absoluteSrc = new URL(\n attr.value,\n url ?? window.location.origin,\n ).href;\n newScript.setAttribute(\n attr.name,\n resolveClientUrl?.(absoluteSrc) ?? absoluteSrc,\n );\n } else {\n newScript.setAttribute(attr.name, attr.value);\n }\n }\n newScript.textContent = el.textContent;\n if (remoteComponentSrc) {\n newScript.setAttribute(\n 'data-remote-component-src',\n remoteComponentSrc,\n );\n }\n this.root?.appendChild(newScript);\n } else {\n const newEl = el.cloneNode(true) as HTMLElement;\n for (const attr of el.attributes) {\n if (attr.name.startsWith('on')) {\n newEl.setAttribute(attr.name, attr.value);\n }\n }\n this.root?.appendChild(newEl);\n }\n });\n }\n\n // clear the loading content of the shadow DOM root\n for (const el of removable) {\n el.parentElement?.removeChild(el);\n }\n this.fallbackSlot?.remove();\n\n // function to apply the reset styles to the shadow DOM\n const applyReset = () => {\n if (\n this.reset &&\n !this.root?.querySelector('link[data-remote-components-reset]')\n ) {\n // all initial styles to reset inherited styles leaking from the host page\n const allInitial = document.createElement('link');\n allInitial.setAttribute('data-remote-components-reset', '');\n const css = `:host { all: initial; }`;\n const allInitialHref = URL.createObjectURL(\n new Blob([css], { type: 'text/css' }),\n );\n allInitial.href = allInitialHref;\n allInitial.rel = 'stylesheet';\n // we need to revoke the object URL after the stylesheet is loaded to free up memory\n allInitial.onload = () => {\n URL.revokeObjectURL(allInitialHref);\n allInitial.removeAttribute('onload');\n };\n allInitial.onerror = () => {\n URL.revokeObjectURL(allInitialHref);\n allInitial.removeAttribute('onload');\n };\n this.root?.prepend(allInitial);\n } else if (\n !this.reset &&\n this.root?.querySelector('link[data-remote-components-reset]')\n ) {\n this.root\n .querySelector('link[data-remote-components-reset]')\n ?.remove();\n }\n };\n\n // apply the reset styles if required and not already applied\n if (!this.reactRoot) {\n applyReset();\n }\n\n const {\n self,\n createFromReadableStream,\n nextClientPagesLoader,\n preloadScripts,\n } = await getRuntime(\n metadataObj.runtime as Runtime,\n effectiveUrl,\n this.bundle,\n {\n react: async () => (await import('react')).default,\n 'react/jsx-dev-runtime': async () =>\n (await import('react/jsx-dev-runtime')).default,\n 'react/jsx-runtime': async () =>\n (await import('react/jsx-runtime')).default,\n 'react-dom': async () => (await import('react-dom')).default,\n 'react-dom/client': async () =>\n (await import('react-dom/client')).default,\n },\n remoteShared,\n resolveClientUrl,\n );\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n\n const scripts = isRemoteComponent\n ? component.querySelectorAll<HTMLScriptElement>('script')\n : doc.querySelectorAll<HTMLScriptElement>(\n 'script[src],script[data-src],script[data-remote-component-entrypoint]',\n );\n if (!url) {\n url = new URL(\n component.getAttribute('data-route') ?? '/',\n window.location.href,\n );\n }\n\n await preloadScripts(Array.from(scripts), url, this.bundle, this.name);\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n\n // remove all script elements from the shadow DOM to prevent re-execution of scripts\n if (isRemoteComponent) {\n Array.from(component.children).forEach((child) => {\n if (child.tagName === 'SCRIPT') {\n child.remove();\n }\n });\n }\n\n // cleanup previous remote component instances when a new remote component is loaded\n // this is required when the src attribute is changed to load a new remote component\n const doCleanup = () => {\n if (this.root && remoteComponentSrc) {\n const selector = `[data-remote-component-src]:not([data-remote-component-src=\"${remoteComponentSrc}\"])`;\n const prevCleanup = [\n ...this.root.querySelectorAll(selector),\n ...document.body.querySelectorAll(selector),\n ] as HTMLElement[];\n\n if (prevCleanup.length > 0) {\n prevCleanup.forEach((prev) => {\n prev.remove();\n });\n }\n }\n };\n\n // using RSC hydration if the RSC flight data is available\n if (rsc) {\n // remove the RSC flight data script element\n rsc.parentElement?.removeChild(rsc);\n\n // reload the RSC flight data script to eval it's content\n const rscName = `__remote_component_rsc_${escapeString(\n url.href,\n )}_${escapeString(this.name)}`;\n const rscClone = document.createElement('script');\n rscClone.id = `${rscName}_rsc`;\n rscClone.textContent =\n rsc.textContent?.replace(\n new RegExp(`self\\\\[\"${this.name}\"\\\\]`, 'g'),\n `self[\"${rscName}\"]`,\n ) ?? '';\n document.body.appendChild(rscClone);\n\n let cache: React.ReactNode;\n // React component to convert the RSC flight data into a React component\n const RemoteComponentFromReadableStream = ({\n name,\n initial,\n }: {\n name: string;\n initial: boolean;\n }) => {\n // convert the RSC flight data array into a ReadableStream\n // get the RSC flight data from the global scope\n // the RSC flight data is stored in an array\n // fallback to an empty RSC payload if the data is not found\n const stream = createRSCStream(\n rscName,\n self[rscName as RSCKey] ?? [`0:[null]\\n`],\n );\n const Component =\n cache ??\n // cache the component to avoid reloading the RSC flight data\n (cache = createFromReadableStream(stream) as React.ReactNode);\n\n useLayoutEffect(() => {\n // clear the RSC flight data from the global scope to free up memory\n if (self[name as RSCKey]) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete self[name as RSCKey];\n }\n const rscScript = document.getElementById(`${name}_rsc`);\n if (rscScript) {\n rscScript.remove();\n }\n\n doCleanup();\n applyReset();\n if (!initial) {\n doAttachStyles().catch((e: unknown) => {\n logError('HtmlHost', 'Error attaching styles.', e);\n });\n }\n if (isCurrentLoad()) {\n this.hostState.stage = 'loaded';\n }\n\n this.emitter.load(this.src ?? '');\n }, [initial, name]);\n\n // React can handle the component reference and will wait for the component to be ready\n return Component;\n };\n\n // when we already have a React root, we just need to render the new component\n if (this.reactRoot) {\n const root = this.reactRoot;\n startTransition(() => {\n root.render(\n <RemoteComponentFromReadableStream\n initial={false}\n name={this.name}\n />,\n );\n });\n return;\n }\n\n // hydrate the remote component using the RSC flight data\n this.reactRoot = hydrateRoot(\n // hydrateRoot expects a document or element, but it works for the shadow DOM too\n // @ts-expect-error support for shadow DOM\n this.root,\n <RemoteComponentFromReadableStream initial name={this.name} />,\n );\n } else if (nextData) {\n // using Next.js client pages loader if the Next.js hydration data is available\n const { Component, App } = nextClientPagesLoader(\n this.bundle,\n nextData.page ?? '/',\n this.root,\n );\n\n // if we have the component, we can hydrate it\n if (Component) {\n const RemoteComponentFromNext = ((\n NextApp: ReturnType<typeof nextClientPagesLoader>['App'],\n NextComponent: NonNullable<\n ReturnType<typeof nextClientPagesLoader>['Component']\n >,\n remoteComponent = this,\n ) =>\n function RemoteComponentNext({ initial }: { initial: boolean }) {\n useLayoutEffect(() => {\n doCleanup();\n if (!initial) {\n applyReset();\n doAttachStyles().catch((e: unknown) => {\n logError('HtmlHost', 'Error attaching styles.', e);\n });\n }\n if (isCurrentLoad()) {\n remoteComponent.hostState.stage = 'loaded';\n }\n\n remoteComponent.emitter.load(remoteComponent.src ?? '');\n }, [initial, remoteComponent]);\n\n return NextApp ? (\n <NextApp Component={NextComponent} {...nextData.props} />\n ) : (\n <NextComponent {...nextData.props} />\n );\n })(App, Component, this);\n\n // when we already have a React root, we just need to render the new component\n if (this.reactRoot) {\n const root = this.reactRoot;\n startTransition(() => {\n root.render(<RemoteComponentFromNext initial={false} />);\n doCleanup();\n if (isCurrentLoad()) {\n this.hostState.stage = 'loaded';\n }\n });\n return;\n }\n\n // hydrate the remote component using the Next.js pages router\n this.reactRoot = hydrateRoot(\n // hydrateRoot expects a document or element, but it works for the shadow DOM too\n // @ts-expect-error support for shadow DOM\n this.root,\n <RemoteComponentFromNext initial />,\n );\n }\n\n // remove the FOUC workaround style element to show the remote component\n // this is only for development mode\n if (this.fouc) {\n this.root.removeChild(this.fouc);\n }\n } else if (getNamespace().mountFns[url.href]) {\n // using script entrypoint when no RSC or Next.js data is available\n await Promise.all(\n Array.from(getNamespace().mountFns[url.href] ?? []).map(\n async (mount) => {\n try {\n await mount(this.root);\n } catch (e) {\n logError(\n 'HtmlHost',\n `Error while calling mount() for Remote Component from ${url.href}.`,\n e,\n );\n }\n },\n ),\n );\n\n this.emitter.load(this.src ?? '');\n } else {\n this.emitter.load(this.src ?? '');\n }\n\n if (isCurrentLoad()) {\n this.hostState.stage = 'loaded';\n }\n }\n }\n\n // register the custom element\n customElements.define('remote-component', RemoteComponent);\n}\n\nexport function registerSharedModules(\n modules: Record<string, () => Promise<unknown>> = {},\n) {\n const ns = getNamespace();\n Object.entries(modules).forEach(([key, value]) => {\n ns.hostSharedModules[key] = value;\n });\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\ninterface AttachStylesOptions {\n /** The parsed document containing link and style elements */\n doc: Document;\n /** The component element to check if links are already contained */\n component: Element;\n /** Links from the document head */\n links: NodeListOf<HTMLLinkElement>;\n /** AbortSignal to cancel loading */\n signal: AbortSignal | undefined;\n /** Base URL for resolving relative hrefs */\n baseUrl: string | undefined;\n /** Source URL to set as data attribute */\n remoteComponentSrc: string | null;\n /** Root element to append styles to (ShadowRoot or Element) */\n root: ShadowRoot | Element | null;\n /** Callback to transform asset URLs before loading */\n resolveClientUrl?: InternalResolveClientUrl;\n}\n\n/**\n * Attaches link and style elements from a remote component document to the shadow root.\n * Handles abort signals efficiently with a single shared listener for all links.\n *\n * @throws DOMException with name 'AbortError' if signal is aborted\n * @throws RemoteComponentsError if a stylesheet fails to load\n */\nexport async function attachStyles({\n doc,\n component,\n links,\n signal,\n baseUrl,\n remoteComponentSrc,\n root,\n resolveClientUrl,\n}: AttachStylesOptions): Promise<void> {\n // Track appended links for cleanup on abort\n const appendedLinks: HTMLLinkElement[] = [];\n\n // Single shared abort promise - avoids N listeners for N links\n let abortReject: ((error: DOMException) => void) | null = null;\n const abortPromise = new Promise<never>((_, reject) => {\n abortReject = reject;\n });\n const abortHandler = () => {\n // Clean up all pending links on abort\n for (const link of appendedLinks) {\n link.onload = null;\n link.onerror = null;\n link.remove();\n }\n abortReject?.(new DOMException('Aborted', 'AbortError'));\n };\n signal?.addEventListener('abort', abortHandler, { once: true });\n\n try {\n // Attach each link element to the shadow DOM to load the styles\n await Promise.all(\n Array.from(links)\n .filter((link) => !component.contains(link))\n .map((link) => {\n const newLink = document.createElement('link');\n appendedLinks.push(newLink);\n\n const loadPromise = new Promise<void>((resolve, reject) => {\n if (link.rel === 'stylesheet') {\n // TODO: needs to be cancellable with a singular listener for the abort signal https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\n newLink.onload = () => resolve();\n newLink.onerror = () =>\n reject(\n new RemoteComponentsError(\n `Failed to load <link href=\"${link.href}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n } else {\n resolve();\n }\n });\n\n for (const attr of link.attributes) {\n if (attr.name === 'href') {\n const absoluteHref = new URL(\n attr.value,\n baseUrl ?? location.origin,\n ).href;\n newLink.setAttribute(\n attr.name,\n resolveClientUrl?.(absoluteHref) ?? absoluteHref,\n );\n } else {\n newLink.setAttribute(attr.name, attr.value);\n }\n }\n\n if (remoteComponentSrc) {\n newLink.setAttribute(\n 'data-remote-component-src',\n remoteComponentSrc,\n );\n }\n\n // TODO: needs to be cancellable with a singular listener for the abort signal https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\n root?.appendChild(newLink);\n\n // Race each link load against the shared abort promise\n return Promise.race([loadPromise, abortPromise]);\n }),\n );\n } finally {\n signal?.removeEventListener('abort', abortHandler);\n }\n\n // Attach inline styles from the document head\n const styles = doc.querySelectorAll<HTMLStyleElement>('style');\n for (const style of styles) {\n if (style.parentElement?.tagName.toLowerCase() === 'head') {\n const newStyle = document.createElement('style');\n newStyle.textContent = style.textContent;\n\n if (remoteComponentSrc) {\n newStyle.setAttribute('data-remote-component-src', remoteComponentSrc);\n }\n\n root?.appendChild(newStyle);\n }\n }\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\nexport type Runtime = 'webpack' | 'turbopack' | 'script' | 'unknown';\n\nexport async function getRuntime(\n type: Runtime,\n url: URL,\n bundle: string,\n shared?: Record<string, () => Promise<unknown>>,\n remoteShared?: Record<string, string>,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n // minimally mock process.env for browser environments\n if (typeof globalThis.process === 'undefined') {\n globalThis.process = {\n env: {},\n } as NodeJS.Process;\n }\n\n if (type === 'webpack') {\n const { webpackRuntime } = await import(`./webpack`);\n return webpackRuntime(bundle, shared, remoteShared, resolveClientUrl);\n } else if (type === 'turbopack') {\n const { turbopackRuntime } = await import(`./turbopack`);\n return turbopackRuntime(\n url,\n bundle,\n shared,\n remoteShared,\n resolveClientUrl,\n );\n } else if (type === 'script') {\n const { scriptRuntime } = await import(`./script`);\n return scriptRuntime(resolveClientUrl);\n }\n throw new RemoteComponentsError(\n `Remote Components runtime \"${type}\" is not supported. Supported runtimes are \"webpack\", \"turbopack\", and \"script\".`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB,uBAAuB;AACjD,SAAS,mBAAmB;;;AC4B5B,eAAsB,aAAa;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAuC;AAErC,QAAM,gBAAmC,CAAC;AAG1C,MAAI,cAAsD;AAC1D,QAAM,eAAe,IAAI,QAAe,CAAC,GAAG,WAAW;AACrD,kBAAc;AAAA,EAChB,CAAC;AACD,QAAM,eAAe,MAAM;AAEzB,eAAW,QAAQ,eAAe;AAChC,WAAK,SAAS;AACd,WAAK,UAAU;AACf,WAAK,OAAO;AAAA,IACd;AACA,kBAAc,IAAI,aAAa,WAAW,YAAY,CAAC;AAAA,EACzD;AACA,UAAQ,iBAAiB,SAAS,cAAc,EAAE,MAAM,KAAK,CAAC;AAE9D,MAAI;AAEF,UAAM,QAAQ;AAAA,MACZ,MAAM,KAAK,KAAK,EACb,OAAO,CAAC,SAAS,CAAC,UAAU,SAAS,IAAI,CAAC,EAC1C,IAAI,CAAC,SAAS;AACb,cAAM,UAAU,SAAS,cAAc,MAAM;AAC7C,sBAAc,KAAK,OAAO;AAE1B,cAAM,cAAc,IAAI,QAAc,CAAC,SAAS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,CAAC,CAAC,KAAK,KAAK,MAAM;AAChD,OAAG,kBAAkB,GAAG,IAAI;AAAA,EAC9B,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/host/html/index.tsx","../../src/host/html/attach-styles.ts","../../src/host/html/runtime/index.ts"],"sourcesContent":["import { startTransition, useLayoutEffect } from 'react';\nimport { hydrateRoot } from 'react-dom/client';\nimport { fetchWithHooks } from '#internal/host/server/fetch-with-hooks';\nimport { getClientOrServerUrl } from '#internal/host/server/get-client-or-server-url';\nimport type {\n ConsumeClientConfig,\n ConsumeServerConfig,\n} from '#internal/host/shared/config';\nimport {\n type LifecycleEmitter,\n makeEventEmitter,\n} from '#internal/host/shared/lifecycle';\nimport { preparePipeline } from '#internal/host/shared/pipeline';\nimport type { HostState } from '#internal/host/shared/state';\nimport { createHostState } from '#internal/host/shared/state';\nimport { resolveNameFromSrc } from '#internal/host/utils/resolve-name-from-src';\nimport {\n DEFAULT_BUNDLE_NAME,\n DEFAULT_COMPONENT_NAME,\n} from '#internal/runtime/constants';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport { createRSCStream } from '#internal/runtime/rsc';\nimport type { RSCKey } from '#internal/runtime/types';\nimport { bindResolveClientUrl } from '#internal/runtime/url/default-resolve-client-url';\nimport { escapeString } from '#internal/utils';\nimport { isAbortError } from '#internal/utils/abort';\nimport {\n errorFromFailedFetch,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport { logError } from '#internal/utils/logger';\nimport { attachStyles } from './attach-styles';\nimport { getRuntime, type Runtime } from './runtime';\n\nif (typeof HTMLElement !== 'undefined') {\n /**\n * `<remote-component>` custom element — the HTML host implementation.\n *\n * Implements {@link ConsumeClientConfig}\n * via typed property accessors that reflect to/from DOM attributes.\n *\n * {@link ConsumeLifecycleCallbacks} are dispatched as DOM events:\n * `beforeload`, `load`, `error`, `change`.\n */\n class RemoteComponent extends HTMLElement implements ConsumeClientConfig {\n name: string = DEFAULT_COMPONENT_NAME;\n bundle: string = DEFAULT_BUNDLE_NAME;\n fallbackSlot?: HTMLSlotElement;\n __next: HTMLDivElement | null = null;\n fouc: HTMLStyleElement | null = null;\n hostState: HostState = createHostState();\n root?: ShadowRoot | null = null;\n reactRoot?: ReturnType<typeof hydrateRoot>;\n emitter: LifecycleEmitter = makeEventEmitter(this);\n onRequest?: ConsumeServerConfig['onRequest'];\n onResponse?: ConsumeServerConfig['onResponse'];\n resolveClientUrl?: ConsumeClientConfig['resolveClientUrl'];\n\n // -- ConsumeServerConfig property accessors (attribute-reflected) --\n\n get src(): string | URL | undefined {\n return this.getAttribute('src') ?? undefined;\n }\n\n set src(value: string | URL | undefined) {\n if (value == null) {\n this.removeAttribute('src');\n } else {\n this.setAttribute('src', String(value));\n }\n }\n\n /** Always `true` — the HTML host always isolates via Shadow DOM. */\n get isolate(): boolean {\n return true;\n }\n\n get mode(): 'open' | 'closed' | undefined {\n const attr = this.getAttribute('mode');\n return attr === 'closed' ? 'closed' : 'open';\n }\n\n set mode(value: 'open' | 'closed' | undefined) {\n if (value) {\n this.setAttribute('mode', value);\n }\n }\n\n get reset(): boolean | undefined {\n return this.getAttribute('reset') !== null;\n }\n\n set reset(value: boolean | undefined) {\n if (value) {\n this.setAttribute('reset', '');\n } else {\n this.removeAttribute('reset');\n }\n }\n\n get credentials(): RequestCredentials | undefined {\n return (this.getAttribute('credentials') ||\n 'same-origin') as RequestCredentials;\n }\n\n set credentials(value: RequestCredentials | undefined) {\n if (value) {\n this.setAttribute('credentials', value);\n } else {\n this.removeAttribute('credentials');\n }\n }\n\n static get observedAttributes() {\n return ['src', 'name', 'mode'];\n }\n\n attributeChangedCallback(name: string, oldValue: string, newValue: string) {\n if ((name === 'src' || name === 'name') && oldValue !== newValue) {\n if (this.src) {\n this.load().catch((e) => {\n // AbortError is expected when loading is cancelled - don't log or dispatch\n if (isAbortError(e)) {\n return;\n }\n logError('HtmlHost', 'Error loading remote component.', e);\n this.emitter.error(e, this.src);\n this.hostState.stage = 'error';\n });\n }\n } else if (name === 'mode' && oldValue !== newValue && this.root) {\n // changing the shadow DOM mode is not supported\n // we need to recreate the shadow DOM and reload the component\n const newRoot = this.attachShadow({\n mode: newValue === 'closed' ? 'closed' : 'open',\n });\n // move all existing children to the new shadow root\n Array.from(this.root.children).forEach((child) => {\n newRoot.appendChild(child);\n });\n this.root = newRoot;\n // reload the remote component to apply the new shadow DOM\n this.load().catch((e) => {\n // AbortError is expected when loading is cancelled - don't log or dispatch\n if (isAbortError(e)) {\n return;\n }\n logError('HtmlHost', 'Error reloading remote component.', e);\n this.emitter.error(e, this.src);\n });\n }\n }\n\n async load() {\n // wait for the current call stack to finish\n await new Promise((resolve) => {\n (typeof queueMicrotask === 'function'\n ? queueMicrotask\n : requestAnimationFrame)(() => {\n resolve(undefined);\n });\n });\n\n // Abort any in-progress load so the latest src always wins.\n if (this.hostState.stage === 'loading') {\n this.hostState.abortController?.abort();\n this.hostState.stage = 'idle';\n // The aborted load may have already appended partial content to the shadow DOM\n // (styles, component children) before reaching an isCurrentLoad() check.\n // Clear it now so the new load starts from a clean state. Skip this when a\n // React root exists — that means a previous load completed successfully and\n // we'll take the startTransition re-render path instead.\n if (this.root && !this.reactRoot) {\n this.root.innerHTML = '';\n this.fouc = null;\n this.fallbackSlot = document.createElement('slot');\n this.root.appendChild(this.fallbackSlot);\n }\n }\n\n if (!this.root) {\n this.root = this.attachShadow({\n mode: this.mode === 'closed' ? 'closed' : 'open',\n });\n\n // create a slot element to allow the remote component to use the default slot\n this.fallbackSlot = document.createElement('slot');\n this.root.appendChild(this.fallbackSlot);\n }\n\n this.name = this.getAttribute('name') || this.name;\n\n this.hostState.stage = 'loading';\n const src = this.src;\n\n // Create AbortController for this load operation\n this.hostState.abortController = new AbortController();\n const signal = this.hostState.abortController.signal;\n\n // Returns true if this is still the active load — the signal hasn't been\n // aborted by a newer load() call, and the src hasn't changed in the meantime.\n // Checking the signal (not just the src) handles the case where the user\n // cycles back to the same src (e.g. styled → basic → styled): both loads\n // share the same src string, so a src-only check would pass for both,\n // causing double renders.\n const isCurrentLoad = () => !signal.aborted && this.src === src;\n\n // Resets stage to 'idle' for expected cancellations (AbortError). Real\n // errors are thrown and caught by attributeChangedCallback which sets\n // stage to 'error'. Only resets if no newer load() has superseded this\n // one — a new load replaces the abortController so the signal comparison\n // fails, preventing us from clobbering the new load's stage.\n const abandonLoad = () => {\n if (\n this.hostState.abortController?.signal === signal &&\n this.hostState.stage === 'loading'\n ) {\n this.hostState.stage = 'idle';\n }\n };\n\n this.emitter.beforeLoad(src ?? '');\n\n const remoteComponentChild =\n this.querySelector('div#__REMOTE_COMPONENT__') ||\n this.querySelector('div[data-bundle][data-route]');\n\n if (!src && !remoteComponentChild) {\n throw new RemoteComponentsError('\"src\" attribute is required');\n }\n\n let url: URL | null = null;\n let html = this.innerHTML;\n\n if (src) {\n url = getClientOrServerUrl(src, window.location.href);\n this.name = resolveNameFromSrc(src, this.name);\n }\n\n const resolveClientUrl = url\n ? bindResolveClientUrl(this.resolveClientUrl, url.href)\n : undefined;\n\n if (!remoteComponentChild && url) {\n // fetch the remote component\n const fetchInit = {\n credentials: this.credentials || 'same-origin',\n } as RequestInit;\n\n const resolvedUrl = new URL(\n resolveClientUrl?.(url.href) ?? url.href,\n window.location.href,\n );\n let res: Response;\n try {\n res = await fetchWithHooks(resolvedUrl, fetchInit, {\n onRequest: this.onRequest,\n onResponse: this.onResponse,\n abortController: this.hostState.abortController,\n });\n } catch (e) {\n if (isAbortError(e)) {\n return abandonLoad();\n }\n throw e;\n }\n\n if (!res || !res.ok) {\n throw await errorFromFailedFetch(url.href, resolvedUrl, res);\n }\n\n // get the full HTML content as a string - race with abort signal\n try {\n html = await res.text();\n } catch (e) {\n if (isAbortError(e)) {\n return abandonLoad();\n }\n throw e;\n }\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n }\n\n const effectiveUrl = url ?? new URL(window.location.href);\n const { doc, parsed } = preparePipeline({\n html,\n name: this.name,\n url: effectiveUrl,\n shared: {},\n resolveClientUrl,\n });\n const {\n component,\n name: resolvedName,\n isRemoteComponent,\n metadata: parsedMetadata,\n nextData,\n rsc,\n remoteShared,\n } = parsed;\n\n // when using a Next.js Pages Router remote application in development mode\n // we hide the remote component to prevent flickering\n // until the CSS is loaded for the remote component\n if (nextData && nextData.buildId === 'development' && !this.reactRoot) {\n this.fouc = document.createElement('style');\n this.fouc.textContent = `:host { display: none; }`;\n this.root.appendChild(this.fouc);\n }\n\n this.name = resolvedName;\n this.bundle = parsedMetadata.bundle;\n\n if (url) {\n getNamespace().bundleUrls[this.bundle] = url;\n }\n\n // add remote component metadata information at the custom element\n const metadataEl = document.createElement('script');\n metadataEl.type = 'application/json';\n metadataEl.setAttribute('data-remote-component', '');\n const metadataObj = {\n name: this.name,\n bundle: this.bundle,\n route: parsedMetadata.route,\n runtime: parsedMetadata.runtime,\n };\n metadataEl.textContent = JSON.stringify(metadataObj);\n\n if (\n this.previousElementSibling?.getAttribute('data-remote-component') !==\n null\n ) {\n this.previousElementSibling?.remove();\n }\n this.parentElement?.insertBefore(metadataEl, this);\n\n if (this.hostState.prevIsRemoteComponent) {\n if (this.hostState.prevUrl) {\n const prevUrl = this.hostState.prevUrl;\n const nsUnmount = getNamespace();\n if (nsUnmount.unmountFns[prevUrl.href]) {\n // call unmount() for all registered unmount functions for the previous remote component\n await Promise.all(\n Array.from(nsUnmount.unmountFns[prevUrl.href] ?? []).map(\n async (unmount) => {\n try {\n await unmount(this.root);\n } catch (e) {\n logError(\n 'HtmlHost',\n `Error while calling unmount() for Remote Component from ${prevUrl.href}.`,\n e,\n );\n }\n },\n ),\n );\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n }\n }\n this.root.innerHTML = '';\n }\n // Dispatch change event if this is not the first load\n if (this.hostState.prevSrc !== undefined) {\n this.emitter.change({\n previousSrc: this.hostState.prevSrc ?? null,\n nextSrc: src ?? null,\n previousName: this.hostState.prevName,\n nextName: this.name,\n });\n }\n\n this.hostState.prevUrl = effectiveUrl;\n this.hostState.prevIsRemoteComponent = isRemoteComponent;\n this.hostState.prevSrc = src;\n this.hostState.prevName = this.name;\n\n // store the original loading content of the custom element\n // this is required to remove the loading content after the remote component is loaded\n const removable = Array.from(this.childNodes);\n\n // reference to all link elements in the remote component\n const links = doc.querySelectorAll<HTMLLinkElement>('link[href]');\n\n const remoteComponentSrc = this.src ? String(this.src) : null;\n\n // Bound function for attaching styles — used both initially and in React effects\n const doAttachStyles = () =>\n attachStyles({\n doc,\n component,\n links,\n signal: undefined, // Effects run after load, no abort needed\n baseUrl: url?.href,\n remoteComponentSrc,\n root: this.root ?? null,\n resolveClientUrl,\n });\n\n if (!this.reactRoot) {\n // ensure all styles are loaded before hydrating to prevent FOUC\n await attachStyles({\n doc,\n component,\n links,\n signal,\n baseUrl: url?.href,\n remoteComponentSrc,\n root: this.root,\n resolveClientUrl,\n });\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n }\n\n if (!this.reactRoot) {\n // attach the remote component content to the shadow DOM\n Array.from(component.children).forEach((el) => {\n if (!isRemoteComponent && el.tagName.toLowerCase() === 'script') {\n const newScript = document.createElement('script');\n // copy all attributes\n for (const attr of el.attributes) {\n if (attr.name === 'src') {\n const absoluteSrc = new URL(\n attr.value,\n url ?? window.location.origin,\n ).href;\n newScript.setAttribute(\n attr.name,\n resolveClientUrl?.(absoluteSrc) ?? absoluteSrc,\n );\n } else {\n newScript.setAttribute(attr.name, attr.value);\n }\n }\n newScript.textContent = el.textContent;\n if (remoteComponentSrc) {\n newScript.setAttribute(\n 'data-remote-component-src',\n remoteComponentSrc,\n );\n }\n this.root?.appendChild(newScript);\n } else {\n const newEl = el.cloneNode(true) as HTMLElement;\n for (const attr of el.attributes) {\n if (attr.name.startsWith('on')) {\n newEl.setAttribute(attr.name, attr.value);\n }\n }\n this.root?.appendChild(newEl);\n }\n });\n }\n\n // clear the loading content of the shadow DOM root\n for (const el of removable) {\n el.parentElement?.removeChild(el);\n }\n this.fallbackSlot?.remove();\n\n // function to apply the reset styles to the shadow DOM\n const applyReset = () => {\n if (\n this.reset &&\n !this.root?.querySelector('link[data-remote-components-reset]')\n ) {\n // all initial styles to reset inherited styles leaking from the host page\n const allInitial = document.createElement('link');\n allInitial.setAttribute('data-remote-components-reset', '');\n const css = `:host { all: initial; }`;\n const allInitialHref = URL.createObjectURL(\n new Blob([css], { type: 'text/css' }),\n );\n allInitial.href = allInitialHref;\n allInitial.rel = 'stylesheet';\n // we need to revoke the object URL after the stylesheet is loaded to free up memory\n allInitial.onload = () => {\n URL.revokeObjectURL(allInitialHref);\n allInitial.removeAttribute('onload');\n };\n allInitial.onerror = () => {\n URL.revokeObjectURL(allInitialHref);\n allInitial.removeAttribute('onload');\n };\n this.root?.prepend(allInitial);\n } else if (\n !this.reset &&\n this.root?.querySelector('link[data-remote-components-reset]')\n ) {\n this.root\n .querySelector('link[data-remote-components-reset]')\n ?.remove();\n }\n };\n\n // apply the reset styles if required and not already applied\n if (!this.reactRoot) {\n applyReset();\n }\n\n const {\n self,\n createFromReadableStream,\n nextClientPagesLoader,\n preloadScripts,\n } = await getRuntime(\n metadataObj.runtime as Runtime,\n effectiveUrl,\n this.bundle,\n {\n react: async () => (await import('react')).default,\n 'react/jsx-dev-runtime': async () =>\n (await import('react/jsx-dev-runtime')).default,\n 'react/jsx-runtime': async () =>\n (await import('react/jsx-runtime')).default,\n 'react-dom': async () => (await import('react-dom')).default,\n 'react-dom/client': async () =>\n (await import('react-dom/client')).default,\n },\n remoteShared,\n resolveClientUrl,\n );\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n\n const scripts = isRemoteComponent\n ? component.querySelectorAll<HTMLScriptElement>('script')\n : doc.querySelectorAll<HTMLScriptElement>(\n 'script[src],script[data-src],script[data-remote-component-entrypoint]',\n );\n if (!url) {\n url = new URL(\n component.getAttribute('data-route') ?? '/',\n window.location.href,\n );\n }\n\n await preloadScripts(Array.from(scripts), url, this.bundle, this.name);\n if (!isCurrentLoad()) {\n return abandonLoad();\n }\n\n // remove all script elements from the shadow DOM to prevent re-execution of scripts\n if (isRemoteComponent) {\n Array.from(component.children).forEach((child) => {\n if (child.tagName === 'SCRIPT') {\n child.remove();\n }\n });\n }\n\n // cleanup previous remote component instances when a new remote component is loaded\n // this is required when the src attribute is changed to load a new remote component\n const doCleanup = () => {\n if (this.root && remoteComponentSrc) {\n const selector = `[data-remote-component-src]:not([data-remote-component-src=\"${remoteComponentSrc}\"])`;\n const prevCleanup = [\n ...this.root.querySelectorAll(selector),\n ...document.body.querySelectorAll(selector),\n ] as HTMLElement[];\n\n if (prevCleanup.length > 0) {\n prevCleanup.forEach((prev) => {\n prev.remove();\n });\n }\n }\n };\n\n // using RSC hydration if the RSC flight data is available\n if (rsc) {\n // remove the RSC flight data script element\n rsc.parentElement?.removeChild(rsc);\n\n // reload the RSC flight data script to eval it's content\n const rscName = `__remote_component_rsc_${escapeString(\n url.href,\n )}_${escapeString(this.name)}`;\n const rscClone = document.createElement('script');\n rscClone.id = `${rscName}_rsc`;\n rscClone.textContent =\n rsc.textContent?.replace(\n new RegExp(`self\\\\[\"${this.name}\"\\\\]`, 'g'),\n `self[\"${rscName}\"]`,\n ) ?? '';\n document.body.appendChild(rscClone);\n\n let cache: React.ReactNode;\n // React component to convert the RSC flight data into a React component\n const RemoteComponentFromReadableStream = ({\n name,\n initial,\n }: {\n name: string;\n initial: boolean;\n }) => {\n // convert the RSC flight data array into a ReadableStream\n // get the RSC flight data from the global scope\n // the RSC flight data is stored in an array\n // fallback to an empty RSC payload if the data is not found\n const stream = createRSCStream(\n rscName,\n self[rscName as RSCKey] ?? [`0:[null]\\n`],\n );\n const Component =\n cache ??\n // cache the component to avoid reloading the RSC flight data\n (cache = createFromReadableStream(stream) as React.ReactNode);\n\n useLayoutEffect(() => {\n // clear the RSC flight data from the global scope to free up memory\n if (self[name as RSCKey]) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete self[name as RSCKey];\n }\n const rscScript = document.getElementById(`${name}_rsc`);\n if (rscScript) {\n rscScript.remove();\n }\n\n doCleanup();\n applyReset();\n if (!initial) {\n doAttachStyles().catch((e: unknown) => {\n logError('HtmlHost', 'Error attaching styles.', e);\n });\n }\n if (isCurrentLoad()) {\n this.hostState.stage = 'loaded';\n }\n\n this.emitter.load(this.src ?? '');\n }, [initial, name]);\n\n // React can handle the component reference and will wait for the component to be ready\n return Component;\n };\n\n // when we already have a React root, we just need to render the new component\n if (this.reactRoot) {\n const root = this.reactRoot;\n startTransition(() => {\n root.render(\n <RemoteComponentFromReadableStream\n initial={false}\n name={this.name}\n />,\n );\n });\n return;\n }\n\n // hydrate the remote component using the RSC flight data\n this.reactRoot = hydrateRoot(\n // hydrateRoot expects a document or element, but it works for the shadow DOM too\n // @ts-expect-error support for shadow DOM\n this.root,\n <RemoteComponentFromReadableStream initial name={this.name} />,\n );\n } else if (nextData) {\n // using Next.js client pages loader if the Next.js hydration data is available\n const { Component, App } = nextClientPagesLoader(\n this.bundle,\n nextData.page ?? '/',\n this.root,\n );\n\n // if we have the component, we can hydrate it\n if (Component) {\n const RemoteComponentFromNext = ((\n NextApp: ReturnType<typeof nextClientPagesLoader>['App'],\n NextComponent: NonNullable<\n ReturnType<typeof nextClientPagesLoader>['Component']\n >,\n remoteComponent = this,\n ) =>\n function RemoteComponentNext({ initial }: { initial: boolean }) {\n useLayoutEffect(() => {\n doCleanup();\n if (!initial) {\n applyReset();\n doAttachStyles().catch((e: unknown) => {\n logError('HtmlHost', 'Error attaching styles.', e);\n });\n }\n if (isCurrentLoad()) {\n remoteComponent.hostState.stage = 'loaded';\n }\n\n remoteComponent.emitter.load(remoteComponent.src ?? '');\n }, [initial, remoteComponent]);\n\n return NextApp ? (\n <NextApp Component={NextComponent} {...nextData.props} />\n ) : (\n <NextComponent {...nextData.props} />\n );\n })(App, Component, this);\n\n // when we already have a React root, we just need to render the new component\n if (this.reactRoot) {\n const root = this.reactRoot;\n startTransition(() => {\n root.render(<RemoteComponentFromNext initial={false} />);\n doCleanup();\n if (isCurrentLoad()) {\n this.hostState.stage = 'loaded';\n }\n });\n return;\n }\n\n // hydrate the remote component using the Next.js pages router\n this.reactRoot = hydrateRoot(\n // hydrateRoot expects a document or element, but it works for the shadow DOM too\n // @ts-expect-error support for shadow DOM\n this.root,\n <RemoteComponentFromNext initial />,\n );\n }\n\n // remove the FOUC workaround style element to show the remote component\n // this is only for development mode\n if (this.fouc) {\n this.root.removeChild(this.fouc);\n }\n } else if (getNamespace().mountFns[url.href]) {\n // using script entrypoint when no RSC or Next.js data is available\n await Promise.all(\n Array.from(getNamespace().mountFns[url.href] ?? []).map(\n async (mount) => {\n try {\n await mount(this.root);\n } catch (e) {\n logError(\n 'HtmlHost',\n `Error while calling mount() for Remote Component from ${url.href}.`,\n e,\n );\n }\n },\n ),\n );\n\n this.emitter.load(this.src ?? '');\n } else {\n this.emitter.load(this.src ?? '');\n }\n\n if (isCurrentLoad()) {\n this.hostState.stage = 'loaded';\n }\n }\n }\n\n // register the custom element\n customElements.define('remote-component', RemoteComponent);\n}\n\nexport function registerSharedModules(\n modules: Record<string, () => Promise<unknown>> = {},\n) {\n const ns = getNamespace();\n Object.entries(modules).forEach(([key, value]) => {\n ns.hostSharedModules[key] = value;\n });\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\ninterface AttachStylesOptions {\n /** The parsed document containing link and style elements */\n doc: Document;\n /** The component element to check if links are already contained */\n component: Element;\n /** Links from the document head */\n links: NodeListOf<HTMLLinkElement>;\n /** AbortSignal to cancel loading */\n signal: AbortSignal | undefined;\n /** Base URL for resolving relative hrefs */\n baseUrl: string | undefined;\n /** Source URL to set as data attribute */\n remoteComponentSrc: string | null;\n /** Root element to append styles to (ShadowRoot or Element) */\n root: ShadowRoot | Element | null;\n /** Callback to transform asset URLs before loading */\n resolveClientUrl?: InternalResolveClientUrl;\n}\n\n/**\n * Attaches link and style elements from a remote component document to the shadow root.\n * Handles abort signals efficiently with a single shared listener for all links.\n *\n * @throws DOMException with name 'AbortError' if signal is aborted\n * @throws RemoteComponentsError if a stylesheet fails to load\n */\nexport async function attachStyles({\n doc,\n component,\n links,\n signal,\n baseUrl,\n remoteComponentSrc,\n root,\n resolveClientUrl,\n}: AttachStylesOptions): Promise<void> {\n // Track appended links for cleanup on abort\n const appendedLinks: HTMLLinkElement[] = [];\n\n // Single shared abort promise - avoids N listeners for N links\n let abortReject: ((error: DOMException) => void) | null = null;\n const abortPromise = new Promise<never>((_, reject) => {\n abortReject = reject;\n });\n const abortHandler = () => {\n // Clean up all pending links on abort\n for (const link of appendedLinks) {\n link.onload = null;\n link.onerror = null;\n link.remove();\n }\n abortReject?.(new DOMException('Aborted', 'AbortError'));\n };\n signal?.addEventListener('abort', abortHandler, { once: true });\n\n try {\n // Attach each link element to the shadow DOM to load the styles\n await Promise.all(\n Array.from(links)\n .filter((link) => !component.contains(link))\n .map((link) => {\n const newLink = document.createElement('link');\n appendedLinks.push(newLink);\n\n const loadPromise = new Promise<void>((resolve, reject) => {\n if (link.rel === 'stylesheet') {\n // TODO: needs to be cancellable with a singular listener for the abort signal https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\n newLink.onload = () => resolve();\n newLink.onerror = () =>\n reject(\n new RemoteComponentsError(\n `Failed to load <link href=\"${link.href}\"> for Remote Component. Check the URL is correct.`,\n ),\n );\n } else {\n resolve();\n }\n });\n\n for (const attr of link.attributes) {\n if (attr.name === 'href') {\n const absoluteHref = new URL(\n attr.value,\n baseUrl ?? location.origin,\n ).href;\n newLink.setAttribute(\n attr.name,\n resolveClientUrl?.(absoluteHref) ?? absoluteHref,\n );\n } else {\n newLink.setAttribute(attr.name, attr.value);\n }\n }\n\n if (remoteComponentSrc) {\n newLink.setAttribute(\n 'data-remote-component-src',\n remoteComponentSrc,\n );\n }\n\n // TODO: needs to be cancellable with a singular listener for the abort signal https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\n root?.appendChild(newLink);\n\n // Race each link load against the shared abort promise\n return Promise.race([loadPromise, abortPromise]);\n }),\n );\n } finally {\n signal?.removeEventListener('abort', abortHandler);\n }\n\n // Attach inline styles from the document head\n const styles = doc.querySelectorAll<HTMLStyleElement>('style');\n for (const style of styles) {\n if (style.parentElement?.tagName.toLowerCase() === 'head') {\n const newStyle = document.createElement('style');\n newStyle.textContent = style.textContent;\n\n if (remoteComponentSrc) {\n newStyle.setAttribute('data-remote-component-src', remoteComponentSrc);\n }\n\n root?.appendChild(newStyle);\n }\n }\n}\n","import type { InternalResolveClientUrl } from '#internal/host/server/types';\nimport type { RemoteSharedModules } from '#internal/host/shared/shared-broker';\nimport { RemoteComponentsError } from '#internal/utils/error';\n\nexport type Runtime = 'webpack' | 'turbopack' | 'script' | 'unknown';\n\nexport async function getRuntime(\n type: Runtime,\n url: URL,\n bundle: string,\n shared?: Record<string, () => Promise<unknown>>,\n remoteShared?: RemoteSharedModules,\n resolveClientUrl?: InternalResolveClientUrl,\n) {\n // minimally mock process.env for browser environments\n if (typeof globalThis.process === 'undefined') {\n globalThis.process = {\n env: {},\n } as NodeJS.Process;\n }\n\n if (type === 'webpack') {\n const { webpackRuntime } = await import(`./webpack`);\n return webpackRuntime(bundle, shared, remoteShared, resolveClientUrl);\n } else if (type === 'turbopack') {\n const { turbopackRuntime } = await import(`./turbopack`);\n return turbopackRuntime(\n url,\n bundle,\n shared,\n remoteShared,\n resolveClientUrl,\n );\n } else if (type === 'script') {\n const { scriptRuntime } = await import(`./script`);\n return scriptRuntime(resolveClientUrl);\n }\n throw new RemoteComponentsError(\n `Remote Components runtime \"${type}\" is not supported. Supported runtimes are \"webpack\", \"turbopack\", and \"script\".`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB,uBAAuB;AACjD,SAAS,mBAAmB;;;AC4B5B,eAAsB,aAAa;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,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AQ;AAAA,UACZ,MAAM,KAAK,aAAa,EAAE,SAAS,IAAI,IAAI,KAAK,CAAC,CAAC,EAAE;AAAA,YAClD,OAAO,UAAU;AACf,kBAAI;AACF,sBAAM,MAAM,KAAK,IAAI;AAAA,cACvB,SAAS,GAAP;AACA;AAAA,kBACE;AAAA,kBACA,yDAAyD,IAAI;AAAA,kBAC7D;AAAA,gBACF;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAEA,aAAK,QAAQ,KAAK,KAAK,OAAO,EAAE;AAAA,MAClC,OAAO;AACL,aAAK,QAAQ,KAAK,KAAK,OAAO,EAAE;AAAA,MAClC;AAEA,UAAI,cAAc,GAAG;AACnB,aAAK,UAAU,QAAQ;AAAA,MACzB;AAAA,IACF;AAAA,EACF;AAGA,iBAAe,OAAO,oBAAoB,eAAe;AAC3D;AAEO,SAAS,sBACd,UAAkD,CAAC,GACnD;AACA,QAAM,KAAK,aAAa;AACxB,SAAO,QAAQ,OAAO,EAAE,QAAQ,CAAC,CAAC,KAAK,KAAK,MAAM;AAChD,OAAG,kBAAkB,GAAG,IAAI;AAAA,EAC9B,CAAC;AACH;","names":[]}
@@ -1,19 +1,19 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }"use client";
2
2
 
3
3
 
4
- var _chunk4AH3KXDWcjs = require('../../../chunk-4AH3KXDW.cjs');
4
+ var _chunkTWO3XB6Hcjs = require('../../../chunk-TWO3XB6H.cjs');
5
5
 
6
6
 
7
- var _chunk2W7JBTIDcjs = require('../../../chunk-2W7JBTID.cjs');
8
- require('../../../chunk-C5EYU7EQ.cjs');
9
- require('../../../chunk-SECN7UAL.cjs');
10
- require('../../../chunk-HMB3SIVJ.cjs');
7
+ var _chunkPNASFKWAcjs = require('../../../chunk-PNASFKWA.cjs');
8
+ require('../../../chunk-4MLJE6UP.cjs');
9
+ require('../../../chunk-7OD5S534.cjs');
10
+ require('../../../chunk-W5FSHVWU.cjs');
11
11
  require('../../../chunk-3AX5WLZD.cjs');
12
12
  require('../../../chunk-N3SQTOSE.cjs');
13
13
 
14
14
 
15
15
 
16
- var _chunk7XXO2DLFcjs = require('../../../chunk-7XXO2DLF.cjs');
16
+ var _chunkI7VKDF3Ecjs = require('../../../chunk-I7VKDF3E.cjs');
17
17
  require('../../../chunk-Z2SLBFQL.cjs');
18
18
  require('../../../chunk-5KTAEO52.cjs');
19
19
 
@@ -31,8 +31,8 @@ var _react = require('react');
31
31
  function resolveForBundle(unbound, bundle) {
32
32
  if (!unbound)
33
33
  return void 0;
34
- const remoteSrc = _nullishCoalesce(_optionalChain([_chunk7XXO2DLFcjs.getScope.call(void 0, bundle), 'optionalAccess', _2 => _2.url, 'access', _3 => _3.href]), () => ( ""));
35
- return _chunk2W7JBTIDcjs.bindResolveClientUrl.call(void 0, unbound, remoteSrc);
34
+ const remoteSrc = _nullishCoalesce(_optionalChain([_chunkI7VKDF3Ecjs.getScope.call(void 0, bundle), 'optionalAccess', _2 => _2.url, 'access', _3 => _3.href]), () => ( ""));
35
+ return _chunkPNASFKWAcjs.bindResolveClientUrl.call(void 0, unbound, remoteSrc);
36
36
  }
37
37
  function createImageLoaderSharedEntries({
38
38
  bound,
@@ -41,13 +41,13 @@ function createImageLoaderSharedEntries({
41
41
  const loaderEntry = (bundle) => {
42
42
  const resolveClientUrl = _nullishCoalesce(bound, () => ( resolveForBundle(unbound, bundle)));
43
43
  return Promise.resolve({
44
- default: _chunk7XXO2DLFcjs.createRemoteImageLoader.call(void 0, bundle, resolveClientUrl),
44
+ default: _chunkI7VKDF3Ecjs.createRemoteImageLoader.call(void 0, bundle, resolveClientUrl),
45
45
  __esModule: true
46
46
  });
47
47
  };
48
48
  const imageEntry = async (bundle) => {
49
49
  const resolveClientUrl = _nullishCoalesce(bound, () => ( resolveForBundle(unbound, bundle)));
50
- const rawLoader = _chunk7XXO2DLFcjs.createRemoteImageLoader.call(void 0, bundle, resolveClientUrl);
50
+ const rawLoader = _chunkI7VKDF3Ecjs.createRemoteImageLoader.call(void 0, bundle, resolveClientUrl);
51
51
  const remoteLoader = Object.assign(
52
52
  (p) => rawLoader({ ...p, config: { path: "/_next/image" } }),
53
53
  { __next_img_default: true }
@@ -191,7 +191,7 @@ function ConsumeRemoteComponent2(props) {
191
191
  return _nullishCoalesce(props.children, () => ( null));
192
192
  }
193
193
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
194
- _chunk4AH3KXDWcjs.ConsumeRemoteComponent,
194
+ _chunkTWO3XB6Hcjs.ConsumeRemoteComponent,
195
195
  {
196
196
  ...props,
197
197
  shared: sharedModules(props.shared, props.resolveClientUrl)
@@ -1,19 +1,19 @@
1
1
  "use client";
2
2
  import {
3
3
  ConsumeRemoteComponent
4
- } from "../../../chunk-HYVNEUIK.js";
4
+ } from "../../../chunk-MJ2KYXGR.js";
5
5
  import {
6
6
  bindResolveClientUrl
7
- } from "../../../chunk-DGZVFKSQ.js";
8
- import "../../../chunk-HL6BL5HY.js";
9
- import "../../../chunk-KV5J7PNM.js";
10
- import "../../../chunk-4NW46ZVD.js";
7
+ } from "../../../chunk-O4A6CJGI.js";
8
+ import "../../../chunk-WGSS7TJP.js";
9
+ import "../../../chunk-NZM2SI6U.js";
10
+ import "../../../chunk-PT3R275L.js";
11
11
  import "../../../chunk-LEKG4YWI.js";
12
12
  import "../../../chunk-RHGEBXPL.js";
13
13
  import {
14
14
  createRemoteImageLoader,
15
15
  getScope
16
- } from "../../../chunk-55TEMSB5.js";
16
+ } from "../../../chunk-JZRA6DPE.js";
17
17
  import "../../../chunk-D5GNZB6O.js";
18
18
  import "../../../chunk-STIJO4AG.js";
19
19
  import {
@@ -42,7 +42,9 @@ var import_react = require("react");
42
42
  var import_react2 = require("remote-components/host/react");
43
43
  var import_image_shared = require("#internal/host/nextjs/image-shared");
44
44
  var import_fetch_remote_component = require("#internal/host/server/fetch-remote-component");
45
+ var import_shared_broker = require("#internal/host/shared/shared-broker");
45
46
  var import_constants = require("#internal/runtime/constants");
47
+ var import_html_spec = require("#internal/runtime/html/html-spec");
46
48
  var import_error = require("#internal/utils/error");
47
49
  var import_pages = require("#remote-components/host/defaults/pages");
48
50
  const navigationImpl = {
@@ -85,6 +87,35 @@ const shared = (bundle, resolveClientUrl) => {
85
87
  const REMOTE_COMPONENT_STORE = Symbol("REMOTE_COMPONENT_STORE");
86
88
  const REMOTE_COMPONENT_KEY = "__REMOTE_COMPONENT_KEY__";
87
89
  const self = globalThis;
90
+ function RemoteSharedScript({
91
+ name,
92
+ remoteShared
93
+ }) {
94
+ if ((0, import_shared_broker.isSharedModuleManifest)(remoteShared)) {
95
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
96
+ "script",
97
+ {
98
+ ...{ [import_html_spec.DATA_REMOTE_COMPONENTS_SHARED_MANIFEST]: "" },
99
+ id: `${name}${import_html_spec.ID_SUFFIX_SHARED_MANIFEST}`,
100
+ type: "application/json",
101
+ children: JSON.stringify(remoteShared)
102
+ }
103
+ );
104
+ }
105
+ return (
106
+ // @legacy(remote-components<=0.4.x): keep writing the historical shared
107
+ // map until hosts and remotes on 0.4.x are outside support.
108
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
109
+ "script",
110
+ {
111
+ ...{ [import_html_spec.DATA_REMOTE_COMPONENTS_SHARED]: "" },
112
+ id: `${name}${import_html_spec.ID_SUFFIX_SHARED}`,
113
+ type: "application/json",
114
+ children: JSON.stringify(remoteShared)
115
+ }
116
+ )
117
+ );
118
+ }
88
119
  function getKey(bundle, route, name) {
89
120
  return `${bundle}:${route}:${name}__${crypto.randomUUID()}`;
90
121
  }
@@ -181,15 +212,7 @@ async function getConsumeRemoteComponentProps(src, options) {
181
212
  setComponent(
182
213
  key,
183
214
  /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
184
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
185
- "script",
186
- {
187
- "data-remote-components-shared": "",
188
- id: `${name}_shared`,
189
- type: "application/json",
190
- children: JSON.stringify(remoteShared)
191
- }
192
- ),
215
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(RemoteSharedScript, { name, remoteShared }),
193
216
  links.map((link) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
194
217
  "link",
195
218
  {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/host/nextjs/pages.tsx"],"sourcesContent":["import 'remote-components/remote/defaults/wrapper';\nimport * as Form from 'next/form';\nimport * as Link from 'next/link';\nimport * as Router from 'next/router';\nimport * as Script from 'next/script';\nimport { useEffect } from 'react';\nimport { ConsumeRemoteComponent as ConsumeRemoteComponentReact } from 'remote-components/host/react';\nimport { createImageLoaderSharedEntries } from '#internal/host/nextjs/image-shared';\nimport { fetchRemoteComponent } from '#internal/host/server/fetch-remote-component';\nimport type { ConsumeRemoteComponentConfig } from '#internal/host/shared/config';\nimport type {\n OnRequestHook,\n OnResponseHook,\n} from '#internal/host/shared/fetch-interceptors';\nimport {\n DEFAULT_BUNDLE_NAME,\n DEFAULT_COMPONENT_NAME,\n} from '#internal/runtime/constants';\nimport type { ResolveClientUrl } from '#internal/runtime/url/resolve-client-url';\nimport { RemoteComponentsError } from '#internal/utils/error';\nimport { shared as _shared } from '#remote-components/host/defaults/pages';\n\nconst navigationImpl = {\n useRouter: () => Router.useRouter(),\n useSearchParams: () => {\n const router = Router.useRouter();\n return {\n get: (key: string) => router.query[key],\n has: (key: string) => key in router.query,\n };\n },\n};\n\nconst sharedCache = new Map<string, Record<string, () => Promise<unknown>>>();\nconst shared = (bundle: string, resolveClientUrl?: ResolveClientUrl) => {\n // Skip cache when resolveClientUrl is provided — different resolver instances\n // must not share a cache entry, since the image loader closes over the resolver.\n if (!resolveClientUrl) {\n if (sharedCache.has(bundle)) {\n return sharedCache.get(bundle);\n }\n }\n\n const result = {\n // polyfill Next.js App Router client API (minimal)\n // some API methods are not available when using a Next.js Pages Router application as host\n 'next/navigation': () =>\n Promise.resolve(navigationImpl) as Promise<unknown>,\n 'next/dist/client/components/navigation': () =>\n Promise.resolve(navigationImpl) as Promise<unknown>,\n 'next/dist/client/app-dir/link': () =>\n Promise.resolve(Link.default) as Promise<unknown>,\n 'next/link': () => Promise.resolve(Link.default) as Promise<unknown>,\n 'next/dist/client/app-dir/form': () =>\n Promise.resolve(Form.default) as Promise<unknown>,\n 'next/form': () => Promise.resolve(Form.default) as Promise<unknown>,\n 'next/dist/client/script': () =>\n Promise.resolve(Script.default) as Promise<unknown>,\n 'next/script': () => Promise.resolve(Script.default) as Promise<unknown>,\n 'next/router': () => Promise.resolve(Router) as Promise<unknown>,\n ..._shared,\n ...createImageLoaderSharedEntries({ unbound: resolveClientUrl }),\n };\n\n if (!resolveClientUrl) {\n sharedCache.set(bundle, result);\n }\n\n return result;\n};\n\n// internal symbols to access global store\nconst REMOTE_COMPONENT_STORE = Symbol('REMOTE_COMPONENT_STORE');\nconst REMOTE_COMPONENT_KEY = '__REMOTE_COMPONENT_KEY__';\n\n// temporary global store for remote component HTML\n// the store is used to save the HTML of remote components for SSR without sending the content to the client\nconst self = globalThis as typeof globalThis & {\n [REMOTE_COMPONENT_STORE]?: Map<string, React.ReactNode>;\n};\n\nfunction getKey(bundle: string, route: string, name: string): string {\n return `${bundle}:${route}:${name}__${crypto.randomUUID()}`;\n}\n\nfunction setComponent(key: string, component: React.ReactNode): void {\n if (!self[REMOTE_COMPONENT_STORE]) {\n self[REMOTE_COMPONENT_STORE] = new Map();\n }\n self[REMOTE_COMPONENT_STORE].set(key, component);\n}\n\nfunction getComponent(key: string): React.ReactNode | undefined {\n const component = self[REMOTE_COMPONENT_STORE]?.get(key);\n // remove the component from the store after retrieving it to prevent memory leaks\n // storing the HTML in the global store is only needed for SSR and it's temporary only used for a single render\n self[REMOTE_COMPONENT_STORE]?.delete(key);\n return component;\n}\n\n/**\n * Props for the Next.js Pages Router remote component host.\n *\n * Extends {@link ConsumeRemoteComponentConfig} with Pages Router–specific `bundle` and\n * `route` props used for SSR hydration.\n */\nexport interface ConsumeRemoteComponentProps\n extends ConsumeRemoteComponentConfig {\n /** The source URL of the remote component. Required for server rendering. */\n src: string | URL;\n /** The Webpack bundle name for the remote component. */\n bundle?: string;\n /** The page route of the remote component. */\n route?: string;\n /** Loading fallback content displayed while the remote component is being fetched. */\n children?: React.ReactNode;\n [REMOTE_COMPONENT_KEY]?: string;\n}\n\n/**\n * This component handles the rendering of remote microfrontends.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n */\nexport function ConsumeRemoteComponent(props: ConsumeRemoteComponentProps) {\n const remoteComponent =\n typeof document !== 'undefined'\n ? null\n : // retrieve the HTML from the global store\n getComponent(props[REMOTE_COMPONENT_KEY] ?? DEFAULT_COMPONENT_NAME);\n\n const sharedResult = shared(\n props.bundle ?? DEFAULT_BUNDLE_NAME,\n props.resolveClientUrl,\n );\n\n useEffect(() => {\n const clientSelf = globalThis as typeof globalThis & {\n __remote_component_shared__?: Record<string, () => Promise<unknown>>;\n };\n // eslint-disable-next-line camelcase\n clientSelf.__remote_component_shared__ = sharedResult;\n }, [sharedResult]);\n\n if (!props[REMOTE_COMPONENT_KEY]) {\n return (\n <ConsumeRemoteComponentReact\n isolate={props.isolate}\n mode={props.mode}\n name={props.name}\n onBeforeLoad={props.onBeforeLoad}\n onChange={props.onChange}\n onError={props.onError}\n onLoad={props.onLoad}\n onRequest={props.onRequest}\n onResponse={props.onResponse}\n resolveClientUrl={props.resolveClientUrl}\n reset={props.reset}\n shared={sharedResult}\n src={props.src}\n >\n {props.children}\n </ConsumeRemoteComponentReact>\n );\n }\n\n return (\n <ConsumeRemoteComponentReact\n isolate={props.isolate}\n mode={props.mode}\n name={props.name}\n onBeforeLoad={props.onBeforeLoad}\n onChange={props.onChange}\n onError={props.onError}\n onLoad={props.onLoad}\n onRequest={props.onRequest}\n onResponse={props.onResponse}\n resolveClientUrl={props.resolveClientUrl}\n reset={props.reset}\n shared={sharedResult}\n src={props.src}\n >\n {remoteComponent}\n </ConsumeRemoteComponentReact>\n );\n}\n\n/**\n * Fetches the remote component properties from the server. You need to pass these properties to the `<ConsumeRemoteComponent>` component to render the fetched remote component.\n *\n * @param src - The source URL of the remote component. When using the Vercel Microfrontends solution, you can use relative paths, e.g. `/nextjs-app-remote/components/header`. Absolute URLs are also supported.\n * @param headers - The HTTP headers used for supporting the Vercel Microfrontends proxy.\n * @returns The properties of the remote component.\n *\n * @example\n *\n * ```tsx\n * import { getRemoteComponentProps } from 'remote-components/next/host/pages';\n * import type { GetServerSideProps } from 'next';\n *\n * export const getServerSideProps: GetServerSideProps<PageProps> = async function getServerSideProps({ req }) {\n * const myRemoteComponent = await getConsumeRemoteComponentProps(\n * '/nextjs-app-remote/components/header',\n * req.headers,\n * );\n * return {\n * props: {\n * remoteComponents: {\n * myRemoteComponent,\n * },\n * },\n * };\n * }\n * ```\n */\nexport async function getConsumeRemoteComponentProps(\n src: string,\n options?: {\n /**\n * Called when a fetch request is made to retrieve the remote component payload.\n * Can be used to intercept requests, modify headers, or provide a custom response.\n */\n onRequest?: OnRequestHook;\n /**\n * Called after a fetch completes to retrieve the remote component payload.\n * Can be used to inspect the response (e.g., check for redirects) or transform it.\n */\n onResponse?: OnResponseHook;\n /**\n * The name of the exposed remote component. Used to identify the remote component\n * when multiple remote components are exposed on a page.\n */\n name?: string;\n },\n): Promise<ConsumeRemoteComponentProps> {\n if (typeof document !== 'undefined') {\n throw new RemoteComponentsError(\n '`getConsumeRemoteComponentProps()` can only be used on the server side.',\n );\n }\n\n const {\n metadata: { bundle, route },\n name,\n links,\n component,\n nextData,\n remoteShared,\n } = await fetchRemoteComponent(src, {\n rsc: true,\n ...options,\n });\n\n const props: ConsumeRemoteComponentProps = {\n src,\n bundle,\n name,\n route,\n };\n\n const key = getKey(bundle, route, name);\n\n // do not render the HTML in development mode when remote is using Next.js Pages Router\n // this behavior is emulating the Next.js Pages Router FOUC as the styles are only applied on the client when running in development mode\n if (nextData?.buildId !== 'development') {\n // store the HTML in a global store\n setComponent(\n key,\n <>\n <script\n data-remote-components-shared=\"\"\n id={`${name}_shared`}\n type=\"application/json\"\n >\n {JSON.stringify(remoteShared)}\n </script>\n {links.map((link) => (\n <link\n key={`${link.as}_${link.href}`}\n {...link}\n precedence={undefined}\n />\n ))}\n {component}\n </>,\n );\n }\n\n return {\n ...props,\n // add remote component key to the props\n [REMOTE_COMPONENT_KEY]: key,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmJM;AAnJN,qBAAO;AACP,WAAsB;AACtB,WAAsB;AACtB,aAAwB;AACxB,aAAwB;AACxB,mBAA0B;AAC1B,IAAAA,gBAAsE;AACtE,0BAA+C;AAC/C,oCAAqC;AAMrC,uBAGO;AAEP,mBAAsC;AACtC,mBAAkC;AAElC,MAAM,iBAAiB;AAAA,EACrB,WAAW,MAAM,OAAO,UAAU;AAAA,EAClC,iBAAiB,MAAM;AACrB,UAAM,SAAS,OAAO,UAAU;AAChC,WAAO;AAAA,MACL,KAAK,CAAC,QAAgB,OAAO,MAAM,GAAG;AAAA,MACtC,KAAK,CAAC,QAAgB,OAAO,OAAO;AAAA,IACtC;AAAA,EACF;AACF;AAEA,MAAM,cAAc,oBAAI,IAAoD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a,aAAa;AACnC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM;AAAA,IACJ,UAAU,EAAE,QAAQ,MAAM;AAAA,IAC1B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,UAAM,oDAAqB,KAAK;AAAA,IAClC,KAAK;AAAA,IACL,GAAG;AAAA,EACL,CAAC;AAED,QAAM,QAAqC;AAAA,IACzC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,QAAM,MAAM,OAAO,QAAQ,OAAO,IAAI;AAItC,MAAI,UAAU,YAAY,eAAe;AAEvC;AAAA,MACE;AAAA,MACA,4EACE;AAAA;AAAA,UAAC;AAAA;AAAA,YACC,iCAA8B;AAAA,YAC9B,IAAI,GAAG;AAAA,YACP,MAAK;AAAA,YAEJ,eAAK,UAAU,YAAY;AAAA;AAAA,QAC9B;AAAA,QACC,MAAM,IAAI,CAAC,SACV;AAAA,UAAC;AAAA;AAAA,YAEE,GAAG;AAAA,YACJ,YAAY;AAAA;AAAA,UAFP,GAAG,KAAK,MAAM,KAAK;AAAA,QAG1B,CACD;AAAA,QACA;AAAA,SACH;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,GAAG;AAAA;AAAA,IAEH,CAAC,oBAAoB,GAAG;AAAA,EAC1B;AACF;","names":["import_react","_shared","ConsumeRemoteComponentReact"]}
1
+ {"version":3,"sources":["../../../src/host/nextjs/pages.tsx"],"sourcesContent":["import 'remote-components/remote/defaults/wrapper';\nimport * as Form from 'next/form';\nimport * as Link from 'next/link';\nimport * as Router from 'next/router';\nimport * as Script from 'next/script';\nimport { useEffect } from 'react';\nimport { ConsumeRemoteComponent as ConsumeRemoteComponentReact } from 'remote-components/host/react';\nimport { createImageLoaderSharedEntries } from '#internal/host/nextjs/image-shared';\nimport { fetchRemoteComponent } from '#internal/host/server/fetch-remote-component';\nimport type { ConsumeRemoteComponentConfig } from '#internal/host/shared/config';\nimport type {\n OnRequestHook,\n OnResponseHook,\n} from '#internal/host/shared/fetch-interceptors';\nimport {\n isSharedModuleManifest,\n type RemoteSharedModules,\n} from '#internal/host/shared/shared-broker';\nimport {\n DEFAULT_BUNDLE_NAME,\n DEFAULT_COMPONENT_NAME,\n} from '#internal/runtime/constants';\nimport {\n DATA_REMOTE_COMPONENTS_SHARED,\n DATA_REMOTE_COMPONENTS_SHARED_MANIFEST,\n ID_SUFFIX_SHARED,\n ID_SUFFIX_SHARED_MANIFEST,\n} from '#internal/runtime/html/html-spec';\nimport type { ResolveClientUrl } from '#internal/runtime/url/resolve-client-url';\nimport { RemoteComponentsError } from '#internal/utils/error';\nimport { shared as _shared } from '#remote-components/host/defaults/pages';\n\nconst navigationImpl = {\n useRouter: () => Router.useRouter(),\n useSearchParams: () => {\n const router = Router.useRouter();\n return {\n get: (key: string) => router.query[key],\n has: (key: string) => key in router.query,\n };\n },\n};\n\nconst sharedCache = new Map<string, Record<string, () => Promise<unknown>>>();\nconst shared = (bundle: string, resolveClientUrl?: ResolveClientUrl) => {\n // Skip cache when resolveClientUrl is provided — different resolver instances\n // must not share a cache entry, since the image loader closes over the resolver.\n if (!resolveClientUrl) {\n if (sharedCache.has(bundle)) {\n return sharedCache.get(bundle);\n }\n }\n\n const result = {\n // polyfill Next.js App Router client API (minimal)\n // some API methods are not available when using a Next.js Pages Router application as host\n 'next/navigation': () =>\n Promise.resolve(navigationImpl) as Promise<unknown>,\n 'next/dist/client/components/navigation': () =>\n Promise.resolve(navigationImpl) as Promise<unknown>,\n 'next/dist/client/app-dir/link': () =>\n Promise.resolve(Link.default) as Promise<unknown>,\n 'next/link': () => Promise.resolve(Link.default) as Promise<unknown>,\n 'next/dist/client/app-dir/form': () =>\n Promise.resolve(Form.default) as Promise<unknown>,\n 'next/form': () => Promise.resolve(Form.default) as Promise<unknown>,\n 'next/dist/client/script': () =>\n Promise.resolve(Script.default) as Promise<unknown>,\n 'next/script': () => Promise.resolve(Script.default) as Promise<unknown>,\n 'next/router': () => Promise.resolve(Router) as Promise<unknown>,\n ..._shared,\n ...createImageLoaderSharedEntries({ unbound: resolveClientUrl }),\n };\n\n if (!resolveClientUrl) {\n sharedCache.set(bundle, result);\n }\n\n return result;\n};\n\n// internal symbols to access global store\nconst REMOTE_COMPONENT_STORE = Symbol('REMOTE_COMPONENT_STORE');\nconst REMOTE_COMPONENT_KEY = '__REMOTE_COMPONENT_KEY__';\n\n// temporary global store for remote component HTML\n// the store is used to save the HTML of remote components for SSR without sending the content to the client\nconst self = globalThis as typeof globalThis & {\n [REMOTE_COMPONENT_STORE]?: Map<string, React.ReactNode>;\n};\n\nfunction RemoteSharedScript({\n name,\n remoteShared,\n}: {\n name: string;\n remoteShared: RemoteSharedModules;\n}) {\n if (isSharedModuleManifest(remoteShared)) {\n return (\n <script\n {...{ [DATA_REMOTE_COMPONENTS_SHARED_MANIFEST]: '' }}\n id={`${name}${ID_SUFFIX_SHARED_MANIFEST}`}\n type=\"application/json\"\n >\n {JSON.stringify(remoteShared)}\n </script>\n );\n }\n\n return (\n // @legacy(remote-components<=0.4.x): keep writing the historical shared\n // map until hosts and remotes on 0.4.x are outside support.\n <script\n {...{ [DATA_REMOTE_COMPONENTS_SHARED]: '' }}\n id={`${name}${ID_SUFFIX_SHARED}`}\n type=\"application/json\"\n >\n {JSON.stringify(remoteShared)}\n </script>\n );\n}\n\nfunction getKey(bundle: string, route: string, name: string): string {\n return `${bundle}:${route}:${name}__${crypto.randomUUID()}`;\n}\n\nfunction setComponent(key: string, component: React.ReactNode): void {\n if (!self[REMOTE_COMPONENT_STORE]) {\n self[REMOTE_COMPONENT_STORE] = new Map();\n }\n self[REMOTE_COMPONENT_STORE].set(key, component);\n}\n\nfunction getComponent(key: string): React.ReactNode | undefined {\n const component = self[REMOTE_COMPONENT_STORE]?.get(key);\n // remove the component from the store after retrieving it to prevent memory leaks\n // storing the HTML in the global store is only needed for SSR and it's temporary only used for a single render\n self[REMOTE_COMPONENT_STORE]?.delete(key);\n return component;\n}\n\n/**\n * Props for the Next.js Pages Router remote component host.\n *\n * Extends {@link ConsumeRemoteComponentConfig} with Pages Router–specific `bundle` and\n * `route` props used for SSR hydration.\n */\nexport interface ConsumeRemoteComponentProps\n extends ConsumeRemoteComponentConfig {\n /** The source URL of the remote component. Required for server rendering. */\n src: string | URL;\n /** The Webpack bundle name for the remote component. */\n bundle?: string;\n /** The page route of the remote component. */\n route?: string;\n /** Loading fallback content displayed while the remote component is being fetched. */\n children?: React.ReactNode;\n [REMOTE_COMPONENT_KEY]?: string;\n}\n\n/**\n * This component handles the rendering of remote microfrontends.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n */\nexport function ConsumeRemoteComponent(props: ConsumeRemoteComponentProps) {\n const remoteComponent =\n typeof document !== 'undefined'\n ? null\n : // retrieve the HTML from the global store\n getComponent(props[REMOTE_COMPONENT_KEY] ?? DEFAULT_COMPONENT_NAME);\n\n const sharedResult = shared(\n props.bundle ?? DEFAULT_BUNDLE_NAME,\n props.resolveClientUrl,\n );\n\n useEffect(() => {\n const clientSelf = globalThis as typeof globalThis & {\n __remote_component_shared__?: Record<string, () => Promise<unknown>>;\n };\n // eslint-disable-next-line camelcase\n clientSelf.__remote_component_shared__ = sharedResult;\n }, [sharedResult]);\n\n if (!props[REMOTE_COMPONENT_KEY]) {\n return (\n <ConsumeRemoteComponentReact\n isolate={props.isolate}\n mode={props.mode}\n name={props.name}\n onBeforeLoad={props.onBeforeLoad}\n onChange={props.onChange}\n onError={props.onError}\n onLoad={props.onLoad}\n onRequest={props.onRequest}\n onResponse={props.onResponse}\n resolveClientUrl={props.resolveClientUrl}\n reset={props.reset}\n shared={sharedResult}\n src={props.src}\n >\n {props.children}\n </ConsumeRemoteComponentReact>\n );\n }\n\n return (\n <ConsumeRemoteComponentReact\n isolate={props.isolate}\n mode={props.mode}\n name={props.name}\n onBeforeLoad={props.onBeforeLoad}\n onChange={props.onChange}\n onError={props.onError}\n onLoad={props.onLoad}\n onRequest={props.onRequest}\n onResponse={props.onResponse}\n resolveClientUrl={props.resolveClientUrl}\n reset={props.reset}\n shared={sharedResult}\n src={props.src}\n >\n {remoteComponent}\n </ConsumeRemoteComponentReact>\n );\n}\n\n/**\n * Fetches the remote component properties from the server. You need to pass these properties to the `<ConsumeRemoteComponent>` component to render the fetched remote component.\n *\n * @param src - The source URL of the remote component. When using the Vercel Microfrontends solution, you can use relative paths, e.g. `/nextjs-app-remote/components/header`. Absolute URLs are also supported.\n * @param headers - The HTTP headers used for supporting the Vercel Microfrontends proxy.\n * @returns The properties of the remote component.\n *\n * @example\n *\n * ```tsx\n * import { getRemoteComponentProps } from 'remote-components/next/host/pages';\n * import type { GetServerSideProps } from 'next';\n *\n * export const getServerSideProps: GetServerSideProps<PageProps> = async function getServerSideProps({ req }) {\n * const myRemoteComponent = await getConsumeRemoteComponentProps(\n * '/nextjs-app-remote/components/header',\n * req.headers,\n * );\n * return {\n * props: {\n * remoteComponents: {\n * myRemoteComponent,\n * },\n * },\n * };\n * }\n * ```\n */\nexport async function getConsumeRemoteComponentProps(\n src: string,\n options?: {\n /**\n * Called when a fetch request is made to retrieve the remote component payload.\n * Can be used to intercept requests, modify headers, or provide a custom response.\n */\n onRequest?: OnRequestHook;\n /**\n * Called after a fetch completes to retrieve the remote component payload.\n * Can be used to inspect the response (e.g., check for redirects) or transform it.\n */\n onResponse?: OnResponseHook;\n /**\n * The name of the exposed remote component. Used to identify the remote component\n * when multiple remote components are exposed on a page.\n */\n name?: string;\n },\n): Promise<ConsumeRemoteComponentProps> {\n if (typeof document !== 'undefined') {\n throw new RemoteComponentsError(\n '`getConsumeRemoteComponentProps()` can only be used on the server side.',\n );\n }\n\n const {\n metadata: { bundle, route },\n name,\n links,\n component,\n nextData,\n remoteShared,\n } = await fetchRemoteComponent(src, {\n rsc: true,\n ...options,\n });\n\n const props: ConsumeRemoteComponentProps = {\n src,\n bundle,\n name,\n route,\n };\n\n const key = getKey(bundle, route, name);\n\n // do not render the HTML in development mode when remote is using Next.js Pages Router\n // this behavior is emulating the Next.js Pages Router FOUC as the styles are only applied on the client when running in development mode\n if (nextData?.buildId !== 'development') {\n // store the HTML in a global store\n setComponent(\n key,\n <>\n <RemoteSharedScript name={name} remoteShared={remoteShared} />\n {links.map((link) => (\n <link\n key={`${link.as}_${link.href}`}\n {...link}\n precedence={undefined}\n />\n ))}\n {component}\n </>,\n );\n }\n\n return {\n ...props,\n // add remote component key to the props\n [REMOTE_COMPONENT_KEY]: key,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoGM;AApGN,qBAAO;AACP,WAAsB;AACtB,WAAsB;AACtB,aAAwB;AACxB,aAAwB;AACxB,mBAA0B;AAC1B,IAAAA,gBAAsE;AACtE,0BAA+C;AAC/C,oCAAqC;AAMrC,2BAGO;AACP,uBAGO;AACP,uBAKO;AAEP,mBAAsC;AACtC,mBAAkC;AAElC,MAAM,iBAAiB;AAAA,EACrB,WAAW,MAAM,OAAO,UAAU;AAAA,EAClC,iBAAiB,MAAM;AACrB,UAAM,SAAS,OAAO,UAAU;AAChC,WAAO;AAAA,MACL,KAAK,CAAC,QAAgB,OAAO,MAAM,GAAG;AAAA,MACtC,KAAK,CAAC,QAAgB,OAAO,OAAO;AAAA,IACtC;AAAA,EACF;AACF;AAEA,MAAM,cAAc,oBAAI,IAAoD;AAC5E,MAAM,SAAS,CAAC,QAAgB,qBAAwC;AAGtE,MAAI,CAAC,kBAAkB;AACrB,QAAI,YAAY,IAAI,MAAM,GAAG;AAC3B,aAAO,YAAY,IAAI,MAAM;AAAA,IAC/B;AAAA,EACF;AAEA,QAAM,SAAS;AAAA;AAAA;AAAA,IAGb,mBAAmB,MACjB,QAAQ,QAAQ,cAAc;AAAA,IAChC,0CAA0C,MACxC,QAAQ,QAAQ,cAAc;AAAA,IAChC,iCAAiC,MAC/B,QAAQ,QAAQ,KAAK,OAAO;AAAA,IAC9B,aA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A,MACb,QAAQ;AAAA,MACR,KAAK,MAAM;AAAA,MAEV;AAAA;AAAA,EACH;AAEJ;AA8BA,eAAsB,+BACpB,KACA,SAiBsC;AACtC,MAAI,OAAO,aAAa,aAAa;AACnC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM;AAAA,IACJ,UAAU,EAAE,QAAQ,MAAM;AAAA,IAC1B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,UAAM,oDAAqB,KAAK;AAAA,IAClC,KAAK;AAAA,IACL,GAAG;AAAA,EACL,CAAC;AAED,QAAM,QAAqC;AAAA,IACzC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,QAAM,MAAM,OAAO,QAAQ,OAAO,IAAI;AAItC,MAAI,UAAU,YAAY,eAAe;AAEvC;AAAA,MACE;AAAA,MACA,4EACE;AAAA,oDAAC,sBAAmB,MAAY,cAA4B;AAAA,QAC3D,MAAM,IAAI,CAAC,SACV;AAAA,UAAC;AAAA;AAAA,YAEE,GAAG;AAAA,YACJ,YAAY;AAAA;AAAA,UAFP,GAAG,KAAK,MAAM,KAAK;AAAA,QAG1B,CACD;AAAA,QACA;AAAA,SACH;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,GAAG;AAAA;AAAA,IAEH,CAAC,oBAAoB,GAAG;AAAA,EAC1B;AACF;","names":["import_react","_shared","ConsumeRemoteComponentReact"]}
@@ -8,10 +8,19 @@ import { useEffect } from "react";
8
8
  import { ConsumeRemoteComponent as ConsumeRemoteComponentReact } from "remote-components/host/react";
9
9
  import { createImageLoaderSharedEntries } from "#internal/host/nextjs/image-shared";
10
10
  import { fetchRemoteComponent } from "#internal/host/server/fetch-remote-component";
11
+ import {
12
+ isSharedModuleManifest
13
+ } from "#internal/host/shared/shared-broker";
11
14
  import {
12
15
  DEFAULT_BUNDLE_NAME,
13
16
  DEFAULT_COMPONENT_NAME
14
17
  } from "#internal/runtime/constants";
18
+ import {
19
+ DATA_REMOTE_COMPONENTS_SHARED,
20
+ DATA_REMOTE_COMPONENTS_SHARED_MANIFEST,
21
+ ID_SUFFIX_SHARED,
22
+ ID_SUFFIX_SHARED_MANIFEST
23
+ } from "#internal/runtime/html/html-spec";
15
24
  import { RemoteComponentsError } from "#internal/utils/error";
16
25
  import { shared as _shared } from "#remote-components/host/defaults/pages";
17
26
  const navigationImpl = {
@@ -54,6 +63,35 @@ const shared = (bundle, resolveClientUrl) => {
54
63
  const REMOTE_COMPONENT_STORE = Symbol("REMOTE_COMPONENT_STORE");
55
64
  const REMOTE_COMPONENT_KEY = "__REMOTE_COMPONENT_KEY__";
56
65
  const self = globalThis;
66
+ function RemoteSharedScript({
67
+ name,
68
+ remoteShared
69
+ }) {
70
+ if (isSharedModuleManifest(remoteShared)) {
71
+ return /* @__PURE__ */ jsx(
72
+ "script",
73
+ {
74
+ ...{ [DATA_REMOTE_COMPONENTS_SHARED_MANIFEST]: "" },
75
+ id: `${name}${ID_SUFFIX_SHARED_MANIFEST}`,
76
+ type: "application/json",
77
+ children: JSON.stringify(remoteShared)
78
+ }
79
+ );
80
+ }
81
+ return (
82
+ // @legacy(remote-components<=0.4.x): keep writing the historical shared
83
+ // map until hosts and remotes on 0.4.x are outside support.
84
+ /* @__PURE__ */ jsx(
85
+ "script",
86
+ {
87
+ ...{ [DATA_REMOTE_COMPONENTS_SHARED]: "" },
88
+ id: `${name}${ID_SUFFIX_SHARED}`,
89
+ type: "application/json",
90
+ children: JSON.stringify(remoteShared)
91
+ }
92
+ )
93
+ );
94
+ }
57
95
  function getKey(bundle, route, name) {
58
96
  return `${bundle}:${route}:${name}__${crypto.randomUUID()}`;
59
97
  }
@@ -150,15 +188,7 @@ async function getConsumeRemoteComponentProps(src, options) {
150
188
  setComponent(
151
189
  key,
152
190
  /* @__PURE__ */ jsxs(Fragment, { children: [
153
- /* @__PURE__ */ jsx(
154
- "script",
155
- {
156
- "data-remote-components-shared": "",
157
- id: `${name}_shared`,
158
- type: "application/json",
159
- children: JSON.stringify(remoteShared)
160
- }
161
- ),
191
+ /* @__PURE__ */ jsx(RemoteSharedScript, { name, remoteShared }),
162
192
  links.map((link) => /* @__PURE__ */ jsx(
163
193
  "link",
164
194
  {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/host/nextjs/pages.tsx"],"sourcesContent":["import 'remote-components/remote/defaults/wrapper';\nimport * as Form from 'next/form';\nimport * as Link from 'next/link';\nimport * as Router from 'next/router';\nimport * as Script from 'next/script';\nimport { useEffect } from 'react';\nimport { ConsumeRemoteComponent as ConsumeRemoteComponentReact } from 'remote-components/host/react';\nimport { createImageLoaderSharedEntries } from '#internal/host/nextjs/image-shared';\nimport { fetchRemoteComponent } from '#internal/host/server/fetch-remote-component';\nimport type { ConsumeRemoteComponentConfig } from '#internal/host/shared/config';\nimport type {\n OnRequestHook,\n OnResponseHook,\n} from '#internal/host/shared/fetch-interceptors';\nimport {\n DEFAULT_BUNDLE_NAME,\n DEFAULT_COMPONENT_NAME,\n} from '#internal/runtime/constants';\nimport type { ResolveClientUrl } from '#internal/runtime/url/resolve-client-url';\nimport { RemoteComponentsError } from '#internal/utils/error';\nimport { shared as _shared } from '#remote-components/host/defaults/pages';\n\nconst navigationImpl = {\n useRouter: () => Router.useRouter(),\n useSearchParams: () => {\n const router = Router.useRouter();\n return {\n get: (key: string) => router.query[key],\n has: (key: string) => key in router.query,\n };\n },\n};\n\nconst sharedCache = new Map<string, Record<string, () => Promise<unknown>>>();\nconst shared = (bundle: string, resolveClientUrl?: ResolveClientUrl) => {\n // Skip cache when resolveClientUrl is provided — different resolver instances\n // must not share a cache entry, since the image loader closes over the resolver.\n if (!resolveClientUrl) {\n if (sharedCache.has(bundle)) {\n return sharedCache.get(bundle);\n }\n }\n\n const result = {\n // polyfill Next.js App Router client API (minimal)\n // some API methods are not available when using a Next.js Pages Router application as host\n 'next/navigation': () =>\n Promise.resolve(navigationImpl) as Promise<unknown>,\n 'next/dist/client/components/navigation': () =>\n Promise.resolve(navigationImpl) as Promise<unknown>,\n 'next/dist/client/app-dir/link': () =>\n Promise.resolve(Link.default) as Promise<unknown>,\n 'next/link': () => Promise.resolve(Link.default) as Promise<unknown>,\n 'next/dist/client/app-dir/form': () =>\n Promise.resolve(Form.default) as Promise<unknown>,\n 'next/form': () => Promise.resolve(Form.default) as Promise<unknown>,\n 'next/dist/client/script': () =>\n Promise.resolve(Script.default) as Promise<unknown>,\n 'next/script': () => Promise.resolve(Script.default) as Promise<unknown>,\n 'next/router': () => Promise.resolve(Router) as Promise<unknown>,\n ..._shared,\n ...createImageLoaderSharedEntries({ unbound: resolveClientUrl }),\n };\n\n if (!resolveClientUrl) {\n sharedCache.set(bundle, result);\n }\n\n return result;\n};\n\n// internal symbols to access global store\nconst REMOTE_COMPONENT_STORE = Symbol('REMOTE_COMPONENT_STORE');\nconst REMOTE_COMPONENT_KEY = '__REMOTE_COMPONENT_KEY__';\n\n// temporary global store for remote component HTML\n// the store is used to save the HTML of remote components for SSR without sending the content to the client\nconst self = globalThis as typeof globalThis & {\n [REMOTE_COMPONENT_STORE]?: Map<string, React.ReactNode>;\n};\n\nfunction getKey(bundle: string, route: string, name: string): string {\n return `${bundle}:${route}:${name}__${crypto.randomUUID()}`;\n}\n\nfunction setComponent(key: string, component: React.ReactNode): void {\n if (!self[REMOTE_COMPONENT_STORE]) {\n self[REMOTE_COMPONENT_STORE] = new Map();\n }\n self[REMOTE_COMPONENT_STORE].set(key, component);\n}\n\nfunction getComponent(key: string): React.ReactNode | undefined {\n const component = self[REMOTE_COMPONENT_STORE]?.get(key);\n // remove the component from the store after retrieving it to prevent memory leaks\n // storing the HTML in the global store is only needed for SSR and it's temporary only used for a single render\n self[REMOTE_COMPONENT_STORE]?.delete(key);\n return component;\n}\n\n/**\n * Props for the Next.js Pages Router remote component host.\n *\n * Extends {@link ConsumeRemoteComponentConfig} with Pages Router–specific `bundle` and\n * `route` props used for SSR hydration.\n */\nexport interface ConsumeRemoteComponentProps\n extends ConsumeRemoteComponentConfig {\n /** The source URL of the remote component. Required for server rendering. */\n src: string | URL;\n /** The Webpack bundle name for the remote component. */\n bundle?: string;\n /** The page route of the remote component. */\n route?: string;\n /** Loading fallback content displayed while the remote component is being fetched. */\n children?: React.ReactNode;\n [REMOTE_COMPONENT_KEY]?: string;\n}\n\n/**\n * This component handles the rendering of remote microfrontends.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n */\nexport function ConsumeRemoteComponent(props: ConsumeRemoteComponentProps) {\n const remoteComponent =\n typeof document !== 'undefined'\n ? null\n : // retrieve the HTML from the global store\n getComponent(props[REMOTE_COMPONENT_KEY] ?? DEFAULT_COMPONENT_NAME);\n\n const sharedResult = shared(\n props.bundle ?? DEFAULT_BUNDLE_NAME,\n props.resolveClientUrl,\n );\n\n useEffect(() => {\n const clientSelf = globalThis as typeof globalThis & {\n __remote_component_shared__?: Record<string, () => Promise<unknown>>;\n };\n // eslint-disable-next-line camelcase\n clientSelf.__remote_component_shared__ = sharedResult;\n }, [sharedResult]);\n\n if (!props[REMOTE_COMPONENT_KEY]) {\n return (\n <ConsumeRemoteComponentReact\n isolate={props.isolate}\n mode={props.mode}\n name={props.name}\n onBeforeLoad={props.onBeforeLoad}\n onChange={props.onChange}\n onError={props.onError}\n onLoad={props.onLoad}\n onRequest={props.onRequest}\n onResponse={props.onResponse}\n resolveClientUrl={props.resolveClientUrl}\n reset={props.reset}\n shared={sharedResult}\n src={props.src}\n >\n {props.children}\n </ConsumeRemoteComponentReact>\n );\n }\n\n return (\n <ConsumeRemoteComponentReact\n isolate={props.isolate}\n mode={props.mode}\n name={props.name}\n onBeforeLoad={props.onBeforeLoad}\n onChange={props.onChange}\n onError={props.onError}\n onLoad={props.onLoad}\n onRequest={props.onRequest}\n onResponse={props.onResponse}\n resolveClientUrl={props.resolveClientUrl}\n reset={props.reset}\n shared={sharedResult}\n src={props.src}\n >\n {remoteComponent}\n </ConsumeRemoteComponentReact>\n );\n}\n\n/**\n * Fetches the remote component properties from the server. You need to pass these properties to the `<ConsumeRemoteComponent>` component to render the fetched remote component.\n *\n * @param src - The source URL of the remote component. When using the Vercel Microfrontends solution, you can use relative paths, e.g. `/nextjs-app-remote/components/header`. Absolute URLs are also supported.\n * @param headers - The HTTP headers used for supporting the Vercel Microfrontends proxy.\n * @returns The properties of the remote component.\n *\n * @example\n *\n * ```tsx\n * import { getRemoteComponentProps } from 'remote-components/next/host/pages';\n * import type { GetServerSideProps } from 'next';\n *\n * export const getServerSideProps: GetServerSideProps<PageProps> = async function getServerSideProps({ req }) {\n * const myRemoteComponent = await getConsumeRemoteComponentProps(\n * '/nextjs-app-remote/components/header',\n * req.headers,\n * );\n * return {\n * props: {\n * remoteComponents: {\n * myRemoteComponent,\n * },\n * },\n * };\n * }\n * ```\n */\nexport async function getConsumeRemoteComponentProps(\n src: string,\n options?: {\n /**\n * Called when a fetch request is made to retrieve the remote component payload.\n * Can be used to intercept requests, modify headers, or provide a custom response.\n */\n onRequest?: OnRequestHook;\n /**\n * Called after a fetch completes to retrieve the remote component payload.\n * Can be used to inspect the response (e.g., check for redirects) or transform it.\n */\n onResponse?: OnResponseHook;\n /**\n * The name of the exposed remote component. Used to identify the remote component\n * when multiple remote components are exposed on a page.\n */\n name?: string;\n },\n): Promise<ConsumeRemoteComponentProps> {\n if (typeof document !== 'undefined') {\n throw new RemoteComponentsError(\n '`getConsumeRemoteComponentProps()` can only be used on the server side.',\n );\n }\n\n const {\n metadata: { bundle, route },\n name,\n links,\n component,\n nextData,\n remoteShared,\n } = await fetchRemoteComponent(src, {\n rsc: true,\n ...options,\n });\n\n const props: ConsumeRemoteComponentProps = {\n src,\n bundle,\n name,\n route,\n };\n\n const key = getKey(bundle, route, name);\n\n // do not render the HTML in development mode when remote is using Next.js Pages Router\n // this behavior is emulating the Next.js Pages Router FOUC as the styles are only applied on the client when running in development mode\n if (nextData?.buildId !== 'development') {\n // store the HTML in a global store\n setComponent(\n key,\n <>\n <script\n data-remote-components-shared=\"\"\n id={`${name}_shared`}\n type=\"application/json\"\n >\n {JSON.stringify(remoteShared)}\n </script>\n {links.map((link) => (\n <link\n key={`${link.as}_${link.href}`}\n {...link}\n precedence={undefined}\n />\n ))}\n {component}\n </>,\n );\n }\n\n return {\n ...props,\n // add remote component key to the props\n [REMOTE_COMPONENT_KEY]: key,\n };\n}\n"],"mappings":"AAmJM,SA0HA,UA1HA,KA0HA,YA1HA;AAnJN,OAAO;AACP,YAAY,UAAU;AACtB,YAAY,UAAU;AACtB,YAAY,YAAY;AACxB,YAAY,YAAY;AACxB,SAAS,iBAAiB;AAC1B,SAAS,0BAA0B,mCAAmC;AACtE,SAAS,sCAAsC;AAC/C,SAAS,4BAA4B;AAMrC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,6BAA6B;AACtC,SAAS,UAAU,eAAe;AAElC,MAAM,iBAAiB;AAAA,EACrB,WAAW,MAAM,OAAO,UAAU;AAAA,EAClC,iBAAiB,MAAM;AACrB,UAAM,SAAS,OAAO,UAAU;AAChC,WAAO;AAAA,MACL,KAAK,CAAC,QAAgB,OAAO,MAAM,GAAG;AAAA,MACtC,KAAK,CAAC,QAAgB,OAAO,OAAO;AAAA,IACtC;AAAA,EACF;AACF;AAEA,MAAM,cAAc,oBAAI,IAAoD;AAC5E,MAAM,SAAS,CAAC,QAAgB,qBAAwC;AAGtE,MAAI,CAAC,kBAAkB;AACrB,QAAI,YAAY,IAAI,MAAM,GAAG;AAC3B,aAAO,YAAY,IAAI,MAAM;AAAA,IAC/B;AAAA,EACF;AAEA,QAAM,SAAS;AAAA;AAAA;AAAA,IAGb,mBAAmB,MACjB,QAAQ,QAAQ,cAAc;AAAA,IAChC,0CAA0C,MACxC,QAAQ,QAAQ,cAAc;AAAA,IAChC,iCAAiC,MAC/B,QAAQ,QAAQ,KAAK,OAAO;AAAA,IAC9B,aAAa,MAAM,QAAQ,QAAQ,KAAK,OAAO;AAAA,IAC/C,iCAAiC,MAC/B,Q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AA;AAAA,YACC,iCAA8B;AAAA,YAC9B,IAAI,GAAG;AAAA,YACP,MAAK;AAAA,YAEJ,eAAK,UAAU,YAAY;AAAA;AAAA,QAC9B;AAAA,QACC,MAAM,IAAI,CAAC,SACV;AAAA,UAAC;AAAA;AAAA,YAEE,GAAG;AAAA,YACJ,YAAY;AAAA;AAAA,UAFP,GAAG,KAAK,MAAM,KAAK;AAAA,QAG1B,CACD;AAAA,QACA;AAAA,SACH;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,GAAG;AAAA;AAAA,IAEH,CAAC,oBAAoB,GAAG;AAAA,EAC1B;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/host/nextjs/pages.tsx"],"sourcesContent":["import 'remote-components/remote/defaults/wrapper';\nimport * as Form from 'next/form';\nimport * as Link from 'next/link';\nimport * as Router from 'next/router';\nimport * as Script from 'next/script';\nimport { useEffect } from 'react';\nimport { ConsumeRemoteComponent as ConsumeRemoteComponentReact } from 'remote-components/host/react';\nimport { createImageLoaderSharedEntries } from '#internal/host/nextjs/image-shared';\nimport { fetchRemoteComponent } from '#internal/host/server/fetch-remote-component';\nimport type { ConsumeRemoteComponentConfig } from '#internal/host/shared/config';\nimport type {\n OnRequestHook,\n OnResponseHook,\n} from '#internal/host/shared/fetch-interceptors';\nimport {\n isSharedModuleManifest,\n type RemoteSharedModules,\n} from '#internal/host/shared/shared-broker';\nimport {\n DEFAULT_BUNDLE_NAME,\n DEFAULT_COMPONENT_NAME,\n} from '#internal/runtime/constants';\nimport {\n DATA_REMOTE_COMPONENTS_SHARED,\n DATA_REMOTE_COMPONENTS_SHARED_MANIFEST,\n ID_SUFFIX_SHARED,\n ID_SUFFIX_SHARED_MANIFEST,\n} from '#internal/runtime/html/html-spec';\nimport type { ResolveClientUrl } from '#internal/runtime/url/resolve-client-url';\nimport { RemoteComponentsError } from '#internal/utils/error';\nimport { shared as _shared } from '#remote-components/host/defaults/pages';\n\nconst navigationImpl = {\n useRouter: () => Router.useRouter(),\n useSearchParams: () => {\n const router = Router.useRouter();\n return {\n get: (key: string) => router.query[key],\n has: (key: string) => key in router.query,\n };\n },\n};\n\nconst sharedCache = new Map<string, Record<string, () => Promise<unknown>>>();\nconst shared = (bundle: string, resolveClientUrl?: ResolveClientUrl) => {\n // Skip cache when resolveClientUrl is provided — different resolver instances\n // must not share a cache entry, since the image loader closes over the resolver.\n if (!resolveClientUrl) {\n if (sharedCache.has(bundle)) {\n return sharedCache.get(bundle);\n }\n }\n\n const result = {\n // polyfill Next.js App Router client API (minimal)\n // some API methods are not available when using a Next.js Pages Router application as host\n 'next/navigation': () =>\n Promise.resolve(navigationImpl) as Promise<unknown>,\n 'next/dist/client/components/navigation': () =>\n Promise.resolve(navigationImpl) as Promise<unknown>,\n 'next/dist/client/app-dir/link': () =>\n Promise.resolve(Link.default) as Promise<unknown>,\n 'next/link': () => Promise.resolve(Link.default) as Promise<unknown>,\n 'next/dist/client/app-dir/form': () =>\n Promise.resolve(Form.default) as Promise<unknown>,\n 'next/form': () => Promise.resolve(Form.default) as Promise<unknown>,\n 'next/dist/client/script': () =>\n Promise.resolve(Script.default) as Promise<unknown>,\n 'next/script': () => Promise.resolve(Script.default) as Promise<unknown>,\n 'next/router': () => Promise.resolve(Router) as Promise<unknown>,\n ..._shared,\n ...createImageLoaderSharedEntries({ unbound: resolveClientUrl }),\n };\n\n if (!resolveClientUrl) {\n sharedCache.set(bundle, result);\n }\n\n return result;\n};\n\n// internal symbols to access global store\nconst REMOTE_COMPONENT_STORE = Symbol('REMOTE_COMPONENT_STORE');\nconst REMOTE_COMPONENT_KEY = '__REMOTE_COMPONENT_KEY__';\n\n// temporary global store for remote component HTML\n// the store is used to save the HTML of remote components for SSR without sending the content to the client\nconst self = globalThis as typeof globalThis & {\n [REMOTE_COMPONENT_STORE]?: Map<string, React.ReactNode>;\n};\n\nfunction RemoteSharedScript({\n name,\n remoteShared,\n}: {\n name: string;\n remoteShared: RemoteSharedModules;\n}) {\n if (isSharedModuleManifest(remoteShared)) {\n return (\n <script\n {...{ [DATA_REMOTE_COMPONENTS_SHARED_MANIFEST]: '' }}\n id={`${name}${ID_SUFFIX_SHARED_MANIFEST}`}\n type=\"application/json\"\n >\n {JSON.stringify(remoteShared)}\n </script>\n );\n }\n\n return (\n // @legacy(remote-components<=0.4.x): keep writing the historical shared\n // map until hosts and remotes on 0.4.x are outside support.\n <script\n {...{ [DATA_REMOTE_COMPONENTS_SHARED]: '' }}\n id={`${name}${ID_SUFFIX_SHARED}`}\n type=\"application/json\"\n >\n {JSON.stringify(remoteShared)}\n </script>\n );\n}\n\nfunction getKey(bundle: string, route: string, name: string): string {\n return `${bundle}:${route}:${name}__${crypto.randomUUID()}`;\n}\n\nfunction setComponent(key: string, component: React.ReactNode): void {\n if (!self[REMOTE_COMPONENT_STORE]) {\n self[REMOTE_COMPONENT_STORE] = new Map();\n }\n self[REMOTE_COMPONENT_STORE].set(key, component);\n}\n\nfunction getComponent(key: string): React.ReactNode | undefined {\n const component = self[REMOTE_COMPONENT_STORE]?.get(key);\n // remove the component from the store after retrieving it to prevent memory leaks\n // storing the HTML in the global store is only needed for SSR and it's temporary only used for a single render\n self[REMOTE_COMPONENT_STORE]?.delete(key);\n return component;\n}\n\n/**\n * Props for the Next.js Pages Router remote component host.\n *\n * Extends {@link ConsumeRemoteComponentConfig} with Pages Router–specific `bundle` and\n * `route` props used for SSR hydration.\n */\nexport interface ConsumeRemoteComponentProps\n extends ConsumeRemoteComponentConfig {\n /** The source URL of the remote component. Required for server rendering. */\n src: string | URL;\n /** The Webpack bundle name for the remote component. */\n bundle?: string;\n /** The page route of the remote component. */\n route?: string;\n /** Loading fallback content displayed while the remote component is being fetched. */\n children?: React.ReactNode;\n [REMOTE_COMPONENT_KEY]?: string;\n}\n\n/**\n * This component handles the rendering of remote microfrontends.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n */\nexport function ConsumeRemoteComponent(props: ConsumeRemoteComponentProps) {\n const remoteComponent =\n typeof document !== 'undefined'\n ? null\n : // retrieve the HTML from the global store\n getComponent(props[REMOTE_COMPONENT_KEY] ?? DEFAULT_COMPONENT_NAME);\n\n const sharedResult = shared(\n props.bundle ?? DEFAULT_BUNDLE_NAME,\n props.resolveClientUrl,\n );\n\n useEffect(() => {\n const clientSelf = globalThis as typeof globalThis & {\n __remote_component_shared__?: Record<string, () => Promise<unknown>>;\n };\n // eslint-disable-next-line camelcase\n clientSelf.__remote_component_shared__ = sharedResult;\n }, [sharedResult]);\n\n if (!props[REMOTE_COMPONENT_KEY]) {\n return (\n <ConsumeRemoteComponentReact\n isolate={props.isolate}\n mode={props.mode}\n name={props.name}\n onBeforeLoad={props.onBeforeLoad}\n onChange={props.onChange}\n onError={props.onError}\n onLoad={props.onLoad}\n onRequest={props.onRequest}\n onResponse={props.onResponse}\n resolveClientUrl={props.resolveClientUrl}\n reset={props.reset}\n shared={sharedResult}\n src={props.src}\n >\n {props.children}\n </ConsumeRemoteComponentReact>\n );\n }\n\n return (\n <ConsumeRemoteComponentReact\n isolate={props.isolate}\n mode={props.mode}\n name={props.name}\n onBeforeLoad={props.onBeforeLoad}\n onChange={props.onChange}\n onError={props.onError}\n onLoad={props.onLoad}\n onRequest={props.onRequest}\n onResponse={props.onResponse}\n resolveClientUrl={props.resolveClientUrl}\n reset={props.reset}\n shared={sharedResult}\n src={props.src}\n >\n {remoteComponent}\n </ConsumeRemoteComponentReact>\n );\n}\n\n/**\n * Fetches the remote component properties from the server. You need to pass these properties to the `<ConsumeRemoteComponent>` component to render the fetched remote component.\n *\n * @param src - The source URL of the remote component. When using the Vercel Microfrontends solution, you can use relative paths, e.g. `/nextjs-app-remote/components/header`. Absolute URLs are also supported.\n * @param headers - The HTTP headers used for supporting the Vercel Microfrontends proxy.\n * @returns The properties of the remote component.\n *\n * @example\n *\n * ```tsx\n * import { getRemoteComponentProps } from 'remote-components/next/host/pages';\n * import type { GetServerSideProps } from 'next';\n *\n * export const getServerSideProps: GetServerSideProps<PageProps> = async function getServerSideProps({ req }) {\n * const myRemoteComponent = await getConsumeRemoteComponentProps(\n * '/nextjs-app-remote/components/header',\n * req.headers,\n * );\n * return {\n * props: {\n * remoteComponents: {\n * myRemoteComponent,\n * },\n * },\n * };\n * }\n * ```\n */\nexport async function getConsumeRemoteComponentProps(\n src: string,\n options?: {\n /**\n * Called when a fetch request is made to retrieve the remote component payload.\n * Can be used to intercept requests, modify headers, or provide a custom response.\n */\n onRequest?: OnRequestHook;\n /**\n * Called after a fetch completes to retrieve the remote component payload.\n * Can be used to inspect the response (e.g., check for redirects) or transform it.\n */\n onResponse?: OnResponseHook;\n /**\n * The name of the exposed remote component. Used to identify the remote component\n * when multiple remote components are exposed on a page.\n */\n name?: string;\n },\n): Promise<ConsumeRemoteComponentProps> {\n if (typeof document !== 'undefined') {\n throw new RemoteComponentsError(\n '`getConsumeRemoteComponentProps()` can only be used on the server side.',\n );\n }\n\n const {\n metadata: { bundle, route },\n name,\n links,\n component,\n nextData,\n remoteShared,\n } = await fetchRemoteComponent(src, {\n rsc: true,\n ...options,\n });\n\n const props: ConsumeRemoteComponentProps = {\n src,\n bundle,\n name,\n route,\n };\n\n const key = getKey(bundle, route, name);\n\n // do not render the HTML in development mode when remote is using Next.js Pages Router\n // this behavior is emulating the Next.js Pages Router FOUC as the styles are only applied on the client when running in development mode\n if (nextData?.buildId !== 'development') {\n // store the HTML in a global store\n setComponent(\n key,\n <>\n <RemoteSharedScript name={name} remoteShared={remoteShared} />\n {links.map((link) => (\n <link\n key={`${link.as}_${link.href}`}\n {...link}\n precedence={undefined}\n />\n ))}\n {component}\n </>,\n );\n }\n\n return {\n ...props,\n // add remote component key to the props\n [REMOTE_COMPONENT_KEY]: key,\n };\n}\n"],"mappings":"AAoGM,SAmNA,UAnNA,KAmNA,YAnNA;AApGN,OAAO;AACP,YAAY,UAAU;AACtB,YAAY,UAAU;AACtB,YAAY,YAAY;AACxB,YAAY,YAAY;AACxB,SAAS,iBAAiB;AAC1B,SAAS,0BAA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