remote-components 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/config/nextjs.cjs.map +1 -1
  2. package/dist/config/nextjs.js.map +1 -1
  3. package/dist/host/html.cjs +467 -395
  4. package/dist/host/html.cjs.map +1 -1
  5. package/dist/host/html.js +467 -395
  6. package/dist/host/html.js.map +1 -1
  7. package/dist/host/nextjs/app/client-only.cjs +507 -447
  8. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  9. package/dist/host/nextjs/app/client-only.js +515 -455
  10. package/dist/host/nextjs/app/client-only.js.map +1 -1
  11. package/dist/host/nextjs/app.cjs +5 -6
  12. package/dist/host/nextjs/app.cjs.map +1 -1
  13. package/dist/host/nextjs/app.js +5 -6
  14. package/dist/host/nextjs/app.js.map +1 -1
  15. package/dist/host/nextjs/pages.cjs +6 -11
  16. package/dist/host/nextjs/pages.cjs.map +1 -1
  17. package/dist/host/nextjs/pages.js +9 -11
  18. package/dist/host/nextjs/pages.js.map +1 -1
  19. package/dist/host/react.cjs +435 -374
  20. package/dist/host/react.cjs.map +1 -1
  21. package/dist/host/react.js +435 -374
  22. package/dist/host/react.js.map +1 -1
  23. package/dist/internal/host/nextjs/dom-flight.cjs +16 -7
  24. package/dist/internal/host/nextjs/dom-flight.cjs.map +1 -1
  25. package/dist/internal/host/nextjs/dom-flight.d.ts +2 -2
  26. package/dist/internal/host/nextjs/dom-flight.js +16 -7
  27. package/dist/internal/host/nextjs/dom-flight.js.map +1 -1
  28. package/dist/internal/host/nextjs/image-shared.cjs +2 -2
  29. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  30. package/dist/internal/host/nextjs/image-shared.js +2 -2
  31. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  32. package/dist/internal/host/server/fetch-remote-component.cjs +183 -149
  33. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  34. package/dist/internal/host/server/fetch-remote-component.js +185 -149
  35. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  36. package/dist/internal/host/shared/remote-image-loader.cjs +2 -5
  37. package/dist/internal/host/shared/remote-image-loader.cjs.map +1 -1
  38. package/dist/internal/host/shared/remote-image-loader.js +2 -5
  39. package/dist/internal/host/shared/remote-image-loader.js.map +1 -1
  40. package/dist/internal/runtime/constants.cjs +6 -6
  41. package/dist/internal/runtime/constants.cjs.map +1 -1
  42. package/dist/internal/runtime/constants.d.ts +3 -3
  43. package/dist/internal/runtime/constants.js +4 -4
  44. package/dist/internal/runtime/constants.js.map +1 -1
  45. package/dist/internal/runtime/html/parse-remote-html.cjs +11 -15
  46. package/dist/internal/runtime/html/parse-remote-html.cjs.map +1 -1
  47. package/dist/internal/runtime/html/parse-remote-html.d.ts +2 -12
  48. package/dist/internal/runtime/html/parse-remote-html.js +17 -15
  49. package/dist/internal/runtime/html/parse-remote-html.js.map +1 -1
  50. package/dist/internal/runtime/loaders/script-loader.cjs +2 -2
  51. package/dist/internal/runtime/loaders/script-loader.cjs.map +1 -1
  52. package/dist/internal/runtime/loaders/script-loader.js +1 -1
  53. package/dist/internal/runtime/loaders/script-loader.js.map +1 -1
  54. package/dist/internal/runtime/metadata.cjs +42 -0
  55. package/dist/internal/runtime/metadata.cjs.map +1 -1
  56. package/dist/internal/runtime/metadata.d.ts +21 -1
  57. package/dist/internal/runtime/metadata.js +38 -0
  58. package/dist/internal/runtime/metadata.js.map +1 -1
  59. package/dist/internal/runtime/patterns.cjs +38 -0
  60. package/dist/internal/runtime/patterns.cjs.map +1 -0
  61. package/dist/internal/runtime/patterns.d.ts +5 -0
  62. package/dist/internal/runtime/patterns.js +12 -0
  63. package/dist/internal/runtime/patterns.js.map +1 -0
  64. package/dist/internal/runtime/turbopack/chunk-loader.cjs +79 -128
  65. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  66. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +22 -7
  67. package/dist/internal/runtime/turbopack/chunk-loader.js +85 -131
  68. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  69. package/dist/internal/runtime/turbopack/module.cjs +56 -57
  70. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  71. package/dist/internal/runtime/turbopack/module.d.ts +14 -11
  72. package/dist/internal/runtime/turbopack/module.js +54 -56
  73. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  74. package/dist/internal/runtime/turbopack/remote-scope.cjs +101 -0
  75. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -0
  76. package/dist/internal/runtime/turbopack/remote-scope.d.ts +55 -0
  77. package/dist/internal/runtime/turbopack/remote-scope.js +73 -0
  78. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -0
  79. package/dist/internal/runtime/turbopack/shared-modules.cjs +62 -56
  80. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  81. package/dist/internal/runtime/turbopack/shared-modules.d.ts +7 -3
  82. package/dist/internal/runtime/turbopack/shared-modules.js +63 -57
  83. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  84. package/dist/internal/runtime/turbopack/webpack-runtime.cjs +50 -31
  85. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +1 -1
  86. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +5 -2
  87. package/dist/internal/runtime/turbopack/webpack-runtime.js +52 -34
  88. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +1 -1
  89. package/dist/internal/runtime/types.cjs.map +1 -1
  90. package/dist/internal/runtime/types.d.ts +4 -3
  91. package/dist/internal/utils/logger.cjs.map +1 -1
  92. package/dist/internal/utils/logger.d.ts +1 -1
  93. package/dist/internal/utils/logger.js.map +1 -1
  94. package/dist/internal/utils.cjs +5 -0
  95. package/dist/internal/utils.cjs.map +1 -1
  96. package/dist/internal/utils.d.ts +15 -1
  97. package/dist/internal/utils.js +4 -0
  98. package/dist/internal/utils.js.map +1 -1
  99. package/dist/remote/html.cjs.map +1 -1
  100. package/dist/remote/html.js.map +1 -1
  101. package/dist/remote/nextjs/app.cjs +2 -1
  102. package/dist/remote/nextjs/app.cjs.map +1 -1
  103. package/dist/remote/nextjs/app.js +2 -1
  104. package/dist/remote/nextjs/app.js.map +1 -1
  105. package/package.json +1 -1
@@ -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
+ );
318
+ }
319
+ function getScope(name) {
320
+ return getRegistry().get(name);
244
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_ROUTE = "/";
450
- var RUNTIME_WEBPACK = "webpack";
451
- var RUNTIME_TURBOPACK = "turbopack";
452
- var RUNTIME_SCRIPT = "script";
453
- var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
454
- var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
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",
@@ -518,6 +588,38 @@ function applyOriginToNodes(doc, url, resolveClientUrl) {
518
588
  }
519
589
  }
520
590
 
591
+ // src/runtime/metadata.ts
592
+ var VALID_RUNTIMES = /* @__PURE__ */ new Set(["webpack", "turbopack", "script"]);
593
+ var VALID_TYPES = /* @__PURE__ */ new Set([
594
+ "nextjs",
595
+ "remote-component",
596
+ "unknown"
597
+ ]);
598
+ function isRuntime(value) {
599
+ return VALID_RUNTIMES.has(value);
600
+ }
601
+ function isComponentType(value) {
602
+ return VALID_TYPES.has(value);
603
+ }
604
+ function toRuntime(value) {
605
+ return value && isRuntime(value) ? value : "webpack";
606
+ }
607
+ function toComponentType(value) {
608
+ return value && isComponentType(value) ? value : "unknown";
609
+ }
610
+ function buildMetadata(attrs, url) {
611
+ const id = attrs.id || DEFAULT_COMPONENT_NAME;
612
+ const bundle = attrs.bundle || process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION || DEFAULT_BUNDLE_NAME;
613
+ return {
614
+ name: attrs.name || id.replace(/_ssr$/, ""),
615
+ bundle,
616
+ route: attrs.route || url.pathname || DEFAULT_ROUTE,
617
+ runtime: toRuntime(attrs.runtime),
618
+ id,
619
+ type: toComponentType(attrs.type)
620
+ };
621
+ }
622
+
521
623
  // src/runtime/html/parse-remote-html.ts
522
624
  function validateSingleComponent(doc, name, url) {
523
625
  if (doc.querySelectorAll("div[data-bundle][data-route]").length > 1 && !doc.querySelector(`div[data-bundle][data-route][id^="${name}"]`) || doc.querySelectorAll("remote-component:not([src])").length > 1 && !doc.querySelector(`remote-component[name="${name}"]`)) {
@@ -537,14 +639,6 @@ function resolveComponentName(component, nextData, fallbackName) {
537
639
  const name = component?.getAttribute("id")?.replace(/_ssr$/, "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
538
640
  return { name, isRemoteComponent };
539
641
  }
540
- function extractComponentMetadata(component, nextData, name, url) {
541
- return {
542
- name,
543
- bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle || "default",
544
- route: component?.getAttribute("data-route") ?? nextData?.page ?? (url.pathname || DEFAULT_ROUTE),
545
- runtime: component?.getAttribute("data-runtime") ?? (nextData?.props.__REMOTE_COMPONENT__?.runtime || RUNTIME_SCRIPT)
546
- };
547
- }
548
642
  function extractRemoteShared(doc, name, nextData) {
549
643
  const remoteSharedEl = doc.querySelector(
550
644
  `#${name}_shared[data-remote-components-shared]`
@@ -556,7 +650,7 @@ function extractRemoteShared(doc, name, nextData) {
556
650
  function validateComponentFound(component, rsc, nextData, isRemoteComponent, url, name) {
557
651
  if (!component || !(rsc || nextData || isRemoteComponent)) {
558
652
  throw new RemoteComponentsError(
559
- `Remote Component not found on ${url}.${name !== "__vercel_remote_component" ? ` The name for the <RemoteComponent> is "${name}". Check <RemoteComponent> usage.` : ""} Did you forget to wrap the content in <RemoteComponent>?`
653
+ `Remote Component not found on ${url}.${name !== DEFAULT_COMPONENT_NAME ? ` The name for the <RemoteComponent> is "${name}". Check <RemoteComponent> usage.` : ""} Did you forget to wrap the content in <RemoteComponent>?`
560
654
  );
561
655
  }
562
656
  }
@@ -582,10 +676,15 @@ function parseRemoteComponentDocument(doc, name, url) {
582
676
  name
583
677
  );
584
678
  const rsc = doc.querySelector(`#${resolvedName}_rsc`);
585
- const metadata = extractComponentMetadata(
586
- component,
587
- nextData,
588
- resolvedName,
679
+ const metadata = buildMetadata(
680
+ {
681
+ name: resolvedName,
682
+ bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle,
683
+ route: component?.getAttribute("data-route") ?? nextData?.page,
684
+ runtime: component?.getAttribute("data-runtime") ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
685
+ id: component?.getAttribute("id"),
686
+ type: component?.getAttribute("data-type")
687
+ },
589
688
  url
590
689
  );
591
690
  const remoteShared = extractRemoteShared(doc, resolvedName, nextData);
@@ -910,62 +1009,39 @@ var ASYNC_MODULE_ALL_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<vCb
910
1009
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
911
1010
 
912
1011
  // src/runtime/turbopack/chunk-loader.ts
913
- function createChunkLoader(runtime, resolveClientUrl) {
914
- return function __turbopack_chunk_load__(chunkId, scriptBundle) {
915
- logDebug("ChunkLoader", `Loading chunk: "${chunkId}"`);
916
- const self = globalThis;
917
- const {
918
- bundle,
919
- id: path,
920
- prefix
921
- } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {
922
- bundle: scriptBundle ?? "",
923
- id: chunkId
924
- };
925
- logDebug(
926
- "ChunkLoader",
927
- `Parsed chunk - bundle: "${bundle}", path: "${path}", prefix: "${prefix}"`
928
- );
929
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
930
- logDebug("ChunkLoader", `Remote runtime: "${remoteRuntime}"`);
931
- if (remoteRuntime === RUNTIME_WEBPACK) {
932
- logDebug("ChunkLoader", "Skipping chunk load - webpack runtime detected");
933
- return Promise.resolve(void 0);
934
- }
935
- const url = new URL(
936
- path ? `${prefix ?? ""}${path}`.replace(
937
- /(?<char>[^:])(?<double>\/\/)/g,
938
- "$1/"
939
- ) : "/",
940
- self.__remote_bundle_url__?.[bundle ?? "default"] ?? new URL(location.origin)
941
- ).href;
942
- if (url.endsWith(".css")) {
943
- logDebug("ChunkLoader", `Skipping CSS file: "${url}"`);
944
- return;
945
- }
946
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
947
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
948
- }
949
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
950
- logDebug("ChunkLoader", `Returning cached promise for: "${url}"`);
951
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
952
- }
953
- const resolvedUrl = resolveClientUrl?.(url) ?? url;
954
- logDebug("ChunkLoader", `Fetching chunk from: "${resolvedUrl}"`);
955
- 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) => {
956
1040
  fetch(resolvedUrl).then((res) => res.text()).then((code) => {
957
1041
  const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
958
1042
  if (hasTurbopack) {
959
- return handleTurbopackChunk(code, bundle ?? "", url);
1043
+ return handleTurbopackChunk(code, scope, url);
960
1044
  }
961
- logDebug(
962
- "ChunkLoader",
963
- `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: "${url}"`
964
- );
965
- logDebug(
966
- "ChunkLoader",
967
- `First 500 chars of chunk: ${code.slice(0, 500)}`
968
- );
969
1045
  }).then(resolve).catch((error) => {
970
1046
  const isProxied = isProxiedUrl(resolvedUrl);
971
1047
  if (isProxied) {
@@ -975,17 +1051,29 @@ function createChunkLoader(runtime, resolveClientUrl) {
975
1051
  reject(error);
976
1052
  }
977
1053
  });
978
- });
979
- 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);
980
1073
  };
981
1074
  }
982
- async function handleTurbopackChunk(code, bundle, url) {
983
- logDebug(
984
- "ChunkLoader",
985
- `Handling Turbopack chunk - bundle: "${bundle}", url: "${url}"`
986
- );
1075
+ async function handleTurbopackChunk(code, scope, url) {
987
1076
  if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
988
- logDebug("ChunkLoader", `Skipping worker chunk: "${url}"`);
989
1077
  const preloadLinks = document.querySelectorAll(
990
1078
  `link[rel="preload"][href="${new URL(url).pathname}"]`
991
1079
  );
@@ -993,58 +1081,41 @@ async function handleTurbopackChunk(code, bundle, url) {
993
1081
  return;
994
1082
  }
995
1083
  const self = globalThis;
996
- const bundleKey = getBundleKey(bundle);
997
- logDebug("ChunkLoader", `Bundle key: "${bundleKey}"`);
1084
+ const { globalKey } = scope;
998
1085
  const transformedCode = code.replace(
999
1086
  /globalThis\[\s*["']TURBOPACK["']\s*\]/g,
1000
- `globalThis["TURBOPACK_${bundleKey}"]`
1087
+ `globalThis["TURBOPACK_${globalKey}"]`
1001
1088
  ).replace(
1002
1089
  /self\[\s*["']TURBOPACK["']\s*\]/g,
1003
- `self["TURBOPACK_${bundleKey}"]`
1004
- ).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(
1005
1092
  /TURBOPACK_WORKER_LOCATION/g,
1006
- `TURBOPACK_WORKER_LOCATION_${bundleKey}`
1093
+ `TURBOPACK_WORKER_LOCATION_${globalKey}`
1007
1094
  ).replace(
1008
1095
  /TURBOPACK_NEXT_CHUNK_URLS/g,
1009
- `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
1096
+ `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`
1010
1097
  ).replace(
1011
1098
  /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
1012
- `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
1013
- ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
1099
+ `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`
1100
+ ).replace(/__next_require__/g, `__${globalKey}_next_require__`).replace(
1014
1101
  /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
1015
- `//# sourceMappingURL=${new URL(
1016
- ".",
1017
- new URL(
1018
- url,
1019
- self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin)
1020
- )
1021
- ).href}$1$2.js.map`
1102
+ `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1022
1103
  );
1023
- if (!self[`TURBOPACK_${bundleKey}`]) {
1104
+ if (!self[`TURBOPACK_${globalKey}`]) {
1024
1105
  const chunkData = [];
1025
1106
  const turbopackObject = {
1026
1107
  push: (item) => {
1027
- logDebug(
1028
- "ChunkLoader",
1029
- `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? "array" : typeof item}`
1030
- );
1031
1108
  if (Array.isArray(item)) {
1032
1109
  chunkData.push(item);
1033
- logDebug(
1034
- "ChunkLoader",
1035
- `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`
1036
- );
1037
1110
  } else {
1038
1111
  chunkData.push([item]);
1039
1112
  }
1040
1113
  return chunkData.length;
1041
1114
  },
1042
- // Store chunks for later access
1043
1115
  __chunks__: chunkData
1044
1116
  };
1045
- self[`TURBOPACK_${bundleKey}`] = turbopackObject;
1117
+ self[`TURBOPACK_${globalKey}`] = turbopackObject;
1046
1118
  }
1047
- logDebug("ChunkLoader", `Creating blob script for: "${url}"`);
1048
1119
  await new Promise((scriptResolve, scriptReject) => {
1049
1120
  const blob = new Blob([transformedCode], {
1050
1121
  type: "application/javascript; charset=UTF-8"
@@ -1056,21 +1127,6 @@ async function handleTurbopackChunk(code, bundle, url) {
1056
1127
  script.async = true;
1057
1128
  script.onload = () => {
1058
1129
  URL.revokeObjectURL(scriptUrl);
1059
- logDebug(
1060
- "ChunkLoader",
1061
- `Script loaded successfully for bundle "${bundle}"`
1062
- );
1063
- const turbopackBundle = self[`TURBOPACK_${bundleKey}`];
1064
- logDebug(
1065
- "ChunkLoader",
1066
- `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${turbopackBundle ? Object.keys(turbopackBundle).slice(0, 10).join(", ") : "none"}`
1067
- );
1068
- if (turbopackBundle && typeof turbopackBundle === "object") {
1069
- logDebug(
1070
- "ChunkLoader",
1071
- `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle).length}`
1072
- );
1073
- }
1074
1130
  scriptResolve(void 0);
1075
1131
  script.remove();
1076
1132
  };
@@ -1085,43 +1141,177 @@ async function handleTurbopackChunk(code, bundle, url) {
1085
1141
  };
1086
1142
  document.head.appendChild(script);
1087
1143
  });
1088
- const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`];
1089
- logDebug(
1090
- "ChunkLoader",
1091
- `Processing chunk lists for bundle "${bundle}": ${chunkLists?.length ?? 0} lists`
1092
- );
1093
- const loadChunkLists = [];
1144
+ const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`];
1145
+ const loadChunkPromises = [];
1094
1146
  while (chunkLists?.length) {
1095
1147
  const { chunks } = chunkLists.shift() ?? { chunks: [] };
1096
1148
  if (chunks.length > 0) {
1097
- logDebug(
1098
- "ChunkLoader",
1099
- `Loading ${chunks.length} additional chunks for bundle "${bundle}": [${chunks.join(", ")}]`
1100
- );
1101
- chunks.forEach((id) => {
1102
- const chunkLoadResult = self.__webpack_chunk_load__?.(
1103
- `[${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}`)
1104
1154
  );
1105
1155
  if (chunkLoadResult) {
1106
- loadChunkLists.push(chunkLoadResult);
1156
+ loadChunkPromises.push(chunkLoadResult);
1107
1157
  }
1108
- });
1158
+ }
1109
1159
  }
1110
1160
  }
1111
- if (loadChunkLists.length > 0) {
1112
- logDebug(
1113
- "ChunkLoader",
1114
- `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)`
1115
1237
  );
1116
- await Promise.all(loadChunkLists);
1117
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;
1118
1291
  }
1119
1292
 
1120
1293
  // src/runtime/turbopack/module.ts
1121
- 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) {
1122
1310
  const self = globalThis;
1123
- const bundleKey = getBundleKey(bundle);
1124
- const raw = self[`TURBOPACK_${bundleKey}`];
1311
+ if (scope.moduleCache[moduleId]) {
1312
+ return scope.moduleCache[moduleId];
1313
+ }
1314
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1125
1315
  let modules;
1126
1316
  if (raw && typeof raw === "object" && "__chunks__" in raw) {
1127
1317
  modules = raw.__chunks__.flat();
@@ -1130,48 +1320,35 @@ function handleTurbopackModule(bundle, moduleId, id) {
1130
1320
  } else {
1131
1321
  modules = raw;
1132
1322
  }
1133
- if (!self.__remote_components_turbopack_modules__) {
1134
- self.__remote_components_turbopack_modules__ = {};
1135
- }
1136
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1137
- self.__remote_components_turbopack_modules__[bundle] = {};
1138
- }
1139
- if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
1140
- return self.__remote_components_turbopack_modules__[bundle][moduleId];
1141
- }
1142
1323
  if (!modules) {
1143
- logError("TurbopackModule", `TURBOPACK_${bundleKey} is undefined`);
1324
+ logError(
1325
+ "TurbopackModule",
1326
+ `TURBOPACK_${scope.globalKey} is undefined (scope: "${scope.scopedName}")`
1327
+ );
1144
1328
  }
1145
1329
  const moduleInit = findModuleInit(modules, moduleId);
1146
1330
  const exports = {};
1147
1331
  const moduleExports = { exports };
1148
1332
  if (typeof moduleInit !== "function") {
1149
1333
  throw new Error(
1150
- `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
1334
+ `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`
1151
1335
  );
1152
1336
  }
1153
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1154
- if (!self.__remote_components_turbopack_global__) {
1155
- self.__remote_components_turbopack_global__ = {};
1156
- }
1157
- if (!self.__remote_components_turbopack_global__[bundle]) {
1158
- self.__remote_components_turbopack_global__[bundle] = {};
1159
- }
1337
+ scope.moduleCache[moduleId] = moduleExports.exports;
1160
1338
  moduleInit(
1161
1339
  createTurbopackContext(
1162
- bundle,
1340
+ scope,
1163
1341
  exports,
1164
1342
  moduleExports,
1165
1343
  modules,
1166
1344
  moduleInit,
1167
- id,
1168
- self
1345
+ id
1169
1346
  ),
1170
1347
  moduleExports,
1171
1348
  exports
1172
1349
  );
1173
- if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
1174
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1350
+ if (scope.moduleCache[moduleId] !== moduleExports.exports) {
1351
+ scope.moduleCache[moduleId] = moduleExports.exports;
1175
1352
  }
1176
1353
  return moduleExports.exports;
1177
1354
  }
@@ -1196,7 +1373,8 @@ function findModuleInit(modules, moduleId) {
1196
1373
  (e) => Boolean(e && typeof e === "object" && moduleId in e)
1197
1374
  )?.[moduleId];
1198
1375
  }
1199
- 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)));
1200
1378
  return {
1201
1379
  // HMR not implemented for Remote Components
1202
1380
  k: {
@@ -1212,16 +1390,10 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1212
1390
  s(bindings, esmId) {
1213
1391
  let mod = exports;
1214
1392
  if (typeof esmId === "string" || typeof esmId === "number") {
1215
- if (!self.__remote_components_turbopack_modules__) {
1216
- self.__remote_components_turbopack_modules__ = {};
1217
- }
1218
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1219
- self.__remote_components_turbopack_modules__[bundle] = {};
1220
- }
1221
- if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
1222
- self.__remote_components_turbopack_modules__[bundle][esmId] = {};
1393
+ if (!scope.moduleCache[esmId]) {
1394
+ scope.moduleCache[esmId] = {};
1223
1395
  }
1224
- mod = self.__remote_components_turbopack_modules__[bundle][esmId];
1396
+ mod = scope.moduleCache[esmId];
1225
1397
  }
1226
1398
  Object.defineProperty(mod, "__esModule", { value: true });
1227
1399
  if (Array.isArray(bindings)) {
@@ -1254,7 +1426,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1254
1426
  }
1255
1427
  }
1256
1428
  },
1257
- // import
1429
+ // import — resolves directly via scope, no global dispatch
1258
1430
  i(importId) {
1259
1431
  let mod;
1260
1432
  if (typeof importId === "string") {
@@ -1265,7 +1437,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1265
1437
  /\s+<export(?<specifier>.*)>$/,
1266
1438
  ""
1267
1439
  );
1268
- mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`);
1440
+ mod = scopedRequire(normalizedId);
1269
1441
  if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
1270
1442
  if (exportSource === "*") {
1271
1443
  mod[exportName] = mod;
@@ -1274,7 +1446,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1274
1446
  }
1275
1447
  }
1276
1448
  } else {
1277
- mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
1449
+ mod = scopedRequire(importId);
1278
1450
  }
1279
1451
  if (typeof mod !== "object" || mod === null) {
1280
1452
  mod = { default: mod };
@@ -1286,16 +1458,14 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1286
1458
  }
1287
1459
  return mod;
1288
1460
  },
1289
- // require
1461
+ // require — resolves directly via scope
1290
1462
  r(requireId) {
1291
- return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
1463
+ return scopedRequire(requireId);
1292
1464
  },
1293
1465
  // value exports
1294
1466
  v(value) {
1295
1467
  if (typeof value === "function") {
1296
- exports.default = value((vid) => {
1297
- return self.__webpack_require__?.(`[${bundle}] ${vid}`);
1298
- });
1468
+ exports.default = value((vid) => scopedRequire(vid));
1299
1469
  } else {
1300
1470
  moduleExports.exports = value;
1301
1471
  }
@@ -1310,17 +1480,15 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1310
1480
  );
1311
1481
  exports.default = result;
1312
1482
  },
1313
- // async module loader
1483
+ // async module loader — resolves directly via scope
1314
1484
  async A(Aid) {
1315
- const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
1316
- return mod.default(
1317
- (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
1318
- );
1485
+ const mod = scopedRequire(Aid);
1486
+ return mod.default((parentId) => scopedRequire(parentId));
1319
1487
  },
1320
1488
  // dynamic import tracking — no-op for remote components
1321
1489
  j() {
1322
1490
  },
1323
- // chunk loader
1491
+ // chunk loader — loads directly via scope, no global dispatch
1324
1492
  l(url) {
1325
1493
  const flatModules = Array.isArray(modules) ? modules : [];
1326
1494
  const moduleInitIndex = flatModules.indexOf(moduleInit);
@@ -1331,173 +1499,69 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1331
1499
  const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1332
1500
  const nextIndex = scriptSrc.indexOf("/_next");
1333
1501
  const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1334
- const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
1335
- return self.__webpack_chunk_load__?.(bundleUrl, bundle);
1502
+ const chunkUrl = `${baseUrl}/_next/${url}`;
1503
+ return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));
1336
1504
  }
1337
1505
  }
1338
1506
  throw new Error(
1339
1507
  `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1340
1508
  );
1341
1509
  },
1342
- // global object for this bundle
1343
- g: self.__remote_components_turbopack_global__?.[bundle],
1510
+ // globalThis substitute shared across all modules in this scope
1511
+ g: scope.moduleGlobal,
1344
1512
  m: moduleExports,
1345
1513
  e: exports
1346
1514
  };
1347
1515
  }
1348
1516
 
1349
- // src/runtime/turbopack/shared-modules.ts
1350
- 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).";
1351
- async function initializeSharedModules(bundle, hostShared = {}, remoteShared = {}) {
1352
- const self = globalThis;
1353
- self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};
1354
- if (!self.__remote_shared_modules__[bundle]) {
1355
- self.__remote_shared_modules__[bundle] = {};
1356
- }
1357
- const bundleKey = getBundleKey(bundle);
1358
- let modules = self[`TURBOPACK_${bundleKey}`];
1359
- if (modules && typeof modules === "object" && "__chunks__" in modules) {
1360
- const chunks = modules.__chunks__;
1361
- modules = chunks.flat();
1362
- }
1363
- let sharedModuleInitializer = null;
1364
- if (modules) {
1365
- const allModules = Array.isArray(modules) ? modules.flat() : Object.entries(modules).flat();
1366
- const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1367
- if (typeof idOrFunc !== "function") {
1368
- return false;
1369
- }
1370
- const funcCode = idOrFunc.toString();
1371
- return REMOTE_SHARED_MARKER_RE.test(funcCode);
1372
- });
1373
- if (sharedModuleInitializerIndex > 0) {
1374
- const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1375
- const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1376
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1377
- if (sharedModuleId) {
1378
- const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1379
- bundle,
1380
- sharedModuleId,
1381
- `[${bundle}] ${sharedModuleInitializerId}`
1382
- );
1383
- sharedModuleInitializer = sharedModuleInitializerInstance;
1384
- }
1385
- }
1386
- if (sharedModuleInitializer) {
1387
- const { shared } = await sharedModuleInitializer;
1388
- const sharedModuleIds = extractSharedModuleIds(
1389
- shared,
1390
- bundleKey,
1391
- self
1392
- );
1393
- return Promise.all(
1394
- Object.entries(sharedModuleIds).map(async ([id, module2]) => {
1395
- if (self.__remote_shared_modules__?.[bundle]) {
1396
- if (hostShared[module2]) {
1397
- self.__remote_shared_modules__[bundle][id] = await hostShared[module2](bundle);
1398
- } else {
1399
- logError(
1400
- "SharedModules",
1401
- `Host shared module "${module2}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1402
- );
1403
- }
1404
- }
1405
- })
1406
- );
1407
- }
1408
- }
1409
- return Promise.all(
1410
- Object.entries(remoteShared).map(async ([id, module2]) => {
1411
- if (self.__remote_shared_modules__?.[bundle]) {
1412
- if (hostShared[module2]) {
1413
- const normalizedId = id.replace("[app-ssr]", "[app-client]");
1414
- self.__remote_shared_modules__[bundle][normalizedId] = await hostShared[module2](bundle);
1415
- } else {
1416
- logError(
1417
- "SharedModules",
1418
- `Shared module "${module2}" not found for "${bundle}". ${DEDUPLICATION_WARNING}`
1419
- );
1420
- }
1421
- }
1422
- })
1423
- );
1424
- }
1425
- function extractSharedModuleIds(shared, bundleKey, self) {
1426
- return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1427
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1428
- if (asyncSharedModuleId) {
1429
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1430
- let asyncSharedModule;
1431
- let turbopackModules = self[`TURBOPACK_${bundleKey}`];
1432
- if (turbopackModules && typeof turbopackModules === "object" && "__chunks__" in turbopackModules) {
1433
- const chunks = turbopackModules.__chunks__;
1434
- turbopackModules = chunks.flat();
1435
- }
1436
- const newAllModules = Array.isArray(turbopackModules) ? turbopackModules.flat() : turbopackModules ? Object.entries(turbopackModules).flatMap(([key2, value2]) => [
1437
- key2,
1438
- value2
1439
- ]) : [];
1440
- const asyncSharedModuleIdIndex = newAllModules.indexOf(
1441
- asyncSharedModuleIdNumber
1442
- );
1443
- if (asyncSharedModuleIdIndex !== -1 && typeof newAllModules[asyncSharedModuleIdIndex + 1] === "function") {
1444
- asyncSharedModule = newAllModules[asyncSharedModuleIdIndex + 1];
1445
- }
1446
- if (asyncSharedModule) {
1447
- const asyncSharedModuleCode = asyncSharedModule.toString();
1448
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1449
- acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1450
- "__remote_shared_module_",
1451
- ""
1452
- );
1453
- }
1454
- }
1455
- return acc;
1456
- }, {});
1457
- }
1458
- function getSharedModule(bundle, id) {
1459
- const self = globalThis;
1460
- for (const [key, value] of Object.entries(
1461
- self.__remote_shared_modules__?.[bundle] ?? {}
1462
- )) {
1463
- if (typeof value !== "undefined" && (typeof id === "string" && id.includes(key) || id === key)) {
1464
- return value;
1465
- }
1466
- }
1467
- return null;
1468
- }
1469
-
1470
1517
  // src/runtime/turbopack/webpack-runtime.ts
1471
1518
  async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1472
1519
  const self = globalThis;
1520
+ const bundleName = bundle ?? "default";
1521
+ const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1522
+ registerScope(scope);
1473
1523
  if (!self.__remote_bundle_url__) {
1474
1524
  self.__remote_bundle_url__ = {};
1475
1525
  }
1476
- 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
+ }
1477
1530
  self.__webpack_get_script_filename__ = () => null;
1478
- 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) {
1479
1533
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1480
1534
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1481
1535
  self.__original_webpack_require__ = self.__webpack_require__;
1482
1536
  }
1483
- self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);
1484
- self.__webpack_require__ = createModuleRequire(runtime);
1537
+ self.__webpack_chunk_load__ = createChunkDispatcher();
1538
+ self.__webpack_require__ = createModuleDispatcher(runtime);
1485
1539
  self.__webpack_require_type__ = runtime;
1486
1540
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1487
- const remoteBundle = bundle ?? "default";
1488
- self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
1489
- self.__remote_webpack_require__[remoteBundle].type = "turbopack";
1541
+ self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
1542
+ self.__remote_webpack_require__[bundleName].type = "turbopack";
1490
1543
  }
1491
1544
  }
1545
+ if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
1546
+ self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
1547
+ }
1492
1548
  if (runtime === RUNTIME_TURBOPACK) {
1493
- await Promise.all(
1549
+ const results = await Promise.allSettled(
1494
1550
  scripts.map((script) => {
1495
1551
  if (script.src) {
1496
- return self.__webpack_chunk_load__?.(script.src, bundle);
1552
+ return loadChunkWithScope(scope, script.src);
1497
1553
  }
1498
1554
  return Promise.resolve(void 0);
1499
1555
  })
1500
1556
  );
1557
+ for (const result of results) {
1558
+ if (result.status === "rejected") {
1559
+ logWarn(
1560
+ "WebpackRuntime",
1561
+ `Initial chunk load failed: ${String(result.reason)}`
1562
+ );
1563
+ }
1564
+ }
1501
1565
  }
1502
1566
  const coreShared = {
1503
1567
  react: async () => (await import("react")).default,
@@ -1507,54 +1571,54 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1507
1571
  "react-dom/client": async () => (await import("react-dom/client")).default,
1508
1572
  ...shared
1509
1573
  };
1510
- await initializeSharedModules(
1511
- bundle ?? "default",
1512
- // include all core modules as shared
1513
- coreShared,
1514
- remoteShared
1515
- );
1574
+ await initializeSharedModules(scope, coreShared, remoteShared);
1516
1575
  }
1517
- function createModuleRequire(runtime) {
1576
+ function createModuleDispatcher(runtime) {
1518
1577
  return (id) => {
1519
1578
  const self = globalThis;
1520
1579
  const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1521
1580
  bundle: "default",
1522
1581
  id
1523
1582
  };
1524
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1525
- 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
+ );
1526
1589
  try {
1527
1590
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1528
1591
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1529
1592
  }
1530
- const sharedModuleId = moduleId ?? id;
1531
- const sharedModule = getSharedModule(bundle ?? "default", sharedModuleId);
1532
- if (sharedModule) {
1533
- return sharedModule;
1593
+ const scope = getScope(bundleName);
1594
+ if (scope) {
1595
+ return requireModule(scope, moduleId ?? id, id);
1534
1596
  }
1535
- if (bundle && moduleId) {
1536
- return handleTurbopackModule(bundle, moduleId, id);
1537
- }
1538
- throw new Error(`Module "${id}" not found.`);
1597
+ throw new Error(
1598
+ `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
1599
+ );
1539
1600
  } catch (requireError) {
1540
1601
  logWarn(
1541
- "WebpackRuntime",
1602
+ "ModuleDispatcher",
1542
1603
  `Module require failed: ${String(requireError)}`
1543
1604
  );
1544
1605
  if (typeof self.__original_webpack_require__ !== "function") {
1545
1606
  throw new RemoteComponentsError(
1546
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1607
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1547
1608
  {
1548
1609
  cause: requireError instanceof Error ? requireError : void 0
1549
1610
  }
1550
1611
  );
1551
1612
  }
1552
1613
  try {
1553
- logDebug("WebpackRuntime", "Falling back to original webpack require");
1614
+ logDebug(
1615
+ "ModuleDispatcher",
1616
+ "Falling back to original webpack require"
1617
+ );
1554
1618
  return self.__original_webpack_require__(id);
1555
1619
  } catch (originalError) {
1556
1620
  throw new RemoteComponentsError(
1557
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1621
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1558
1622
  { cause: originalError instanceof Error ? originalError : void 0 }
1559
1623
  );
1560
1624
  }
@@ -1980,7 +2044,7 @@ function getRemoteComponentHtml(html) {
1980
2044
  return ssrRemoteComponentContainer.innerHTML;
1981
2045
  }
1982
2046
  const remoteComponentContainer = temp.querySelectorAll(
1983
- `div[data-bundle][data-route][data-runtime][id^="__vercel_remote_component"],div[data-bundle][data-route],div#__next,remote-component:not([src])`
2047
+ `div[data-bundle][data-route][data-runtime][id^="${DEFAULT_COMPONENT_NAME}"],div[data-bundle][data-route],div#__next,remote-component:not([src])`
1984
2048
  );
1985
2049
  if (remoteComponentContainer.length > 0) {
1986
2050
  return `${Array.from(temp.querySelectorAll("link,script")).map((link) => link.outerHTML).join("")}${Array.from(remoteComponentContainer).map((container) => container.outerHTML).join("")}`;
@@ -2000,7 +2064,7 @@ function ConsumeRemoteComponent({
2000
2064
  mode = "open",
2001
2065
  reset,
2002
2066
  credentials: credentialsProp,
2003
- name: nameProp = "__vercel_remote_component",
2067
+ name: nameProp = DEFAULT_COMPONENT_NAME,
2004
2068
  shared: sharedProp,
2005
2069
  children,
2006
2070
  onBeforeLoad,
@@ -2339,10 +2403,7 @@ function ConsumeRemoteComponent({
2339
2403
  };
2340
2404
  return {
2341
2405
  src: new URL(
2342
- `${prefix ?? ""}${path}`.replace(
2343
- /(?<char>[^:])(?<double>\/\/)/g,
2344
- "$1/"
2345
- ),
2406
+ collapseDoubleSlashes(`${prefix ?? ""}${path}`),
2346
2407
  url
2347
2408
  ).href
2348
2409
  };