remote-components 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/dist/config/nextjs.cjs +36 -25
  2. package/dist/config/nextjs.cjs.map +1 -1
  3. package/dist/config/nextjs.js +30 -19
  4. package/dist/config/nextjs.js.map +1 -1
  5. package/dist/host/defaults/app.cjs +2 -5
  6. package/dist/host/defaults/app.cjs.map +1 -1
  7. package/dist/host/defaults/app.d.ts +1 -3
  8. package/dist/host/defaults/app.js +1 -4
  9. package/dist/host/defaults/app.js.map +1 -1
  10. package/dist/host/defaults/pages.cjs +2 -5
  11. package/dist/host/defaults/pages.cjs.map +1 -1
  12. package/dist/host/defaults/pages.d.ts +1 -3
  13. package/dist/host/defaults/pages.js +1 -4
  14. package/dist/host/defaults/pages.js.map +1 -1
  15. package/dist/host/defaults/shared.cjs +32 -0
  16. package/dist/host/defaults/shared.cjs.map +1 -0
  17. package/dist/host/defaults/shared.d.ts +3 -0
  18. package/dist/host/defaults/shared.js +8 -0
  19. package/dist/host/defaults/shared.js.map +1 -0
  20. package/dist/host/html.cjs +390 -357
  21. package/dist/host/html.cjs.map +1 -1
  22. package/dist/host/html.js +390 -357
  23. package/dist/host/html.js.map +1 -1
  24. package/dist/host/nextjs/app/client-only.cjs +477 -453
  25. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  26. package/dist/host/nextjs/app/client-only.js +485 -461
  27. package/dist/host/nextjs/app/client-only.js.map +1 -1
  28. package/dist/host/react.cjs +382 -367
  29. package/dist/host/react.cjs.map +1 -1
  30. package/dist/host/react.js +382 -367
  31. package/dist/host/react.js.map +1 -1
  32. package/dist/internal/host/nextjs/app-client.cjs +2 -19
  33. package/dist/internal/host/nextjs/app-client.cjs.map +1 -1
  34. package/dist/internal/host/nextjs/app-client.js +1 -8
  35. package/dist/internal/host/nextjs/app-client.js.map +1 -1
  36. package/dist/internal/host/nextjs/image-shared.cjs +2 -2
  37. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  38. package/dist/internal/host/nextjs/image-shared.js +2 -2
  39. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  40. package/dist/internal/host/nextjs/shared-import.cjs +46 -0
  41. package/dist/internal/host/nextjs/shared-import.cjs.map +1 -0
  42. package/dist/internal/host/nextjs/shared-import.d.ts +3 -0
  43. package/dist/internal/host/nextjs/shared-import.js +12 -0
  44. package/dist/internal/host/nextjs/shared-import.js.map +1 -0
  45. package/dist/internal/host/server/fetch-remote-component.cjs +20 -1
  46. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  47. package/dist/internal/host/server/fetch-remote-component.js +20 -1
  48. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  49. package/dist/internal/host/shared/remote-image-loader.cjs +2 -5
  50. package/dist/internal/host/shared/remote-image-loader.cjs.map +1 -1
  51. package/dist/internal/host/shared/remote-image-loader.js +2 -5
  52. package/dist/internal/host/shared/remote-image-loader.js.map +1 -1
  53. package/dist/internal/runtime/loaders/script-loader.cjs +7 -0
  54. package/dist/internal/runtime/loaders/script-loader.cjs.map +1 -1
  55. package/dist/internal/runtime/loaders/script-loader.js +7 -0
  56. package/dist/internal/runtime/loaders/script-loader.js.map +1 -1
  57. package/dist/internal/runtime/turbopack/chunk-loader.cjs +76 -126
  58. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  59. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +22 -7
  60. package/dist/internal/runtime/turbopack/chunk-loader.js +85 -131
  61. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  62. package/dist/internal/runtime/turbopack/module.cjs +53 -65
  63. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  64. package/dist/internal/runtime/turbopack/module.d.ts +14 -11
  65. package/dist/internal/runtime/turbopack/module.js +51 -64
  66. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  67. package/dist/internal/runtime/turbopack/remote-scope.cjs +101 -0
  68. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -0
  69. package/dist/internal/runtime/turbopack/remote-scope.d.ts +55 -0
  70. package/dist/internal/runtime/turbopack/remote-scope.js +73 -0
  71. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -0
  72. package/dist/internal/runtime/turbopack/shared-modules.cjs +64 -56
  73. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  74. package/dist/internal/runtime/turbopack/shared-modules.d.ts +13 -4
  75. package/dist/internal/runtime/turbopack/shared-modules.js +64 -57
  76. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  77. package/dist/internal/runtime/turbopack/webpack-runtime.cjs +39 -29
  78. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +1 -1
  79. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +5 -2
  80. package/dist/internal/runtime/turbopack/webpack-runtime.js +42 -32
  81. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +1 -1
  82. package/dist/internal/runtime/types.cjs.map +1 -1
  83. package/dist/internal/runtime/types.d.ts +4 -3
  84. package/dist/internal/utils/logger.cjs.map +1 -1
  85. package/dist/internal/utils/logger.d.ts +1 -1
  86. package/dist/internal/utils/logger.js.map +1 -1
  87. package/dist/internal/utils/project-id-env.cjs +31 -0
  88. package/dist/internal/utils/project-id-env.cjs.map +1 -0
  89. package/dist/internal/utils/project-id-env.d.ts +7 -0
  90. package/dist/internal/utils/project-id-env.js +7 -0
  91. package/dist/internal/utils/project-id-env.js.map +1 -0
  92. package/dist/internal/utils/project-id.cjs +46 -0
  93. package/dist/internal/utils/project-id.cjs.map +1 -0
  94. package/dist/internal/utils/project-id.d.ts +8 -0
  95. package/dist/internal/utils/project-id.js +22 -0
  96. package/dist/internal/utils/project-id.js.map +1 -0
  97. package/dist/internal/utils.cjs +5 -0
  98. package/dist/internal/utils.cjs.map +1 -1
  99. package/dist/internal/utils.d.ts +15 -1
  100. package/dist/internal/utils.js +4 -0
  101. package/dist/internal/utils.js.map +1 -1
  102. package/dist/remote/defaults/app.cjs +2 -5
  103. package/dist/remote/defaults/app.cjs.map +1 -1
  104. package/dist/remote/defaults/app.d.ts +1 -3
  105. package/dist/remote/defaults/app.js +1 -4
  106. package/dist/remote/defaults/app.js.map +1 -1
  107. package/dist/remote/defaults/pages.cjs +2 -5
  108. package/dist/remote/defaults/pages.cjs.map +1 -1
  109. package/dist/remote/defaults/pages.d.ts +1 -3
  110. package/dist/remote/defaults/pages.js +1 -4
  111. package/dist/remote/defaults/pages.js.map +1 -1
  112. package/dist/{internal/host/shared/resolved-data.cjs → remote/defaults/shared.cjs} +18 -3
  113. package/dist/remote/defaults/shared.cjs.map +1 -0
  114. package/dist/remote/defaults/shared.d.ts +3 -0
  115. package/dist/remote/defaults/shared.js +8 -0
  116. package/dist/remote/defaults/shared.js.map +1 -0
  117. package/dist/remote/html.cjs.map +1 -1
  118. package/dist/remote/html.js.map +1 -1
  119. package/dist/remote/nextjs/app.cjs +2 -1
  120. package/dist/remote/nextjs/app.cjs.map +1 -1
  121. package/dist/remote/nextjs/app.js +2 -1
  122. package/dist/remote/nextjs/app.js.map +1 -1
  123. package/dist/remote/nextjs/pages.cjs +2 -1
  124. package/dist/remote/nextjs/pages.cjs.map +1 -1
  125. package/dist/remote/nextjs/pages.js +2 -1
  126. package/dist/remote/nextjs/pages.js.map +1 -1
  127. package/package.json +1 -1
  128. package/dist/internal/host/shared/resolved-data.cjs.map +0 -1
  129. package/dist/internal/host/shared/resolved-data.d.ts +0 -48
  130. package/dist/internal/host/shared/resolved-data.js +0 -1
  131. package/dist/internal/host/shared/resolved-data.js.map +0 -1
@@ -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
+ };
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
+ );
244
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,93 +1141,203 @@ 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`
1152
- );
1153
- await Promise.all(loadChunkLists);
1161
+ if (loadChunkPromises.length > 0) {
1162
+ await Promise.all(loadChunkPromises);
1154
1163
  }
1155
1164
  }
1156
1165
 
1157
- // src/runtime/turbopack/module.ts
1158
- function handleTurbopackModule(bundle, moduleId, id) {
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) {
1159
1169
  const self = globalThis;
1160
- const bundleKey = getBundleKey(bundle);
1161
- const raw = self[`TURBOPACK_${bundleKey}`];
1162
- let modules;
1163
- if (raw && typeof raw === "object" && "__chunks__" in raw) {
1164
- modules = raw.__chunks__.flat();
1165
- } else if (Array.isArray(raw)) {
1166
- modules = raw.flat();
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
+ );
1167
1233
  } else {
1168
- modules = raw;
1234
+ logWarn(
1235
+ "SharedModules",
1236
+ `No TURBOPACK modules found for scope="${scope.scopedName}" (TURBOPACK_${scope.globalKey} is empty)`
1237
+ );
1169
1238
  }
1170
- if (!self.__remote_components_turbopack_modules__) {
1171
- self.__remote_components_turbopack_modules__ = {};
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];
1172
1284
  }
1173
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1174
- self.__remote_components_turbopack_modules__[bundle] = {};
1285
+ for (const [key, value] of Object.entries(scope.sharedModules)) {
1286
+ if (typeof value !== "undefined" && idStr !== key && idStr.endsWith(key)) {
1287
+ return value;
1288
+ }
1175
1289
  }
1176
- if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
1177
- return self.__remote_components_turbopack_modules__[bundle][moduleId];
1290
+ return null;
1291
+ }
1292
+
1293
+ // src/runtime/turbopack/module.ts
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
+ return sharedModule;
1301
+ return handleTurbopackModule(
1302
+ scope,
1303
+ idStr,
1304
+ fullId ?? formatRemoteId(scope, idStr)
1305
+ );
1306
+ }
1307
+ function handleTurbopackModule(scope, moduleId, id) {
1308
+ if (scope.moduleCache[moduleId]) {
1309
+ return scope.moduleCache[moduleId];
1178
1310
  }
1311
+ const modules = getTurbopackModules(scope);
1179
1312
  if (!modules) {
1180
- logError("TurbopackModule", `TURBOPACK_${bundleKey} is undefined`);
1313
+ logError(
1314
+ "TurbopackModule",
1315
+ `TURBOPACK_${scope.globalKey} is undefined (scope: "${scope.scopedName}")`
1316
+ );
1181
1317
  }
1182
1318
  const moduleInit = findModuleInit(modules, moduleId);
1183
1319
  const exports = {};
1184
1320
  const moduleExports = { exports };
1185
1321
  if (typeof moduleInit !== "function") {
1186
1322
  throw new Error(
1187
- `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
1323
+ `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`
1188
1324
  );
1189
1325
  }
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
- }
1326
+ scope.moduleCache[moduleId] = moduleExports.exports;
1197
1327
  moduleInit(
1198
1328
  createTurbopackContext(
1199
- bundle,
1329
+ scope,
1200
1330
  exports,
1201
1331
  moduleExports,
1202
1332
  modules,
1203
1333
  moduleInit,
1204
- id,
1205
- self
1334
+ id
1206
1335
  ),
1207
1336
  moduleExports,
1208
1337
  exports
1209
1338
  );
1210
- if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
1211
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1339
+ if (scope.moduleCache[moduleId] !== moduleExports.exports) {
1340
+ scope.moduleCache[moduleId] = moduleExports.exports;
1212
1341
  }
1213
1342
  return moduleExports.exports;
1214
1343
  }
@@ -1233,7 +1362,8 @@ function findModuleInit(modules, moduleId) {
1233
1362
  (e) => Boolean(e && typeof e === "object" && moduleId in e)
1234
1363
  )?.[moduleId];
1235
1364
  }
1236
- function createTurbopackContext(bundle, exports, moduleExports, modules, moduleInit, id, self) {
1365
+ function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1366
+ const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
1237
1367
  return {
1238
1368
  // HMR not implemented for Remote Components
1239
1369
  k: {
@@ -1249,16 +1379,10 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1249
1379
  s(bindings, esmId) {
1250
1380
  let mod = exports;
1251
1381
  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] = {};
1257
- }
1258
- if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
1259
- self.__remote_components_turbopack_modules__[bundle][esmId] = {};
1382
+ if (!scope.moduleCache[esmId]) {
1383
+ scope.moduleCache[esmId] = {};
1260
1384
  }
1261
- mod = self.__remote_components_turbopack_modules__[bundle][esmId];
1385
+ mod = scope.moduleCache[esmId];
1262
1386
  }
1263
1387
  Object.defineProperty(mod, "__esModule", { value: true });
1264
1388
  if (Array.isArray(bindings)) {
@@ -1291,7 +1415,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1291
1415
  }
1292
1416
  }
1293
1417
  },
1294
- // import
1418
+ // import — resolves directly via scope, no global dispatch
1295
1419
  i(importId) {
1296
1420
  let mod;
1297
1421
  if (typeof importId === "string") {
@@ -1302,7 +1426,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1302
1426
  /\s+<export(?<specifier>.*)>$/,
1303
1427
  ""
1304
1428
  );
1305
- mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`);
1429
+ mod = scopedRequire(normalizedId);
1306
1430
  if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
1307
1431
  if (exportSource === "*") {
1308
1432
  mod[exportName] = mod;
@@ -1311,7 +1435,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1311
1435
  }
1312
1436
  }
1313
1437
  } else {
1314
- mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
1438
+ mod = scopedRequire(importId);
1315
1439
  }
1316
1440
  if (typeof mod !== "object" || mod === null) {
1317
1441
  mod = { default: mod };
@@ -1323,16 +1447,14 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1323
1447
  }
1324
1448
  return mod;
1325
1449
  },
1326
- // require
1450
+ // require — resolves directly via scope
1327
1451
  r(requireId) {
1328
- return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
1452
+ return scopedRequire(requireId);
1329
1453
  },
1330
1454
  // value exports
1331
1455
  v(value) {
1332
1456
  if (typeof value === "function") {
1333
- exports.default = value((vid) => {
1334
- return self.__webpack_require__?.(`[${bundle}] ${vid}`);
1335
- });
1457
+ exports.default = value((vid) => scopedRequire(vid));
1336
1458
  } else {
1337
1459
  moduleExports.exports = value;
1338
1460
  }
@@ -1347,17 +1469,15 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1347
1469
  );
1348
1470
  exports.default = result;
1349
1471
  },
1350
- // async module loader
1472
+ // async module loader — resolves directly via scope
1351
1473
  async A(Aid) {
1352
- const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
1353
- return mod.default(
1354
- (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
1355
- );
1474
+ const mod = scopedRequire(Aid);
1475
+ return mod.default((parentId) => scopedRequire(parentId));
1356
1476
  },
1357
1477
  // dynamic import tracking — no-op for remote components
1358
1478
  j() {
1359
1479
  },
1360
- // chunk loader
1480
+ // chunk loader — loads directly via scope, no global dispatch
1361
1481
  l(url) {
1362
1482
  const flatModules = Array.isArray(modules) ? modules : [];
1363
1483
  const moduleInitIndex = flatModules.indexOf(moduleInit);
@@ -1368,169 +1488,57 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1368
1488
  const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1369
1489
  const nextIndex = scriptSrc.indexOf("/_next");
1370
1490
  const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1371
- const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
1372
- return self.__webpack_chunk_load__?.(bundleUrl, bundle);
1491
+ const chunkUrl = `${baseUrl}/_next/${url}`;
1492
+ return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));
1373
1493
  }
1374
1494
  }
1375
1495
  throw new Error(
1376
1496
  `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1377
1497
  );
1378
1498
  },
1379
- // global object for this bundle
1380
- g: self.__remote_components_turbopack_global__?.[bundle],
1499
+ // globalThis substitute shared across all modules in this scope
1500
+ g: scope.moduleGlobal,
1381
1501
  m: moduleExports,
1382
1502
  e: exports
1383
1503
  };
1384
1504
  }
1385
1505
 
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
1506
  // src/runtime/turbopack/webpack-runtime.ts
1508
1507
  async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1509
1508
  const self = globalThis;
1509
+ const bundleName = bundle ?? "default";
1510
+ const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1511
+ registerScope(scope);
1510
1512
  if (!self.__remote_bundle_url__) {
1511
1513
  self.__remote_bundle_url__ = {};
1512
1514
  }
1513
- self.__remote_bundle_url__[bundle ?? "default"] = url;
1515
+ self.__remote_bundle_url__[bundleName] = url;
1516
+ if (scope.scopedName !== bundleName) {
1517
+ self.__remote_bundle_url__[scope.scopedName] = url;
1518
+ }
1514
1519
  self.__webpack_get_script_filename__ = () => null;
1515
- if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
1520
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1521
+ if (willCreateDispatchers) {
1516
1522
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1517
1523
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1518
1524
  self.__original_webpack_require__ = self.__webpack_require__;
1519
1525
  }
1520
- self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);
1521
- self.__webpack_require__ = createModuleRequire(runtime);
1526
+ self.__webpack_chunk_load__ = createChunkDispatcher();
1527
+ self.__webpack_require__ = createModuleDispatcher(runtime);
1522
1528
  self.__webpack_require_type__ = runtime;
1523
1529
  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";
1530
+ self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
1531
+ self.__remote_webpack_require__[bundleName].type = "turbopack";
1527
1532
  }
1528
1533
  }
1534
+ if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
1535
+ self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
1536
+ }
1529
1537
  if (runtime === RUNTIME_TURBOPACK) {
1530
1538
  const results = await Promise.allSettled(
1531
1539
  scripts.map((script) => {
1532
1540
  if (script.src) {
1533
- return self.__webpack_chunk_load__?.(script.src, bundle);
1541
+ return loadChunkWithScope(scope, script.src);
1534
1542
  }
1535
1543
  return Promise.resolve(void 0);
1536
1544
  })
@@ -1552,54 +1560,54 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1552
1560
  "react-dom/client": async () => (await import("react-dom/client")).default,
1553
1561
  ...shared
1554
1562
  };
1555
- await initializeSharedModules(
1556
- bundle ?? "default",
1557
- // include all core modules as shared
1558
- coreShared,
1559
- remoteShared
1560
- );
1563
+ await initializeSharedModules(scope, coreShared, remoteShared);
1561
1564
  }
1562
- function createModuleRequire(runtime) {
1565
+ function createModuleDispatcher(runtime) {
1563
1566
  return (id) => {
1564
1567
  const self = globalThis;
1565
1568
  const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1566
1569
  bundle: "default",
1567
1570
  id
1568
1571
  };
1569
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1570
- logDebug("WebpackRuntime", `remoteRuntime: "${remoteRuntime}"`);
1572
+ const bundleName = bundle ?? "default";
1573
+ const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
1574
+ logDebug(
1575
+ "ModuleDispatcher",
1576
+ `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
1577
+ );
1571
1578
  try {
1572
1579
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1573
1580
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1574
1581
  }
1575
- const sharedModuleId = moduleId ?? id;
1576
- const sharedModule = getSharedModule(bundle ?? "default", sharedModuleId);
1577
- if (sharedModule) {
1578
- return sharedModule;
1579
- }
1580
- if (bundle && moduleId) {
1581
- return handleTurbopackModule(bundle, moduleId, id);
1582
+ const scope = getScope(bundleName);
1583
+ if (scope) {
1584
+ return requireModule(scope, moduleId ?? id, id);
1582
1585
  }
1583
- throw new Error(`Module "${id}" not found.`);
1586
+ throw new Error(
1587
+ `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
1588
+ );
1584
1589
  } catch (requireError) {
1585
1590
  logWarn(
1586
- "WebpackRuntime",
1591
+ "ModuleDispatcher",
1587
1592
  `Module require failed: ${String(requireError)}`
1588
1593
  );
1589
1594
  if (typeof self.__original_webpack_require__ !== "function") {
1590
1595
  throw new RemoteComponentsError(
1591
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1596
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1592
1597
  {
1593
1598
  cause: requireError instanceof Error ? requireError : void 0
1594
1599
  }
1595
1600
  );
1596
1601
  }
1597
1602
  try {
1598
- logDebug("WebpackRuntime", "Falling back to original webpack require");
1603
+ logDebug(
1604
+ "ModuleDispatcher",
1605
+ "Falling back to original webpack require"
1606
+ );
1599
1607
  return self.__original_webpack_require__(id);
1600
1608
  } catch (originalError) {
1601
1609
  throw new RemoteComponentsError(
1602
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1610
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1603
1611
  { cause: originalError instanceof Error ? originalError : void 0 }
1604
1612
  );
1605
1613
  }
@@ -1618,6 +1626,13 @@ async function loadScripts(scripts, resolveClientUrl) {
1618
1626
  location.origin
1619
1627
  ).href;
1620
1628
  const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;
1629
+ const alreadyLoaded = Array.from(
1630
+ document.querySelectorAll("script[src]")
1631
+ ).some((s) => s.src === resolvedSrc);
1632
+ if (alreadyLoaded) {
1633
+ resolve();
1634
+ return;
1635
+ }
1621
1636
  const newScript = document.createElement("script");
1622
1637
  newScript.onload = () => resolve();
1623
1638
  newScript.onerror = () => {