remote-components 0.3.0 → 0.3.2

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 (105) hide show
  1. package/dist/config/nextjs.cjs.map +1 -1
  2. package/dist/config/nextjs.js.map +1 -1
  3. package/dist/host/html.cjs +467 -395
  4. package/dist/host/html.cjs.map +1 -1
  5. package/dist/host/html.js +467 -395
  6. package/dist/host/html.js.map +1 -1
  7. package/dist/host/nextjs/app/client-only.cjs +507 -447
  8. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  9. package/dist/host/nextjs/app/client-only.js +515 -455
  10. package/dist/host/nextjs/app/client-only.js.map +1 -1
  11. package/dist/host/nextjs/app.cjs +5 -6
  12. package/dist/host/nextjs/app.cjs.map +1 -1
  13. package/dist/host/nextjs/app.js +5 -6
  14. package/dist/host/nextjs/app.js.map +1 -1
  15. package/dist/host/nextjs/pages.cjs +6 -11
  16. package/dist/host/nextjs/pages.cjs.map +1 -1
  17. package/dist/host/nextjs/pages.js +9 -11
  18. package/dist/host/nextjs/pages.js.map +1 -1
  19. package/dist/host/react.cjs +435 -374
  20. package/dist/host/react.cjs.map +1 -1
  21. package/dist/host/react.js +435 -374
  22. package/dist/host/react.js.map +1 -1
  23. package/dist/internal/host/nextjs/dom-flight.cjs +16 -7
  24. package/dist/internal/host/nextjs/dom-flight.cjs.map +1 -1
  25. package/dist/internal/host/nextjs/dom-flight.d.ts +2 -2
  26. package/dist/internal/host/nextjs/dom-flight.js +16 -7
  27. package/dist/internal/host/nextjs/dom-flight.js.map +1 -1
  28. package/dist/internal/host/nextjs/image-shared.cjs +2 -2
  29. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  30. package/dist/internal/host/nextjs/image-shared.js +2 -2
  31. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  32. package/dist/internal/host/server/fetch-remote-component.cjs +183 -149
  33. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  34. package/dist/internal/host/server/fetch-remote-component.js +185 -149
  35. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  36. package/dist/internal/host/shared/remote-image-loader.cjs +2 -5
  37. package/dist/internal/host/shared/remote-image-loader.cjs.map +1 -1
  38. package/dist/internal/host/shared/remote-image-loader.js +2 -5
  39. package/dist/internal/host/shared/remote-image-loader.js.map +1 -1
  40. package/dist/internal/runtime/constants.cjs +6 -6
  41. package/dist/internal/runtime/constants.cjs.map +1 -1
  42. package/dist/internal/runtime/constants.d.ts +3 -3
  43. package/dist/internal/runtime/constants.js +4 -4
  44. package/dist/internal/runtime/constants.js.map +1 -1
  45. package/dist/internal/runtime/html/parse-remote-html.cjs +11 -15
  46. package/dist/internal/runtime/html/parse-remote-html.cjs.map +1 -1
  47. package/dist/internal/runtime/html/parse-remote-html.d.ts +2 -12
  48. package/dist/internal/runtime/html/parse-remote-html.js +17 -15
  49. package/dist/internal/runtime/html/parse-remote-html.js.map +1 -1
  50. package/dist/internal/runtime/loaders/script-loader.cjs +2 -2
  51. package/dist/internal/runtime/loaders/script-loader.cjs.map +1 -1
  52. package/dist/internal/runtime/loaders/script-loader.js +1 -1
  53. package/dist/internal/runtime/loaders/script-loader.js.map +1 -1
  54. package/dist/internal/runtime/metadata.cjs +42 -0
  55. package/dist/internal/runtime/metadata.cjs.map +1 -1
  56. package/dist/internal/runtime/metadata.d.ts +21 -1
  57. package/dist/internal/runtime/metadata.js +38 -0
  58. package/dist/internal/runtime/metadata.js.map +1 -1
  59. package/dist/internal/runtime/patterns.cjs +38 -0
  60. package/dist/internal/runtime/patterns.cjs.map +1 -0
  61. package/dist/internal/runtime/patterns.d.ts +5 -0
  62. package/dist/internal/runtime/patterns.js +12 -0
  63. package/dist/internal/runtime/patterns.js.map +1 -0
  64. package/dist/internal/runtime/turbopack/chunk-loader.cjs +79 -128
  65. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  66. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +22 -7
  67. package/dist/internal/runtime/turbopack/chunk-loader.js +85 -131
  68. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  69. package/dist/internal/runtime/turbopack/module.cjs +56 -57
  70. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  71. package/dist/internal/runtime/turbopack/module.d.ts +14 -11
  72. package/dist/internal/runtime/turbopack/module.js +54 -56
  73. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  74. package/dist/internal/runtime/turbopack/remote-scope.cjs +101 -0
  75. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -0
  76. package/dist/internal/runtime/turbopack/remote-scope.d.ts +55 -0
  77. package/dist/internal/runtime/turbopack/remote-scope.js +73 -0
  78. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -0
  79. package/dist/internal/runtime/turbopack/shared-modules.cjs +62 -56
  80. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  81. package/dist/internal/runtime/turbopack/shared-modules.d.ts +7 -3
  82. package/dist/internal/runtime/turbopack/shared-modules.js +63 -57
  83. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  84. package/dist/internal/runtime/turbopack/webpack-runtime.cjs +50 -31
  85. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +1 -1
  86. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +5 -2
  87. package/dist/internal/runtime/turbopack/webpack-runtime.js +52 -34
  88. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +1 -1
  89. package/dist/internal/runtime/types.cjs.map +1 -1
  90. package/dist/internal/runtime/types.d.ts +4 -3
  91. package/dist/internal/utils/logger.cjs.map +1 -1
  92. package/dist/internal/utils/logger.d.ts +1 -1
  93. package/dist/internal/utils/logger.js.map +1 -1
  94. package/dist/internal/utils.cjs +5 -0
  95. package/dist/internal/utils.cjs.map +1 -1
  96. package/dist/internal/utils.d.ts +15 -1
  97. package/dist/internal/utils.js +4 -0
  98. package/dist/internal/utils.js.map +1 -1
  99. package/dist/remote/html.cjs.map +1 -1
  100. package/dist/remote/html.js.map +1 -1
  101. package/dist/remote/nextjs/app.cjs +2 -1
  102. package/dist/remote/nextjs/app.cjs.map +1 -1
  103. package/dist/remote/nextjs/app.js +2 -1
  104. package/dist/remote/nextjs/app.js.map +1 -1
  105. package/package.json +1 -1
@@ -211,11 +211,104 @@ function getClientOrServerUrl(src, serverFallback) {
211
211
  return typeof src === "string" ? new URL(src, fallback) : src;
212
212
  }
213
213
 
214
- // src/host/shared/remote-image-loader.ts
215
- function getRemoteBundleOrigin(bundle) {
214
+ // src/utils/index.ts
215
+ function escapeString(str) {
216
+ return str.replace(/[^a-z0-9]/g, "_");
217
+ }
218
+ function computeScopedName(name, options) {
219
+ return options.isCrossOrigin ? `${name}_${escapeString(options.remoteHost.toLowerCase())}` : name;
220
+ }
221
+ var attrToProp = {
222
+ fetchpriority: "fetchPriority",
223
+ crossorigin: "crossOrigin",
224
+ imagesrcset: "imageSrcSet",
225
+ imagesizes: "imageSizes",
226
+ srcset: "srcSet"
227
+ };
228
+
229
+ // src/runtime/constants.ts
230
+ var DEFAULT_BUNDLE_NAME = "__vercel_remote_bundle";
231
+ var DEFAULT_COMPONENT_NAME = "__vercel_remote_component";
232
+ var DEFAULT_ROUTE = "/";
233
+ var RUNTIME_WEBPACK = "webpack";
234
+ var RUNTIME_TURBOPACK = "turbopack";
235
+ var RUNTIME_SCRIPT = "script";
236
+ function getBundleKey(bundle) {
237
+ return escapeString(bundle);
238
+ }
239
+
240
+ // src/runtime/patterns.ts
241
+ var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
242
+ var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
243
+ var DOUBLE_SLASH_RE = /(?<!:)\/\//g;
244
+ function collapseDoubleSlashes(path) {
245
+ return path.replace(DOUBLE_SLASH_RE, "/");
246
+ }
247
+
248
+ // src/runtime/turbopack/remote-scope.ts
249
+ function getRegistry() {
216
250
  const self = globalThis;
217
- return self.__remote_bundle_url__?.[bundle]?.origin ?? "";
251
+ if (!self.__remote_component_scopes__) {
252
+ self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
253
+ }
254
+ return self.__remote_component_scopes__;
255
+ }
256
+ function createScope(name, url, runtime, resolveClientUrl) {
257
+ const isCrossOrigin = url.origin !== location.origin;
258
+ const scopedName = computeScopedName(name, {
259
+ remoteHost: url.host,
260
+ isCrossOrigin
261
+ });
262
+ const globalKey = getBundleKey(scopedName);
263
+ return {
264
+ name,
265
+ scopedName,
266
+ globalKey,
267
+ url,
268
+ runtime,
269
+ resolveClientUrl,
270
+ moduleCache: {},
271
+ sharedModules: {},
272
+ moduleGlobal: {}
273
+ };
274
+ }
275
+ function registerScope(scope) {
276
+ const registry = getRegistry();
277
+ registry.set(scope.scopedName, scope);
278
+ if (scope.scopedName !== scope.name) {
279
+ const existing = registry.get(scope.name);
280
+ if (existing && existing.scopedName !== scope.scopedName) {
281
+ logWarn(
282
+ "RemoteScope",
283
+ `Plain name "${scope.name}" already registered by scope "${existing.scopedName}" \u2014 overwriting with "${scope.scopedName}". Static hosts will only resolve the latest one.`
284
+ );
285
+ }
286
+ registry.set(scope.name, scope);
287
+ }
288
+ logDebug(
289
+ "RemoteScope",
290
+ `Registered scope "${scope.scopedName}" (${registry.size} total)`
291
+ );
292
+ }
293
+ function getScope(name) {
294
+ return getRegistry().get(name);
218
295
  }
296
+ function formatRemoteId(scope, path) {
297
+ return `[${scope.scopedName}] ${path}`;
298
+ }
299
+ function parseRemoteId(id) {
300
+ const groups = REMOTE_COMPONENT_REGEX.exec(id)?.groups;
301
+ if (groups?.bundle && groups.id) {
302
+ return {
303
+ bundle: groups.bundle,
304
+ path: groups.id,
305
+ prefix: groups.prefix ?? ""
306
+ };
307
+ }
308
+ return { bundle: "default", path: id, prefix: "" };
309
+ }
310
+
311
+ // src/host/shared/remote-image-loader.ts
219
312
  function createRemoteImageLoader(bundle, resolveClientUrl) {
220
313
  const loader = Object.assign(
221
314
  ({
@@ -225,7 +318,7 @@ function createRemoteImageLoader(bundle, resolveClientUrl) {
225
318
  quality
226
319
  }) => {
227
320
  const q = quality ?? 75;
228
- const remoteOrigin = getRemoteBundleOrigin(bundle);
321
+ const remoteOrigin = getScope(bundle)?.url.origin ?? "";
229
322
  const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;
230
323
  const basePath = isCrossOrigin ? `${remoteOrigin}${config.path ?? "/_next/image"}` : config.path ?? `${remoteOrigin}/_next/image`;
231
324
  const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;
@@ -407,29 +500,6 @@ function resolveNameFromSrc(src, defaultName) {
407
500
  return name || defaultName;
408
501
  }
409
502
 
410
- // src/utils/index.ts
411
- function escapeString(str) {
412
- return str.replace(/[^a-z0-9]/g, "_");
413
- }
414
- var attrToProp = {
415
- fetchpriority: "fetchPriority",
416
- crossorigin: "crossOrigin",
417
- imagesrcset: "imageSrcSet",
418
- imagesizes: "imageSizes",
419
- srcset: "srcSet"
420
- };
421
-
422
- // src/runtime/constants.ts
423
- var DEFAULT_ROUTE = "/";
424
- var RUNTIME_WEBPACK = "webpack";
425
- var RUNTIME_TURBOPACK = "turbopack";
426
- var RUNTIME_SCRIPT = "script";
427
- var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
428
- var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
429
- function getBundleKey(bundle) {
430
- return escapeString(bundle);
431
- }
432
-
433
503
  // src/runtime/html/apply-origin.ts
434
504
  var tagNames = [
435
505
  "img",
@@ -492,6 +562,38 @@ function applyOriginToNodes(doc, url, resolveClientUrl) {
492
562
  }
493
563
  }
494
564
 
565
+ // src/runtime/metadata.ts
566
+ var VALID_RUNTIMES = /* @__PURE__ */ new Set(["webpack", "turbopack", "script"]);
567
+ var VALID_TYPES = /* @__PURE__ */ new Set([
568
+ "nextjs",
569
+ "remote-component",
570
+ "unknown"
571
+ ]);
572
+ function isRuntime(value) {
573
+ return VALID_RUNTIMES.has(value);
574
+ }
575
+ function isComponentType(value) {
576
+ return VALID_TYPES.has(value);
577
+ }
578
+ function toRuntime(value) {
579
+ return value && isRuntime(value) ? value : "webpack";
580
+ }
581
+ function toComponentType(value) {
582
+ return value && isComponentType(value) ? value : "unknown";
583
+ }
584
+ function buildMetadata(attrs, url) {
585
+ const id = attrs.id || DEFAULT_COMPONENT_NAME;
586
+ const bundle = attrs.bundle || process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION || DEFAULT_BUNDLE_NAME;
587
+ return {
588
+ name: attrs.name || id.replace(/_ssr$/, ""),
589
+ bundle,
590
+ route: attrs.route || url.pathname || DEFAULT_ROUTE,
591
+ runtime: toRuntime(attrs.runtime),
592
+ id,
593
+ type: toComponentType(attrs.type)
594
+ };
595
+ }
596
+
495
597
  // src/runtime/html/parse-remote-html.ts
496
598
  function validateSingleComponent(doc, name, url) {
497
599
  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}"]`)) {
@@ -511,14 +613,6 @@ function resolveComponentName(component, nextData, fallbackName) {
511
613
  const name = component?.getAttribute("id")?.replace(/_ssr$/, "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
512
614
  return { name, isRemoteComponent };
513
615
  }
514
- function extractComponentMetadata(component, nextData, name, url) {
515
- return {
516
- name,
517
- bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle || "default",
518
- route: component?.getAttribute("data-route") ?? nextData?.page ?? (url.pathname || DEFAULT_ROUTE),
519
- runtime: component?.getAttribute("data-runtime") ?? (nextData?.props.__REMOTE_COMPONENT__?.runtime || RUNTIME_SCRIPT)
520
- };
521
- }
522
616
  function extractRemoteShared(doc, name, nextData) {
523
617
  const remoteSharedEl = doc.querySelector(
524
618
  `#${name}_shared[data-remote-components-shared]`
@@ -530,7 +624,7 @@ function extractRemoteShared(doc, name, nextData) {
530
624
  function validateComponentFound(component, rsc, nextData, isRemoteComponent, url, name) {
531
625
  if (!component || !(rsc || nextData || isRemoteComponent)) {
532
626
  throw new RemoteComponentsError(
533
- `Remote Component not found on ${url}.${name !== "__vercel_remote_component" ? ` The name for the <RemoteComponent> is "${name}". Check <RemoteComponent> usage.` : ""} Did you forget to wrap the content in <RemoteComponent>?`
627
+ `Remote Component not found on ${url}.${name !== DEFAULT_COMPONENT_NAME ? ` The name for the <RemoteComponent> is "${name}". Check <RemoteComponent> usage.` : ""} Did you forget to wrap the content in <RemoteComponent>?`
534
628
  );
535
629
  }
536
630
  }
@@ -556,10 +650,15 @@ function parseRemoteComponentDocument(doc, name, url) {
556
650
  name
557
651
  );
558
652
  const rsc = doc.querySelector(`#${resolvedName}_rsc`);
559
- const metadata = extractComponentMetadata(
560
- component,
561
- nextData,
562
- resolvedName,
653
+ const metadata = buildMetadata(
654
+ {
655
+ name: resolvedName,
656
+ bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle,
657
+ route: component?.getAttribute("data-route") ?? nextData?.page,
658
+ runtime: component?.getAttribute("data-runtime") ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
659
+ id: component?.getAttribute("id"),
660
+ type: component?.getAttribute("data-type")
661
+ },
563
662
  url
564
663
  );
565
664
  const remoteShared = extractRemoteShared(doc, resolvedName, nextData);
@@ -884,62 +983,39 @@ var ASYNC_MODULE_ALL_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<vCb
884
983
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
885
984
 
886
985
  // src/runtime/turbopack/chunk-loader.ts
887
- function createChunkLoader(runtime, resolveClientUrl) {
888
- return function __turbopack_chunk_load__(chunkId, scriptBundle) {
889
- logDebug("ChunkLoader", `Loading chunk: "${chunkId}"`);
890
- const self = globalThis;
891
- const {
892
- bundle,
893
- id: path,
894
- prefix
895
- } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {
896
- bundle: scriptBundle ?? "",
897
- id: chunkId
898
- };
899
- logDebug(
900
- "ChunkLoader",
901
- `Parsed chunk - bundle: "${bundle}", path: "${path}", prefix: "${prefix}"`
902
- );
903
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
904
- logDebug("ChunkLoader", `Remote runtime: "${remoteRuntime}"`);
905
- if (remoteRuntime === RUNTIME_WEBPACK) {
906
- logDebug("ChunkLoader", "Skipping chunk load - webpack runtime detected");
907
- return Promise.resolve(void 0);
908
- }
909
- const url = new URL(
910
- path ? `${prefix ?? ""}${path}`.replace(
911
- /(?<char>[^:])(?<double>\/\/)/g,
912
- "$1/"
913
- ) : "/",
914
- self.__remote_bundle_url__?.[bundle ?? "default"] ?? new URL(location.origin)
915
- ).href;
916
- if (url.endsWith(".css")) {
917
- logDebug("ChunkLoader", `Skipping CSS file: "${url}"`);
918
- return;
919
- }
920
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
921
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
922
- }
923
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
924
- logDebug("ChunkLoader", `Returning cached promise for: "${url}"`);
925
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
926
- }
927
- const resolvedUrl = resolveClientUrl?.(url) ?? url;
928
- logDebug("ChunkLoader", `Fetching chunk from: "${resolvedUrl}"`);
929
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise((resolve, reject) => {
986
+ function loadChunkWithScope(scope, chunkId) {
987
+ logDebug(
988
+ "ChunkLoader",
989
+ `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
990
+ );
991
+ const self = globalThis;
992
+ const { bundle, path, prefix } = parseRemoteId(chunkId);
993
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
994
+ if (remoteRuntime === RUNTIME_WEBPACK) {
995
+ return Promise.resolve(void 0);
996
+ }
997
+ const rawPath = path ? collapseDoubleSlashes(`${prefix}${path}`) : "/";
998
+ const url = new URL(rawPath, scope.url).href;
999
+ if (url.endsWith(".css")) {
1000
+ return;
1001
+ }
1002
+ if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1003
+ self.__remote_components_turbopack_chunk_loader_promise__ = {};
1004
+ }
1005
+ if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1006
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
1007
+ }
1008
+ const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1009
+ if (resolvedUrl !== url) {
1010
+ logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1011
+ }
1012
+ self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1013
+ (resolve, reject) => {
930
1014
  fetch(resolvedUrl).then((res) => res.text()).then((code) => {
931
1015
  const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
932
1016
  if (hasTurbopack) {
933
- return handleTurbopackChunk(code, bundle ?? "", url);
1017
+ return handleTurbopackChunk(code, scope, url);
934
1018
  }
935
- logDebug(
936
- "ChunkLoader",
937
- `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: "${url}"`
938
- );
939
- logDebug(
940
- "ChunkLoader",
941
- `First 500 chars of chunk: ${code.slice(0, 500)}`
942
- );
943
1019
  }).then(resolve).catch((error) => {
944
1020
  const isProxied = isProxiedUrl(resolvedUrl);
945
1021
  if (isProxied) {
@@ -949,17 +1025,29 @@ function createChunkLoader(runtime, resolveClientUrl) {
949
1025
  reject(error);
950
1026
  }
951
1027
  });
952
- });
953
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1028
+ }
1029
+ );
1030
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
1031
+ }
1032
+ function createChunkDispatcher() {
1033
+ return function __chunk_dispatcher__(chunkId, scriptBundle) {
1034
+ logDebug("ChunkDispatcher", `Dispatching chunk: "${chunkId}"`);
1035
+ const { bundle } = parseRemoteId(chunkId);
1036
+ const bundleName = bundle || scriptBundle || "default";
1037
+ const scope = getScope(bundleName);
1038
+ logDebug(
1039
+ "ChunkDispatcher",
1040
+ `Scope resolution: bundle="${bundleName}", scope=${scope?.scopedName ?? "null"}`
1041
+ );
1042
+ if (!scope) {
1043
+ logWarn("ChunkDispatcher", `No scope found for bundle "${bundleName}"`);
1044
+ return Promise.resolve(void 0);
1045
+ }
1046
+ return loadChunkWithScope(scope, chunkId);
954
1047
  };
955
1048
  }
956
- async function handleTurbopackChunk(code, bundle, url) {
957
- logDebug(
958
- "ChunkLoader",
959
- `Handling Turbopack chunk - bundle: "${bundle}", url: "${url}"`
960
- );
1049
+ async function handleTurbopackChunk(code, scope, url) {
961
1050
  if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
962
- logDebug("ChunkLoader", `Skipping worker chunk: "${url}"`);
963
1051
  const preloadLinks = document.querySelectorAll(
964
1052
  `link[rel="preload"][href="${new URL(url).pathname}"]`
965
1053
  );
@@ -967,58 +1055,41 @@ async function handleTurbopackChunk(code, bundle, url) {
967
1055
  return;
968
1056
  }
969
1057
  const self = globalThis;
970
- const bundleKey = getBundleKey(bundle);
971
- logDebug("ChunkLoader", `Bundle key: "${bundleKey}"`);
1058
+ const { globalKey } = scope;
972
1059
  const transformedCode = code.replace(
973
1060
  /globalThis\[\s*["']TURBOPACK["']\s*\]/g,
974
- `globalThis["TURBOPACK_${bundleKey}"]`
1061
+ `globalThis["TURBOPACK_${globalKey}"]`
975
1062
  ).replace(
976
1063
  /self\[\s*["']TURBOPACK["']\s*\]/g,
977
- `self["TURBOPACK_${bundleKey}"]`
978
- ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`).replace(
1064
+ `self["TURBOPACK_${globalKey}"]`
1065
+ ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`).replace(
979
1066
  /TURBOPACK_WORKER_LOCATION/g,
980
- `TURBOPACK_WORKER_LOCATION_${bundleKey}`
1067
+ `TURBOPACK_WORKER_LOCATION_${globalKey}`
981
1068
  ).replace(
982
1069
  /TURBOPACK_NEXT_CHUNK_URLS/g,
983
- `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
1070
+ `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`
984
1071
  ).replace(
985
1072
  /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
986
- `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
987
- ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
1073
+ `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`
1074
+ ).replace(/__next_require__/g, `__${globalKey}_next_require__`).replace(
988
1075
  /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
989
- `//# sourceMappingURL=${new URL(
990
- ".",
991
- new URL(
992
- url,
993
- self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin)
994
- )
995
- ).href}$1$2.js.map`
1076
+ `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
996
1077
  );
997
- if (!self[`TURBOPACK_${bundleKey}`]) {
1078
+ if (!self[`TURBOPACK_${globalKey}`]) {
998
1079
  const chunkData = [];
999
1080
  const turbopackObject = {
1000
1081
  push: (item) => {
1001
- logDebug(
1002
- "ChunkLoader",
1003
- `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? "array" : typeof item}`
1004
- );
1005
1082
  if (Array.isArray(item)) {
1006
1083
  chunkData.push(item);
1007
- logDebug(
1008
- "ChunkLoader",
1009
- `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`
1010
- );
1011
1084
  } else {
1012
1085
  chunkData.push([item]);
1013
1086
  }
1014
1087
  return chunkData.length;
1015
1088
  },
1016
- // Store chunks for later access
1017
1089
  __chunks__: chunkData
1018
1090
  };
1019
- self[`TURBOPACK_${bundleKey}`] = turbopackObject;
1091
+ self[`TURBOPACK_${globalKey}`] = turbopackObject;
1020
1092
  }
1021
- logDebug("ChunkLoader", `Creating blob script for: "${url}"`);
1022
1093
  await new Promise((scriptResolve, scriptReject) => {
1023
1094
  const blob = new Blob([transformedCode], {
1024
1095
  type: "application/javascript; charset=UTF-8"
@@ -1030,21 +1101,6 @@ async function handleTurbopackChunk(code, bundle, url) {
1030
1101
  script.async = true;
1031
1102
  script.onload = () => {
1032
1103
  URL.revokeObjectURL(scriptUrl);
1033
- logDebug(
1034
- "ChunkLoader",
1035
- `Script loaded successfully for bundle "${bundle}"`
1036
- );
1037
- const turbopackBundle = self[`TURBOPACK_${bundleKey}`];
1038
- logDebug(
1039
- "ChunkLoader",
1040
- `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${turbopackBundle ? Object.keys(turbopackBundle).slice(0, 10).join(", ") : "none"}`
1041
- );
1042
- if (turbopackBundle && typeof turbopackBundle === "object") {
1043
- logDebug(
1044
- "ChunkLoader",
1045
- `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle).length}`
1046
- );
1047
- }
1048
1104
  scriptResolve(void 0);
1049
1105
  script.remove();
1050
1106
  };
@@ -1059,43 +1115,177 @@ async function handleTurbopackChunk(code, bundle, url) {
1059
1115
  };
1060
1116
  document.head.appendChild(script);
1061
1117
  });
1062
- const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`];
1063
- logDebug(
1064
- "ChunkLoader",
1065
- `Processing chunk lists for bundle "${bundle}": ${chunkLists?.length ?? 0} lists`
1066
- );
1067
- const loadChunkLists = [];
1118
+ const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`];
1119
+ const loadChunkPromises = [];
1068
1120
  while (chunkLists?.length) {
1069
1121
  const { chunks } = chunkLists.shift() ?? { chunks: [] };
1070
1122
  if (chunks.length > 0) {
1071
- logDebug(
1072
- "ChunkLoader",
1073
- `Loading ${chunks.length} additional chunks for bundle "${bundle}": [${chunks.join(", ")}]`
1074
- );
1075
- chunks.forEach((id) => {
1076
- const chunkLoadResult = self.__webpack_chunk_load__?.(
1077
- `[${bundle}] ${url.slice(0, url.indexOf("/_next"))}/_next/${id}`
1123
+ for (const id of chunks) {
1124
+ const baseUrl = url.slice(0, url.indexOf("/_next"));
1125
+ const chunkLoadResult = loadChunkWithScope(
1126
+ scope,
1127
+ formatRemoteId(scope, `${baseUrl}/_next/${id}`)
1078
1128
  );
1079
1129
  if (chunkLoadResult) {
1080
- loadChunkLists.push(chunkLoadResult);
1130
+ loadChunkPromises.push(chunkLoadResult);
1081
1131
  }
1082
- });
1132
+ }
1083
1133
  }
1084
1134
  }
1085
- if (loadChunkLists.length > 0) {
1086
- logDebug(
1087
- "ChunkLoader",
1088
- `Waiting for ${loadChunkLists.length} additional chunks to load`
1135
+ if (loadChunkPromises.length > 0) {
1136
+ await Promise.all(loadChunkPromises);
1137
+ }
1138
+ }
1139
+
1140
+ // src/runtime/turbopack/shared-modules.ts
1141
+ 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).";
1142
+ function getTurbopackModules(scope) {
1143
+ const self = globalThis;
1144
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1145
+ if (!raw)
1146
+ return void 0;
1147
+ if (typeof raw === "object" && "__chunks__" in raw) {
1148
+ return raw.__chunks__.flat();
1149
+ }
1150
+ if (Array.isArray(raw)) {
1151
+ return raw.flat();
1152
+ }
1153
+ return Object.entries(raw).flat();
1154
+ }
1155
+ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}) {
1156
+ const allModules = getTurbopackModules(scope);
1157
+ logDebug(
1158
+ "SharedModules",
1159
+ `initializeSharedModules: scope="${scope.scopedName}", allModules=${allModules ? allModules.length : "null"}, hostShared=[${Object.keys(hostShared).join(", ")}], remoteShared=${JSON.stringify(remoteShared)}`
1160
+ );
1161
+ let sharedModuleInitializer = null;
1162
+ if (allModules) {
1163
+ const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1164
+ if (typeof idOrFunc !== "function") {
1165
+ return false;
1166
+ }
1167
+ const funcCode = idOrFunc.toString();
1168
+ return REMOTE_SHARED_MARKER_RE.test(funcCode);
1169
+ });
1170
+ if (sharedModuleInitializerIndex > 0) {
1171
+ const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1172
+ const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1173
+ const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1174
+ if (sharedModuleId) {
1175
+ const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1176
+ scope,
1177
+ sharedModuleId,
1178
+ formatRemoteId(scope, String(sharedModuleInitializerId))
1179
+ );
1180
+ sharedModuleInitializer = sharedModuleInitializerInstance;
1181
+ }
1182
+ }
1183
+ if (sharedModuleInitializer) {
1184
+ const { shared } = await sharedModuleInitializer;
1185
+ const sharedModuleIds = extractSharedModuleIds(shared, scope);
1186
+ logDebug(
1187
+ "SharedModules",
1188
+ `Resolved shared modules for scope="${scope.scopedName}": ${JSON.stringify(sharedModuleIds)}`
1189
+ );
1190
+ return Promise.all(
1191
+ Object.entries(sharedModuleIds).map(async ([id, module]) => {
1192
+ if (hostShared[module]) {
1193
+ scope.sharedModules[id] = await hostShared[module](scope.name);
1194
+ } else {
1195
+ logError(
1196
+ "SharedModules",
1197
+ `Host shared module "${module}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1198
+ );
1199
+ }
1200
+ })
1201
+ );
1202
+ }
1203
+ logWarn(
1204
+ "SharedModules",
1205
+ `No shared module initializer found in bundle for scope="${scope.scopedName}" \u2014 falling back to remoteShared mapping`
1206
+ );
1207
+ } else {
1208
+ logWarn(
1209
+ "SharedModules",
1210
+ `No TURBOPACK modules found for scope="${scope.scopedName}" (TURBOPACK_${scope.globalKey} is empty)`
1089
1211
  );
1090
- await Promise.all(loadChunkLists);
1091
1212
  }
1213
+ return Promise.all(
1214
+ Object.entries(remoteShared).map(async ([id, module]) => {
1215
+ if (hostShared[module]) {
1216
+ const normalizedId = id.replace("[app-ssr]", "[app-client]");
1217
+ scope.sharedModules[normalizedId] = await hostShared[module](
1218
+ scope.name
1219
+ );
1220
+ } else {
1221
+ logError(
1222
+ "SharedModules",
1223
+ `Shared module "${module}" not found for "${scope.name}". ${DEDUPLICATION_WARNING}`
1224
+ );
1225
+ }
1226
+ })
1227
+ );
1228
+ }
1229
+ function extractSharedModuleIds(shared, scope) {
1230
+ return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1231
+ const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1232
+ if (asyncSharedModuleId) {
1233
+ const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1234
+ let asyncSharedModule;
1235
+ const turbopackModules = getTurbopackModules(scope) ?? [];
1236
+ const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1237
+ asyncSharedModuleIdNumber
1238
+ );
1239
+ if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1240
+ asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1241
+ }
1242
+ if (asyncSharedModule) {
1243
+ const asyncSharedModuleCode = asyncSharedModule.toString();
1244
+ const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1245
+ acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1246
+ "__remote_shared_module_",
1247
+ ""
1248
+ );
1249
+ }
1250
+ }
1251
+ return acc;
1252
+ }, {});
1253
+ }
1254
+ function getSharedModule(scope, id) {
1255
+ const idStr = String(id);
1256
+ if (scope.sharedModules[idStr] !== void 0) {
1257
+ return scope.sharedModules[idStr];
1258
+ }
1259
+ for (const [key, value] of Object.entries(scope.sharedModules)) {
1260
+ if (typeof value !== "undefined" && idStr !== key && idStr.endsWith(key)) {
1261
+ return value;
1262
+ }
1263
+ }
1264
+ return null;
1092
1265
  }
1093
1266
 
1094
1267
  // src/runtime/turbopack/module.ts
1095
- function handleTurbopackModule(bundle, moduleId, id) {
1268
+ function requireModule(scope, moduleId, fullId) {
1269
+ const idStr = String(moduleId);
1270
+ if (scope.moduleCache[idStr])
1271
+ return scope.moduleCache[idStr];
1272
+ const sharedModule = getSharedModule(scope, moduleId);
1273
+ if (sharedModule) {
1274
+ scope.moduleCache[idStr] = sharedModule;
1275
+ return sharedModule;
1276
+ }
1277
+ return handleTurbopackModule(
1278
+ scope,
1279
+ idStr,
1280
+ fullId ?? formatRemoteId(scope, idStr)
1281
+ );
1282
+ }
1283
+ function handleTurbopackModule(scope, moduleId, id) {
1096
1284
  const self = globalThis;
1097
- const bundleKey = getBundleKey(bundle);
1098
- const raw = self[`TURBOPACK_${bundleKey}`];
1285
+ if (scope.moduleCache[moduleId]) {
1286
+ return scope.moduleCache[moduleId];
1287
+ }
1288
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1099
1289
  let modules;
1100
1290
  if (raw && typeof raw === "object" && "__chunks__" in raw) {
1101
1291
  modules = raw.__chunks__.flat();
@@ -1104,48 +1294,35 @@ function handleTurbopackModule(bundle, moduleId, id) {
1104
1294
  } else {
1105
1295
  modules = raw;
1106
1296
  }
1107
- if (!self.__remote_components_turbopack_modules__) {
1108
- self.__remote_components_turbopack_modules__ = {};
1109
- }
1110
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1111
- self.__remote_components_turbopack_modules__[bundle] = {};
1112
- }
1113
- if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
1114
- return self.__remote_components_turbopack_modules__[bundle][moduleId];
1115
- }
1116
1297
  if (!modules) {
1117
- logError("TurbopackModule", `TURBOPACK_${bundleKey} is undefined`);
1298
+ logError(
1299
+ "TurbopackModule",
1300
+ `TURBOPACK_${scope.globalKey} is undefined (scope: "${scope.scopedName}")`
1301
+ );
1118
1302
  }
1119
1303
  const moduleInit = findModuleInit(modules, moduleId);
1120
1304
  const exports = {};
1121
1305
  const moduleExports = { exports };
1122
1306
  if (typeof moduleInit !== "function") {
1123
1307
  throw new Error(
1124
- `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
1308
+ `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`
1125
1309
  );
1126
1310
  }
1127
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1128
- if (!self.__remote_components_turbopack_global__) {
1129
- self.__remote_components_turbopack_global__ = {};
1130
- }
1131
- if (!self.__remote_components_turbopack_global__[bundle]) {
1132
- self.__remote_components_turbopack_global__[bundle] = {};
1133
- }
1311
+ scope.moduleCache[moduleId] = moduleExports.exports;
1134
1312
  moduleInit(
1135
1313
  createTurbopackContext(
1136
- bundle,
1314
+ scope,
1137
1315
  exports,
1138
1316
  moduleExports,
1139
1317
  modules,
1140
1318
  moduleInit,
1141
- id,
1142
- self
1319
+ id
1143
1320
  ),
1144
1321
  moduleExports,
1145
1322
  exports
1146
1323
  );
1147
- if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
1148
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1324
+ if (scope.moduleCache[moduleId] !== moduleExports.exports) {
1325
+ scope.moduleCache[moduleId] = moduleExports.exports;
1149
1326
  }
1150
1327
  return moduleExports.exports;
1151
1328
  }
@@ -1170,7 +1347,8 @@ function findModuleInit(modules, moduleId) {
1170
1347
  (e) => Boolean(e && typeof e === "object" && moduleId in e)
1171
1348
  )?.[moduleId];
1172
1349
  }
1173
- function createTurbopackContext(bundle, exports, moduleExports, modules, moduleInit, id, self) {
1350
+ function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1351
+ const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
1174
1352
  return {
1175
1353
  // HMR not implemented for Remote Components
1176
1354
  k: {
@@ -1186,16 +1364,10 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1186
1364
  s(bindings, esmId) {
1187
1365
  let mod = exports;
1188
1366
  if (typeof esmId === "string" || typeof esmId === "number") {
1189
- if (!self.__remote_components_turbopack_modules__) {
1190
- self.__remote_components_turbopack_modules__ = {};
1191
- }
1192
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1193
- self.__remote_components_turbopack_modules__[bundle] = {};
1194
- }
1195
- if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
1196
- self.__remote_components_turbopack_modules__[bundle][esmId] = {};
1367
+ if (!scope.moduleCache[esmId]) {
1368
+ scope.moduleCache[esmId] = {};
1197
1369
  }
1198
- mod = self.__remote_components_turbopack_modules__[bundle][esmId];
1370
+ mod = scope.moduleCache[esmId];
1199
1371
  }
1200
1372
  Object.defineProperty(mod, "__esModule", { value: true });
1201
1373
  if (Array.isArray(bindings)) {
@@ -1228,7 +1400,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1228
1400
  }
1229
1401
  }
1230
1402
  },
1231
- // import
1403
+ // import — resolves directly via scope, no global dispatch
1232
1404
  i(importId) {
1233
1405
  let mod;
1234
1406
  if (typeof importId === "string") {
@@ -1239,7 +1411,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1239
1411
  /\s+<export(?<specifier>.*)>$/,
1240
1412
  ""
1241
1413
  );
1242
- mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`);
1414
+ mod = scopedRequire(normalizedId);
1243
1415
  if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
1244
1416
  if (exportSource === "*") {
1245
1417
  mod[exportName] = mod;
@@ -1248,7 +1420,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1248
1420
  }
1249
1421
  }
1250
1422
  } else {
1251
- mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
1423
+ mod = scopedRequire(importId);
1252
1424
  }
1253
1425
  if (typeof mod !== "object" || mod === null) {
1254
1426
  mod = { default: mod };
@@ -1260,16 +1432,14 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1260
1432
  }
1261
1433
  return mod;
1262
1434
  },
1263
- // require
1435
+ // require — resolves directly via scope
1264
1436
  r(requireId) {
1265
- return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
1437
+ return scopedRequire(requireId);
1266
1438
  },
1267
1439
  // value exports
1268
1440
  v(value) {
1269
1441
  if (typeof value === "function") {
1270
- exports.default = value((vid) => {
1271
- return self.__webpack_require__?.(`[${bundle}] ${vid}`);
1272
- });
1442
+ exports.default = value((vid) => scopedRequire(vid));
1273
1443
  } else {
1274
1444
  moduleExports.exports = value;
1275
1445
  }
@@ -1284,17 +1454,15 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1284
1454
  );
1285
1455
  exports.default = result;
1286
1456
  },
1287
- // async module loader
1457
+ // async module loader — resolves directly via scope
1288
1458
  async A(Aid) {
1289
- const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
1290
- return mod.default(
1291
- (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
1292
- );
1459
+ const mod = scopedRequire(Aid);
1460
+ return mod.default((parentId) => scopedRequire(parentId));
1293
1461
  },
1294
1462
  // dynamic import tracking — no-op for remote components
1295
1463
  j() {
1296
1464
  },
1297
- // chunk loader
1465
+ // chunk loader — loads directly via scope, no global dispatch
1298
1466
  l(url) {
1299
1467
  const flatModules = Array.isArray(modules) ? modules : [];
1300
1468
  const moduleInitIndex = flatModules.indexOf(moduleInit);
@@ -1305,173 +1473,69 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1305
1473
  const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1306
1474
  const nextIndex = scriptSrc.indexOf("/_next");
1307
1475
  const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1308
- const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
1309
- return self.__webpack_chunk_load__?.(bundleUrl, bundle);
1476
+ const chunkUrl = `${baseUrl}/_next/${url}`;
1477
+ return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));
1310
1478
  }
1311
1479
  }
1312
1480
  throw new Error(
1313
1481
  `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1314
1482
  );
1315
1483
  },
1316
- // global object for this bundle
1317
- g: self.__remote_components_turbopack_global__?.[bundle],
1484
+ // globalThis substitute shared across all modules in this scope
1485
+ g: scope.moduleGlobal,
1318
1486
  m: moduleExports,
1319
1487
  e: exports
1320
1488
  };
1321
1489
  }
1322
1490
 
1323
- // src/runtime/turbopack/shared-modules.ts
1324
- 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).";
1325
- async function initializeSharedModules(bundle, hostShared = {}, remoteShared = {}) {
1326
- const self = globalThis;
1327
- self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};
1328
- if (!self.__remote_shared_modules__[bundle]) {
1329
- self.__remote_shared_modules__[bundle] = {};
1330
- }
1331
- const bundleKey = getBundleKey(bundle);
1332
- let modules = self[`TURBOPACK_${bundleKey}`];
1333
- if (modules && typeof modules === "object" && "__chunks__" in modules) {
1334
- const chunks = modules.__chunks__;
1335
- modules = chunks.flat();
1336
- }
1337
- let sharedModuleInitializer = null;
1338
- if (modules) {
1339
- const allModules = Array.isArray(modules) ? modules.flat() : Object.entries(modules).flat();
1340
- const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1341
- if (typeof idOrFunc !== "function") {
1342
- return false;
1343
- }
1344
- const funcCode = idOrFunc.toString();
1345
- return REMOTE_SHARED_MARKER_RE.test(funcCode);
1346
- });
1347
- if (sharedModuleInitializerIndex > 0) {
1348
- const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1349
- const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1350
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1351
- if (sharedModuleId) {
1352
- const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1353
- bundle,
1354
- sharedModuleId,
1355
- `[${bundle}] ${sharedModuleInitializerId}`
1356
- );
1357
- sharedModuleInitializer = sharedModuleInitializerInstance;
1358
- }
1359
- }
1360
- if (sharedModuleInitializer) {
1361
- const { shared } = await sharedModuleInitializer;
1362
- const sharedModuleIds = extractSharedModuleIds(
1363
- shared,
1364
- bundleKey,
1365
- self
1366
- );
1367
- return Promise.all(
1368
- Object.entries(sharedModuleIds).map(async ([id, module]) => {
1369
- if (self.__remote_shared_modules__?.[bundle]) {
1370
- if (hostShared[module]) {
1371
- self.__remote_shared_modules__[bundle][id] = await hostShared[module](bundle);
1372
- } else {
1373
- logError(
1374
- "SharedModules",
1375
- `Host shared module "${module}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1376
- );
1377
- }
1378
- }
1379
- })
1380
- );
1381
- }
1382
- }
1383
- return Promise.all(
1384
- Object.entries(remoteShared).map(async ([id, module]) => {
1385
- if (self.__remote_shared_modules__?.[bundle]) {
1386
- if (hostShared[module]) {
1387
- const normalizedId = id.replace("[app-ssr]", "[app-client]");
1388
- self.__remote_shared_modules__[bundle][normalizedId] = await hostShared[module](bundle);
1389
- } else {
1390
- logError(
1391
- "SharedModules",
1392
- `Shared module "${module}" not found for "${bundle}". ${DEDUPLICATION_WARNING}`
1393
- );
1394
- }
1395
- }
1396
- })
1397
- );
1398
- }
1399
- function extractSharedModuleIds(shared, bundleKey, self) {
1400
- return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1401
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1402
- if (asyncSharedModuleId) {
1403
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1404
- let asyncSharedModule;
1405
- let turbopackModules = self[`TURBOPACK_${bundleKey}`];
1406
- if (turbopackModules && typeof turbopackModules === "object" && "__chunks__" in turbopackModules) {
1407
- const chunks = turbopackModules.__chunks__;
1408
- turbopackModules = chunks.flat();
1409
- }
1410
- const newAllModules = Array.isArray(turbopackModules) ? turbopackModules.flat() : turbopackModules ? Object.entries(turbopackModules).flatMap(([key2, value2]) => [
1411
- key2,
1412
- value2
1413
- ]) : [];
1414
- const asyncSharedModuleIdIndex = newAllModules.indexOf(
1415
- asyncSharedModuleIdNumber
1416
- );
1417
- if (asyncSharedModuleIdIndex !== -1 && typeof newAllModules[asyncSharedModuleIdIndex + 1] === "function") {
1418
- asyncSharedModule = newAllModules[asyncSharedModuleIdIndex + 1];
1419
- }
1420
- if (asyncSharedModule) {
1421
- const asyncSharedModuleCode = asyncSharedModule.toString();
1422
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1423
- acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1424
- "__remote_shared_module_",
1425
- ""
1426
- );
1427
- }
1428
- }
1429
- return acc;
1430
- }, {});
1431
- }
1432
- function getSharedModule(bundle, id) {
1433
- const self = globalThis;
1434
- for (const [key, value] of Object.entries(
1435
- self.__remote_shared_modules__?.[bundle] ?? {}
1436
- )) {
1437
- if (typeof value !== "undefined" && (typeof id === "string" && id.includes(key) || id === key)) {
1438
- return value;
1439
- }
1440
- }
1441
- return null;
1442
- }
1443
-
1444
1491
  // src/runtime/turbopack/webpack-runtime.ts
1445
1492
  async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1446
1493
  const self = globalThis;
1494
+ const bundleName = bundle ?? "default";
1495
+ const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1496
+ registerScope(scope);
1447
1497
  if (!self.__remote_bundle_url__) {
1448
1498
  self.__remote_bundle_url__ = {};
1449
1499
  }
1450
- self.__remote_bundle_url__[bundle ?? "default"] = url;
1500
+ self.__remote_bundle_url__[bundleName] = url;
1501
+ if (scope.scopedName !== bundleName) {
1502
+ self.__remote_bundle_url__[scope.scopedName] = url;
1503
+ }
1451
1504
  self.__webpack_get_script_filename__ = () => null;
1452
- if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
1505
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1506
+ if (willCreateDispatchers) {
1453
1507
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1454
1508
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1455
1509
  self.__original_webpack_require__ = self.__webpack_require__;
1456
1510
  }
1457
- self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);
1458
- self.__webpack_require__ = createModuleRequire(runtime);
1511
+ self.__webpack_chunk_load__ = createChunkDispatcher();
1512
+ self.__webpack_require__ = createModuleDispatcher(runtime);
1459
1513
  self.__webpack_require_type__ = runtime;
1460
1514
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1461
- const remoteBundle = bundle ?? "default";
1462
- self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
1463
- self.__remote_webpack_require__[remoteBundle].type = "turbopack";
1515
+ self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
1516
+ self.__remote_webpack_require__[bundleName].type = "turbopack";
1464
1517
  }
1465
1518
  }
1519
+ if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
1520
+ self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
1521
+ }
1466
1522
  if (runtime === RUNTIME_TURBOPACK) {
1467
- await Promise.all(
1523
+ const results = await Promise.allSettled(
1468
1524
  scripts.map((script) => {
1469
1525
  if (script.src) {
1470
- return self.__webpack_chunk_load__?.(script.src, bundle);
1526
+ return loadChunkWithScope(scope, script.src);
1471
1527
  }
1472
1528
  return Promise.resolve(void 0);
1473
1529
  })
1474
1530
  );
1531
+ for (const result of results) {
1532
+ if (result.status === "rejected") {
1533
+ logWarn(
1534
+ "WebpackRuntime",
1535
+ `Initial chunk load failed: ${String(result.reason)}`
1536
+ );
1537
+ }
1538
+ }
1475
1539
  }
1476
1540
  const coreShared = {
1477
1541
  react: async () => (await import("react")).default,
@@ -1481,54 +1545,54 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1481
1545
  "react-dom/client": async () => (await import("react-dom/client")).default,
1482
1546
  ...shared
1483
1547
  };
1484
- await initializeSharedModules(
1485
- bundle ?? "default",
1486
- // include all core modules as shared
1487
- coreShared,
1488
- remoteShared
1489
- );
1548
+ await initializeSharedModules(scope, coreShared, remoteShared);
1490
1549
  }
1491
- function createModuleRequire(runtime) {
1550
+ function createModuleDispatcher(runtime) {
1492
1551
  return (id) => {
1493
1552
  const self = globalThis;
1494
1553
  const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1495
1554
  bundle: "default",
1496
1555
  id
1497
1556
  };
1498
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1499
- logDebug("WebpackRuntime", `remoteRuntime: "${remoteRuntime}"`);
1557
+ const bundleName = bundle ?? "default";
1558
+ const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
1559
+ logDebug(
1560
+ "ModuleDispatcher",
1561
+ `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
1562
+ );
1500
1563
  try {
1501
1564
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1502
1565
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1503
1566
  }
1504
- const sharedModuleId = moduleId ?? id;
1505
- const sharedModule = getSharedModule(bundle ?? "default", sharedModuleId);
1506
- if (sharedModule) {
1507
- return sharedModule;
1567
+ const scope = getScope(bundleName);
1568
+ if (scope) {
1569
+ return requireModule(scope, moduleId ?? id, id);
1508
1570
  }
1509
- if (bundle && moduleId) {
1510
- return handleTurbopackModule(bundle, moduleId, id);
1511
- }
1512
- throw new Error(`Module "${id}" not found.`);
1571
+ throw new Error(
1572
+ `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
1573
+ );
1513
1574
  } catch (requireError) {
1514
1575
  logWarn(
1515
- "WebpackRuntime",
1576
+ "ModuleDispatcher",
1516
1577
  `Module require failed: ${String(requireError)}`
1517
1578
  );
1518
1579
  if (typeof self.__original_webpack_require__ !== "function") {
1519
1580
  throw new RemoteComponentsError(
1520
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1581
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1521
1582
  {
1522
1583
  cause: requireError instanceof Error ? requireError : void 0
1523
1584
  }
1524
1585
  );
1525
1586
  }
1526
1587
  try {
1527
- logDebug("WebpackRuntime", "Falling back to original webpack require");
1588
+ logDebug(
1589
+ "ModuleDispatcher",
1590
+ "Falling back to original webpack require"
1591
+ );
1528
1592
  return self.__original_webpack_require__(id);
1529
1593
  } catch (originalError) {
1530
1594
  throw new RemoteComponentsError(
1531
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1595
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1532
1596
  { cause: originalError instanceof Error ? originalError : void 0 }
1533
1597
  );
1534
1598
  }
@@ -1954,7 +2018,7 @@ function getRemoteComponentHtml(html) {
1954
2018
  return ssrRemoteComponentContainer.innerHTML;
1955
2019
  }
1956
2020
  const remoteComponentContainer = temp.querySelectorAll(
1957
- `div[data-bundle][data-route][data-runtime][id^="__vercel_remote_component"],div[data-bundle][data-route],div#__next,remote-component:not([src])`
2021
+ `div[data-bundle][data-route][data-runtime][id^="${DEFAULT_COMPONENT_NAME}"],div[data-bundle][data-route],div#__next,remote-component:not([src])`
1958
2022
  );
1959
2023
  if (remoteComponentContainer.length > 0) {
1960
2024
  return `${Array.from(temp.querySelectorAll("link,script")).map((link) => link.outerHTML).join("")}${Array.from(remoteComponentContainer).map((container) => container.outerHTML).join("")}`;
@@ -1971,7 +2035,7 @@ function ConsumeRemoteComponent({
1971
2035
  mode = "open",
1972
2036
  reset,
1973
2037
  credentials: credentialsProp,
1974
- name: nameProp = "__vercel_remote_component",
2038
+ name: nameProp = DEFAULT_COMPONENT_NAME,
1975
2039
  shared: sharedProp,
1976
2040
  children,
1977
2041
  onBeforeLoad,
@@ -2311,10 +2375,7 @@ function ConsumeRemoteComponent({
2311
2375
  };
2312
2376
  return {
2313
2377
  src: new URL(
2314
- `${prefix ?? ""}${path}`.replace(
2315
- /(?<char>[^:])(?<double>\/\/)/g,
2316
- "$1/"
2317
- ),
2378
+ collapseDoubleSlashes(`${prefix ?? ""}${path}`),
2318
2379
  url
2319
2380
  ).href
2320
2381
  };