remote-components 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/dist/config/nextjs.cjs +122 -62
  2. package/dist/config/nextjs.cjs.map +1 -1
  3. package/dist/config/nextjs.js +116 -56
  4. package/dist/config/nextjs.js.map +1 -1
  5. package/dist/config/webpack.cjs +5 -1
  6. package/dist/config/webpack.cjs.map +1 -1
  7. package/dist/config/webpack.js +5 -1
  8. package/dist/config/webpack.js.map +1 -1
  9. package/dist/host/defaults/app.cjs +2 -5
  10. package/dist/host/defaults/app.cjs.map +1 -1
  11. package/dist/host/defaults/app.d.ts +1 -3
  12. package/dist/host/defaults/app.js +1 -4
  13. package/dist/host/defaults/app.js.map +1 -1
  14. package/dist/host/defaults/pages.cjs +2 -5
  15. package/dist/host/defaults/pages.cjs.map +1 -1
  16. package/dist/host/defaults/pages.d.ts +1 -3
  17. package/dist/host/defaults/pages.js +1 -4
  18. package/dist/host/defaults/pages.js.map +1 -1
  19. package/dist/host/defaults/shared.cjs +32 -0
  20. package/dist/host/defaults/shared.cjs.map +1 -0
  21. package/dist/host/defaults/shared.d.ts +3 -0
  22. package/dist/host/defaults/shared.js +8 -0
  23. package/dist/host/defaults/shared.js.map +1 -0
  24. package/dist/host/html.cjs +533 -351
  25. package/dist/host/html.cjs.map +1 -1
  26. package/dist/host/html.js +533 -351
  27. package/dist/host/html.js.map +1 -1
  28. package/dist/host/nextjs/app/client-only.cjs +494 -285
  29. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  30. package/dist/host/nextjs/app/client-only.js +468 -259
  31. package/dist/host/nextjs/app/client-only.js.map +1 -1
  32. package/dist/host/react.cjs +412 -241
  33. package/dist/host/react.cjs.map +1 -1
  34. package/dist/host/react.js +412 -241
  35. package/dist/host/react.js.map +1 -1
  36. package/dist/internal/config/webpack/apply-shared-modules.cjs +6 -4
  37. package/dist/internal/config/webpack/apply-shared-modules.cjs.map +1 -1
  38. package/dist/internal/config/webpack/apply-shared-modules.js +6 -4
  39. package/dist/internal/config/webpack/apply-shared-modules.js.map +1 -1
  40. package/dist/internal/config/webpack/next-client-pages-loader.cjs +6 -7
  41. package/dist/internal/config/webpack/next-client-pages-loader.cjs.map +1 -1
  42. package/dist/internal/config/webpack/next-client-pages-loader.js +6 -7
  43. package/dist/internal/config/webpack/next-client-pages-loader.js.map +1 -1
  44. package/dist/internal/host/nextjs/app-client.cjs +6 -22
  45. package/dist/internal/host/nextjs/app-client.cjs.map +1 -1
  46. package/dist/internal/host/nextjs/app-client.js +5 -11
  47. package/dist/internal/host/nextjs/app-client.js.map +1 -1
  48. package/dist/internal/host/nextjs/dom-flight.cjs +19 -39
  49. package/dist/internal/host/nextjs/dom-flight.cjs.map +1 -1
  50. package/dist/internal/host/nextjs/dom-flight.js +31 -39
  51. package/dist/internal/host/nextjs/dom-flight.js.map +1 -1
  52. package/dist/internal/host/nextjs/image-shared.cjs +39 -3
  53. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  54. package/dist/internal/host/nextjs/image-shared.d.ts +5 -10
  55. package/dist/internal/host/nextjs/image-shared.js +29 -3
  56. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  57. package/dist/internal/host/nextjs/shared-import.cjs +46 -0
  58. package/dist/internal/host/nextjs/shared-import.cjs.map +1 -0
  59. package/dist/internal/host/nextjs/shared-import.d.ts +3 -0
  60. package/dist/internal/host/nextjs/shared-import.js +12 -0
  61. package/dist/internal/host/nextjs/shared-import.js.map +1 -0
  62. package/dist/internal/host/server/fetch-remote-component.cjs +2 -1
  63. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  64. package/dist/internal/host/server/fetch-remote-component.js +2 -1
  65. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  66. package/dist/internal/host/shared/polyfill.cjs +8 -7
  67. package/dist/internal/host/shared/polyfill.cjs.map +1 -1
  68. package/dist/internal/host/shared/polyfill.js +8 -7
  69. package/dist/internal/host/shared/polyfill.js.map +1 -1
  70. package/dist/internal/host/shared/shared-module-resolver.cjs +117 -0
  71. package/dist/internal/host/shared/shared-module-resolver.cjs.map +1 -0
  72. package/dist/internal/host/shared/shared-module-resolver.d.ts +64 -0
  73. package/dist/internal/host/shared/shared-module-resolver.js +78 -0
  74. package/dist/internal/host/shared/shared-module-resolver.js.map +1 -0
  75. package/dist/internal/remote/nextjs/next-internals.cjs +53 -0
  76. package/dist/internal/remote/nextjs/next-internals.cjs.map +1 -0
  77. package/dist/internal/remote/nextjs/next-internals.d.ts +42 -0
  78. package/dist/internal/remote/nextjs/next-internals.js +26 -0
  79. package/dist/internal/remote/nextjs/next-internals.js.map +1 -0
  80. package/dist/internal/runtime/html/apply-origin.cjs +11 -32
  81. package/dist/internal/runtime/html/apply-origin.cjs.map +1 -1
  82. package/dist/internal/runtime/html/apply-origin.js +11 -32
  83. package/dist/internal/runtime/html/apply-origin.js.map +1 -1
  84. package/dist/internal/runtime/html/html-spec.cjs +78 -0
  85. package/dist/internal/runtime/html/html-spec.cjs.map +1 -0
  86. package/dist/internal/runtime/html/html-spec.d.ts +23 -0
  87. package/dist/internal/runtime/html/html-spec.js +41 -0
  88. package/dist/internal/runtime/html/html-spec.js.map +1 -0
  89. package/dist/internal/runtime/html/parse-remote-html.cjs +15 -12
  90. package/dist/internal/runtime/html/parse-remote-html.cjs.map +1 -1
  91. package/dist/internal/runtime/html/parse-remote-html.js +29 -12
  92. package/dist/internal/runtime/html/parse-remote-html.js.map +1 -1
  93. package/dist/internal/runtime/html/rewrite-srcset.cjs +38 -0
  94. package/dist/internal/runtime/html/rewrite-srcset.cjs.map +1 -0
  95. package/dist/internal/runtime/html/rewrite-srcset.d.ts +12 -0
  96. package/dist/internal/runtime/html/rewrite-srcset.js +14 -0
  97. package/dist/internal/runtime/html/rewrite-srcset.js.map +1 -0
  98. package/dist/internal/runtime/loaders/component-loader.cjs +25 -44
  99. package/dist/internal/runtime/loaders/component-loader.cjs.map +1 -1
  100. package/dist/internal/runtime/loaders/component-loader.d.ts +3 -1
  101. package/dist/internal/runtime/loaders/component-loader.js +28 -44
  102. package/dist/internal/runtime/loaders/component-loader.js.map +1 -1
  103. package/dist/internal/runtime/loaders/script-loader.cjs +7 -0
  104. package/dist/internal/runtime/loaders/script-loader.cjs.map +1 -1
  105. package/dist/internal/runtime/loaders/script-loader.js +7 -0
  106. package/dist/internal/runtime/loaders/script-loader.js.map +1 -1
  107. package/dist/internal/runtime/loaders/static-loader.cjs +15 -21
  108. package/dist/internal/runtime/loaders/static-loader.cjs.map +1 -1
  109. package/dist/internal/runtime/loaders/static-loader.d.ts +3 -1
  110. package/dist/internal/runtime/loaders/static-loader.js +15 -21
  111. package/dist/internal/runtime/loaders/static-loader.js.map +1 -1
  112. package/dist/internal/runtime/namespace.cjs +82 -0
  113. package/dist/internal/runtime/namespace.cjs.map +1 -0
  114. package/dist/internal/runtime/namespace.d.ts +5 -0
  115. package/dist/internal/runtime/namespace.js +58 -0
  116. package/dist/internal/runtime/namespace.js.map +1 -0
  117. package/dist/internal/runtime/rsc-imports.cjs +86 -0
  118. package/dist/internal/runtime/rsc-imports.cjs.map +1 -0
  119. package/dist/internal/runtime/rsc-imports.d.ts +39 -0
  120. package/dist/internal/runtime/rsc-imports.js +50 -0
  121. package/dist/internal/runtime/rsc-imports.js.map +1 -0
  122. package/dist/internal/{host/shared/resolved-data.cjs → runtime/rsc-runtime.cjs} +3 -3
  123. package/dist/internal/runtime/rsc-runtime.cjs.map +1 -0
  124. package/dist/internal/runtime/rsc-runtime.d.ts +37 -0
  125. package/dist/internal/runtime/rsc-runtime.js +1 -0
  126. package/dist/internal/runtime/rsc.cjs +23 -12
  127. package/dist/internal/runtime/rsc.cjs.map +1 -1
  128. package/dist/internal/runtime/rsc.d.ts +19 -2
  129. package/dist/internal/runtime/rsc.js +20 -11
  130. package/dist/internal/runtime/rsc.js.map +1 -1
  131. package/dist/internal/runtime/turbopack/chunk-loader.cjs +53 -35
  132. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  133. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +1 -1
  134. package/dist/internal/runtime/turbopack/chunk-loader.js +53 -35
  135. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  136. package/dist/internal/runtime/turbopack/module.cjs +19 -17
  137. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  138. package/dist/internal/runtime/turbopack/module.d.ts +23 -1
  139. package/dist/internal/runtime/turbopack/module.js +19 -18
  140. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  141. package/dist/internal/runtime/turbopack/patterns.cjs +26 -10
  142. package/dist/internal/runtime/turbopack/patterns.cjs.map +1 -1
  143. package/dist/internal/runtime/turbopack/patterns.d.ts +44 -49
  144. package/dist/internal/runtime/turbopack/patterns.js +23 -7
  145. package/dist/internal/runtime/turbopack/patterns.js.map +1 -1
  146. package/dist/internal/runtime/turbopack/{webpack-runtime.cjs → remote-scope-setup.cjs} +35 -32
  147. package/dist/internal/runtime/turbopack/remote-scope-setup.cjs.map +1 -0
  148. package/dist/internal/runtime/turbopack/remote-scope-setup.d.ts +25 -0
  149. package/dist/internal/runtime/turbopack/{webpack-runtime.js → remote-scope-setup.js} +36 -19
  150. package/dist/internal/runtime/turbopack/remote-scope-setup.js.map +1 -0
  151. package/dist/internal/runtime/turbopack/remote-scope.cjs +4 -6
  152. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -1
  153. package/dist/internal/runtime/turbopack/remote-scope.d.ts +20 -1
  154. package/dist/internal/runtime/turbopack/remote-scope.js +4 -6
  155. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -1
  156. package/dist/internal/runtime/turbopack/shared-modules.cjs +23 -15
  157. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  158. package/dist/internal/runtime/turbopack/shared-modules.d.ts +13 -1
  159. package/dist/internal/runtime/turbopack/shared-modules.js +25 -18
  160. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  161. package/dist/internal/runtime/types.cjs.map +1 -1
  162. package/dist/internal/runtime/types.d.ts +5 -41
  163. package/dist/internal/utils/logger.cjs +1 -1
  164. package/dist/internal/utils/logger.cjs.map +1 -1
  165. package/dist/internal/utils/logger.d.ts +2 -2
  166. package/dist/internal/utils/logger.js +1 -1
  167. package/dist/internal/utils/logger.js.map +1 -1
  168. package/dist/internal/utils/project-id-env.cjs +31 -0
  169. package/dist/internal/utils/project-id-env.cjs.map +1 -0
  170. package/dist/internal/utils/project-id-env.d.ts +7 -0
  171. package/dist/internal/utils/project-id-env.js +7 -0
  172. package/dist/internal/utils/project-id-env.js.map +1 -0
  173. package/dist/internal/utils/project-id.cjs +46 -0
  174. package/dist/internal/utils/project-id.cjs.map +1 -0
  175. package/dist/internal/utils/project-id.d.ts +8 -0
  176. package/dist/internal/utils/project-id.js +22 -0
  177. package/dist/internal/utils/project-id.js.map +1 -0
  178. package/dist/remote/defaults/app.cjs +2 -5
  179. package/dist/remote/defaults/app.cjs.map +1 -1
  180. package/dist/remote/defaults/app.d.ts +1 -3
  181. package/dist/remote/defaults/app.js +1 -4
  182. package/dist/remote/defaults/app.js.map +1 -1
  183. package/dist/remote/defaults/pages.cjs +2 -5
  184. package/dist/remote/defaults/pages.cjs.map +1 -1
  185. package/dist/remote/defaults/pages.d.ts +1 -3
  186. package/dist/remote/defaults/pages.js +1 -4
  187. package/dist/remote/defaults/pages.js.map +1 -1
  188. package/dist/remote/defaults/shared.cjs +32 -0
  189. package/dist/remote/defaults/shared.cjs.map +1 -0
  190. package/dist/remote/defaults/shared.d.ts +3 -0
  191. package/dist/remote/defaults/shared.js +8 -0
  192. package/dist/remote/defaults/shared.js.map +1 -0
  193. package/dist/remote/html.cjs +78 -22
  194. package/dist/remote/html.cjs.map +1 -1
  195. package/dist/remote/html.js +78 -22
  196. package/dist/remote/html.js.map +1 -1
  197. package/dist/remote/nextjs/app.cjs +16 -56
  198. package/dist/remote/nextjs/app.cjs.map +1 -1
  199. package/dist/remote/nextjs/app.js +26 -46
  200. package/dist/remote/nextjs/app.js.map +1 -1
  201. package/dist/remote/nextjs/pages.cjs +2 -1
  202. package/dist/remote/nextjs/pages.cjs.map +1 -1
  203. package/dist/remote/nextjs/pages.js +2 -1
  204. package/dist/remote/nextjs/pages.js.map +1 -1
  205. package/dist/types-59251814.d.ts +94 -0
  206. package/package.json +1 -1
  207. package/dist/internal/host/shared/resolved-data.cjs.map +0 -1
  208. package/dist/internal/host/shared/resolved-data.d.ts +0 -48
  209. package/dist/internal/host/shared/resolved-data.js +0 -1
  210. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +0 -1
  211. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +0 -23
  212. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +0 -1
  213. /package/dist/internal/{host/shared/resolved-data.js.map → runtime/rsc-runtime.js.map} +0 -0
@@ -20,25 +20,36 @@ var init_constants = __esm({
20
20
  }
21
21
  });
22
22
 
23
+ // src/host/defaults/shared.ts
24
+ var shared;
25
+ var init_shared = __esm({
26
+ "src/host/defaults/shared.ts"() {
27
+ "use strict";
28
+ init_constants();
29
+ shared = {
30
+ __remote_components_missing_shared__: () => Promise.reject(new Error(MISSING_SHARED_MODULES_MESSAGE))
31
+ };
32
+ }
33
+ });
34
+
23
35
  // src/host/defaults/app.ts
24
36
  var app_exports = {};
25
37
  __export(app_exports, {
26
38
  shared: () => shared
27
39
  });
28
- var shared;
29
40
  var init_app = __esm({
30
41
  "src/host/defaults/app.ts"() {
31
42
  "use strict";
32
- init_constants();
33
- shared = {
34
- __remote_components_missing_shared__: () => Promise.reject(new Error(MISSING_SHARED_MODULES_MESSAGE))
35
- };
43
+ init_shared();
36
44
  }
37
45
  });
38
46
 
39
47
  // src/host/nextjs/app-client-only.tsx
40
48
  import { useMemo as useMemo3 } from "react";
41
49
 
50
+ // src/host/nextjs/image-shared.ts
51
+ import { createElement, forwardRef } from "react";
52
+
42
53
  // src/utils/index.ts
43
54
  function escapeString(str) {
44
55
  return str.replace(/[^a-z0-9]/g, "_");
@@ -65,6 +76,62 @@ function getBundleKey(bundle) {
65
76
  return escapeString(bundle);
66
77
  }
67
78
 
79
+ // src/runtime/namespace.ts
80
+ var SHADOW_ROOT_PREFIX = "__remote_components_shadowroot_";
81
+ var LEGACY_ALIASES = [
82
+ { global: "__remote_component_scopes__", prop: "scopes" },
83
+ {
84
+ global: "__remote_components_turbopack_chunk_loader_promise__",
85
+ prop: "chunkCache"
86
+ },
87
+ { global: "__remote_script_entrypoint_mount__", prop: "mountFns" },
88
+ { global: "__remote_script_entrypoint_unmount__", prop: "unmountFns" },
89
+ { global: "__remote_bundle_url__", prop: "bundleUrls" },
90
+ { global: "__rc_module_registry__", prop: "moduleRegistry" },
91
+ {
92
+ global: "__remote_component_host_shared_modules__",
93
+ prop: "hostSharedModules"
94
+ },
95
+ { global: "__remote_next_css__", prop: "cssCache" }
96
+ ];
97
+ function getNamespace() {
98
+ const g = globalThis;
99
+ const existing = g.__remote_components__;
100
+ if (existing) {
101
+ return existing;
102
+ }
103
+ const ns = {
104
+ scopes: /* @__PURE__ */ new Map(),
105
+ chunkCache: {},
106
+ mountFns: {},
107
+ unmountFns: {},
108
+ bundleUrls: {},
109
+ moduleRegistry: {},
110
+ dispatcherRuntime: void 0,
111
+ hostSharedModules: {},
112
+ cssCache: {},
113
+ shadowRoots: {}
114
+ };
115
+ const nsRecord = ns;
116
+ for (const { global, prop } of LEGACY_ALIASES) {
117
+ const legacyValue = g[global];
118
+ if (legacyValue != null) {
119
+ nsRecord[prop] = legacyValue;
120
+ }
121
+ g[global] = ns[prop];
122
+ }
123
+ const gRecord = g;
124
+ for (const key of Object.keys(gRecord)) {
125
+ if (key.startsWith(SHADOW_ROOT_PREFIX)) {
126
+ const suffix = key.slice(SHADOW_ROOT_PREFIX.length);
127
+ ns.shadowRoots[suffix] = gRecord[key];
128
+ delete gRecord[key];
129
+ }
130
+ }
131
+ g.__remote_components__ = ns;
132
+ return ns;
133
+ }
134
+
68
135
  // src/runtime/patterns.ts
69
136
  var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
70
137
  var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
@@ -189,7 +256,7 @@ Docs: ${CORS_DOCS_URL}`
189
256
 
190
257
  // src/utils/logger.ts
191
258
  var PREFIX = "remote-components";
192
- var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
259
+ var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true" || typeof process !== "undefined" && process.env.RC_DEBUG === "true";
193
260
  function logDebug(location2, message) {
194
261
  if (DEBUG) {
195
262
  console.debug(`[${PREFIX}:${location2}]: ${message}`);
@@ -221,11 +288,7 @@ function warnCrossOriginFetchError(logLocation, url) {
221
288
 
222
289
  // src/runtime/turbopack/remote-scope.ts
223
290
  function getRegistry() {
224
- const self = globalThis;
225
- if (!self.__remote_component_scopes__) {
226
- self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
227
- }
228
- return self.__remote_component_scopes__;
291
+ return getNamespace().scopes;
229
292
  }
230
293
  function createScope(name, url, runtime, resolveClientUrl) {
231
294
  const isCrossOrigin = url.origin !== location.origin;
@@ -243,7 +306,8 @@ function createScope(name, url, runtime, resolveClientUrl) {
243
306
  resolveClientUrl,
244
307
  moduleCache: {},
245
308
  sharedModules: {},
246
- moduleGlobal: {}
309
+ moduleGlobal: {},
310
+ turbopackModules: []
247
311
  };
248
312
  }
249
313
  function registerScope(scope) {
@@ -340,19 +404,54 @@ function createImageLoaderSharedEntries({
340
404
  bound,
341
405
  unbound
342
406
  } = {}) {
343
- const entry = (bundle) => {
407
+ const loaderEntry = (bundle) => {
344
408
  const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
345
409
  return Promise.resolve({
346
410
  default: createRemoteImageLoader(bundle, resolveClientUrl),
347
411
  __esModule: true
348
412
  });
349
413
  };
414
+ const imageEntry = async (bundle) => {
415
+ const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
416
+ const rawLoader = createRemoteImageLoader(bundle, resolveClientUrl);
417
+ const remoteLoader = Object.assign(
418
+ (p) => rawLoader({ ...p, config: { path: "/_next/image" } }),
419
+ { __next_img_default: true }
420
+ );
421
+ const mod = await import("next/image");
422
+ const OriginalImage = mod.default;
423
+ const RemoteImage = forwardRef(
424
+ (props, ref) => createElement(OriginalImage, {
425
+ ...props,
426
+ loader: props.loader ?? remoteLoader,
427
+ ref
428
+ })
429
+ );
430
+ RemoteImage.displayName = "RemoteImage";
431
+ return { ...mod, default: RemoteImage, __esModule: true };
432
+ };
350
433
  return {
351
- "next/dist/shared/lib/image-loader": entry,
352
- "next/dist/esm/shared/lib/image-loader": entry
434
+ "next/dist/shared/lib/image-loader": loaderEntry,
435
+ "next/dist/esm/shared/lib/image-loader": loaderEntry,
436
+ // Can be removed once 0.2.x support is dropped.
437
+ "next/image": imageEntry,
438
+ // Can be removed once 0.2.x support is dropped.
439
+ "next/dist/client/image-component": imageEntry,
440
+ // Can be removed once 0.2.x support is dropped.
441
+ "next/dist/api/image": imageEntry
353
442
  };
354
443
  }
355
444
 
445
+ // src/host/nextjs/shared-import.ts
446
+ async function tryImportShared() {
447
+ try {
448
+ const { shared: shared2 } = await Promise.resolve().then(() => (init_app(), app_exports));
449
+ return shared2;
450
+ } catch {
451
+ return {};
452
+ }
453
+ }
454
+
356
455
  // src/host/nextjs/app-client-only.tsx
357
456
  import { RemoteComponentsContext } from "#internal/host/react/context";
358
457
 
@@ -427,9 +526,9 @@ function getClientOrServerUrl(src, serverFallback) {
427
526
  // src/host/shared/polyfill.tsx
428
527
  import { jsx } from "react/jsx-runtime";
429
528
  function sharedPolyfills(shared2, resolveClientUrl) {
430
- const self = globalThis;
529
+ const hostShared = getNamespace().hostSharedModules;
431
530
  const polyfill = {
432
- "next/dist/client/components/navigation": self.__remote_component_host_shared_modules__?.["next/navigation"] ?? shared2?.["next/navigation"] ?? (() => Promise.resolve({
531
+ "next/dist/client/components/navigation": hostShared["next/navigation"] ?? shared2?.["next/navigation"] ?? (() => Promise.resolve({
433
532
  useRouter() {
434
533
  return {
435
534
  push: (routerUrl) => {
@@ -460,7 +559,7 @@ function sharedPolyfills(shared2, resolveClientUrl) {
460
559
  },
461
560
  __esModule: true
462
561
  })),
463
- "next/dist/client/app-dir/link": self.__remote_component_host_shared_modules__?.["next/link"] ?? shared2?.["next/link"] ?? (() => Promise.resolve({
562
+ "next/dist/client/app-dir/link": hostShared["next/link"] ?? shared2?.["next/link"] ?? (() => Promise.resolve({
464
563
  default: ({
465
564
  scroll: _,
466
565
  replace,
@@ -510,7 +609,7 @@ function sharedPolyfills(shared2, resolveClientUrl) {
510
609
  },
511
610
  __esModule: true
512
611
  })),
513
- "next/dist/client/app-dir/form": self.__remote_component_host_shared_modules__?.["next/form"] ?? shared2?.["next/form"] ?? (() => Promise.resolve({
612
+ "next/dist/client/app-dir/form": hostShared["next/form"] ?? shared2?.["next/form"] ?? (() => Promise.resolve({
514
613
  default: () => {
515
614
  throw new Error("Next.js <Form> component not implemented");
516
615
  },
@@ -521,17 +620,17 @@ function sharedPolyfills(shared2, resolveClientUrl) {
521
620
  // This gives us full next/image fidelity (fill, priority, srcSet, blur
522
621
  // placeholders, error handling) while routing image optimization through the
523
622
  // remote app's /_next/image endpoint.
524
- "next/dist/shared/lib/image-loader": self.__remote_component_host_shared_modules__?.["next/dist/shared/lib/image-loader"] ?? shared2?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
623
+ "next/dist/shared/lib/image-loader": hostShared["next/dist/shared/lib/image-loader"] ?? shared2?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
525
624
  default: createRemoteImageLoader(bundle, resolveClientUrl),
526
625
  __esModule: true
527
626
  })),
528
- "next/dist/client/script": self.__remote_component_host_shared_modules__?.["next/script"] ?? shared2?.["next/script"] ?? (() => Promise.resolve({
627
+ "next/dist/client/script": hostShared["next/script"] ?? shared2?.["next/script"] ?? (() => Promise.resolve({
529
628
  // TODO: implement <Script> component for non-Next.js host applications
530
629
  // do not throw an error for now
531
630
  default: () => null,
532
631
  __esModule: true
533
632
  })),
534
- "next/router": self.__remote_component_host_shared_modules__?.["next/router"] ?? shared2?.["next/router"] ?? (() => (
633
+ "next/router": hostShared["next/router"] ?? shared2?.["next/router"] ?? (() => (
535
634
  // TODO: incomplete implementation
536
635
  Promise.resolve({
537
636
  useRouter() {
@@ -567,6 +666,68 @@ function sharedPolyfills(shared2, resolveClientUrl) {
567
666
  return polyfill;
568
667
  }
569
668
 
669
+ // src/host/shared/shared-module-resolver.ts
670
+ var CORE_REACT_PATH_MAP = {
671
+ react: "/react/index.js",
672
+ "react/jsx-dev-runtime": "/react/jsx-dev-runtime.js",
673
+ "react/jsx-runtime": "/react/jsx-runtime.js",
674
+ "react-dom": "/react-dom/index.js",
675
+ "react-dom/client": "/react-dom/client.js"
676
+ };
677
+ var VENDOR_SHARED = Object.fromEntries(
678
+ Object.entries(CORE_REACT_PATH_MAP).filter(([key]) => key !== "react-dom/client").map(([key, path]) => [key, `'${path}'`])
679
+ );
680
+ function buildCoreShared(userShared) {
681
+ return {
682
+ react: async () => (await import("react")).default,
683
+ "react-dom": async () => (await import("react-dom")).default,
684
+ "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
685
+ "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
686
+ "react-dom/client": async () => (await import("react-dom/client")).default,
687
+ ...userShared
688
+ };
689
+ }
690
+ function buildHostShared(userShared, resolveClientUrl, options) {
691
+ const self = globalThis;
692
+ const result = {
693
+ ...sharedPolyfills(userShared, resolveClientUrl),
694
+ ...self.__remote_component_host_shared_modules__,
695
+ ...userShared
696
+ };
697
+ if (options?.includeRemoteComponentShared) {
698
+ Object.assign(result, self.__remote_component_shared__);
699
+ }
700
+ return result;
701
+ }
702
+ async function buildWebpackResolve(hostShared, remoteShared, bundle, reactModules, callerTag = "SharedModuleResolver") {
703
+ const resolve = {
704
+ ...reactModules,
705
+ ...Object.entries(remoteShared).reduce(
706
+ (acc, [key, value]) => {
707
+ if (typeof hostShared[value] !== "undefined") {
708
+ acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
709
+ } else {
710
+ logDebug(
711
+ callerTag,
712
+ `Remote requests "${value}" but host doesn't provide it`
713
+ );
714
+ }
715
+ return acc;
716
+ },
717
+ {}
718
+ )
719
+ };
720
+ await Promise.all(
721
+ Object.entries(resolve).map(async ([key, value]) => {
722
+ if (typeof value === "function") {
723
+ resolve[key] = await value(bundle);
724
+ }
725
+ return Promise.resolve(value);
726
+ })
727
+ );
728
+ return resolve;
729
+ }
730
+
570
731
  // src/host/shared/state.ts
571
732
  function createHostState() {
572
733
  return {
@@ -593,8 +754,8 @@ function resolveNameFromSrc(src, defaultName) {
593
754
  return name || defaultName;
594
755
  }
595
756
 
596
- // src/runtime/html/apply-origin.ts
597
- var tagNames = [
757
+ // src/runtime/html/html-spec.ts
758
+ var ORIGIN_REWRITE_TAGS = [
598
759
  "img",
599
760
  "source",
600
761
  "video",
@@ -605,10 +766,37 @@ var tagNames = [
605
766
  "script",
606
767
  "link"
607
768
  ];
769
+ var ID_SUFFIX_RSC = "_rsc";
770
+ var ID_SUFFIX_SSR = "_ssr";
771
+ var ID_SUFFIX_SHARED = "_shared";
772
+ var DATA_BUNDLE = "data-bundle";
773
+ var DATA_ROUTE = "data-route";
774
+ var DATA_RUNTIME = "data-runtime";
775
+ var DATA_TYPE = "data-type";
776
+ var DATA_SRC = "data-src";
777
+ var DATA_REMOTE_COMPONENTS_SHARED = "data-remote-components-shared";
778
+ var TAG_REMOTE_COMPONENT = "remote-component";
779
+ var NEXT_DATA_ID = "__NEXT_DATA__";
780
+ var REMOTE_NEXT_DATA_ID = "__REMOTE_NEXT_DATA__";
781
+ var NEXT_CONTAINER_ID = "__next";
782
+
783
+ // src/runtime/html/rewrite-srcset.ts
784
+ function rewriteSrcset(srcset, base, resolve) {
785
+ return srcset.split(",").map((entry) => {
786
+ const [url, descriptor] = entry.trim().split(/\s+/);
787
+ if (!url)
788
+ return entry;
789
+ const absoluteUrl = new URL(url, base).href;
790
+ const resolvedUrl = resolve ? resolve(absoluteUrl) : absoluteUrl;
791
+ return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
792
+ }).join(", ");
793
+ }
794
+
795
+ // src/runtime/html/apply-origin.ts
608
796
  function applyOriginToNodes(doc, url, resolveClientUrl) {
609
797
  if (url.origin !== location.origin) {
610
798
  const nodes = doc.querySelectorAll(
611
- tagNames.map(
799
+ ORIGIN_REWRITE_TAGS.map(
612
800
  (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
613
801
  ).join(",")
614
802
  );
@@ -626,29 +814,17 @@ function applyOriginToNodes(doc, url, resolveClientUrl) {
626
814
  );
627
815
  }
628
816
  if (node.hasAttribute("srcset")) {
629
- const srcSet = node.getAttribute("srcset")?.split(",").map((entry) => {
630
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
631
- if (!urlPart)
632
- return entry;
633
- const absoluteUrl = new URL(urlPart, url).href;
634
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
635
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
636
- }).join(", ");
637
- if (srcSet) {
638
- node.setAttribute("srcset", srcSet);
817
+ const raw = node.getAttribute("srcset");
818
+ if (raw) {
819
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
820
+ node.setAttribute("srcset", rewriteSrcset(raw, url, resolve));
639
821
  }
640
822
  }
641
823
  if (node.hasAttribute("imagesrcset")) {
642
- const srcSet = node.getAttribute("imagesrcset")?.split(",").map((entry) => {
643
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
644
- if (!urlPart)
645
- return entry;
646
- const absoluteUrl = new URL(urlPart, url).href;
647
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
648
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
649
- }).join(", ");
650
- if (srcSet) {
651
- node.setAttribute("imagesrcset", srcSet);
824
+ const raw = node.getAttribute("imagesrcset");
825
+ if (raw) {
826
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
827
+ node.setAttribute("imagesrcset", rewriteSrcset(raw, url, resolve));
652
828
  }
653
829
  }
654
830
  });
@@ -689,26 +865,28 @@ function buildMetadata(attrs, url) {
689
865
 
690
866
  // src/runtime/html/parse-remote-html.ts
691
867
  function validateSingleComponent(doc, name, url) {
692
- if (doc.querySelectorAll("div[data-bundle][data-route]").length > 1 && !doc.querySelector(`div[data-bundle][data-route][id^="${name}"]`) || doc.querySelectorAll("remote-component:not([src])").length > 1 && !doc.querySelector(`remote-component[name="${name}"]`)) {
868
+ if (doc.querySelectorAll(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`).length > 1 && !doc.querySelector(
869
+ `div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`
870
+ ) || doc.querySelectorAll(`${TAG_REMOTE_COMPONENT}:not([src])`).length > 1 && !doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]`)) {
693
871
  throw multipleRemoteComponentsError(url);
694
872
  }
695
873
  }
696
874
  function findComponentElement(doc, name) {
697
- return doc.querySelector(`div[data-bundle][data-route][id^="${name}"]`) ?? doc.querySelector("div[data-bundle][data-route]") ?? doc.querySelector("div#__next") ?? doc.querySelector(`remote-component[name="${name}"]:not([src])`) ?? doc.querySelector("remote-component:not([src])");
875
+ return doc.querySelector(`div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`) ?? doc.querySelector(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`) ?? doc.querySelector(`div#${NEXT_CONTAINER_ID}`) ?? doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]:not([src])`) ?? doc.querySelector(`${TAG_REMOTE_COMPONENT}:not([src])`);
698
876
  }
699
877
  function parseNextData(doc) {
700
878
  return JSON.parse(
701
- (doc.querySelector("#__NEXT_DATA__") ?? doc.querySelector("#__REMOTE_NEXT_DATA__"))?.textContent ?? "null"
879
+ (doc.querySelector(`#${NEXT_DATA_ID}`) ?? doc.querySelector(`#${REMOTE_NEXT_DATA_ID}`))?.textContent ?? "null"
702
880
  );
703
881
  }
704
882
  function resolveComponentName(component, nextData, fallbackName) {
705
- const isRemoteComponent = component?.tagName.toLowerCase() === "remote-component";
706
- const name = component?.getAttribute("id")?.replace(/_ssr$/, "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
883
+ const isRemoteComponent = component?.tagName.toLowerCase() === TAG_REMOTE_COMPONENT;
884
+ const name = component?.getAttribute("id")?.replace(new RegExp(`${ID_SUFFIX_SSR}$`), "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
707
885
  return { name, isRemoteComponent };
708
886
  }
709
887
  function extractRemoteShared(doc, name, nextData) {
710
888
  const remoteSharedEl = doc.querySelector(
711
- `#${name}_shared[data-remote-components-shared]`
889
+ `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`
712
890
  );
713
891
  const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
714
892
  remoteSharedEl?.remove();
@@ -729,7 +907,7 @@ function extractLinks(doc, component) {
729
907
  function extractScripts(doc, component, isRemoteComponent) {
730
908
  return Array.from(
731
909
  (isRemoteComponent ? component : doc).querySelectorAll(
732
- "script[src],script[data-src]"
910
+ `script[src],script[${DATA_SRC}]`
733
911
  )
734
912
  );
735
913
  }
@@ -742,15 +920,15 @@ function parseRemoteComponentDocument(doc, name, url) {
742
920
  nextData,
743
921
  name
744
922
  );
745
- const rsc = doc.querySelector(`#${resolvedName}_rsc`);
923
+ const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);
746
924
  const metadata = buildMetadata(
747
925
  {
748
926
  name: resolvedName,
749
- bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle,
750
- route: component?.getAttribute("data-route") ?? nextData?.page,
751
- runtime: component?.getAttribute("data-runtime") ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
927
+ bundle: component?.getAttribute(DATA_BUNDLE) || nextData?.props.__REMOTE_COMPONENT__?.bundle,
928
+ route: component?.getAttribute(DATA_ROUTE) ?? nextData?.page,
929
+ runtime: component?.getAttribute(DATA_RUNTIME) ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
752
930
  id: component?.getAttribute("id"),
753
- type: component?.getAttribute("data-type")
931
+ type: component?.getAttribute(DATA_TYPE)
754
932
  },
755
933
  url
756
934
  );
@@ -839,13 +1017,15 @@ function applySharedModules(bundle, resolve) {
839
1017
  `Shared modules to resolve: ${Object.keys(resolve)}`
840
1018
  );
841
1019
  const self = globalThis;
842
- if (self.__remote_webpack_require__?.[bundle]) {
1020
+ const scope = getScope(bundle);
1021
+ const webpackBundle = scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];
1022
+ if (webpackBundle) {
843
1023
  const modulePaths = Object.keys(
844
- self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
1024
+ self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {}
845
1025
  );
846
1026
  logDebug(
847
1027
  "SharedModules",
848
- `Available module paths in __remote_webpack_require__[${bundle}]: ${modulePaths}`
1028
+ `Available module paths for bundle "${bundle}": ${modulePaths}`
849
1029
  );
850
1030
  for (const [key, value] of Object.entries(resolve)) {
851
1031
  const exactIds = modulePaths.filter((p) => p === key);
@@ -857,7 +1037,6 @@ function applySharedModules(bundle, resolve) {
857
1037
  );
858
1038
  }
859
1039
  for (const id of ids) {
860
- const webpackBundle = self.__remote_webpack_require__[bundle];
861
1040
  if (webpackBundle.m) {
862
1041
  const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
863
1042
  if (resolvedId !== id) {
@@ -955,10 +1134,8 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
955
1134
  ];
956
1135
  const { default: Component } = componentLoader();
957
1136
  const { default: App } = appLoader();
958
- if (!self.__remote_next_css__) {
959
- self.__remote_next_css__ = {};
960
- }
961
- if (!self.__remote_next_css__[bundle]) {
1137
+ const cssCache = getNamespace().cssCache;
1138
+ if (!cssCache[bundle]) {
962
1139
  const cssRE = /\.s?css$/;
963
1140
  Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
964
1141
  self.__remote_webpack_require__?.[bundle]?.(id);
@@ -976,15 +1153,15 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
976
1153
  node.remove();
977
1154
  node = nextCss.previousSibling;
978
1155
  }
979
- self.__remote_next_css__[bundle] = elements;
1156
+ cssCache[bundle] = elements;
980
1157
  }
981
1158
  if (styleContainer) {
982
- const elements = self.__remote_next_css__[bundle];
1159
+ const elements = cssCache[bundle];
983
1160
  elements.forEach((el) => {
984
1161
  styleContainer.appendChild(el.cloneNode(true));
985
1162
  });
986
1163
  } else {
987
- const elements = self.__remote_next_css__[bundle];
1164
+ const elements = cssCache[bundle];
988
1165
  elements.forEach((el) => {
989
1166
  document.head.appendChild(el);
990
1167
  });
@@ -1021,6 +1198,18 @@ function fixPayload(payload) {
1021
1198
  }
1022
1199
  }
1023
1200
  }
1201
+ function buildRSCChunks(rscName, data) {
1202
+ const chunks = [];
1203
+ for (const chunk of data) {
1204
+ for (const line of chunk.split("\n")) {
1205
+ const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1206
+ if (match?.groups?.rsc) {
1207
+ chunks.push(JSON.parse(`"${match.groups.rsc}"`));
1208
+ }
1209
+ }
1210
+ }
1211
+ return chunks;
1212
+ }
1024
1213
  function createRSCStream(rscName, data) {
1025
1214
  return new ReadableStream({
1026
1215
  type: "bytes",
@@ -1028,16 +1217,11 @@ function createRSCStream(rscName, data) {
1028
1217
  const encoder = new TextEncoder();
1029
1218
  const self = globalThis;
1030
1219
  if (data.length > 0) {
1031
- data.forEach((chunk) => {
1032
- const lines = chunk.split("\n");
1033
- for (const line of lines) {
1034
- const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1035
- if (match?.groups?.rsc) {
1036
- self[rscName] = self[rscName] ?? [];
1037
- self[rscName].push(JSON.parse(`"${match.groups.rsc}"`));
1038
- }
1039
- }
1040
- });
1220
+ const parsed = buildRSCChunks(rscName, data);
1221
+ if (parsed.length > 0) {
1222
+ self[rscName] = self[rscName] ?? [];
1223
+ self[rscName].push(...parsed);
1224
+ }
1041
1225
  }
1042
1226
  const allChunks = (self[rscName] ?? [`0:[null]
1043
1227
  `]).join("");
@@ -1067,12 +1251,38 @@ function createRSCStream(rscName, data) {
1067
1251
  });
1068
1252
  }
1069
1253
 
1254
+ // src/runtime/rsc-imports.ts
1255
+ async function importRSCClientBrowser() {
1256
+ try {
1257
+ return await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1258
+ } catch {
1259
+ const mod = await import("react-server-dom-webpack/client.browser");
1260
+ return mod.default ?? mod;
1261
+ }
1262
+ }
1263
+
1070
1264
  // src/runtime/turbopack/patterns.ts
1265
+ var MODULE_ID_PATTERN = '"[^"]+"|[0-9]+';
1266
+ function stripQuotes(value) {
1267
+ if (value.startsWith('"') && value.endsWith('"')) {
1268
+ return value.slice(1, -1);
1269
+ }
1270
+ return value;
1271
+ }
1272
+ function extractGroup(re, input, group) {
1273
+ const raw = re.exec(input)?.groups?.[group];
1274
+ return raw ? stripQuotes(raw) : void 0;
1275
+ }
1071
1276
  var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
1072
- var REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
1073
- var ASYNC_MODULE_LOADER_RE = /(?:__turbopack_context__|e)\.A\((?<asyncSharedModuleId>[0-9]+)\)/;
1074
- var ASYNC_MODULE_RESOLVE_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<inner>parentImport|e)=>Promise\.resolve\(\)\.then\(\(\)=>\k<inner>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
1075
- var ASYNC_MODULE_ALL_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<vCb>parentImport|t)=>Promise\.all\(\["[^"]+"\]\.map\((?<mapCb>chunk|t)=>\k<ctx>\.l\(\k<mapCb>\)\)\)\.then\(\(\)=>\k<vCb>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
1277
+ var REMOTE_SHARED_ASSIGNMENT_RE = new RegExp(
1278
+ `\\.TURBOPACK_REMOTE_SHARED\\s*=\\s*await (?:__turbopack_context__|[a-z])\\.A\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1279
+ );
1280
+ var ASYNC_MODULE_LOADER_RE = new RegExp(
1281
+ `(?:__turbopack_context__|e)\\.A\\((?<asyncSharedModuleId>${MODULE_ID_PATTERN})\\)`
1282
+ );
1283
+ var ASYNC_MODULE_CALLBACK_RE = new RegExp(
1284
+ `(?:parentImport|[a-z])\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1285
+ );
1076
1286
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
1077
1287
 
1078
1288
  // src/runtime/turbopack/chunk-loader.ts
@@ -1082,6 +1292,7 @@ function loadChunkWithScope(scope, chunkId) {
1082
1292
  `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
1083
1293
  );
1084
1294
  const self = globalThis;
1295
+ const ns = getNamespace();
1085
1296
  const { bundle, path, prefix } = parseRemoteId(chunkId);
1086
1297
  const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
1087
1298
  if (remoteRuntime === RUNTIME_WEBPACK) {
@@ -1092,35 +1303,31 @@ function loadChunkWithScope(scope, chunkId) {
1092
1303
  if (url.endsWith(".css")) {
1093
1304
  return;
1094
1305
  }
1095
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1096
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
1097
- }
1098
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1099
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1306
+ if (ns.chunkCache[url]) {
1307
+ logDebug("ChunkLoader", `Cache hit for "${chunkId}" (url="${url}")`);
1308
+ return ns.chunkCache[url];
1100
1309
  }
1101
1310
  const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1102
1311
  if (resolvedUrl !== url) {
1103
1312
  logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1104
1313
  }
1105
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1106
- (resolve, reject) => {
1107
- fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1108
- const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1109
- if (hasTurbopack) {
1110
- return handleTurbopackChunk(code, scope, url);
1111
- }
1112
- }).then(resolve).catch((error) => {
1113
- const isProxied = isProxiedUrl(resolvedUrl);
1114
- if (isProxied) {
1115
- reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1116
- } else {
1117
- warnCrossOriginFetchError("ChunkLoader", url);
1118
- reject(error);
1119
- }
1120
- });
1121
- }
1122
- );
1123
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1314
+ ns.chunkCache[url] = new Promise((resolve, reject) => {
1315
+ fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1316
+ const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1317
+ if (hasTurbopack) {
1318
+ return handleTurbopackChunk(code, scope, url);
1319
+ }
1320
+ }).then(resolve).catch((error) => {
1321
+ const isProxied = isProxiedUrl(resolvedUrl);
1322
+ if (isProxied) {
1323
+ reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1324
+ } else {
1325
+ warnCrossOriginFetchError("ChunkLoader", url);
1326
+ reject(error);
1327
+ }
1328
+ });
1329
+ });
1330
+ return ns.chunkCache[url];
1124
1331
  }
1125
1332
  function createChunkDispatcher() {
1126
1333
  return function __chunk_dispatcher__(chunkId, scriptBundle) {
@@ -1169,19 +1376,39 @@ async function handleTurbopackChunk(code, scope, url) {
1169
1376
  `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1170
1377
  );
1171
1378
  if (!self[`TURBOPACK_${globalKey}`]) {
1172
- const chunkData = [];
1173
- const turbopackObject = {
1174
- push: (item) => {
1175
- if (Array.isArray(item)) {
1176
- chunkData.push(item);
1177
- } else {
1178
- chunkData.push([item]);
1379
+ const wrapPush = (target) => {
1380
+ const originalPush = target.push;
1381
+ if (typeof originalPush !== "function")
1382
+ return target;
1383
+ target.push = (...items) => {
1384
+ for (const item of items) {
1385
+ if (Array.isArray(item)) {
1386
+ for (const entry of item) {
1387
+ scope.turbopackModules.push(entry);
1388
+ }
1389
+ } else {
1390
+ scope.turbopackModules.push(item);
1391
+ }
1179
1392
  }
1180
- return chunkData.length;
1181
- },
1182
- __chunks__: chunkData
1393
+ return originalPush.apply(target, items);
1394
+ };
1395
+ return target;
1183
1396
  };
1184
- self[`TURBOPACK_${globalKey}`] = turbopackObject;
1397
+ const globalProp = `TURBOPACK_${globalKey}`;
1398
+ let currentValue = wrapPush([]);
1399
+ Object.defineProperty(self, globalProp, {
1400
+ get() {
1401
+ return currentValue;
1402
+ },
1403
+ set(newValue) {
1404
+ if (newValue && typeof newValue === "object") {
1405
+ wrapPush(newValue);
1406
+ }
1407
+ currentValue = newValue;
1408
+ },
1409
+ configurable: true,
1410
+ enumerable: true
1411
+ });
1185
1412
  }
1186
1413
  await new Promise((scriptResolve, scriptReject) => {
1187
1414
  const blob = new Blob([transformedCode], {
@@ -1233,13 +1460,13 @@ async function handleTurbopackChunk(code, scope, url) {
1233
1460
  // src/runtime/turbopack/shared-modules.ts
1234
1461
  var DEDUPLICATION_WARNING = "This module will not be deduplicated \u2014 the remote may load its own copy, which can cause duplicate instance errors (e.g. invalid hook calls if React is loaded twice).";
1235
1462
  function getTurbopackModules(scope) {
1463
+ if (scope.turbopackModules.length > 0) {
1464
+ return scope.turbopackModules;
1465
+ }
1236
1466
  const self = globalThis;
1237
1467
  const raw = self[`TURBOPACK_${scope.globalKey}`];
1238
1468
  if (!raw)
1239
1469
  return void 0;
1240
- if (typeof raw === "object" && "__chunks__" in raw) {
1241
- return raw.__chunks__.flat();
1242
- }
1243
1470
  if (Array.isArray(raw)) {
1244
1471
  return raw.flat();
1245
1472
  }
@@ -1263,7 +1490,11 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1263
1490
  if (sharedModuleInitializerIndex > 0) {
1264
1491
  const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1265
1492
  const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1266
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1493
+ const sharedModuleId = extractGroup(
1494
+ REMOTE_SHARED_ASSIGNMENT_RE,
1495
+ sharedModuleInitializerCode,
1496
+ "sharedModuleId"
1497
+ );
1267
1498
  if (sharedModuleId) {
1268
1499
  const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1269
1500
  scope,
@@ -1321,20 +1552,22 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1321
1552
  }
1322
1553
  function extractSharedModuleIds(shared2, scope) {
1323
1554
  return Object.entries(shared2).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1324
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1555
+ const asyncSharedModuleId = extractGroup(
1556
+ ASYNC_MODULE_LOADER_RE,
1557
+ value.toString(),
1558
+ "asyncSharedModuleId"
1559
+ );
1325
1560
  if (asyncSharedModuleId) {
1326
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1327
- let asyncSharedModule;
1328
- const turbopackModules = getTurbopackModules(scope) ?? [];
1329
- const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1330
- asyncSharedModuleIdNumber
1561
+ const asyncSharedModule = findModuleInit(
1562
+ getTurbopackModules(scope),
1563
+ asyncSharedModuleId
1331
1564
  );
1332
- if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1333
- asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1334
- }
1335
1565
  if (asyncSharedModule) {
1336
- const asyncSharedModuleCode = asyncSharedModule.toString();
1337
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1566
+ const sharedModuleId = extractGroup(
1567
+ ASYNC_MODULE_CALLBACK_RE,
1568
+ asyncSharedModule.toString(),
1569
+ "sharedModuleId"
1570
+ );
1338
1571
  acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1339
1572
  "__remote_shared_module_",
1340
1573
  ""
@@ -1363,10 +1596,8 @@ function requireModule(scope, moduleId, fullId) {
1363
1596
  if (scope.moduleCache[idStr])
1364
1597
  return scope.moduleCache[idStr];
1365
1598
  const sharedModule = getSharedModule(scope, moduleId);
1366
- if (sharedModule) {
1367
- scope.moduleCache[idStr] = sharedModule;
1599
+ if (sharedModule)
1368
1600
  return sharedModule;
1369
- }
1370
1601
  return handleTurbopackModule(
1371
1602
  scope,
1372
1603
  idStr,
@@ -1374,19 +1605,10 @@ function requireModule(scope, moduleId, fullId) {
1374
1605
  );
1375
1606
  }
1376
1607
  function handleTurbopackModule(scope, moduleId, id) {
1377
- const self = globalThis;
1378
1608
  if (scope.moduleCache[moduleId]) {
1379
1609
  return scope.moduleCache[moduleId];
1380
1610
  }
1381
- const raw = self[`TURBOPACK_${scope.globalKey}`];
1382
- let modules;
1383
- if (raw && typeof raw === "object" && "__chunks__" in raw) {
1384
- modules = raw.__chunks__.flat();
1385
- } else if (Array.isArray(raw)) {
1386
- modules = raw.flat();
1387
- } else {
1388
- modules = raw;
1389
- }
1611
+ const modules = getTurbopackModules(scope);
1390
1612
  if (!modules) {
1391
1613
  logError(
1392
1614
  "TurbopackModule",
@@ -1436,9 +1658,17 @@ function findModuleInit(modules, moduleId) {
1436
1658
  if (idx >= 0) {
1437
1659
  return flat.slice(idx + 1).find((e) => typeof e === "function");
1438
1660
  }
1439
- return flat.find(
1440
- (e) => Boolean(e && typeof e === "object" && moduleId in e)
1441
- )?.[moduleId];
1661
+ for (const entry of flat) {
1662
+ if (!entry || typeof entry !== "object")
1663
+ continue;
1664
+ const obj = entry;
1665
+ if (moduleId in obj)
1666
+ return obj[moduleId];
1667
+ const prefixKey = Object.keys(obj).find((k) => k.startsWith(moduleId));
1668
+ if (prefixKey)
1669
+ return obj[prefixKey];
1670
+ }
1671
+ return void 0;
1442
1672
  }
1443
1673
  function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1444
1674
  const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
@@ -1517,7 +1747,10 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1517
1747
  }
1518
1748
  if (typeof mod !== "object" || mod === null) {
1519
1749
  mod = { default: mod };
1520
- } else if (!("default" in mod) && mod.toString() !== "[object Module]") {
1750
+ } else if (!("default" in mod) && // ES module namespace objects have a null prototype, so calling
1751
+ // mod.toString() directly throws. Use Object.prototype.toString
1752
+ // to safely detect them.
1753
+ Object.prototype.toString.call(mod) !== "[object Module]") {
1521
1754
  try {
1522
1755
  mod.default = mod;
1523
1756
  } catch {
@@ -1581,21 +1814,38 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1581
1814
  };
1582
1815
  }
1583
1816
 
1584
- // src/runtime/turbopack/webpack-runtime.ts
1585
- async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared2 = {}, remoteShared = {}, resolveClientUrl) {
1817
+ // src/runtime/turbopack/remote-scope-setup.ts
1818
+ async function setupRemoteScope(runtime, scripts = [], url = new URL(location.href), bundle, resolveClientUrl) {
1586
1819
  const self = globalThis;
1820
+ const ns = getNamespace();
1587
1821
  const bundleName = bundle ?? "default";
1822
+ const existingScope = getScope(bundleName);
1823
+ if (existingScope && existingScope.url.origin === url.origin) {
1824
+ logDebug(
1825
+ "WebpackRuntime",
1826
+ `Reusing scope "${existingScope.scopedName}" (turbopackModules=${existingScope.turbopackModules.length})`
1827
+ );
1828
+ existingScope.resolveClientUrl = resolveClientUrl;
1829
+ if (runtime === RUNTIME_TURBOPACK) {
1830
+ await Promise.allSettled(
1831
+ scripts.map(
1832
+ (script) => script.src ? loadChunkWithScope(existingScope, script.src) : Promise.resolve(void 0)
1833
+ )
1834
+ );
1835
+ }
1836
+ return existingScope;
1837
+ }
1588
1838
  const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1589
1839
  registerScope(scope);
1590
- if (!self.__remote_bundle_url__) {
1591
- self.__remote_bundle_url__ = {};
1840
+ if (runtime === RUNTIME_WEBPACK && self.__remote_webpack_require__?.[bundleName]) {
1841
+ scope.webpackRequire = self.__remote_webpack_require__[bundleName];
1592
1842
  }
1593
- self.__remote_bundle_url__[bundleName] = url;
1843
+ ns.bundleUrls[bundleName] = url;
1594
1844
  if (scope.scopedName !== bundleName) {
1595
- self.__remote_bundle_url__[scope.scopedName] = url;
1845
+ ns.bundleUrls[scope.scopedName] = url;
1596
1846
  }
1597
1847
  self.__webpack_get_script_filename__ = () => null;
1598
- const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1848
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || ns.dispatcherRuntime !== "turbopack";
1599
1849
  if (willCreateDispatchers) {
1600
1850
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1601
1851
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
@@ -1603,6 +1853,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1603
1853
  }
1604
1854
  self.__webpack_chunk_load__ = createChunkDispatcher();
1605
1855
  self.__webpack_require__ = createModuleDispatcher(runtime);
1856
+ ns.dispatcherRuntime = runtime;
1606
1857
  self.__webpack_require_type__ = runtime;
1607
1858
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1608
1859
  self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
@@ -1630,15 +1881,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1630
1881
  }
1631
1882
  }
1632
1883
  }
1633
- const coreShared = {
1634
- react: async () => (await import("react")).default,
1635
- "react-dom": async () => (await import("react-dom")).default,
1636
- "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
1637
- "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
1638
- "react-dom/client": async () => (await import("react-dom/client")).default,
1639
- ...shared2
1640
- };
1641
- await initializeSharedModules(scope, coreShared, remoteShared);
1884
+ return scope;
1642
1885
  }
1643
1886
  function createModuleDispatcher(runtime) {
1644
1887
  return (id) => {
@@ -1655,6 +1898,9 @@ function createModuleDispatcher(runtime) {
1655
1898
  );
1656
1899
  try {
1657
1900
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1901
+ const scope2 = getScope(bundle);
1902
+ if (scope2?.webpackRequire)
1903
+ return scope2.webpackRequire(moduleId);
1658
1904
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1659
1905
  }
1660
1906
  const scope = getScope(bundleName);
@@ -1704,6 +1950,13 @@ async function loadScripts(scripts, resolveClientUrl) {
1704
1950
  location.origin
1705
1951
  ).href;
1706
1952
  const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;
1953
+ const alreadyLoaded = Array.from(
1954
+ document.querySelectorAll("script[src]")
1955
+ ).some((s) => s.src === resolvedSrc);
1956
+ if (alreadyLoaded) {
1957
+ resolve();
1958
+ return;
1959
+ }
1707
1960
  const newScript = document.createElement("script");
1708
1961
  newScript.onload = () => resolve();
1709
1962
  newScript.onerror = () => {
@@ -1765,44 +2018,33 @@ async function loadRemoteComponent({
1765
2018
  "ComponentLoader",
1766
2019
  `Remote shared modules requested: ${JSON.stringify(remoteShared)}`
1767
2020
  );
1768
- await setupWebpackRuntime(
2021
+ const scope = await setupRemoteScope(
1769
2022
  runtime,
1770
2023
  scripts,
1771
2024
  url,
1772
2025
  bundle,
1773
- hostShared,
1774
- remoteShared,
1775
2026
  resolveClientUrl
1776
2027
  );
2028
+ if (runtime === "turbopack") {
2029
+ await initializeSharedModules(
2030
+ scope,
2031
+ buildCoreShared(hostShared),
2032
+ remoteShared
2033
+ );
2034
+ }
1777
2035
  if (bundle) {
1778
- const resolve = {
1779
- "/react/index.js": React,
1780
- "/react/jsx-dev-runtime.js": JSXDevRuntime,
1781
- "/react/jsx-runtime.js": JSXRuntime,
1782
- "/react-dom/index.js": ReactDOM,
1783
- "/react-dom/client.js": ReactDOMClient,
1784
- ...Object.entries(remoteShared).reduce(
1785
- (acc, [key, value]) => {
1786
- if (typeof hostShared[value] !== "undefined") {
1787
- acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
1788
- } else {
1789
- logDebug(
1790
- "ComponentLoader",
1791
- `Remote requests "${value}" but host doesn't provide it`
1792
- );
1793
- }
1794
- return acc;
1795
- },
1796
- {}
1797
- )
1798
- };
1799
- await Promise.all(
1800
- Object.entries(resolve).map(async ([key, value]) => {
1801
- if (typeof value === "function") {
1802
- resolve[key] = await value(bundle);
1803
- }
1804
- return Promise.resolve(value);
1805
- })
2036
+ const resolve = await buildWebpackResolve(
2037
+ hostShared,
2038
+ remoteShared,
2039
+ bundle,
2040
+ {
2041
+ "/react/index.js": React,
2042
+ "/react/jsx-dev-runtime.js": JSXDevRuntime,
2043
+ "/react/jsx-runtime.js": JSXRuntime,
2044
+ "/react-dom/index.js": ReactDOM,
2045
+ "/react-dom/client.js": ReactDOMClient
2046
+ },
2047
+ "ComponentLoader"
1806
2048
  );
1807
2049
  applySharedModules(bundle, resolve);
1808
2050
  } else {
@@ -1830,19 +2072,8 @@ async function loadRemoteComponent({
1830
2072
  };
1831
2073
  }
1832
2074
  }
1833
- async function importCreateFromReadableStream() {
1834
- try {
1835
- const { createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1836
- return createFromReadableStream;
1837
- } catch {
1838
- const {
1839
- default: { createFromReadableStream }
1840
- } = await import("react-server-dom-webpack/client.browser");
1841
- return createFromReadableStream;
1842
- }
1843
- }
1844
2075
  async function loadRSCComponent(rscName, data) {
1845
- const createFromReadableStream = await importCreateFromReadableStream();
2076
+ const { createFromReadableStream } = await importRSCClientBrowser();
1846
2077
  if (typeof createFromReadableStream !== "function") {
1847
2078
  throw new RemoteComponentsError(
1848
2079
  'Failed to import "react-server-dom-webpack". Is Next.js installed correctly?'
@@ -1906,10 +2137,9 @@ async function importViaCallback(absoluteSrc, resolveClientUrl) {
1906
2137
  URL.revokeObjectURL(moduleBlobUrl);
1907
2138
  URL.revokeObjectURL(wrapperBlobUrl);
1908
2139
  }
1909
- const registry = globalThis.__rc_module_registry__;
1910
- const mod = registry?.[absoluteSrc] ?? {};
1911
- if (registry)
1912
- delete registry[absoluteSrc];
2140
+ const registry = getNamespace().moduleRegistry;
2141
+ const mod = registry[absoluteSrc] ?? {};
2142
+ delete registry[absoluteSrc];
1913
2143
  return mod;
1914
2144
  }
1915
2145
  async function importDirectly(absoluteSrc) {
@@ -1939,12 +2169,12 @@ function resolveScriptSrc(script, url) {
1939
2169
  return rawSrc;
1940
2170
  }
1941
2171
  async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1942
- const self = globalThis;
1943
- if (self.__remote_script_entrypoint_mount__?.[url.href]) {
1944
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
2172
+ const ns = getNamespace();
2173
+ if (ns.mountFns[url.href]) {
2174
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1945
2175
  }
1946
- if (self.__remote_script_entrypoint_unmount__?.[url.href]) {
1947
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
2176
+ if (ns.unmountFns[url.href]) {
2177
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1948
2178
  }
1949
2179
  const mountUnmountSets = await Promise.all(
1950
2180
  scripts.map(async (script) => {
@@ -1956,25 +2186,19 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1956
2186
  URL.revokeObjectURL(src);
1957
2187
  }
1958
2188
  if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
1959
- if (!self.__remote_script_entrypoint_mount__) {
1960
- self.__remote_script_entrypoint_mount__ = {};
1961
- }
1962
- if (!self.__remote_script_entrypoint_mount__[url.href]) {
1963
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
2189
+ if (!ns.mountFns[url.href]) {
2190
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1964
2191
  }
1965
- self.__remote_script_entrypoint_mount__[url.href]?.add(
2192
+ ns.mountFns[url.href]?.add(
1966
2193
  mod.mount || mod.default?.mount || (() => {
1967
2194
  })
1968
2195
  );
1969
2196
  }
1970
2197
  if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
1971
- if (!self.__remote_script_entrypoint_unmount__) {
1972
- self.__remote_script_entrypoint_unmount__ = {};
1973
- }
1974
- if (!self.__remote_script_entrypoint_unmount__[url.href]) {
1975
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
2198
+ if (!ns.unmountFns[url.href]) {
2199
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1976
2200
  }
1977
- self.__remote_script_entrypoint_unmount__[url.href]?.add(
2201
+ ns.unmountFns[url.href]?.add(
1978
2202
  mod.unmount || mod.default?.unmount || (() => {
1979
2203
  })
1980
2204
  );
@@ -2031,27 +2255,25 @@ function useShadowRoot({
2031
2255
  }) {
2032
2256
  const shadowRootContainerRef = useRef(null);
2033
2257
  const [shadowRoot, setShadowRoot] = useState(() => {
2034
- const self = globalThis;
2035
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2258
+ const shadowRoots = getNamespace().shadowRoots;
2036
2259
  const ssrShadowRoot = typeof document !== "undefined" ? document.querySelector(
2037
2260
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
2038
- )?.shadowRoot ?? self[shadowRootKey] ?? null : null;
2039
- self[shadowRootKey] = null;
2261
+ )?.shadowRoot ?? shadowRoots[keySuffix] ?? null : null;
2262
+ shadowRoots[keySuffix] = null;
2040
2263
  return ssrShadowRoot;
2041
2264
  });
2042
2265
  useLayoutEffect(() => {
2266
+ const shadowRoots = getNamespace().shadowRoots;
2043
2267
  if (isolate !== false && typeof document !== "undefined" && (!shadowRoot || !shadowRoot.isConnected)) {
2044
- const self = globalThis;
2045
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2046
2268
  let shadowRootElement = null;
2047
2269
  const element = document.querySelector(
2048
2270
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
2049
2271
  );
2050
- shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;
2272
+ shadowRootElement = shadowRoots[keySuffix] ?? element?.shadowRoot ?? null;
2051
2273
  if (!shadowRootElement && element) {
2052
2274
  try {
2053
2275
  shadowRootElement = element.attachShadow({ mode });
2054
- self[shadowRootKey] = shadowRootElement;
2276
+ shadowRoots[keySuffix] = shadowRootElement;
2055
2277
  } catch {
2056
2278
  }
2057
2279
  }
@@ -2062,9 +2284,7 @@ function useShadowRoot({
2062
2284
  setShadowRoot(shadowRootElement);
2063
2285
  }
2064
2286
  } else if (isolate === false && shadowRoot) {
2065
- const self = globalThis;
2066
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2067
- self[shadowRootKey] = null;
2287
+ shadowRoots[keySuffix] = null;
2068
2288
  setShadowRoot(null);
2069
2289
  }
2070
2290
  }, [isolate, shadowRoot, mode, keySuffix]);
@@ -2095,7 +2315,7 @@ function getRemoteComponentHtml(html) {
2095
2315
 
2096
2316
  // src/host/react/index.tsx
2097
2317
  import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
2098
- import { createElement as createElement2 } from "react";
2318
+ import { createElement as createElement3 } from "react";
2099
2319
  function ConsumeRemoteComponent({
2100
2320
  src,
2101
2321
  isolate,
@@ -2160,9 +2380,8 @@ function ConsumeRemoteComponent({
2160
2380
  const prevRemoteComponentContainerRef = useRef2(null);
2161
2381
  const unmountRef = useRef2(null);
2162
2382
  useLayoutEffect2(() => {
2163
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2164
2383
  return () => {
2165
- delete globalThis[shadowRootKey];
2384
+ delete getNamespace().shadowRoots[keySuffix];
2166
2385
  };
2167
2386
  }, [keySuffix]);
2168
2387
  useLayoutEffect2(() => {
@@ -2255,9 +2474,8 @@ function ConsumeRemoteComponent({
2255
2474
  if (shadowRoot) {
2256
2475
  shadowRoot.innerHTML = "";
2257
2476
  }
2258
- const self = globalThis;
2259
2477
  const prevUrl = hostStateRef.current.prevUrl;
2260
- if (prevUrl && self.__remote_script_entrypoint_unmount__?.[prevUrl.href]) {
2478
+ if (prevUrl && getNamespace().unmountFns[prevUrl.href]) {
2261
2479
  const unmountPromises = Promise.all(
2262
2480
  Array.from(unmountRef.current ?? []).map(
2263
2481
  async (unmount) => unmount(
@@ -2447,10 +2665,7 @@ function ConsumeRemoteComponent({
2447
2665
  ).href
2448
2666
  };
2449
2667
  }),
2450
- shared: {
2451
- ...sharedPolyfills(userShared, resolveClientUrl),
2452
- ...userShared
2453
- },
2668
+ shared: buildHostShared(userShared, resolveClientUrl),
2454
2669
  remoteShared,
2455
2670
  container: shadowRoot,
2456
2671
  resolveClientUrl
@@ -2516,7 +2731,7 @@ function ConsumeRemoteComponent({
2516
2731
  runtime: hostStateRef.current.prevIsRemoteComponent ? RUNTIME_SCRIPT : data?.runtime || RUNTIME_WEBPACK
2517
2732
  }) });
2518
2733
  const resetStyle = reset ? /* @__PURE__ */ jsx2("style", { "data-remote-components-reset": "react", children: `:host { all: initial; }` }) : null;
2519
- const linksToRender = data?.links?.map((link) => /* @__PURE__ */ createElement2(
2734
+ const linksToRender = data?.links?.map((link) => /* @__PURE__ */ createElement3(
2520
2735
  "link",
2521
2736
  {
2522
2737
  ...link,
@@ -2582,8 +2797,10 @@ function ConsumeRemoteComponent({
2582
2797
  alt="" decoding="async" style="display:none"
2583
2798
  src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
2584
2799
  onload="(function(el){
2800
+ // Capture the shadow root during SSR hydration so the client-side
2801
+ // useShadowRoot hook can find it.
2585
2802
  const root = el.getRootNode();
2586
- globalThis.__remote_components_shadowroot_${keySuffix} = root;
2803
+ globalThis.__remote_components_shadowroot_${keySuffix}=root;
2587
2804
  el.parentElement.remove();
2588
2805
  })(this)"
2589
2806
  />`
@@ -2686,14 +2903,6 @@ var routerImpl = async () => {
2686
2903
 
2687
2904
  // src/host/nextjs/app-client-only.tsx
2688
2905
  import { jsx as jsx3 } from "react/jsx-runtime";
2689
- async function tryImportShared() {
2690
- try {
2691
- const { shared: shared2 } = await Promise.resolve().then(() => (init_app(), app_exports));
2692
- return shared2;
2693
- } catch {
2694
- return {};
2695
- }
2696
- }
2697
2906
  var sharedModules = async (userShared, resolveClientUrl) => {
2698
2907
  const [resolvedShared, resolvedUserShared] = await Promise.all([
2699
2908
  tryImportShared(),