remote-components 0.3.2 → 0.3.4

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 (213) hide show
  1. package/dist/config/nextjs.cjs +122 -62
  2. package/dist/config/nextjs.cjs.map +1 -1
  3. package/dist/config/nextjs.js +116 -56
  4. package/dist/config/nextjs.js.map +1 -1
  5. package/dist/config/webpack.cjs +5 -1
  6. package/dist/config/webpack.cjs.map +1 -1
  7. package/dist/config/webpack.js +5 -1
  8. package/dist/config/webpack.js.map +1 -1
  9. package/dist/host/defaults/app.cjs +2 -5
  10. package/dist/host/defaults/app.cjs.map +1 -1
  11. package/dist/host/defaults/app.d.ts +1 -3
  12. package/dist/host/defaults/app.js +1 -4
  13. package/dist/host/defaults/app.js.map +1 -1
  14. package/dist/host/defaults/pages.cjs +2 -5
  15. package/dist/host/defaults/pages.cjs.map +1 -1
  16. package/dist/host/defaults/pages.d.ts +1 -3
  17. package/dist/host/defaults/pages.js +1 -4
  18. package/dist/host/defaults/pages.js.map +1 -1
  19. package/dist/host/defaults/shared.cjs +32 -0
  20. package/dist/host/defaults/shared.cjs.map +1 -0
  21. package/dist/host/defaults/shared.d.ts +3 -0
  22. package/dist/host/defaults/shared.js +8 -0
  23. package/dist/host/defaults/shared.js.map +1 -0
  24. package/dist/host/html.cjs +533 -351
  25. package/dist/host/html.cjs.map +1 -1
  26. package/dist/host/html.js +533 -351
  27. package/dist/host/html.js.map +1 -1
  28. package/dist/host/nextjs/app/client-only.cjs +494 -285
  29. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  30. package/dist/host/nextjs/app/client-only.js +468 -259
  31. package/dist/host/nextjs/app/client-only.js.map +1 -1
  32. package/dist/host/react.cjs +412 -241
  33. package/dist/host/react.cjs.map +1 -1
  34. package/dist/host/react.js +412 -241
  35. package/dist/host/react.js.map +1 -1
  36. package/dist/internal/config/webpack/apply-shared-modules.cjs +6 -4
  37. package/dist/internal/config/webpack/apply-shared-modules.cjs.map +1 -1
  38. package/dist/internal/config/webpack/apply-shared-modules.js +6 -4
  39. package/dist/internal/config/webpack/apply-shared-modules.js.map +1 -1
  40. package/dist/internal/config/webpack/next-client-pages-loader.cjs +6 -7
  41. package/dist/internal/config/webpack/next-client-pages-loader.cjs.map +1 -1
  42. package/dist/internal/config/webpack/next-client-pages-loader.js +6 -7
  43. package/dist/internal/config/webpack/next-client-pages-loader.js.map +1 -1
  44. package/dist/internal/host/nextjs/app-client.cjs +6 -22
  45. package/dist/internal/host/nextjs/app-client.cjs.map +1 -1
  46. package/dist/internal/host/nextjs/app-client.js +5 -11
  47. package/dist/internal/host/nextjs/app-client.js.map +1 -1
  48. package/dist/internal/host/nextjs/dom-flight.cjs +19 -39
  49. package/dist/internal/host/nextjs/dom-flight.cjs.map +1 -1
  50. package/dist/internal/host/nextjs/dom-flight.js +31 -39
  51. package/dist/internal/host/nextjs/dom-flight.js.map +1 -1
  52. package/dist/internal/host/nextjs/image-shared.cjs +39 -3
  53. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  54. package/dist/internal/host/nextjs/image-shared.d.ts +5 -10
  55. package/dist/internal/host/nextjs/image-shared.js +29 -3
  56. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  57. package/dist/internal/host/nextjs/shared-import.cjs +46 -0
  58. package/dist/internal/host/nextjs/shared-import.cjs.map +1 -0
  59. package/dist/internal/host/nextjs/shared-import.d.ts +3 -0
  60. package/dist/internal/host/nextjs/shared-import.js +12 -0
  61. package/dist/internal/host/nextjs/shared-import.js.map +1 -0
  62. package/dist/internal/host/server/fetch-remote-component.cjs +2 -1
  63. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  64. package/dist/internal/host/server/fetch-remote-component.js +2 -1
  65. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  66. package/dist/internal/host/shared/polyfill.cjs +8 -7
  67. package/dist/internal/host/shared/polyfill.cjs.map +1 -1
  68. package/dist/internal/host/shared/polyfill.js +8 -7
  69. package/dist/internal/host/shared/polyfill.js.map +1 -1
  70. package/dist/internal/host/shared/shared-module-resolver.cjs +117 -0
  71. package/dist/internal/host/shared/shared-module-resolver.cjs.map +1 -0
  72. package/dist/internal/host/shared/shared-module-resolver.d.ts +64 -0
  73. package/dist/internal/host/shared/shared-module-resolver.js +78 -0
  74. package/dist/internal/host/shared/shared-module-resolver.js.map +1 -0
  75. package/dist/internal/remote/nextjs/next-internals.cjs +53 -0
  76. package/dist/internal/remote/nextjs/next-internals.cjs.map +1 -0
  77. package/dist/internal/remote/nextjs/next-internals.d.ts +42 -0
  78. package/dist/internal/remote/nextjs/next-internals.js +26 -0
  79. package/dist/internal/remote/nextjs/next-internals.js.map +1 -0
  80. package/dist/internal/runtime/html/apply-origin.cjs +11 -32
  81. package/dist/internal/runtime/html/apply-origin.cjs.map +1 -1
  82. package/dist/internal/runtime/html/apply-origin.js +11 -32
  83. package/dist/internal/runtime/html/apply-origin.js.map +1 -1
  84. package/dist/internal/runtime/html/html-spec.cjs +78 -0
  85. package/dist/internal/runtime/html/html-spec.cjs.map +1 -0
  86. package/dist/internal/runtime/html/html-spec.d.ts +23 -0
  87. package/dist/internal/runtime/html/html-spec.js +41 -0
  88. package/dist/internal/runtime/html/html-spec.js.map +1 -0
  89. package/dist/internal/runtime/html/parse-remote-html.cjs +15 -12
  90. package/dist/internal/runtime/html/parse-remote-html.cjs.map +1 -1
  91. package/dist/internal/runtime/html/parse-remote-html.js +29 -12
  92. package/dist/internal/runtime/html/parse-remote-html.js.map +1 -1
  93. package/dist/internal/runtime/html/rewrite-srcset.cjs +38 -0
  94. package/dist/internal/runtime/html/rewrite-srcset.cjs.map +1 -0
  95. package/dist/internal/runtime/html/rewrite-srcset.d.ts +12 -0
  96. package/dist/internal/runtime/html/rewrite-srcset.js +14 -0
  97. package/dist/internal/runtime/html/rewrite-srcset.js.map +1 -0
  98. package/dist/internal/runtime/loaders/component-loader.cjs +25 -44
  99. package/dist/internal/runtime/loaders/component-loader.cjs.map +1 -1
  100. package/dist/internal/runtime/loaders/component-loader.d.ts +3 -1
  101. package/dist/internal/runtime/loaders/component-loader.js +28 -44
  102. package/dist/internal/runtime/loaders/component-loader.js.map +1 -1
  103. package/dist/internal/runtime/loaders/script-loader.cjs +7 -0
  104. package/dist/internal/runtime/loaders/script-loader.cjs.map +1 -1
  105. package/dist/internal/runtime/loaders/script-loader.js +7 -0
  106. package/dist/internal/runtime/loaders/script-loader.js.map +1 -1
  107. package/dist/internal/runtime/loaders/static-loader.cjs +15 -21
  108. package/dist/internal/runtime/loaders/static-loader.cjs.map +1 -1
  109. package/dist/internal/runtime/loaders/static-loader.d.ts +3 -1
  110. package/dist/internal/runtime/loaders/static-loader.js +15 -21
  111. package/dist/internal/runtime/loaders/static-loader.js.map +1 -1
  112. package/dist/internal/runtime/namespace.cjs +82 -0
  113. package/dist/internal/runtime/namespace.cjs.map +1 -0
  114. package/dist/internal/runtime/namespace.d.ts +5 -0
  115. package/dist/internal/runtime/namespace.js +58 -0
  116. package/dist/internal/runtime/namespace.js.map +1 -0
  117. package/dist/internal/runtime/rsc-imports.cjs +86 -0
  118. package/dist/internal/runtime/rsc-imports.cjs.map +1 -0
  119. package/dist/internal/runtime/rsc-imports.d.ts +39 -0
  120. package/dist/internal/runtime/rsc-imports.js +50 -0
  121. package/dist/internal/runtime/rsc-imports.js.map +1 -0
  122. package/dist/internal/{host/shared/resolved-data.cjs → runtime/rsc-runtime.cjs} +3 -3
  123. package/dist/internal/runtime/rsc-runtime.cjs.map +1 -0
  124. package/dist/internal/runtime/rsc-runtime.d.ts +37 -0
  125. package/dist/internal/runtime/rsc-runtime.js +1 -0
  126. package/dist/internal/runtime/rsc.cjs +23 -12
  127. package/dist/internal/runtime/rsc.cjs.map +1 -1
  128. package/dist/internal/runtime/rsc.d.ts +19 -2
  129. package/dist/internal/runtime/rsc.js +20 -11
  130. package/dist/internal/runtime/rsc.js.map +1 -1
  131. package/dist/internal/runtime/turbopack/chunk-loader.cjs +53 -35
  132. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  133. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +1 -1
  134. package/dist/internal/runtime/turbopack/chunk-loader.js +53 -35
  135. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  136. package/dist/internal/runtime/turbopack/module.cjs +19 -17
  137. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  138. package/dist/internal/runtime/turbopack/module.d.ts +23 -1
  139. package/dist/internal/runtime/turbopack/module.js +19 -18
  140. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  141. package/dist/internal/runtime/turbopack/patterns.cjs +26 -10
  142. package/dist/internal/runtime/turbopack/patterns.cjs.map +1 -1
  143. package/dist/internal/runtime/turbopack/patterns.d.ts +44 -49
  144. package/dist/internal/runtime/turbopack/patterns.js +23 -7
  145. package/dist/internal/runtime/turbopack/patterns.js.map +1 -1
  146. package/dist/internal/runtime/turbopack/{webpack-runtime.cjs → remote-scope-setup.cjs} +35 -32
  147. package/dist/internal/runtime/turbopack/remote-scope-setup.cjs.map +1 -0
  148. package/dist/internal/runtime/turbopack/remote-scope-setup.d.ts +25 -0
  149. package/dist/internal/runtime/turbopack/{webpack-runtime.js → remote-scope-setup.js} +36 -19
  150. package/dist/internal/runtime/turbopack/remote-scope-setup.js.map +1 -0
  151. package/dist/internal/runtime/turbopack/remote-scope.cjs +4 -6
  152. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -1
  153. package/dist/internal/runtime/turbopack/remote-scope.d.ts +20 -1
  154. package/dist/internal/runtime/turbopack/remote-scope.js +4 -6
  155. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -1
  156. package/dist/internal/runtime/turbopack/shared-modules.cjs +23 -15
  157. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  158. package/dist/internal/runtime/turbopack/shared-modules.d.ts +13 -1
  159. package/dist/internal/runtime/turbopack/shared-modules.js +25 -18
  160. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  161. package/dist/internal/runtime/types.cjs.map +1 -1
  162. package/dist/internal/runtime/types.d.ts +5 -41
  163. package/dist/internal/utils/logger.cjs +1 -1
  164. package/dist/internal/utils/logger.cjs.map +1 -1
  165. package/dist/internal/utils/logger.d.ts +2 -2
  166. package/dist/internal/utils/logger.js +1 -1
  167. package/dist/internal/utils/logger.js.map +1 -1
  168. package/dist/internal/utils/project-id-env.cjs +31 -0
  169. package/dist/internal/utils/project-id-env.cjs.map +1 -0
  170. package/dist/internal/utils/project-id-env.d.ts +7 -0
  171. package/dist/internal/utils/project-id-env.js +7 -0
  172. package/dist/internal/utils/project-id-env.js.map +1 -0
  173. package/dist/internal/utils/project-id.cjs +46 -0
  174. package/dist/internal/utils/project-id.cjs.map +1 -0
  175. package/dist/internal/utils/project-id.d.ts +8 -0
  176. package/dist/internal/utils/project-id.js +22 -0
  177. package/dist/internal/utils/project-id.js.map +1 -0
  178. package/dist/remote/defaults/app.cjs +2 -5
  179. package/dist/remote/defaults/app.cjs.map +1 -1
  180. package/dist/remote/defaults/app.d.ts +1 -3
  181. package/dist/remote/defaults/app.js +1 -4
  182. package/dist/remote/defaults/app.js.map +1 -1
  183. package/dist/remote/defaults/pages.cjs +2 -5
  184. package/dist/remote/defaults/pages.cjs.map +1 -1
  185. package/dist/remote/defaults/pages.d.ts +1 -3
  186. package/dist/remote/defaults/pages.js +1 -4
  187. package/dist/remote/defaults/pages.js.map +1 -1
  188. package/dist/remote/defaults/shared.cjs +32 -0
  189. package/dist/remote/defaults/shared.cjs.map +1 -0
  190. package/dist/remote/defaults/shared.d.ts +3 -0
  191. package/dist/remote/defaults/shared.js +8 -0
  192. package/dist/remote/defaults/shared.js.map +1 -0
  193. package/dist/remote/html.cjs +78 -22
  194. package/dist/remote/html.cjs.map +1 -1
  195. package/dist/remote/html.js +78 -22
  196. package/dist/remote/html.js.map +1 -1
  197. package/dist/remote/nextjs/app.cjs +16 -56
  198. package/dist/remote/nextjs/app.cjs.map +1 -1
  199. package/dist/remote/nextjs/app.js +26 -46
  200. package/dist/remote/nextjs/app.js.map +1 -1
  201. package/dist/remote/nextjs/pages.cjs +2 -1
  202. package/dist/remote/nextjs/pages.cjs.map +1 -1
  203. package/dist/remote/nextjs/pages.js +2 -1
  204. package/dist/remote/nextjs/pages.js.map +1 -1
  205. package/dist/types-59251814.d.ts +94 -0
  206. package/package.json +1 -1
  207. package/dist/internal/host/shared/resolved-data.cjs.map +0 -1
  208. package/dist/internal/host/shared/resolved-data.d.ts +0 -48
  209. package/dist/internal/host/shared/resolved-data.js +0 -1
  210. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +0 -1
  211. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +0 -23
  212. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +0 -1
  213. /package/dist/internal/{host/shared/resolved-data.js.map → runtime/rsc-runtime.js.map} +0 -0
@@ -42,19 +42,27 @@ var init_constants = __esm({
42
42
  }
43
43
  });
44
44
 
45
+ // src/host/defaults/shared.ts
46
+ var shared;
47
+ var init_shared = __esm({
48
+ "src/host/defaults/shared.ts"() {
49
+ "use strict";
50
+ init_constants();
51
+ shared = {
52
+ __remote_components_missing_shared__: () => Promise.reject(new Error(MISSING_SHARED_MODULES_MESSAGE))
53
+ };
54
+ }
55
+ });
56
+
45
57
  // src/host/defaults/app.ts
46
58
  var app_exports = {};
47
59
  __export(app_exports, {
48
60
  shared: () => shared
49
61
  });
50
- var shared;
51
62
  var init_app = __esm({
52
63
  "src/host/defaults/app.ts"() {
53
64
  "use strict";
54
- init_constants();
55
- shared = {
56
- __remote_components_missing_shared__: () => Promise.reject(new Error(MISSING_SHARED_MODULES_MESSAGE))
57
- };
65
+ init_shared();
58
66
  }
59
67
  });
60
68
 
@@ -65,7 +73,10 @@ __export(app_client_only_exports, {
65
73
  RemoteComponentsClientProvider: () => RemoteComponentsClientProvider
66
74
  });
67
75
  module.exports = __toCommonJS(app_client_only_exports);
68
- var import_react5 = require("react");
76
+ var import_react6 = require("react");
77
+
78
+ // src/host/nextjs/image-shared.ts
79
+ var import_react = require("react");
69
80
 
70
81
  // src/utils/index.ts
71
82
  function escapeString(str) {
@@ -93,6 +104,62 @@ function getBundleKey(bundle) {
93
104
  return escapeString(bundle);
94
105
  }
95
106
 
107
+ // src/runtime/namespace.ts
108
+ var SHADOW_ROOT_PREFIX = "__remote_components_shadowroot_";
109
+ var LEGACY_ALIASES = [
110
+ { global: "__remote_component_scopes__", prop: "scopes" },
111
+ {
112
+ global: "__remote_components_turbopack_chunk_loader_promise__",
113
+ prop: "chunkCache"
114
+ },
115
+ { global: "__remote_script_entrypoint_mount__", prop: "mountFns" },
116
+ { global: "__remote_script_entrypoint_unmount__", prop: "unmountFns" },
117
+ { global: "__remote_bundle_url__", prop: "bundleUrls" },
118
+ { global: "__rc_module_registry__", prop: "moduleRegistry" },
119
+ {
120
+ global: "__remote_component_host_shared_modules__",
121
+ prop: "hostSharedModules"
122
+ },
123
+ { global: "__remote_next_css__", prop: "cssCache" }
124
+ ];
125
+ function getNamespace() {
126
+ const g = globalThis;
127
+ const existing = g.__remote_components__;
128
+ if (existing) {
129
+ return existing;
130
+ }
131
+ const ns = {
132
+ scopes: /* @__PURE__ */ new Map(),
133
+ chunkCache: {},
134
+ mountFns: {},
135
+ unmountFns: {},
136
+ bundleUrls: {},
137
+ moduleRegistry: {},
138
+ dispatcherRuntime: void 0,
139
+ hostSharedModules: {},
140
+ cssCache: {},
141
+ shadowRoots: {}
142
+ };
143
+ const nsRecord = ns;
144
+ for (const { global, prop } of LEGACY_ALIASES) {
145
+ const legacyValue = g[global];
146
+ if (legacyValue != null) {
147
+ nsRecord[prop] = legacyValue;
148
+ }
149
+ g[global] = ns[prop];
150
+ }
151
+ const gRecord = g;
152
+ for (const key of Object.keys(gRecord)) {
153
+ if (key.startsWith(SHADOW_ROOT_PREFIX)) {
154
+ const suffix = key.slice(SHADOW_ROOT_PREFIX.length);
155
+ ns.shadowRoots[suffix] = gRecord[key];
156
+ delete gRecord[key];
157
+ }
158
+ }
159
+ g.__remote_components__ = ns;
160
+ return ns;
161
+ }
162
+
96
163
  // src/runtime/patterns.ts
97
164
  var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
98
165
  var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
@@ -217,7 +284,7 @@ Docs: ${CORS_DOCS_URL}`
217
284
 
218
285
  // src/utils/logger.ts
219
286
  var PREFIX = "remote-components";
220
- var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
287
+ var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true" || typeof process !== "undefined" && process.env.RC_DEBUG === "true";
221
288
  function logDebug(location2, message) {
222
289
  if (DEBUG) {
223
290
  console.debug(`[${PREFIX}:${location2}]: ${message}`);
@@ -249,11 +316,7 @@ function warnCrossOriginFetchError(logLocation, url) {
249
316
 
250
317
  // src/runtime/turbopack/remote-scope.ts
251
318
  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__;
319
+ return getNamespace().scopes;
257
320
  }
258
321
  function createScope(name, url, runtime, resolveClientUrl) {
259
322
  const isCrossOrigin = url.origin !== location.origin;
@@ -271,7 +334,8 @@ function createScope(name, url, runtime, resolveClientUrl) {
271
334
  resolveClientUrl,
272
335
  moduleCache: {},
273
336
  sharedModules: {},
274
- moduleGlobal: {}
337
+ moduleGlobal: {},
338
+ turbopackModules: []
275
339
  };
276
340
  }
277
341
  function registerScope(scope) {
@@ -368,24 +432,59 @@ function createImageLoaderSharedEntries({
368
432
  bound,
369
433
  unbound
370
434
  } = {}) {
371
- const entry = (bundle) => {
435
+ const loaderEntry = (bundle) => {
372
436
  const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
373
437
  return Promise.resolve({
374
438
  default: createRemoteImageLoader(bundle, resolveClientUrl),
375
439
  __esModule: true
376
440
  });
377
441
  };
442
+ const imageEntry = async (bundle) => {
443
+ const resolveClientUrl = bound ?? resolveForBundle(unbound, bundle);
444
+ const rawLoader = createRemoteImageLoader(bundle, resolveClientUrl);
445
+ const remoteLoader = Object.assign(
446
+ (p) => rawLoader({ ...p, config: { path: "/_next/image" } }),
447
+ { __next_img_default: true }
448
+ );
449
+ const mod = await import("next/image");
450
+ const OriginalImage = mod.default;
451
+ const RemoteImage = (0, import_react.forwardRef)(
452
+ (props, ref) => (0, import_react.createElement)(OriginalImage, {
453
+ ...props,
454
+ loader: props.loader ?? remoteLoader,
455
+ ref
456
+ })
457
+ );
458
+ RemoteImage.displayName = "RemoteImage";
459
+ return { ...mod, default: RemoteImage, __esModule: true };
460
+ };
378
461
  return {
379
- "next/dist/shared/lib/image-loader": entry,
380
- "next/dist/esm/shared/lib/image-loader": entry
462
+ "next/dist/shared/lib/image-loader": loaderEntry,
463
+ "next/dist/esm/shared/lib/image-loader": loaderEntry,
464
+ // Can be removed once 0.2.x support is dropped.
465
+ "next/image": imageEntry,
466
+ // Can be removed once 0.2.x support is dropped.
467
+ "next/dist/client/image-component": imageEntry,
468
+ // Can be removed once 0.2.x support is dropped.
469
+ "next/dist/api/image": imageEntry
381
470
  };
382
471
  }
383
472
 
473
+ // src/host/nextjs/shared-import.ts
474
+ async function tryImportShared() {
475
+ try {
476
+ const { shared: shared2 } = await Promise.resolve().then(() => (init_app(), app_exports));
477
+ return shared2;
478
+ } catch {
479
+ return {};
480
+ }
481
+ }
482
+
384
483
  // src/host/nextjs/app-client-only.tsx
385
484
  var import_context3 = require("#internal/host/react/context");
386
485
 
387
486
  // src/host/react/index.tsx
388
- var import_react3 = require("react");
487
+ var import_react4 = require("react");
389
488
  var import_react_dom = require("react-dom");
390
489
  var import_context2 = require("#internal/host/react/context");
391
490
 
@@ -447,9 +546,9 @@ function getClientOrServerUrl(src, serverFallback) {
447
546
  // src/host/shared/polyfill.tsx
448
547
  var import_jsx_runtime = require("react/jsx-runtime");
449
548
  function sharedPolyfills(shared2, resolveClientUrl) {
450
- const self = globalThis;
549
+ const hostShared = getNamespace().hostSharedModules;
451
550
  const polyfill = {
452
- "next/dist/client/components/navigation": self.__remote_component_host_shared_modules__?.["next/navigation"] ?? shared2?.["next/navigation"] ?? (() => Promise.resolve({
551
+ "next/dist/client/components/navigation": hostShared["next/navigation"] ?? shared2?.["next/navigation"] ?? (() => Promise.resolve({
453
552
  useRouter() {
454
553
  return {
455
554
  push: (routerUrl) => {
@@ -480,7 +579,7 @@ function sharedPolyfills(shared2, resolveClientUrl) {
480
579
  },
481
580
  __esModule: true
482
581
  })),
483
- "next/dist/client/app-dir/link": self.__remote_component_host_shared_modules__?.["next/link"] ?? shared2?.["next/link"] ?? (() => Promise.resolve({
582
+ "next/dist/client/app-dir/link": hostShared["next/link"] ?? shared2?.["next/link"] ?? (() => Promise.resolve({
484
583
  default: ({
485
584
  scroll: _,
486
585
  replace,
@@ -530,7 +629,7 @@ function sharedPolyfills(shared2, resolveClientUrl) {
530
629
  },
531
630
  __esModule: true
532
631
  })),
533
- "next/dist/client/app-dir/form": self.__remote_component_host_shared_modules__?.["next/form"] ?? shared2?.["next/form"] ?? (() => Promise.resolve({
632
+ "next/dist/client/app-dir/form": hostShared["next/form"] ?? shared2?.["next/form"] ?? (() => Promise.resolve({
534
633
  default: () => {
535
634
  throw new Error("Next.js <Form> component not implemented");
536
635
  },
@@ -541,17 +640,17 @@ function sharedPolyfills(shared2, resolveClientUrl) {
541
640
  // This gives us full next/image fidelity (fill, priority, srcSet, blur
542
641
  // placeholders, error handling) while routing image optimization through the
543
642
  // remote app's /_next/image endpoint.
544
- "next/dist/shared/lib/image-loader": self.__remote_component_host_shared_modules__?.["next/dist/shared/lib/image-loader"] ?? shared2?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
643
+ "next/dist/shared/lib/image-loader": hostShared["next/dist/shared/lib/image-loader"] ?? shared2?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
545
644
  default: createRemoteImageLoader(bundle, resolveClientUrl),
546
645
  __esModule: true
547
646
  })),
548
- "next/dist/client/script": self.__remote_component_host_shared_modules__?.["next/script"] ?? shared2?.["next/script"] ?? (() => Promise.resolve({
647
+ "next/dist/client/script": hostShared["next/script"] ?? shared2?.["next/script"] ?? (() => Promise.resolve({
549
648
  // TODO: implement <Script> component for non-Next.js host applications
550
649
  // do not throw an error for now
551
650
  default: () => null,
552
651
  __esModule: true
553
652
  })),
554
- "next/router": self.__remote_component_host_shared_modules__?.["next/router"] ?? shared2?.["next/router"] ?? (() => (
653
+ "next/router": hostShared["next/router"] ?? shared2?.["next/router"] ?? (() => (
555
654
  // TODO: incomplete implementation
556
655
  Promise.resolve({
557
656
  useRouter() {
@@ -587,6 +686,68 @@ function sharedPolyfills(shared2, resolveClientUrl) {
587
686
  return polyfill;
588
687
  }
589
688
 
689
+ // src/host/shared/shared-module-resolver.ts
690
+ var CORE_REACT_PATH_MAP = {
691
+ react: "/react/index.js",
692
+ "react/jsx-dev-runtime": "/react/jsx-dev-runtime.js",
693
+ "react/jsx-runtime": "/react/jsx-runtime.js",
694
+ "react-dom": "/react-dom/index.js",
695
+ "react-dom/client": "/react-dom/client.js"
696
+ };
697
+ var VENDOR_SHARED = Object.fromEntries(
698
+ Object.entries(CORE_REACT_PATH_MAP).filter(([key]) => key !== "react-dom/client").map(([key, path]) => [key, `'${path}'`])
699
+ );
700
+ function buildCoreShared(userShared) {
701
+ return {
702
+ react: async () => (await import("react")).default,
703
+ "react-dom": async () => (await import("react-dom")).default,
704
+ "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
705
+ "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
706
+ "react-dom/client": async () => (await import("react-dom/client")).default,
707
+ ...userShared
708
+ };
709
+ }
710
+ function buildHostShared(userShared, resolveClientUrl, options) {
711
+ const self = globalThis;
712
+ const result = {
713
+ ...sharedPolyfills(userShared, resolveClientUrl),
714
+ ...self.__remote_component_host_shared_modules__,
715
+ ...userShared
716
+ };
717
+ if (options?.includeRemoteComponentShared) {
718
+ Object.assign(result, self.__remote_component_shared__);
719
+ }
720
+ return result;
721
+ }
722
+ async function buildWebpackResolve(hostShared, remoteShared, bundle, reactModules, callerTag = "SharedModuleResolver") {
723
+ const resolve = {
724
+ ...reactModules,
725
+ ...Object.entries(remoteShared).reduce(
726
+ (acc, [key, value]) => {
727
+ if (typeof hostShared[value] !== "undefined") {
728
+ acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
729
+ } else {
730
+ logDebug(
731
+ callerTag,
732
+ `Remote requests "${value}" but host doesn't provide it`
733
+ );
734
+ }
735
+ return acc;
736
+ },
737
+ {}
738
+ )
739
+ };
740
+ await Promise.all(
741
+ Object.entries(resolve).map(async ([key, value]) => {
742
+ if (typeof value === "function") {
743
+ resolve[key] = await value(bundle);
744
+ }
745
+ return Promise.resolve(value);
746
+ })
747
+ );
748
+ return resolve;
749
+ }
750
+
590
751
  // src/host/shared/state.ts
591
752
  function createHostState() {
592
753
  return {
@@ -613,8 +774,8 @@ function resolveNameFromSrc(src, defaultName) {
613
774
  return name || defaultName;
614
775
  }
615
776
 
616
- // src/runtime/html/apply-origin.ts
617
- var tagNames = [
777
+ // src/runtime/html/html-spec.ts
778
+ var ORIGIN_REWRITE_TAGS = [
618
779
  "img",
619
780
  "source",
620
781
  "video",
@@ -625,10 +786,37 @@ var tagNames = [
625
786
  "script",
626
787
  "link"
627
788
  ];
789
+ var ID_SUFFIX_RSC = "_rsc";
790
+ var ID_SUFFIX_SSR = "_ssr";
791
+ var ID_SUFFIX_SHARED = "_shared";
792
+ var DATA_BUNDLE = "data-bundle";
793
+ var DATA_ROUTE = "data-route";
794
+ var DATA_RUNTIME = "data-runtime";
795
+ var DATA_TYPE = "data-type";
796
+ var DATA_SRC = "data-src";
797
+ var DATA_REMOTE_COMPONENTS_SHARED = "data-remote-components-shared";
798
+ var TAG_REMOTE_COMPONENT = "remote-component";
799
+ var NEXT_DATA_ID = "__NEXT_DATA__";
800
+ var REMOTE_NEXT_DATA_ID = "__REMOTE_NEXT_DATA__";
801
+ var NEXT_CONTAINER_ID = "__next";
802
+
803
+ // src/runtime/html/rewrite-srcset.ts
804
+ function rewriteSrcset(srcset, base, resolve) {
805
+ return srcset.split(",").map((entry) => {
806
+ const [url, descriptor] = entry.trim().split(/\s+/);
807
+ if (!url)
808
+ return entry;
809
+ const absoluteUrl = new URL(url, base).href;
810
+ const resolvedUrl = resolve ? resolve(absoluteUrl) : absoluteUrl;
811
+ return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
812
+ }).join(", ");
813
+ }
814
+
815
+ // src/runtime/html/apply-origin.ts
628
816
  function applyOriginToNodes(doc, url, resolveClientUrl) {
629
817
  if (url.origin !== location.origin) {
630
818
  const nodes = doc.querySelectorAll(
631
- tagNames.map(
819
+ ORIGIN_REWRITE_TAGS.map(
632
820
  (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
633
821
  ).join(",")
634
822
  );
@@ -646,29 +834,17 @@ function applyOriginToNodes(doc, url, resolveClientUrl) {
646
834
  );
647
835
  }
648
836
  if (node.hasAttribute("srcset")) {
649
- const srcSet = node.getAttribute("srcset")?.split(",").map((entry) => {
650
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
651
- if (!urlPart)
652
- return entry;
653
- const absoluteUrl = new URL(urlPart, url).href;
654
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
655
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
656
- }).join(", ");
657
- if (srcSet) {
658
- node.setAttribute("srcset", srcSet);
837
+ const raw = node.getAttribute("srcset");
838
+ if (raw) {
839
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
840
+ node.setAttribute("srcset", rewriteSrcset(raw, url, resolve));
659
841
  }
660
842
  }
661
843
  if (node.hasAttribute("imagesrcset")) {
662
- const srcSet = node.getAttribute("imagesrcset")?.split(",").map((entry) => {
663
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
664
- if (!urlPart)
665
- return entry;
666
- const absoluteUrl = new URL(urlPart, url).href;
667
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
668
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
669
- }).join(", ");
670
- if (srcSet) {
671
- node.setAttribute("imagesrcset", srcSet);
844
+ const raw = node.getAttribute("imagesrcset");
845
+ if (raw) {
846
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
847
+ node.setAttribute("imagesrcset", rewriteSrcset(raw, url, resolve));
672
848
  }
673
849
  }
674
850
  });
@@ -709,26 +885,28 @@ function buildMetadata(attrs, url) {
709
885
 
710
886
  // src/runtime/html/parse-remote-html.ts
711
887
  function validateSingleComponent(doc, name, url) {
712
- 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}"]`)) {
888
+ if (doc.querySelectorAll(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`).length > 1 && !doc.querySelector(
889
+ `div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`
890
+ ) || doc.querySelectorAll(`${TAG_REMOTE_COMPONENT}:not([src])`).length > 1 && !doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]`)) {
713
891
  throw multipleRemoteComponentsError(url);
714
892
  }
715
893
  }
716
894
  function findComponentElement(doc, name) {
717
- return doc.querySelector(`div[data-bundle][data-route][id^="${name}"]`) ?? doc.querySelector("div[data-bundle][data-route]") ?? doc.querySelector("div#__next") ?? doc.querySelector(`remote-component[name="${name}"]:not([src])`) ?? doc.querySelector("remote-component:not([src])");
895
+ return doc.querySelector(`div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`) ?? doc.querySelector(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`) ?? doc.querySelector(`div#${NEXT_CONTAINER_ID}`) ?? doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]:not([src])`) ?? doc.querySelector(`${TAG_REMOTE_COMPONENT}:not([src])`);
718
896
  }
719
897
  function parseNextData(doc) {
720
898
  return JSON.parse(
721
- (doc.querySelector("#__NEXT_DATA__") ?? doc.querySelector("#__REMOTE_NEXT_DATA__"))?.textContent ?? "null"
899
+ (doc.querySelector(`#${NEXT_DATA_ID}`) ?? doc.querySelector(`#${REMOTE_NEXT_DATA_ID}`))?.textContent ?? "null"
722
900
  );
723
901
  }
724
902
  function resolveComponentName(component, nextData, fallbackName) {
725
- const isRemoteComponent = component?.tagName.toLowerCase() === "remote-component";
726
- const name = component?.getAttribute("id")?.replace(/_ssr$/, "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
903
+ const isRemoteComponent = component?.tagName.toLowerCase() === TAG_REMOTE_COMPONENT;
904
+ const name = component?.getAttribute("id")?.replace(new RegExp(`${ID_SUFFIX_SSR}$`), "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
727
905
  return { name, isRemoteComponent };
728
906
  }
729
907
  function extractRemoteShared(doc, name, nextData) {
730
908
  const remoteSharedEl = doc.querySelector(
731
- `#${name}_shared[data-remote-components-shared]`
909
+ `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`
732
910
  );
733
911
  const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
734
912
  remoteSharedEl?.remove();
@@ -749,7 +927,7 @@ function extractLinks(doc, component) {
749
927
  function extractScripts(doc, component, isRemoteComponent) {
750
928
  return Array.from(
751
929
  (isRemoteComponent ? component : doc).querySelectorAll(
752
- "script[src],script[data-src]"
930
+ `script[src],script[${DATA_SRC}]`
753
931
  )
754
932
  );
755
933
  }
@@ -762,15 +940,15 @@ function parseRemoteComponentDocument(doc, name, url) {
762
940
  nextData,
763
941
  name
764
942
  );
765
- const rsc = doc.querySelector(`#${resolvedName}_rsc`);
943
+ const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);
766
944
  const metadata = buildMetadata(
767
945
  {
768
946
  name: resolvedName,
769
- bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle,
770
- route: component?.getAttribute("data-route") ?? nextData?.page,
771
- runtime: component?.getAttribute("data-runtime") ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
947
+ bundle: component?.getAttribute(DATA_BUNDLE) || nextData?.props.__REMOTE_COMPONENT__?.bundle,
948
+ route: component?.getAttribute(DATA_ROUTE) ?? nextData?.page,
949
+ runtime: component?.getAttribute(DATA_RUNTIME) ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
772
950
  id: component?.getAttribute("id"),
773
- type: component?.getAttribute("data-type")
951
+ type: component?.getAttribute(DATA_TYPE)
774
952
  },
775
953
  url
776
954
  );
@@ -859,13 +1037,15 @@ function applySharedModules(bundle, resolve) {
859
1037
  `Shared modules to resolve: ${Object.keys(resolve)}`
860
1038
  );
861
1039
  const self = globalThis;
862
- if (self.__remote_webpack_require__?.[bundle]) {
1040
+ const scope = getScope(bundle);
1041
+ const webpackBundle = scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];
1042
+ if (webpackBundle) {
863
1043
  const modulePaths = Object.keys(
864
- self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
1044
+ self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {}
865
1045
  );
866
1046
  logDebug(
867
1047
  "SharedModules",
868
- `Available module paths in __remote_webpack_require__[${bundle}]: ${modulePaths}`
1048
+ `Available module paths for bundle "${bundle}": ${modulePaths}`
869
1049
  );
870
1050
  for (const [key, value] of Object.entries(resolve)) {
871
1051
  const exactIds = modulePaths.filter((p) => p === key);
@@ -877,7 +1057,6 @@ function applySharedModules(bundle, resolve) {
877
1057
  );
878
1058
  }
879
1059
  for (const id of ids) {
880
- const webpackBundle = self.__remote_webpack_require__[bundle];
881
1060
  if (webpackBundle.m) {
882
1061
  const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
883
1062
  if (resolvedId !== id) {
@@ -975,10 +1154,8 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
975
1154
  ];
976
1155
  const { default: Component } = componentLoader();
977
1156
  const { default: App } = appLoader();
978
- if (!self.__remote_next_css__) {
979
- self.__remote_next_css__ = {};
980
- }
981
- if (!self.__remote_next_css__[bundle]) {
1157
+ const cssCache = getNamespace().cssCache;
1158
+ if (!cssCache[bundle]) {
982
1159
  const cssRE = /\.s?css$/;
983
1160
  Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
984
1161
  self.__remote_webpack_require__?.[bundle]?.(id);
@@ -996,15 +1173,15 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
996
1173
  node.remove();
997
1174
  node = nextCss.previousSibling;
998
1175
  }
999
- self.__remote_next_css__[bundle] = elements;
1176
+ cssCache[bundle] = elements;
1000
1177
  }
1001
1178
  if (styleContainer) {
1002
- const elements = self.__remote_next_css__[bundle];
1179
+ const elements = cssCache[bundle];
1003
1180
  elements.forEach((el) => {
1004
1181
  styleContainer.appendChild(el.cloneNode(true));
1005
1182
  });
1006
1183
  } else {
1007
- const elements = self.__remote_next_css__[bundle];
1184
+ const elements = cssCache[bundle];
1008
1185
  elements.forEach((el) => {
1009
1186
  document.head.appendChild(el);
1010
1187
  });
@@ -1041,6 +1218,18 @@ function fixPayload(payload) {
1041
1218
  }
1042
1219
  }
1043
1220
  }
1221
+ function buildRSCChunks(rscName, data) {
1222
+ const chunks = [];
1223
+ for (const chunk of data) {
1224
+ for (const line of chunk.split("\n")) {
1225
+ const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1226
+ if (match?.groups?.rsc) {
1227
+ chunks.push(JSON.parse(`"${match.groups.rsc}"`));
1228
+ }
1229
+ }
1230
+ }
1231
+ return chunks;
1232
+ }
1044
1233
  function createRSCStream(rscName, data) {
1045
1234
  return new import_web_streams_polyfill.ReadableStream({
1046
1235
  type: "bytes",
@@ -1048,16 +1237,11 @@ function createRSCStream(rscName, data) {
1048
1237
  const encoder = new TextEncoder();
1049
1238
  const self = globalThis;
1050
1239
  if (data.length > 0) {
1051
- data.forEach((chunk) => {
1052
- const lines = chunk.split("\n");
1053
- for (const line of lines) {
1054
- const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1055
- if (match?.groups?.rsc) {
1056
- self[rscName] = self[rscName] ?? [];
1057
- self[rscName].push(JSON.parse(`"${match.groups.rsc}"`));
1058
- }
1059
- }
1060
- });
1240
+ const parsed = buildRSCChunks(rscName, data);
1241
+ if (parsed.length > 0) {
1242
+ self[rscName] = self[rscName] ?? [];
1243
+ self[rscName].push(...parsed);
1244
+ }
1061
1245
  }
1062
1246
  const allChunks = (self[rscName] ?? [`0:[null]
1063
1247
  `]).join("");
@@ -1087,12 +1271,38 @@ function createRSCStream(rscName, data) {
1087
1271
  });
1088
1272
  }
1089
1273
 
1274
+ // src/runtime/rsc-imports.ts
1275
+ async function importRSCClientBrowser() {
1276
+ try {
1277
+ return await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1278
+ } catch {
1279
+ const mod = await import("react-server-dom-webpack/client.browser");
1280
+ return mod.default ?? mod;
1281
+ }
1282
+ }
1283
+
1090
1284
  // src/runtime/turbopack/patterns.ts
1285
+ var MODULE_ID_PATTERN = '"[^"]+"|[0-9]+';
1286
+ function stripQuotes(value) {
1287
+ if (value.startsWith('"') && value.endsWith('"')) {
1288
+ return value.slice(1, -1);
1289
+ }
1290
+ return value;
1291
+ }
1292
+ function extractGroup(re, input, group) {
1293
+ const raw = re.exec(input)?.groups?.[group];
1294
+ return raw ? stripQuotes(raw) : void 0;
1295
+ }
1091
1296
  var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
1092
- var REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
1093
- var ASYNC_MODULE_LOADER_RE = /(?:__turbopack_context__|e)\.A\((?<asyncSharedModuleId>[0-9]+)\)/;
1094
- var ASYNC_MODULE_RESOLVE_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<inner>parentImport|e)=>Promise\.resolve\(\)\.then\(\(\)=>\k<inner>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
1095
- var ASYNC_MODULE_ALL_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<vCb>parentImport|t)=>Promise\.all\(\["[^"]+"\]\.map\((?<mapCb>chunk|t)=>\k<ctx>\.l\(\k<mapCb>\)\)\)\.then\(\(\)=>\k<vCb>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
1297
+ var REMOTE_SHARED_ASSIGNMENT_RE = new RegExp(
1298
+ `\\.TURBOPACK_REMOTE_SHARED\\s*=\\s*await (?:__turbopack_context__|[a-z])\\.A\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1299
+ );
1300
+ var ASYNC_MODULE_LOADER_RE = new RegExp(
1301
+ `(?:__turbopack_context__|e)\\.A\\((?<asyncSharedModuleId>${MODULE_ID_PATTERN})\\)`
1302
+ );
1303
+ var ASYNC_MODULE_CALLBACK_RE = new RegExp(
1304
+ `(?:parentImport|[a-z])\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1305
+ );
1096
1306
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
1097
1307
 
1098
1308
  // src/runtime/turbopack/chunk-loader.ts
@@ -1102,6 +1312,7 @@ function loadChunkWithScope(scope, chunkId) {
1102
1312
  `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
1103
1313
  );
1104
1314
  const self = globalThis;
1315
+ const ns = getNamespace();
1105
1316
  const { bundle, path, prefix } = parseRemoteId(chunkId);
1106
1317
  const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
1107
1318
  if (remoteRuntime === RUNTIME_WEBPACK) {
@@ -1112,35 +1323,31 @@ function loadChunkWithScope(scope, chunkId) {
1112
1323
  if (url.endsWith(".css")) {
1113
1324
  return;
1114
1325
  }
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];
1326
+ if (ns.chunkCache[url]) {
1327
+ logDebug("ChunkLoader", `Cache hit for "${chunkId}" (url="${url}")`);
1328
+ return ns.chunkCache[url];
1120
1329
  }
1121
1330
  const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1122
1331
  if (resolvedUrl !== url) {
1123
1332
  logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1124
1333
  }
1125
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1126
- (resolve, reject) => {
1127
- fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1128
- const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1129
- if (hasTurbopack) {
1130
- return handleTurbopackChunk(code, scope, url);
1131
- }
1132
- }).then(resolve).catch((error) => {
1133
- const isProxied = isProxiedUrl(resolvedUrl);
1134
- if (isProxied) {
1135
- reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1136
- } else {
1137
- warnCrossOriginFetchError("ChunkLoader", url);
1138
- reject(error);
1139
- }
1140
- });
1141
- }
1142
- );
1143
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1334
+ ns.chunkCache[url] = new Promise((resolve, reject) => {
1335
+ fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1336
+ const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1337
+ if (hasTurbopack) {
1338
+ return handleTurbopackChunk(code, scope, url);
1339
+ }
1340
+ }).then(resolve).catch((error) => {
1341
+ const isProxied = isProxiedUrl(resolvedUrl);
1342
+ if (isProxied) {
1343
+ reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1344
+ } else {
1345
+ warnCrossOriginFetchError("ChunkLoader", url);
1346
+ reject(error);
1347
+ }
1348
+ });
1349
+ });
1350
+ return ns.chunkCache[url];
1144
1351
  }
1145
1352
  function createChunkDispatcher() {
1146
1353
  return function __chunk_dispatcher__(chunkId, scriptBundle) {
@@ -1189,19 +1396,39 @@ async function handleTurbopackChunk(code, scope, url) {
1189
1396
  `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1190
1397
  );
1191
1398
  if (!self[`TURBOPACK_${globalKey}`]) {
1192
- const chunkData = [];
1193
- const turbopackObject = {
1194
- push: (item) => {
1195
- if (Array.isArray(item)) {
1196
- chunkData.push(item);
1197
- } else {
1198
- chunkData.push([item]);
1399
+ const wrapPush = (target) => {
1400
+ const originalPush = target.push;
1401
+ if (typeof originalPush !== "function")
1402
+ return target;
1403
+ target.push = (...items) => {
1404
+ for (const item of items) {
1405
+ if (Array.isArray(item)) {
1406
+ for (const entry of item) {
1407
+ scope.turbopackModules.push(entry);
1408
+ }
1409
+ } else {
1410
+ scope.turbopackModules.push(item);
1411
+ }
1199
1412
  }
1200
- return chunkData.length;
1201
- },
1202
- __chunks__: chunkData
1413
+ return originalPush.apply(target, items);
1414
+ };
1415
+ return target;
1203
1416
  };
1204
- self[`TURBOPACK_${globalKey}`] = turbopackObject;
1417
+ const globalProp = `TURBOPACK_${globalKey}`;
1418
+ let currentValue = wrapPush([]);
1419
+ Object.defineProperty(self, globalProp, {
1420
+ get() {
1421
+ return currentValue;
1422
+ },
1423
+ set(newValue) {
1424
+ if (newValue && typeof newValue === "object") {
1425
+ wrapPush(newValue);
1426
+ }
1427
+ currentValue = newValue;
1428
+ },
1429
+ configurable: true,
1430
+ enumerable: true
1431
+ });
1205
1432
  }
1206
1433
  await new Promise((scriptResolve, scriptReject) => {
1207
1434
  const blob = new Blob([transformedCode], {
@@ -1253,13 +1480,13 @@ async function handleTurbopackChunk(code, scope, url) {
1253
1480
  // src/runtime/turbopack/shared-modules.ts
1254
1481
  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
1482
  function getTurbopackModules(scope) {
1483
+ if (scope.turbopackModules.length > 0) {
1484
+ return scope.turbopackModules;
1485
+ }
1256
1486
  const self = globalThis;
1257
1487
  const raw = self[`TURBOPACK_${scope.globalKey}`];
1258
1488
  if (!raw)
1259
1489
  return void 0;
1260
- if (typeof raw === "object" && "__chunks__" in raw) {
1261
- return raw.__chunks__.flat();
1262
- }
1263
1490
  if (Array.isArray(raw)) {
1264
1491
  return raw.flat();
1265
1492
  }
@@ -1283,7 +1510,11 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1283
1510
  if (sharedModuleInitializerIndex > 0) {
1284
1511
  const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1285
1512
  const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1286
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1513
+ const sharedModuleId = extractGroup(
1514
+ REMOTE_SHARED_ASSIGNMENT_RE,
1515
+ sharedModuleInitializerCode,
1516
+ "sharedModuleId"
1517
+ );
1287
1518
  if (sharedModuleId) {
1288
1519
  const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1289
1520
  scope,
@@ -1341,20 +1572,22 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1341
1572
  }
1342
1573
  function extractSharedModuleIds(shared2, scope) {
1343
1574
  return Object.entries(shared2).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1344
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1575
+ const asyncSharedModuleId = extractGroup(
1576
+ ASYNC_MODULE_LOADER_RE,
1577
+ value.toString(),
1578
+ "asyncSharedModuleId"
1579
+ );
1345
1580
  if (asyncSharedModuleId) {
1346
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1347
- let asyncSharedModule;
1348
- const turbopackModules = getTurbopackModules(scope) ?? [];
1349
- const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1350
- asyncSharedModuleIdNumber
1581
+ const asyncSharedModule = findModuleInit(
1582
+ getTurbopackModules(scope),
1583
+ asyncSharedModuleId
1351
1584
  );
1352
- if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1353
- asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1354
- }
1355
1585
  if (asyncSharedModule) {
1356
- const asyncSharedModuleCode = asyncSharedModule.toString();
1357
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1586
+ const sharedModuleId = extractGroup(
1587
+ ASYNC_MODULE_CALLBACK_RE,
1588
+ asyncSharedModule.toString(),
1589
+ "sharedModuleId"
1590
+ );
1358
1591
  acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1359
1592
  "__remote_shared_module_",
1360
1593
  ""
@@ -1383,10 +1616,8 @@ function requireModule(scope, moduleId, fullId) {
1383
1616
  if (scope.moduleCache[idStr])
1384
1617
  return scope.moduleCache[idStr];
1385
1618
  const sharedModule = getSharedModule(scope, moduleId);
1386
- if (sharedModule) {
1387
- scope.moduleCache[idStr] = sharedModule;
1619
+ if (sharedModule)
1388
1620
  return sharedModule;
1389
- }
1390
1621
  return handleTurbopackModule(
1391
1622
  scope,
1392
1623
  idStr,
@@ -1394,19 +1625,10 @@ function requireModule(scope, moduleId, fullId) {
1394
1625
  );
1395
1626
  }
1396
1627
  function handleTurbopackModule(scope, moduleId, id) {
1397
- const self = globalThis;
1398
1628
  if (scope.moduleCache[moduleId]) {
1399
1629
  return scope.moduleCache[moduleId];
1400
1630
  }
1401
- const raw = self[`TURBOPACK_${scope.globalKey}`];
1402
- let modules;
1403
- if (raw && typeof raw === "object" && "__chunks__" in raw) {
1404
- modules = raw.__chunks__.flat();
1405
- } else if (Array.isArray(raw)) {
1406
- modules = raw.flat();
1407
- } else {
1408
- modules = raw;
1409
- }
1631
+ const modules = getTurbopackModules(scope);
1410
1632
  if (!modules) {
1411
1633
  logError(
1412
1634
  "TurbopackModule",
@@ -1456,9 +1678,17 @@ function findModuleInit(modules, moduleId) {
1456
1678
  if (idx >= 0) {
1457
1679
  return flat.slice(idx + 1).find((e) => typeof e === "function");
1458
1680
  }
1459
- return flat.find(
1460
- (e) => Boolean(e && typeof e === "object" && moduleId in e)
1461
- )?.[moduleId];
1681
+ for (const entry of flat) {
1682
+ if (!entry || typeof entry !== "object")
1683
+ continue;
1684
+ const obj = entry;
1685
+ if (moduleId in obj)
1686
+ return obj[moduleId];
1687
+ const prefixKey = Object.keys(obj).find((k) => k.startsWith(moduleId));
1688
+ if (prefixKey)
1689
+ return obj[prefixKey];
1690
+ }
1691
+ return void 0;
1462
1692
  }
1463
1693
  function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1464
1694
  const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
@@ -1537,7 +1767,10 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1537
1767
  }
1538
1768
  if (typeof mod !== "object" || mod === null) {
1539
1769
  mod = { default: mod };
1540
- } else if (!("default" in mod) && mod.toString() !== "[object Module]") {
1770
+ } else if (!("default" in mod) && // ES module namespace objects have a null prototype, so calling
1771
+ // mod.toString() directly throws. Use Object.prototype.toString
1772
+ // to safely detect them.
1773
+ Object.prototype.toString.call(mod) !== "[object Module]") {
1541
1774
  try {
1542
1775
  mod.default = mod;
1543
1776
  } catch {
@@ -1601,21 +1834,38 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1601
1834
  };
1602
1835
  }
1603
1836
 
1604
- // src/runtime/turbopack/webpack-runtime.ts
1605
- async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared2 = {}, remoteShared = {}, resolveClientUrl) {
1837
+ // src/runtime/turbopack/remote-scope-setup.ts
1838
+ async function setupRemoteScope(runtime, scripts = [], url = new URL(location.href), bundle, resolveClientUrl) {
1606
1839
  const self = globalThis;
1840
+ const ns = getNamespace();
1607
1841
  const bundleName = bundle ?? "default";
1842
+ const existingScope = getScope(bundleName);
1843
+ if (existingScope && existingScope.url.origin === url.origin) {
1844
+ logDebug(
1845
+ "WebpackRuntime",
1846
+ `Reusing scope "${existingScope.scopedName}" (turbopackModules=${existingScope.turbopackModules.length})`
1847
+ );
1848
+ existingScope.resolveClientUrl = resolveClientUrl;
1849
+ if (runtime === RUNTIME_TURBOPACK) {
1850
+ await Promise.allSettled(
1851
+ scripts.map(
1852
+ (script) => script.src ? loadChunkWithScope(existingScope, script.src) : Promise.resolve(void 0)
1853
+ )
1854
+ );
1855
+ }
1856
+ return existingScope;
1857
+ }
1608
1858
  const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1609
1859
  registerScope(scope);
1610
- if (!self.__remote_bundle_url__) {
1611
- self.__remote_bundle_url__ = {};
1860
+ if (runtime === RUNTIME_WEBPACK && self.__remote_webpack_require__?.[bundleName]) {
1861
+ scope.webpackRequire = self.__remote_webpack_require__[bundleName];
1612
1862
  }
1613
- self.__remote_bundle_url__[bundleName] = url;
1863
+ ns.bundleUrls[bundleName] = url;
1614
1864
  if (scope.scopedName !== bundleName) {
1615
- self.__remote_bundle_url__[scope.scopedName] = url;
1865
+ ns.bundleUrls[scope.scopedName] = url;
1616
1866
  }
1617
1867
  self.__webpack_get_script_filename__ = () => null;
1618
- const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1868
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || ns.dispatcherRuntime !== "turbopack";
1619
1869
  if (willCreateDispatchers) {
1620
1870
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1621
1871
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
@@ -1623,6 +1873,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1623
1873
  }
1624
1874
  self.__webpack_chunk_load__ = createChunkDispatcher();
1625
1875
  self.__webpack_require__ = createModuleDispatcher(runtime);
1876
+ ns.dispatcherRuntime = runtime;
1626
1877
  self.__webpack_require_type__ = runtime;
1627
1878
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1628
1879
  self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
@@ -1650,15 +1901,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1650
1901
  }
1651
1902
  }
1652
1903
  }
1653
- const coreShared = {
1654
- react: async () => (await import("react")).default,
1655
- "react-dom": async () => (await import("react-dom")).default,
1656
- "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
1657
- "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
1658
- "react-dom/client": async () => (await import("react-dom/client")).default,
1659
- ...shared2
1660
- };
1661
- await initializeSharedModules(scope, coreShared, remoteShared);
1904
+ return scope;
1662
1905
  }
1663
1906
  function createModuleDispatcher(runtime) {
1664
1907
  return (id) => {
@@ -1675,6 +1918,9 @@ function createModuleDispatcher(runtime) {
1675
1918
  );
1676
1919
  try {
1677
1920
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1921
+ const scope2 = getScope(bundle);
1922
+ if (scope2?.webpackRequire)
1923
+ return scope2.webpackRequire(moduleId);
1678
1924
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1679
1925
  }
1680
1926
  const scope = getScope(bundleName);
@@ -1724,6 +1970,13 @@ async function loadScripts(scripts, resolveClientUrl) {
1724
1970
  location.origin
1725
1971
  ).href;
1726
1972
  const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;
1973
+ const alreadyLoaded = Array.from(
1974
+ document.querySelectorAll("script[src]")
1975
+ ).some((s) => s.src === resolvedSrc);
1976
+ if (alreadyLoaded) {
1977
+ resolve();
1978
+ return;
1979
+ }
1727
1980
  const newScript = document.createElement("script");
1728
1981
  newScript.onload = () => resolve();
1729
1982
  newScript.onerror = () => {
@@ -1785,44 +2038,33 @@ async function loadRemoteComponent({
1785
2038
  "ComponentLoader",
1786
2039
  `Remote shared modules requested: ${JSON.stringify(remoteShared)}`
1787
2040
  );
1788
- await setupWebpackRuntime(
2041
+ const scope = await setupRemoteScope(
1789
2042
  runtime,
1790
2043
  scripts,
1791
2044
  url,
1792
2045
  bundle,
1793
- hostShared,
1794
- remoteShared,
1795
2046
  resolveClientUrl
1796
2047
  );
2048
+ if (runtime === "turbopack") {
2049
+ await initializeSharedModules(
2050
+ scope,
2051
+ buildCoreShared(hostShared),
2052
+ remoteShared
2053
+ );
2054
+ }
1797
2055
  if (bundle) {
1798
- const resolve = {
1799
- "/react/index.js": React,
1800
- "/react/jsx-dev-runtime.js": JSXDevRuntime,
1801
- "/react/jsx-runtime.js": JSXRuntime,
1802
- "/react-dom/index.js": ReactDOM,
1803
- "/react-dom/client.js": ReactDOMClient,
1804
- ...Object.entries(remoteShared).reduce(
1805
- (acc, [key, value]) => {
1806
- if (typeof hostShared[value] !== "undefined") {
1807
- acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
1808
- } else {
1809
- logDebug(
1810
- "ComponentLoader",
1811
- `Remote requests "${value}" but host doesn't provide it`
1812
- );
1813
- }
1814
- return acc;
1815
- },
1816
- {}
1817
- )
1818
- };
1819
- await Promise.all(
1820
- Object.entries(resolve).map(async ([key, value]) => {
1821
- if (typeof value === "function") {
1822
- resolve[key] = await value(bundle);
1823
- }
1824
- return Promise.resolve(value);
1825
- })
2056
+ const resolve = await buildWebpackResolve(
2057
+ hostShared,
2058
+ remoteShared,
2059
+ bundle,
2060
+ {
2061
+ "/react/index.js": React,
2062
+ "/react/jsx-dev-runtime.js": JSXDevRuntime,
2063
+ "/react/jsx-runtime.js": JSXRuntime,
2064
+ "/react-dom/index.js": ReactDOM,
2065
+ "/react-dom/client.js": ReactDOMClient
2066
+ },
2067
+ "ComponentLoader"
1826
2068
  );
1827
2069
  applySharedModules(bundle, resolve);
1828
2070
  } else {
@@ -1850,19 +2092,8 @@ async function loadRemoteComponent({
1850
2092
  };
1851
2093
  }
1852
2094
  }
1853
- async function importCreateFromReadableStream() {
1854
- try {
1855
- const { createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1856
- return createFromReadableStream;
1857
- } catch {
1858
- const {
1859
- default: { createFromReadableStream }
1860
- } = await import("react-server-dom-webpack/client.browser");
1861
- return createFromReadableStream;
1862
- }
1863
- }
1864
2095
  async function loadRSCComponent(rscName, data) {
1865
- const createFromReadableStream = await importCreateFromReadableStream();
2096
+ const { createFromReadableStream } = await importRSCClientBrowser();
1866
2097
  if (typeof createFromReadableStream !== "function") {
1867
2098
  throw new RemoteComponentsError(
1868
2099
  'Failed to import "react-server-dom-webpack". Is Next.js installed correctly?'
@@ -1926,10 +2157,9 @@ async function importViaCallback(absoluteSrc, resolveClientUrl) {
1926
2157
  URL.revokeObjectURL(moduleBlobUrl);
1927
2158
  URL.revokeObjectURL(wrapperBlobUrl);
1928
2159
  }
1929
- const registry = globalThis.__rc_module_registry__;
1930
- const mod = registry?.[absoluteSrc] ?? {};
1931
- if (registry)
1932
- delete registry[absoluteSrc];
2160
+ const registry = getNamespace().moduleRegistry;
2161
+ const mod = registry[absoluteSrc] ?? {};
2162
+ delete registry[absoluteSrc];
1933
2163
  return mod;
1934
2164
  }
1935
2165
  async function importDirectly(absoluteSrc) {
@@ -1959,12 +2189,12 @@ function resolveScriptSrc(script, url) {
1959
2189
  return rawSrc;
1960
2190
  }
1961
2191
  async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1962
- const self = globalThis;
1963
- if (self.__remote_script_entrypoint_mount__?.[url.href]) {
1964
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
2192
+ const ns = getNamespace();
2193
+ if (ns.mountFns[url.href]) {
2194
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1965
2195
  }
1966
- if (self.__remote_script_entrypoint_unmount__?.[url.href]) {
1967
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
2196
+ if (ns.unmountFns[url.href]) {
2197
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1968
2198
  }
1969
2199
  const mountUnmountSets = await Promise.all(
1970
2200
  scripts.map(async (script) => {
@@ -1976,25 +2206,19 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1976
2206
  URL.revokeObjectURL(src);
1977
2207
  }
1978
2208
  if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
1979
- if (!self.__remote_script_entrypoint_mount__) {
1980
- self.__remote_script_entrypoint_mount__ = {};
2209
+ if (!ns.mountFns[url.href]) {
2210
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1981
2211
  }
1982
- if (!self.__remote_script_entrypoint_mount__[url.href]) {
1983
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
1984
- }
1985
- self.__remote_script_entrypoint_mount__[url.href]?.add(
2212
+ ns.mountFns[url.href]?.add(
1986
2213
  mod.mount || mod.default?.mount || (() => {
1987
2214
  })
1988
2215
  );
1989
2216
  }
1990
2217
  if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
1991
- if (!self.__remote_script_entrypoint_unmount__) {
1992
- self.__remote_script_entrypoint_unmount__ = {};
1993
- }
1994
- if (!self.__remote_script_entrypoint_unmount__[url.href]) {
1995
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
2218
+ if (!ns.unmountFns[url.href]) {
2219
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1996
2220
  }
1997
- self.__remote_script_entrypoint_unmount__[url.href]?.add(
2221
+ ns.unmountFns[url.href]?.add(
1998
2222
  mod.unmount || mod.default?.unmount || (() => {
1999
2223
  })
2000
2224
  );
@@ -2034,44 +2258,42 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
2034
2258
  }
2035
2259
 
2036
2260
  // src/host/react/hooks/use-resolve-client-url.ts
2037
- var import_react = require("react");
2261
+ var import_react2 = require("react");
2038
2262
  var import_context = require("#internal/host/react/context");
2039
2263
  function useResolveClientUrl(prop, urlHref) {
2040
2264
  const { resolveClientUrl: contextValue } = (0, import_context.useRemoteComponentsContext)();
2041
2265
  const raw = prop ?? contextValue;
2042
- return (0, import_react.useMemo)(() => bindResolveClientUrl(raw, urlHref), [raw, urlHref]);
2266
+ return (0, import_react2.useMemo)(() => bindResolveClientUrl(raw, urlHref), [raw, urlHref]);
2043
2267
  }
2044
2268
 
2045
2269
  // src/host/react/hooks/use-shadow-root.ts
2046
- var import_react2 = require("react");
2270
+ var import_react3 = require("react");
2047
2271
  function useShadowRoot({
2048
2272
  isolate,
2049
2273
  mode,
2050
2274
  keySuffix
2051
2275
  }) {
2052
- const shadowRootContainerRef = (0, import_react2.useRef)(null);
2053
- const [shadowRoot, setShadowRoot] = (0, import_react2.useState)(() => {
2054
- const self = globalThis;
2055
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2276
+ const shadowRootContainerRef = (0, import_react3.useRef)(null);
2277
+ const [shadowRoot, setShadowRoot] = (0, import_react3.useState)(() => {
2278
+ const shadowRoots = getNamespace().shadowRoots;
2056
2279
  const ssrShadowRoot = typeof document !== "undefined" ? document.querySelector(
2057
2280
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
2058
- )?.shadowRoot ?? self[shadowRootKey] ?? null : null;
2059
- self[shadowRootKey] = null;
2281
+ )?.shadowRoot ?? shadowRoots[keySuffix] ?? null : null;
2282
+ shadowRoots[keySuffix] = null;
2060
2283
  return ssrShadowRoot;
2061
2284
  });
2062
- (0, import_react2.useLayoutEffect)(() => {
2285
+ (0, import_react3.useLayoutEffect)(() => {
2286
+ const shadowRoots = getNamespace().shadowRoots;
2063
2287
  if (isolate !== false && typeof document !== "undefined" && (!shadowRoot || !shadowRoot.isConnected)) {
2064
- const self = globalThis;
2065
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2066
2288
  let shadowRootElement = null;
2067
2289
  const element = document.querySelector(
2068
2290
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
2069
2291
  );
2070
- shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;
2292
+ shadowRootElement = shadowRoots[keySuffix] ?? element?.shadowRoot ?? null;
2071
2293
  if (!shadowRootElement && element) {
2072
2294
  try {
2073
2295
  shadowRootElement = element.attachShadow({ mode });
2074
- self[shadowRootKey] = shadowRootElement;
2296
+ shadowRoots[keySuffix] = shadowRootElement;
2075
2297
  } catch {
2076
2298
  }
2077
2299
  }
@@ -2082,9 +2304,7 @@ function useShadowRoot({
2082
2304
  setShadowRoot(shadowRootElement);
2083
2305
  }
2084
2306
  } else if (isolate === false && shadowRoot) {
2085
- const self = globalThis;
2086
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2087
- self[shadowRootKey] = null;
2307
+ shadowRoots[keySuffix] = null;
2088
2308
  setShadowRoot(null);
2089
2309
  }
2090
2310
  }, [isolate, shadowRoot, mode, keySuffix]);
@@ -2118,7 +2338,7 @@ var import_jsx_runtime2 = (
2118
2338
  // TODO: remove wrapper div by converting HTML to RSC or React tree
2119
2339
  require("react/jsx-runtime")
2120
2340
  );
2121
- var import_react4 = require("react");
2341
+ var import_react5 = require("react");
2122
2342
  function ConsumeRemoteComponent({
2123
2343
  src,
2124
2344
  isolate,
@@ -2136,36 +2356,36 @@ function ConsumeRemoteComponent({
2136
2356
  onResponse,
2137
2357
  resolveClientUrl: resolveClientUrlProp
2138
2358
  }) {
2139
- const instanceId = (0, import_react3.useId)();
2359
+ const instanceId = (0, import_react4.useId)();
2140
2360
  const { credentials: contextCredentials, shared: contextShared } = (0, import_context2.useRemoteComponentsContext)();
2141
2361
  const credentials = credentialsProp ?? contextCredentials ?? "same-origin";
2142
2362
  const shared2 = sharedProp ?? contextShared ?? {};
2143
- const name = (0, import_react3.useMemo)(
2363
+ const name = (0, import_react4.useMemo)(
2144
2364
  () => resolveNameFromSrc(src, nameProp),
2145
2365
  [src, nameProp]
2146
2366
  );
2147
- const [data, setData] = (0, import_react3.useState)(
2367
+ const [data, setData] = (0, import_react4.useState)(
2148
2368
  null
2149
2369
  );
2150
- const url = (0, import_react3.useMemo)(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);
2370
+ const url = (0, import_react4.useMemo)(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);
2151
2371
  const resolveClientUrl = useResolveClientUrl(resolveClientUrlProp, url.href);
2152
2372
  const id = url.origin === (typeof location !== "undefined" ? location.origin : DUMMY_FALLBACK) ? url.pathname : url.href;
2153
2373
  const keySuffix = `${escapeString(id)}_${escapeString(
2154
2374
  data?.name ?? name
2155
2375
  )}_${escapeString(instanceId)}`;
2156
- const [remoteComponent, setRemoteComponent] = (0, import_react3.useState)(null);
2376
+ const [remoteComponent, setRemoteComponent] = (0, import_react4.useState)(null);
2157
2377
  const { shadowRoot, shadowRootContainerRef } = useShadowRoot({
2158
2378
  isolate,
2159
2379
  mode,
2160
2380
  keySuffix
2161
2381
  });
2162
- const htmlRef = (0, import_react3.useRef)(
2382
+ const htmlRef = (0, import_react4.useRef)(
2163
2383
  typeof document !== "undefined" ? document.querySelector(
2164
2384
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
2165
2385
  )?.shadowRoot?.innerHTML ?? document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ?? document.querySelector(`div[data-bundle][data-route][id^="${name}"]`)?.innerHTML ?? document.querySelector("div[data-bundle][data-route]")?.innerHTML : null
2166
2386
  );
2167
- const endTemplateRef = (0, import_react3.useRef)(null);
2168
- const childrenRef = (0, import_react3.useRef)(
2387
+ const endTemplateRef = (0, import_react4.useRef)(null);
2388
+ const childrenRef = (0, import_react4.useRef)(
2169
2389
  typeof document !== "undefined" ? (() => {
2170
2390
  let el = document.querySelector(`template[id="${name}_start"]`);
2171
2391
  const elements = [];
@@ -2178,17 +2398,16 @@ function ConsumeRemoteComponent({
2178
2398
  return elements;
2179
2399
  })() : []
2180
2400
  );
2181
- const hostStateRef = (0, import_react3.useRef)(createHostState());
2182
- const componentHydrationHtml = (0, import_react3.useRef)(null);
2183
- const prevRemoteComponentContainerRef = (0, import_react3.useRef)(null);
2184
- const unmountRef = (0, import_react3.useRef)(null);
2185
- (0, import_react3.useLayoutEffect)(() => {
2186
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2401
+ const hostStateRef = (0, import_react4.useRef)(createHostState());
2402
+ const componentHydrationHtml = (0, import_react4.useRef)(null);
2403
+ const prevRemoteComponentContainerRef = (0, import_react4.useRef)(null);
2404
+ const unmountRef = (0, import_react4.useRef)(null);
2405
+ (0, import_react4.useLayoutEffect)(() => {
2187
2406
  return () => {
2188
- delete globalThis[shadowRootKey];
2407
+ delete getNamespace().shadowRoots[keySuffix];
2189
2408
  };
2190
2409
  }, [keySuffix]);
2191
- (0, import_react3.useLayoutEffect)(() => {
2410
+ (0, import_react4.useLayoutEffect)(() => {
2192
2411
  if (childrenRef.current.length > 0 && remoteComponent) {
2193
2412
  childrenRef.current.forEach((el) => {
2194
2413
  el.remove();
@@ -2196,7 +2415,7 @@ function ConsumeRemoteComponent({
2196
2415
  childrenRef.current = [];
2197
2416
  }
2198
2417
  }, [remoteComponent]);
2199
- (0, import_react3.useLayoutEffect)(() => {
2418
+ (0, import_react4.useLayoutEffect)(() => {
2200
2419
  if (shadowRoot && remoteComponent) {
2201
2420
  const resetStyles = shadowRoot.querySelectorAll(
2202
2421
  "style[data-remote-components-reset]"
@@ -2219,7 +2438,7 @@ function ConsumeRemoteComponent({
2219
2438
  }
2220
2439
  }
2221
2440
  }, [shadowRoot, remoteComponent, name]);
2222
- (0, import_react3.useEffect)(() => {
2441
+ (0, import_react4.useEffect)(() => {
2223
2442
  if (src && src !== hostStateRef.current.prevSrc) {
2224
2443
  const previousSrc = hostStateRef.current.prevSrc;
2225
2444
  const previousName = hostStateRef.current.prevName;
@@ -2232,7 +2451,7 @@ function ConsumeRemoteComponent({
2232
2451
  const { signal } = hostStateRef.current.abortController;
2233
2452
  onBeforeLoad?.(src);
2234
2453
  hostStateRef.current.stage = "loading";
2235
- (0, import_react3.startTransition)(async () => {
2454
+ (0, import_react4.startTransition)(async () => {
2236
2455
  try {
2237
2456
  let html = getRemoteComponentHtml(
2238
2457
  htmlRef.current ?? (endTemplateRef.current?.previousElementSibling?.tagName === "div" ? endTemplateRef.current.previousElementSibling.innerHTML : "")
@@ -2278,9 +2497,8 @@ function ConsumeRemoteComponent({
2278
2497
  if (shadowRoot) {
2279
2498
  shadowRoot.innerHTML = "";
2280
2499
  }
2281
- const self = globalThis;
2282
2500
  const prevUrl = hostStateRef.current.prevUrl;
2283
- if (prevUrl && self.__remote_script_entrypoint_unmount__?.[prevUrl.href]) {
2501
+ if (prevUrl && getNamespace().unmountFns[prevUrl.href]) {
2284
2502
  const unmountPromises = Promise.all(
2285
2503
  Array.from(unmountRef.current ?? []).map(
2286
2504
  async (unmount) => unmount(
@@ -2469,10 +2687,7 @@ function ConsumeRemoteComponent({
2469
2687
  ).href
2470
2688
  };
2471
2689
  }),
2472
- shared: {
2473
- ...sharedPolyfills(userShared, resolveClientUrl),
2474
- ...userShared
2475
- },
2690
+ shared: buildHostShared(userShared, resolveClientUrl),
2476
2691
  remoteShared,
2477
2692
  container: shadowRoot,
2478
2693
  resolveClientUrl
@@ -2538,7 +2753,7 @@ function ConsumeRemoteComponent({
2538
2753
  runtime: hostStateRef.current.prevIsRemoteComponent ? RUNTIME_SCRIPT : data?.runtime || RUNTIME_WEBPACK
2539
2754
  }) });
2540
2755
  const resetStyle = reset ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("style", { "data-remote-components-reset": "react", children: `:host { all: initial; }` }) : null;
2541
- const linksToRender = data?.links?.map((link) => /* @__PURE__ */ (0, import_react4.createElement)(
2756
+ const linksToRender = data?.links?.map((link) => /* @__PURE__ */ (0, import_react5.createElement)(
2542
2757
  "link",
2543
2758
  {
2544
2759
  ...link,
@@ -2604,8 +2819,10 @@ function ConsumeRemoteComponent({
2604
2819
  alt="" decoding="async" style="display:none"
2605
2820
  src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
2606
2821
  onload="(function(el){
2822
+ // Capture the shadow root during SSR hydration so the client-side
2823
+ // useShadowRoot hook can find it.
2607
2824
  const root = el.getRootNode();
2608
- globalThis.__remote_components_shadowroot_${keySuffix} = root;
2825
+ globalThis.__remote_components_shadowroot_${keySuffix}=root;
2609
2826
  el.parentElement.remove();
2610
2827
  })(this)"
2611
2828
  />`
@@ -2708,14 +2925,6 @@ var routerImpl = async () => {
2708
2925
 
2709
2926
  // src/host/nextjs/app-client-only.tsx
2710
2927
  var import_jsx_runtime3 = require("react/jsx-runtime");
2711
- async function tryImportShared() {
2712
- try {
2713
- const { shared: shared2 } = await Promise.resolve().then(() => (init_app(), app_exports));
2714
- return shared2;
2715
- } catch {
2716
- return {};
2717
- }
2718
- }
2719
2928
  var sharedModules = async (userShared, resolveClientUrl) => {
2720
2929
  const [resolvedShared, resolvedUserShared] = await Promise.all([
2721
2930
  tryImportShared(),
@@ -2734,7 +2943,7 @@ function RemoteComponentsClientProvider({
2734
2943
  children,
2735
2944
  ...props
2736
2945
  }) {
2737
- const mergedShared = (0, import_react5.useMemo)(
2946
+ const mergedShared = (0, import_react6.useMemo)(
2738
2947
  () => sharedModules(shared2, resolveClientUrl),
2739
2948
  [shared2, resolveClientUrl]
2740
2949
  );