remote-components 0.3.1 → 0.3.3

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 (131) hide show
  1. package/dist/config/nextjs.cjs +36 -25
  2. package/dist/config/nextjs.cjs.map +1 -1
  3. package/dist/config/nextjs.js +30 -19
  4. package/dist/config/nextjs.js.map +1 -1
  5. package/dist/host/defaults/app.cjs +2 -5
  6. package/dist/host/defaults/app.cjs.map +1 -1
  7. package/dist/host/defaults/app.d.ts +1 -3
  8. package/dist/host/defaults/app.js +1 -4
  9. package/dist/host/defaults/app.js.map +1 -1
  10. package/dist/host/defaults/pages.cjs +2 -5
  11. package/dist/host/defaults/pages.cjs.map +1 -1
  12. package/dist/host/defaults/pages.d.ts +1 -3
  13. package/dist/host/defaults/pages.js +1 -4
  14. package/dist/host/defaults/pages.js.map +1 -1
  15. package/dist/host/defaults/shared.cjs +32 -0
  16. package/dist/host/defaults/shared.cjs.map +1 -0
  17. package/dist/host/defaults/shared.d.ts +3 -0
  18. package/dist/host/defaults/shared.js +8 -0
  19. package/dist/host/defaults/shared.js.map +1 -0
  20. package/dist/host/html.cjs +390 -357
  21. package/dist/host/html.cjs.map +1 -1
  22. package/dist/host/html.js +390 -357
  23. package/dist/host/html.js.map +1 -1
  24. package/dist/host/nextjs/app/client-only.cjs +477 -453
  25. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  26. package/dist/host/nextjs/app/client-only.js +485 -461
  27. package/dist/host/nextjs/app/client-only.js.map +1 -1
  28. package/dist/host/react.cjs +382 -367
  29. package/dist/host/react.cjs.map +1 -1
  30. package/dist/host/react.js +382 -367
  31. package/dist/host/react.js.map +1 -1
  32. package/dist/internal/host/nextjs/app-client.cjs +2 -19
  33. package/dist/internal/host/nextjs/app-client.cjs.map +1 -1
  34. package/dist/internal/host/nextjs/app-client.js +1 -8
  35. package/dist/internal/host/nextjs/app-client.js.map +1 -1
  36. package/dist/internal/host/nextjs/image-shared.cjs +2 -2
  37. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  38. package/dist/internal/host/nextjs/image-shared.js +2 -2
  39. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  40. package/dist/internal/host/nextjs/shared-import.cjs +46 -0
  41. package/dist/internal/host/nextjs/shared-import.cjs.map +1 -0
  42. package/dist/internal/host/nextjs/shared-import.d.ts +3 -0
  43. package/dist/internal/host/nextjs/shared-import.js +12 -0
  44. package/dist/internal/host/nextjs/shared-import.js.map +1 -0
  45. package/dist/internal/host/server/fetch-remote-component.cjs +20 -1
  46. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  47. package/dist/internal/host/server/fetch-remote-component.js +20 -1
  48. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  49. package/dist/internal/host/shared/remote-image-loader.cjs +2 -5
  50. package/dist/internal/host/shared/remote-image-loader.cjs.map +1 -1
  51. package/dist/internal/host/shared/remote-image-loader.js +2 -5
  52. package/dist/internal/host/shared/remote-image-loader.js.map +1 -1
  53. package/dist/internal/runtime/loaders/script-loader.cjs +7 -0
  54. package/dist/internal/runtime/loaders/script-loader.cjs.map +1 -1
  55. package/dist/internal/runtime/loaders/script-loader.js +7 -0
  56. package/dist/internal/runtime/loaders/script-loader.js.map +1 -1
  57. package/dist/internal/runtime/turbopack/chunk-loader.cjs +76 -126
  58. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  59. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +22 -7
  60. package/dist/internal/runtime/turbopack/chunk-loader.js +85 -131
  61. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  62. package/dist/internal/runtime/turbopack/module.cjs +53 -65
  63. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  64. package/dist/internal/runtime/turbopack/module.d.ts +14 -11
  65. package/dist/internal/runtime/turbopack/module.js +51 -64
  66. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  67. package/dist/internal/runtime/turbopack/remote-scope.cjs +101 -0
  68. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -0
  69. package/dist/internal/runtime/turbopack/remote-scope.d.ts +55 -0
  70. package/dist/internal/runtime/turbopack/remote-scope.js +73 -0
  71. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -0
  72. package/dist/internal/runtime/turbopack/shared-modules.cjs +64 -56
  73. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  74. package/dist/internal/runtime/turbopack/shared-modules.d.ts +13 -4
  75. package/dist/internal/runtime/turbopack/shared-modules.js +64 -57
  76. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  77. package/dist/internal/runtime/turbopack/webpack-runtime.cjs +39 -29
  78. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +1 -1
  79. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +5 -2
  80. package/dist/internal/runtime/turbopack/webpack-runtime.js +42 -32
  81. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +1 -1
  82. package/dist/internal/runtime/types.cjs.map +1 -1
  83. package/dist/internal/runtime/types.d.ts +4 -3
  84. package/dist/internal/utils/logger.cjs.map +1 -1
  85. package/dist/internal/utils/logger.d.ts +1 -1
  86. package/dist/internal/utils/logger.js.map +1 -1
  87. package/dist/internal/utils/project-id-env.cjs +31 -0
  88. package/dist/internal/utils/project-id-env.cjs.map +1 -0
  89. package/dist/internal/utils/project-id-env.d.ts +7 -0
  90. package/dist/internal/utils/project-id-env.js +7 -0
  91. package/dist/internal/utils/project-id-env.js.map +1 -0
  92. package/dist/internal/utils/project-id.cjs +46 -0
  93. package/dist/internal/utils/project-id.cjs.map +1 -0
  94. package/dist/internal/utils/project-id.d.ts +8 -0
  95. package/dist/internal/utils/project-id.js +22 -0
  96. package/dist/internal/utils/project-id.js.map +1 -0
  97. package/dist/internal/utils.cjs +5 -0
  98. package/dist/internal/utils.cjs.map +1 -1
  99. package/dist/internal/utils.d.ts +15 -1
  100. package/dist/internal/utils.js +4 -0
  101. package/dist/internal/utils.js.map +1 -1
  102. package/dist/remote/defaults/app.cjs +2 -5
  103. package/dist/remote/defaults/app.cjs.map +1 -1
  104. package/dist/remote/defaults/app.d.ts +1 -3
  105. package/dist/remote/defaults/app.js +1 -4
  106. package/dist/remote/defaults/app.js.map +1 -1
  107. package/dist/remote/defaults/pages.cjs +2 -5
  108. package/dist/remote/defaults/pages.cjs.map +1 -1
  109. package/dist/remote/defaults/pages.d.ts +1 -3
  110. package/dist/remote/defaults/pages.js +1 -4
  111. package/dist/remote/defaults/pages.js.map +1 -1
  112. package/dist/{internal/host/shared/resolved-data.cjs → remote/defaults/shared.cjs} +18 -3
  113. package/dist/remote/defaults/shared.cjs.map +1 -0
  114. package/dist/remote/defaults/shared.d.ts +3 -0
  115. package/dist/remote/defaults/shared.js +8 -0
  116. package/dist/remote/defaults/shared.js.map +1 -0
  117. package/dist/remote/html.cjs.map +1 -1
  118. package/dist/remote/html.js.map +1 -1
  119. package/dist/remote/nextjs/app.cjs +2 -1
  120. package/dist/remote/nextjs/app.cjs.map +1 -1
  121. package/dist/remote/nextjs/app.js +2 -1
  122. package/dist/remote/nextjs/app.js.map +1 -1
  123. package/dist/remote/nextjs/pages.cjs +2 -1
  124. package/dist/remote/nextjs/pages.cjs.map +1 -1
  125. package/dist/remote/nextjs/pages.js +2 -1
  126. package/dist/remote/nextjs/pages.js.map +1 -1
  127. package/package.json +1 -1
  128. package/dist/internal/host/shared/resolved-data.cjs.map +0 -1
  129. package/dist/internal/host/shared/resolved-data.d.ts +0 -48
  130. package/dist/internal/host/shared/resolved-data.js +0 -1
  131. package/dist/internal/host/shared/resolved-data.js.map +0 -1
package/dist/host/html.js CHANGED
@@ -191,6 +191,9 @@ var init_logger = __esm({
191
191
  function escapeString(str) {
192
192
  return str.replace(/[^a-z0-9]/g, "_");
193
193
  }
194
+ function computeScopedName(name, options) {
195
+ return options.isCrossOrigin ? `${name}_${escapeString(options.remoteHost.toLowerCase())}` : name;
196
+ }
194
197
  var init_utils = __esm({
195
198
  "src/utils/index.ts"() {
196
199
  "use strict";
@@ -402,11 +405,93 @@ var init_next_client_pages_loader = __esm({
402
405
  }
403
406
  });
404
407
 
405
- // src/host/shared/remote-image-loader.ts
406
- function getRemoteBundleOrigin(bundle) {
408
+ // src/runtime/patterns.ts
409
+ function collapseDoubleSlashes(path) {
410
+ return path.replace(DOUBLE_SLASH_RE, "/");
411
+ }
412
+ var REMOTE_COMPONENT_REGEX, NEXT_BUNDLE_PATH_RE, DOUBLE_SLASH_RE;
413
+ var init_patterns = __esm({
414
+ "src/runtime/patterns.ts"() {
415
+ "use strict";
416
+ REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
417
+ NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
418
+ DOUBLE_SLASH_RE = /(?<!:)\/\//g;
419
+ }
420
+ });
421
+
422
+ // src/runtime/turbopack/remote-scope.ts
423
+ function getRegistry() {
407
424
  const self = globalThis;
408
- return self.__remote_bundle_url__?.[bundle]?.origin ?? "";
425
+ if (!self.__remote_component_scopes__) {
426
+ self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
427
+ }
428
+ return self.__remote_component_scopes__;
429
+ }
430
+ function createScope(name, url, runtime, resolveClientUrl) {
431
+ const isCrossOrigin = url.origin !== location.origin;
432
+ const scopedName = computeScopedName(name, {
433
+ remoteHost: url.host,
434
+ isCrossOrigin
435
+ });
436
+ const globalKey = getBundleKey(scopedName);
437
+ return {
438
+ name,
439
+ scopedName,
440
+ globalKey,
441
+ url,
442
+ runtime,
443
+ resolveClientUrl,
444
+ moduleCache: {},
445
+ sharedModules: {},
446
+ moduleGlobal: {}
447
+ };
409
448
  }
449
+ function registerScope(scope) {
450
+ const registry = getRegistry();
451
+ registry.set(scope.scopedName, scope);
452
+ if (scope.scopedName !== scope.name) {
453
+ const existing = registry.get(scope.name);
454
+ if (existing && existing.scopedName !== scope.scopedName) {
455
+ logWarn(
456
+ "RemoteScope",
457
+ `Plain name "${scope.name}" already registered by scope "${existing.scopedName}" \u2014 overwriting with "${scope.scopedName}". Static hosts will only resolve the latest one.`
458
+ );
459
+ }
460
+ registry.set(scope.name, scope);
461
+ }
462
+ logDebug(
463
+ "RemoteScope",
464
+ `Registered scope "${scope.scopedName}" (${registry.size} total)`
465
+ );
466
+ }
467
+ function getScope(name) {
468
+ return getRegistry().get(name);
469
+ }
470
+ function formatRemoteId(scope, path) {
471
+ return `[${scope.scopedName}] ${path}`;
472
+ }
473
+ function parseRemoteId(id) {
474
+ const groups = REMOTE_COMPONENT_REGEX.exec(id)?.groups;
475
+ if (groups?.bundle && groups.id) {
476
+ return {
477
+ bundle: groups.bundle,
478
+ path: groups.id,
479
+ prefix: groups.prefix ?? ""
480
+ };
481
+ }
482
+ return { bundle: "default", path: id, prefix: "" };
483
+ }
484
+ var init_remote_scope = __esm({
485
+ "src/runtime/turbopack/remote-scope.ts"() {
486
+ "use strict";
487
+ init_constants2();
488
+ init_patterns();
489
+ init_utils();
490
+ init_logger();
491
+ }
492
+ });
493
+
494
+ // src/host/shared/remote-image-loader.ts
410
495
  function createRemoteImageLoader(bundle, resolveClientUrl) {
411
496
  const loader = Object.assign(
412
497
  ({
@@ -416,7 +501,7 @@ function createRemoteImageLoader(bundle, resolveClientUrl) {
416
501
  quality
417
502
  }) => {
418
503
  const q = quality ?? 75;
419
- const remoteOrigin = getRemoteBundleOrigin(bundle);
504
+ const remoteOrigin = getScope(bundle)?.url.origin ?? "";
420
505
  const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;
421
506
  const basePath = isCrossOrigin ? `${remoteOrigin}${config.path ?? "/_next/image"}` : config.path ?? `${remoteOrigin}/_next/image`;
422
507
  const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;
@@ -431,6 +516,7 @@ function createRemoteImageLoader(bundle, resolveClientUrl) {
431
516
  var init_remote_image_loader = __esm({
432
517
  "src/host/shared/remote-image-loader.ts"() {
433
518
  "use strict";
519
+ init_remote_scope();
434
520
  }
435
521
  });
436
522
 
@@ -584,16 +670,6 @@ var init_polyfill = __esm({
584
670
  }
585
671
  });
586
672
 
587
- // src/runtime/patterns.ts
588
- var REMOTE_COMPONENT_REGEX, NEXT_BUNDLE_PATH_RE;
589
- var init_patterns = __esm({
590
- "src/runtime/patterns.ts"() {
591
- "use strict";
592
- REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
593
- NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
594
- }
595
- });
596
-
597
673
  // src/runtime/loaders/script-loader.ts
598
674
  async function loadScripts(scripts, resolveClientUrl) {
599
675
  await Promise.all(
@@ -605,6 +681,13 @@ async function loadScripts(scripts, resolveClientUrl) {
605
681
  location.origin
606
682
  ).href;
607
683
  const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;
684
+ const alreadyLoaded = Array.from(
685
+ document.querySelectorAll("script[src]")
686
+ ).some((s) => s.src === resolvedSrc);
687
+ if (alreadyLoaded) {
688
+ resolve();
689
+ return;
690
+ }
608
691
  const newScript = document.createElement("script");
609
692
  newScript.onload = () => resolve();
610
693
  newScript.onerror = () => {
@@ -752,62 +835,39 @@ var init_patterns2 = __esm({
752
835
  });
753
836
 
754
837
  // src/runtime/turbopack/chunk-loader.ts
755
- function createChunkLoader(runtime, resolveClientUrl) {
756
- return function __turbopack_chunk_load__(chunkId, scriptBundle) {
757
- logDebug("ChunkLoader", `Loading chunk: "${chunkId}"`);
758
- const self = globalThis;
759
- const {
760
- bundle,
761
- id: path,
762
- prefix
763
- } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {
764
- bundle: scriptBundle ?? "",
765
- id: chunkId
766
- };
767
- logDebug(
768
- "ChunkLoader",
769
- `Parsed chunk - bundle: "${bundle}", path: "${path}", prefix: "${prefix}"`
770
- );
771
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
772
- logDebug("ChunkLoader", `Remote runtime: "${remoteRuntime}"`);
773
- if (remoteRuntime === RUNTIME_WEBPACK) {
774
- logDebug("ChunkLoader", "Skipping chunk load - webpack runtime detected");
775
- return Promise.resolve(void 0);
776
- }
777
- const url = new URL(
778
- path ? `${prefix ?? ""}${path}`.replace(
779
- /(?<char>[^:])(?<double>\/\/)/g,
780
- "$1/"
781
- ) : "/",
782
- self.__remote_bundle_url__?.[bundle ?? "default"] ?? new URL(location.origin)
783
- ).href;
784
- if (url.endsWith(".css")) {
785
- logDebug("ChunkLoader", `Skipping CSS file: "${url}"`);
786
- return;
787
- }
788
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
789
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
790
- }
791
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
792
- logDebug("ChunkLoader", `Returning cached promise for: "${url}"`);
793
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
794
- }
795
- const resolvedUrl = resolveClientUrl?.(url) ?? url;
796
- logDebug("ChunkLoader", `Fetching chunk from: "${resolvedUrl}"`);
797
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise((resolve, reject) => {
838
+ function loadChunkWithScope(scope, chunkId) {
839
+ logDebug(
840
+ "ChunkLoader",
841
+ `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
842
+ );
843
+ const self = globalThis;
844
+ const { bundle, path, prefix } = parseRemoteId(chunkId);
845
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
846
+ if (remoteRuntime === RUNTIME_WEBPACK) {
847
+ return Promise.resolve(void 0);
848
+ }
849
+ const rawPath = path ? collapseDoubleSlashes(`${prefix}${path}`) : "/";
850
+ const url = new URL(rawPath, scope.url).href;
851
+ if (url.endsWith(".css")) {
852
+ return;
853
+ }
854
+ if (!self.__remote_components_turbopack_chunk_loader_promise__) {
855
+ self.__remote_components_turbopack_chunk_loader_promise__ = {};
856
+ }
857
+ if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
858
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
859
+ }
860
+ const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
861
+ if (resolvedUrl !== url) {
862
+ logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
863
+ }
864
+ self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
865
+ (resolve, reject) => {
798
866
  fetch(resolvedUrl).then((res) => res.text()).then((code) => {
799
867
  const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
800
868
  if (hasTurbopack) {
801
- return handleTurbopackChunk(code, bundle ?? "", url);
869
+ return handleTurbopackChunk(code, scope, url);
802
870
  }
803
- logDebug(
804
- "ChunkLoader",
805
- `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: "${url}"`
806
- );
807
- logDebug(
808
- "ChunkLoader",
809
- `First 500 chars of chunk: ${code.slice(0, 500)}`
810
- );
811
871
  }).then(resolve).catch((error) => {
812
872
  const isProxied = isProxiedUrl(resolvedUrl);
813
873
  if (isProxied) {
@@ -817,17 +877,29 @@ function createChunkLoader(runtime, resolveClientUrl) {
817
877
  reject(error);
818
878
  }
819
879
  });
820
- });
821
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
880
+ }
881
+ );
882
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
883
+ }
884
+ function createChunkDispatcher() {
885
+ return function __chunk_dispatcher__(chunkId, scriptBundle) {
886
+ logDebug("ChunkDispatcher", `Dispatching chunk: "${chunkId}"`);
887
+ const { bundle } = parseRemoteId(chunkId);
888
+ const bundleName = bundle || scriptBundle || "default";
889
+ const scope = getScope(bundleName);
890
+ logDebug(
891
+ "ChunkDispatcher",
892
+ `Scope resolution: bundle="${bundleName}", scope=${scope?.scopedName ?? "null"}`
893
+ );
894
+ if (!scope) {
895
+ logWarn("ChunkDispatcher", `No scope found for bundle "${bundleName}"`);
896
+ return Promise.resolve(void 0);
897
+ }
898
+ return loadChunkWithScope(scope, chunkId);
822
899
  };
823
900
  }
824
- async function handleTurbopackChunk(code, bundle, url) {
825
- logDebug(
826
- "ChunkLoader",
827
- `Handling Turbopack chunk - bundle: "${bundle}", url: "${url}"`
828
- );
901
+ async function handleTurbopackChunk(code, scope, url) {
829
902
  if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
830
- logDebug("ChunkLoader", `Skipping worker chunk: "${url}"`);
831
903
  const preloadLinks = document.querySelectorAll(
832
904
  `link[rel="preload"][href="${new URL(url).pathname}"]`
833
905
  );
@@ -835,58 +907,41 @@ async function handleTurbopackChunk(code, bundle, url) {
835
907
  return;
836
908
  }
837
909
  const self = globalThis;
838
- const bundleKey = getBundleKey(bundle);
839
- logDebug("ChunkLoader", `Bundle key: "${bundleKey}"`);
910
+ const { globalKey } = scope;
840
911
  const transformedCode = code.replace(
841
912
  /globalThis\[\s*["']TURBOPACK["']\s*\]/g,
842
- `globalThis["TURBOPACK_${bundleKey}"]`
913
+ `globalThis["TURBOPACK_${globalKey}"]`
843
914
  ).replace(
844
915
  /self\[\s*["']TURBOPACK["']\s*\]/g,
845
- `self["TURBOPACK_${bundleKey}"]`
846
- ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`).replace(
916
+ `self["TURBOPACK_${globalKey}"]`
917
+ ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`).replace(
847
918
  /TURBOPACK_WORKER_LOCATION/g,
848
- `TURBOPACK_WORKER_LOCATION_${bundleKey}`
919
+ `TURBOPACK_WORKER_LOCATION_${globalKey}`
849
920
  ).replace(
850
921
  /TURBOPACK_NEXT_CHUNK_URLS/g,
851
- `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
922
+ `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`
852
923
  ).replace(
853
924
  /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
854
- `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
855
- ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
925
+ `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`
926
+ ).replace(/__next_require__/g, `__${globalKey}_next_require__`).replace(
856
927
  /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
857
- `//# sourceMappingURL=${new URL(
858
- ".",
859
- new URL(
860
- url,
861
- self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin)
862
- )
863
- ).href}$1$2.js.map`
928
+ `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
864
929
  );
865
- if (!self[`TURBOPACK_${bundleKey}`]) {
930
+ if (!self[`TURBOPACK_${globalKey}`]) {
866
931
  const chunkData = [];
867
932
  const turbopackObject = {
868
933
  push: (item) => {
869
- logDebug(
870
- "ChunkLoader",
871
- `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? "array" : typeof item}`
872
- );
873
934
  if (Array.isArray(item)) {
874
935
  chunkData.push(item);
875
- logDebug(
876
- "ChunkLoader",
877
- `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`
878
- );
879
936
  } else {
880
937
  chunkData.push([item]);
881
938
  }
882
939
  return chunkData.length;
883
940
  },
884
- // Store chunks for later access
885
941
  __chunks__: chunkData
886
942
  };
887
- self[`TURBOPACK_${bundleKey}`] = turbopackObject;
943
+ self[`TURBOPACK_${globalKey}`] = turbopackObject;
888
944
  }
889
- logDebug("ChunkLoader", `Creating blob script for: "${url}"`);
890
945
  await new Promise((scriptResolve, scriptReject) => {
891
946
  const blob = new Blob([transformedCode], {
892
947
  type: "application/javascript; charset=UTF-8"
@@ -898,21 +953,6 @@ async function handleTurbopackChunk(code, bundle, url) {
898
953
  script.async = true;
899
954
  script.onload = () => {
900
955
  URL.revokeObjectURL(scriptUrl);
901
- logDebug(
902
- "ChunkLoader",
903
- `Script loaded successfully for bundle "${bundle}"`
904
- );
905
- const turbopackBundle = self[`TURBOPACK_${bundleKey}`];
906
- logDebug(
907
- "ChunkLoader",
908
- `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${turbopackBundle ? Object.keys(turbopackBundle).slice(0, 10).join(", ") : "none"}`
909
- );
910
- if (turbopackBundle && typeof turbopackBundle === "object") {
911
- logDebug(
912
- "ChunkLoader",
913
- `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle).length}`
914
- );
915
- }
916
956
  scriptResolve(void 0);
917
957
  script.remove();
918
958
  };
@@ -927,35 +967,25 @@ async function handleTurbopackChunk(code, bundle, url) {
927
967
  };
928
968
  document.head.appendChild(script);
929
969
  });
930
- const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`];
931
- logDebug(
932
- "ChunkLoader",
933
- `Processing chunk lists for bundle "${bundle}": ${chunkLists?.length ?? 0} lists`
934
- );
935
- const loadChunkLists = [];
970
+ const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`];
971
+ const loadChunkPromises = [];
936
972
  while (chunkLists?.length) {
937
973
  const { chunks } = chunkLists.shift() ?? { chunks: [] };
938
974
  if (chunks.length > 0) {
939
- logDebug(
940
- "ChunkLoader",
941
- `Loading ${chunks.length} additional chunks for bundle "${bundle}": [${chunks.join(", ")}]`
942
- );
943
- chunks.forEach((id) => {
944
- const chunkLoadResult = self.__webpack_chunk_load__?.(
945
- `[${bundle}] ${url.slice(0, url.indexOf("/_next"))}/_next/${id}`
975
+ for (const id of chunks) {
976
+ const baseUrl = url.slice(0, url.indexOf("/_next"));
977
+ const chunkLoadResult = loadChunkWithScope(
978
+ scope,
979
+ formatRemoteId(scope, `${baseUrl}/_next/${id}`)
946
980
  );
947
981
  if (chunkLoadResult) {
948
- loadChunkLists.push(chunkLoadResult);
982
+ loadChunkPromises.push(chunkLoadResult);
949
983
  }
950
- });
984
+ }
951
985
  }
952
986
  }
953
- if (loadChunkLists.length > 0) {
954
- logDebug(
955
- "ChunkLoader",
956
- `Waiting for ${loadChunkLists.length} additional chunks to load`
957
- );
958
- await Promise.all(loadChunkLists);
987
+ if (loadChunkPromises.length > 0) {
988
+ await Promise.all(loadChunkPromises);
959
989
  }
960
990
  }
961
991
  var init_chunk_loader = __esm({
@@ -967,64 +997,195 @@ var init_chunk_loader = __esm({
967
997
  init_error();
968
998
  init_logger();
969
999
  init_patterns2();
1000
+ init_remote_scope();
970
1001
  }
971
1002
  });
972
1003
 
973
- // src/runtime/turbopack/module.ts
974
- function handleTurbopackModule(bundle, moduleId, id) {
1004
+ // src/runtime/turbopack/shared-modules.ts
1005
+ function getTurbopackModules(scope) {
975
1006
  const self = globalThis;
976
- const bundleKey = getBundleKey(bundle);
977
- const raw = self[`TURBOPACK_${bundleKey}`];
978
- let modules;
979
- if (raw && typeof raw === "object" && "__chunks__" in raw) {
980
- modules = raw.__chunks__.flat();
981
- } else if (Array.isArray(raw)) {
982
- modules = raw.flat();
1007
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1008
+ if (!raw)
1009
+ return void 0;
1010
+ if (typeof raw === "object" && "__chunks__" in raw) {
1011
+ return raw.__chunks__.flat();
1012
+ }
1013
+ if (Array.isArray(raw)) {
1014
+ return raw.flat();
1015
+ }
1016
+ return Object.entries(raw).flat();
1017
+ }
1018
+ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}) {
1019
+ const allModules = getTurbopackModules(scope);
1020
+ logDebug(
1021
+ "SharedModules",
1022
+ `initializeSharedModules: scope="${scope.scopedName}", allModules=${allModules ? allModules.length : "null"}, hostShared=[${Object.keys(hostShared).join(", ")}], remoteShared=${JSON.stringify(remoteShared)}`
1023
+ );
1024
+ let sharedModuleInitializer = null;
1025
+ if (allModules) {
1026
+ const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1027
+ if (typeof idOrFunc !== "function") {
1028
+ return false;
1029
+ }
1030
+ const funcCode = idOrFunc.toString();
1031
+ return REMOTE_SHARED_MARKER_RE.test(funcCode);
1032
+ });
1033
+ if (sharedModuleInitializerIndex > 0) {
1034
+ const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1035
+ const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1036
+ const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1037
+ if (sharedModuleId) {
1038
+ const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1039
+ scope,
1040
+ sharedModuleId,
1041
+ formatRemoteId(scope, String(sharedModuleInitializerId))
1042
+ );
1043
+ sharedModuleInitializer = sharedModuleInitializerInstance;
1044
+ }
1045
+ }
1046
+ if (sharedModuleInitializer) {
1047
+ const { shared } = await sharedModuleInitializer;
1048
+ const sharedModuleIds = extractSharedModuleIds(shared, scope);
1049
+ logDebug(
1050
+ "SharedModules",
1051
+ `Resolved shared modules for scope="${scope.scopedName}": ${JSON.stringify(sharedModuleIds)}`
1052
+ );
1053
+ return Promise.all(
1054
+ Object.entries(sharedModuleIds).map(async ([id, module]) => {
1055
+ if (hostShared[module]) {
1056
+ scope.sharedModules[id] = await hostShared[module](scope.name);
1057
+ } else {
1058
+ logError(
1059
+ "SharedModules",
1060
+ `Host shared module "${module}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1061
+ );
1062
+ }
1063
+ })
1064
+ );
1065
+ }
1066
+ logWarn(
1067
+ "SharedModules",
1068
+ `No shared module initializer found in bundle for scope="${scope.scopedName}" \u2014 falling back to remoteShared mapping`
1069
+ );
983
1070
  } else {
984
- modules = raw;
1071
+ logWarn(
1072
+ "SharedModules",
1073
+ `No TURBOPACK modules found for scope="${scope.scopedName}" (TURBOPACK_${scope.globalKey} is empty)`
1074
+ );
1075
+ }
1076
+ return Promise.all(
1077
+ Object.entries(remoteShared).map(async ([id, module]) => {
1078
+ if (hostShared[module]) {
1079
+ const normalizedId = id.replace("[app-ssr]", "[app-client]");
1080
+ scope.sharedModules[normalizedId] = await hostShared[module](
1081
+ scope.name
1082
+ );
1083
+ } else {
1084
+ logError(
1085
+ "SharedModules",
1086
+ `Shared module "${module}" not found for "${scope.name}". ${DEDUPLICATION_WARNING}`
1087
+ );
1088
+ }
1089
+ })
1090
+ );
1091
+ }
1092
+ function extractSharedModuleIds(shared, scope) {
1093
+ return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1094
+ const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1095
+ if (asyncSharedModuleId) {
1096
+ const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1097
+ let asyncSharedModule;
1098
+ const turbopackModules = getTurbopackModules(scope) ?? [];
1099
+ const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1100
+ asyncSharedModuleIdNumber
1101
+ );
1102
+ if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1103
+ asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1104
+ }
1105
+ if (asyncSharedModule) {
1106
+ const asyncSharedModuleCode = asyncSharedModule.toString();
1107
+ const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1108
+ acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1109
+ "__remote_shared_module_",
1110
+ ""
1111
+ );
1112
+ }
1113
+ }
1114
+ return acc;
1115
+ }, {});
1116
+ }
1117
+ function getSharedModule(scope, id) {
1118
+ const idStr = String(id);
1119
+ if (scope.sharedModules[idStr] !== void 0) {
1120
+ return scope.sharedModules[idStr];
985
1121
  }
986
- if (!self.__remote_components_turbopack_modules__) {
987
- self.__remote_components_turbopack_modules__ = {};
1122
+ for (const [key, value] of Object.entries(scope.sharedModules)) {
1123
+ if (typeof value !== "undefined" && idStr !== key && idStr.endsWith(key)) {
1124
+ return value;
1125
+ }
988
1126
  }
989
- if (!self.__remote_components_turbopack_modules__[bundle]) {
990
- self.__remote_components_turbopack_modules__[bundle] = {};
1127
+ return null;
1128
+ }
1129
+ var DEDUPLICATION_WARNING;
1130
+ var init_shared_modules = __esm({
1131
+ "src/runtime/turbopack/shared-modules.ts"() {
1132
+ "use strict";
1133
+ init_logger();
1134
+ init_module();
1135
+ init_patterns2();
1136
+ init_remote_scope();
1137
+ 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).";
991
1138
  }
992
- if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
993
- return self.__remote_components_turbopack_modules__[bundle][moduleId];
1139
+ });
1140
+
1141
+ // src/runtime/turbopack/module.ts
1142
+ function requireModule(scope, moduleId, fullId) {
1143
+ const idStr = String(moduleId);
1144
+ if (scope.moduleCache[idStr])
1145
+ return scope.moduleCache[idStr];
1146
+ const sharedModule = getSharedModule(scope, moduleId);
1147
+ if (sharedModule)
1148
+ return sharedModule;
1149
+ return handleTurbopackModule(
1150
+ scope,
1151
+ idStr,
1152
+ fullId ?? formatRemoteId(scope, idStr)
1153
+ );
1154
+ }
1155
+ function handleTurbopackModule(scope, moduleId, id) {
1156
+ if (scope.moduleCache[moduleId]) {
1157
+ return scope.moduleCache[moduleId];
994
1158
  }
1159
+ const modules = getTurbopackModules(scope);
995
1160
  if (!modules) {
996
- logError("TurbopackModule", `TURBOPACK_${bundleKey} is undefined`);
1161
+ logError(
1162
+ "TurbopackModule",
1163
+ `TURBOPACK_${scope.globalKey} is undefined (scope: "${scope.scopedName}")`
1164
+ );
997
1165
  }
998
1166
  const moduleInit = findModuleInit(modules, moduleId);
999
1167
  const exports = {};
1000
1168
  const moduleExports = { exports };
1001
1169
  if (typeof moduleInit !== "function") {
1002
1170
  throw new Error(
1003
- `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
1171
+ `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`
1004
1172
  );
1005
1173
  }
1006
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1007
- if (!self.__remote_components_turbopack_global__) {
1008
- self.__remote_components_turbopack_global__ = {};
1009
- }
1010
- if (!self.__remote_components_turbopack_global__[bundle]) {
1011
- self.__remote_components_turbopack_global__[bundle] = {};
1012
- }
1174
+ scope.moduleCache[moduleId] = moduleExports.exports;
1013
1175
  moduleInit(
1014
1176
  createTurbopackContext(
1015
- bundle,
1177
+ scope,
1016
1178
  exports,
1017
1179
  moduleExports,
1018
1180
  modules,
1019
1181
  moduleInit,
1020
- id,
1021
- self
1182
+ id
1022
1183
  ),
1023
1184
  moduleExports,
1024
1185
  exports
1025
1186
  );
1026
- if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
1027
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1187
+ if (scope.moduleCache[moduleId] !== moduleExports.exports) {
1188
+ scope.moduleCache[moduleId] = moduleExports.exports;
1028
1189
  }
1029
1190
  return moduleExports.exports;
1030
1191
  }
@@ -1049,7 +1210,8 @@ function findModuleInit(modules, moduleId) {
1049
1210
  (e) => Boolean(e && typeof e === "object" && moduleId in e)
1050
1211
  )?.[moduleId];
1051
1212
  }
1052
- function createTurbopackContext(bundle, exports, moduleExports, modules, moduleInit, id, self) {
1213
+ function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1214
+ const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
1053
1215
  return {
1054
1216
  // HMR not implemented for Remote Components
1055
1217
  k: {
@@ -1065,16 +1227,10 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1065
1227
  s(bindings, esmId) {
1066
1228
  let mod = exports;
1067
1229
  if (typeof esmId === "string" || typeof esmId === "number") {
1068
- if (!self.__remote_components_turbopack_modules__) {
1069
- self.__remote_components_turbopack_modules__ = {};
1070
- }
1071
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1072
- self.__remote_components_turbopack_modules__[bundle] = {};
1073
- }
1074
- if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
1075
- self.__remote_components_turbopack_modules__[bundle][esmId] = {};
1230
+ if (!scope.moduleCache[esmId]) {
1231
+ scope.moduleCache[esmId] = {};
1076
1232
  }
1077
- mod = self.__remote_components_turbopack_modules__[bundle][esmId];
1233
+ mod = scope.moduleCache[esmId];
1078
1234
  }
1079
1235
  Object.defineProperty(mod, "__esModule", { value: true });
1080
1236
  if (Array.isArray(bindings)) {
@@ -1107,7 +1263,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1107
1263
  }
1108
1264
  }
1109
1265
  },
1110
- // import
1266
+ // import — resolves directly via scope, no global dispatch
1111
1267
  i(importId) {
1112
1268
  let mod;
1113
1269
  if (typeof importId === "string") {
@@ -1118,7 +1274,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1118
1274
  /\s+<export(?<specifier>.*)>$/,
1119
1275
  ""
1120
1276
  );
1121
- mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`);
1277
+ mod = scopedRequire(normalizedId);
1122
1278
  if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
1123
1279
  if (exportSource === "*") {
1124
1280
  mod[exportName] = mod;
@@ -1127,7 +1283,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1127
1283
  }
1128
1284
  }
1129
1285
  } else {
1130
- mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
1286
+ mod = scopedRequire(importId);
1131
1287
  }
1132
1288
  if (typeof mod !== "object" || mod === null) {
1133
1289
  mod = { default: mod };
@@ -1139,16 +1295,14 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1139
1295
  }
1140
1296
  return mod;
1141
1297
  },
1142
- // require
1298
+ // require — resolves directly via scope
1143
1299
  r(requireId) {
1144
- return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
1300
+ return scopedRequire(requireId);
1145
1301
  },
1146
1302
  // value exports
1147
1303
  v(value) {
1148
1304
  if (typeof value === "function") {
1149
- exports.default = value((vid) => {
1150
- return self.__webpack_require__?.(`[${bundle}] ${vid}`);
1151
- });
1305
+ exports.default = value((vid) => scopedRequire(vid));
1152
1306
  } else {
1153
1307
  moduleExports.exports = value;
1154
1308
  }
@@ -1163,17 +1317,15 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1163
1317
  );
1164
1318
  exports.default = result;
1165
1319
  },
1166
- // async module loader
1320
+ // async module loader — resolves directly via scope
1167
1321
  async A(Aid) {
1168
- const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
1169
- return mod.default(
1170
- (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
1171
- );
1322
+ const mod = scopedRequire(Aid);
1323
+ return mod.default((parentId) => scopedRequire(parentId));
1172
1324
  },
1173
1325
  // dynamic import tracking — no-op for remote components
1174
1326
  j() {
1175
1327
  },
1176
- // chunk loader
1328
+ // chunk loader — loads directly via scope, no global dispatch
1177
1329
  l(url) {
1178
1330
  const flatModules = Array.isArray(modules) ? modules : [];
1179
1331
  const moduleInitIndex = flatModules.indexOf(moduleInit);
@@ -1184,16 +1336,16 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1184
1336
  const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1185
1337
  const nextIndex = scriptSrc.indexOf("/_next");
1186
1338
  const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1187
- const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
1188
- return self.__webpack_chunk_load__?.(bundleUrl, bundle);
1339
+ const chunkUrl = `${baseUrl}/_next/${url}`;
1340
+ return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));
1189
1341
  }
1190
1342
  }
1191
1343
  throw new Error(
1192
1344
  `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1193
1345
  );
1194
1346
  },
1195
- // global object for this bundle
1196
- g: self.__remote_components_turbopack_global__?.[bundle],
1347
+ // globalThis substitute shared across all modules in this scope
1348
+ g: scope.moduleGlobal,
1197
1349
  m: moduleExports,
1198
1350
  e: exports
1199
1351
  };
@@ -1201,169 +1353,49 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1201
1353
  var init_module = __esm({
1202
1354
  "src/runtime/turbopack/module.ts"() {
1203
1355
  "use strict";
1204
- init_constants2();
1205
1356
  init_logger();
1206
- }
1207
- });
1208
-
1209
- // src/runtime/turbopack/shared-modules.ts
1210
- async function initializeSharedModules(bundle, hostShared = {}, remoteShared = {}) {
1211
- const self = globalThis;
1212
- self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};
1213
- if (!self.__remote_shared_modules__[bundle]) {
1214
- self.__remote_shared_modules__[bundle] = {};
1215
- }
1216
- const bundleKey = getBundleKey(bundle);
1217
- let modules = self[`TURBOPACK_${bundleKey}`];
1218
- if (modules && typeof modules === "object" && "__chunks__" in modules) {
1219
- const chunks = modules.__chunks__;
1220
- modules = chunks.flat();
1221
- }
1222
- let sharedModuleInitializer = null;
1223
- if (modules) {
1224
- const allModules = Array.isArray(modules) ? modules.flat() : Object.entries(modules).flat();
1225
- const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1226
- if (typeof idOrFunc !== "function") {
1227
- return false;
1228
- }
1229
- const funcCode = idOrFunc.toString();
1230
- return REMOTE_SHARED_MARKER_RE.test(funcCode);
1231
- });
1232
- if (sharedModuleInitializerIndex > 0) {
1233
- const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1234
- const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1235
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1236
- if (sharedModuleId) {
1237
- const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1238
- bundle,
1239
- sharedModuleId,
1240
- `[${bundle}] ${sharedModuleInitializerId}`
1241
- );
1242
- sharedModuleInitializer = sharedModuleInitializerInstance;
1243
- }
1244
- }
1245
- if (sharedModuleInitializer) {
1246
- const { shared } = await sharedModuleInitializer;
1247
- const sharedModuleIds = extractSharedModuleIds(
1248
- shared,
1249
- bundleKey,
1250
- self
1251
- );
1252
- return Promise.all(
1253
- Object.entries(sharedModuleIds).map(async ([id, module]) => {
1254
- if (self.__remote_shared_modules__?.[bundle]) {
1255
- if (hostShared[module]) {
1256
- self.__remote_shared_modules__[bundle][id] = await hostShared[module](bundle);
1257
- } else {
1258
- logError(
1259
- "SharedModules",
1260
- `Host shared module "${module}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1261
- );
1262
- }
1263
- }
1264
- })
1265
- );
1266
- }
1267
- }
1268
- return Promise.all(
1269
- Object.entries(remoteShared).map(async ([id, module]) => {
1270
- if (self.__remote_shared_modules__?.[bundle]) {
1271
- if (hostShared[module]) {
1272
- const normalizedId = id.replace("[app-ssr]", "[app-client]");
1273
- self.__remote_shared_modules__[bundle][normalizedId] = await hostShared[module](bundle);
1274
- } else {
1275
- logError(
1276
- "SharedModules",
1277
- `Shared module "${module}" not found for "${bundle}". ${DEDUPLICATION_WARNING}`
1278
- );
1279
- }
1280
- }
1281
- })
1282
- );
1283
- }
1284
- function extractSharedModuleIds(shared, bundleKey, self) {
1285
- return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1286
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1287
- if (asyncSharedModuleId) {
1288
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1289
- let asyncSharedModule;
1290
- let turbopackModules = self[`TURBOPACK_${bundleKey}`];
1291
- if (turbopackModules && typeof turbopackModules === "object" && "__chunks__" in turbopackModules) {
1292
- const chunks = turbopackModules.__chunks__;
1293
- turbopackModules = chunks.flat();
1294
- }
1295
- const newAllModules = Array.isArray(turbopackModules) ? turbopackModules.flat() : turbopackModules ? Object.entries(turbopackModules).flatMap(([key2, value2]) => [
1296
- key2,
1297
- value2
1298
- ]) : [];
1299
- const asyncSharedModuleIdIndex = newAllModules.indexOf(
1300
- asyncSharedModuleIdNumber
1301
- );
1302
- if (asyncSharedModuleIdIndex !== -1 && typeof newAllModules[asyncSharedModuleIdIndex + 1] === "function") {
1303
- asyncSharedModule = newAllModules[asyncSharedModuleIdIndex + 1];
1304
- }
1305
- if (asyncSharedModule) {
1306
- const asyncSharedModuleCode = asyncSharedModule.toString();
1307
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1308
- acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1309
- "__remote_shared_module_",
1310
- ""
1311
- );
1312
- }
1313
- }
1314
- return acc;
1315
- }, {});
1316
- }
1317
- function getSharedModule(bundle, id) {
1318
- const self = globalThis;
1319
- for (const [key, value] of Object.entries(
1320
- self.__remote_shared_modules__?.[bundle] ?? {}
1321
- )) {
1322
- if (typeof value !== "undefined" && (typeof id === "string" && id.includes(key) || id === key)) {
1323
- return value;
1324
- }
1325
- }
1326
- return null;
1327
- }
1328
- var DEDUPLICATION_WARNING;
1329
- var init_shared_modules = __esm({
1330
- "src/runtime/turbopack/shared-modules.ts"() {
1331
- "use strict";
1332
- init_constants2();
1333
- init_logger();
1334
- init_module();
1335
- init_patterns2();
1336
- 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).";
1357
+ init_chunk_loader();
1358
+ init_remote_scope();
1359
+ init_shared_modules();
1337
1360
  }
1338
1361
  });
1339
1362
 
1340
1363
  // src/runtime/turbopack/webpack-runtime.ts
1341
1364
  async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1342
1365
  const self = globalThis;
1366
+ const bundleName = bundle ?? "default";
1367
+ const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1368
+ registerScope(scope);
1343
1369
  if (!self.__remote_bundle_url__) {
1344
1370
  self.__remote_bundle_url__ = {};
1345
1371
  }
1346
- self.__remote_bundle_url__[bundle ?? "default"] = url;
1372
+ self.__remote_bundle_url__[bundleName] = url;
1373
+ if (scope.scopedName !== bundleName) {
1374
+ self.__remote_bundle_url__[scope.scopedName] = url;
1375
+ }
1347
1376
  self.__webpack_get_script_filename__ = () => null;
1348
- if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
1377
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1378
+ if (willCreateDispatchers) {
1349
1379
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1350
1380
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1351
1381
  self.__original_webpack_require__ = self.__webpack_require__;
1352
1382
  }
1353
- self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);
1354
- self.__webpack_require__ = createModuleRequire(runtime);
1383
+ self.__webpack_chunk_load__ = createChunkDispatcher();
1384
+ self.__webpack_require__ = createModuleDispatcher(runtime);
1355
1385
  self.__webpack_require_type__ = runtime;
1356
1386
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1357
- const remoteBundle = bundle ?? "default";
1358
- self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
1359
- self.__remote_webpack_require__[remoteBundle].type = "turbopack";
1387
+ self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
1388
+ self.__remote_webpack_require__[bundleName].type = "turbopack";
1360
1389
  }
1361
1390
  }
1391
+ if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
1392
+ self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
1393
+ }
1362
1394
  if (runtime === RUNTIME_TURBOPACK) {
1363
1395
  const results = await Promise.allSettled(
1364
1396
  scripts.map((script) => {
1365
1397
  if (script.src) {
1366
- return self.__webpack_chunk_load__?.(script.src, bundle);
1398
+ return loadChunkWithScope(scope, script.src);
1367
1399
  }
1368
1400
  return Promise.resolve(void 0);
1369
1401
  })
@@ -1385,54 +1417,54 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1385
1417
  "react-dom/client": async () => (await import("react-dom/client")).default,
1386
1418
  ...shared
1387
1419
  };
1388
- await initializeSharedModules(
1389
- bundle ?? "default",
1390
- // include all core modules as shared
1391
- coreShared,
1392
- remoteShared
1393
- );
1420
+ await initializeSharedModules(scope, coreShared, remoteShared);
1394
1421
  }
1395
- function createModuleRequire(runtime) {
1422
+ function createModuleDispatcher(runtime) {
1396
1423
  return (id) => {
1397
1424
  const self = globalThis;
1398
1425
  const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1399
1426
  bundle: "default",
1400
1427
  id
1401
1428
  };
1402
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1403
- logDebug("WebpackRuntime", `remoteRuntime: "${remoteRuntime}"`);
1429
+ const bundleName = bundle ?? "default";
1430
+ const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
1431
+ logDebug(
1432
+ "ModuleDispatcher",
1433
+ `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
1434
+ );
1404
1435
  try {
1405
1436
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1406
1437
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1407
1438
  }
1408
- const sharedModuleId = moduleId ?? id;
1409
- const sharedModule = getSharedModule(bundle ?? "default", sharedModuleId);
1410
- if (sharedModule) {
1411
- return sharedModule;
1412
- }
1413
- if (bundle && moduleId) {
1414
- return handleTurbopackModule(bundle, moduleId, id);
1439
+ const scope = getScope(bundleName);
1440
+ if (scope) {
1441
+ return requireModule(scope, moduleId ?? id, id);
1415
1442
  }
1416
- throw new Error(`Module "${id}" not found.`);
1443
+ throw new Error(
1444
+ `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
1445
+ );
1417
1446
  } catch (requireError) {
1418
1447
  logWarn(
1419
- "WebpackRuntime",
1448
+ "ModuleDispatcher",
1420
1449
  `Module require failed: ${String(requireError)}`
1421
1450
  );
1422
1451
  if (typeof self.__original_webpack_require__ !== "function") {
1423
1452
  throw new RemoteComponentsError(
1424
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1453
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1425
1454
  {
1426
1455
  cause: requireError instanceof Error ? requireError : void 0
1427
1456
  }
1428
1457
  );
1429
1458
  }
1430
1459
  try {
1431
- logDebug("WebpackRuntime", "Falling back to original webpack require");
1460
+ logDebug(
1461
+ "ModuleDispatcher",
1462
+ "Falling back to original webpack require"
1463
+ );
1432
1464
  return self.__original_webpack_require__(id);
1433
1465
  } catch (originalError) {
1434
1466
  throw new RemoteComponentsError(
1435
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1467
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1436
1468
  { cause: originalError instanceof Error ? originalError : void 0 }
1437
1469
  );
1438
1470
  }
@@ -1448,6 +1480,7 @@ var init_webpack_runtime = __esm({
1448
1480
  init_logger();
1449
1481
  init_chunk_loader();
1450
1482
  init_module();
1483
+ init_remote_scope();
1451
1484
  init_shared_modules();
1452
1485
  }
1453
1486
  });