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
@@ -152,7 +152,7 @@ Docs: ${CORS_DOCS_URL}`
152
152
 
153
153
  // src/utils/logger.ts
154
154
  var PREFIX = "remote-components";
155
- var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
155
+ var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true" || typeof process !== "undefined" && process.env.RC_DEBUG === "true";
156
156
  function logDebug(location2, message) {
157
157
  if (DEBUG) {
158
158
  console.debug(`[${PREFIX}:${location2}]: ${message}`);
@@ -263,6 +263,62 @@ function getBundleKey(bundle) {
263
263
  return escapeString(bundle);
264
264
  }
265
265
 
266
+ // src/runtime/namespace.ts
267
+ var SHADOW_ROOT_PREFIX = "__remote_components_shadowroot_";
268
+ var LEGACY_ALIASES = [
269
+ { global: "__remote_component_scopes__", prop: "scopes" },
270
+ {
271
+ global: "__remote_components_turbopack_chunk_loader_promise__",
272
+ prop: "chunkCache"
273
+ },
274
+ { global: "__remote_script_entrypoint_mount__", prop: "mountFns" },
275
+ { global: "__remote_script_entrypoint_unmount__", prop: "unmountFns" },
276
+ { global: "__remote_bundle_url__", prop: "bundleUrls" },
277
+ { global: "__rc_module_registry__", prop: "moduleRegistry" },
278
+ {
279
+ global: "__remote_component_host_shared_modules__",
280
+ prop: "hostSharedModules"
281
+ },
282
+ { global: "__remote_next_css__", prop: "cssCache" }
283
+ ];
284
+ function getNamespace() {
285
+ const g = globalThis;
286
+ const existing = g.__remote_components__;
287
+ if (existing) {
288
+ return existing;
289
+ }
290
+ const ns = {
291
+ scopes: /* @__PURE__ */ new Map(),
292
+ chunkCache: {},
293
+ mountFns: {},
294
+ unmountFns: {},
295
+ bundleUrls: {},
296
+ moduleRegistry: {},
297
+ dispatcherRuntime: void 0,
298
+ hostSharedModules: {},
299
+ cssCache: {},
300
+ shadowRoots: {}
301
+ };
302
+ const nsRecord = ns;
303
+ for (const { global, prop } of LEGACY_ALIASES) {
304
+ const legacyValue = g[global];
305
+ if (legacyValue != null) {
306
+ nsRecord[prop] = legacyValue;
307
+ }
308
+ g[global] = ns[prop];
309
+ }
310
+ const gRecord = g;
311
+ for (const key of Object.keys(gRecord)) {
312
+ if (key.startsWith(SHADOW_ROOT_PREFIX)) {
313
+ const suffix = key.slice(SHADOW_ROOT_PREFIX.length);
314
+ ns.shadowRoots[suffix] = gRecord[key];
315
+ delete gRecord[key];
316
+ }
317
+ }
318
+ g.__remote_components__ = ns;
319
+ return ns;
320
+ }
321
+
266
322
  // src/runtime/patterns.ts
267
323
  var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
268
324
  var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
@@ -273,11 +329,7 @@ function collapseDoubleSlashes(path) {
273
329
 
274
330
  // src/runtime/turbopack/remote-scope.ts
275
331
  function getRegistry() {
276
- const self = globalThis;
277
- if (!self.__remote_component_scopes__) {
278
- self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
279
- }
280
- return self.__remote_component_scopes__;
332
+ return getNamespace().scopes;
281
333
  }
282
334
  function createScope(name, url, runtime, resolveClientUrl) {
283
335
  const isCrossOrigin = url.origin !== location.origin;
@@ -295,7 +347,8 @@ function createScope(name, url, runtime, resolveClientUrl) {
295
347
  resolveClientUrl,
296
348
  moduleCache: {},
297
349
  sharedModules: {},
298
- moduleGlobal: {}
350
+ moduleGlobal: {},
351
+ turbopackModules: []
299
352
  };
300
353
  }
301
354
  function registerScope(scope) {
@@ -360,9 +413,9 @@ function createRemoteImageLoader(bundle, resolveClientUrl) {
360
413
  // src/host/shared/polyfill.tsx
361
414
  var import_jsx_runtime = require("react/jsx-runtime");
362
415
  function sharedPolyfills(shared, resolveClientUrl) {
363
- const self = globalThis;
416
+ const hostShared = getNamespace().hostSharedModules;
364
417
  const polyfill = {
365
- "next/dist/client/components/navigation": self.__remote_component_host_shared_modules__?.["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
418
+ "next/dist/client/components/navigation": hostShared["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
366
419
  useRouter() {
367
420
  return {
368
421
  push: (routerUrl) => {
@@ -393,7 +446,7 @@ function sharedPolyfills(shared, resolveClientUrl) {
393
446
  },
394
447
  __esModule: true
395
448
  })),
396
- "next/dist/client/app-dir/link": self.__remote_component_host_shared_modules__?.["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
449
+ "next/dist/client/app-dir/link": hostShared["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
397
450
  default: ({
398
451
  scroll: _,
399
452
  replace,
@@ -443,7 +496,7 @@ function sharedPolyfills(shared, resolveClientUrl) {
443
496
  },
444
497
  __esModule: true
445
498
  })),
446
- "next/dist/client/app-dir/form": self.__remote_component_host_shared_modules__?.["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
499
+ "next/dist/client/app-dir/form": hostShared["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
447
500
  default: () => {
448
501
  throw new Error("Next.js <Form> component not implemented");
449
502
  },
@@ -454,17 +507,17 @@ function sharedPolyfills(shared, resolveClientUrl) {
454
507
  // This gives us full next/image fidelity (fill, priority, srcSet, blur
455
508
  // placeholders, error handling) while routing image optimization through the
456
509
  // remote app's /_next/image endpoint.
457
- "next/dist/shared/lib/image-loader": self.__remote_component_host_shared_modules__?.["next/dist/shared/lib/image-loader"] ?? shared?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
510
+ "next/dist/shared/lib/image-loader": hostShared["next/dist/shared/lib/image-loader"] ?? shared?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
458
511
  default: createRemoteImageLoader(bundle, resolveClientUrl),
459
512
  __esModule: true
460
513
  })),
461
- "next/dist/client/script": self.__remote_component_host_shared_modules__?.["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
514
+ "next/dist/client/script": hostShared["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
462
515
  // TODO: implement <Script> component for non-Next.js host applications
463
516
  // do not throw an error for now
464
517
  default: () => null,
465
518
  __esModule: true
466
519
  })),
467
- "next/router": self.__remote_component_host_shared_modules__?.["next/router"] ?? shared?.["next/router"] ?? (() => (
520
+ "next/router": hostShared["next/router"] ?? shared?.["next/router"] ?? (() => (
468
521
  // TODO: incomplete implementation
469
522
  Promise.resolve({
470
523
  useRouter() {
@@ -500,6 +553,68 @@ function sharedPolyfills(shared, resolveClientUrl) {
500
553
  return polyfill;
501
554
  }
502
555
 
556
+ // src/host/shared/shared-module-resolver.ts
557
+ var CORE_REACT_PATH_MAP = {
558
+ react: "/react/index.js",
559
+ "react/jsx-dev-runtime": "/react/jsx-dev-runtime.js",
560
+ "react/jsx-runtime": "/react/jsx-runtime.js",
561
+ "react-dom": "/react-dom/index.js",
562
+ "react-dom/client": "/react-dom/client.js"
563
+ };
564
+ var VENDOR_SHARED = Object.fromEntries(
565
+ Object.entries(CORE_REACT_PATH_MAP).filter(([key]) => key !== "react-dom/client").map(([key, path]) => [key, `'${path}'`])
566
+ );
567
+ function buildCoreShared(userShared) {
568
+ return {
569
+ react: async () => (await import("react")).default,
570
+ "react-dom": async () => (await import("react-dom")).default,
571
+ "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
572
+ "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
573
+ "react-dom/client": async () => (await import("react-dom/client")).default,
574
+ ...userShared
575
+ };
576
+ }
577
+ function buildHostShared(userShared, resolveClientUrl, options) {
578
+ const self = globalThis;
579
+ const result = {
580
+ ...sharedPolyfills(userShared, resolveClientUrl),
581
+ ...self.__remote_component_host_shared_modules__,
582
+ ...userShared
583
+ };
584
+ if (options?.includeRemoteComponentShared) {
585
+ Object.assign(result, self.__remote_component_shared__);
586
+ }
587
+ return result;
588
+ }
589
+ async function buildWebpackResolve(hostShared, remoteShared, bundle, reactModules, callerTag = "SharedModuleResolver") {
590
+ const resolve = {
591
+ ...reactModules,
592
+ ...Object.entries(remoteShared).reduce(
593
+ (acc, [key, value]) => {
594
+ if (typeof hostShared[value] !== "undefined") {
595
+ acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
596
+ } else {
597
+ logDebug(
598
+ callerTag,
599
+ `Remote requests "${value}" but host doesn't provide it`
600
+ );
601
+ }
602
+ return acc;
603
+ },
604
+ {}
605
+ )
606
+ };
607
+ await Promise.all(
608
+ Object.entries(resolve).map(async ([key, value]) => {
609
+ if (typeof value === "function") {
610
+ resolve[key] = await value(bundle);
611
+ }
612
+ return Promise.resolve(value);
613
+ })
614
+ );
615
+ return resolve;
616
+ }
617
+
503
618
  // src/host/shared/state.ts
504
619
  function createHostState() {
505
620
  return {
@@ -526,8 +641,8 @@ function resolveNameFromSrc(src, defaultName) {
526
641
  return name || defaultName;
527
642
  }
528
643
 
529
- // src/runtime/html/apply-origin.ts
530
- var tagNames = [
644
+ // src/runtime/html/html-spec.ts
645
+ var ORIGIN_REWRITE_TAGS = [
531
646
  "img",
532
647
  "source",
533
648
  "video",
@@ -538,10 +653,37 @@ var tagNames = [
538
653
  "script",
539
654
  "link"
540
655
  ];
656
+ var ID_SUFFIX_RSC = "_rsc";
657
+ var ID_SUFFIX_SSR = "_ssr";
658
+ var ID_SUFFIX_SHARED = "_shared";
659
+ var DATA_BUNDLE = "data-bundle";
660
+ var DATA_ROUTE = "data-route";
661
+ var DATA_RUNTIME = "data-runtime";
662
+ var DATA_TYPE = "data-type";
663
+ var DATA_SRC = "data-src";
664
+ var DATA_REMOTE_COMPONENTS_SHARED = "data-remote-components-shared";
665
+ var TAG_REMOTE_COMPONENT = "remote-component";
666
+ var NEXT_DATA_ID = "__NEXT_DATA__";
667
+ var REMOTE_NEXT_DATA_ID = "__REMOTE_NEXT_DATA__";
668
+ var NEXT_CONTAINER_ID = "__next";
669
+
670
+ // src/runtime/html/rewrite-srcset.ts
671
+ function rewriteSrcset(srcset, base, resolve) {
672
+ return srcset.split(",").map((entry) => {
673
+ const [url, descriptor] = entry.trim().split(/\s+/);
674
+ if (!url)
675
+ return entry;
676
+ const absoluteUrl = new URL(url, base).href;
677
+ const resolvedUrl = resolve ? resolve(absoluteUrl) : absoluteUrl;
678
+ return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
679
+ }).join(", ");
680
+ }
681
+
682
+ // src/runtime/html/apply-origin.ts
541
683
  function applyOriginToNodes(doc, url, resolveClientUrl) {
542
684
  if (url.origin !== location.origin) {
543
685
  const nodes = doc.querySelectorAll(
544
- tagNames.map(
686
+ ORIGIN_REWRITE_TAGS.map(
545
687
  (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
546
688
  ).join(",")
547
689
  );
@@ -559,29 +701,17 @@ function applyOriginToNodes(doc, url, resolveClientUrl) {
559
701
  );
560
702
  }
561
703
  if (node.hasAttribute("srcset")) {
562
- const srcSet = node.getAttribute("srcset")?.split(",").map((entry) => {
563
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
564
- if (!urlPart)
565
- return entry;
566
- const absoluteUrl = new URL(urlPart, url).href;
567
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
568
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
569
- }).join(", ");
570
- if (srcSet) {
571
- node.setAttribute("srcset", srcSet);
704
+ const raw = node.getAttribute("srcset");
705
+ if (raw) {
706
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
707
+ node.setAttribute("srcset", rewriteSrcset(raw, url, resolve));
572
708
  }
573
709
  }
574
710
  if (node.hasAttribute("imagesrcset")) {
575
- const srcSet = node.getAttribute("imagesrcset")?.split(",").map((entry) => {
576
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
577
- if (!urlPart)
578
- return entry;
579
- const absoluteUrl = new URL(urlPart, url).href;
580
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
581
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
582
- }).join(", ");
583
- if (srcSet) {
584
- node.setAttribute("imagesrcset", srcSet);
711
+ const raw = node.getAttribute("imagesrcset");
712
+ if (raw) {
713
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
714
+ node.setAttribute("imagesrcset", rewriteSrcset(raw, url, resolve));
585
715
  }
586
716
  }
587
717
  });
@@ -622,26 +752,28 @@ function buildMetadata(attrs, url) {
622
752
 
623
753
  // src/runtime/html/parse-remote-html.ts
624
754
  function validateSingleComponent(doc, name, url) {
625
- 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}"]`)) {
755
+ if (doc.querySelectorAll(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`).length > 1 && !doc.querySelector(
756
+ `div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`
757
+ ) || doc.querySelectorAll(`${TAG_REMOTE_COMPONENT}:not([src])`).length > 1 && !doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]`)) {
626
758
  throw multipleRemoteComponentsError(url);
627
759
  }
628
760
  }
629
761
  function findComponentElement(doc, name) {
630
- 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])");
762
+ 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])`);
631
763
  }
632
764
  function parseNextData(doc) {
633
765
  return JSON.parse(
634
- (doc.querySelector("#__NEXT_DATA__") ?? doc.querySelector("#__REMOTE_NEXT_DATA__"))?.textContent ?? "null"
766
+ (doc.querySelector(`#${NEXT_DATA_ID}`) ?? doc.querySelector(`#${REMOTE_NEXT_DATA_ID}`))?.textContent ?? "null"
635
767
  );
636
768
  }
637
769
  function resolveComponentName(component, nextData, fallbackName) {
638
- const isRemoteComponent = component?.tagName.toLowerCase() === "remote-component";
639
- const name = component?.getAttribute("id")?.replace(/_ssr$/, "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
770
+ const isRemoteComponent = component?.tagName.toLowerCase() === TAG_REMOTE_COMPONENT;
771
+ const name = component?.getAttribute("id")?.replace(new RegExp(`${ID_SUFFIX_SSR}$`), "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
640
772
  return { name, isRemoteComponent };
641
773
  }
642
774
  function extractRemoteShared(doc, name, nextData) {
643
775
  const remoteSharedEl = doc.querySelector(
644
- `#${name}_shared[data-remote-components-shared]`
776
+ `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`
645
777
  );
646
778
  const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
647
779
  remoteSharedEl?.remove();
@@ -662,7 +794,7 @@ function extractLinks(doc, component) {
662
794
  function extractScripts(doc, component, isRemoteComponent) {
663
795
  return Array.from(
664
796
  (isRemoteComponent ? component : doc).querySelectorAll(
665
- "script[src],script[data-src]"
797
+ `script[src],script[${DATA_SRC}]`
666
798
  )
667
799
  );
668
800
  }
@@ -675,15 +807,15 @@ function parseRemoteComponentDocument(doc, name, url) {
675
807
  nextData,
676
808
  name
677
809
  );
678
- const rsc = doc.querySelector(`#${resolvedName}_rsc`);
810
+ const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);
679
811
  const metadata = buildMetadata(
680
812
  {
681
813
  name: resolvedName,
682
- bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle,
683
- route: component?.getAttribute("data-route") ?? nextData?.page,
684
- runtime: component?.getAttribute("data-runtime") ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
814
+ bundle: component?.getAttribute(DATA_BUNDLE) || nextData?.props.__REMOTE_COMPONENT__?.bundle,
815
+ route: component?.getAttribute(DATA_ROUTE) ?? nextData?.page,
816
+ runtime: component?.getAttribute(DATA_RUNTIME) ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
685
817
  id: component?.getAttribute("id"),
686
- type: component?.getAttribute("data-type")
818
+ type: component?.getAttribute(DATA_TYPE)
687
819
  },
688
820
  url
689
821
  );
@@ -772,13 +904,15 @@ function applySharedModules(bundle, resolve) {
772
904
  `Shared modules to resolve: ${Object.keys(resolve)}`
773
905
  );
774
906
  const self = globalThis;
775
- if (self.__remote_webpack_require__?.[bundle]) {
907
+ const scope = getScope(bundle);
908
+ const webpackBundle = scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];
909
+ if (webpackBundle) {
776
910
  const modulePaths = Object.keys(
777
- self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
911
+ self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {}
778
912
  );
779
913
  logDebug(
780
914
  "SharedModules",
781
- `Available module paths in __remote_webpack_require__[${bundle}]: ${modulePaths}`
915
+ `Available module paths for bundle "${bundle}": ${modulePaths}`
782
916
  );
783
917
  for (const [key, value] of Object.entries(resolve)) {
784
918
  const exactIds = modulePaths.filter((p) => p === key);
@@ -790,7 +924,6 @@ function applySharedModules(bundle, resolve) {
790
924
  );
791
925
  }
792
926
  for (const id of ids) {
793
- const webpackBundle = self.__remote_webpack_require__[bundle];
794
927
  if (webpackBundle.m) {
795
928
  const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
796
929
  if (resolvedId !== id) {
@@ -888,10 +1021,8 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
888
1021
  ];
889
1022
  const { default: Component } = componentLoader();
890
1023
  const { default: App } = appLoader();
891
- if (!self.__remote_next_css__) {
892
- self.__remote_next_css__ = {};
893
- }
894
- if (!self.__remote_next_css__[bundle]) {
1024
+ const cssCache = getNamespace().cssCache;
1025
+ if (!cssCache[bundle]) {
895
1026
  const cssRE = /\.s?css$/;
896
1027
  Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
897
1028
  self.__remote_webpack_require__?.[bundle]?.(id);
@@ -909,15 +1040,15 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
909
1040
  node.remove();
910
1041
  node = nextCss.previousSibling;
911
1042
  }
912
- self.__remote_next_css__[bundle] = elements;
1043
+ cssCache[bundle] = elements;
913
1044
  }
914
1045
  if (styleContainer) {
915
- const elements = self.__remote_next_css__[bundle];
1046
+ const elements = cssCache[bundle];
916
1047
  elements.forEach((el) => {
917
1048
  styleContainer.appendChild(el.cloneNode(true));
918
1049
  });
919
1050
  } else {
920
- const elements = self.__remote_next_css__[bundle];
1051
+ const elements = cssCache[bundle];
921
1052
  elements.forEach((el) => {
922
1053
  document.head.appendChild(el);
923
1054
  });
@@ -954,6 +1085,18 @@ function fixPayload(payload) {
954
1085
  }
955
1086
  }
956
1087
  }
1088
+ function buildRSCChunks(rscName, data) {
1089
+ const chunks = [];
1090
+ for (const chunk of data) {
1091
+ for (const line of chunk.split("\n")) {
1092
+ const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1093
+ if (match?.groups?.rsc) {
1094
+ chunks.push(JSON.parse(`"${match.groups.rsc}"`));
1095
+ }
1096
+ }
1097
+ }
1098
+ return chunks;
1099
+ }
957
1100
  function createRSCStream(rscName, data) {
958
1101
  return new import_web_streams_polyfill.ReadableStream({
959
1102
  type: "bytes",
@@ -961,16 +1104,11 @@ function createRSCStream(rscName, data) {
961
1104
  const encoder = new TextEncoder();
962
1105
  const self = globalThis;
963
1106
  if (data.length > 0) {
964
- data.forEach((chunk) => {
965
- const lines = chunk.split("\n");
966
- for (const line of lines) {
967
- const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
968
- if (match?.groups?.rsc) {
969
- self[rscName] = self[rscName] ?? [];
970
- self[rscName].push(JSON.parse(`"${match.groups.rsc}"`));
971
- }
972
- }
973
- });
1107
+ const parsed = buildRSCChunks(rscName, data);
1108
+ if (parsed.length > 0) {
1109
+ self[rscName] = self[rscName] ?? [];
1110
+ self[rscName].push(...parsed);
1111
+ }
974
1112
  }
975
1113
  const allChunks = (self[rscName] ?? [`0:[null]
976
1114
  `]).join("");
@@ -1000,12 +1138,38 @@ function createRSCStream(rscName, data) {
1000
1138
  });
1001
1139
  }
1002
1140
 
1141
+ // src/runtime/rsc-imports.ts
1142
+ async function importRSCClientBrowser() {
1143
+ try {
1144
+ return await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1145
+ } catch {
1146
+ const mod = await import("react-server-dom-webpack/client.browser");
1147
+ return mod.default ?? mod;
1148
+ }
1149
+ }
1150
+
1003
1151
  // src/runtime/turbopack/patterns.ts
1152
+ var MODULE_ID_PATTERN = '"[^"]+"|[0-9]+';
1153
+ function stripQuotes(value) {
1154
+ if (value.startsWith('"') && value.endsWith('"')) {
1155
+ return value.slice(1, -1);
1156
+ }
1157
+ return value;
1158
+ }
1159
+ function extractGroup(re, input, group) {
1160
+ const raw = re.exec(input)?.groups?.[group];
1161
+ return raw ? stripQuotes(raw) : void 0;
1162
+ }
1004
1163
  var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
1005
- var REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
1006
- var ASYNC_MODULE_LOADER_RE = /(?:__turbopack_context__|e)\.A\((?<asyncSharedModuleId>[0-9]+)\)/;
1007
- var ASYNC_MODULE_RESOLVE_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<inner>parentImport|e)=>Promise\.resolve\(\)\.then\(\(\)=>\k<inner>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
1008
- 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]+)\)\)\)\}/;
1164
+ var REMOTE_SHARED_ASSIGNMENT_RE = new RegExp(
1165
+ `\\.TURBOPACK_REMOTE_SHARED\\s*=\\s*await (?:__turbopack_context__|[a-z])\\.A\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1166
+ );
1167
+ var ASYNC_MODULE_LOADER_RE = new RegExp(
1168
+ `(?:__turbopack_context__|e)\\.A\\((?<asyncSharedModuleId>${MODULE_ID_PATTERN})\\)`
1169
+ );
1170
+ var ASYNC_MODULE_CALLBACK_RE = new RegExp(
1171
+ `(?:parentImport|[a-z])\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1172
+ );
1009
1173
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
1010
1174
 
1011
1175
  // src/runtime/turbopack/chunk-loader.ts
@@ -1015,6 +1179,7 @@ function loadChunkWithScope(scope, chunkId) {
1015
1179
  `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
1016
1180
  );
1017
1181
  const self = globalThis;
1182
+ const ns = getNamespace();
1018
1183
  const { bundle, path, prefix } = parseRemoteId(chunkId);
1019
1184
  const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
1020
1185
  if (remoteRuntime === RUNTIME_WEBPACK) {
@@ -1025,35 +1190,31 @@ function loadChunkWithScope(scope, chunkId) {
1025
1190
  if (url.endsWith(".css")) {
1026
1191
  return;
1027
1192
  }
1028
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1029
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
1030
- }
1031
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1032
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1193
+ if (ns.chunkCache[url]) {
1194
+ logDebug("ChunkLoader", `Cache hit for "${chunkId}" (url="${url}")`);
1195
+ return ns.chunkCache[url];
1033
1196
  }
1034
1197
  const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1035
1198
  if (resolvedUrl !== url) {
1036
1199
  logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1037
1200
  }
1038
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1039
- (resolve, reject) => {
1040
- fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1041
- const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1042
- if (hasTurbopack) {
1043
- return handleTurbopackChunk(code, scope, url);
1044
- }
1045
- }).then(resolve).catch((error) => {
1046
- const isProxied = isProxiedUrl(resolvedUrl);
1047
- if (isProxied) {
1048
- reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1049
- } else {
1050
- warnCrossOriginFetchError("ChunkLoader", url);
1051
- reject(error);
1052
- }
1053
- });
1054
- }
1055
- );
1056
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1201
+ ns.chunkCache[url] = new Promise((resolve, reject) => {
1202
+ fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1203
+ const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1204
+ if (hasTurbopack) {
1205
+ return handleTurbopackChunk(code, scope, url);
1206
+ }
1207
+ }).then(resolve).catch((error) => {
1208
+ const isProxied = isProxiedUrl(resolvedUrl);
1209
+ if (isProxied) {
1210
+ reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1211
+ } else {
1212
+ warnCrossOriginFetchError("ChunkLoader", url);
1213
+ reject(error);
1214
+ }
1215
+ });
1216
+ });
1217
+ return ns.chunkCache[url];
1057
1218
  }
1058
1219
  function createChunkDispatcher() {
1059
1220
  return function __chunk_dispatcher__(chunkId, scriptBundle) {
@@ -1102,19 +1263,39 @@ async function handleTurbopackChunk(code, scope, url) {
1102
1263
  `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1103
1264
  );
1104
1265
  if (!self[`TURBOPACK_${globalKey}`]) {
1105
- const chunkData = [];
1106
- const turbopackObject = {
1107
- push: (item) => {
1108
- if (Array.isArray(item)) {
1109
- chunkData.push(item);
1110
- } else {
1111
- chunkData.push([item]);
1266
+ const wrapPush = (target) => {
1267
+ const originalPush = target.push;
1268
+ if (typeof originalPush !== "function")
1269
+ return target;
1270
+ target.push = (...items) => {
1271
+ for (const item of items) {
1272
+ if (Array.isArray(item)) {
1273
+ for (const entry of item) {
1274
+ scope.turbopackModules.push(entry);
1275
+ }
1276
+ } else {
1277
+ scope.turbopackModules.push(item);
1278
+ }
1112
1279
  }
1113
- return chunkData.length;
1114
- },
1115
- __chunks__: chunkData
1280
+ return originalPush.apply(target, items);
1281
+ };
1282
+ return target;
1116
1283
  };
1117
- self[`TURBOPACK_${globalKey}`] = turbopackObject;
1284
+ const globalProp = `TURBOPACK_${globalKey}`;
1285
+ let currentValue = wrapPush([]);
1286
+ Object.defineProperty(self, globalProp, {
1287
+ get() {
1288
+ return currentValue;
1289
+ },
1290
+ set(newValue) {
1291
+ if (newValue && typeof newValue === "object") {
1292
+ wrapPush(newValue);
1293
+ }
1294
+ currentValue = newValue;
1295
+ },
1296
+ configurable: true,
1297
+ enumerable: true
1298
+ });
1118
1299
  }
1119
1300
  await new Promise((scriptResolve, scriptReject) => {
1120
1301
  const blob = new Blob([transformedCode], {
@@ -1166,13 +1347,13 @@ async function handleTurbopackChunk(code, scope, url) {
1166
1347
  // src/runtime/turbopack/shared-modules.ts
1167
1348
  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).";
1168
1349
  function getTurbopackModules(scope) {
1350
+ if (scope.turbopackModules.length > 0) {
1351
+ return scope.turbopackModules;
1352
+ }
1169
1353
  const self = globalThis;
1170
1354
  const raw = self[`TURBOPACK_${scope.globalKey}`];
1171
1355
  if (!raw)
1172
1356
  return void 0;
1173
- if (typeof raw === "object" && "__chunks__" in raw) {
1174
- return raw.__chunks__.flat();
1175
- }
1176
1357
  if (Array.isArray(raw)) {
1177
1358
  return raw.flat();
1178
1359
  }
@@ -1196,7 +1377,11 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1196
1377
  if (sharedModuleInitializerIndex > 0) {
1197
1378
  const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1198
1379
  const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1199
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1380
+ const sharedModuleId = extractGroup(
1381
+ REMOTE_SHARED_ASSIGNMENT_RE,
1382
+ sharedModuleInitializerCode,
1383
+ "sharedModuleId"
1384
+ );
1200
1385
  if (sharedModuleId) {
1201
1386
  const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1202
1387
  scope,
@@ -1254,20 +1439,22 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1254
1439
  }
1255
1440
  function extractSharedModuleIds(shared, scope) {
1256
1441
  return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1257
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1442
+ const asyncSharedModuleId = extractGroup(
1443
+ ASYNC_MODULE_LOADER_RE,
1444
+ value.toString(),
1445
+ "asyncSharedModuleId"
1446
+ );
1258
1447
  if (asyncSharedModuleId) {
1259
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1260
- let asyncSharedModule;
1261
- const turbopackModules = getTurbopackModules(scope) ?? [];
1262
- const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1263
- asyncSharedModuleIdNumber
1448
+ const asyncSharedModule = findModuleInit(
1449
+ getTurbopackModules(scope),
1450
+ asyncSharedModuleId
1264
1451
  );
1265
- if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1266
- asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1267
- }
1268
1452
  if (asyncSharedModule) {
1269
- const asyncSharedModuleCode = asyncSharedModule.toString();
1270
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1453
+ const sharedModuleId = extractGroup(
1454
+ ASYNC_MODULE_CALLBACK_RE,
1455
+ asyncSharedModule.toString(),
1456
+ "sharedModuleId"
1457
+ );
1271
1458
  acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1272
1459
  "__remote_shared_module_",
1273
1460
  ""
@@ -1358,9 +1545,17 @@ function findModuleInit(modules, moduleId) {
1358
1545
  if (idx >= 0) {
1359
1546
  return flat.slice(idx + 1).find((e) => typeof e === "function");
1360
1547
  }
1361
- return flat.find(
1362
- (e) => Boolean(e && typeof e === "object" && moduleId in e)
1363
- )?.[moduleId];
1548
+ for (const entry of flat) {
1549
+ if (!entry || typeof entry !== "object")
1550
+ continue;
1551
+ const obj = entry;
1552
+ if (moduleId in obj)
1553
+ return obj[moduleId];
1554
+ const prefixKey = Object.keys(obj).find((k) => k.startsWith(moduleId));
1555
+ if (prefixKey)
1556
+ return obj[prefixKey];
1557
+ }
1558
+ return void 0;
1364
1559
  }
1365
1560
  function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1366
1561
  const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
@@ -1439,7 +1634,10 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1439
1634
  }
1440
1635
  if (typeof mod !== "object" || mod === null) {
1441
1636
  mod = { default: mod };
1442
- } else if (!("default" in mod) && mod.toString() !== "[object Module]") {
1637
+ } else if (!("default" in mod) && // ES module namespace objects have a null prototype, so calling
1638
+ // mod.toString() directly throws. Use Object.prototype.toString
1639
+ // to safely detect them.
1640
+ Object.prototype.toString.call(mod) !== "[object Module]") {
1443
1641
  try {
1444
1642
  mod.default = mod;
1445
1643
  } catch {
@@ -1503,21 +1701,38 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1503
1701
  };
1504
1702
  }
1505
1703
 
1506
- // src/runtime/turbopack/webpack-runtime.ts
1507
- async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1704
+ // src/runtime/turbopack/remote-scope-setup.ts
1705
+ async function setupRemoteScope(runtime, scripts = [], url = new URL(location.href), bundle, resolveClientUrl) {
1508
1706
  const self = globalThis;
1707
+ const ns = getNamespace();
1509
1708
  const bundleName = bundle ?? "default";
1709
+ const existingScope = getScope(bundleName);
1710
+ if (existingScope && existingScope.url.origin === url.origin) {
1711
+ logDebug(
1712
+ "WebpackRuntime",
1713
+ `Reusing scope "${existingScope.scopedName}" (turbopackModules=${existingScope.turbopackModules.length})`
1714
+ );
1715
+ existingScope.resolveClientUrl = resolveClientUrl;
1716
+ if (runtime === RUNTIME_TURBOPACK) {
1717
+ await Promise.allSettled(
1718
+ scripts.map(
1719
+ (script) => script.src ? loadChunkWithScope(existingScope, script.src) : Promise.resolve(void 0)
1720
+ )
1721
+ );
1722
+ }
1723
+ return existingScope;
1724
+ }
1510
1725
  const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1511
1726
  registerScope(scope);
1512
- if (!self.__remote_bundle_url__) {
1513
- self.__remote_bundle_url__ = {};
1727
+ if (runtime === RUNTIME_WEBPACK && self.__remote_webpack_require__?.[bundleName]) {
1728
+ scope.webpackRequire = self.__remote_webpack_require__[bundleName];
1514
1729
  }
1515
- self.__remote_bundle_url__[bundleName] = url;
1730
+ ns.bundleUrls[bundleName] = url;
1516
1731
  if (scope.scopedName !== bundleName) {
1517
- self.__remote_bundle_url__[scope.scopedName] = url;
1732
+ ns.bundleUrls[scope.scopedName] = url;
1518
1733
  }
1519
1734
  self.__webpack_get_script_filename__ = () => null;
1520
- const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1735
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || ns.dispatcherRuntime !== "turbopack";
1521
1736
  if (willCreateDispatchers) {
1522
1737
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1523
1738
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
@@ -1525,6 +1740,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1525
1740
  }
1526
1741
  self.__webpack_chunk_load__ = createChunkDispatcher();
1527
1742
  self.__webpack_require__ = createModuleDispatcher(runtime);
1743
+ ns.dispatcherRuntime = runtime;
1528
1744
  self.__webpack_require_type__ = runtime;
1529
1745
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1530
1746
  self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
@@ -1552,15 +1768,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1552
1768
  }
1553
1769
  }
1554
1770
  }
1555
- const coreShared = {
1556
- react: async () => (await import("react")).default,
1557
- "react-dom": async () => (await import("react-dom")).default,
1558
- "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
1559
- "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
1560
- "react-dom/client": async () => (await import("react-dom/client")).default,
1561
- ...shared
1562
- };
1563
- await initializeSharedModules(scope, coreShared, remoteShared);
1771
+ return scope;
1564
1772
  }
1565
1773
  function createModuleDispatcher(runtime) {
1566
1774
  return (id) => {
@@ -1577,6 +1785,9 @@ function createModuleDispatcher(runtime) {
1577
1785
  );
1578
1786
  try {
1579
1787
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1788
+ const scope2 = getScope(bundle);
1789
+ if (scope2?.webpackRequire)
1790
+ return scope2.webpackRequire(moduleId);
1580
1791
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1581
1792
  }
1582
1793
  const scope = getScope(bundleName);
@@ -1694,44 +1905,33 @@ async function loadRemoteComponent({
1694
1905
  "ComponentLoader",
1695
1906
  `Remote shared modules requested: ${JSON.stringify(remoteShared)}`
1696
1907
  );
1697
- await setupWebpackRuntime(
1908
+ const scope = await setupRemoteScope(
1698
1909
  runtime,
1699
1910
  scripts,
1700
1911
  url,
1701
1912
  bundle,
1702
- hostShared,
1703
- remoteShared,
1704
1913
  resolveClientUrl
1705
1914
  );
1915
+ if (runtime === "turbopack") {
1916
+ await initializeSharedModules(
1917
+ scope,
1918
+ buildCoreShared(hostShared),
1919
+ remoteShared
1920
+ );
1921
+ }
1706
1922
  if (bundle) {
1707
- const resolve = {
1708
- "/react/index.js": React,
1709
- "/react/jsx-dev-runtime.js": JSXDevRuntime,
1710
- "/react/jsx-runtime.js": JSXRuntime,
1711
- "/react-dom/index.js": ReactDOM,
1712
- "/react-dom/client.js": ReactDOMClient,
1713
- ...Object.entries(remoteShared).reduce(
1714
- (acc, [key, value]) => {
1715
- if (typeof hostShared[value] !== "undefined") {
1716
- acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
1717
- } else {
1718
- logDebug(
1719
- "ComponentLoader",
1720
- `Remote requests "${value}" but host doesn't provide it`
1721
- );
1722
- }
1723
- return acc;
1724
- },
1725
- {}
1726
- )
1727
- };
1728
- await Promise.all(
1729
- Object.entries(resolve).map(async ([key, value]) => {
1730
- if (typeof value === "function") {
1731
- resolve[key] = await value(bundle);
1732
- }
1733
- return Promise.resolve(value);
1734
- })
1923
+ const resolve = await buildWebpackResolve(
1924
+ hostShared,
1925
+ remoteShared,
1926
+ bundle,
1927
+ {
1928
+ "/react/index.js": React,
1929
+ "/react/jsx-dev-runtime.js": JSXDevRuntime,
1930
+ "/react/jsx-runtime.js": JSXRuntime,
1931
+ "/react-dom/index.js": ReactDOM,
1932
+ "/react-dom/client.js": ReactDOMClient
1933
+ },
1934
+ "ComponentLoader"
1735
1935
  );
1736
1936
  applySharedModules(bundle, resolve);
1737
1937
  } else {
@@ -1759,19 +1959,8 @@ async function loadRemoteComponent({
1759
1959
  };
1760
1960
  }
1761
1961
  }
1762
- async function importCreateFromReadableStream() {
1763
- try {
1764
- const { createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1765
- return createFromReadableStream;
1766
- } catch {
1767
- const {
1768
- default: { createFromReadableStream }
1769
- } = await import("react-server-dom-webpack/client.browser");
1770
- return createFromReadableStream;
1771
- }
1772
- }
1773
1962
  async function loadRSCComponent(rscName, data) {
1774
- const createFromReadableStream = await importCreateFromReadableStream();
1963
+ const { createFromReadableStream } = await importRSCClientBrowser();
1775
1964
  if (typeof createFromReadableStream !== "function") {
1776
1965
  throw new RemoteComponentsError(
1777
1966
  'Failed to import "react-server-dom-webpack". Is Next.js installed correctly?'
@@ -1835,10 +2024,9 @@ async function importViaCallback(absoluteSrc, resolveClientUrl) {
1835
2024
  URL.revokeObjectURL(moduleBlobUrl);
1836
2025
  URL.revokeObjectURL(wrapperBlobUrl);
1837
2026
  }
1838
- const registry = globalThis.__rc_module_registry__;
1839
- const mod = registry?.[absoluteSrc] ?? {};
1840
- if (registry)
1841
- delete registry[absoluteSrc];
2027
+ const registry = getNamespace().moduleRegistry;
2028
+ const mod = registry[absoluteSrc] ?? {};
2029
+ delete registry[absoluteSrc];
1842
2030
  return mod;
1843
2031
  }
1844
2032
  async function importDirectly(absoluteSrc) {
@@ -1868,12 +2056,12 @@ function resolveScriptSrc(script, url) {
1868
2056
  return rawSrc;
1869
2057
  }
1870
2058
  async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1871
- const self = globalThis;
1872
- if (self.__remote_script_entrypoint_mount__?.[url.href]) {
1873
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
2059
+ const ns = getNamespace();
2060
+ if (ns.mountFns[url.href]) {
2061
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1874
2062
  }
1875
- if (self.__remote_script_entrypoint_unmount__?.[url.href]) {
1876
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
2063
+ if (ns.unmountFns[url.href]) {
2064
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1877
2065
  }
1878
2066
  const mountUnmountSets = await Promise.all(
1879
2067
  scripts.map(async (script) => {
@@ -1885,25 +2073,19 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1885
2073
  URL.revokeObjectURL(src);
1886
2074
  }
1887
2075
  if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
1888
- if (!self.__remote_script_entrypoint_mount__) {
1889
- self.__remote_script_entrypoint_mount__ = {};
1890
- }
1891
- if (!self.__remote_script_entrypoint_mount__[url.href]) {
1892
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
2076
+ if (!ns.mountFns[url.href]) {
2077
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1893
2078
  }
1894
- self.__remote_script_entrypoint_mount__[url.href]?.add(
2079
+ ns.mountFns[url.href]?.add(
1895
2080
  mod.mount || mod.default?.mount || (() => {
1896
2081
  })
1897
2082
  );
1898
2083
  }
1899
2084
  if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
1900
- if (!self.__remote_script_entrypoint_unmount__) {
1901
- self.__remote_script_entrypoint_unmount__ = {};
2085
+ if (!ns.unmountFns[url.href]) {
2086
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1902
2087
  }
1903
- if (!self.__remote_script_entrypoint_unmount__[url.href]) {
1904
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
1905
- }
1906
- self.__remote_script_entrypoint_unmount__[url.href]?.add(
2088
+ ns.unmountFns[url.href]?.add(
1907
2089
  mod.unmount || mod.default?.unmount || (() => {
1908
2090
  })
1909
2091
  );
@@ -1986,27 +2168,25 @@ function useShadowRoot({
1986
2168
  }) {
1987
2169
  const shadowRootContainerRef = (0, import_react2.useRef)(null);
1988
2170
  const [shadowRoot, setShadowRoot] = (0, import_react2.useState)(() => {
1989
- const self = globalThis;
1990
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2171
+ const shadowRoots = getNamespace().shadowRoots;
1991
2172
  const ssrShadowRoot = typeof document !== "undefined" ? document.querySelector(
1992
2173
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
1993
- )?.shadowRoot ?? self[shadowRootKey] ?? null : null;
1994
- self[shadowRootKey] = null;
2174
+ )?.shadowRoot ?? shadowRoots[keySuffix] ?? null : null;
2175
+ shadowRoots[keySuffix] = null;
1995
2176
  return ssrShadowRoot;
1996
2177
  });
1997
2178
  (0, import_react2.useLayoutEffect)(() => {
2179
+ const shadowRoots = getNamespace().shadowRoots;
1998
2180
  if (isolate !== false && typeof document !== "undefined" && (!shadowRoot || !shadowRoot.isConnected)) {
1999
- const self = globalThis;
2000
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2001
2181
  let shadowRootElement = null;
2002
2182
  const element = document.querySelector(
2003
2183
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
2004
2184
  );
2005
- shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;
2185
+ shadowRootElement = shadowRoots[keySuffix] ?? element?.shadowRoot ?? null;
2006
2186
  if (!shadowRootElement && element) {
2007
2187
  try {
2008
2188
  shadowRootElement = element.attachShadow({ mode });
2009
- self[shadowRootKey] = shadowRootElement;
2189
+ shadowRoots[keySuffix] = shadowRootElement;
2010
2190
  } catch {
2011
2191
  }
2012
2192
  }
@@ -2017,9 +2197,7 @@ function useShadowRoot({
2017
2197
  setShadowRoot(shadowRootElement);
2018
2198
  }
2019
2199
  } else if (isolate === false && shadowRoot) {
2020
- const self = globalThis;
2021
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2022
- self[shadowRootKey] = null;
2200
+ shadowRoots[keySuffix] = null;
2023
2201
  setShadowRoot(null);
2024
2202
  }
2025
2203
  }, [isolate, shadowRoot, mode, keySuffix]);
@@ -2118,9 +2296,8 @@ function ConsumeRemoteComponent({
2118
2296
  const prevRemoteComponentContainerRef = (0, import_react3.useRef)(null);
2119
2297
  const unmountRef = (0, import_react3.useRef)(null);
2120
2298
  (0, import_react3.useLayoutEffect)(() => {
2121
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2122
2299
  return () => {
2123
- delete globalThis[shadowRootKey];
2300
+ delete getNamespace().shadowRoots[keySuffix];
2124
2301
  };
2125
2302
  }, [keySuffix]);
2126
2303
  (0, import_react3.useLayoutEffect)(() => {
@@ -2213,9 +2390,8 @@ function ConsumeRemoteComponent({
2213
2390
  if (shadowRoot) {
2214
2391
  shadowRoot.innerHTML = "";
2215
2392
  }
2216
- const self = globalThis;
2217
2393
  const prevUrl = hostStateRef.current.prevUrl;
2218
- if (prevUrl && self.__remote_script_entrypoint_unmount__?.[prevUrl.href]) {
2394
+ if (prevUrl && getNamespace().unmountFns[prevUrl.href]) {
2219
2395
  const unmountPromises = Promise.all(
2220
2396
  Array.from(unmountRef.current ?? []).map(
2221
2397
  async (unmount) => unmount(
@@ -2404,10 +2580,7 @@ function ConsumeRemoteComponent({
2404
2580
  ).href
2405
2581
  };
2406
2582
  }),
2407
- shared: {
2408
- ...sharedPolyfills(userShared, resolveClientUrl),
2409
- ...userShared
2410
- },
2583
+ shared: buildHostShared(userShared, resolveClientUrl),
2411
2584
  remoteShared,
2412
2585
  container: shadowRoot,
2413
2586
  resolveClientUrl
@@ -2539,8 +2712,10 @@ function ConsumeRemoteComponent({
2539
2712
  alt="" decoding="async" style="display:none"
2540
2713
  src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
2541
2714
  onload="(function(el){
2715
+ // Capture the shadow root during SSR hydration so the client-side
2716
+ // useShadowRoot hook can find it.
2542
2717
  const root = el.getRootNode();
2543
- globalThis.__remote_components_shadowroot_${keySuffix} = root;
2718
+ globalThis.__remote_components_shadowroot_${keySuffix}=root;
2544
2719
  el.parentElement.remove();
2545
2720
  })(this)"
2546
2721
  />`