remote-components 0.3.1 → 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 (64) 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 +390 -353
  4. package/dist/host/html.cjs.map +1 -1
  5. package/dist/host/html.js +390 -353
  6. package/dist/host/html.js.map +1 -1
  7. package/dist/host/nextjs/app/client-only.cjs +453 -435
  8. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  9. package/dist/host/nextjs/app/client-only.js +461 -443
  10. package/dist/host/nextjs/app/client-only.js.map +1 -1
  11. package/dist/host/react.cjs +381 -362
  12. package/dist/host/react.cjs.map +1 -1
  13. package/dist/host/react.js +381 -362
  14. package/dist/host/react.js.map +1 -1
  15. package/dist/internal/host/nextjs/image-shared.cjs +2 -2
  16. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  17. package/dist/internal/host/nextjs/image-shared.js +2 -2
  18. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  19. package/dist/internal/host/server/fetch-remote-component.cjs +20 -1
  20. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  21. package/dist/internal/host/server/fetch-remote-component.js +20 -1
  22. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  23. package/dist/internal/host/shared/remote-image-loader.cjs +2 -5
  24. package/dist/internal/host/shared/remote-image-loader.cjs.map +1 -1
  25. package/dist/internal/host/shared/remote-image-loader.js +2 -5
  26. package/dist/internal/host/shared/remote-image-loader.js.map +1 -1
  27. package/dist/internal/runtime/turbopack/chunk-loader.cjs +76 -126
  28. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  29. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +22 -7
  30. package/dist/internal/runtime/turbopack/chunk-loader.js +85 -131
  31. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  32. package/dist/internal/runtime/turbopack/module.cjs +56 -57
  33. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  34. package/dist/internal/runtime/turbopack/module.d.ts +14 -11
  35. package/dist/internal/runtime/turbopack/module.js +54 -56
  36. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  37. package/dist/internal/runtime/turbopack/remote-scope.cjs +101 -0
  38. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -0
  39. package/dist/internal/runtime/turbopack/remote-scope.d.ts +55 -0
  40. package/dist/internal/runtime/turbopack/remote-scope.js +73 -0
  41. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -0
  42. package/dist/internal/runtime/turbopack/shared-modules.cjs +62 -56
  43. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  44. package/dist/internal/runtime/turbopack/shared-modules.d.ts +7 -3
  45. package/dist/internal/runtime/turbopack/shared-modules.js +63 -57
  46. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  47. package/dist/internal/runtime/turbopack/webpack-runtime.cjs +39 -29
  48. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +1 -1
  49. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +5 -2
  50. package/dist/internal/runtime/turbopack/webpack-runtime.js +42 -32
  51. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +1 -1
  52. package/dist/internal/runtime/types.cjs.map +1 -1
  53. package/dist/internal/runtime/types.d.ts +4 -3
  54. package/dist/internal/utils/logger.cjs.map +1 -1
  55. package/dist/internal/utils/logger.d.ts +1 -1
  56. package/dist/internal/utils/logger.js.map +1 -1
  57. package/dist/internal/utils.cjs +5 -0
  58. package/dist/internal/utils.cjs.map +1 -1
  59. package/dist/internal/utils.d.ts +15 -1
  60. package/dist/internal/utils.js +4 -0
  61. package/dist/internal/utils.js.map +1 -1
  62. package/dist/remote/html.cjs.map +1 -1
  63. package/dist/remote/html.js.map +1 -1
  64. package/package.json +1 -1
@@ -237,11 +237,104 @@ function getClientOrServerUrl(src, serverFallback) {
237
237
  return typeof src === "string" ? new URL(src, fallback) : src;
238
238
  }
239
239
 
240
- // src/host/shared/remote-image-loader.ts
241
- function getRemoteBundleOrigin(bundle) {
240
+ // src/utils/index.ts
241
+ function escapeString(str) {
242
+ return str.replace(/[^a-z0-9]/g, "_");
243
+ }
244
+ function computeScopedName(name, options) {
245
+ return options.isCrossOrigin ? `${name}_${escapeString(options.remoteHost.toLowerCase())}` : name;
246
+ }
247
+ var attrToProp = {
248
+ fetchpriority: "fetchPriority",
249
+ crossorigin: "crossOrigin",
250
+ imagesrcset: "imageSrcSet",
251
+ imagesizes: "imageSizes",
252
+ srcset: "srcSet"
253
+ };
254
+
255
+ // src/runtime/constants.ts
256
+ var DEFAULT_BUNDLE_NAME = "__vercel_remote_bundle";
257
+ var DEFAULT_COMPONENT_NAME = "__vercel_remote_component";
258
+ var DEFAULT_ROUTE = "/";
259
+ var RUNTIME_WEBPACK = "webpack";
260
+ var RUNTIME_TURBOPACK = "turbopack";
261
+ var RUNTIME_SCRIPT = "script";
262
+ function getBundleKey(bundle) {
263
+ return escapeString(bundle);
264
+ }
265
+
266
+ // src/runtime/patterns.ts
267
+ var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
268
+ var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
269
+ var DOUBLE_SLASH_RE = /(?<!:)\/\//g;
270
+ function collapseDoubleSlashes(path) {
271
+ return path.replace(DOUBLE_SLASH_RE, "/");
272
+ }
273
+
274
+ // src/runtime/turbopack/remote-scope.ts
275
+ function getRegistry() {
242
276
  const self = globalThis;
243
- return self.__remote_bundle_url__?.[bundle]?.origin ?? "";
277
+ if (!self.__remote_component_scopes__) {
278
+ self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
279
+ }
280
+ return self.__remote_component_scopes__;
281
+ }
282
+ function createScope(name, url, runtime, resolveClientUrl) {
283
+ const isCrossOrigin = url.origin !== location.origin;
284
+ const scopedName = computeScopedName(name, {
285
+ remoteHost: url.host,
286
+ isCrossOrigin
287
+ });
288
+ const globalKey = getBundleKey(scopedName);
289
+ return {
290
+ name,
291
+ scopedName,
292
+ globalKey,
293
+ url,
294
+ runtime,
295
+ resolveClientUrl,
296
+ moduleCache: {},
297
+ sharedModules: {},
298
+ moduleGlobal: {}
299
+ };
244
300
  }
301
+ function registerScope(scope) {
302
+ const registry = getRegistry();
303
+ registry.set(scope.scopedName, scope);
304
+ if (scope.scopedName !== scope.name) {
305
+ const existing = registry.get(scope.name);
306
+ if (existing && existing.scopedName !== scope.scopedName) {
307
+ logWarn(
308
+ "RemoteScope",
309
+ `Plain name "${scope.name}" already registered by scope "${existing.scopedName}" \u2014 overwriting with "${scope.scopedName}". Static hosts will only resolve the latest one.`
310
+ );
311
+ }
312
+ registry.set(scope.name, scope);
313
+ }
314
+ logDebug(
315
+ "RemoteScope",
316
+ `Registered scope "${scope.scopedName}" (${registry.size} total)`
317
+ );
318
+ }
319
+ function getScope(name) {
320
+ return getRegistry().get(name);
321
+ }
322
+ function formatRemoteId(scope, path) {
323
+ return `[${scope.scopedName}] ${path}`;
324
+ }
325
+ function parseRemoteId(id) {
326
+ const groups = REMOTE_COMPONENT_REGEX.exec(id)?.groups;
327
+ if (groups?.bundle && groups.id) {
328
+ return {
329
+ bundle: groups.bundle,
330
+ path: groups.id,
331
+ prefix: groups.prefix ?? ""
332
+ };
333
+ }
334
+ return { bundle: "default", path: id, prefix: "" };
335
+ }
336
+
337
+ // src/host/shared/remote-image-loader.ts
245
338
  function createRemoteImageLoader(bundle, resolveClientUrl) {
246
339
  const loader = Object.assign(
247
340
  ({
@@ -251,7 +344,7 @@ function createRemoteImageLoader(bundle, resolveClientUrl) {
251
344
  quality
252
345
  }) => {
253
346
  const q = quality ?? 75;
254
- const remoteOrigin = getRemoteBundleOrigin(bundle);
347
+ const remoteOrigin = getScope(bundle)?.url.origin ?? "";
255
348
  const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;
256
349
  const basePath = isCrossOrigin ? `${remoteOrigin}${config.path ?? "/_next/image"}` : config.path ?? `${remoteOrigin}/_next/image`;
257
350
  const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;
@@ -433,29 +526,6 @@ function resolveNameFromSrc(src, defaultName) {
433
526
  return name || defaultName;
434
527
  }
435
528
 
436
- // src/utils/index.ts
437
- function escapeString(str) {
438
- return str.replace(/[^a-z0-9]/g, "_");
439
- }
440
- var attrToProp = {
441
- fetchpriority: "fetchPriority",
442
- crossorigin: "crossOrigin",
443
- imagesrcset: "imageSrcSet",
444
- imagesizes: "imageSizes",
445
- srcset: "srcSet"
446
- };
447
-
448
- // src/runtime/constants.ts
449
- var DEFAULT_BUNDLE_NAME = "__vercel_remote_bundle";
450
- var DEFAULT_COMPONENT_NAME = "__vercel_remote_component";
451
- var DEFAULT_ROUTE = "/";
452
- var RUNTIME_WEBPACK = "webpack";
453
- var RUNTIME_TURBOPACK = "turbopack";
454
- var RUNTIME_SCRIPT = "script";
455
- function getBundleKey(bundle) {
456
- return escapeString(bundle);
457
- }
458
-
459
529
  // src/runtime/html/apply-origin.ts
460
530
  var tagNames = [
461
531
  "img",
@@ -930,14 +1000,6 @@ function createRSCStream(rscName, data) {
930
1000
  });
931
1001
  }
932
1002
 
933
- // src/runtime/patterns.ts
934
- var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
935
- var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
936
- var DOUBLE_SLASH_RE = /(?<!:)\/\//g;
937
- function collapseDoubleSlashes(path) {
938
- return path.replace(DOUBLE_SLASH_RE, "/");
939
- }
940
-
941
1003
  // src/runtime/turbopack/patterns.ts
942
1004
  var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
943
1005
  var REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
@@ -947,62 +1009,39 @@ var ASYNC_MODULE_ALL_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<vCb
947
1009
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
948
1010
 
949
1011
  // src/runtime/turbopack/chunk-loader.ts
950
- function createChunkLoader(runtime, resolveClientUrl) {
951
- return function __turbopack_chunk_load__(chunkId, scriptBundle) {
952
- logDebug("ChunkLoader", `Loading chunk: "${chunkId}"`);
953
- const self = globalThis;
954
- const {
955
- bundle,
956
- id: path,
957
- prefix
958
- } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {
959
- bundle: scriptBundle ?? "",
960
- id: chunkId
961
- };
962
- logDebug(
963
- "ChunkLoader",
964
- `Parsed chunk - bundle: "${bundle}", path: "${path}", prefix: "${prefix}"`
965
- );
966
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
967
- logDebug("ChunkLoader", `Remote runtime: "${remoteRuntime}"`);
968
- if (remoteRuntime === RUNTIME_WEBPACK) {
969
- logDebug("ChunkLoader", "Skipping chunk load - webpack runtime detected");
970
- return Promise.resolve(void 0);
971
- }
972
- const url = new URL(
973
- path ? `${prefix ?? ""}${path}`.replace(
974
- /(?<char>[^:])(?<double>\/\/)/g,
975
- "$1/"
976
- ) : "/",
977
- self.__remote_bundle_url__?.[bundle ?? "default"] ?? new URL(location.origin)
978
- ).href;
979
- if (url.endsWith(".css")) {
980
- logDebug("ChunkLoader", `Skipping CSS file: "${url}"`);
981
- return;
982
- }
983
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
984
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
985
- }
986
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
987
- logDebug("ChunkLoader", `Returning cached promise for: "${url}"`);
988
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
989
- }
990
- const resolvedUrl = resolveClientUrl?.(url) ?? url;
991
- logDebug("ChunkLoader", `Fetching chunk from: "${resolvedUrl}"`);
992
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise((resolve, reject) => {
1012
+ function loadChunkWithScope(scope, chunkId) {
1013
+ logDebug(
1014
+ "ChunkLoader",
1015
+ `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
1016
+ );
1017
+ const self = globalThis;
1018
+ const { bundle, path, prefix } = parseRemoteId(chunkId);
1019
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
1020
+ if (remoteRuntime === RUNTIME_WEBPACK) {
1021
+ return Promise.resolve(void 0);
1022
+ }
1023
+ const rawPath = path ? collapseDoubleSlashes(`${prefix}${path}`) : "/";
1024
+ const url = new URL(rawPath, scope.url).href;
1025
+ if (url.endsWith(".css")) {
1026
+ return;
1027
+ }
1028
+ if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1029
+ self.__remote_components_turbopack_chunk_loader_promise__ = {};
1030
+ }
1031
+ if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1032
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
1033
+ }
1034
+ const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1035
+ if (resolvedUrl !== url) {
1036
+ logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1037
+ }
1038
+ self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1039
+ (resolve, reject) => {
993
1040
  fetch(resolvedUrl).then((res) => res.text()).then((code) => {
994
1041
  const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
995
1042
  if (hasTurbopack) {
996
- return handleTurbopackChunk(code, bundle ?? "", url);
1043
+ return handleTurbopackChunk(code, scope, url);
997
1044
  }
998
- logDebug(
999
- "ChunkLoader",
1000
- `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: "${url}"`
1001
- );
1002
- logDebug(
1003
- "ChunkLoader",
1004
- `First 500 chars of chunk: ${code.slice(0, 500)}`
1005
- );
1006
1045
  }).then(resolve).catch((error) => {
1007
1046
  const isProxied = isProxiedUrl(resolvedUrl);
1008
1047
  if (isProxied) {
@@ -1012,17 +1051,29 @@ function createChunkLoader(runtime, resolveClientUrl) {
1012
1051
  reject(error);
1013
1052
  }
1014
1053
  });
1015
- });
1016
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1054
+ }
1055
+ );
1056
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
1057
+ }
1058
+ function createChunkDispatcher() {
1059
+ return function __chunk_dispatcher__(chunkId, scriptBundle) {
1060
+ logDebug("ChunkDispatcher", `Dispatching chunk: "${chunkId}"`);
1061
+ const { bundle } = parseRemoteId(chunkId);
1062
+ const bundleName = bundle || scriptBundle || "default";
1063
+ const scope = getScope(bundleName);
1064
+ logDebug(
1065
+ "ChunkDispatcher",
1066
+ `Scope resolution: bundle="${bundleName}", scope=${scope?.scopedName ?? "null"}`
1067
+ );
1068
+ if (!scope) {
1069
+ logWarn("ChunkDispatcher", `No scope found for bundle "${bundleName}"`);
1070
+ return Promise.resolve(void 0);
1071
+ }
1072
+ return loadChunkWithScope(scope, chunkId);
1017
1073
  };
1018
1074
  }
1019
- async function handleTurbopackChunk(code, bundle, url) {
1020
- logDebug(
1021
- "ChunkLoader",
1022
- `Handling Turbopack chunk - bundle: "${bundle}", url: "${url}"`
1023
- );
1075
+ async function handleTurbopackChunk(code, scope, url) {
1024
1076
  if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
1025
- logDebug("ChunkLoader", `Skipping worker chunk: "${url}"`);
1026
1077
  const preloadLinks = document.querySelectorAll(
1027
1078
  `link[rel="preload"][href="${new URL(url).pathname}"]`
1028
1079
  );
@@ -1030,58 +1081,41 @@ async function handleTurbopackChunk(code, bundle, url) {
1030
1081
  return;
1031
1082
  }
1032
1083
  const self = globalThis;
1033
- const bundleKey = getBundleKey(bundle);
1034
- logDebug("ChunkLoader", `Bundle key: "${bundleKey}"`);
1084
+ const { globalKey } = scope;
1035
1085
  const transformedCode = code.replace(
1036
1086
  /globalThis\[\s*["']TURBOPACK["']\s*\]/g,
1037
- `globalThis["TURBOPACK_${bundleKey}"]`
1087
+ `globalThis["TURBOPACK_${globalKey}"]`
1038
1088
  ).replace(
1039
1089
  /self\[\s*["']TURBOPACK["']\s*\]/g,
1040
- `self["TURBOPACK_${bundleKey}"]`
1041
- ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`).replace(
1090
+ `self["TURBOPACK_${globalKey}"]`
1091
+ ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`).replace(
1042
1092
  /TURBOPACK_WORKER_LOCATION/g,
1043
- `TURBOPACK_WORKER_LOCATION_${bundleKey}`
1093
+ `TURBOPACK_WORKER_LOCATION_${globalKey}`
1044
1094
  ).replace(
1045
1095
  /TURBOPACK_NEXT_CHUNK_URLS/g,
1046
- `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
1096
+ `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`
1047
1097
  ).replace(
1048
1098
  /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
1049
- `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
1050
- ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
1099
+ `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`
1100
+ ).replace(/__next_require__/g, `__${globalKey}_next_require__`).replace(
1051
1101
  /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
1052
- `//# sourceMappingURL=${new URL(
1053
- ".",
1054
- new URL(
1055
- url,
1056
- self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin)
1057
- )
1058
- ).href}$1$2.js.map`
1102
+ `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1059
1103
  );
1060
- if (!self[`TURBOPACK_${bundleKey}`]) {
1104
+ if (!self[`TURBOPACK_${globalKey}`]) {
1061
1105
  const chunkData = [];
1062
1106
  const turbopackObject = {
1063
1107
  push: (item) => {
1064
- logDebug(
1065
- "ChunkLoader",
1066
- `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? "array" : typeof item}`
1067
- );
1068
1108
  if (Array.isArray(item)) {
1069
1109
  chunkData.push(item);
1070
- logDebug(
1071
- "ChunkLoader",
1072
- `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`
1073
- );
1074
1110
  } else {
1075
1111
  chunkData.push([item]);
1076
1112
  }
1077
1113
  return chunkData.length;
1078
1114
  },
1079
- // Store chunks for later access
1080
1115
  __chunks__: chunkData
1081
1116
  };
1082
- self[`TURBOPACK_${bundleKey}`] = turbopackObject;
1117
+ self[`TURBOPACK_${globalKey}`] = turbopackObject;
1083
1118
  }
1084
- logDebug("ChunkLoader", `Creating blob script for: "${url}"`);
1085
1119
  await new Promise((scriptResolve, scriptReject) => {
1086
1120
  const blob = new Blob([transformedCode], {
1087
1121
  type: "application/javascript; charset=UTF-8"
@@ -1093,21 +1127,6 @@ async function handleTurbopackChunk(code, bundle, url) {
1093
1127
  script.async = true;
1094
1128
  script.onload = () => {
1095
1129
  URL.revokeObjectURL(scriptUrl);
1096
- logDebug(
1097
- "ChunkLoader",
1098
- `Script loaded successfully for bundle "${bundle}"`
1099
- );
1100
- const turbopackBundle = self[`TURBOPACK_${bundleKey}`];
1101
- logDebug(
1102
- "ChunkLoader",
1103
- `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${turbopackBundle ? Object.keys(turbopackBundle).slice(0, 10).join(", ") : "none"}`
1104
- );
1105
- if (turbopackBundle && typeof turbopackBundle === "object") {
1106
- logDebug(
1107
- "ChunkLoader",
1108
- `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle).length}`
1109
- );
1110
- }
1111
1130
  scriptResolve(void 0);
1112
1131
  script.remove();
1113
1132
  };
@@ -1122,43 +1141,177 @@ async function handleTurbopackChunk(code, bundle, url) {
1122
1141
  };
1123
1142
  document.head.appendChild(script);
1124
1143
  });
1125
- const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`];
1126
- logDebug(
1127
- "ChunkLoader",
1128
- `Processing chunk lists for bundle "${bundle}": ${chunkLists?.length ?? 0} lists`
1129
- );
1130
- const loadChunkLists = [];
1144
+ const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`];
1145
+ const loadChunkPromises = [];
1131
1146
  while (chunkLists?.length) {
1132
1147
  const { chunks } = chunkLists.shift() ?? { chunks: [] };
1133
1148
  if (chunks.length > 0) {
1134
- logDebug(
1135
- "ChunkLoader",
1136
- `Loading ${chunks.length} additional chunks for bundle "${bundle}": [${chunks.join(", ")}]`
1137
- );
1138
- chunks.forEach((id) => {
1139
- const chunkLoadResult = self.__webpack_chunk_load__?.(
1140
- `[${bundle}] ${url.slice(0, url.indexOf("/_next"))}/_next/${id}`
1149
+ for (const id of chunks) {
1150
+ const baseUrl = url.slice(0, url.indexOf("/_next"));
1151
+ const chunkLoadResult = loadChunkWithScope(
1152
+ scope,
1153
+ formatRemoteId(scope, `${baseUrl}/_next/${id}`)
1141
1154
  );
1142
1155
  if (chunkLoadResult) {
1143
- loadChunkLists.push(chunkLoadResult);
1156
+ loadChunkPromises.push(chunkLoadResult);
1144
1157
  }
1145
- });
1158
+ }
1146
1159
  }
1147
1160
  }
1148
- if (loadChunkLists.length > 0) {
1149
- logDebug(
1150
- "ChunkLoader",
1151
- `Waiting for ${loadChunkLists.length} additional chunks to load`
1161
+ if (loadChunkPromises.length > 0) {
1162
+ await Promise.all(loadChunkPromises);
1163
+ }
1164
+ }
1165
+
1166
+ // src/runtime/turbopack/shared-modules.ts
1167
+ var DEDUPLICATION_WARNING = "This module will not be deduplicated \u2014 the remote may load its own copy, which can cause duplicate instance errors (e.g. invalid hook calls if React is loaded twice).";
1168
+ function getTurbopackModules(scope) {
1169
+ const self = globalThis;
1170
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1171
+ if (!raw)
1172
+ return void 0;
1173
+ if (typeof raw === "object" && "__chunks__" in raw) {
1174
+ return raw.__chunks__.flat();
1175
+ }
1176
+ if (Array.isArray(raw)) {
1177
+ return raw.flat();
1178
+ }
1179
+ return Object.entries(raw).flat();
1180
+ }
1181
+ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}) {
1182
+ const allModules = getTurbopackModules(scope);
1183
+ logDebug(
1184
+ "SharedModules",
1185
+ `initializeSharedModules: scope="${scope.scopedName}", allModules=${allModules ? allModules.length : "null"}, hostShared=[${Object.keys(hostShared).join(", ")}], remoteShared=${JSON.stringify(remoteShared)}`
1186
+ );
1187
+ let sharedModuleInitializer = null;
1188
+ if (allModules) {
1189
+ const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1190
+ if (typeof idOrFunc !== "function") {
1191
+ return false;
1192
+ }
1193
+ const funcCode = idOrFunc.toString();
1194
+ return REMOTE_SHARED_MARKER_RE.test(funcCode);
1195
+ });
1196
+ if (sharedModuleInitializerIndex > 0) {
1197
+ const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1198
+ const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1199
+ const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1200
+ if (sharedModuleId) {
1201
+ const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1202
+ scope,
1203
+ sharedModuleId,
1204
+ formatRemoteId(scope, String(sharedModuleInitializerId))
1205
+ );
1206
+ sharedModuleInitializer = sharedModuleInitializerInstance;
1207
+ }
1208
+ }
1209
+ if (sharedModuleInitializer) {
1210
+ const { shared } = await sharedModuleInitializer;
1211
+ const sharedModuleIds = extractSharedModuleIds(shared, scope);
1212
+ logDebug(
1213
+ "SharedModules",
1214
+ `Resolved shared modules for scope="${scope.scopedName}": ${JSON.stringify(sharedModuleIds)}`
1215
+ );
1216
+ return Promise.all(
1217
+ Object.entries(sharedModuleIds).map(async ([id, module2]) => {
1218
+ if (hostShared[module2]) {
1219
+ scope.sharedModules[id] = await hostShared[module2](scope.name);
1220
+ } else {
1221
+ logError(
1222
+ "SharedModules",
1223
+ `Host shared module "${module2}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1224
+ );
1225
+ }
1226
+ })
1227
+ );
1228
+ }
1229
+ logWarn(
1230
+ "SharedModules",
1231
+ `No shared module initializer found in bundle for scope="${scope.scopedName}" \u2014 falling back to remoteShared mapping`
1232
+ );
1233
+ } else {
1234
+ logWarn(
1235
+ "SharedModules",
1236
+ `No TURBOPACK modules found for scope="${scope.scopedName}" (TURBOPACK_${scope.globalKey} is empty)`
1152
1237
  );
1153
- await Promise.all(loadChunkLists);
1154
1238
  }
1239
+ return Promise.all(
1240
+ Object.entries(remoteShared).map(async ([id, module2]) => {
1241
+ if (hostShared[module2]) {
1242
+ const normalizedId = id.replace("[app-ssr]", "[app-client]");
1243
+ scope.sharedModules[normalizedId] = await hostShared[module2](
1244
+ scope.name
1245
+ );
1246
+ } else {
1247
+ logError(
1248
+ "SharedModules",
1249
+ `Shared module "${module2}" not found for "${scope.name}". ${DEDUPLICATION_WARNING}`
1250
+ );
1251
+ }
1252
+ })
1253
+ );
1254
+ }
1255
+ function extractSharedModuleIds(shared, scope) {
1256
+ return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1257
+ const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1258
+ if (asyncSharedModuleId) {
1259
+ const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1260
+ let asyncSharedModule;
1261
+ const turbopackModules = getTurbopackModules(scope) ?? [];
1262
+ const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1263
+ asyncSharedModuleIdNumber
1264
+ );
1265
+ if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1266
+ asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1267
+ }
1268
+ if (asyncSharedModule) {
1269
+ const asyncSharedModuleCode = asyncSharedModule.toString();
1270
+ const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1271
+ acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1272
+ "__remote_shared_module_",
1273
+ ""
1274
+ );
1275
+ }
1276
+ }
1277
+ return acc;
1278
+ }, {});
1279
+ }
1280
+ function getSharedModule(scope, id) {
1281
+ const idStr = String(id);
1282
+ if (scope.sharedModules[idStr] !== void 0) {
1283
+ return scope.sharedModules[idStr];
1284
+ }
1285
+ for (const [key, value] of Object.entries(scope.sharedModules)) {
1286
+ if (typeof value !== "undefined" && idStr !== key && idStr.endsWith(key)) {
1287
+ return value;
1288
+ }
1289
+ }
1290
+ return null;
1155
1291
  }
1156
1292
 
1157
1293
  // src/runtime/turbopack/module.ts
1158
- function handleTurbopackModule(bundle, moduleId, id) {
1294
+ function requireModule(scope, moduleId, fullId) {
1295
+ const idStr = String(moduleId);
1296
+ if (scope.moduleCache[idStr])
1297
+ return scope.moduleCache[idStr];
1298
+ const sharedModule = getSharedModule(scope, moduleId);
1299
+ if (sharedModule) {
1300
+ scope.moduleCache[idStr] = sharedModule;
1301
+ return sharedModule;
1302
+ }
1303
+ return handleTurbopackModule(
1304
+ scope,
1305
+ idStr,
1306
+ fullId ?? formatRemoteId(scope, idStr)
1307
+ );
1308
+ }
1309
+ function handleTurbopackModule(scope, moduleId, id) {
1159
1310
  const self = globalThis;
1160
- const bundleKey = getBundleKey(bundle);
1161
- const raw = self[`TURBOPACK_${bundleKey}`];
1311
+ if (scope.moduleCache[moduleId]) {
1312
+ return scope.moduleCache[moduleId];
1313
+ }
1314
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1162
1315
  let modules;
1163
1316
  if (raw && typeof raw === "object" && "__chunks__" in raw) {
1164
1317
  modules = raw.__chunks__.flat();
@@ -1167,48 +1320,35 @@ function handleTurbopackModule(bundle, moduleId, id) {
1167
1320
  } else {
1168
1321
  modules = raw;
1169
1322
  }
1170
- if (!self.__remote_components_turbopack_modules__) {
1171
- self.__remote_components_turbopack_modules__ = {};
1172
- }
1173
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1174
- self.__remote_components_turbopack_modules__[bundle] = {};
1175
- }
1176
- if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
1177
- return self.__remote_components_turbopack_modules__[bundle][moduleId];
1178
- }
1179
1323
  if (!modules) {
1180
- logError("TurbopackModule", `TURBOPACK_${bundleKey} is undefined`);
1324
+ logError(
1325
+ "TurbopackModule",
1326
+ `TURBOPACK_${scope.globalKey} is undefined (scope: "${scope.scopedName}")`
1327
+ );
1181
1328
  }
1182
1329
  const moduleInit = findModuleInit(modules, moduleId);
1183
1330
  const exports = {};
1184
1331
  const moduleExports = { exports };
1185
1332
  if (typeof moduleInit !== "function") {
1186
1333
  throw new Error(
1187
- `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
1334
+ `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`
1188
1335
  );
1189
1336
  }
1190
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1191
- if (!self.__remote_components_turbopack_global__) {
1192
- self.__remote_components_turbopack_global__ = {};
1193
- }
1194
- if (!self.__remote_components_turbopack_global__[bundle]) {
1195
- self.__remote_components_turbopack_global__[bundle] = {};
1196
- }
1337
+ scope.moduleCache[moduleId] = moduleExports.exports;
1197
1338
  moduleInit(
1198
1339
  createTurbopackContext(
1199
- bundle,
1340
+ scope,
1200
1341
  exports,
1201
1342
  moduleExports,
1202
1343
  modules,
1203
1344
  moduleInit,
1204
- id,
1205
- self
1345
+ id
1206
1346
  ),
1207
1347
  moduleExports,
1208
1348
  exports
1209
1349
  );
1210
- if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
1211
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1350
+ if (scope.moduleCache[moduleId] !== moduleExports.exports) {
1351
+ scope.moduleCache[moduleId] = moduleExports.exports;
1212
1352
  }
1213
1353
  return moduleExports.exports;
1214
1354
  }
@@ -1233,7 +1373,8 @@ function findModuleInit(modules, moduleId) {
1233
1373
  (e) => Boolean(e && typeof e === "object" && moduleId in e)
1234
1374
  )?.[moduleId];
1235
1375
  }
1236
- function createTurbopackContext(bundle, exports, moduleExports, modules, moduleInit, id, self) {
1376
+ function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1377
+ const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
1237
1378
  return {
1238
1379
  // HMR not implemented for Remote Components
1239
1380
  k: {
@@ -1249,16 +1390,10 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1249
1390
  s(bindings, esmId) {
1250
1391
  let mod = exports;
1251
1392
  if (typeof esmId === "string" || typeof esmId === "number") {
1252
- if (!self.__remote_components_turbopack_modules__) {
1253
- self.__remote_components_turbopack_modules__ = {};
1254
- }
1255
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1256
- self.__remote_components_turbopack_modules__[bundle] = {};
1393
+ if (!scope.moduleCache[esmId]) {
1394
+ scope.moduleCache[esmId] = {};
1257
1395
  }
1258
- if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
1259
- self.__remote_components_turbopack_modules__[bundle][esmId] = {};
1260
- }
1261
- mod = self.__remote_components_turbopack_modules__[bundle][esmId];
1396
+ mod = scope.moduleCache[esmId];
1262
1397
  }
1263
1398
  Object.defineProperty(mod, "__esModule", { value: true });
1264
1399
  if (Array.isArray(bindings)) {
@@ -1291,7 +1426,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1291
1426
  }
1292
1427
  }
1293
1428
  },
1294
- // import
1429
+ // import — resolves directly via scope, no global dispatch
1295
1430
  i(importId) {
1296
1431
  let mod;
1297
1432
  if (typeof importId === "string") {
@@ -1302,7 +1437,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1302
1437
  /\s+<export(?<specifier>.*)>$/,
1303
1438
  ""
1304
1439
  );
1305
- mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`);
1440
+ mod = scopedRequire(normalizedId);
1306
1441
  if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
1307
1442
  if (exportSource === "*") {
1308
1443
  mod[exportName] = mod;
@@ -1311,7 +1446,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1311
1446
  }
1312
1447
  }
1313
1448
  } else {
1314
- mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
1449
+ mod = scopedRequire(importId);
1315
1450
  }
1316
1451
  if (typeof mod !== "object" || mod === null) {
1317
1452
  mod = { default: mod };
@@ -1323,16 +1458,14 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1323
1458
  }
1324
1459
  return mod;
1325
1460
  },
1326
- // require
1461
+ // require — resolves directly via scope
1327
1462
  r(requireId) {
1328
- return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
1463
+ return scopedRequire(requireId);
1329
1464
  },
1330
1465
  // value exports
1331
1466
  v(value) {
1332
1467
  if (typeof value === "function") {
1333
- exports.default = value((vid) => {
1334
- return self.__webpack_require__?.(`[${bundle}] ${vid}`);
1335
- });
1468
+ exports.default = value((vid) => scopedRequire(vid));
1336
1469
  } else {
1337
1470
  moduleExports.exports = value;
1338
1471
  }
@@ -1347,17 +1480,15 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1347
1480
  );
1348
1481
  exports.default = result;
1349
1482
  },
1350
- // async module loader
1483
+ // async module loader — resolves directly via scope
1351
1484
  async A(Aid) {
1352
- const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
1353
- return mod.default(
1354
- (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
1355
- );
1485
+ const mod = scopedRequire(Aid);
1486
+ return mod.default((parentId) => scopedRequire(parentId));
1356
1487
  },
1357
1488
  // dynamic import tracking — no-op for remote components
1358
1489
  j() {
1359
1490
  },
1360
- // chunk loader
1491
+ // chunk loader — loads directly via scope, no global dispatch
1361
1492
  l(url) {
1362
1493
  const flatModules = Array.isArray(modules) ? modules : [];
1363
1494
  const moduleInitIndex = flatModules.indexOf(moduleInit);
@@ -1368,169 +1499,57 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1368
1499
  const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1369
1500
  const nextIndex = scriptSrc.indexOf("/_next");
1370
1501
  const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1371
- const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
1372
- return self.__webpack_chunk_load__?.(bundleUrl, bundle);
1502
+ const chunkUrl = `${baseUrl}/_next/${url}`;
1503
+ return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));
1373
1504
  }
1374
1505
  }
1375
1506
  throw new Error(
1376
1507
  `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1377
1508
  );
1378
1509
  },
1379
- // global object for this bundle
1380
- g: self.__remote_components_turbopack_global__?.[bundle],
1510
+ // globalThis substitute shared across all modules in this scope
1511
+ g: scope.moduleGlobal,
1381
1512
  m: moduleExports,
1382
1513
  e: exports
1383
1514
  };
1384
1515
  }
1385
1516
 
1386
- // src/runtime/turbopack/shared-modules.ts
1387
- 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).";
1388
- async function initializeSharedModules(bundle, hostShared = {}, remoteShared = {}) {
1389
- const self = globalThis;
1390
- self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};
1391
- if (!self.__remote_shared_modules__[bundle]) {
1392
- self.__remote_shared_modules__[bundle] = {};
1393
- }
1394
- const bundleKey = getBundleKey(bundle);
1395
- let modules = self[`TURBOPACK_${bundleKey}`];
1396
- if (modules && typeof modules === "object" && "__chunks__" in modules) {
1397
- const chunks = modules.__chunks__;
1398
- modules = chunks.flat();
1399
- }
1400
- let sharedModuleInitializer = null;
1401
- if (modules) {
1402
- const allModules = Array.isArray(modules) ? modules.flat() : Object.entries(modules).flat();
1403
- const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1404
- if (typeof idOrFunc !== "function") {
1405
- return false;
1406
- }
1407
- const funcCode = idOrFunc.toString();
1408
- return REMOTE_SHARED_MARKER_RE.test(funcCode);
1409
- });
1410
- if (sharedModuleInitializerIndex > 0) {
1411
- const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1412
- const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1413
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1414
- if (sharedModuleId) {
1415
- const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1416
- bundle,
1417
- sharedModuleId,
1418
- `[${bundle}] ${sharedModuleInitializerId}`
1419
- );
1420
- sharedModuleInitializer = sharedModuleInitializerInstance;
1421
- }
1422
- }
1423
- if (sharedModuleInitializer) {
1424
- const { shared } = await sharedModuleInitializer;
1425
- const sharedModuleIds = extractSharedModuleIds(
1426
- shared,
1427
- bundleKey,
1428
- self
1429
- );
1430
- return Promise.all(
1431
- Object.entries(sharedModuleIds).map(async ([id, module2]) => {
1432
- if (self.__remote_shared_modules__?.[bundle]) {
1433
- if (hostShared[module2]) {
1434
- self.__remote_shared_modules__[bundle][id] = await hostShared[module2](bundle);
1435
- } else {
1436
- logError(
1437
- "SharedModules",
1438
- `Host shared module "${module2}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1439
- );
1440
- }
1441
- }
1442
- })
1443
- );
1444
- }
1445
- }
1446
- return Promise.all(
1447
- Object.entries(remoteShared).map(async ([id, module2]) => {
1448
- if (self.__remote_shared_modules__?.[bundle]) {
1449
- if (hostShared[module2]) {
1450
- const normalizedId = id.replace("[app-ssr]", "[app-client]");
1451
- self.__remote_shared_modules__[bundle][normalizedId] = await hostShared[module2](bundle);
1452
- } else {
1453
- logError(
1454
- "SharedModules",
1455
- `Shared module "${module2}" not found for "${bundle}". ${DEDUPLICATION_WARNING}`
1456
- );
1457
- }
1458
- }
1459
- })
1460
- );
1461
- }
1462
- function extractSharedModuleIds(shared, bundleKey, self) {
1463
- return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1464
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1465
- if (asyncSharedModuleId) {
1466
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1467
- let asyncSharedModule;
1468
- let turbopackModules = self[`TURBOPACK_${bundleKey}`];
1469
- if (turbopackModules && typeof turbopackModules === "object" && "__chunks__" in turbopackModules) {
1470
- const chunks = turbopackModules.__chunks__;
1471
- turbopackModules = chunks.flat();
1472
- }
1473
- const newAllModules = Array.isArray(turbopackModules) ? turbopackModules.flat() : turbopackModules ? Object.entries(turbopackModules).flatMap(([key2, value2]) => [
1474
- key2,
1475
- value2
1476
- ]) : [];
1477
- const asyncSharedModuleIdIndex = newAllModules.indexOf(
1478
- asyncSharedModuleIdNumber
1479
- );
1480
- if (asyncSharedModuleIdIndex !== -1 && typeof newAllModules[asyncSharedModuleIdIndex + 1] === "function") {
1481
- asyncSharedModule = newAllModules[asyncSharedModuleIdIndex + 1];
1482
- }
1483
- if (asyncSharedModule) {
1484
- const asyncSharedModuleCode = asyncSharedModule.toString();
1485
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1486
- acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1487
- "__remote_shared_module_",
1488
- ""
1489
- );
1490
- }
1491
- }
1492
- return acc;
1493
- }, {});
1494
- }
1495
- function getSharedModule(bundle, id) {
1496
- const self = globalThis;
1497
- for (const [key, value] of Object.entries(
1498
- self.__remote_shared_modules__?.[bundle] ?? {}
1499
- )) {
1500
- if (typeof value !== "undefined" && (typeof id === "string" && id.includes(key) || id === key)) {
1501
- return value;
1502
- }
1503
- }
1504
- return null;
1505
- }
1506
-
1507
1517
  // src/runtime/turbopack/webpack-runtime.ts
1508
1518
  async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1509
1519
  const self = globalThis;
1520
+ const bundleName = bundle ?? "default";
1521
+ const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1522
+ registerScope(scope);
1510
1523
  if (!self.__remote_bundle_url__) {
1511
1524
  self.__remote_bundle_url__ = {};
1512
1525
  }
1513
- self.__remote_bundle_url__[bundle ?? "default"] = url;
1526
+ self.__remote_bundle_url__[bundleName] = url;
1527
+ if (scope.scopedName !== bundleName) {
1528
+ self.__remote_bundle_url__[scope.scopedName] = url;
1529
+ }
1514
1530
  self.__webpack_get_script_filename__ = () => null;
1515
- if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
1531
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1532
+ if (willCreateDispatchers) {
1516
1533
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1517
1534
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1518
1535
  self.__original_webpack_require__ = self.__webpack_require__;
1519
1536
  }
1520
- self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);
1521
- self.__webpack_require__ = createModuleRequire(runtime);
1537
+ self.__webpack_chunk_load__ = createChunkDispatcher();
1538
+ self.__webpack_require__ = createModuleDispatcher(runtime);
1522
1539
  self.__webpack_require_type__ = runtime;
1523
1540
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1524
- const remoteBundle = bundle ?? "default";
1525
- self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
1526
- self.__remote_webpack_require__[remoteBundle].type = "turbopack";
1541
+ self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
1542
+ self.__remote_webpack_require__[bundleName].type = "turbopack";
1527
1543
  }
1528
1544
  }
1545
+ if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
1546
+ self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
1547
+ }
1529
1548
  if (runtime === RUNTIME_TURBOPACK) {
1530
1549
  const results = await Promise.allSettled(
1531
1550
  scripts.map((script) => {
1532
1551
  if (script.src) {
1533
- return self.__webpack_chunk_load__?.(script.src, bundle);
1552
+ return loadChunkWithScope(scope, script.src);
1534
1553
  }
1535
1554
  return Promise.resolve(void 0);
1536
1555
  })
@@ -1552,54 +1571,54 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1552
1571
  "react-dom/client": async () => (await import("react-dom/client")).default,
1553
1572
  ...shared
1554
1573
  };
1555
- await initializeSharedModules(
1556
- bundle ?? "default",
1557
- // include all core modules as shared
1558
- coreShared,
1559
- remoteShared
1560
- );
1574
+ await initializeSharedModules(scope, coreShared, remoteShared);
1561
1575
  }
1562
- function createModuleRequire(runtime) {
1576
+ function createModuleDispatcher(runtime) {
1563
1577
  return (id) => {
1564
1578
  const self = globalThis;
1565
1579
  const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1566
1580
  bundle: "default",
1567
1581
  id
1568
1582
  };
1569
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1570
- logDebug("WebpackRuntime", `remoteRuntime: "${remoteRuntime}"`);
1583
+ const bundleName = bundle ?? "default";
1584
+ const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
1585
+ logDebug(
1586
+ "ModuleDispatcher",
1587
+ `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
1588
+ );
1571
1589
  try {
1572
1590
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1573
1591
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1574
1592
  }
1575
- const sharedModuleId = moduleId ?? id;
1576
- const sharedModule = getSharedModule(bundle ?? "default", sharedModuleId);
1577
- if (sharedModule) {
1578
- return sharedModule;
1593
+ const scope = getScope(bundleName);
1594
+ if (scope) {
1595
+ return requireModule(scope, moduleId ?? id, id);
1579
1596
  }
1580
- if (bundle && moduleId) {
1581
- return handleTurbopackModule(bundle, moduleId, id);
1582
- }
1583
- throw new Error(`Module "${id}" not found.`);
1597
+ throw new Error(
1598
+ `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
1599
+ );
1584
1600
  } catch (requireError) {
1585
1601
  logWarn(
1586
- "WebpackRuntime",
1602
+ "ModuleDispatcher",
1587
1603
  `Module require failed: ${String(requireError)}`
1588
1604
  );
1589
1605
  if (typeof self.__original_webpack_require__ !== "function") {
1590
1606
  throw new RemoteComponentsError(
1591
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1607
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1592
1608
  {
1593
1609
  cause: requireError instanceof Error ? requireError : void 0
1594
1610
  }
1595
1611
  );
1596
1612
  }
1597
1613
  try {
1598
- logDebug("WebpackRuntime", "Falling back to original webpack require");
1614
+ logDebug(
1615
+ "ModuleDispatcher",
1616
+ "Falling back to original webpack require"
1617
+ );
1599
1618
  return self.__original_webpack_require__(id);
1600
1619
  } catch (originalError) {
1601
1620
  throw new RemoteComponentsError(
1602
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1621
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1603
1622
  { cause: originalError instanceof Error ? originalError : void 0 }
1604
1623
  );
1605
1624
  }