remote-components 0.3.3 → 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 (157) hide show
  1. package/dist/config/nextjs.cjs +86 -37
  2. package/dist/config/nextjs.cjs.map +1 -1
  3. package/dist/config/nextjs.js +86 -37
  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/html.cjs +524 -338
  10. package/dist/host/html.cjs.map +1 -1
  11. package/dist/host/html.js +524 -338
  12. package/dist/host/html.js.map +1 -1
  13. package/dist/host/nextjs/app/client-only.cjs +462 -259
  14. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  15. package/dist/host/nextjs/app/client-only.js +436 -233
  16. package/dist/host/nextjs/app/client-only.js.map +1 -1
  17. package/dist/host/react.cjs +403 -228
  18. package/dist/host/react.cjs.map +1 -1
  19. package/dist/host/react.js +403 -228
  20. package/dist/host/react.js.map +1 -1
  21. package/dist/internal/config/webpack/apply-shared-modules.cjs +6 -4
  22. package/dist/internal/config/webpack/apply-shared-modules.cjs.map +1 -1
  23. package/dist/internal/config/webpack/apply-shared-modules.js +6 -4
  24. package/dist/internal/config/webpack/apply-shared-modules.js.map +1 -1
  25. package/dist/internal/config/webpack/next-client-pages-loader.cjs +6 -7
  26. package/dist/internal/config/webpack/next-client-pages-loader.cjs.map +1 -1
  27. package/dist/internal/config/webpack/next-client-pages-loader.js +6 -7
  28. package/dist/internal/config/webpack/next-client-pages-loader.js.map +1 -1
  29. package/dist/internal/host/nextjs/app-client.cjs +4 -3
  30. package/dist/internal/host/nextjs/app-client.cjs.map +1 -1
  31. package/dist/internal/host/nextjs/app-client.js +4 -3
  32. package/dist/internal/host/nextjs/app-client.js.map +1 -1
  33. package/dist/internal/host/nextjs/dom-flight.cjs +19 -39
  34. package/dist/internal/host/nextjs/dom-flight.cjs.map +1 -1
  35. package/dist/internal/host/nextjs/dom-flight.js +31 -39
  36. package/dist/internal/host/nextjs/dom-flight.js.map +1 -1
  37. package/dist/internal/host/nextjs/image-shared.cjs +39 -3
  38. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  39. package/dist/internal/host/nextjs/image-shared.d.ts +5 -10
  40. package/dist/internal/host/nextjs/image-shared.js +29 -3
  41. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  42. package/dist/internal/host/server/fetch-remote-component.cjs +2 -1
  43. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  44. package/dist/internal/host/server/fetch-remote-component.js +2 -1
  45. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  46. package/dist/internal/host/shared/polyfill.cjs +8 -7
  47. package/dist/internal/host/shared/polyfill.cjs.map +1 -1
  48. package/dist/internal/host/shared/polyfill.js +8 -7
  49. package/dist/internal/host/shared/polyfill.js.map +1 -1
  50. package/dist/internal/host/shared/shared-module-resolver.cjs +117 -0
  51. package/dist/internal/host/shared/shared-module-resolver.cjs.map +1 -0
  52. package/dist/internal/host/shared/shared-module-resolver.d.ts +64 -0
  53. package/dist/internal/host/shared/shared-module-resolver.js +78 -0
  54. package/dist/internal/host/shared/shared-module-resolver.js.map +1 -0
  55. package/dist/internal/remote/nextjs/next-internals.cjs +53 -0
  56. package/dist/internal/remote/nextjs/next-internals.cjs.map +1 -0
  57. package/dist/internal/remote/nextjs/next-internals.d.ts +42 -0
  58. package/dist/internal/remote/nextjs/next-internals.js +26 -0
  59. package/dist/internal/remote/nextjs/next-internals.js.map +1 -0
  60. package/dist/internal/runtime/html/apply-origin.cjs +11 -32
  61. package/dist/internal/runtime/html/apply-origin.cjs.map +1 -1
  62. package/dist/internal/runtime/html/apply-origin.js +11 -32
  63. package/dist/internal/runtime/html/apply-origin.js.map +1 -1
  64. package/dist/internal/runtime/html/html-spec.cjs +78 -0
  65. package/dist/internal/runtime/html/html-spec.cjs.map +1 -0
  66. package/dist/internal/runtime/html/html-spec.d.ts +23 -0
  67. package/dist/internal/runtime/html/html-spec.js +41 -0
  68. package/dist/internal/runtime/html/html-spec.js.map +1 -0
  69. package/dist/internal/runtime/html/parse-remote-html.cjs +15 -12
  70. package/dist/internal/runtime/html/parse-remote-html.cjs.map +1 -1
  71. package/dist/internal/runtime/html/parse-remote-html.js +29 -12
  72. package/dist/internal/runtime/html/parse-remote-html.js.map +1 -1
  73. package/dist/internal/runtime/html/rewrite-srcset.cjs +38 -0
  74. package/dist/internal/runtime/html/rewrite-srcset.cjs.map +1 -0
  75. package/dist/internal/runtime/html/rewrite-srcset.d.ts +12 -0
  76. package/dist/internal/runtime/html/rewrite-srcset.js +14 -0
  77. package/dist/internal/runtime/html/rewrite-srcset.js.map +1 -0
  78. package/dist/internal/runtime/loaders/component-loader.cjs +25 -44
  79. package/dist/internal/runtime/loaders/component-loader.cjs.map +1 -1
  80. package/dist/internal/runtime/loaders/component-loader.d.ts +3 -1
  81. package/dist/internal/runtime/loaders/component-loader.js +28 -44
  82. package/dist/internal/runtime/loaders/component-loader.js.map +1 -1
  83. package/dist/internal/runtime/loaders/static-loader.cjs +15 -21
  84. package/dist/internal/runtime/loaders/static-loader.cjs.map +1 -1
  85. package/dist/internal/runtime/loaders/static-loader.d.ts +3 -1
  86. package/dist/internal/runtime/loaders/static-loader.js +15 -21
  87. package/dist/internal/runtime/loaders/static-loader.js.map +1 -1
  88. package/dist/internal/runtime/namespace.cjs +82 -0
  89. package/dist/internal/runtime/namespace.cjs.map +1 -0
  90. package/dist/internal/runtime/namespace.d.ts +5 -0
  91. package/dist/internal/runtime/namespace.js +58 -0
  92. package/dist/internal/runtime/namespace.js.map +1 -0
  93. package/dist/internal/runtime/rsc-imports.cjs +86 -0
  94. package/dist/internal/runtime/rsc-imports.cjs.map +1 -0
  95. package/dist/internal/runtime/rsc-imports.d.ts +39 -0
  96. package/dist/internal/runtime/rsc-imports.js +50 -0
  97. package/dist/internal/runtime/rsc-imports.js.map +1 -0
  98. package/dist/internal/runtime/rsc-runtime.cjs +17 -0
  99. package/dist/internal/runtime/rsc-runtime.cjs.map +1 -0
  100. package/dist/internal/runtime/rsc-runtime.d.ts +37 -0
  101. package/dist/internal/runtime/rsc-runtime.js +1 -0
  102. package/dist/internal/runtime/rsc-runtime.js.map +1 -0
  103. package/dist/internal/runtime/rsc.cjs +23 -12
  104. package/dist/internal/runtime/rsc.cjs.map +1 -1
  105. package/dist/internal/runtime/rsc.d.ts +19 -2
  106. package/dist/internal/runtime/rsc.js +20 -11
  107. package/dist/internal/runtime/rsc.js.map +1 -1
  108. package/dist/internal/runtime/turbopack/chunk-loader.cjs +53 -35
  109. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  110. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +1 -1
  111. package/dist/internal/runtime/turbopack/chunk-loader.js +53 -35
  112. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  113. package/dist/internal/runtime/turbopack/module.cjs +17 -4
  114. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  115. package/dist/internal/runtime/turbopack/module.d.ts +23 -1
  116. package/dist/internal/runtime/turbopack/module.js +16 -4
  117. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  118. package/dist/internal/runtime/turbopack/patterns.cjs +26 -10
  119. package/dist/internal/runtime/turbopack/patterns.cjs.map +1 -1
  120. package/dist/internal/runtime/turbopack/patterns.d.ts +44 -49
  121. package/dist/internal/runtime/turbopack/patterns.js +23 -7
  122. package/dist/internal/runtime/turbopack/patterns.js.map +1 -1
  123. package/dist/internal/runtime/turbopack/{webpack-runtime.cjs → remote-scope-setup.cjs} +35 -32
  124. package/dist/internal/runtime/turbopack/remote-scope-setup.cjs.map +1 -0
  125. package/dist/internal/runtime/turbopack/remote-scope-setup.d.ts +25 -0
  126. package/dist/internal/runtime/turbopack/{webpack-runtime.js → remote-scope-setup.js} +36 -19
  127. package/dist/internal/runtime/turbopack/remote-scope-setup.js.map +1 -0
  128. package/dist/internal/runtime/turbopack/remote-scope.cjs +4 -6
  129. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -1
  130. package/dist/internal/runtime/turbopack/remote-scope.d.ts +20 -1
  131. package/dist/internal/runtime/turbopack/remote-scope.js +4 -6
  132. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -1
  133. package/dist/internal/runtime/turbopack/shared-modules.cjs +21 -15
  134. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  135. package/dist/internal/runtime/turbopack/shared-modules.d.ts +9 -2
  136. package/dist/internal/runtime/turbopack/shared-modules.js +24 -18
  137. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  138. package/dist/internal/runtime/types.cjs.map +1 -1
  139. package/dist/internal/runtime/types.d.ts +5 -41
  140. package/dist/internal/utils/logger.cjs +1 -1
  141. package/dist/internal/utils/logger.cjs.map +1 -1
  142. package/dist/internal/utils/logger.d.ts +2 -2
  143. package/dist/internal/utils/logger.js +1 -1
  144. package/dist/internal/utils/logger.js.map +1 -1
  145. package/dist/remote/html.cjs +78 -22
  146. package/dist/remote/html.cjs.map +1 -1
  147. package/dist/remote/html.js +78 -22
  148. package/dist/remote/html.js.map +1 -1
  149. package/dist/remote/nextjs/app.cjs +14 -55
  150. package/dist/remote/nextjs/app.cjs.map +1 -1
  151. package/dist/remote/nextjs/app.js +24 -45
  152. package/dist/remote/nextjs/app.js.map +1 -1
  153. package/dist/types-59251814.d.ts +94 -0
  154. package/package.json +1 -1
  155. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +0 -1
  156. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +0 -23
  157. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +0 -1
@@ -73,7 +73,10 @@ __export(app_client_only_exports, {
73
73
  RemoteComponentsClientProvider: () => RemoteComponentsClientProvider
74
74
  });
75
75
  module.exports = __toCommonJS(app_client_only_exports);
76
- var import_react5 = require("react");
76
+ var import_react6 = require("react");
77
+
78
+ // src/host/nextjs/image-shared.ts
79
+ var import_react = require("react");
77
80
 
78
81
  // src/utils/index.ts
79
82
  function escapeString(str) {
@@ -101,6 +104,62 @@ function getBundleKey(bundle) {
101
104
  return escapeString(bundle);
102
105
  }
103
106
 
107
+ // src/runtime/namespace.ts
108
+ var SHADOW_ROOT_PREFIX = "__remote_components_shadowroot_";
109
+ var LEGACY_ALIASES = [
110
+ { global: "__remote_component_scopes__", prop: "scopes" },
111
+ {
112
+ global: "__remote_components_turbopack_chunk_loader_promise__",
113
+ prop: "chunkCache"
114
+ },
115
+ { global: "__remote_script_entrypoint_mount__", prop: "mountFns" },
116
+ { global: "__remote_script_entrypoint_unmount__", prop: "unmountFns" },
117
+ { global: "__remote_bundle_url__", prop: "bundleUrls" },
118
+ { global: "__rc_module_registry__", prop: "moduleRegistry" },
119
+ {
120
+ global: "__remote_component_host_shared_modules__",
121
+ prop: "hostSharedModules"
122
+ },
123
+ { global: "__remote_next_css__", prop: "cssCache" }
124
+ ];
125
+ function getNamespace() {
126
+ const g = globalThis;
127
+ const existing = g.__remote_components__;
128
+ if (existing) {
129
+ return existing;
130
+ }
131
+ const ns = {
132
+ scopes: /* @__PURE__ */ new Map(),
133
+ chunkCache: {},
134
+ mountFns: {},
135
+ unmountFns: {},
136
+ bundleUrls: {},
137
+ moduleRegistry: {},
138
+ dispatcherRuntime: void 0,
139
+ hostSharedModules: {},
140
+ cssCache: {},
141
+ shadowRoots: {}
142
+ };
143
+ const nsRecord = ns;
144
+ for (const { global, prop } of LEGACY_ALIASES) {
145
+ const legacyValue = g[global];
146
+ if (legacyValue != null) {
147
+ nsRecord[prop] = legacyValue;
148
+ }
149
+ g[global] = ns[prop];
150
+ }
151
+ const gRecord = g;
152
+ for (const key of Object.keys(gRecord)) {
153
+ if (key.startsWith(SHADOW_ROOT_PREFIX)) {
154
+ const suffix = key.slice(SHADOW_ROOT_PREFIX.length);
155
+ ns.shadowRoots[suffix] = gRecord[key];
156
+ delete gRecord[key];
157
+ }
158
+ }
159
+ g.__remote_components__ = ns;
160
+ return ns;
161
+ }
162
+
104
163
  // src/runtime/patterns.ts
105
164
  var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
106
165
  var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
@@ -225,7 +284,7 @@ Docs: ${CORS_DOCS_URL}`
225
284
 
226
285
  // src/utils/logger.ts
227
286
  var PREFIX = "remote-components";
228
- var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
287
+ var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true" || typeof process !== "undefined" && process.env.RC_DEBUG === "true";
229
288
  function logDebug(location2, message) {
230
289
  if (DEBUG) {
231
290
  console.debug(`[${PREFIX}:${location2}]: ${message}`);
@@ -257,11 +316,7 @@ function warnCrossOriginFetchError(logLocation, url) {
257
316
 
258
317
  // src/runtime/turbopack/remote-scope.ts
259
318
  function getRegistry() {
260
- const self = globalThis;
261
- if (!self.__remote_component_scopes__) {
262
- self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
263
- }
264
- return self.__remote_component_scopes__;
319
+ return getNamespace().scopes;
265
320
  }
266
321
  function createScope(name, url, runtime, resolveClientUrl) {
267
322
  const isCrossOrigin = url.origin !== location.origin;
@@ -279,7 +334,8 @@ function createScope(name, url, runtime, resolveClientUrl) {
279
334
  resolveClientUrl,
280
335
  moduleCache: {},
281
336
  sharedModules: {},
282
- moduleGlobal: {}
337
+ moduleGlobal: {},
338
+ turbopackModules: []
283
339
  };
284
340
  }
285
341
  function registerScope(scope) {
@@ -376,16 +432,41 @@ function createImageLoaderSharedEntries({
376
432
  bound,
377
433
  unbound
378
434
  } = {}) {
379
- const entry = (bundle) => {
435
+ const loaderEntry = (bundle) => {
380
436
  const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
381
437
  return Promise.resolve({
382
438
  default: createRemoteImageLoader(bundle, resolveClientUrl),
383
439
  __esModule: true
384
440
  });
385
441
  };
442
+ const imageEntry = async (bundle) => {
443
+ const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
444
+ const rawLoader = createRemoteImageLoader(bundle, resolveClientUrl);
445
+ const remoteLoader = Object.assign(
446
+ (p) => rawLoader({ ...p, config: { path: "/_next/image" } }),
447
+ { __next_img_default: true }
448
+ );
449
+ const mod = await import("next/image");
450
+ const OriginalImage = mod.default;
451
+ const RemoteImage = (0, import_react.forwardRef)(
452
+ (props, ref) => (0, import_react.createElement)(OriginalImage, {
453
+ ...props,
454
+ loader: props.loader ?? remoteLoader,
455
+ ref
456
+ })
457
+ );
458
+ RemoteImage.displayName = "RemoteImage";
459
+ return { ...mod, default: RemoteImage, __esModule: true };
460
+ };
386
461
  return {
387
- "next/dist/shared/lib/image-loader": entry,
388
- "next/dist/esm/shared/lib/image-loader": entry
462
+ "next/dist/shared/lib/image-loader": loaderEntry,
463
+ "next/dist/esm/shared/lib/image-loader": loaderEntry,
464
+ // Can be removed once 0.2.x support is dropped.
465
+ "next/image": imageEntry,
466
+ // Can be removed once 0.2.x support is dropped.
467
+ "next/dist/client/image-component": imageEntry,
468
+ // Can be removed once 0.2.x support is dropped.
469
+ "next/dist/api/image": imageEntry
389
470
  };
390
471
  }
391
472
 
@@ -403,7 +484,7 @@ async function tryImportShared() {
403
484
  var import_context3 = require("#internal/host/react/context");
404
485
 
405
486
  // src/host/react/index.tsx
406
- var import_react3 = require("react");
487
+ var import_react4 = require("react");
407
488
  var import_react_dom = require("react-dom");
408
489
  var import_context2 = require("#internal/host/react/context");
409
490
 
@@ -465,9 +546,9 @@ function getClientOrServerUrl(src, serverFallback) {
465
546
  // src/host/shared/polyfill.tsx
466
547
  var import_jsx_runtime = require("react/jsx-runtime");
467
548
  function sharedPolyfills(shared2, resolveClientUrl) {
468
- const self = globalThis;
549
+ const hostShared = getNamespace().hostSharedModules;
469
550
  const polyfill = {
470
- "next/dist/client/components/navigation": self.__remote_component_host_shared_modules__?.["next/navigation"] ?? shared2?.["next/navigation"] ?? (() => Promise.resolve({
551
+ "next/dist/client/components/navigation": hostShared["next/navigation"] ?? shared2?.["next/navigation"] ?? (() => Promise.resolve({
471
552
  useRouter() {
472
553
  return {
473
554
  push: (routerUrl) => {
@@ -498,7 +579,7 @@ function sharedPolyfills(shared2, resolveClientUrl) {
498
579
  },
499
580
  __esModule: true
500
581
  })),
501
- "next/dist/client/app-dir/link": self.__remote_component_host_shared_modules__?.["next/link"] ?? shared2?.["next/link"] ?? (() => Promise.resolve({
582
+ "next/dist/client/app-dir/link": hostShared["next/link"] ?? shared2?.["next/link"] ?? (() => Promise.resolve({
502
583
  default: ({
503
584
  scroll: _,
504
585
  replace,
@@ -548,7 +629,7 @@ function sharedPolyfills(shared2, resolveClientUrl) {
548
629
  },
549
630
  __esModule: true
550
631
  })),
551
- "next/dist/client/app-dir/form": self.__remote_component_host_shared_modules__?.["next/form"] ?? shared2?.["next/form"] ?? (() => Promise.resolve({
632
+ "next/dist/client/app-dir/form": hostShared["next/form"] ?? shared2?.["next/form"] ?? (() => Promise.resolve({
552
633
  default: () => {
553
634
  throw new Error("Next.js <Form> component not implemented");
554
635
  },
@@ -559,17 +640,17 @@ function sharedPolyfills(shared2, resolveClientUrl) {
559
640
  // This gives us full next/image fidelity (fill, priority, srcSet, blur
560
641
  // placeholders, error handling) while routing image optimization through the
561
642
  // remote app's /_next/image endpoint.
562
- "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({
643
+ "next/dist/shared/lib/image-loader": hostShared["next/dist/shared/lib/image-loader"] ?? shared2?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
563
644
  default: createRemoteImageLoader(bundle, resolveClientUrl),
564
645
  __esModule: true
565
646
  })),
566
- "next/dist/client/script": self.__remote_component_host_shared_modules__?.["next/script"] ?? shared2?.["next/script"] ?? (() => Promise.resolve({
647
+ "next/dist/client/script": hostShared["next/script"] ?? shared2?.["next/script"] ?? (() => Promise.resolve({
567
648
  // TODO: implement <Script> component for non-Next.js host applications
568
649
  // do not throw an error for now
569
650
  default: () => null,
570
651
  __esModule: true
571
652
  })),
572
- "next/router": self.__remote_component_host_shared_modules__?.["next/router"] ?? shared2?.["next/router"] ?? (() => (
653
+ "next/router": hostShared["next/router"] ?? shared2?.["next/router"] ?? (() => (
573
654
  // TODO: incomplete implementation
574
655
  Promise.resolve({
575
656
  useRouter() {
@@ -605,6 +686,68 @@ function sharedPolyfills(shared2, resolveClientUrl) {
605
686
  return polyfill;
606
687
  }
607
688
 
689
+ // src/host/shared/shared-module-resolver.ts
690
+ var CORE_REACT_PATH_MAP = {
691
+ react: "/react/index.js",
692
+ "react/jsx-dev-runtime": "/react/jsx-dev-runtime.js",
693
+ "react/jsx-runtime": "/react/jsx-runtime.js",
694
+ "react-dom": "/react-dom/index.js",
695
+ "react-dom/client": "/react-dom/client.js"
696
+ };
697
+ var VENDOR_SHARED = Object.fromEntries(
698
+ Object.entries(CORE_REACT_PATH_MAP).filter(([key]) => key !== "react-dom/client").map(([key, path]) => [key, `'${path}'`])
699
+ );
700
+ function buildCoreShared(userShared) {
701
+ return {
702
+ react: async () => (await import("react")).default,
703
+ "react-dom": async () => (await import("react-dom")).default,
704
+ "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
705
+ "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
706
+ "react-dom/client": async () => (await import("react-dom/client")).default,
707
+ ...userShared
708
+ };
709
+ }
710
+ function buildHostShared(userShared, resolveClientUrl, options) {
711
+ const self = globalThis;
712
+ const result = {
713
+ ...sharedPolyfills(userShared, resolveClientUrl),
714
+ ...self.__remote_component_host_shared_modules__,
715
+ ...userShared
716
+ };
717
+ if (options?.includeRemoteComponentShared) {
718
+ Object.assign(result, self.__remote_component_shared__);
719
+ }
720
+ return result;
721
+ }
722
+ async function buildWebpackResolve(hostShared, remoteShared, bundle, reactModules, callerTag = "SharedModuleResolver") {
723
+ const resolve = {
724
+ ...reactModules,
725
+ ...Object.entries(remoteShared).reduce(
726
+ (acc, [key, value]) => {
727
+ if (typeof hostShared[value] !== "undefined") {
728
+ acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
729
+ } else {
730
+ logDebug(
731
+ callerTag,
732
+ `Remote requests "${value}" but host doesn't provide it`
733
+ );
734
+ }
735
+ return acc;
736
+ },
737
+ {}
738
+ )
739
+ };
740
+ await Promise.all(
741
+ Object.entries(resolve).map(async ([key, value]) => {
742
+ if (typeof value === "function") {
743
+ resolve[key] = await value(bundle);
744
+ }
745
+ return Promise.resolve(value);
746
+ })
747
+ );
748
+ return resolve;
749
+ }
750
+
608
751
  // src/host/shared/state.ts
609
752
  function createHostState() {
610
753
  return {
@@ -631,8 +774,8 @@ function resolveNameFromSrc(src, defaultName) {
631
774
  return name || defaultName;
632
775
  }
633
776
 
634
- // src/runtime/html/apply-origin.ts
635
- var tagNames = [
777
+ // src/runtime/html/html-spec.ts
778
+ var ORIGIN_REWRITE_TAGS = [
636
779
  "img",
637
780
  "source",
638
781
  "video",
@@ -643,10 +786,37 @@ var tagNames = [
643
786
  "script",
644
787
  "link"
645
788
  ];
789
+ var ID_SUFFIX_RSC = "_rsc";
790
+ var ID_SUFFIX_SSR = "_ssr";
791
+ var ID_SUFFIX_SHARED = "_shared";
792
+ var DATA_BUNDLE = "data-bundle";
793
+ var DATA_ROUTE = "data-route";
794
+ var DATA_RUNTIME = "data-runtime";
795
+ var DATA_TYPE = "data-type";
796
+ var DATA_SRC = "data-src";
797
+ var DATA_REMOTE_COMPONENTS_SHARED = "data-remote-components-shared";
798
+ var TAG_REMOTE_COMPONENT = "remote-component";
799
+ var NEXT_DATA_ID = "__NEXT_DATA__";
800
+ var REMOTE_NEXT_DATA_ID = "__REMOTE_NEXT_DATA__";
801
+ var NEXT_CONTAINER_ID = "__next";
802
+
803
+ // src/runtime/html/rewrite-srcset.ts
804
+ function rewriteSrcset(srcset, base, resolve) {
805
+ return srcset.split(",").map((entry) => {
806
+ const [url, descriptor] = entry.trim().split(/\s+/);
807
+ if (!url)
808
+ return entry;
809
+ const absoluteUrl = new URL(url, base).href;
810
+ const resolvedUrl = resolve ? resolve(absoluteUrl) : absoluteUrl;
811
+ return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
812
+ }).join(", ");
813
+ }
814
+
815
+ // src/runtime/html/apply-origin.ts
646
816
  function applyOriginToNodes(doc, url, resolveClientUrl) {
647
817
  if (url.origin !== location.origin) {
648
818
  const nodes = doc.querySelectorAll(
649
- tagNames.map(
819
+ ORIGIN_REWRITE_TAGS.map(
650
820
  (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
651
821
  ).join(",")
652
822
  );
@@ -664,29 +834,17 @@ function applyOriginToNodes(doc, url, resolveClientUrl) {
664
834
  );
665
835
  }
666
836
  if (node.hasAttribute("srcset")) {
667
- const srcSet = node.getAttribute("srcset")?.split(",").map((entry) => {
668
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
669
- if (!urlPart)
670
- return entry;
671
- const absoluteUrl = new URL(urlPart, url).href;
672
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
673
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
674
- }).join(", ");
675
- if (srcSet) {
676
- node.setAttribute("srcset", srcSet);
837
+ const raw = node.getAttribute("srcset");
838
+ if (raw) {
839
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
840
+ node.setAttribute("srcset", rewriteSrcset(raw, url, resolve));
677
841
  }
678
842
  }
679
843
  if (node.hasAttribute("imagesrcset")) {
680
- const srcSet = node.getAttribute("imagesrcset")?.split(",").map((entry) => {
681
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
682
- if (!urlPart)
683
- return entry;
684
- const absoluteUrl = new URL(urlPart, url).href;
685
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
686
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
687
- }).join(", ");
688
- if (srcSet) {
689
- node.setAttribute("imagesrcset", srcSet);
844
+ const raw = node.getAttribute("imagesrcset");
845
+ if (raw) {
846
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
847
+ node.setAttribute("imagesrcset", rewriteSrcset(raw, url, resolve));
690
848
  }
691
849
  }
692
850
  });
@@ -727,26 +885,28 @@ function buildMetadata(attrs, url) {
727
885
 
728
886
  // src/runtime/html/parse-remote-html.ts
729
887
  function validateSingleComponent(doc, name, url) {
730
- 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}"]`)) {
888
+ if (doc.querySelectorAll(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`).length > 1 && !doc.querySelector(
889
+ `div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`
890
+ ) || doc.querySelectorAll(`${TAG_REMOTE_COMPONENT}:not([src])`).length > 1 && !doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]`)) {
731
891
  throw multipleRemoteComponentsError(url);
732
892
  }
733
893
  }
734
894
  function findComponentElement(doc, name) {
735
- 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])");
895
+ 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])`);
736
896
  }
737
897
  function parseNextData(doc) {
738
898
  return JSON.parse(
739
- (doc.querySelector("#__NEXT_DATA__") ?? doc.querySelector("#__REMOTE_NEXT_DATA__"))?.textContent ?? "null"
899
+ (doc.querySelector(`#${NEXT_DATA_ID}`) ?? doc.querySelector(`#${REMOTE_NEXT_DATA_ID}`))?.textContent ?? "null"
740
900
  );
741
901
  }
742
902
  function resolveComponentName(component, nextData, fallbackName) {
743
- const isRemoteComponent = component?.tagName.toLowerCase() === "remote-component";
744
- const name = component?.getAttribute("id")?.replace(/_ssr$/, "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
903
+ const isRemoteComponent = component?.tagName.toLowerCase() === TAG_REMOTE_COMPONENT;
904
+ const name = component?.getAttribute("id")?.replace(new RegExp(`${ID_SUFFIX_SSR}$`), "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
745
905
  return { name, isRemoteComponent };
746
906
  }
747
907
  function extractRemoteShared(doc, name, nextData) {
748
908
  const remoteSharedEl = doc.querySelector(
749
- `#${name}_shared[data-remote-components-shared]`
909
+ `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`
750
910
  );
751
911
  const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
752
912
  remoteSharedEl?.remove();
@@ -767,7 +927,7 @@ function extractLinks(doc, component) {
767
927
  function extractScripts(doc, component, isRemoteComponent) {
768
928
  return Array.from(
769
929
  (isRemoteComponent ? component : doc).querySelectorAll(
770
- "script[src],script[data-src]"
930
+ `script[src],script[${DATA_SRC}]`
771
931
  )
772
932
  );
773
933
  }
@@ -780,15 +940,15 @@ function parseRemoteComponentDocument(doc, name, url) {
780
940
  nextData,
781
941
  name
782
942
  );
783
- const rsc = doc.querySelector(`#${resolvedName}_rsc`);
943
+ const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);
784
944
  const metadata = buildMetadata(
785
945
  {
786
946
  name: resolvedName,
787
- bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle,
788
- route: component?.getAttribute("data-route") ?? nextData?.page,
789
- runtime: component?.getAttribute("data-runtime") ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
947
+ bundle: component?.getAttribute(DATA_BUNDLE) || nextData?.props.__REMOTE_COMPONENT__?.bundle,
948
+ route: component?.getAttribute(DATA_ROUTE) ?? nextData?.page,
949
+ runtime: component?.getAttribute(DATA_RUNTIME) ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
790
950
  id: component?.getAttribute("id"),
791
- type: component?.getAttribute("data-type")
951
+ type: component?.getAttribute(DATA_TYPE)
792
952
  },
793
953
  url
794
954
  );
@@ -877,13 +1037,15 @@ function applySharedModules(bundle, resolve) {
877
1037
  `Shared modules to resolve: ${Object.keys(resolve)}`
878
1038
  );
879
1039
  const self = globalThis;
880
- if (self.__remote_webpack_require__?.[bundle]) {
1040
+ const scope = getScope(bundle);
1041
+ const webpackBundle = scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];
1042
+ if (webpackBundle) {
881
1043
  const modulePaths = Object.keys(
882
- self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
1044
+ self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {}
883
1045
  );
884
1046
  logDebug(
885
1047
  "SharedModules",
886
- `Available module paths in __remote_webpack_require__[${bundle}]: ${modulePaths}`
1048
+ `Available module paths for bundle "${bundle}": ${modulePaths}`
887
1049
  );
888
1050
  for (const [key, value] of Object.entries(resolve)) {
889
1051
  const exactIds = modulePaths.filter((p) => p === key);
@@ -895,7 +1057,6 @@ function applySharedModules(bundle, resolve) {
895
1057
  );
896
1058
  }
897
1059
  for (const id of ids) {
898
- const webpackBundle = self.__remote_webpack_require__[bundle];
899
1060
  if (webpackBundle.m) {
900
1061
  const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
901
1062
  if (resolvedId !== id) {
@@ -993,10 +1154,8 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
993
1154
  ];
994
1155
  const { default: Component } = componentLoader();
995
1156
  const { default: App } = appLoader();
996
- if (!self.__remote_next_css__) {
997
- self.__remote_next_css__ = {};
998
- }
999
- if (!self.__remote_next_css__[bundle]) {
1157
+ const cssCache = getNamespace().cssCache;
1158
+ if (!cssCache[bundle]) {
1000
1159
  const cssRE = /\.s?css$/;
1001
1160
  Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
1002
1161
  self.__remote_webpack_require__?.[bundle]?.(id);
@@ -1014,15 +1173,15 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
1014
1173
  node.remove();
1015
1174
  node = nextCss.previousSibling;
1016
1175
  }
1017
- self.__remote_next_css__[bundle] = elements;
1176
+ cssCache[bundle] = elements;
1018
1177
  }
1019
1178
  if (styleContainer) {
1020
- const elements = self.__remote_next_css__[bundle];
1179
+ const elements = cssCache[bundle];
1021
1180
  elements.forEach((el) => {
1022
1181
  styleContainer.appendChild(el.cloneNode(true));
1023
1182
  });
1024
1183
  } else {
1025
- const elements = self.__remote_next_css__[bundle];
1184
+ const elements = cssCache[bundle];
1026
1185
  elements.forEach((el) => {
1027
1186
  document.head.appendChild(el);
1028
1187
  });
@@ -1059,6 +1218,18 @@ function fixPayload(payload) {
1059
1218
  }
1060
1219
  }
1061
1220
  }
1221
+ function buildRSCChunks(rscName, data) {
1222
+ const chunks = [];
1223
+ for (const chunk of data) {
1224
+ for (const line of chunk.split("\n")) {
1225
+ const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1226
+ if (match?.groups?.rsc) {
1227
+ chunks.push(JSON.parse(`"${match.groups.rsc}"`));
1228
+ }
1229
+ }
1230
+ }
1231
+ return chunks;
1232
+ }
1062
1233
  function createRSCStream(rscName, data) {
1063
1234
  return new import_web_streams_polyfill.ReadableStream({
1064
1235
  type: "bytes",
@@ -1066,16 +1237,11 @@ function createRSCStream(rscName, data) {
1066
1237
  const encoder = new TextEncoder();
1067
1238
  const self = globalThis;
1068
1239
  if (data.length > 0) {
1069
- data.forEach((chunk) => {
1070
- const lines = chunk.split("\n");
1071
- for (const line of lines) {
1072
- const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1073
- if (match?.groups?.rsc) {
1074
- self[rscName] = self[rscName] ?? [];
1075
- self[rscName].push(JSON.parse(`"${match.groups.rsc}"`));
1076
- }
1077
- }
1078
- });
1240
+ const parsed = buildRSCChunks(rscName, data);
1241
+ if (parsed.length > 0) {
1242
+ self[rscName] = self[rscName] ?? [];
1243
+ self[rscName].push(...parsed);
1244
+ }
1079
1245
  }
1080
1246
  const allChunks = (self[rscName] ?? [`0:[null]
1081
1247
  `]).join("");
@@ -1105,12 +1271,38 @@ function createRSCStream(rscName, data) {
1105
1271
  });
1106
1272
  }
1107
1273
 
1274
+ // src/runtime/rsc-imports.ts
1275
+ async function importRSCClientBrowser() {
1276
+ try {
1277
+ return await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1278
+ } catch {
1279
+ const mod = await import("react-server-dom-webpack/client.browser");
1280
+ return mod.default ?? mod;
1281
+ }
1282
+ }
1283
+
1108
1284
  // src/runtime/turbopack/patterns.ts
1285
+ var MODULE_ID_PATTERN = '"[^"]+"|[0-9]+';
1286
+ function stripQuotes(value) {
1287
+ if (value.startsWith('"') && value.endsWith('"')) {
1288
+ return value.slice(1, -1);
1289
+ }
1290
+ return value;
1291
+ }
1292
+ function extractGroup(re, input, group) {
1293
+ const raw = re.exec(input)?.groups?.[group];
1294
+ return raw ? stripQuotes(raw) : void 0;
1295
+ }
1109
1296
  var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
1110
- var REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
1111
- var ASYNC_MODULE_LOADER_RE = /(?:__turbopack_context__|e)\.A\((?<asyncSharedModuleId>[0-9]+)\)/;
1112
- var ASYNC_MODULE_RESOLVE_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<inner>parentImport|e)=>Promise\.resolve\(\)\.then\(\(\)=>\k<inner>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
1113
- 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]+)\)\)\)\}/;
1297
+ var REMOTE_SHARED_ASSIGNMENT_RE = new RegExp(
1298
+ `\\.TURBOPACK_REMOTE_SHARED\\s*=\\s*await (?:__turbopack_context__|[a-z])\\.A\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1299
+ );
1300
+ var ASYNC_MODULE_LOADER_RE = new RegExp(
1301
+ `(?:__turbopack_context__|e)\\.A\\((?<asyncSharedModuleId>${MODULE_ID_PATTERN})\\)`
1302
+ );
1303
+ var ASYNC_MODULE_CALLBACK_RE = new RegExp(
1304
+ `(?:parentImport|[a-z])\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1305
+ );
1114
1306
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
1115
1307
 
1116
1308
  // src/runtime/turbopack/chunk-loader.ts
@@ -1120,6 +1312,7 @@ function loadChunkWithScope(scope, chunkId) {
1120
1312
  `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
1121
1313
  );
1122
1314
  const self = globalThis;
1315
+ const ns = getNamespace();
1123
1316
  const { bundle, path, prefix } = parseRemoteId(chunkId);
1124
1317
  const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
1125
1318
  if (remoteRuntime === RUNTIME_WEBPACK) {
@@ -1130,35 +1323,31 @@ function loadChunkWithScope(scope, chunkId) {
1130
1323
  if (url.endsWith(".css")) {
1131
1324
  return;
1132
1325
  }
1133
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1134
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
1135
- }
1136
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1137
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1326
+ if (ns.chunkCache[url]) {
1327
+ logDebug("ChunkLoader", `Cache hit for "${chunkId}" (url="${url}")`);
1328
+ return ns.chunkCache[url];
1138
1329
  }
1139
1330
  const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1140
1331
  if (resolvedUrl !== url) {
1141
1332
  logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1142
1333
  }
1143
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1144
- (resolve, reject) => {
1145
- fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1146
- const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1147
- if (hasTurbopack) {
1148
- return handleTurbopackChunk(code, scope, url);
1149
- }
1150
- }).then(resolve).catch((error) => {
1151
- const isProxied = isProxiedUrl(resolvedUrl);
1152
- if (isProxied) {
1153
- reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1154
- } else {
1155
- warnCrossOriginFetchError("ChunkLoader", url);
1156
- reject(error);
1157
- }
1158
- });
1159
- }
1160
- );
1161
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1334
+ ns.chunkCache[url] = new Promise((resolve, reject) => {
1335
+ fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1336
+ const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1337
+ if (hasTurbopack) {
1338
+ return handleTurbopackChunk(code, scope, url);
1339
+ }
1340
+ }).then(resolve).catch((error) => {
1341
+ const isProxied = isProxiedUrl(resolvedUrl);
1342
+ if (isProxied) {
1343
+ reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1344
+ } else {
1345
+ warnCrossOriginFetchError("ChunkLoader", url);
1346
+ reject(error);
1347
+ }
1348
+ });
1349
+ });
1350
+ return ns.chunkCache[url];
1162
1351
  }
1163
1352
  function createChunkDispatcher() {
1164
1353
  return function __chunk_dispatcher__(chunkId, scriptBundle) {
@@ -1207,19 +1396,39 @@ async function handleTurbopackChunk(code, scope, url) {
1207
1396
  `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1208
1397
  );
1209
1398
  if (!self[`TURBOPACK_${globalKey}`]) {
1210
- const chunkData = [];
1211
- const turbopackObject = {
1212
- push: (item) => {
1213
- if (Array.isArray(item)) {
1214
- chunkData.push(item);
1215
- } else {
1216
- chunkData.push([item]);
1399
+ const wrapPush = (target) => {
1400
+ const originalPush = target.push;
1401
+ if (typeof originalPush !== "function")
1402
+ return target;
1403
+ target.push = (...items) => {
1404
+ for (const item of items) {
1405
+ if (Array.isArray(item)) {
1406
+ for (const entry of item) {
1407
+ scope.turbopackModules.push(entry);
1408
+ }
1409
+ } else {
1410
+ scope.turbopackModules.push(item);
1411
+ }
1217
1412
  }
1218
- return chunkData.length;
1219
- },
1220
- __chunks__: chunkData
1413
+ return originalPush.apply(target, items);
1414
+ };
1415
+ return target;
1221
1416
  };
1222
- self[`TURBOPACK_${globalKey}`] = turbopackObject;
1417
+ const globalProp = `TURBOPACK_${globalKey}`;
1418
+ let currentValue = wrapPush([]);
1419
+ Object.defineProperty(self, globalProp, {
1420
+ get() {
1421
+ return currentValue;
1422
+ },
1423
+ set(newValue) {
1424
+ if (newValue && typeof newValue === "object") {
1425
+ wrapPush(newValue);
1426
+ }
1427
+ currentValue = newValue;
1428
+ },
1429
+ configurable: true,
1430
+ enumerable: true
1431
+ });
1223
1432
  }
1224
1433
  await new Promise((scriptResolve, scriptReject) => {
1225
1434
  const blob = new Blob([transformedCode], {
@@ -1271,13 +1480,13 @@ async function handleTurbopackChunk(code, scope, url) {
1271
1480
  // src/runtime/turbopack/shared-modules.ts
1272
1481
  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).";
1273
1482
  function getTurbopackModules(scope) {
1483
+ if (scope.turbopackModules.length > 0) {
1484
+ return scope.turbopackModules;
1485
+ }
1274
1486
  const self = globalThis;
1275
1487
  const raw = self[`TURBOPACK_${scope.globalKey}`];
1276
1488
  if (!raw)
1277
1489
  return void 0;
1278
- if (typeof raw === "object" && "__chunks__" in raw) {
1279
- return raw.__chunks__.flat();
1280
- }
1281
1490
  if (Array.isArray(raw)) {
1282
1491
  return raw.flat();
1283
1492
  }
@@ -1301,7 +1510,11 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1301
1510
  if (sharedModuleInitializerIndex > 0) {
1302
1511
  const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1303
1512
  const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1304
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1513
+ const sharedModuleId = extractGroup(
1514
+ REMOTE_SHARED_ASSIGNMENT_RE,
1515
+ sharedModuleInitializerCode,
1516
+ "sharedModuleId"
1517
+ );
1305
1518
  if (sharedModuleId) {
1306
1519
  const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1307
1520
  scope,
@@ -1359,20 +1572,22 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1359
1572
  }
1360
1573
  function extractSharedModuleIds(shared2, scope) {
1361
1574
  return Object.entries(shared2).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1362
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1575
+ const asyncSharedModuleId = extractGroup(
1576
+ ASYNC_MODULE_LOADER_RE,
1577
+ value.toString(),
1578
+ "asyncSharedModuleId"
1579
+ );
1363
1580
  if (asyncSharedModuleId) {
1364
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1365
- let asyncSharedModule;
1366
- const turbopackModules = getTurbopackModules(scope) ?? [];
1367
- const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1368
- asyncSharedModuleIdNumber
1581
+ const asyncSharedModule = findModuleInit(
1582
+ getTurbopackModules(scope),
1583
+ asyncSharedModuleId
1369
1584
  );
1370
- if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1371
- asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1372
- }
1373
1585
  if (asyncSharedModule) {
1374
- const asyncSharedModuleCode = asyncSharedModule.toString();
1375
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1586
+ const sharedModuleId = extractGroup(
1587
+ ASYNC_MODULE_CALLBACK_RE,
1588
+ asyncSharedModule.toString(),
1589
+ "sharedModuleId"
1590
+ );
1376
1591
  acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1377
1592
  "__remote_shared_module_",
1378
1593
  ""
@@ -1463,9 +1678,17 @@ function findModuleInit(modules, moduleId) {
1463
1678
  if (idx >= 0) {
1464
1679
  return flat.slice(idx + 1).find((e) => typeof e === "function");
1465
1680
  }
1466
- return flat.find(
1467
- (e) => Boolean(e && typeof e === "object" && moduleId in e)
1468
- )?.[moduleId];
1681
+ for (const entry of flat) {
1682
+ if (!entry || typeof entry !== "object")
1683
+ continue;
1684
+ const obj = entry;
1685
+ if (moduleId in obj)
1686
+ return obj[moduleId];
1687
+ const prefixKey = Object.keys(obj).find((k) => k.startsWith(moduleId));
1688
+ if (prefixKey)
1689
+ return obj[prefixKey];
1690
+ }
1691
+ return void 0;
1469
1692
  }
1470
1693
  function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1471
1694
  const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
@@ -1544,7 +1767,10 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1544
1767
  }
1545
1768
  if (typeof mod !== "object" || mod === null) {
1546
1769
  mod = { default: mod };
1547
- } else if (!("default" in mod) && mod.toString() !== "[object Module]") {
1770
+ } else if (!("default" in mod) && // ES module namespace objects have a null prototype, so calling
1771
+ // mod.toString() directly throws. Use Object.prototype.toString
1772
+ // to safely detect them.
1773
+ Object.prototype.toString.call(mod) !== "[object Module]") {
1548
1774
  try {
1549
1775
  mod.default = mod;
1550
1776
  } catch {
@@ -1608,21 +1834,38 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1608
1834
  };
1609
1835
  }
1610
1836
 
1611
- // src/runtime/turbopack/webpack-runtime.ts
1612
- async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared2 = {}, remoteShared = {}, resolveClientUrl) {
1837
+ // src/runtime/turbopack/remote-scope-setup.ts
1838
+ async function setupRemoteScope(runtime, scripts = [], url = new URL(location.href), bundle, resolveClientUrl) {
1613
1839
  const self = globalThis;
1840
+ const ns = getNamespace();
1614
1841
  const bundleName = bundle ?? "default";
1842
+ const existingScope = getScope(bundleName);
1843
+ if (existingScope && existingScope.url.origin === url.origin) {
1844
+ logDebug(
1845
+ "WebpackRuntime",
1846
+ `Reusing scope "${existingScope.scopedName}" (turbopackModules=${existingScope.turbopackModules.length})`
1847
+ );
1848
+ existingScope.resolveClientUrl = resolveClientUrl;
1849
+ if (runtime === RUNTIME_TURBOPACK) {
1850
+ await Promise.allSettled(
1851
+ scripts.map(
1852
+ (script) => script.src ? loadChunkWithScope(existingScope, script.src) : Promise.resolve(void 0)
1853
+ )
1854
+ );
1855
+ }
1856
+ return existingScope;
1857
+ }
1615
1858
  const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1616
1859
  registerScope(scope);
1617
- if (!self.__remote_bundle_url__) {
1618
- self.__remote_bundle_url__ = {};
1860
+ if (runtime === RUNTIME_WEBPACK && self.__remote_webpack_require__?.[bundleName]) {
1861
+ scope.webpackRequire = self.__remote_webpack_require__[bundleName];
1619
1862
  }
1620
- self.__remote_bundle_url__[bundleName] = url;
1863
+ ns.bundleUrls[bundleName] = url;
1621
1864
  if (scope.scopedName !== bundleName) {
1622
- self.__remote_bundle_url__[scope.scopedName] = url;
1865
+ ns.bundleUrls[scope.scopedName] = url;
1623
1866
  }
1624
1867
  self.__webpack_get_script_filename__ = () => null;
1625
- const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1868
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || ns.dispatcherRuntime !== "turbopack";
1626
1869
  if (willCreateDispatchers) {
1627
1870
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1628
1871
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
@@ -1630,6 +1873,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1630
1873
  }
1631
1874
  self.__webpack_chunk_load__ = createChunkDispatcher();
1632
1875
  self.__webpack_require__ = createModuleDispatcher(runtime);
1876
+ ns.dispatcherRuntime = runtime;
1633
1877
  self.__webpack_require_type__ = runtime;
1634
1878
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1635
1879
  self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
@@ -1657,15 +1901,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1657
1901
  }
1658
1902
  }
1659
1903
  }
1660
- const coreShared = {
1661
- react: async () => (await import("react")).default,
1662
- "react-dom": async () => (await import("react-dom")).default,
1663
- "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
1664
- "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
1665
- "react-dom/client": async () => (await import("react-dom/client")).default,
1666
- ...shared2
1667
- };
1668
- await initializeSharedModules(scope, coreShared, remoteShared);
1904
+ return scope;
1669
1905
  }
1670
1906
  function createModuleDispatcher(runtime) {
1671
1907
  return (id) => {
@@ -1682,6 +1918,9 @@ function createModuleDispatcher(runtime) {
1682
1918
  );
1683
1919
  try {
1684
1920
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1921
+ const scope2 = getScope(bundle);
1922
+ if (scope2?.webpackRequire)
1923
+ return scope2.webpackRequire(moduleId);
1685
1924
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1686
1925
  }
1687
1926
  const scope = getScope(bundleName);
@@ -1799,44 +2038,33 @@ async function loadRemoteComponent({
1799
2038
  "ComponentLoader",
1800
2039
  `Remote shared modules requested: ${JSON.stringify(remoteShared)}`
1801
2040
  );
1802
- await setupWebpackRuntime(
2041
+ const scope = await setupRemoteScope(
1803
2042
  runtime,
1804
2043
  scripts,
1805
2044
  url,
1806
2045
  bundle,
1807
- hostShared,
1808
- remoteShared,
1809
2046
  resolveClientUrl
1810
2047
  );
2048
+ if (runtime === "turbopack") {
2049
+ await initializeSharedModules(
2050
+ scope,
2051
+ buildCoreShared(hostShared),
2052
+ remoteShared
2053
+ );
2054
+ }
1811
2055
  if (bundle) {
1812
- const resolve = {
1813
- "/react/index.js": React,
1814
- "/react/jsx-dev-runtime.js": JSXDevRuntime,
1815
- "/react/jsx-runtime.js": JSXRuntime,
1816
- "/react-dom/index.js": ReactDOM,
1817
- "/react-dom/client.js": ReactDOMClient,
1818
- ...Object.entries(remoteShared).reduce(
1819
- (acc, [key, value]) => {
1820
- if (typeof hostShared[value] !== "undefined") {
1821
- acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
1822
- } else {
1823
- logDebug(
1824
- "ComponentLoader",
1825
- `Remote requests "${value}" but host doesn't provide it`
1826
- );
1827
- }
1828
- return acc;
1829
- },
1830
- {}
1831
- )
1832
- };
1833
- await Promise.all(
1834
- Object.entries(resolve).map(async ([key, value]) => {
1835
- if (typeof value === "function") {
1836
- resolve[key] = await value(bundle);
1837
- }
1838
- return Promise.resolve(value);
1839
- })
2056
+ const resolve = await buildWebpackResolve(
2057
+ hostShared,
2058
+ remoteShared,
2059
+ bundle,
2060
+ {
2061
+ "/react/index.js": React,
2062
+ "/react/jsx-dev-runtime.js": JSXDevRuntime,
2063
+ "/react/jsx-runtime.js": JSXRuntime,
2064
+ "/react-dom/index.js": ReactDOM,
2065
+ "/react-dom/client.js": ReactDOMClient
2066
+ },
2067
+ "ComponentLoader"
1840
2068
  );
1841
2069
  applySharedModules(bundle, resolve);
1842
2070
  } else {
@@ -1864,19 +2092,8 @@ async function loadRemoteComponent({
1864
2092
  };
1865
2093
  }
1866
2094
  }
1867
- async function importCreateFromReadableStream() {
1868
- try {
1869
- const { createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1870
- return createFromReadableStream;
1871
- } catch {
1872
- const {
1873
- default: { createFromReadableStream }
1874
- } = await import("react-server-dom-webpack/client.browser");
1875
- return createFromReadableStream;
1876
- }
1877
- }
1878
2095
  async function loadRSCComponent(rscName, data) {
1879
- const createFromReadableStream = await importCreateFromReadableStream();
2096
+ const { createFromReadableStream } = await importRSCClientBrowser();
1880
2097
  if (typeof createFromReadableStream !== "function") {
1881
2098
  throw new RemoteComponentsError(
1882
2099
  'Failed to import "react-server-dom-webpack". Is Next.js installed correctly?'
@@ -1940,10 +2157,9 @@ async function importViaCallback(absoluteSrc, resolveClientUrl) {
1940
2157
  URL.revokeObjectURL(moduleBlobUrl);
1941
2158
  URL.revokeObjectURL(wrapperBlobUrl);
1942
2159
  }
1943
- const registry = globalThis.__rc_module_registry__;
1944
- const mod = registry?.[absoluteSrc] ?? {};
1945
- if (registry)
1946
- delete registry[absoluteSrc];
2160
+ const registry = getNamespace().moduleRegistry;
2161
+ const mod = registry[absoluteSrc] ?? {};
2162
+ delete registry[absoluteSrc];
1947
2163
  return mod;
1948
2164
  }
1949
2165
  async function importDirectly(absoluteSrc) {
@@ -1973,12 +2189,12 @@ function resolveScriptSrc(script, url) {
1973
2189
  return rawSrc;
1974
2190
  }
1975
2191
  async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1976
- const self = globalThis;
1977
- if (self.__remote_script_entrypoint_mount__?.[url.href]) {
1978
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
2192
+ const ns = getNamespace();
2193
+ if (ns.mountFns[url.href]) {
2194
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1979
2195
  }
1980
- if (self.__remote_script_entrypoint_unmount__?.[url.href]) {
1981
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
2196
+ if (ns.unmountFns[url.href]) {
2197
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1982
2198
  }
1983
2199
  const mountUnmountSets = await Promise.all(
1984
2200
  scripts.map(async (script) => {
@@ -1990,25 +2206,19 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1990
2206
  URL.revokeObjectURL(src);
1991
2207
  }
1992
2208
  if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
1993
- if (!self.__remote_script_entrypoint_mount__) {
1994
- self.__remote_script_entrypoint_mount__ = {};
1995
- }
1996
- if (!self.__remote_script_entrypoint_mount__[url.href]) {
1997
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
2209
+ if (!ns.mountFns[url.href]) {
2210
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1998
2211
  }
1999
- self.__remote_script_entrypoint_mount__[url.href]?.add(
2212
+ ns.mountFns[url.href]?.add(
2000
2213
  mod.mount || mod.default?.mount || (() => {
2001
2214
  })
2002
2215
  );
2003
2216
  }
2004
2217
  if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
2005
- if (!self.__remote_script_entrypoint_unmount__) {
2006
- self.__remote_script_entrypoint_unmount__ = {};
2218
+ if (!ns.unmountFns[url.href]) {
2219
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
2007
2220
  }
2008
- if (!self.__remote_script_entrypoint_unmount__[url.href]) {
2009
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
2010
- }
2011
- self.__remote_script_entrypoint_unmount__[url.href]?.add(
2221
+ ns.unmountFns[url.href]?.add(
2012
2222
  mod.unmount || mod.default?.unmount || (() => {
2013
2223
  })
2014
2224
  );
@@ -2048,44 +2258,42 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
2048
2258
  }
2049
2259
 
2050
2260
  // src/host/react/hooks/use-resolve-client-url.ts
2051
- var import_react = require("react");
2261
+ var import_react2 = require("react");
2052
2262
  var import_context = require("#internal/host/react/context");
2053
2263
  function useResolveClientUrl(prop, urlHref) {
2054
2264
  const { resolveClientUrl: contextValue } = (0, import_context.useRemoteComponentsContext)();
2055
2265
  const raw = prop ?? contextValue;
2056
- return (0, import_react.useMemo)(() => bindResolveClientUrl(raw, urlHref), [raw, urlHref]);
2266
+ return (0, import_react2.useMemo)(() => bindResolveClientUrl(raw, urlHref), [raw, urlHref]);
2057
2267
  }
2058
2268
 
2059
2269
  // src/host/react/hooks/use-shadow-root.ts
2060
- var import_react2 = require("react");
2270
+ var import_react3 = require("react");
2061
2271
  function useShadowRoot({
2062
2272
  isolate,
2063
2273
  mode,
2064
2274
  keySuffix
2065
2275
  }) {
2066
- const shadowRootContainerRef = (0, import_react2.useRef)(null);
2067
- const [shadowRoot, setShadowRoot] = (0, import_react2.useState)(() => {
2068
- const self = globalThis;
2069
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2276
+ const shadowRootContainerRef = (0, import_react3.useRef)(null);
2277
+ const [shadowRoot, setShadowRoot] = (0, import_react3.useState)(() => {
2278
+ const shadowRoots = getNamespace().shadowRoots;
2070
2279
  const ssrShadowRoot = typeof document !== "undefined" ? document.querySelector(
2071
2280
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
2072
- )?.shadowRoot ?? self[shadowRootKey] ?? null : null;
2073
- self[shadowRootKey] = null;
2281
+ )?.shadowRoot ?? shadowRoots[keySuffix] ?? null : null;
2282
+ shadowRoots[keySuffix] = null;
2074
2283
  return ssrShadowRoot;
2075
2284
  });
2076
- (0, import_react2.useLayoutEffect)(() => {
2285
+ (0, import_react3.useLayoutEffect)(() => {
2286
+ const shadowRoots = getNamespace().shadowRoots;
2077
2287
  if (isolate !== false && typeof document !== "undefined" && (!shadowRoot || !shadowRoot.isConnected)) {
2078
- const self = globalThis;
2079
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2080
2288
  let shadowRootElement = null;
2081
2289
  const element = document.querySelector(
2082
2290
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
2083
2291
  );
2084
- shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;
2292
+ shadowRootElement = shadowRoots[keySuffix] ?? element?.shadowRoot ?? null;
2085
2293
  if (!shadowRootElement && element) {
2086
2294
  try {
2087
2295
  shadowRootElement = element.attachShadow({ mode });
2088
- self[shadowRootKey] = shadowRootElement;
2296
+ shadowRoots[keySuffix] = shadowRootElement;
2089
2297
  } catch {
2090
2298
  }
2091
2299
  }
@@ -2096,9 +2304,7 @@ function useShadowRoot({
2096
2304
  setShadowRoot(shadowRootElement);
2097
2305
  }
2098
2306
  } else if (isolate === false && shadowRoot) {
2099
- const self = globalThis;
2100
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2101
- self[shadowRootKey] = null;
2307
+ shadowRoots[keySuffix] = null;
2102
2308
  setShadowRoot(null);
2103
2309
  }
2104
2310
  }, [isolate, shadowRoot, mode, keySuffix]);
@@ -2132,7 +2338,7 @@ var import_jsx_runtime2 = (
2132
2338
  // TODO: remove wrapper div by converting HTML to RSC or React tree
2133
2339
  require("react/jsx-runtime")
2134
2340
  );
2135
- var import_react4 = require("react");
2341
+ var import_react5 = require("react");
2136
2342
  function ConsumeRemoteComponent({
2137
2343
  src,
2138
2344
  isolate,
@@ -2150,36 +2356,36 @@ function ConsumeRemoteComponent({
2150
2356
  onResponse,
2151
2357
  resolveClientUrl: resolveClientUrlProp
2152
2358
  }) {
2153
- const instanceId = (0, import_react3.useId)();
2359
+ const instanceId = (0, import_react4.useId)();
2154
2360
  const { credentials: contextCredentials, shared: contextShared } = (0, import_context2.useRemoteComponentsContext)();
2155
2361
  const credentials = credentialsProp ?? contextCredentials ?? "same-origin";
2156
2362
  const shared2 = sharedProp ?? contextShared ?? {};
2157
- const name = (0, import_react3.useMemo)(
2363
+ const name = (0, import_react4.useMemo)(
2158
2364
  () => resolveNameFromSrc(src, nameProp),
2159
2365
  [src, nameProp]
2160
2366
  );
2161
- const [data, setData] = (0, import_react3.useState)(
2367
+ const [data, setData] = (0, import_react4.useState)(
2162
2368
  null
2163
2369
  );
2164
- const url = (0, import_react3.useMemo)(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);
2370
+ const url = (0, import_react4.useMemo)(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);
2165
2371
  const resolveClientUrl = useResolveClientUrl(resolveClientUrlProp, url.href);
2166
2372
  const id = url.origin === (typeof location !== "undefined" ? location.origin : DUMMY_FALLBACK) ? url.pathname : url.href;
2167
2373
  const keySuffix = `${escapeString(id)}_${escapeString(
2168
2374
  data?.name ?? name
2169
2375
  )}_${escapeString(instanceId)}`;
2170
- const [remoteComponent, setRemoteComponent] = (0, import_react3.useState)(null);
2376
+ const [remoteComponent, setRemoteComponent] = (0, import_react4.useState)(null);
2171
2377
  const { shadowRoot, shadowRootContainerRef } = useShadowRoot({
2172
2378
  isolate,
2173
2379
  mode,
2174
2380
  keySuffix
2175
2381
  });
2176
- const htmlRef = (0, import_react3.useRef)(
2382
+ const htmlRef = (0, import_react4.useRef)(
2177
2383
  typeof document !== "undefined" ? document.querySelector(
2178
2384
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
2179
2385
  )?.shadowRoot?.innerHTML ?? document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ?? document.querySelector(`div[data-bundle][data-route][id^="${name}"]`)?.innerHTML ?? document.querySelector("div[data-bundle][data-route]")?.innerHTML : null
2180
2386
  );
2181
- const endTemplateRef = (0, import_react3.useRef)(null);
2182
- const childrenRef = (0, import_react3.useRef)(
2387
+ const endTemplateRef = (0, import_react4.useRef)(null);
2388
+ const childrenRef = (0, import_react4.useRef)(
2183
2389
  typeof document !== "undefined" ? (() => {
2184
2390
  let el = document.querySelector(`template[id="${name}_start"]`);
2185
2391
  const elements = [];
@@ -2192,17 +2398,16 @@ function ConsumeRemoteComponent({
2192
2398
  return elements;
2193
2399
  })() : []
2194
2400
  );
2195
- const hostStateRef = (0, import_react3.useRef)(createHostState());
2196
- const componentHydrationHtml = (0, import_react3.useRef)(null);
2197
- const prevRemoteComponentContainerRef = (0, import_react3.useRef)(null);
2198
- const unmountRef = (0, import_react3.useRef)(null);
2199
- (0, import_react3.useLayoutEffect)(() => {
2200
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2401
+ const hostStateRef = (0, import_react4.useRef)(createHostState());
2402
+ const componentHydrationHtml = (0, import_react4.useRef)(null);
2403
+ const prevRemoteComponentContainerRef = (0, import_react4.useRef)(null);
2404
+ const unmountRef = (0, import_react4.useRef)(null);
2405
+ (0, import_react4.useLayoutEffect)(() => {
2201
2406
  return () => {
2202
- delete globalThis[shadowRootKey];
2407
+ delete getNamespace().shadowRoots[keySuffix];
2203
2408
  };
2204
2409
  }, [keySuffix]);
2205
- (0, import_react3.useLayoutEffect)(() => {
2410
+ (0, import_react4.useLayoutEffect)(() => {
2206
2411
  if (childrenRef.current.length > 0 && remoteComponent) {
2207
2412
  childrenRef.current.forEach((el) => {
2208
2413
  el.remove();
@@ -2210,7 +2415,7 @@ function ConsumeRemoteComponent({
2210
2415
  childrenRef.current = [];
2211
2416
  }
2212
2417
  }, [remoteComponent]);
2213
- (0, import_react3.useLayoutEffect)(() => {
2418
+ (0, import_react4.useLayoutEffect)(() => {
2214
2419
  if (shadowRoot && remoteComponent) {
2215
2420
  const resetStyles = shadowRoot.querySelectorAll(
2216
2421
  "style[data-remote-components-reset]"
@@ -2233,7 +2438,7 @@ function ConsumeRemoteComponent({
2233
2438
  }
2234
2439
  }
2235
2440
  }, [shadowRoot, remoteComponent, name]);
2236
- (0, import_react3.useEffect)(() => {
2441
+ (0, import_react4.useEffect)(() => {
2237
2442
  if (src && src !== hostStateRef.current.prevSrc) {
2238
2443
  const previousSrc = hostStateRef.current.prevSrc;
2239
2444
  const previousName = hostStateRef.current.prevName;
@@ -2246,7 +2451,7 @@ function ConsumeRemoteComponent({
2246
2451
  const { signal } = hostStateRef.current.abortController;
2247
2452
  onBeforeLoad?.(src);
2248
2453
  hostStateRef.current.stage = "loading";
2249
- (0, import_react3.startTransition)(async () => {
2454
+ (0, import_react4.startTransition)(async () => {
2250
2455
  try {
2251
2456
  let html = getRemoteComponentHtml(
2252
2457
  htmlRef.current ?? (endTemplateRef.current?.previousElementSibling?.tagName === "div" ? endTemplateRef.current.previousElementSibling.innerHTML : "")
@@ -2292,9 +2497,8 @@ function ConsumeRemoteComponent({
2292
2497
  if (shadowRoot) {
2293
2498
  shadowRoot.innerHTML = "";
2294
2499
  }
2295
- const self = globalThis;
2296
2500
  const prevUrl = hostStateRef.current.prevUrl;
2297
- if (prevUrl && self.__remote_script_entrypoint_unmount__?.[prevUrl.href]) {
2501
+ if (prevUrl && getNamespace().unmountFns[prevUrl.href]) {
2298
2502
  const unmountPromises = Promise.all(
2299
2503
  Array.from(unmountRef.current ?? []).map(
2300
2504
  async (unmount) => unmount(
@@ -2483,10 +2687,7 @@ function ConsumeRemoteComponent({
2483
2687
  ).href
2484
2688
  };
2485
2689
  }),
2486
- shared: {
2487
- ...sharedPolyfills(userShared, resolveClientUrl),
2488
- ...userShared
2489
- },
2690
+ shared: buildHostShared(userShared, resolveClientUrl),
2490
2691
  remoteShared,
2491
2692
  container: shadowRoot,
2492
2693
  resolveClientUrl
@@ -2552,7 +2753,7 @@ function ConsumeRemoteComponent({
2552
2753
  runtime: hostStateRef.current.prevIsRemoteComponent ? RUNTIME_SCRIPT : data?.runtime || RUNTIME_WEBPACK
2553
2754
  }) });
2554
2755
  const resetStyle = reset ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("style", { "data-remote-components-reset": "react", children: `:host { all: initial; }` }) : null;
2555
- const linksToRender = data?.links?.map((link) => /* @__PURE__ */ (0, import_react4.createElement)(
2756
+ const linksToRender = data?.links?.map((link) => /* @__PURE__ */ (0, import_react5.createElement)(
2556
2757
  "link",
2557
2758
  {
2558
2759
  ...link,
@@ -2618,8 +2819,10 @@ function ConsumeRemoteComponent({
2618
2819
  alt="" decoding="async" style="display:none"
2619
2820
  src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
2620
2821
  onload="(function(el){
2822
+ // Capture the shadow root during SSR hydration so the client-side
2823
+ // useShadowRoot hook can find it.
2621
2824
  const root = el.getRootNode();
2622
- globalThis.__remote_components_shadowroot_${keySuffix} = root;
2825
+ globalThis.__remote_components_shadowroot_${keySuffix}=root;
2623
2826
  el.parentElement.remove();
2624
2827
  })(this)"
2625
2828
  />`
@@ -2740,7 +2943,7 @@ function RemoteComponentsClientProvider({
2740
2943
  children,
2741
2944
  ...props
2742
2945
  }) {
2743
- const mergedShared = (0, import_react5.useMemo)(
2946
+ const mergedShared = (0, import_react6.useMemo)(
2744
2947
  () => sharedModules(shared2, resolveClientUrl),
2745
2948
  [shared2, resolveClientUrl]
2746
2949
  );