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
@@ -47,6 +47,9 @@ var init_app = __esm({
47
47
  // src/host/nextjs/app-client-only.tsx
48
48
  import { useMemo as useMemo3 } from "react";
49
49
 
50
+ // src/host/nextjs/image-shared.ts
51
+ import { createElement, forwardRef } from "react";
52
+
50
53
  // src/utils/index.ts
51
54
  function escapeString(str) {
52
55
  return str.replace(/[^a-z0-9]/g, "_");
@@ -73,6 +76,62 @@ function getBundleKey(bundle) {
73
76
  return escapeString(bundle);
74
77
  }
75
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
+
76
135
  // src/runtime/patterns.ts
77
136
  var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
78
137
  var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
@@ -197,7 +256,7 @@ Docs: ${CORS_DOCS_URL}`
197
256
 
198
257
  // src/utils/logger.ts
199
258
  var PREFIX = "remote-components";
200
- 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";
201
260
  function logDebug(location2, message) {
202
261
  if (DEBUG) {
203
262
  console.debug(`[${PREFIX}:${location2}]: ${message}`);
@@ -229,11 +288,7 @@ function warnCrossOriginFetchError(logLocation, url) {
229
288
 
230
289
  // src/runtime/turbopack/remote-scope.ts
231
290
  function getRegistry() {
232
- const self = globalThis;
233
- if (!self.__remote_component_scopes__) {
234
- self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
235
- }
236
- return self.__remote_component_scopes__;
291
+ return getNamespace().scopes;
237
292
  }
238
293
  function createScope(name, url, runtime, resolveClientUrl) {
239
294
  const isCrossOrigin = url.origin !== location.origin;
@@ -251,7 +306,8 @@ function createScope(name, url, runtime, resolveClientUrl) {
251
306
  resolveClientUrl,
252
307
  moduleCache: {},
253
308
  sharedModules: {},
254
- moduleGlobal: {}
309
+ moduleGlobal: {},
310
+ turbopackModules: []
255
311
  };
256
312
  }
257
313
  function registerScope(scope) {
@@ -348,16 +404,41 @@ function createImageLoaderSharedEntries({
348
404
  bound,
349
405
  unbound
350
406
  } = {}) {
351
- const entry = (bundle) => {
407
+ const loaderEntry = (bundle) => {
352
408
  const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
353
409
  return Promise.resolve({
354
410
  default: createRemoteImageLoader(bundle, resolveClientUrl),
355
411
  __esModule: true
356
412
  });
357
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
+ };
358
433
  return {
359
- "next/dist/shared/lib/image-loader": entry,
360
- "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
361
442
  };
362
443
  }
363
444
 
@@ -445,9 +526,9 @@ function getClientOrServerUrl(src, serverFallback) {
445
526
  // src/host/shared/polyfill.tsx
446
527
  import { jsx } from "react/jsx-runtime";
447
528
  function sharedPolyfills(shared2, resolveClientUrl) {
448
- const self = globalThis;
529
+ const hostShared = getNamespace().hostSharedModules;
449
530
  const polyfill = {
450
- "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({
451
532
  useRouter() {
452
533
  return {
453
534
  push: (routerUrl) => {
@@ -478,7 +559,7 @@ function sharedPolyfills(shared2, resolveClientUrl) {
478
559
  },
479
560
  __esModule: true
480
561
  })),
481
- "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({
482
563
  default: ({
483
564
  scroll: _,
484
565
  replace,
@@ -528,7 +609,7 @@ function sharedPolyfills(shared2, resolveClientUrl) {
528
609
  },
529
610
  __esModule: true
530
611
  })),
531
- "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({
532
613
  default: () => {
533
614
  throw new Error("Next.js <Form> component not implemented");
534
615
  },
@@ -539,17 +620,17 @@ function sharedPolyfills(shared2, resolveClientUrl) {
539
620
  // This gives us full next/image fidelity (fill, priority, srcSet, blur
540
621
  // placeholders, error handling) while routing image optimization through the
541
622
  // remote app's /_next/image endpoint.
542
- "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({
543
624
  default: createRemoteImageLoader(bundle, resolveClientUrl),
544
625
  __esModule: true
545
626
  })),
546
- "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({
547
628
  // TODO: implement <Script> component for non-Next.js host applications
548
629
  // do not throw an error for now
549
630
  default: () => null,
550
631
  __esModule: true
551
632
  })),
552
- "next/router": self.__remote_component_host_shared_modules__?.["next/router"] ?? shared2?.["next/router"] ?? (() => (
633
+ "next/router": hostShared["next/router"] ?? shared2?.["next/router"] ?? (() => (
553
634
  // TODO: incomplete implementation
554
635
  Promise.resolve({
555
636
  useRouter() {
@@ -585,6 +666,68 @@ function sharedPolyfills(shared2, resolveClientUrl) {
585
666
  return polyfill;
586
667
  }
587
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
+
588
731
  // src/host/shared/state.ts
589
732
  function createHostState() {
590
733
  return {
@@ -611,8 +754,8 @@ function resolveNameFromSrc(src, defaultName) {
611
754
  return name || defaultName;
612
755
  }
613
756
 
614
- // src/runtime/html/apply-origin.ts
615
- var tagNames = [
757
+ // src/runtime/html/html-spec.ts
758
+ var ORIGIN_REWRITE_TAGS = [
616
759
  "img",
617
760
  "source",
618
761
  "video",
@@ -623,10 +766,37 @@ var tagNames = [
623
766
  "script",
624
767
  "link"
625
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
626
796
  function applyOriginToNodes(doc, url, resolveClientUrl) {
627
797
  if (url.origin !== location.origin) {
628
798
  const nodes = doc.querySelectorAll(
629
- tagNames.map(
799
+ ORIGIN_REWRITE_TAGS.map(
630
800
  (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
631
801
  ).join(",")
632
802
  );
@@ -644,29 +814,17 @@ function applyOriginToNodes(doc, url, resolveClientUrl) {
644
814
  );
645
815
  }
646
816
  if (node.hasAttribute("srcset")) {
647
- const srcSet = node.getAttribute("srcset")?.split(",").map((entry) => {
648
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
649
- if (!urlPart)
650
- return entry;
651
- const absoluteUrl = new URL(urlPart, url).href;
652
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
653
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
654
- }).join(", ");
655
- if (srcSet) {
656
- 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));
657
821
  }
658
822
  }
659
823
  if (node.hasAttribute("imagesrcset")) {
660
- const srcSet = node.getAttribute("imagesrcset")?.split(",").map((entry) => {
661
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
662
- if (!urlPart)
663
- return entry;
664
- const absoluteUrl = new URL(urlPart, url).href;
665
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
666
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
667
- }).join(", ");
668
- if (srcSet) {
669
- 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));
670
828
  }
671
829
  }
672
830
  });
@@ -707,26 +865,28 @@ function buildMetadata(attrs, url) {
707
865
 
708
866
  // src/runtime/html/parse-remote-html.ts
709
867
  function validateSingleComponent(doc, name, url) {
710
- 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}"]`)) {
711
871
  throw multipleRemoteComponentsError(url);
712
872
  }
713
873
  }
714
874
  function findComponentElement(doc, name) {
715
- 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])`);
716
876
  }
717
877
  function parseNextData(doc) {
718
878
  return JSON.parse(
719
- (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"
720
880
  );
721
881
  }
722
882
  function resolveComponentName(component, nextData, fallbackName) {
723
- const isRemoteComponent = component?.tagName.toLowerCase() === "remote-component";
724
- 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);
725
885
  return { name, isRemoteComponent };
726
886
  }
727
887
  function extractRemoteShared(doc, name, nextData) {
728
888
  const remoteSharedEl = doc.querySelector(
729
- `#${name}_shared[data-remote-components-shared]`
889
+ `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`
730
890
  );
731
891
  const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
732
892
  remoteSharedEl?.remove();
@@ -747,7 +907,7 @@ function extractLinks(doc, component) {
747
907
  function extractScripts(doc, component, isRemoteComponent) {
748
908
  return Array.from(
749
909
  (isRemoteComponent ? component : doc).querySelectorAll(
750
- "script[src],script[data-src]"
910
+ `script[src],script[${DATA_SRC}]`
751
911
  )
752
912
  );
753
913
  }
@@ -760,15 +920,15 @@ function parseRemoteComponentDocument(doc, name, url) {
760
920
  nextData,
761
921
  name
762
922
  );
763
- const rsc = doc.querySelector(`#${resolvedName}_rsc`);
923
+ const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);
764
924
  const metadata = buildMetadata(
765
925
  {
766
926
  name: resolvedName,
767
- bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle,
768
- route: component?.getAttribute("data-route") ?? nextData?.page,
769
- 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,
770
930
  id: component?.getAttribute("id"),
771
- type: component?.getAttribute("data-type")
931
+ type: component?.getAttribute(DATA_TYPE)
772
932
  },
773
933
  url
774
934
  );
@@ -857,13 +1017,15 @@ function applySharedModules(bundle, resolve) {
857
1017
  `Shared modules to resolve: ${Object.keys(resolve)}`
858
1018
  );
859
1019
  const self = globalThis;
860
- if (self.__remote_webpack_require__?.[bundle]) {
1020
+ const scope = getScope(bundle);
1021
+ const webpackBundle = scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];
1022
+ if (webpackBundle) {
861
1023
  const modulePaths = Object.keys(
862
- self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
1024
+ self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {}
863
1025
  );
864
1026
  logDebug(
865
1027
  "SharedModules",
866
- `Available module paths in __remote_webpack_require__[${bundle}]: ${modulePaths}`
1028
+ `Available module paths for bundle "${bundle}": ${modulePaths}`
867
1029
  );
868
1030
  for (const [key, value] of Object.entries(resolve)) {
869
1031
  const exactIds = modulePaths.filter((p) => p === key);
@@ -875,7 +1037,6 @@ function applySharedModules(bundle, resolve) {
875
1037
  );
876
1038
  }
877
1039
  for (const id of ids) {
878
- const webpackBundle = self.__remote_webpack_require__[bundle];
879
1040
  if (webpackBundle.m) {
880
1041
  const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
881
1042
  if (resolvedId !== id) {
@@ -973,10 +1134,8 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
973
1134
  ];
974
1135
  const { default: Component } = componentLoader();
975
1136
  const { default: App } = appLoader();
976
- if (!self.__remote_next_css__) {
977
- self.__remote_next_css__ = {};
978
- }
979
- if (!self.__remote_next_css__[bundle]) {
1137
+ const cssCache = getNamespace().cssCache;
1138
+ if (!cssCache[bundle]) {
980
1139
  const cssRE = /\.s?css$/;
981
1140
  Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
982
1141
  self.__remote_webpack_require__?.[bundle]?.(id);
@@ -994,15 +1153,15 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
994
1153
  node.remove();
995
1154
  node = nextCss.previousSibling;
996
1155
  }
997
- self.__remote_next_css__[bundle] = elements;
1156
+ cssCache[bundle] = elements;
998
1157
  }
999
1158
  if (styleContainer) {
1000
- const elements = self.__remote_next_css__[bundle];
1159
+ const elements = cssCache[bundle];
1001
1160
  elements.forEach((el) => {
1002
1161
  styleContainer.appendChild(el.cloneNode(true));
1003
1162
  });
1004
1163
  } else {
1005
- const elements = self.__remote_next_css__[bundle];
1164
+ const elements = cssCache[bundle];
1006
1165
  elements.forEach((el) => {
1007
1166
  document.head.appendChild(el);
1008
1167
  });
@@ -1039,6 +1198,18 @@ function fixPayload(payload) {
1039
1198
  }
1040
1199
  }
1041
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
+ }
1042
1213
  function createRSCStream(rscName, data) {
1043
1214
  return new ReadableStream({
1044
1215
  type: "bytes",
@@ -1046,16 +1217,11 @@ function createRSCStream(rscName, data) {
1046
1217
  const encoder = new TextEncoder();
1047
1218
  const self = globalThis;
1048
1219
  if (data.length > 0) {
1049
- data.forEach((chunk) => {
1050
- const lines = chunk.split("\n");
1051
- for (const line of lines) {
1052
- const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1053
- if (match?.groups?.rsc) {
1054
- self[rscName] = self[rscName] ?? [];
1055
- self[rscName].push(JSON.parse(`"${match.groups.rsc}"`));
1056
- }
1057
- }
1058
- });
1220
+ const parsed = buildRSCChunks(rscName, data);
1221
+ if (parsed.length > 0) {
1222
+ self[rscName] = self[rscName] ?? [];
1223
+ self[rscName].push(...parsed);
1224
+ }
1059
1225
  }
1060
1226
  const allChunks = (self[rscName] ?? [`0:[null]
1061
1227
  `]).join("");
@@ -1085,12 +1251,38 @@ function createRSCStream(rscName, data) {
1085
1251
  });
1086
1252
  }
1087
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
+
1088
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
+ }
1089
1276
  var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
1090
- var REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
1091
- var ASYNC_MODULE_LOADER_RE = /(?:__turbopack_context__|e)\.A\((?<asyncSharedModuleId>[0-9]+)\)/;
1092
- var ASYNC_MODULE_RESOLVE_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<inner>parentImport|e)=>Promise\.resolve\(\)\.then\(\(\)=>\k<inner>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
1093
- 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
+ );
1094
1286
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
1095
1287
 
1096
1288
  // src/runtime/turbopack/chunk-loader.ts
@@ -1100,6 +1292,7 @@ function loadChunkWithScope(scope, chunkId) {
1100
1292
  `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
1101
1293
  );
1102
1294
  const self = globalThis;
1295
+ const ns = getNamespace();
1103
1296
  const { bundle, path, prefix } = parseRemoteId(chunkId);
1104
1297
  const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
1105
1298
  if (remoteRuntime === RUNTIME_WEBPACK) {
@@ -1110,35 +1303,31 @@ function loadChunkWithScope(scope, chunkId) {
1110
1303
  if (url.endsWith(".css")) {
1111
1304
  return;
1112
1305
  }
1113
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1114
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
1115
- }
1116
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1117
- 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];
1118
1309
  }
1119
1310
  const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1120
1311
  if (resolvedUrl !== url) {
1121
1312
  logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1122
1313
  }
1123
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1124
- (resolve, reject) => {
1125
- fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1126
- const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1127
- if (hasTurbopack) {
1128
- return handleTurbopackChunk(code, scope, url);
1129
- }
1130
- }).then(resolve).catch((error) => {
1131
- const isProxied = isProxiedUrl(resolvedUrl);
1132
- if (isProxied) {
1133
- reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1134
- } else {
1135
- warnCrossOriginFetchError("ChunkLoader", url);
1136
- reject(error);
1137
- }
1138
- });
1139
- }
1140
- );
1141
- 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];
1142
1331
  }
1143
1332
  function createChunkDispatcher() {
1144
1333
  return function __chunk_dispatcher__(chunkId, scriptBundle) {
@@ -1187,19 +1376,39 @@ async function handleTurbopackChunk(code, scope, url) {
1187
1376
  `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1188
1377
  );
1189
1378
  if (!self[`TURBOPACK_${globalKey}`]) {
1190
- const chunkData = [];
1191
- const turbopackObject = {
1192
- push: (item) => {
1193
- if (Array.isArray(item)) {
1194
- chunkData.push(item);
1195
- } else {
1196
- 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
+ }
1197
1392
  }
1198
- return chunkData.length;
1199
- },
1200
- __chunks__: chunkData
1393
+ return originalPush.apply(target, items);
1394
+ };
1395
+ return target;
1201
1396
  };
1202
- 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
+ });
1203
1412
  }
1204
1413
  await new Promise((scriptResolve, scriptReject) => {
1205
1414
  const blob = new Blob([transformedCode], {
@@ -1251,13 +1460,13 @@ async function handleTurbopackChunk(code, scope, url) {
1251
1460
  // src/runtime/turbopack/shared-modules.ts
1252
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).";
1253
1462
  function getTurbopackModules(scope) {
1463
+ if (scope.turbopackModules.length > 0) {
1464
+ return scope.turbopackModules;
1465
+ }
1254
1466
  const self = globalThis;
1255
1467
  const raw = self[`TURBOPACK_${scope.globalKey}`];
1256
1468
  if (!raw)
1257
1469
  return void 0;
1258
- if (typeof raw === "object" && "__chunks__" in raw) {
1259
- return raw.__chunks__.flat();
1260
- }
1261
1470
  if (Array.isArray(raw)) {
1262
1471
  return raw.flat();
1263
1472
  }
@@ -1281,7 +1490,11 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1281
1490
  if (sharedModuleInitializerIndex > 0) {
1282
1491
  const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1283
1492
  const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1284
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1493
+ const sharedModuleId = extractGroup(
1494
+ REMOTE_SHARED_ASSIGNMENT_RE,
1495
+ sharedModuleInitializerCode,
1496
+ "sharedModuleId"
1497
+ );
1285
1498
  if (sharedModuleId) {
1286
1499
  const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1287
1500
  scope,
@@ -1339,20 +1552,22 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1339
1552
  }
1340
1553
  function extractSharedModuleIds(shared2, scope) {
1341
1554
  return Object.entries(shared2).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1342
- 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
+ );
1343
1560
  if (asyncSharedModuleId) {
1344
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1345
- let asyncSharedModule;
1346
- const turbopackModules = getTurbopackModules(scope) ?? [];
1347
- const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1348
- asyncSharedModuleIdNumber
1561
+ const asyncSharedModule = findModuleInit(
1562
+ getTurbopackModules(scope),
1563
+ asyncSharedModuleId
1349
1564
  );
1350
- if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1351
- asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1352
- }
1353
1565
  if (asyncSharedModule) {
1354
- const asyncSharedModuleCode = asyncSharedModule.toString();
1355
- 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
+ );
1356
1571
  acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1357
1572
  "__remote_shared_module_",
1358
1573
  ""
@@ -1443,9 +1658,17 @@ function findModuleInit(modules, moduleId) {
1443
1658
  if (idx >= 0) {
1444
1659
  return flat.slice(idx + 1).find((e) => typeof e === "function");
1445
1660
  }
1446
- return flat.find(
1447
- (e) => Boolean(e && typeof e === "object" && moduleId in e)
1448
- )?.[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;
1449
1672
  }
1450
1673
  function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1451
1674
  const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
@@ -1524,7 +1747,10 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1524
1747
  }
1525
1748
  if (typeof mod !== "object" || mod === null) {
1526
1749
  mod = { default: mod };
1527
- } 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]") {
1528
1754
  try {
1529
1755
  mod.default = mod;
1530
1756
  } catch {
@@ -1588,21 +1814,38 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1588
1814
  };
1589
1815
  }
1590
1816
 
1591
- // src/runtime/turbopack/webpack-runtime.ts
1592
- 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) {
1593
1819
  const self = globalThis;
1820
+ const ns = getNamespace();
1594
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
+ }
1595
1838
  const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1596
1839
  registerScope(scope);
1597
- if (!self.__remote_bundle_url__) {
1598
- self.__remote_bundle_url__ = {};
1840
+ if (runtime === RUNTIME_WEBPACK && self.__remote_webpack_require__?.[bundleName]) {
1841
+ scope.webpackRequire = self.__remote_webpack_require__[bundleName];
1599
1842
  }
1600
- self.__remote_bundle_url__[bundleName] = url;
1843
+ ns.bundleUrls[bundleName] = url;
1601
1844
  if (scope.scopedName !== bundleName) {
1602
- self.__remote_bundle_url__[scope.scopedName] = url;
1845
+ ns.bundleUrls[scope.scopedName] = url;
1603
1846
  }
1604
1847
  self.__webpack_get_script_filename__ = () => null;
1605
- const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1848
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || ns.dispatcherRuntime !== "turbopack";
1606
1849
  if (willCreateDispatchers) {
1607
1850
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1608
1851
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
@@ -1610,6 +1853,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1610
1853
  }
1611
1854
  self.__webpack_chunk_load__ = createChunkDispatcher();
1612
1855
  self.__webpack_require__ = createModuleDispatcher(runtime);
1856
+ ns.dispatcherRuntime = runtime;
1613
1857
  self.__webpack_require_type__ = runtime;
1614
1858
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1615
1859
  self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
@@ -1637,15 +1881,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1637
1881
  }
1638
1882
  }
1639
1883
  }
1640
- const coreShared = {
1641
- react: async () => (await import("react")).default,
1642
- "react-dom": async () => (await import("react-dom")).default,
1643
- "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
1644
- "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
1645
- "react-dom/client": async () => (await import("react-dom/client")).default,
1646
- ...shared2
1647
- };
1648
- await initializeSharedModules(scope, coreShared, remoteShared);
1884
+ return scope;
1649
1885
  }
1650
1886
  function createModuleDispatcher(runtime) {
1651
1887
  return (id) => {
@@ -1662,6 +1898,9 @@ function createModuleDispatcher(runtime) {
1662
1898
  );
1663
1899
  try {
1664
1900
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1901
+ const scope2 = getScope(bundle);
1902
+ if (scope2?.webpackRequire)
1903
+ return scope2.webpackRequire(moduleId);
1665
1904
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1666
1905
  }
1667
1906
  const scope = getScope(bundleName);
@@ -1779,44 +2018,33 @@ async function loadRemoteComponent({
1779
2018
  "ComponentLoader",
1780
2019
  `Remote shared modules requested: ${JSON.stringify(remoteShared)}`
1781
2020
  );
1782
- await setupWebpackRuntime(
2021
+ const scope = await setupRemoteScope(
1783
2022
  runtime,
1784
2023
  scripts,
1785
2024
  url,
1786
2025
  bundle,
1787
- hostShared,
1788
- remoteShared,
1789
2026
  resolveClientUrl
1790
2027
  );
2028
+ if (runtime === "turbopack") {
2029
+ await initializeSharedModules(
2030
+ scope,
2031
+ buildCoreShared(hostShared),
2032
+ remoteShared
2033
+ );
2034
+ }
1791
2035
  if (bundle) {
1792
- const resolve = {
1793
- "/react/index.js": React,
1794
- "/react/jsx-dev-runtime.js": JSXDevRuntime,
1795
- "/react/jsx-runtime.js": JSXRuntime,
1796
- "/react-dom/index.js": ReactDOM,
1797
- "/react-dom/client.js": ReactDOMClient,
1798
- ...Object.entries(remoteShared).reduce(
1799
- (acc, [key, value]) => {
1800
- if (typeof hostShared[value] !== "undefined") {
1801
- acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
1802
- } else {
1803
- logDebug(
1804
- "ComponentLoader",
1805
- `Remote requests "${value}" but host doesn't provide it`
1806
- );
1807
- }
1808
- return acc;
1809
- },
1810
- {}
1811
- )
1812
- };
1813
- await Promise.all(
1814
- Object.entries(resolve).map(async ([key, value]) => {
1815
- if (typeof value === "function") {
1816
- resolve[key] = await value(bundle);
1817
- }
1818
- return Promise.resolve(value);
1819
- })
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"
1820
2048
  );
1821
2049
  applySharedModules(bundle, resolve);
1822
2050
  } else {
@@ -1844,19 +2072,8 @@ async function loadRemoteComponent({
1844
2072
  };
1845
2073
  }
1846
2074
  }
1847
- async function importCreateFromReadableStream() {
1848
- try {
1849
- const { createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1850
- return createFromReadableStream;
1851
- } catch {
1852
- const {
1853
- default: { createFromReadableStream }
1854
- } = await import("react-server-dom-webpack/client.browser");
1855
- return createFromReadableStream;
1856
- }
1857
- }
1858
2075
  async function loadRSCComponent(rscName, data) {
1859
- const createFromReadableStream = await importCreateFromReadableStream();
2076
+ const { createFromReadableStream } = await importRSCClientBrowser();
1860
2077
  if (typeof createFromReadableStream !== "function") {
1861
2078
  throw new RemoteComponentsError(
1862
2079
  'Failed to import "react-server-dom-webpack". Is Next.js installed correctly?'
@@ -1920,10 +2137,9 @@ async function importViaCallback(absoluteSrc, resolveClientUrl) {
1920
2137
  URL.revokeObjectURL(moduleBlobUrl);
1921
2138
  URL.revokeObjectURL(wrapperBlobUrl);
1922
2139
  }
1923
- const registry = globalThis.__rc_module_registry__;
1924
- const mod = registry?.[absoluteSrc] ?? {};
1925
- if (registry)
1926
- delete registry[absoluteSrc];
2140
+ const registry = getNamespace().moduleRegistry;
2141
+ const mod = registry[absoluteSrc] ?? {};
2142
+ delete registry[absoluteSrc];
1927
2143
  return mod;
1928
2144
  }
1929
2145
  async function importDirectly(absoluteSrc) {
@@ -1953,12 +2169,12 @@ function resolveScriptSrc(script, url) {
1953
2169
  return rawSrc;
1954
2170
  }
1955
2171
  async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1956
- const self = globalThis;
1957
- if (self.__remote_script_entrypoint_mount__?.[url.href]) {
1958
- 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();
1959
2175
  }
1960
- if (self.__remote_script_entrypoint_unmount__?.[url.href]) {
1961
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
2176
+ if (ns.unmountFns[url.href]) {
2177
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1962
2178
  }
1963
2179
  const mountUnmountSets = await Promise.all(
1964
2180
  scripts.map(async (script) => {
@@ -1970,25 +2186,19 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1970
2186
  URL.revokeObjectURL(src);
1971
2187
  }
1972
2188
  if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
1973
- if (!self.__remote_script_entrypoint_mount__) {
1974
- self.__remote_script_entrypoint_mount__ = {};
2189
+ if (!ns.mountFns[url.href]) {
2190
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1975
2191
  }
1976
- if (!self.__remote_script_entrypoint_mount__[url.href]) {
1977
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
1978
- }
1979
- self.__remote_script_entrypoint_mount__[url.href]?.add(
2192
+ ns.mountFns[url.href]?.add(
1980
2193
  mod.mount || mod.default?.mount || (() => {
1981
2194
  })
1982
2195
  );
1983
2196
  }
1984
2197
  if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
1985
- if (!self.__remote_script_entrypoint_unmount__) {
1986
- self.__remote_script_entrypoint_unmount__ = {};
1987
- }
1988
- if (!self.__remote_script_entrypoint_unmount__[url.href]) {
1989
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
2198
+ if (!ns.unmountFns[url.href]) {
2199
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1990
2200
  }
1991
- self.__remote_script_entrypoint_unmount__[url.href]?.add(
2201
+ ns.unmountFns[url.href]?.add(
1992
2202
  mod.unmount || mod.default?.unmount || (() => {
1993
2203
  })
1994
2204
  );
@@ -2045,27 +2255,25 @@ function useShadowRoot({
2045
2255
  }) {
2046
2256
  const shadowRootContainerRef = useRef(null);
2047
2257
  const [shadowRoot, setShadowRoot] = useState(() => {
2048
- const self = globalThis;
2049
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2258
+ const shadowRoots = getNamespace().shadowRoots;
2050
2259
  const ssrShadowRoot = typeof document !== "undefined" ? document.querySelector(
2051
2260
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
2052
- )?.shadowRoot ?? self[shadowRootKey] ?? null : null;
2053
- self[shadowRootKey] = null;
2261
+ )?.shadowRoot ?? shadowRoots[keySuffix] ?? null : null;
2262
+ shadowRoots[keySuffix] = null;
2054
2263
  return ssrShadowRoot;
2055
2264
  });
2056
2265
  useLayoutEffect(() => {
2266
+ const shadowRoots = getNamespace().shadowRoots;
2057
2267
  if (isolate !== false && typeof document !== "undefined" && (!shadowRoot || !shadowRoot.isConnected)) {
2058
- const self = globalThis;
2059
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2060
2268
  let shadowRootElement = null;
2061
2269
  const element = document.querySelector(
2062
2270
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
2063
2271
  );
2064
- shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;
2272
+ shadowRootElement = shadowRoots[keySuffix] ?? element?.shadowRoot ?? null;
2065
2273
  if (!shadowRootElement && element) {
2066
2274
  try {
2067
2275
  shadowRootElement = element.attachShadow({ mode });
2068
- self[shadowRootKey] = shadowRootElement;
2276
+ shadowRoots[keySuffix] = shadowRootElement;
2069
2277
  } catch {
2070
2278
  }
2071
2279
  }
@@ -2076,9 +2284,7 @@ function useShadowRoot({
2076
2284
  setShadowRoot(shadowRootElement);
2077
2285
  }
2078
2286
  } else if (isolate === false && shadowRoot) {
2079
- const self = globalThis;
2080
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2081
- self[shadowRootKey] = null;
2287
+ shadowRoots[keySuffix] = null;
2082
2288
  setShadowRoot(null);
2083
2289
  }
2084
2290
  }, [isolate, shadowRoot, mode, keySuffix]);
@@ -2109,7 +2315,7 @@ function getRemoteComponentHtml(html) {
2109
2315
 
2110
2316
  // src/host/react/index.tsx
2111
2317
  import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
2112
- import { createElement as createElement2 } from "react";
2318
+ import { createElement as createElement3 } from "react";
2113
2319
  function ConsumeRemoteComponent({
2114
2320
  src,
2115
2321
  isolate,
@@ -2174,9 +2380,8 @@ function ConsumeRemoteComponent({
2174
2380
  const prevRemoteComponentContainerRef = useRef2(null);
2175
2381
  const unmountRef = useRef2(null);
2176
2382
  useLayoutEffect2(() => {
2177
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2178
2383
  return () => {
2179
- delete globalThis[shadowRootKey];
2384
+ delete getNamespace().shadowRoots[keySuffix];
2180
2385
  };
2181
2386
  }, [keySuffix]);
2182
2387
  useLayoutEffect2(() => {
@@ -2269,9 +2474,8 @@ function ConsumeRemoteComponent({
2269
2474
  if (shadowRoot) {
2270
2475
  shadowRoot.innerHTML = "";
2271
2476
  }
2272
- const self = globalThis;
2273
2477
  const prevUrl = hostStateRef.current.prevUrl;
2274
- if (prevUrl && self.__remote_script_entrypoint_unmount__?.[prevUrl.href]) {
2478
+ if (prevUrl && getNamespace().unmountFns[prevUrl.href]) {
2275
2479
  const unmountPromises = Promise.all(
2276
2480
  Array.from(unmountRef.current ?? []).map(
2277
2481
  async (unmount) => unmount(
@@ -2461,10 +2665,7 @@ function ConsumeRemoteComponent({
2461
2665
  ).href
2462
2666
  };
2463
2667
  }),
2464
- shared: {
2465
- ...sharedPolyfills(userShared, resolveClientUrl),
2466
- ...userShared
2467
- },
2668
+ shared: buildHostShared(userShared, resolveClientUrl),
2468
2669
  remoteShared,
2469
2670
  container: shadowRoot,
2470
2671
  resolveClientUrl
@@ -2530,7 +2731,7 @@ function ConsumeRemoteComponent({
2530
2731
  runtime: hostStateRef.current.prevIsRemoteComponent ? RUNTIME_SCRIPT : data?.runtime || RUNTIME_WEBPACK
2531
2732
  }) });
2532
2733
  const resetStyle = reset ? /* @__PURE__ */ jsx2("style", { "data-remote-components-reset": "react", children: `:host { all: initial; }` }) : null;
2533
- const linksToRender = data?.links?.map((link) => /* @__PURE__ */ createElement2(
2734
+ const linksToRender = data?.links?.map((link) => /* @__PURE__ */ createElement3(
2534
2735
  "link",
2535
2736
  {
2536
2737
  ...link,
@@ -2596,8 +2797,10 @@ function ConsumeRemoteComponent({
2596
2797
  alt="" decoding="async" style="display:none"
2597
2798
  src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
2598
2799
  onload="(function(el){
2800
+ // Capture the shadow root during SSR hydration so the client-side
2801
+ // useShadowRoot hook can find it.
2599
2802
  const root = el.getRootNode();
2600
- globalThis.__remote_components_shadowroot_${keySuffix} = root;
2803
+ globalThis.__remote_components_shadowroot_${keySuffix}=root;
2601
2804
  el.parentElement.remove();
2602
2805
  })(this)"
2603
2806
  />`