remote-components 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/config/nextjs.cjs.map +1 -1
  2. package/dist/config/nextjs.js.map +1 -1
  3. package/dist/host/html.cjs +390 -353
  4. package/dist/host/html.cjs.map +1 -1
  5. package/dist/host/html.js +390 -353
  6. package/dist/host/html.js.map +1 -1
  7. package/dist/host/nextjs/app/client-only.cjs +453 -435
  8. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  9. package/dist/host/nextjs/app/client-only.js +461 -443
  10. package/dist/host/nextjs/app/client-only.js.map +1 -1
  11. package/dist/host/react.cjs +381 -362
  12. package/dist/host/react.cjs.map +1 -1
  13. package/dist/host/react.js +381 -362
  14. package/dist/host/react.js.map +1 -1
  15. package/dist/internal/host/nextjs/image-shared.cjs +2 -2
  16. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  17. package/dist/internal/host/nextjs/image-shared.js +2 -2
  18. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  19. package/dist/internal/host/server/fetch-remote-component.cjs +20 -1
  20. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  21. package/dist/internal/host/server/fetch-remote-component.js +20 -1
  22. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  23. package/dist/internal/host/shared/remote-image-loader.cjs +2 -5
  24. package/dist/internal/host/shared/remote-image-loader.cjs.map +1 -1
  25. package/dist/internal/host/shared/remote-image-loader.js +2 -5
  26. package/dist/internal/host/shared/remote-image-loader.js.map +1 -1
  27. package/dist/internal/runtime/turbopack/chunk-loader.cjs +76 -126
  28. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  29. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +22 -7
  30. package/dist/internal/runtime/turbopack/chunk-loader.js +85 -131
  31. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  32. package/dist/internal/runtime/turbopack/module.cjs +56 -57
  33. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  34. package/dist/internal/runtime/turbopack/module.d.ts +14 -11
  35. package/dist/internal/runtime/turbopack/module.js +54 -56
  36. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  37. package/dist/internal/runtime/turbopack/remote-scope.cjs +101 -0
  38. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -0
  39. package/dist/internal/runtime/turbopack/remote-scope.d.ts +55 -0
  40. package/dist/internal/runtime/turbopack/remote-scope.js +73 -0
  41. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -0
  42. package/dist/internal/runtime/turbopack/shared-modules.cjs +62 -56
  43. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  44. package/dist/internal/runtime/turbopack/shared-modules.d.ts +7 -3
  45. package/dist/internal/runtime/turbopack/shared-modules.js +63 -57
  46. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  47. package/dist/internal/runtime/turbopack/webpack-runtime.cjs +39 -29
  48. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +1 -1
  49. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +5 -2
  50. package/dist/internal/runtime/turbopack/webpack-runtime.js +42 -32
  51. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +1 -1
  52. package/dist/internal/runtime/types.cjs.map +1 -1
  53. package/dist/internal/runtime/types.d.ts +4 -3
  54. package/dist/internal/utils/logger.cjs.map +1 -1
  55. package/dist/internal/utils/logger.d.ts +1 -1
  56. package/dist/internal/utils/logger.js.map +1 -1
  57. package/dist/internal/utils.cjs +5 -0
  58. package/dist/internal/utils.cjs.map +1 -1
  59. package/dist/internal/utils.d.ts +15 -1
  60. package/dist/internal/utils.js +4 -0
  61. package/dist/internal/utils.js.map +1 -1
  62. package/dist/remote/html.cjs.map +1 -1
  63. package/dist/remote/html.js.map +1 -1
  64. package/package.json +1 -1
@@ -67,90 +67,40 @@ __export(app_client_only_exports, {
67
67
  module.exports = __toCommonJS(app_client_only_exports);
68
68
  var import_react5 = require("react");
69
69
 
70
- // src/host/shared/remote-image-loader.ts
71
- function getRemoteBundleOrigin(bundle) {
72
- const self = globalThis;
73
- return self.__remote_bundle_url__?.[bundle]?.origin ?? "";
74
- }
75
- function createRemoteImageLoader(bundle, resolveClientUrl) {
76
- const loader = Object.assign(
77
- ({
78
- config,
79
- src,
80
- width,
81
- quality
82
- }) => {
83
- const q = quality ?? 75;
84
- const remoteOrigin = getRemoteBundleOrigin(bundle);
85
- const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;
86
- const basePath = isCrossOrigin ? `${remoteOrigin}${config.path ?? "/_next/image"}` : config.path ?? `${remoteOrigin}/_next/image`;
87
- const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;
88
- return resolveClientUrl?.(url) ?? url;
89
- },
90
- // Signals to getImgProps that this is a default loader (not a user-defined
91
- // one), enabling srcSet generation with device/image sizes from the config.
92
- { __next_img_default: true }
93
- );
94
- return loader;
95
- }
96
-
97
- // src/runtime/url/resolve-client-url.ts
98
- function withRemoteSrc(resolveClientUrl, remoteSrc) {
99
- const remoteOrigin = parseOrigin(remoteSrc);
100
- return (url) => {
101
- const urlOrigin = parseOrigin(url);
102
- if (remoteOrigin && urlOrigin && urlOrigin !== remoteOrigin) {
103
- return void 0;
104
- }
105
- return resolveClientUrl(remoteSrc, url);
106
- };
70
+ // src/utils/index.ts
71
+ function escapeString(str) {
72
+ return str.replace(/[^a-z0-9]/g, "_");
107
73
  }
108
- function parseOrigin(url) {
109
- try {
110
- return new URL(url).origin;
111
- } catch {
112
- return void 0;
113
- }
74
+ function computeScopedName(name, options) {
75
+ return options.isCrossOrigin ? `${name}_${escapeString(options.remoteHost.toLowerCase())}` : name;
114
76
  }
77
+ var attrToProp = {
78
+ fetchpriority: "fetchPriority",
79
+ crossorigin: "crossOrigin",
80
+ imagesrcset: "imageSrcSet",
81
+ imagesizes: "imageSizes",
82
+ srcset: "srcSet"
83
+ };
115
84
 
116
- // src/runtime/url/default-resolve-client-url.ts
117
- function bindResolveClientUrl(prop, remoteSrc) {
118
- return prop ? withRemoteSrc(prop, remoteSrc) : void 0;
85
+ // src/runtime/constants.ts
86
+ var DEFAULT_BUNDLE_NAME = "__vercel_remote_bundle";
87
+ var DEFAULT_COMPONENT_NAME = "__vercel_remote_component";
88
+ var DEFAULT_ROUTE = "/";
89
+ var RUNTIME_WEBPACK = "webpack";
90
+ var RUNTIME_TURBOPACK = "turbopack";
91
+ var RUNTIME_SCRIPT = "script";
92
+ function getBundleKey(bundle) {
93
+ return escapeString(bundle);
119
94
  }
120
95
 
121
- // src/host/nextjs/image-shared.ts
122
- function resolveForBundle(unbound, bundle) {
123
- if (!unbound)
124
- return void 0;
125
- const self = globalThis;
126
- const remoteSrc = self.__remote_bundle_url__?.[bundle]?.href ?? "";
127
- return bindResolveClientUrl(unbound, remoteSrc);
128
- }
129
- function createImageLoaderSharedEntries({
130
- bound,
131
- unbound
132
- } = {}) {
133
- const entry = (bundle) => {
134
- const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
135
- return Promise.resolve({
136
- default: createRemoteImageLoader(bundle, resolveClientUrl),
137
- __esModule: true
138
- });
139
- };
140
- return {
141
- "next/dist/shared/lib/image-loader": entry,
142
- "next/dist/esm/shared/lib/image-loader": entry
143
- };
96
+ // src/runtime/patterns.ts
97
+ var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
98
+ var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
99
+ var DOUBLE_SLASH_RE = /(?<!:)\/\//g;
100
+ function collapseDoubleSlashes(path) {
101
+ return path.replace(DOUBLE_SLASH_RE, "/");
144
102
  }
145
103
 
146
- // src/host/nextjs/app-client-only.tsx
147
- var import_context3 = require("#internal/host/react/context");
148
-
149
- // src/host/react/index.tsx
150
- var import_react3 = require("react");
151
- var import_react_dom = require("react-dom");
152
- var import_context2 = require("#internal/host/react/context");
153
-
154
104
  // src/utils/logger.ts
155
105
  init_constants();
156
106
 
@@ -297,6 +247,148 @@ function warnCrossOriginFetchError(logLocation, url) {
297
247
  }
298
248
  }
299
249
 
250
+ // src/runtime/turbopack/remote-scope.ts
251
+ function getRegistry() {
252
+ const self = globalThis;
253
+ if (!self.__remote_component_scopes__) {
254
+ self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
255
+ }
256
+ return self.__remote_component_scopes__;
257
+ }
258
+ function createScope(name, url, runtime, resolveClientUrl) {
259
+ const isCrossOrigin = url.origin !== location.origin;
260
+ const scopedName = computeScopedName(name, {
261
+ remoteHost: url.host,
262
+ isCrossOrigin
263
+ });
264
+ const globalKey = getBundleKey(scopedName);
265
+ return {
266
+ name,
267
+ scopedName,
268
+ globalKey,
269
+ url,
270
+ runtime,
271
+ resolveClientUrl,
272
+ moduleCache: {},
273
+ sharedModules: {},
274
+ moduleGlobal: {}
275
+ };
276
+ }
277
+ function registerScope(scope) {
278
+ const registry = getRegistry();
279
+ registry.set(scope.scopedName, scope);
280
+ if (scope.scopedName !== scope.name) {
281
+ const existing = registry.get(scope.name);
282
+ if (existing && existing.scopedName !== scope.scopedName) {
283
+ logWarn(
284
+ "RemoteScope",
285
+ `Plain name "${scope.name}" already registered by scope "${existing.scopedName}" \u2014 overwriting with "${scope.scopedName}". Static hosts will only resolve the latest one.`
286
+ );
287
+ }
288
+ registry.set(scope.name, scope);
289
+ }
290
+ logDebug(
291
+ "RemoteScope",
292
+ `Registered scope "${scope.scopedName}" (${registry.size} total)`
293
+ );
294
+ }
295
+ function getScope(name) {
296
+ return getRegistry().get(name);
297
+ }
298
+ function formatRemoteId(scope, path) {
299
+ return `[${scope.scopedName}] ${path}`;
300
+ }
301
+ function parseRemoteId(id) {
302
+ const groups = REMOTE_COMPONENT_REGEX.exec(id)?.groups;
303
+ if (groups?.bundle && groups.id) {
304
+ return {
305
+ bundle: groups.bundle,
306
+ path: groups.id,
307
+ prefix: groups.prefix ?? ""
308
+ };
309
+ }
310
+ return { bundle: "default", path: id, prefix: "" };
311
+ }
312
+
313
+ // src/host/shared/remote-image-loader.ts
314
+ function createRemoteImageLoader(bundle, resolveClientUrl) {
315
+ const loader = Object.assign(
316
+ ({
317
+ config,
318
+ src,
319
+ width,
320
+ quality
321
+ }) => {
322
+ const q = quality ?? 75;
323
+ const remoteOrigin = getScope(bundle)?.url.origin ?? "";
324
+ const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;
325
+ const basePath = isCrossOrigin ? `${remoteOrigin}${config.path ?? "/_next/image"}` : config.path ?? `${remoteOrigin}/_next/image`;
326
+ const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;
327
+ return resolveClientUrl?.(url) ?? url;
328
+ },
329
+ // Signals to getImgProps that this is a default loader (not a user-defined
330
+ // one), enabling srcSet generation with device/image sizes from the config.
331
+ { __next_img_default: true }
332
+ );
333
+ return loader;
334
+ }
335
+
336
+ // src/runtime/url/resolve-client-url.ts
337
+ function withRemoteSrc(resolveClientUrl, remoteSrc) {
338
+ const remoteOrigin = parseOrigin(remoteSrc);
339
+ return (url) => {
340
+ const urlOrigin = parseOrigin(url);
341
+ if (remoteOrigin && urlOrigin && urlOrigin !== remoteOrigin) {
342
+ return void 0;
343
+ }
344
+ return resolveClientUrl(remoteSrc, url);
345
+ };
346
+ }
347
+ function parseOrigin(url) {
348
+ try {
349
+ return new URL(url).origin;
350
+ } catch {
351
+ return void 0;
352
+ }
353
+ }
354
+
355
+ // src/runtime/url/default-resolve-client-url.ts
356
+ function bindResolveClientUrl(prop, remoteSrc) {
357
+ return prop ? withRemoteSrc(prop, remoteSrc) : void 0;
358
+ }
359
+
360
+ // src/host/nextjs/image-shared.ts
361
+ function resolveForBundle(unbound, bundle) {
362
+ if (!unbound)
363
+ return void 0;
364
+ const remoteSrc = getScope(bundle)?.url.href ?? "";
365
+ return bindResolveClientUrl(unbound, remoteSrc);
366
+ }
367
+ function createImageLoaderSharedEntries({
368
+ bound,
369
+ unbound
370
+ } = {}) {
371
+ const entry = (bundle) => {
372
+ const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
373
+ return Promise.resolve({
374
+ default: createRemoteImageLoader(bundle, resolveClientUrl),
375
+ __esModule: true
376
+ });
377
+ };
378
+ return {
379
+ "next/dist/shared/lib/image-loader": entry,
380
+ "next/dist/esm/shared/lib/image-loader": entry
381
+ };
382
+ }
383
+
384
+ // src/host/nextjs/app-client-only.tsx
385
+ var import_context3 = require("#internal/host/react/context");
386
+
387
+ // src/host/react/index.tsx
388
+ var import_react3 = require("react");
389
+ var import_react_dom = require("react-dom");
390
+ var import_context2 = require("#internal/host/react/context");
391
+
300
392
  // src/host/server/fetch-headers.ts
301
393
  function remoteFetchHeaders() {
302
394
  return {
@@ -521,29 +613,6 @@ function resolveNameFromSrc(src, defaultName) {
521
613
  return name || defaultName;
522
614
  }
523
615
 
524
- // src/utils/index.ts
525
- function escapeString(str) {
526
- return str.replace(/[^a-z0-9]/g, "_");
527
- }
528
- var attrToProp = {
529
- fetchpriority: "fetchPriority",
530
- crossorigin: "crossOrigin",
531
- imagesrcset: "imageSrcSet",
532
- imagesizes: "imageSizes",
533
- srcset: "srcSet"
534
- };
535
-
536
- // src/runtime/constants.ts
537
- var DEFAULT_BUNDLE_NAME = "__vercel_remote_bundle";
538
- var DEFAULT_COMPONENT_NAME = "__vercel_remote_component";
539
- var DEFAULT_ROUTE = "/";
540
- var RUNTIME_WEBPACK = "webpack";
541
- var RUNTIME_TURBOPACK = "turbopack";
542
- var RUNTIME_SCRIPT = "script";
543
- function getBundleKey(bundle) {
544
- return escapeString(bundle);
545
- }
546
-
547
616
  // src/runtime/html/apply-origin.ts
548
617
  var tagNames = [
549
618
  "img",
@@ -1018,14 +1087,6 @@ function createRSCStream(rscName, data) {
1018
1087
  });
1019
1088
  }
1020
1089
 
1021
- // src/runtime/patterns.ts
1022
- var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
1023
- var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
1024
- var DOUBLE_SLASH_RE = /(?<!:)\/\//g;
1025
- function collapseDoubleSlashes(path) {
1026
- return path.replace(DOUBLE_SLASH_RE, "/");
1027
- }
1028
-
1029
1090
  // src/runtime/turbopack/patterns.ts
1030
1091
  var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
1031
1092
  var REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
@@ -1035,62 +1096,39 @@ var ASYNC_MODULE_ALL_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<vCb
1035
1096
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
1036
1097
 
1037
1098
  // src/runtime/turbopack/chunk-loader.ts
1038
- function createChunkLoader(runtime, resolveClientUrl) {
1039
- return function __turbopack_chunk_load__(chunkId, scriptBundle) {
1040
- logDebug("ChunkLoader", `Loading chunk: "${chunkId}"`);
1041
- const self = globalThis;
1042
- const {
1043
- bundle,
1044
- id: path,
1045
- prefix
1046
- } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {
1047
- bundle: scriptBundle ?? "",
1048
- id: chunkId
1049
- };
1050
- logDebug(
1051
- "ChunkLoader",
1052
- `Parsed chunk - bundle: "${bundle}", path: "${path}", prefix: "${prefix}"`
1053
- );
1054
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1055
- logDebug("ChunkLoader", `Remote runtime: "${remoteRuntime}"`);
1056
- if (remoteRuntime === RUNTIME_WEBPACK) {
1057
- logDebug("ChunkLoader", "Skipping chunk load - webpack runtime detected");
1058
- return Promise.resolve(void 0);
1059
- }
1060
- const url = new URL(
1061
- path ? `${prefix ?? ""}${path}`.replace(
1062
- /(?<char>[^:])(?<double>\/\/)/g,
1063
- "$1/"
1064
- ) : "/",
1065
- self.__remote_bundle_url__?.[bundle ?? "default"] ?? new URL(location.origin)
1066
- ).href;
1067
- if (url.endsWith(".css")) {
1068
- logDebug("ChunkLoader", `Skipping CSS file: "${url}"`);
1069
- return;
1070
- }
1071
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1072
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
1073
- }
1074
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1075
- logDebug("ChunkLoader", `Returning cached promise for: "${url}"`);
1076
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1077
- }
1078
- const resolvedUrl = resolveClientUrl?.(url) ?? url;
1079
- logDebug("ChunkLoader", `Fetching chunk from: "${resolvedUrl}"`);
1080
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise((resolve, reject) => {
1099
+ function loadChunkWithScope(scope, chunkId) {
1100
+ logDebug(
1101
+ "ChunkLoader",
1102
+ `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
1103
+ );
1104
+ const self = globalThis;
1105
+ const { bundle, path, prefix } = parseRemoteId(chunkId);
1106
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
1107
+ if (remoteRuntime === RUNTIME_WEBPACK) {
1108
+ return Promise.resolve(void 0);
1109
+ }
1110
+ const rawPath = path ? collapseDoubleSlashes(`${prefix}${path}`) : "/";
1111
+ const url = new URL(rawPath, scope.url).href;
1112
+ if (url.endsWith(".css")) {
1113
+ return;
1114
+ }
1115
+ if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1116
+ self.__remote_components_turbopack_chunk_loader_promise__ = {};
1117
+ }
1118
+ if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1119
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
1120
+ }
1121
+ const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1122
+ if (resolvedUrl !== url) {
1123
+ logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1124
+ }
1125
+ self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1126
+ (resolve, reject) => {
1081
1127
  fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1082
1128
  const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1083
1129
  if (hasTurbopack) {
1084
- return handleTurbopackChunk(code, bundle ?? "", url);
1130
+ return handleTurbopackChunk(code, scope, url);
1085
1131
  }
1086
- logDebug(
1087
- "ChunkLoader",
1088
- `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: "${url}"`
1089
- );
1090
- logDebug(
1091
- "ChunkLoader",
1092
- `First 500 chars of chunk: ${code.slice(0, 500)}`
1093
- );
1094
1132
  }).then(resolve).catch((error) => {
1095
1133
  const isProxied = isProxiedUrl(resolvedUrl);
1096
1134
  if (isProxied) {
@@ -1100,17 +1138,29 @@ function createChunkLoader(runtime, resolveClientUrl) {
1100
1138
  reject(error);
1101
1139
  }
1102
1140
  });
1103
- });
1104
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1141
+ }
1142
+ );
1143
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
1144
+ }
1145
+ function createChunkDispatcher() {
1146
+ return function __chunk_dispatcher__(chunkId, scriptBundle) {
1147
+ logDebug("ChunkDispatcher", `Dispatching chunk: "${chunkId}"`);
1148
+ const { bundle } = parseRemoteId(chunkId);
1149
+ const bundleName = bundle || scriptBundle || "default";
1150
+ const scope = getScope(bundleName);
1151
+ logDebug(
1152
+ "ChunkDispatcher",
1153
+ `Scope resolution: bundle="${bundleName}", scope=${scope?.scopedName ?? "null"}`
1154
+ );
1155
+ if (!scope) {
1156
+ logWarn("ChunkDispatcher", `No scope found for bundle "${bundleName}"`);
1157
+ return Promise.resolve(void 0);
1158
+ }
1159
+ return loadChunkWithScope(scope, chunkId);
1105
1160
  };
1106
1161
  }
1107
- async function handleTurbopackChunk(code, bundle, url) {
1108
- logDebug(
1109
- "ChunkLoader",
1110
- `Handling Turbopack chunk - bundle: "${bundle}", url: "${url}"`
1111
- );
1162
+ async function handleTurbopackChunk(code, scope, url) {
1112
1163
  if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
1113
- logDebug("ChunkLoader", `Skipping worker chunk: "${url}"`);
1114
1164
  const preloadLinks = document.querySelectorAll(
1115
1165
  `link[rel="preload"][href="${new URL(url).pathname}"]`
1116
1166
  );
@@ -1118,58 +1168,41 @@ async function handleTurbopackChunk(code, bundle, url) {
1118
1168
  return;
1119
1169
  }
1120
1170
  const self = globalThis;
1121
- const bundleKey = getBundleKey(bundle);
1122
- logDebug("ChunkLoader", `Bundle key: "${bundleKey}"`);
1171
+ const { globalKey } = scope;
1123
1172
  const transformedCode = code.replace(
1124
1173
  /globalThis\[\s*["']TURBOPACK["']\s*\]/g,
1125
- `globalThis["TURBOPACK_${bundleKey}"]`
1174
+ `globalThis["TURBOPACK_${globalKey}"]`
1126
1175
  ).replace(
1127
1176
  /self\[\s*["']TURBOPACK["']\s*\]/g,
1128
- `self["TURBOPACK_${bundleKey}"]`
1129
- ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`).replace(
1177
+ `self["TURBOPACK_${globalKey}"]`
1178
+ ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`).replace(
1130
1179
  /TURBOPACK_WORKER_LOCATION/g,
1131
- `TURBOPACK_WORKER_LOCATION_${bundleKey}`
1180
+ `TURBOPACK_WORKER_LOCATION_${globalKey}`
1132
1181
  ).replace(
1133
1182
  /TURBOPACK_NEXT_CHUNK_URLS/g,
1134
- `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
1183
+ `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`
1135
1184
  ).replace(
1136
1185
  /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
1137
- `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
1138
- ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
1186
+ `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`
1187
+ ).replace(/__next_require__/g, `__${globalKey}_next_require__`).replace(
1139
1188
  /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
1140
- `//# sourceMappingURL=${new URL(
1141
- ".",
1142
- new URL(
1143
- url,
1144
- self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin)
1145
- )
1146
- ).href}$1$2.js.map`
1189
+ `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1147
1190
  );
1148
- if (!self[`TURBOPACK_${bundleKey}`]) {
1191
+ if (!self[`TURBOPACK_${globalKey}`]) {
1149
1192
  const chunkData = [];
1150
1193
  const turbopackObject = {
1151
1194
  push: (item) => {
1152
- logDebug(
1153
- "ChunkLoader",
1154
- `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? "array" : typeof item}`
1155
- );
1156
1195
  if (Array.isArray(item)) {
1157
1196
  chunkData.push(item);
1158
- logDebug(
1159
- "ChunkLoader",
1160
- `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`
1161
- );
1162
1197
  } else {
1163
1198
  chunkData.push([item]);
1164
1199
  }
1165
1200
  return chunkData.length;
1166
1201
  },
1167
- // Store chunks for later access
1168
1202
  __chunks__: chunkData
1169
1203
  };
1170
- self[`TURBOPACK_${bundleKey}`] = turbopackObject;
1204
+ self[`TURBOPACK_${globalKey}`] = turbopackObject;
1171
1205
  }
1172
- logDebug("ChunkLoader", `Creating blob script for: "${url}"`);
1173
1206
  await new Promise((scriptResolve, scriptReject) => {
1174
1207
  const blob = new Blob([transformedCode], {
1175
1208
  type: "application/javascript; charset=UTF-8"
@@ -1181,21 +1214,6 @@ async function handleTurbopackChunk(code, bundle, url) {
1181
1214
  script.async = true;
1182
1215
  script.onload = () => {
1183
1216
  URL.revokeObjectURL(scriptUrl);
1184
- logDebug(
1185
- "ChunkLoader",
1186
- `Script loaded successfully for bundle "${bundle}"`
1187
- );
1188
- const turbopackBundle = self[`TURBOPACK_${bundleKey}`];
1189
- logDebug(
1190
- "ChunkLoader",
1191
- `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${turbopackBundle ? Object.keys(turbopackBundle).slice(0, 10).join(", ") : "none"}`
1192
- );
1193
- if (turbopackBundle && typeof turbopackBundle === "object") {
1194
- logDebug(
1195
- "ChunkLoader",
1196
- `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle).length}`
1197
- );
1198
- }
1199
1217
  scriptResolve(void 0);
1200
1218
  script.remove();
1201
1219
  };
@@ -1210,43 +1228,177 @@ async function handleTurbopackChunk(code, bundle, url) {
1210
1228
  };
1211
1229
  document.head.appendChild(script);
1212
1230
  });
1213
- const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`];
1214
- logDebug(
1215
- "ChunkLoader",
1216
- `Processing chunk lists for bundle "${bundle}": ${chunkLists?.length ?? 0} lists`
1217
- );
1218
- const loadChunkLists = [];
1231
+ const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`];
1232
+ const loadChunkPromises = [];
1219
1233
  while (chunkLists?.length) {
1220
1234
  const { chunks } = chunkLists.shift() ?? { chunks: [] };
1221
1235
  if (chunks.length > 0) {
1222
- logDebug(
1223
- "ChunkLoader",
1224
- `Loading ${chunks.length} additional chunks for bundle "${bundle}": [${chunks.join(", ")}]`
1225
- );
1226
- chunks.forEach((id) => {
1227
- const chunkLoadResult = self.__webpack_chunk_load__?.(
1228
- `[${bundle}] ${url.slice(0, url.indexOf("/_next"))}/_next/${id}`
1236
+ for (const id of chunks) {
1237
+ const baseUrl = url.slice(0, url.indexOf("/_next"));
1238
+ const chunkLoadResult = loadChunkWithScope(
1239
+ scope,
1240
+ formatRemoteId(scope, `${baseUrl}/_next/${id}`)
1229
1241
  );
1230
1242
  if (chunkLoadResult) {
1231
- loadChunkLists.push(chunkLoadResult);
1243
+ loadChunkPromises.push(chunkLoadResult);
1232
1244
  }
1233
- });
1245
+ }
1234
1246
  }
1235
1247
  }
1236
- if (loadChunkLists.length > 0) {
1237
- logDebug(
1238
- "ChunkLoader",
1239
- `Waiting for ${loadChunkLists.length} additional chunks to load`
1248
+ if (loadChunkPromises.length > 0) {
1249
+ await Promise.all(loadChunkPromises);
1250
+ }
1251
+ }
1252
+
1253
+ // src/runtime/turbopack/shared-modules.ts
1254
+ 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).";
1255
+ function getTurbopackModules(scope) {
1256
+ const self = globalThis;
1257
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1258
+ if (!raw)
1259
+ return void 0;
1260
+ if (typeof raw === "object" && "__chunks__" in raw) {
1261
+ return raw.__chunks__.flat();
1262
+ }
1263
+ if (Array.isArray(raw)) {
1264
+ return raw.flat();
1265
+ }
1266
+ return Object.entries(raw).flat();
1267
+ }
1268
+ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}) {
1269
+ const allModules = getTurbopackModules(scope);
1270
+ logDebug(
1271
+ "SharedModules",
1272
+ `initializeSharedModules: scope="${scope.scopedName}", allModules=${allModules ? allModules.length : "null"}, hostShared=[${Object.keys(hostShared).join(", ")}], remoteShared=${JSON.stringify(remoteShared)}`
1273
+ );
1274
+ let sharedModuleInitializer = null;
1275
+ if (allModules) {
1276
+ const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1277
+ if (typeof idOrFunc !== "function") {
1278
+ return false;
1279
+ }
1280
+ const funcCode = idOrFunc.toString();
1281
+ return REMOTE_SHARED_MARKER_RE.test(funcCode);
1282
+ });
1283
+ if (sharedModuleInitializerIndex > 0) {
1284
+ const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1285
+ const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1286
+ const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1287
+ if (sharedModuleId) {
1288
+ const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1289
+ scope,
1290
+ sharedModuleId,
1291
+ formatRemoteId(scope, String(sharedModuleInitializerId))
1292
+ );
1293
+ sharedModuleInitializer = sharedModuleInitializerInstance;
1294
+ }
1295
+ }
1296
+ if (sharedModuleInitializer) {
1297
+ const { shared: shared2 } = await sharedModuleInitializer;
1298
+ const sharedModuleIds = extractSharedModuleIds(shared2, scope);
1299
+ logDebug(
1300
+ "SharedModules",
1301
+ `Resolved shared modules for scope="${scope.scopedName}": ${JSON.stringify(sharedModuleIds)}`
1302
+ );
1303
+ return Promise.all(
1304
+ Object.entries(sharedModuleIds).map(async ([id, module2]) => {
1305
+ if (hostShared[module2]) {
1306
+ scope.sharedModules[id] = await hostShared[module2](scope.name);
1307
+ } else {
1308
+ logError(
1309
+ "SharedModules",
1310
+ `Host shared module "${module2}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1311
+ );
1312
+ }
1313
+ })
1314
+ );
1315
+ }
1316
+ logWarn(
1317
+ "SharedModules",
1318
+ `No shared module initializer found in bundle for scope="${scope.scopedName}" \u2014 falling back to remoteShared mapping`
1240
1319
  );
1241
- await Promise.all(loadChunkLists);
1320
+ } else {
1321
+ logWarn(
1322
+ "SharedModules",
1323
+ `No TURBOPACK modules found for scope="${scope.scopedName}" (TURBOPACK_${scope.globalKey} is empty)`
1324
+ );
1325
+ }
1326
+ return Promise.all(
1327
+ Object.entries(remoteShared).map(async ([id, module2]) => {
1328
+ if (hostShared[module2]) {
1329
+ const normalizedId = id.replace("[app-ssr]", "[app-client]");
1330
+ scope.sharedModules[normalizedId] = await hostShared[module2](
1331
+ scope.name
1332
+ );
1333
+ } else {
1334
+ logError(
1335
+ "SharedModules",
1336
+ `Shared module "${module2}" not found for "${scope.name}". ${DEDUPLICATION_WARNING}`
1337
+ );
1338
+ }
1339
+ })
1340
+ );
1341
+ }
1342
+ function extractSharedModuleIds(shared2, scope) {
1343
+ return Object.entries(shared2).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1344
+ const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1345
+ if (asyncSharedModuleId) {
1346
+ const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1347
+ let asyncSharedModule;
1348
+ const turbopackModules = getTurbopackModules(scope) ?? [];
1349
+ const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1350
+ asyncSharedModuleIdNumber
1351
+ );
1352
+ if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1353
+ asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1354
+ }
1355
+ if (asyncSharedModule) {
1356
+ const asyncSharedModuleCode = asyncSharedModule.toString();
1357
+ const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1358
+ acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1359
+ "__remote_shared_module_",
1360
+ ""
1361
+ );
1362
+ }
1363
+ }
1364
+ return acc;
1365
+ }, {});
1366
+ }
1367
+ function getSharedModule(scope, id) {
1368
+ const idStr = String(id);
1369
+ if (scope.sharedModules[idStr] !== void 0) {
1370
+ return scope.sharedModules[idStr];
1371
+ }
1372
+ for (const [key, value] of Object.entries(scope.sharedModules)) {
1373
+ if (typeof value !== "undefined" && idStr !== key && idStr.endsWith(key)) {
1374
+ return value;
1375
+ }
1242
1376
  }
1377
+ return null;
1243
1378
  }
1244
1379
 
1245
1380
  // src/runtime/turbopack/module.ts
1246
- function handleTurbopackModule(bundle, moduleId, id) {
1381
+ function requireModule(scope, moduleId, fullId) {
1382
+ const idStr = String(moduleId);
1383
+ if (scope.moduleCache[idStr])
1384
+ return scope.moduleCache[idStr];
1385
+ const sharedModule = getSharedModule(scope, moduleId);
1386
+ if (sharedModule) {
1387
+ scope.moduleCache[idStr] = sharedModule;
1388
+ return sharedModule;
1389
+ }
1390
+ return handleTurbopackModule(
1391
+ scope,
1392
+ idStr,
1393
+ fullId ?? formatRemoteId(scope, idStr)
1394
+ );
1395
+ }
1396
+ function handleTurbopackModule(scope, moduleId, id) {
1247
1397
  const self = globalThis;
1248
- const bundleKey = getBundleKey(bundle);
1249
- const raw = self[`TURBOPACK_${bundleKey}`];
1398
+ if (scope.moduleCache[moduleId]) {
1399
+ return scope.moduleCache[moduleId];
1400
+ }
1401
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1250
1402
  let modules;
1251
1403
  if (raw && typeof raw === "object" && "__chunks__" in raw) {
1252
1404
  modules = raw.__chunks__.flat();
@@ -1255,48 +1407,35 @@ function handleTurbopackModule(bundle, moduleId, id) {
1255
1407
  } else {
1256
1408
  modules = raw;
1257
1409
  }
1258
- if (!self.__remote_components_turbopack_modules__) {
1259
- self.__remote_components_turbopack_modules__ = {};
1260
- }
1261
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1262
- self.__remote_components_turbopack_modules__[bundle] = {};
1263
- }
1264
- if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
1265
- return self.__remote_components_turbopack_modules__[bundle][moduleId];
1266
- }
1267
1410
  if (!modules) {
1268
- logError("TurbopackModule", `TURBOPACK_${bundleKey} is undefined`);
1411
+ logError(
1412
+ "TurbopackModule",
1413
+ `TURBOPACK_${scope.globalKey} is undefined (scope: "${scope.scopedName}")`
1414
+ );
1269
1415
  }
1270
1416
  const moduleInit = findModuleInit(modules, moduleId);
1271
1417
  const exports = {};
1272
1418
  const moduleExports = { exports };
1273
1419
  if (typeof moduleInit !== "function") {
1274
1420
  throw new Error(
1275
- `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
1421
+ `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`
1276
1422
  );
1277
1423
  }
1278
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1279
- if (!self.__remote_components_turbopack_global__) {
1280
- self.__remote_components_turbopack_global__ = {};
1281
- }
1282
- if (!self.__remote_components_turbopack_global__[bundle]) {
1283
- self.__remote_components_turbopack_global__[bundle] = {};
1284
- }
1424
+ scope.moduleCache[moduleId] = moduleExports.exports;
1285
1425
  moduleInit(
1286
1426
  createTurbopackContext(
1287
- bundle,
1427
+ scope,
1288
1428
  exports,
1289
1429
  moduleExports,
1290
1430
  modules,
1291
1431
  moduleInit,
1292
- id,
1293
- self
1432
+ id
1294
1433
  ),
1295
1434
  moduleExports,
1296
1435
  exports
1297
1436
  );
1298
- if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
1299
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1437
+ if (scope.moduleCache[moduleId] !== moduleExports.exports) {
1438
+ scope.moduleCache[moduleId] = moduleExports.exports;
1300
1439
  }
1301
1440
  return moduleExports.exports;
1302
1441
  }
@@ -1321,7 +1460,8 @@ function findModuleInit(modules, moduleId) {
1321
1460
  (e) => Boolean(e && typeof e === "object" && moduleId in e)
1322
1461
  )?.[moduleId];
1323
1462
  }
1324
- function createTurbopackContext(bundle, exports, moduleExports, modules, moduleInit, id, self) {
1463
+ function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1464
+ const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
1325
1465
  return {
1326
1466
  // HMR not implemented for Remote Components
1327
1467
  k: {
@@ -1337,16 +1477,10 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1337
1477
  s(bindings, esmId) {
1338
1478
  let mod = exports;
1339
1479
  if (typeof esmId === "string" || typeof esmId === "number") {
1340
- if (!self.__remote_components_turbopack_modules__) {
1341
- self.__remote_components_turbopack_modules__ = {};
1342
- }
1343
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1344
- self.__remote_components_turbopack_modules__[bundle] = {};
1480
+ if (!scope.moduleCache[esmId]) {
1481
+ scope.moduleCache[esmId] = {};
1345
1482
  }
1346
- if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
1347
- self.__remote_components_turbopack_modules__[bundle][esmId] = {};
1348
- }
1349
- mod = self.__remote_components_turbopack_modules__[bundle][esmId];
1483
+ mod = scope.moduleCache[esmId];
1350
1484
  }
1351
1485
  Object.defineProperty(mod, "__esModule", { value: true });
1352
1486
  if (Array.isArray(bindings)) {
@@ -1379,7 +1513,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1379
1513
  }
1380
1514
  }
1381
1515
  },
1382
- // import
1516
+ // import — resolves directly via scope, no global dispatch
1383
1517
  i(importId) {
1384
1518
  let mod;
1385
1519
  if (typeof importId === "string") {
@@ -1390,7 +1524,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1390
1524
  /\s+<export(?<specifier>.*)>$/,
1391
1525
  ""
1392
1526
  );
1393
- mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`);
1527
+ mod = scopedRequire(normalizedId);
1394
1528
  if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
1395
1529
  if (exportSource === "*") {
1396
1530
  mod[exportName] = mod;
@@ -1399,7 +1533,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1399
1533
  }
1400
1534
  }
1401
1535
  } else {
1402
- mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
1536
+ mod = scopedRequire(importId);
1403
1537
  }
1404
1538
  if (typeof mod !== "object" || mod === null) {
1405
1539
  mod = { default: mod };
@@ -1411,16 +1545,14 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1411
1545
  }
1412
1546
  return mod;
1413
1547
  },
1414
- // require
1548
+ // require — resolves directly via scope
1415
1549
  r(requireId) {
1416
- return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
1550
+ return scopedRequire(requireId);
1417
1551
  },
1418
1552
  // value exports
1419
1553
  v(value) {
1420
1554
  if (typeof value === "function") {
1421
- exports.default = value((vid) => {
1422
- return self.__webpack_require__?.(`[${bundle}] ${vid}`);
1423
- });
1555
+ exports.default = value((vid) => scopedRequire(vid));
1424
1556
  } else {
1425
1557
  moduleExports.exports = value;
1426
1558
  }
@@ -1435,17 +1567,15 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1435
1567
  );
1436
1568
  exports.default = result;
1437
1569
  },
1438
- // async module loader
1570
+ // async module loader — resolves directly via scope
1439
1571
  async A(Aid) {
1440
- const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
1441
- return mod.default(
1442
- (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
1443
- );
1572
+ const mod = scopedRequire(Aid);
1573
+ return mod.default((parentId) => scopedRequire(parentId));
1444
1574
  },
1445
1575
  // dynamic import tracking — no-op for remote components
1446
1576
  j() {
1447
1577
  },
1448
- // chunk loader
1578
+ // chunk loader — loads directly via scope, no global dispatch
1449
1579
  l(url) {
1450
1580
  const flatModules = Array.isArray(modules) ? modules : [];
1451
1581
  const moduleInitIndex = flatModules.indexOf(moduleInit);
@@ -1456,169 +1586,57 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1456
1586
  const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1457
1587
  const nextIndex = scriptSrc.indexOf("/_next");
1458
1588
  const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1459
- const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
1460
- return self.__webpack_chunk_load__?.(bundleUrl, bundle);
1589
+ const chunkUrl = `${baseUrl}/_next/${url}`;
1590
+ return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));
1461
1591
  }
1462
1592
  }
1463
1593
  throw new Error(
1464
1594
  `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1465
1595
  );
1466
1596
  },
1467
- // global object for this bundle
1468
- g: self.__remote_components_turbopack_global__?.[bundle],
1597
+ // globalThis substitute shared across all modules in this scope
1598
+ g: scope.moduleGlobal,
1469
1599
  m: moduleExports,
1470
1600
  e: exports
1471
1601
  };
1472
1602
  }
1473
1603
 
1474
- // src/runtime/turbopack/shared-modules.ts
1475
- 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).";
1476
- async function initializeSharedModules(bundle, hostShared = {}, remoteShared = {}) {
1477
- const self = globalThis;
1478
- self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};
1479
- if (!self.__remote_shared_modules__[bundle]) {
1480
- self.__remote_shared_modules__[bundle] = {};
1481
- }
1482
- const bundleKey = getBundleKey(bundle);
1483
- let modules = self[`TURBOPACK_${bundleKey}`];
1484
- if (modules && typeof modules === "object" && "__chunks__" in modules) {
1485
- const chunks = modules.__chunks__;
1486
- modules = chunks.flat();
1487
- }
1488
- let sharedModuleInitializer = null;
1489
- if (modules) {
1490
- const allModules = Array.isArray(modules) ? modules.flat() : Object.entries(modules).flat();
1491
- const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1492
- if (typeof idOrFunc !== "function") {
1493
- return false;
1494
- }
1495
- const funcCode = idOrFunc.toString();
1496
- return REMOTE_SHARED_MARKER_RE.test(funcCode);
1497
- });
1498
- if (sharedModuleInitializerIndex > 0) {
1499
- const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1500
- const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1501
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1502
- if (sharedModuleId) {
1503
- const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1504
- bundle,
1505
- sharedModuleId,
1506
- `[${bundle}] ${sharedModuleInitializerId}`
1507
- );
1508
- sharedModuleInitializer = sharedModuleInitializerInstance;
1509
- }
1510
- }
1511
- if (sharedModuleInitializer) {
1512
- const { shared: shared2 } = await sharedModuleInitializer;
1513
- const sharedModuleIds = extractSharedModuleIds(
1514
- shared2,
1515
- bundleKey,
1516
- self
1517
- );
1518
- return Promise.all(
1519
- Object.entries(sharedModuleIds).map(async ([id, module2]) => {
1520
- if (self.__remote_shared_modules__?.[bundle]) {
1521
- if (hostShared[module2]) {
1522
- self.__remote_shared_modules__[bundle][id] = await hostShared[module2](bundle);
1523
- } else {
1524
- logError(
1525
- "SharedModules",
1526
- `Host shared module "${module2}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1527
- );
1528
- }
1529
- }
1530
- })
1531
- );
1532
- }
1533
- }
1534
- return Promise.all(
1535
- Object.entries(remoteShared).map(async ([id, module2]) => {
1536
- if (self.__remote_shared_modules__?.[bundle]) {
1537
- if (hostShared[module2]) {
1538
- const normalizedId = id.replace("[app-ssr]", "[app-client]");
1539
- self.__remote_shared_modules__[bundle][normalizedId] = await hostShared[module2](bundle);
1540
- } else {
1541
- logError(
1542
- "SharedModules",
1543
- `Shared module "${module2}" not found for "${bundle}". ${DEDUPLICATION_WARNING}`
1544
- );
1545
- }
1546
- }
1547
- })
1548
- );
1549
- }
1550
- function extractSharedModuleIds(shared2, bundleKey, self) {
1551
- return Object.entries(shared2).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1552
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1553
- if (asyncSharedModuleId) {
1554
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1555
- let asyncSharedModule;
1556
- let turbopackModules = self[`TURBOPACK_${bundleKey}`];
1557
- if (turbopackModules && typeof turbopackModules === "object" && "__chunks__" in turbopackModules) {
1558
- const chunks = turbopackModules.__chunks__;
1559
- turbopackModules = chunks.flat();
1560
- }
1561
- const newAllModules = Array.isArray(turbopackModules) ? turbopackModules.flat() : turbopackModules ? Object.entries(turbopackModules).flatMap(([key2, value2]) => [
1562
- key2,
1563
- value2
1564
- ]) : [];
1565
- const asyncSharedModuleIdIndex = newAllModules.indexOf(
1566
- asyncSharedModuleIdNumber
1567
- );
1568
- if (asyncSharedModuleIdIndex !== -1 && typeof newAllModules[asyncSharedModuleIdIndex + 1] === "function") {
1569
- asyncSharedModule = newAllModules[asyncSharedModuleIdIndex + 1];
1570
- }
1571
- if (asyncSharedModule) {
1572
- const asyncSharedModuleCode = asyncSharedModule.toString();
1573
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1574
- acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1575
- "__remote_shared_module_",
1576
- ""
1577
- );
1578
- }
1579
- }
1580
- return acc;
1581
- }, {});
1582
- }
1583
- function getSharedModule(bundle, id) {
1584
- const self = globalThis;
1585
- for (const [key, value] of Object.entries(
1586
- self.__remote_shared_modules__?.[bundle] ?? {}
1587
- )) {
1588
- if (typeof value !== "undefined" && (typeof id === "string" && id.includes(key) || id === key)) {
1589
- return value;
1590
- }
1591
- }
1592
- return null;
1593
- }
1594
-
1595
1604
  // src/runtime/turbopack/webpack-runtime.ts
1596
1605
  async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared2 = {}, remoteShared = {}, resolveClientUrl) {
1597
1606
  const self = globalThis;
1607
+ const bundleName = bundle ?? "default";
1608
+ const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1609
+ registerScope(scope);
1598
1610
  if (!self.__remote_bundle_url__) {
1599
1611
  self.__remote_bundle_url__ = {};
1600
1612
  }
1601
- self.__remote_bundle_url__[bundle ?? "default"] = url;
1613
+ self.__remote_bundle_url__[bundleName] = url;
1614
+ if (scope.scopedName !== bundleName) {
1615
+ self.__remote_bundle_url__[scope.scopedName] = url;
1616
+ }
1602
1617
  self.__webpack_get_script_filename__ = () => null;
1603
- if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
1618
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1619
+ if (willCreateDispatchers) {
1604
1620
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1605
1621
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1606
1622
  self.__original_webpack_require__ = self.__webpack_require__;
1607
1623
  }
1608
- self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);
1609
- self.__webpack_require__ = createModuleRequire(runtime);
1624
+ self.__webpack_chunk_load__ = createChunkDispatcher();
1625
+ self.__webpack_require__ = createModuleDispatcher(runtime);
1610
1626
  self.__webpack_require_type__ = runtime;
1611
1627
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1612
- const remoteBundle = bundle ?? "default";
1613
- self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
1614
- self.__remote_webpack_require__[remoteBundle].type = "turbopack";
1628
+ self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
1629
+ self.__remote_webpack_require__[bundleName].type = "turbopack";
1615
1630
  }
1616
1631
  }
1632
+ if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
1633
+ self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
1634
+ }
1617
1635
  if (runtime === RUNTIME_TURBOPACK) {
1618
1636
  const results = await Promise.allSettled(
1619
1637
  scripts.map((script) => {
1620
1638
  if (script.src) {
1621
- return self.__webpack_chunk_load__?.(script.src, bundle);
1639
+ return loadChunkWithScope(scope, script.src);
1622
1640
  }
1623
1641
  return Promise.resolve(void 0);
1624
1642
  })
@@ -1640,54 +1658,54 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1640
1658
  "react-dom/client": async () => (await import("react-dom/client")).default,
1641
1659
  ...shared2
1642
1660
  };
1643
- await initializeSharedModules(
1644
- bundle ?? "default",
1645
- // include all core modules as shared
1646
- coreShared,
1647
- remoteShared
1648
- );
1661
+ await initializeSharedModules(scope, coreShared, remoteShared);
1649
1662
  }
1650
- function createModuleRequire(runtime) {
1663
+ function createModuleDispatcher(runtime) {
1651
1664
  return (id) => {
1652
1665
  const self = globalThis;
1653
1666
  const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1654
1667
  bundle: "default",
1655
1668
  id
1656
1669
  };
1657
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1658
- logDebug("WebpackRuntime", `remoteRuntime: "${remoteRuntime}"`);
1670
+ const bundleName = bundle ?? "default";
1671
+ const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
1672
+ logDebug(
1673
+ "ModuleDispatcher",
1674
+ `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
1675
+ );
1659
1676
  try {
1660
1677
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1661
1678
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1662
1679
  }
1663
- const sharedModuleId = moduleId ?? id;
1664
- const sharedModule = getSharedModule(bundle ?? "default", sharedModuleId);
1665
- if (sharedModule) {
1666
- return sharedModule;
1680
+ const scope = getScope(bundleName);
1681
+ if (scope) {
1682
+ return requireModule(scope, moduleId ?? id, id);
1667
1683
  }
1668
- if (bundle && moduleId) {
1669
- return handleTurbopackModule(bundle, moduleId, id);
1670
- }
1671
- throw new Error(`Module "${id}" not found.`);
1684
+ throw new Error(
1685
+ `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
1686
+ );
1672
1687
  } catch (requireError) {
1673
1688
  logWarn(
1674
- "WebpackRuntime",
1689
+ "ModuleDispatcher",
1675
1690
  `Module require failed: ${String(requireError)}`
1676
1691
  );
1677
1692
  if (typeof self.__original_webpack_require__ !== "function") {
1678
1693
  throw new RemoteComponentsError(
1679
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1694
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1680
1695
  {
1681
1696
  cause: requireError instanceof Error ? requireError : void 0
1682
1697
  }
1683
1698
  );
1684
1699
  }
1685
1700
  try {
1686
- logDebug("WebpackRuntime", "Falling back to original webpack require");
1701
+ logDebug(
1702
+ "ModuleDispatcher",
1703
+ "Falling back to original webpack require"
1704
+ );
1687
1705
  return self.__original_webpack_require__(id);
1688
1706
  } catch (originalError) {
1689
1707
  throw new RemoteComponentsError(
1690
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1708
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1691
1709
  { cause: originalError instanceof Error ? originalError : void 0 }
1692
1710
  );
1693
1711
  }