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
@@ -39,98 +39,40 @@ var init_app = __esm({
39
39
  // src/host/nextjs/app-client-only.tsx
40
40
  import { useMemo as useMemo3 } from "react";
41
41
 
42
- // src/host/shared/remote-image-loader.ts
43
- function getRemoteBundleOrigin(bundle) {
44
- const self = globalThis;
45
- return self.__remote_bundle_url__?.[bundle]?.origin ?? "";
46
- }
47
- function createRemoteImageLoader(bundle, resolveClientUrl) {
48
- const loader = Object.assign(
49
- ({
50
- config,
51
- src,
52
- width,
53
- quality
54
- }) => {
55
- const q = quality ?? 75;
56
- const remoteOrigin = getRemoteBundleOrigin(bundle);
57
- const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;
58
- const basePath = isCrossOrigin ? `${remoteOrigin}${config.path ?? "/_next/image"}` : config.path ?? `${remoteOrigin}/_next/image`;
59
- const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;
60
- return resolveClientUrl?.(url) ?? url;
61
- },
62
- // Signals to getImgProps that this is a default loader (not a user-defined
63
- // one), enabling srcSet generation with device/image sizes from the config.
64
- { __next_img_default: true }
65
- );
66
- return loader;
67
- }
68
-
69
- // src/runtime/url/resolve-client-url.ts
70
- function withRemoteSrc(resolveClientUrl, remoteSrc) {
71
- const remoteOrigin = parseOrigin(remoteSrc);
72
- return (url) => {
73
- const urlOrigin = parseOrigin(url);
74
- if (remoteOrigin && urlOrigin && urlOrigin !== remoteOrigin) {
75
- return void 0;
76
- }
77
- return resolveClientUrl(remoteSrc, url);
78
- };
42
+ // src/utils/index.ts
43
+ function escapeString(str) {
44
+ return str.replace(/[^a-z0-9]/g, "_");
79
45
  }
80
- function parseOrigin(url) {
81
- try {
82
- return new URL(url).origin;
83
- } catch {
84
- return void 0;
85
- }
46
+ function computeScopedName(name, options) {
47
+ return options.isCrossOrigin ? `${name}_${escapeString(options.remoteHost.toLowerCase())}` : name;
86
48
  }
49
+ var attrToProp = {
50
+ fetchpriority: "fetchPriority",
51
+ crossorigin: "crossOrigin",
52
+ imagesrcset: "imageSrcSet",
53
+ imagesizes: "imageSizes",
54
+ srcset: "srcSet"
55
+ };
87
56
 
88
- // src/runtime/url/default-resolve-client-url.ts
89
- function bindResolveClientUrl(prop, remoteSrc) {
90
- return prop ? withRemoteSrc(prop, remoteSrc) : void 0;
57
+ // src/runtime/constants.ts
58
+ var DEFAULT_BUNDLE_NAME = "__vercel_remote_bundle";
59
+ var DEFAULT_COMPONENT_NAME = "__vercel_remote_component";
60
+ var DEFAULT_ROUTE = "/";
61
+ var RUNTIME_WEBPACK = "webpack";
62
+ var RUNTIME_TURBOPACK = "turbopack";
63
+ var RUNTIME_SCRIPT = "script";
64
+ function getBundleKey(bundle) {
65
+ return escapeString(bundle);
91
66
  }
92
67
 
93
- // src/host/nextjs/image-shared.ts
94
- function resolveForBundle(unbound, bundle) {
95
- if (!unbound)
96
- return void 0;
97
- const self = globalThis;
98
- const remoteSrc = self.__remote_bundle_url__?.[bundle]?.href ?? "";
99
- return bindResolveClientUrl(unbound, remoteSrc);
100
- }
101
- function createImageLoaderSharedEntries({
102
- bound,
103
- unbound
104
- } = {}) {
105
- const entry = (bundle) => {
106
- const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
107
- return Promise.resolve({
108
- default: createRemoteImageLoader(bundle, resolveClientUrl),
109
- __esModule: true
110
- });
111
- };
112
- return {
113
- "next/dist/shared/lib/image-loader": entry,
114
- "next/dist/esm/shared/lib/image-loader": entry
115
- };
68
+ // src/runtime/patterns.ts
69
+ var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
70
+ var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
71
+ var DOUBLE_SLASH_RE = /(?<!:)\/\//g;
72
+ function collapseDoubleSlashes(path) {
73
+ return path.replace(DOUBLE_SLASH_RE, "/");
116
74
  }
117
75
 
118
- // src/host/nextjs/app-client-only.tsx
119
- import { RemoteComponentsContext } from "#internal/host/react/context";
120
-
121
- // src/host/react/index.tsx
122
- import {
123
- startTransition,
124
- useEffect,
125
- useId,
126
- useLayoutEffect as useLayoutEffect2,
127
- useMemo as useMemo2,
128
- useRef as useRef2,
129
- useState as useState2
130
- } from "react";
131
- import { createPortal } from "react-dom";
132
- import { useRemoteComponentsContext as useRemoteComponentsContext2 } from "#internal/host/react/context";
133
-
134
76
  // src/utils/logger.ts
135
77
  init_constants();
136
78
 
@@ -277,6 +219,156 @@ function warnCrossOriginFetchError(logLocation, url) {
277
219
  }
278
220
  }
279
221
 
222
+ // src/runtime/turbopack/remote-scope.ts
223
+ function getRegistry() {
224
+ const self = globalThis;
225
+ if (!self.__remote_component_scopes__) {
226
+ self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
227
+ }
228
+ return self.__remote_component_scopes__;
229
+ }
230
+ function createScope(name, url, runtime, resolveClientUrl) {
231
+ const isCrossOrigin = url.origin !== location.origin;
232
+ const scopedName = computeScopedName(name, {
233
+ remoteHost: url.host,
234
+ isCrossOrigin
235
+ });
236
+ const globalKey = getBundleKey(scopedName);
237
+ return {
238
+ name,
239
+ scopedName,
240
+ globalKey,
241
+ url,
242
+ runtime,
243
+ resolveClientUrl,
244
+ moduleCache: {},
245
+ sharedModules: {},
246
+ moduleGlobal: {}
247
+ };
248
+ }
249
+ function registerScope(scope) {
250
+ const registry = getRegistry();
251
+ registry.set(scope.scopedName, scope);
252
+ if (scope.scopedName !== scope.name) {
253
+ const existing = registry.get(scope.name);
254
+ if (existing && existing.scopedName !== scope.scopedName) {
255
+ logWarn(
256
+ "RemoteScope",
257
+ `Plain name "${scope.name}" already registered by scope "${existing.scopedName}" \u2014 overwriting with "${scope.scopedName}". Static hosts will only resolve the latest one.`
258
+ );
259
+ }
260
+ registry.set(scope.name, scope);
261
+ }
262
+ logDebug(
263
+ "RemoteScope",
264
+ `Registered scope "${scope.scopedName}" (${registry.size} total)`
265
+ );
266
+ }
267
+ function getScope(name) {
268
+ return getRegistry().get(name);
269
+ }
270
+ function formatRemoteId(scope, path) {
271
+ return `[${scope.scopedName}] ${path}`;
272
+ }
273
+ function parseRemoteId(id) {
274
+ const groups = REMOTE_COMPONENT_REGEX.exec(id)?.groups;
275
+ if (groups?.bundle && groups.id) {
276
+ return {
277
+ bundle: groups.bundle,
278
+ path: groups.id,
279
+ prefix: groups.prefix ?? ""
280
+ };
281
+ }
282
+ return { bundle: "default", path: id, prefix: "" };
283
+ }
284
+
285
+ // src/host/shared/remote-image-loader.ts
286
+ function createRemoteImageLoader(bundle, resolveClientUrl) {
287
+ const loader = Object.assign(
288
+ ({
289
+ config,
290
+ src,
291
+ width,
292
+ quality
293
+ }) => {
294
+ const q = quality ?? 75;
295
+ const remoteOrigin = getScope(bundle)?.url.origin ?? "";
296
+ const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;
297
+ const basePath = isCrossOrigin ? `${remoteOrigin}${config.path ?? "/_next/image"}` : config.path ?? `${remoteOrigin}/_next/image`;
298
+ const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;
299
+ return resolveClientUrl?.(url) ?? url;
300
+ },
301
+ // Signals to getImgProps that this is a default loader (not a user-defined
302
+ // one), enabling srcSet generation with device/image sizes from the config.
303
+ { __next_img_default: true }
304
+ );
305
+ return loader;
306
+ }
307
+
308
+ // src/runtime/url/resolve-client-url.ts
309
+ function withRemoteSrc(resolveClientUrl, remoteSrc) {
310
+ const remoteOrigin = parseOrigin(remoteSrc);
311
+ return (url) => {
312
+ const urlOrigin = parseOrigin(url);
313
+ if (remoteOrigin && urlOrigin && urlOrigin !== remoteOrigin) {
314
+ return void 0;
315
+ }
316
+ return resolveClientUrl(remoteSrc, url);
317
+ };
318
+ }
319
+ function parseOrigin(url) {
320
+ try {
321
+ return new URL(url).origin;
322
+ } catch {
323
+ return void 0;
324
+ }
325
+ }
326
+
327
+ // src/runtime/url/default-resolve-client-url.ts
328
+ function bindResolveClientUrl(prop, remoteSrc) {
329
+ return prop ? withRemoteSrc(prop, remoteSrc) : void 0;
330
+ }
331
+
332
+ // src/host/nextjs/image-shared.ts
333
+ function resolveForBundle(unbound, bundle) {
334
+ if (!unbound)
335
+ return void 0;
336
+ const remoteSrc = getScope(bundle)?.url.href ?? "";
337
+ return bindResolveClientUrl(unbound, remoteSrc);
338
+ }
339
+ function createImageLoaderSharedEntries({
340
+ bound,
341
+ unbound
342
+ } = {}) {
343
+ const entry = (bundle) => {
344
+ const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
345
+ return Promise.resolve({
346
+ default: createRemoteImageLoader(bundle, resolveClientUrl),
347
+ __esModule: true
348
+ });
349
+ };
350
+ return {
351
+ "next/dist/shared/lib/image-loader": entry,
352
+ "next/dist/esm/shared/lib/image-loader": entry
353
+ };
354
+ }
355
+
356
+ // src/host/nextjs/app-client-only.tsx
357
+ import { RemoteComponentsContext } from "#internal/host/react/context";
358
+
359
+ // src/host/react/index.tsx
360
+ import {
361
+ startTransition,
362
+ useEffect,
363
+ useId,
364
+ useLayoutEffect as useLayoutEffect2,
365
+ useMemo as useMemo2,
366
+ useRef as useRef2,
367
+ useState as useState2
368
+ } from "react";
369
+ import { createPortal } from "react-dom";
370
+ import { useRemoteComponentsContext as useRemoteComponentsContext2 } from "#internal/host/react/context";
371
+
280
372
  // src/host/server/fetch-headers.ts
281
373
  function remoteFetchHeaders() {
282
374
  return {
@@ -501,29 +593,6 @@ function resolveNameFromSrc(src, defaultName) {
501
593
  return name || defaultName;
502
594
  }
503
595
 
504
- // src/utils/index.ts
505
- function escapeString(str) {
506
- return str.replace(/[^a-z0-9]/g, "_");
507
- }
508
- var attrToProp = {
509
- fetchpriority: "fetchPriority",
510
- crossorigin: "crossOrigin",
511
- imagesrcset: "imageSrcSet",
512
- imagesizes: "imageSizes",
513
- srcset: "srcSet"
514
- };
515
-
516
- // src/runtime/constants.ts
517
- var DEFAULT_ROUTE = "/";
518
- var RUNTIME_WEBPACK = "webpack";
519
- var RUNTIME_TURBOPACK = "turbopack";
520
- var RUNTIME_SCRIPT = "script";
521
- var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
522
- var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
523
- function getBundleKey(bundle) {
524
- return escapeString(bundle);
525
- }
526
-
527
596
  // src/runtime/html/apply-origin.ts
528
597
  var tagNames = [
529
598
  "img",
@@ -586,6 +655,38 @@ function applyOriginToNodes(doc, url, resolveClientUrl) {
586
655
  }
587
656
  }
588
657
 
658
+ // src/runtime/metadata.ts
659
+ var VALID_RUNTIMES = /* @__PURE__ */ new Set(["webpack", "turbopack", "script"]);
660
+ var VALID_TYPES = /* @__PURE__ */ new Set([
661
+ "nextjs",
662
+ "remote-component",
663
+ "unknown"
664
+ ]);
665
+ function isRuntime(value) {
666
+ return VALID_RUNTIMES.has(value);
667
+ }
668
+ function isComponentType(value) {
669
+ return VALID_TYPES.has(value);
670
+ }
671
+ function toRuntime(value) {
672
+ return value && isRuntime(value) ? value : "webpack";
673
+ }
674
+ function toComponentType(value) {
675
+ return value && isComponentType(value) ? value : "unknown";
676
+ }
677
+ function buildMetadata(attrs, url) {
678
+ const id = attrs.id || DEFAULT_COMPONENT_NAME;
679
+ const bundle = attrs.bundle || process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION || DEFAULT_BUNDLE_NAME;
680
+ return {
681
+ name: attrs.name || id.replace(/_ssr$/, ""),
682
+ bundle,
683
+ route: attrs.route || url.pathname || DEFAULT_ROUTE,
684
+ runtime: toRuntime(attrs.runtime),
685
+ id,
686
+ type: toComponentType(attrs.type)
687
+ };
688
+ }
689
+
589
690
  // src/runtime/html/parse-remote-html.ts
590
691
  function validateSingleComponent(doc, name, url) {
591
692
  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}"]`)) {
@@ -605,14 +706,6 @@ function resolveComponentName(component, nextData, fallbackName) {
605
706
  const name = component?.getAttribute("id")?.replace(/_ssr$/, "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
606
707
  return { name, isRemoteComponent };
607
708
  }
608
- function extractComponentMetadata(component, nextData, name, url) {
609
- return {
610
- name,
611
- bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle || "default",
612
- route: component?.getAttribute("data-route") ?? nextData?.page ?? (url.pathname || DEFAULT_ROUTE),
613
- runtime: component?.getAttribute("data-runtime") ?? (nextData?.props.__REMOTE_COMPONENT__?.runtime || RUNTIME_SCRIPT)
614
- };
615
- }
616
709
  function extractRemoteShared(doc, name, nextData) {
617
710
  const remoteSharedEl = doc.querySelector(
618
711
  `#${name}_shared[data-remote-components-shared]`
@@ -624,7 +717,7 @@ function extractRemoteShared(doc, name, nextData) {
624
717
  function validateComponentFound(component, rsc, nextData, isRemoteComponent, url, name) {
625
718
  if (!component || !(rsc || nextData || isRemoteComponent)) {
626
719
  throw new RemoteComponentsError(
627
- `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>?`
720
+ `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>?`
628
721
  );
629
722
  }
630
723
  }
@@ -650,10 +743,15 @@ function parseRemoteComponentDocument(doc, name, url) {
650
743
  name
651
744
  );
652
745
  const rsc = doc.querySelector(`#${resolvedName}_rsc`);
653
- const metadata = extractComponentMetadata(
654
- component,
655
- nextData,
656
- resolvedName,
746
+ const metadata = buildMetadata(
747
+ {
748
+ name: resolvedName,
749
+ bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle,
750
+ route: component?.getAttribute("data-route") ?? nextData?.page,
751
+ runtime: component?.getAttribute("data-runtime") ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
752
+ id: component?.getAttribute("id"),
753
+ type: component?.getAttribute("data-type")
754
+ },
657
755
  url
658
756
  );
659
757
  const remoteShared = extractRemoteShared(doc, resolvedName, nextData);
@@ -978,62 +1076,39 @@ var ASYNC_MODULE_ALL_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<vCb
978
1076
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
979
1077
 
980
1078
  // src/runtime/turbopack/chunk-loader.ts
981
- function createChunkLoader(runtime, resolveClientUrl) {
982
- return function __turbopack_chunk_load__(chunkId, scriptBundle) {
983
- logDebug("ChunkLoader", `Loading chunk: "${chunkId}"`);
984
- const self = globalThis;
985
- const {
986
- bundle,
987
- id: path,
988
- prefix
989
- } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {
990
- bundle: scriptBundle ?? "",
991
- id: chunkId
992
- };
993
- logDebug(
994
- "ChunkLoader",
995
- `Parsed chunk - bundle: "${bundle}", path: "${path}", prefix: "${prefix}"`
996
- );
997
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
998
- logDebug("ChunkLoader", `Remote runtime: "${remoteRuntime}"`);
999
- if (remoteRuntime === RUNTIME_WEBPACK) {
1000
- logDebug("ChunkLoader", "Skipping chunk load - webpack runtime detected");
1001
- return Promise.resolve(void 0);
1002
- }
1003
- const url = new URL(
1004
- path ? `${prefix ?? ""}${path}`.replace(
1005
- /(?<char>[^:])(?<double>\/\/)/g,
1006
- "$1/"
1007
- ) : "/",
1008
- self.__remote_bundle_url__?.[bundle ?? "default"] ?? new URL(location.origin)
1009
- ).href;
1010
- if (url.endsWith(".css")) {
1011
- logDebug("ChunkLoader", `Skipping CSS file: "${url}"`);
1012
- return;
1013
- }
1014
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1015
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
1016
- }
1017
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1018
- logDebug("ChunkLoader", `Returning cached promise for: "${url}"`);
1019
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1020
- }
1021
- const resolvedUrl = resolveClientUrl?.(url) ?? url;
1022
- logDebug("ChunkLoader", `Fetching chunk from: "${resolvedUrl}"`);
1023
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise((resolve, reject) => {
1079
+ function loadChunkWithScope(scope, chunkId) {
1080
+ logDebug(
1081
+ "ChunkLoader",
1082
+ `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
1083
+ );
1084
+ const self = globalThis;
1085
+ const { bundle, path, prefix } = parseRemoteId(chunkId);
1086
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
1087
+ if (remoteRuntime === RUNTIME_WEBPACK) {
1088
+ return Promise.resolve(void 0);
1089
+ }
1090
+ const rawPath = path ? collapseDoubleSlashes(`${prefix}${path}`) : "/";
1091
+ const url = new URL(rawPath, scope.url).href;
1092
+ if (url.endsWith(".css")) {
1093
+ return;
1094
+ }
1095
+ if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1096
+ self.__remote_components_turbopack_chunk_loader_promise__ = {};
1097
+ }
1098
+ if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1099
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
1100
+ }
1101
+ const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1102
+ if (resolvedUrl !== url) {
1103
+ logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1104
+ }
1105
+ self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1106
+ (resolve, reject) => {
1024
1107
  fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1025
1108
  const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1026
1109
  if (hasTurbopack) {
1027
- return handleTurbopackChunk(code, bundle ?? "", url);
1110
+ return handleTurbopackChunk(code, scope, url);
1028
1111
  }
1029
- logDebug(
1030
- "ChunkLoader",
1031
- `Chunk does not contain globalThis.TURBOPACK or self.TURBOPACK: "${url}"`
1032
- );
1033
- logDebug(
1034
- "ChunkLoader",
1035
- `First 500 chars of chunk: ${code.slice(0, 500)}`
1036
- );
1037
1112
  }).then(resolve).catch((error) => {
1038
1113
  const isProxied = isProxiedUrl(resolvedUrl);
1039
1114
  if (isProxied) {
@@ -1043,17 +1118,29 @@ function createChunkLoader(runtime, resolveClientUrl) {
1043
1118
  reject(error);
1044
1119
  }
1045
1120
  });
1046
- });
1047
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1121
+ }
1122
+ );
1123
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
1124
+ }
1125
+ function createChunkDispatcher() {
1126
+ return function __chunk_dispatcher__(chunkId, scriptBundle) {
1127
+ logDebug("ChunkDispatcher", `Dispatching chunk: "${chunkId}"`);
1128
+ const { bundle } = parseRemoteId(chunkId);
1129
+ const bundleName = bundle || scriptBundle || "default";
1130
+ const scope = getScope(bundleName);
1131
+ logDebug(
1132
+ "ChunkDispatcher",
1133
+ `Scope resolution: bundle="${bundleName}", scope=${scope?.scopedName ?? "null"}`
1134
+ );
1135
+ if (!scope) {
1136
+ logWarn("ChunkDispatcher", `No scope found for bundle "${bundleName}"`);
1137
+ return Promise.resolve(void 0);
1138
+ }
1139
+ return loadChunkWithScope(scope, chunkId);
1048
1140
  };
1049
1141
  }
1050
- async function handleTurbopackChunk(code, bundle, url) {
1051
- logDebug(
1052
- "ChunkLoader",
1053
- `Handling Turbopack chunk - bundle: "${bundle}", url: "${url}"`
1054
- );
1142
+ async function handleTurbopackChunk(code, scope, url) {
1055
1143
  if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
1056
- logDebug("ChunkLoader", `Skipping worker chunk: "${url}"`);
1057
1144
  const preloadLinks = document.querySelectorAll(
1058
1145
  `link[rel="preload"][href="${new URL(url).pathname}"]`
1059
1146
  );
@@ -1061,58 +1148,41 @@ async function handleTurbopackChunk(code, bundle, url) {
1061
1148
  return;
1062
1149
  }
1063
1150
  const self = globalThis;
1064
- const bundleKey = getBundleKey(bundle);
1065
- logDebug("ChunkLoader", `Bundle key: "${bundleKey}"`);
1151
+ const { globalKey } = scope;
1066
1152
  const transformedCode = code.replace(
1067
1153
  /globalThis\[\s*["']TURBOPACK["']\s*\]/g,
1068
- `globalThis["TURBOPACK_${bundleKey}"]`
1154
+ `globalThis["TURBOPACK_${globalKey}"]`
1069
1155
  ).replace(
1070
1156
  /self\[\s*["']TURBOPACK["']\s*\]/g,
1071
- `self["TURBOPACK_${bundleKey}"]`
1072
- ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${bundleKey}`).replace(
1157
+ `self["TURBOPACK_${globalKey}"]`
1158
+ ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`).replace(
1073
1159
  /TURBOPACK_WORKER_LOCATION/g,
1074
- `TURBOPACK_WORKER_LOCATION_${bundleKey}`
1160
+ `TURBOPACK_WORKER_LOCATION_${globalKey}`
1075
1161
  ).replace(
1076
1162
  /TURBOPACK_NEXT_CHUNK_URLS/g,
1077
- `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
1163
+ `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`
1078
1164
  ).replace(
1079
1165
  /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
1080
- `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
1081
- ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
1166
+ `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`
1167
+ ).replace(/__next_require__/g, `__${globalKey}_next_require__`).replace(
1082
1168
  /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
1083
- `//# sourceMappingURL=${new URL(
1084
- ".",
1085
- new URL(
1086
- url,
1087
- self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin)
1088
- )
1089
- ).href}$1$2.js.map`
1169
+ `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1090
1170
  );
1091
- if (!self[`TURBOPACK_${bundleKey}`]) {
1171
+ if (!self[`TURBOPACK_${globalKey}`]) {
1092
1172
  const chunkData = [];
1093
1173
  const turbopackObject = {
1094
1174
  push: (item) => {
1095
- logDebug(
1096
- "ChunkLoader",
1097
- `TURBOPACK_${bundleKey}.push() called with item type: ${Array.isArray(item) ? "array" : typeof item}`
1098
- );
1099
1175
  if (Array.isArray(item)) {
1100
1176
  chunkData.push(item);
1101
- logDebug(
1102
- "ChunkLoader",
1103
- `TURBOPACK_${bundleKey} now has ${chunkData.length} chunks`
1104
- );
1105
1177
  } else {
1106
1178
  chunkData.push([item]);
1107
1179
  }
1108
1180
  return chunkData.length;
1109
1181
  },
1110
- // Store chunks for later access
1111
1182
  __chunks__: chunkData
1112
1183
  };
1113
- self[`TURBOPACK_${bundleKey}`] = turbopackObject;
1184
+ self[`TURBOPACK_${globalKey}`] = turbopackObject;
1114
1185
  }
1115
- logDebug("ChunkLoader", `Creating blob script for: "${url}"`);
1116
1186
  await new Promise((scriptResolve, scriptReject) => {
1117
1187
  const blob = new Blob([transformedCode], {
1118
1188
  type: "application/javascript; charset=UTF-8"
@@ -1124,21 +1194,6 @@ async function handleTurbopackChunk(code, bundle, url) {
1124
1194
  script.async = true;
1125
1195
  script.onload = () => {
1126
1196
  URL.revokeObjectURL(scriptUrl);
1127
- logDebug(
1128
- "ChunkLoader",
1129
- `Script loaded successfully for bundle "${bundle}"`
1130
- );
1131
- const turbopackBundle = self[`TURBOPACK_${bundleKey}`];
1132
- logDebug(
1133
- "ChunkLoader",
1134
- `TURBOPACK_${bundleKey} type: ${typeof turbopackBundle}, isArray: ${Array.isArray(turbopackBundle)}, keys: ${turbopackBundle ? Object.keys(turbopackBundle).slice(0, 10).join(", ") : "none"}`
1135
- );
1136
- if (turbopackBundle && typeof turbopackBundle === "object") {
1137
- logDebug(
1138
- "ChunkLoader",
1139
- `TURBOPACK_${bundleKey} length/size: ${Array.isArray(turbopackBundle) ? turbopackBundle.length : Object.keys(turbopackBundle).length}`
1140
- );
1141
- }
1142
1197
  scriptResolve(void 0);
1143
1198
  script.remove();
1144
1199
  };
@@ -1153,43 +1208,177 @@ async function handleTurbopackChunk(code, bundle, url) {
1153
1208
  };
1154
1209
  document.head.appendChild(script);
1155
1210
  });
1156
- const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`];
1157
- logDebug(
1158
- "ChunkLoader",
1159
- `Processing chunk lists for bundle "${bundle}": ${chunkLists?.length ?? 0} lists`
1160
- );
1161
- const loadChunkLists = [];
1211
+ const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`];
1212
+ const loadChunkPromises = [];
1162
1213
  while (chunkLists?.length) {
1163
1214
  const { chunks } = chunkLists.shift() ?? { chunks: [] };
1164
1215
  if (chunks.length > 0) {
1165
- logDebug(
1166
- "ChunkLoader",
1167
- `Loading ${chunks.length} additional chunks for bundle "${bundle}": [${chunks.join(", ")}]`
1168
- );
1169
- chunks.forEach((id) => {
1170
- const chunkLoadResult = self.__webpack_chunk_load__?.(
1171
- `[${bundle}] ${url.slice(0, url.indexOf("/_next"))}/_next/${id}`
1216
+ for (const id of chunks) {
1217
+ const baseUrl = url.slice(0, url.indexOf("/_next"));
1218
+ const chunkLoadResult = loadChunkWithScope(
1219
+ scope,
1220
+ formatRemoteId(scope, `${baseUrl}/_next/${id}`)
1172
1221
  );
1173
1222
  if (chunkLoadResult) {
1174
- loadChunkLists.push(chunkLoadResult);
1223
+ loadChunkPromises.push(chunkLoadResult);
1175
1224
  }
1176
- });
1225
+ }
1177
1226
  }
1178
1227
  }
1179
- if (loadChunkLists.length > 0) {
1180
- logDebug(
1181
- "ChunkLoader",
1182
- `Waiting for ${loadChunkLists.length} additional chunks to load`
1228
+ if (loadChunkPromises.length > 0) {
1229
+ await Promise.all(loadChunkPromises);
1230
+ }
1231
+ }
1232
+
1233
+ // src/runtime/turbopack/shared-modules.ts
1234
+ 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).";
1235
+ function getTurbopackModules(scope) {
1236
+ const self = globalThis;
1237
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1238
+ if (!raw)
1239
+ return void 0;
1240
+ if (typeof raw === "object" && "__chunks__" in raw) {
1241
+ return raw.__chunks__.flat();
1242
+ }
1243
+ if (Array.isArray(raw)) {
1244
+ return raw.flat();
1245
+ }
1246
+ return Object.entries(raw).flat();
1247
+ }
1248
+ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}) {
1249
+ const allModules = getTurbopackModules(scope);
1250
+ logDebug(
1251
+ "SharedModules",
1252
+ `initializeSharedModules: scope="${scope.scopedName}", allModules=${allModules ? allModules.length : "null"}, hostShared=[${Object.keys(hostShared).join(", ")}], remoteShared=${JSON.stringify(remoteShared)}`
1253
+ );
1254
+ let sharedModuleInitializer = null;
1255
+ if (allModules) {
1256
+ const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1257
+ if (typeof idOrFunc !== "function") {
1258
+ return false;
1259
+ }
1260
+ const funcCode = idOrFunc.toString();
1261
+ return REMOTE_SHARED_MARKER_RE.test(funcCode);
1262
+ });
1263
+ if (sharedModuleInitializerIndex > 0) {
1264
+ const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1265
+ const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1266
+ const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1267
+ if (sharedModuleId) {
1268
+ const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1269
+ scope,
1270
+ sharedModuleId,
1271
+ formatRemoteId(scope, String(sharedModuleInitializerId))
1272
+ );
1273
+ sharedModuleInitializer = sharedModuleInitializerInstance;
1274
+ }
1275
+ }
1276
+ if (sharedModuleInitializer) {
1277
+ const { shared: shared2 } = await sharedModuleInitializer;
1278
+ const sharedModuleIds = extractSharedModuleIds(shared2, scope);
1279
+ logDebug(
1280
+ "SharedModules",
1281
+ `Resolved shared modules for scope="${scope.scopedName}": ${JSON.stringify(sharedModuleIds)}`
1282
+ );
1283
+ return Promise.all(
1284
+ Object.entries(sharedModuleIds).map(async ([id, module]) => {
1285
+ if (hostShared[module]) {
1286
+ scope.sharedModules[id] = await hostShared[module](scope.name);
1287
+ } else {
1288
+ logError(
1289
+ "SharedModules",
1290
+ `Host shared module "${module}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1291
+ );
1292
+ }
1293
+ })
1294
+ );
1295
+ }
1296
+ logWarn(
1297
+ "SharedModules",
1298
+ `No shared module initializer found in bundle for scope="${scope.scopedName}" \u2014 falling back to remoteShared mapping`
1299
+ );
1300
+ } else {
1301
+ logWarn(
1302
+ "SharedModules",
1303
+ `No TURBOPACK modules found for scope="${scope.scopedName}" (TURBOPACK_${scope.globalKey} is empty)`
1183
1304
  );
1184
- await Promise.all(loadChunkLists);
1185
1305
  }
1306
+ return Promise.all(
1307
+ Object.entries(remoteShared).map(async ([id, module]) => {
1308
+ if (hostShared[module]) {
1309
+ const normalizedId = id.replace("[app-ssr]", "[app-client]");
1310
+ scope.sharedModules[normalizedId] = await hostShared[module](
1311
+ scope.name
1312
+ );
1313
+ } else {
1314
+ logError(
1315
+ "SharedModules",
1316
+ `Shared module "${module}" not found for "${scope.name}". ${DEDUPLICATION_WARNING}`
1317
+ );
1318
+ }
1319
+ })
1320
+ );
1321
+ }
1322
+ function extractSharedModuleIds(shared2, scope) {
1323
+ return Object.entries(shared2).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1324
+ const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1325
+ if (asyncSharedModuleId) {
1326
+ const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1327
+ let asyncSharedModule;
1328
+ const turbopackModules = getTurbopackModules(scope) ?? [];
1329
+ const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1330
+ asyncSharedModuleIdNumber
1331
+ );
1332
+ if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1333
+ asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1334
+ }
1335
+ if (asyncSharedModule) {
1336
+ const asyncSharedModuleCode = asyncSharedModule.toString();
1337
+ const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1338
+ acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1339
+ "__remote_shared_module_",
1340
+ ""
1341
+ );
1342
+ }
1343
+ }
1344
+ return acc;
1345
+ }, {});
1346
+ }
1347
+ function getSharedModule(scope, id) {
1348
+ const idStr = String(id);
1349
+ if (scope.sharedModules[idStr] !== void 0) {
1350
+ return scope.sharedModules[idStr];
1351
+ }
1352
+ for (const [key, value] of Object.entries(scope.sharedModules)) {
1353
+ if (typeof value !== "undefined" && idStr !== key && idStr.endsWith(key)) {
1354
+ return value;
1355
+ }
1356
+ }
1357
+ return null;
1186
1358
  }
1187
1359
 
1188
1360
  // src/runtime/turbopack/module.ts
1189
- function handleTurbopackModule(bundle, moduleId, id) {
1361
+ function requireModule(scope, moduleId, fullId) {
1362
+ const idStr = String(moduleId);
1363
+ if (scope.moduleCache[idStr])
1364
+ return scope.moduleCache[idStr];
1365
+ const sharedModule = getSharedModule(scope, moduleId);
1366
+ if (sharedModule) {
1367
+ scope.moduleCache[idStr] = sharedModule;
1368
+ return sharedModule;
1369
+ }
1370
+ return handleTurbopackModule(
1371
+ scope,
1372
+ idStr,
1373
+ fullId ?? formatRemoteId(scope, idStr)
1374
+ );
1375
+ }
1376
+ function handleTurbopackModule(scope, moduleId, id) {
1190
1377
  const self = globalThis;
1191
- const bundleKey = getBundleKey(bundle);
1192
- const raw = self[`TURBOPACK_${bundleKey}`];
1378
+ if (scope.moduleCache[moduleId]) {
1379
+ return scope.moduleCache[moduleId];
1380
+ }
1381
+ const raw = self[`TURBOPACK_${scope.globalKey}`];
1193
1382
  let modules;
1194
1383
  if (raw && typeof raw === "object" && "__chunks__" in raw) {
1195
1384
  modules = raw.__chunks__.flat();
@@ -1198,48 +1387,35 @@ function handleTurbopackModule(bundle, moduleId, id) {
1198
1387
  } else {
1199
1388
  modules = raw;
1200
1389
  }
1201
- if (!self.__remote_components_turbopack_modules__) {
1202
- self.__remote_components_turbopack_modules__ = {};
1203
- }
1204
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1205
- self.__remote_components_turbopack_modules__[bundle] = {};
1206
- }
1207
- if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
1208
- return self.__remote_components_turbopack_modules__[bundle][moduleId];
1209
- }
1210
1390
  if (!modules) {
1211
- logError("TurbopackModule", `TURBOPACK_${bundleKey} is undefined`);
1391
+ logError(
1392
+ "TurbopackModule",
1393
+ `TURBOPACK_${scope.globalKey} is undefined (scope: "${scope.scopedName}")`
1394
+ );
1212
1395
  }
1213
1396
  const moduleInit = findModuleInit(modules, moduleId);
1214
1397
  const exports = {};
1215
1398
  const moduleExports = { exports };
1216
1399
  if (typeof moduleInit !== "function") {
1217
1400
  throw new Error(
1218
- `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
1401
+ `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`
1219
1402
  );
1220
1403
  }
1221
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1222
- if (!self.__remote_components_turbopack_global__) {
1223
- self.__remote_components_turbopack_global__ = {};
1224
- }
1225
- if (!self.__remote_components_turbopack_global__[bundle]) {
1226
- self.__remote_components_turbopack_global__[bundle] = {};
1227
- }
1404
+ scope.moduleCache[moduleId] = moduleExports.exports;
1228
1405
  moduleInit(
1229
1406
  createTurbopackContext(
1230
- bundle,
1407
+ scope,
1231
1408
  exports,
1232
1409
  moduleExports,
1233
1410
  modules,
1234
1411
  moduleInit,
1235
- id,
1236
- self
1412
+ id
1237
1413
  ),
1238
1414
  moduleExports,
1239
1415
  exports
1240
1416
  );
1241
- if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
1242
- self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
1417
+ if (scope.moduleCache[moduleId] !== moduleExports.exports) {
1418
+ scope.moduleCache[moduleId] = moduleExports.exports;
1243
1419
  }
1244
1420
  return moduleExports.exports;
1245
1421
  }
@@ -1264,7 +1440,8 @@ function findModuleInit(modules, moduleId) {
1264
1440
  (e) => Boolean(e && typeof e === "object" && moduleId in e)
1265
1441
  )?.[moduleId];
1266
1442
  }
1267
- function createTurbopackContext(bundle, exports, moduleExports, modules, moduleInit, id, self) {
1443
+ function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1444
+ const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
1268
1445
  return {
1269
1446
  // HMR not implemented for Remote Components
1270
1447
  k: {
@@ -1280,16 +1457,10 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1280
1457
  s(bindings, esmId) {
1281
1458
  let mod = exports;
1282
1459
  if (typeof esmId === "string" || typeof esmId === "number") {
1283
- if (!self.__remote_components_turbopack_modules__) {
1284
- self.__remote_components_turbopack_modules__ = {};
1285
- }
1286
- if (!self.__remote_components_turbopack_modules__[bundle]) {
1287
- self.__remote_components_turbopack_modules__[bundle] = {};
1460
+ if (!scope.moduleCache[esmId]) {
1461
+ scope.moduleCache[esmId] = {};
1288
1462
  }
1289
- if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
1290
- self.__remote_components_turbopack_modules__[bundle][esmId] = {};
1291
- }
1292
- mod = self.__remote_components_turbopack_modules__[bundle][esmId];
1463
+ mod = scope.moduleCache[esmId];
1293
1464
  }
1294
1465
  Object.defineProperty(mod, "__esModule", { value: true });
1295
1466
  if (Array.isArray(bindings)) {
@@ -1322,7 +1493,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1322
1493
  }
1323
1494
  }
1324
1495
  },
1325
- // import
1496
+ // import — resolves directly via scope, no global dispatch
1326
1497
  i(importId) {
1327
1498
  let mod;
1328
1499
  if (typeof importId === "string") {
@@ -1333,7 +1504,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1333
1504
  /\s+<export(?<specifier>.*)>$/,
1334
1505
  ""
1335
1506
  );
1336
- mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`);
1507
+ mod = scopedRequire(normalizedId);
1337
1508
  if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
1338
1509
  if (exportSource === "*") {
1339
1510
  mod[exportName] = mod;
@@ -1342,7 +1513,7 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1342
1513
  }
1343
1514
  }
1344
1515
  } else {
1345
- mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
1516
+ mod = scopedRequire(importId);
1346
1517
  }
1347
1518
  if (typeof mod !== "object" || mod === null) {
1348
1519
  mod = { default: mod };
@@ -1354,16 +1525,14 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1354
1525
  }
1355
1526
  return mod;
1356
1527
  },
1357
- // require
1528
+ // require — resolves directly via scope
1358
1529
  r(requireId) {
1359
- return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
1530
+ return scopedRequire(requireId);
1360
1531
  },
1361
1532
  // value exports
1362
1533
  v(value) {
1363
1534
  if (typeof value === "function") {
1364
- exports.default = value((vid) => {
1365
- return self.__webpack_require__?.(`[${bundle}] ${vid}`);
1366
- });
1535
+ exports.default = value((vid) => scopedRequire(vid));
1367
1536
  } else {
1368
1537
  moduleExports.exports = value;
1369
1538
  }
@@ -1378,17 +1547,15 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1378
1547
  );
1379
1548
  exports.default = result;
1380
1549
  },
1381
- // async module loader
1550
+ // async module loader — resolves directly via scope
1382
1551
  async A(Aid) {
1383
- const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
1384
- return mod.default(
1385
- (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
1386
- );
1552
+ const mod = scopedRequire(Aid);
1553
+ return mod.default((parentId) => scopedRequire(parentId));
1387
1554
  },
1388
1555
  // dynamic import tracking — no-op for remote components
1389
1556
  j() {
1390
1557
  },
1391
- // chunk loader
1558
+ // chunk loader — loads directly via scope, no global dispatch
1392
1559
  l(url) {
1393
1560
  const flatModules = Array.isArray(modules) ? modules : [];
1394
1561
  const moduleInitIndex = flatModules.indexOf(moduleInit);
@@ -1399,173 +1566,69 @@ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleI
1399
1566
  const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1400
1567
  const nextIndex = scriptSrc.indexOf("/_next");
1401
1568
  const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1402
- const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
1403
- return self.__webpack_chunk_load__?.(bundleUrl, bundle);
1569
+ const chunkUrl = `${baseUrl}/_next/${url}`;
1570
+ return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));
1404
1571
  }
1405
1572
  }
1406
1573
  throw new Error(
1407
1574
  `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1408
1575
  );
1409
1576
  },
1410
- // global object for this bundle
1411
- g: self.__remote_components_turbopack_global__?.[bundle],
1577
+ // globalThis substitute shared across all modules in this scope
1578
+ g: scope.moduleGlobal,
1412
1579
  m: moduleExports,
1413
1580
  e: exports
1414
1581
  };
1415
1582
  }
1416
1583
 
1417
- // src/runtime/turbopack/shared-modules.ts
1418
- 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).";
1419
- async function initializeSharedModules(bundle, hostShared = {}, remoteShared = {}) {
1420
- const self = globalThis;
1421
- self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};
1422
- if (!self.__remote_shared_modules__[bundle]) {
1423
- self.__remote_shared_modules__[bundle] = {};
1424
- }
1425
- const bundleKey = getBundleKey(bundle);
1426
- let modules = self[`TURBOPACK_${bundleKey}`];
1427
- if (modules && typeof modules === "object" && "__chunks__" in modules) {
1428
- const chunks = modules.__chunks__;
1429
- modules = chunks.flat();
1430
- }
1431
- let sharedModuleInitializer = null;
1432
- if (modules) {
1433
- const allModules = Array.isArray(modules) ? modules.flat() : Object.entries(modules).flat();
1434
- const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1435
- if (typeof idOrFunc !== "function") {
1436
- return false;
1437
- }
1438
- const funcCode = idOrFunc.toString();
1439
- return REMOTE_SHARED_MARKER_RE.test(funcCode);
1440
- });
1441
- if (sharedModuleInitializerIndex > 0) {
1442
- const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1443
- const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1444
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1445
- if (sharedModuleId) {
1446
- const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1447
- bundle,
1448
- sharedModuleId,
1449
- `[${bundle}] ${sharedModuleInitializerId}`
1450
- );
1451
- sharedModuleInitializer = sharedModuleInitializerInstance;
1452
- }
1453
- }
1454
- if (sharedModuleInitializer) {
1455
- const { shared: shared2 } = await sharedModuleInitializer;
1456
- const sharedModuleIds = extractSharedModuleIds(
1457
- shared2,
1458
- bundleKey,
1459
- self
1460
- );
1461
- return Promise.all(
1462
- Object.entries(sharedModuleIds).map(async ([id, module]) => {
1463
- if (self.__remote_shared_modules__?.[bundle]) {
1464
- if (hostShared[module]) {
1465
- self.__remote_shared_modules__[bundle][id] = await hostShared[module](bundle);
1466
- } else {
1467
- logError(
1468
- "SharedModules",
1469
- `Host shared module "${module}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1470
- );
1471
- }
1472
- }
1473
- })
1474
- );
1475
- }
1476
- }
1477
- return Promise.all(
1478
- Object.entries(remoteShared).map(async ([id, module]) => {
1479
- if (self.__remote_shared_modules__?.[bundle]) {
1480
- if (hostShared[module]) {
1481
- const normalizedId = id.replace("[app-ssr]", "[app-client]");
1482
- self.__remote_shared_modules__[bundle][normalizedId] = await hostShared[module](bundle);
1483
- } else {
1484
- logError(
1485
- "SharedModules",
1486
- `Shared module "${module}" not found for "${bundle}". ${DEDUPLICATION_WARNING}`
1487
- );
1488
- }
1489
- }
1490
- })
1491
- );
1492
- }
1493
- function extractSharedModuleIds(shared2, bundleKey, self) {
1494
- return Object.entries(shared2).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1495
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1496
- if (asyncSharedModuleId) {
1497
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1498
- let asyncSharedModule;
1499
- let turbopackModules = self[`TURBOPACK_${bundleKey}`];
1500
- if (turbopackModules && typeof turbopackModules === "object" && "__chunks__" in turbopackModules) {
1501
- const chunks = turbopackModules.__chunks__;
1502
- turbopackModules = chunks.flat();
1503
- }
1504
- const newAllModules = Array.isArray(turbopackModules) ? turbopackModules.flat() : turbopackModules ? Object.entries(turbopackModules).flatMap(([key2, value2]) => [
1505
- key2,
1506
- value2
1507
- ]) : [];
1508
- const asyncSharedModuleIdIndex = newAllModules.indexOf(
1509
- asyncSharedModuleIdNumber
1510
- );
1511
- if (asyncSharedModuleIdIndex !== -1 && typeof newAllModules[asyncSharedModuleIdIndex + 1] === "function") {
1512
- asyncSharedModule = newAllModules[asyncSharedModuleIdIndex + 1];
1513
- }
1514
- if (asyncSharedModule) {
1515
- const asyncSharedModuleCode = asyncSharedModule.toString();
1516
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1517
- acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1518
- "__remote_shared_module_",
1519
- ""
1520
- );
1521
- }
1522
- }
1523
- return acc;
1524
- }, {});
1525
- }
1526
- function getSharedModule(bundle, id) {
1527
- const self = globalThis;
1528
- for (const [key, value] of Object.entries(
1529
- self.__remote_shared_modules__?.[bundle] ?? {}
1530
- )) {
1531
- if (typeof value !== "undefined" && (typeof id === "string" && id.includes(key) || id === key)) {
1532
- return value;
1533
- }
1534
- }
1535
- return null;
1536
- }
1537
-
1538
1584
  // src/runtime/turbopack/webpack-runtime.ts
1539
1585
  async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared2 = {}, remoteShared = {}, resolveClientUrl) {
1540
1586
  const self = globalThis;
1587
+ const bundleName = bundle ?? "default";
1588
+ const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1589
+ registerScope(scope);
1541
1590
  if (!self.__remote_bundle_url__) {
1542
1591
  self.__remote_bundle_url__ = {};
1543
1592
  }
1544
- self.__remote_bundle_url__[bundle ?? "default"] = url;
1593
+ self.__remote_bundle_url__[bundleName] = url;
1594
+ if (scope.scopedName !== bundleName) {
1595
+ self.__remote_bundle_url__[scope.scopedName] = url;
1596
+ }
1545
1597
  self.__webpack_get_script_filename__ = () => null;
1546
- if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
1598
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1599
+ if (willCreateDispatchers) {
1547
1600
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1548
1601
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1549
1602
  self.__original_webpack_require__ = self.__webpack_require__;
1550
1603
  }
1551
- self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);
1552
- self.__webpack_require__ = createModuleRequire(runtime);
1604
+ self.__webpack_chunk_load__ = createChunkDispatcher();
1605
+ self.__webpack_require__ = createModuleDispatcher(runtime);
1553
1606
  self.__webpack_require_type__ = runtime;
1554
1607
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1555
- const remoteBundle = bundle ?? "default";
1556
- self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
1557
- self.__remote_webpack_require__[remoteBundle].type = "turbopack";
1608
+ self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
1609
+ self.__remote_webpack_require__[bundleName].type = "turbopack";
1558
1610
  }
1559
1611
  }
1612
+ if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
1613
+ self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
1614
+ }
1560
1615
  if (runtime === RUNTIME_TURBOPACK) {
1561
- await Promise.all(
1616
+ const results = await Promise.allSettled(
1562
1617
  scripts.map((script) => {
1563
1618
  if (script.src) {
1564
- return self.__webpack_chunk_load__?.(script.src, bundle);
1619
+ return loadChunkWithScope(scope, script.src);
1565
1620
  }
1566
1621
  return Promise.resolve(void 0);
1567
1622
  })
1568
1623
  );
1624
+ for (const result of results) {
1625
+ if (result.status === "rejected") {
1626
+ logWarn(
1627
+ "WebpackRuntime",
1628
+ `Initial chunk load failed: ${String(result.reason)}`
1629
+ );
1630
+ }
1631
+ }
1569
1632
  }
1570
1633
  const coreShared = {
1571
1634
  react: async () => (await import("react")).default,
@@ -1575,54 +1638,54 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1575
1638
  "react-dom/client": async () => (await import("react-dom/client")).default,
1576
1639
  ...shared2
1577
1640
  };
1578
- await initializeSharedModules(
1579
- bundle ?? "default",
1580
- // include all core modules as shared
1581
- coreShared,
1582
- remoteShared
1583
- );
1641
+ await initializeSharedModules(scope, coreShared, remoteShared);
1584
1642
  }
1585
- function createModuleRequire(runtime) {
1643
+ function createModuleDispatcher(runtime) {
1586
1644
  return (id) => {
1587
1645
  const self = globalThis;
1588
1646
  const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1589
1647
  bundle: "default",
1590
1648
  id
1591
1649
  };
1592
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1593
- logDebug("WebpackRuntime", `remoteRuntime: "${remoteRuntime}"`);
1650
+ const bundleName = bundle ?? "default";
1651
+ const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
1652
+ logDebug(
1653
+ "ModuleDispatcher",
1654
+ `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
1655
+ );
1594
1656
  try {
1595
1657
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1596
1658
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1597
1659
  }
1598
- const sharedModuleId = moduleId ?? id;
1599
- const sharedModule = getSharedModule(bundle ?? "default", sharedModuleId);
1600
- if (sharedModule) {
1601
- return sharedModule;
1660
+ const scope = getScope(bundleName);
1661
+ if (scope) {
1662
+ return requireModule(scope, moduleId ?? id, id);
1602
1663
  }
1603
- if (bundle && moduleId) {
1604
- return handleTurbopackModule(bundle, moduleId, id);
1605
- }
1606
- throw new Error(`Module "${id}" not found.`);
1664
+ throw new Error(
1665
+ `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
1666
+ );
1607
1667
  } catch (requireError) {
1608
1668
  logWarn(
1609
- "WebpackRuntime",
1669
+ "ModuleDispatcher",
1610
1670
  `Module require failed: ${String(requireError)}`
1611
1671
  );
1612
1672
  if (typeof self.__original_webpack_require__ !== "function") {
1613
1673
  throw new RemoteComponentsError(
1614
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1674
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1615
1675
  {
1616
1676
  cause: requireError instanceof Error ? requireError : void 0
1617
1677
  }
1618
1678
  );
1619
1679
  }
1620
1680
  try {
1621
- logDebug("WebpackRuntime", "Falling back to original webpack require");
1681
+ logDebug(
1682
+ "ModuleDispatcher",
1683
+ "Falling back to original webpack require"
1684
+ );
1622
1685
  return self.__original_webpack_require__(id);
1623
1686
  } catch (originalError) {
1624
1687
  throw new RemoteComponentsError(
1625
- `Module "${id}" not found in remote component bundle "${bundle}".`,
1688
+ `Module "${id}" not found in remote component bundle "${bundleName}".`,
1626
1689
  { cause: originalError instanceof Error ? originalError : void 0 }
1627
1690
  );
1628
1691
  }
@@ -2022,7 +2085,7 @@ function getRemoteComponentHtml(html) {
2022
2085
  return ssrRemoteComponentContainer.innerHTML;
2023
2086
  }
2024
2087
  const remoteComponentContainer = temp.querySelectorAll(
2025
- `div[data-bundle][data-route][data-runtime][id^="__vercel_remote_component"],div[data-bundle][data-route],div#__next,remote-component:not([src])`
2088
+ `div[data-bundle][data-route][data-runtime][id^="${DEFAULT_COMPONENT_NAME}"],div[data-bundle][data-route],div#__next,remote-component:not([src])`
2026
2089
  );
2027
2090
  if (remoteComponentContainer.length > 0) {
2028
2091
  return `${Array.from(temp.querySelectorAll("link,script")).map((link) => link.outerHTML).join("")}${Array.from(remoteComponentContainer).map((container) => container.outerHTML).join("")}`;
@@ -2039,7 +2102,7 @@ function ConsumeRemoteComponent({
2039
2102
  mode = "open",
2040
2103
  reset,
2041
2104
  credentials: credentialsProp,
2042
- name: nameProp = "__vercel_remote_component",
2105
+ name: nameProp = DEFAULT_COMPONENT_NAME,
2043
2106
  shared: sharedProp,
2044
2107
  children,
2045
2108
  onBeforeLoad,
@@ -2379,10 +2442,7 @@ function ConsumeRemoteComponent({
2379
2442
  };
2380
2443
  return {
2381
2444
  src: new URL(
2382
- `${prefix ?? ""}${path}`.replace(
2383
- /(?<char>[^:])(?<double>\/\/)/g,
2384
- "$1/"
2385
- ),
2445
+ collapseDoubleSlashes(`${prefix ?? ""}${path}`),
2386
2446
  url
2387
2447
  ).href
2388
2448
  };