remote-components 0.3.3 → 0.3.5

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 (176) hide show
  1. package/dist/config/nextjs.cjs +86 -37
  2. package/dist/config/nextjs.cjs.map +1 -1
  3. package/dist/config/nextjs.js +86 -37
  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/html.cjs +861 -617
  10. package/dist/host/html.cjs.map +1 -1
  11. package/dist/host/html.js +861 -617
  12. package/dist/host/html.js.map +1 -1
  13. package/dist/host/nextjs/app/client-only.cjs +700 -383
  14. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  15. package/dist/host/nextjs/app/client-only.js +674 -357
  16. package/dist/host/nextjs/app/client-only.js.map +1 -1
  17. package/dist/host/nextjs/app.cjs +34 -2
  18. package/dist/host/nextjs/app.cjs.map +1 -1
  19. package/dist/host/nextjs/app.js +35 -3
  20. package/dist/host/nextjs/app.js.map +1 -1
  21. package/dist/host/react.cjs +641 -352
  22. package/dist/host/react.cjs.map +1 -1
  23. package/dist/host/react.js +641 -352
  24. package/dist/host/react.js.map +1 -1
  25. package/dist/internal/config/webpack/apply-shared-modules.cjs +6 -4
  26. package/dist/internal/config/webpack/apply-shared-modules.cjs.map +1 -1
  27. package/dist/internal/config/webpack/apply-shared-modules.js +6 -4
  28. package/dist/internal/config/webpack/apply-shared-modules.js.map +1 -1
  29. package/dist/internal/config/webpack/next-client-pages-loader.cjs +6 -7
  30. package/dist/internal/config/webpack/next-client-pages-loader.cjs.map +1 -1
  31. package/dist/internal/config/webpack/next-client-pages-loader.js +6 -7
  32. package/dist/internal/config/webpack/next-client-pages-loader.js.map +1 -1
  33. package/dist/internal/host/nextjs/app-client.cjs +42 -27
  34. package/dist/internal/host/nextjs/app-client.cjs.map +1 -1
  35. package/dist/internal/host/nextjs/app-client.js +42 -27
  36. package/dist/internal/host/nextjs/app-client.js.map +1 -1
  37. package/dist/internal/host/nextjs/dom-flight.cjs +19 -39
  38. package/dist/internal/host/nextjs/dom-flight.cjs.map +1 -1
  39. package/dist/internal/host/nextjs/dom-flight.js +31 -39
  40. package/dist/internal/host/nextjs/dom-flight.js.map +1 -1
  41. package/dist/internal/host/nextjs/image-shared.cjs +39 -3
  42. package/dist/internal/host/nextjs/image-shared.cjs.map +1 -1
  43. package/dist/internal/host/nextjs/image-shared.d.ts +5 -10
  44. package/dist/internal/host/nextjs/image-shared.js +29 -3
  45. package/dist/internal/host/nextjs/image-shared.js.map +1 -1
  46. package/dist/internal/host/nextjs/remote-component-links.cjs +24 -13
  47. package/dist/internal/host/nextjs/remote-component-links.cjs.map +1 -1
  48. package/dist/internal/host/nextjs/remote-component-links.d.ts +3 -0
  49. package/dist/internal/host/nextjs/remote-component-links.js +24 -13
  50. package/dist/internal/host/nextjs/remote-component-links.js.map +1 -1
  51. package/dist/internal/host/server/fetch-remote-component.cjs +2 -1
  52. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  53. package/dist/internal/host/server/fetch-remote-component.js +2 -1
  54. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  55. package/dist/internal/host/shared/lifecycle.cjs +69 -0
  56. package/dist/internal/host/shared/lifecycle.cjs.map +1 -0
  57. package/dist/internal/host/shared/lifecycle.d.ts +34 -0
  58. package/dist/internal/host/shared/lifecycle.js +44 -0
  59. package/dist/internal/host/shared/lifecycle.js.map +1 -0
  60. package/dist/internal/host/shared/pipeline.cjs +222 -0
  61. package/dist/internal/host/shared/pipeline.cjs.map +1 -0
  62. package/dist/internal/host/shared/pipeline.d.ts +153 -0
  63. package/dist/internal/host/shared/pipeline.js +200 -0
  64. package/dist/internal/host/shared/pipeline.js.map +1 -0
  65. package/dist/internal/host/shared/polyfill.cjs +8 -7
  66. package/dist/internal/host/shared/polyfill.cjs.map +1 -1
  67. package/dist/internal/host/shared/polyfill.js +8 -7
  68. package/dist/internal/host/shared/polyfill.js.map +1 -1
  69. package/dist/internal/host/shared/shared-module-resolver.cjs +117 -0
  70. package/dist/internal/host/shared/shared-module-resolver.cjs.map +1 -0
  71. package/dist/internal/host/shared/shared-module-resolver.d.ts +64 -0
  72. package/dist/internal/host/shared/shared-module-resolver.js +78 -0
  73. package/dist/internal/host/shared/shared-module-resolver.js.map +1 -0
  74. package/dist/internal/remote/nextjs/next-internals.cjs +53 -0
  75. package/dist/internal/remote/nextjs/next-internals.cjs.map +1 -0
  76. package/dist/internal/remote/nextjs/next-internals.d.ts +42 -0
  77. package/dist/internal/remote/nextjs/next-internals.js +26 -0
  78. package/dist/internal/remote/nextjs/next-internals.js.map +1 -0
  79. package/dist/internal/runtime/html/apply-origin.cjs +11 -32
  80. package/dist/internal/runtime/html/apply-origin.cjs.map +1 -1
  81. package/dist/internal/runtime/html/apply-origin.js +11 -32
  82. package/dist/internal/runtime/html/apply-origin.js.map +1 -1
  83. package/dist/internal/runtime/html/html-spec.cjs +78 -0
  84. package/dist/internal/runtime/html/html-spec.cjs.map +1 -0
  85. package/dist/internal/runtime/html/html-spec.d.ts +23 -0
  86. package/dist/internal/runtime/html/html-spec.js +41 -0
  87. package/dist/internal/runtime/html/html-spec.js.map +1 -0
  88. package/dist/internal/runtime/html/parse-remote-html.cjs +15 -12
  89. package/dist/internal/runtime/html/parse-remote-html.cjs.map +1 -1
  90. package/dist/internal/runtime/html/parse-remote-html.js +29 -12
  91. package/dist/internal/runtime/html/parse-remote-html.js.map +1 -1
  92. package/dist/internal/runtime/html/rewrite-srcset.cjs +38 -0
  93. package/dist/internal/runtime/html/rewrite-srcset.cjs.map +1 -0
  94. package/dist/internal/runtime/html/rewrite-srcset.d.ts +12 -0
  95. package/dist/internal/runtime/html/rewrite-srcset.js +14 -0
  96. package/dist/internal/runtime/html/rewrite-srcset.js.map +1 -0
  97. package/dist/internal/runtime/loaders/component-loader.cjs +25 -44
  98. package/dist/internal/runtime/loaders/component-loader.cjs.map +1 -1
  99. package/dist/internal/runtime/loaders/component-loader.d.ts +3 -1
  100. package/dist/internal/runtime/loaders/component-loader.js +28 -44
  101. package/dist/internal/runtime/loaders/component-loader.js.map +1 -1
  102. package/dist/internal/runtime/loaders/static-loader.cjs +15 -21
  103. package/dist/internal/runtime/loaders/static-loader.cjs.map +1 -1
  104. package/dist/internal/runtime/loaders/static-loader.d.ts +3 -1
  105. package/dist/internal/runtime/loaders/static-loader.js +15 -21
  106. package/dist/internal/runtime/loaders/static-loader.js.map +1 -1
  107. package/dist/internal/runtime/namespace.cjs +82 -0
  108. package/dist/internal/runtime/namespace.cjs.map +1 -0
  109. package/dist/internal/runtime/namespace.d.ts +5 -0
  110. package/dist/internal/runtime/namespace.js +58 -0
  111. package/dist/internal/runtime/namespace.js.map +1 -0
  112. package/dist/internal/runtime/rsc-imports.cjs +86 -0
  113. package/dist/internal/runtime/rsc-imports.cjs.map +1 -0
  114. package/dist/internal/runtime/rsc-imports.d.ts +39 -0
  115. package/dist/internal/runtime/rsc-imports.js +50 -0
  116. package/dist/internal/runtime/rsc-imports.js.map +1 -0
  117. package/dist/internal/runtime/rsc-runtime.cjs +17 -0
  118. package/dist/internal/runtime/rsc-runtime.cjs.map +1 -0
  119. package/dist/internal/runtime/rsc-runtime.d.ts +37 -0
  120. package/dist/internal/runtime/rsc-runtime.js +1 -0
  121. package/dist/internal/runtime/rsc-runtime.js.map +1 -0
  122. package/dist/internal/runtime/rsc.cjs +23 -12
  123. package/dist/internal/runtime/rsc.cjs.map +1 -1
  124. package/dist/internal/runtime/rsc.d.ts +19 -2
  125. package/dist/internal/runtime/rsc.js +20 -11
  126. package/dist/internal/runtime/rsc.js.map +1 -1
  127. package/dist/internal/runtime/turbopack/chunk-loader.cjs +53 -35
  128. package/dist/internal/runtime/turbopack/chunk-loader.cjs.map +1 -1
  129. package/dist/internal/runtime/turbopack/chunk-loader.d.ts +1 -1
  130. package/dist/internal/runtime/turbopack/chunk-loader.js +53 -35
  131. package/dist/internal/runtime/turbopack/chunk-loader.js.map +1 -1
  132. package/dist/internal/runtime/turbopack/module.cjs +17 -4
  133. package/dist/internal/runtime/turbopack/module.cjs.map +1 -1
  134. package/dist/internal/runtime/turbopack/module.d.ts +23 -1
  135. package/dist/internal/runtime/turbopack/module.js +16 -4
  136. package/dist/internal/runtime/turbopack/module.js.map +1 -1
  137. package/dist/internal/runtime/turbopack/patterns.cjs +26 -10
  138. package/dist/internal/runtime/turbopack/patterns.cjs.map +1 -1
  139. package/dist/internal/runtime/turbopack/patterns.d.ts +44 -49
  140. package/dist/internal/runtime/turbopack/patterns.js +23 -7
  141. package/dist/internal/runtime/turbopack/patterns.js.map +1 -1
  142. package/dist/internal/runtime/turbopack/{webpack-runtime.cjs → remote-scope-setup.cjs} +35 -32
  143. package/dist/internal/runtime/turbopack/remote-scope-setup.cjs.map +1 -0
  144. package/dist/internal/runtime/turbopack/remote-scope-setup.d.ts +25 -0
  145. package/dist/internal/runtime/turbopack/{webpack-runtime.js → remote-scope-setup.js} +36 -19
  146. package/dist/internal/runtime/turbopack/remote-scope-setup.js.map +1 -0
  147. package/dist/internal/runtime/turbopack/remote-scope.cjs +4 -6
  148. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -1
  149. package/dist/internal/runtime/turbopack/remote-scope.d.ts +20 -1
  150. package/dist/internal/runtime/turbopack/remote-scope.js +4 -6
  151. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -1
  152. package/dist/internal/runtime/turbopack/shared-modules.cjs +21 -15
  153. package/dist/internal/runtime/turbopack/shared-modules.cjs.map +1 -1
  154. package/dist/internal/runtime/turbopack/shared-modules.d.ts +9 -2
  155. package/dist/internal/runtime/turbopack/shared-modules.js +24 -18
  156. package/dist/internal/runtime/turbopack/shared-modules.js.map +1 -1
  157. package/dist/internal/runtime/types.cjs.map +1 -1
  158. package/dist/internal/runtime/types.d.ts +5 -41
  159. package/dist/internal/utils/logger.cjs +1 -1
  160. package/dist/internal/utils/logger.cjs.map +1 -1
  161. package/dist/internal/utils/logger.d.ts +2 -2
  162. package/dist/internal/utils/logger.js +1 -1
  163. package/dist/internal/utils/logger.js.map +1 -1
  164. package/dist/remote/html.cjs +78 -22
  165. package/dist/remote/html.cjs.map +1 -1
  166. package/dist/remote/html.js +78 -22
  167. package/dist/remote/html.js.map +1 -1
  168. package/dist/remote/nextjs/app.cjs +14 -55
  169. package/dist/remote/nextjs/app.cjs.map +1 -1
  170. package/dist/remote/nextjs/app.js +24 -45
  171. package/dist/remote/nextjs/app.js.map +1 -1
  172. package/dist/types-59251814.d.ts +94 -0
  173. package/package.json +2 -2
  174. package/dist/internal/runtime/turbopack/webpack-runtime.cjs.map +0 -1
  175. package/dist/internal/runtime/turbopack/webpack-runtime.d.ts +0 -23
  176. package/dist/internal/runtime/turbopack/webpack-runtime.js.map +0 -1
@@ -126,7 +126,7 @@ Docs: ${CORS_DOCS_URL}`
126
126
 
127
127
  // src/utils/logger.ts
128
128
  var PREFIX = "remote-components";
129
- var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
129
+ var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true" || typeof process !== "undefined" && process.env.RC_DEBUG === "true";
130
130
  function logDebug(location2, message) {
131
131
  if (DEBUG) {
132
132
  console.debug(`[${PREFIX}:${location2}]: ${message}`);
@@ -211,6 +211,24 @@ function getClientOrServerUrl(src, serverFallback) {
211
211
  return typeof src === "string" ? new URL(src, fallback) : src;
212
212
  }
213
213
 
214
+ // src/host/shared/lifecycle.ts
215
+ function makeReactEmitter(callbacks) {
216
+ return {
217
+ beforeLoad(src) {
218
+ callbacks.onBeforeLoad?.(src);
219
+ },
220
+ load(src) {
221
+ callbacks.onLoad?.(src);
222
+ },
223
+ error(error, _src) {
224
+ callbacks.onError?.(error);
225
+ },
226
+ change(info) {
227
+ callbacks.onChange?.(info);
228
+ }
229
+ };
230
+ }
231
+
214
232
  // src/utils/index.ts
215
233
  function escapeString(str) {
216
234
  return str.replace(/[^a-z0-9]/g, "_");
@@ -237,6 +255,62 @@ function getBundleKey(bundle) {
237
255
  return escapeString(bundle);
238
256
  }
239
257
 
258
+ // src/runtime/namespace.ts
259
+ var SHADOW_ROOT_PREFIX = "__remote_components_shadowroot_";
260
+ var LEGACY_ALIASES = [
261
+ { global: "__remote_component_scopes__", prop: "scopes" },
262
+ {
263
+ global: "__remote_components_turbopack_chunk_loader_promise__",
264
+ prop: "chunkCache"
265
+ },
266
+ { global: "__remote_script_entrypoint_mount__", prop: "mountFns" },
267
+ { global: "__remote_script_entrypoint_unmount__", prop: "unmountFns" },
268
+ { global: "__remote_bundle_url__", prop: "bundleUrls" },
269
+ { global: "__rc_module_registry__", prop: "moduleRegistry" },
270
+ {
271
+ global: "__remote_component_host_shared_modules__",
272
+ prop: "hostSharedModules"
273
+ },
274
+ { global: "__remote_next_css__", prop: "cssCache" }
275
+ ];
276
+ function getNamespace() {
277
+ const g = globalThis;
278
+ const existing = g.__remote_components__;
279
+ if (existing) {
280
+ return existing;
281
+ }
282
+ const ns = {
283
+ scopes: /* @__PURE__ */ new Map(),
284
+ chunkCache: {},
285
+ mountFns: {},
286
+ unmountFns: {},
287
+ bundleUrls: {},
288
+ moduleRegistry: {},
289
+ dispatcherRuntime: void 0,
290
+ hostSharedModules: {},
291
+ cssCache: {},
292
+ shadowRoots: {}
293
+ };
294
+ const nsRecord = ns;
295
+ for (const { global, prop } of LEGACY_ALIASES) {
296
+ const legacyValue = g[global];
297
+ if (legacyValue != null) {
298
+ nsRecord[prop] = legacyValue;
299
+ }
300
+ g[global] = ns[prop];
301
+ }
302
+ const gRecord = g;
303
+ for (const key of Object.keys(gRecord)) {
304
+ if (key.startsWith(SHADOW_ROOT_PREFIX)) {
305
+ const suffix = key.slice(SHADOW_ROOT_PREFIX.length);
306
+ ns.shadowRoots[suffix] = gRecord[key];
307
+ delete gRecord[key];
308
+ }
309
+ }
310
+ g.__remote_components__ = ns;
311
+ return ns;
312
+ }
313
+
240
314
  // src/runtime/patterns.ts
241
315
  var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
242
316
  var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
@@ -247,11 +321,7 @@ function collapseDoubleSlashes(path) {
247
321
 
248
322
  // src/runtime/turbopack/remote-scope.ts
249
323
  function getRegistry() {
250
- const self = globalThis;
251
- if (!self.__remote_component_scopes__) {
252
- self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
253
- }
254
- return self.__remote_component_scopes__;
324
+ return getNamespace().scopes;
255
325
  }
256
326
  function createScope(name, url, runtime, resolveClientUrl) {
257
327
  const isCrossOrigin = url.origin !== location.origin;
@@ -269,7 +339,8 @@ function createScope(name, url, runtime, resolveClientUrl) {
269
339
  resolveClientUrl,
270
340
  moduleCache: {},
271
341
  sharedModules: {},
272
- moduleGlobal: {}
342
+ moduleGlobal: {},
343
+ turbopackModules: []
273
344
  };
274
345
  }
275
346
  function registerScope(scope) {
@@ -334,9 +405,9 @@ function createRemoteImageLoader(bundle, resolveClientUrl) {
334
405
  // src/host/shared/polyfill.tsx
335
406
  import { jsx } from "react/jsx-runtime";
336
407
  function sharedPolyfills(shared, resolveClientUrl) {
337
- const self = globalThis;
408
+ const hostShared = getNamespace().hostSharedModules;
338
409
  const polyfill = {
339
- "next/dist/client/components/navigation": self.__remote_component_host_shared_modules__?.["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
410
+ "next/dist/client/components/navigation": hostShared["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
340
411
  useRouter() {
341
412
  return {
342
413
  push: (routerUrl) => {
@@ -367,7 +438,7 @@ function sharedPolyfills(shared, resolveClientUrl) {
367
438
  },
368
439
  __esModule: true
369
440
  })),
370
- "next/dist/client/app-dir/link": self.__remote_component_host_shared_modules__?.["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
441
+ "next/dist/client/app-dir/link": hostShared["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
371
442
  default: ({
372
443
  scroll: _,
373
444
  replace,
@@ -417,7 +488,7 @@ function sharedPolyfills(shared, resolveClientUrl) {
417
488
  },
418
489
  __esModule: true
419
490
  })),
420
- "next/dist/client/app-dir/form": self.__remote_component_host_shared_modules__?.["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
491
+ "next/dist/client/app-dir/form": hostShared["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
421
492
  default: () => {
422
493
  throw new Error("Next.js <Form> component not implemented");
423
494
  },
@@ -428,17 +499,17 @@ function sharedPolyfills(shared, resolveClientUrl) {
428
499
  // This gives us full next/image fidelity (fill, priority, srcSet, blur
429
500
  // placeholders, error handling) while routing image optimization through the
430
501
  // remote app's /_next/image endpoint.
431
- "next/dist/shared/lib/image-loader": self.__remote_component_host_shared_modules__?.["next/dist/shared/lib/image-loader"] ?? shared?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
502
+ "next/dist/shared/lib/image-loader": hostShared["next/dist/shared/lib/image-loader"] ?? shared?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
432
503
  default: createRemoteImageLoader(bundle, resolveClientUrl),
433
504
  __esModule: true
434
505
  })),
435
- "next/dist/client/script": self.__remote_component_host_shared_modules__?.["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
506
+ "next/dist/client/script": hostShared["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
436
507
  // TODO: implement <Script> component for non-Next.js host applications
437
508
  // do not throw an error for now
438
509
  default: () => null,
439
510
  __esModule: true
440
511
  })),
441
- "next/router": self.__remote_component_host_shared_modules__?.["next/router"] ?? shared?.["next/router"] ?? (() => (
512
+ "next/router": hostShared["next/router"] ?? shared?.["next/router"] ?? (() => (
442
513
  // TODO: incomplete implementation
443
514
  Promise.resolve({
444
515
  useRouter() {
@@ -474,34 +545,70 @@ function sharedPolyfills(shared, resolveClientUrl) {
474
545
  return polyfill;
475
546
  }
476
547
 
477
- // src/host/shared/state.ts
478
- function createHostState() {
548
+ // src/host/shared/shared-module-resolver.ts
549
+ var CORE_REACT_PATH_MAP = {
550
+ react: "/react/index.js",
551
+ "react/jsx-dev-runtime": "/react/jsx-dev-runtime.js",
552
+ "react/jsx-runtime": "/react/jsx-runtime.js",
553
+ "react-dom": "/react-dom/index.js",
554
+ "react-dom/client": "/react-dom/client.js"
555
+ };
556
+ var VENDOR_SHARED = Object.fromEntries(
557
+ Object.entries(CORE_REACT_PATH_MAP).filter(([key]) => key !== "react-dom/client").map(([key, path]) => [key, `'${path}'`])
558
+ );
559
+ function buildCoreShared(userShared) {
479
560
  return {
480
- stage: "idle",
481
- prevSrc: void 0,
482
- prevUrl: void 0,
483
- prevName: void 0,
484
- prevIsRemoteComponent: false,
485
- abortController: void 0
561
+ react: async () => (await import("react")).default,
562
+ "react-dom": async () => (await import("react-dom")).default,
563
+ "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
564
+ "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
565
+ "react-dom/client": async () => (await import("react-dom/client")).default,
566
+ ...userShared
486
567
  };
487
568
  }
488
-
489
- // src/host/utils/resolve-name-from-src.ts
490
- function resolveNameFromSrc(src, defaultName) {
491
- if (!src) {
492
- return defaultName;
493
- }
494
- const hash = typeof src === "string" ? src : src.hash;
495
- const hashIndex = hash.indexOf("#");
496
- if (hashIndex < 0) {
497
- return defaultName;
498
- }
499
- const name = hash.slice(hashIndex + 1);
500
- return name || defaultName;
569
+ function buildHostShared(userShared, resolveClientUrl, options) {
570
+ const self = globalThis;
571
+ const result = {
572
+ ...sharedPolyfills(userShared, resolveClientUrl),
573
+ ...self.__remote_component_host_shared_modules__,
574
+ ...userShared
575
+ };
576
+ if (options?.includeRemoteComponentShared) {
577
+ Object.assign(result, self.__remote_component_shared__);
578
+ }
579
+ return result;
580
+ }
581
+ async function buildWebpackResolve(hostShared, remoteShared, bundle, reactModules, callerTag = "SharedModuleResolver") {
582
+ const resolve = {
583
+ ...reactModules,
584
+ ...Object.entries(remoteShared).reduce(
585
+ (acc, [key, value]) => {
586
+ if (typeof hostShared[value] !== "undefined") {
587
+ acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
588
+ } else {
589
+ logDebug(
590
+ callerTag,
591
+ `Remote requests "${value}" but host doesn't provide it`
592
+ );
593
+ }
594
+ return acc;
595
+ },
596
+ {}
597
+ )
598
+ };
599
+ await Promise.all(
600
+ Object.entries(resolve).map(async ([key, value]) => {
601
+ if (typeof value === "function") {
602
+ resolve[key] = await value(bundle);
603
+ }
604
+ return Promise.resolve(value);
605
+ })
606
+ );
607
+ return resolve;
501
608
  }
502
609
 
503
- // src/runtime/html/apply-origin.ts
504
- var tagNames = [
610
+ // src/runtime/html/html-spec.ts
611
+ var ORIGIN_REWRITE_TAGS = [
505
612
  "img",
506
613
  "source",
507
614
  "video",
@@ -512,10 +619,37 @@ var tagNames = [
512
619
  "script",
513
620
  "link"
514
621
  ];
622
+ var ID_SUFFIX_RSC = "_rsc";
623
+ var ID_SUFFIX_SSR = "_ssr";
624
+ var ID_SUFFIX_SHARED = "_shared";
625
+ var DATA_BUNDLE = "data-bundle";
626
+ var DATA_ROUTE = "data-route";
627
+ var DATA_RUNTIME = "data-runtime";
628
+ var DATA_TYPE = "data-type";
629
+ var DATA_SRC = "data-src";
630
+ var DATA_REMOTE_COMPONENTS_SHARED = "data-remote-components-shared";
631
+ var TAG_REMOTE_COMPONENT = "remote-component";
632
+ var NEXT_DATA_ID = "__NEXT_DATA__";
633
+ var REMOTE_NEXT_DATA_ID = "__REMOTE_NEXT_DATA__";
634
+ var NEXT_CONTAINER_ID = "__next";
635
+
636
+ // src/runtime/html/rewrite-srcset.ts
637
+ function rewriteSrcset(srcset, base, resolve) {
638
+ return srcset.split(",").map((entry) => {
639
+ const [url, descriptor] = entry.trim().split(/\s+/);
640
+ if (!url)
641
+ return entry;
642
+ const absoluteUrl = new URL(url, base).href;
643
+ const resolvedUrl = resolve ? resolve(absoluteUrl) : absoluteUrl;
644
+ return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
645
+ }).join(", ");
646
+ }
647
+
648
+ // src/runtime/html/apply-origin.ts
515
649
  function applyOriginToNodes(doc, url, resolveClientUrl) {
516
650
  if (url.origin !== location.origin) {
517
651
  const nodes = doc.querySelectorAll(
518
- tagNames.map(
652
+ ORIGIN_REWRITE_TAGS.map(
519
653
  (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
520
654
  ).join(",")
521
655
  );
@@ -533,29 +667,17 @@ function applyOriginToNodes(doc, url, resolveClientUrl) {
533
667
  );
534
668
  }
535
669
  if (node.hasAttribute("srcset")) {
536
- const srcSet = node.getAttribute("srcset")?.split(",").map((entry) => {
537
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
538
- if (!urlPart)
539
- return entry;
540
- const absoluteUrl = new URL(urlPart, url).href;
541
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
542
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
543
- }).join(", ");
544
- if (srcSet) {
545
- node.setAttribute("srcset", srcSet);
670
+ const raw = node.getAttribute("srcset");
671
+ if (raw) {
672
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
673
+ node.setAttribute("srcset", rewriteSrcset(raw, url, resolve));
546
674
  }
547
675
  }
548
676
  if (node.hasAttribute("imagesrcset")) {
549
- const srcSet = node.getAttribute("imagesrcset")?.split(",").map((entry) => {
550
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
551
- if (!urlPart)
552
- return entry;
553
- const absoluteUrl = new URL(urlPart, url).href;
554
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
555
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
556
- }).join(", ");
557
- if (srcSet) {
558
- node.setAttribute("imagesrcset", srcSet);
677
+ const raw = node.getAttribute("imagesrcset");
678
+ if (raw) {
679
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
680
+ node.setAttribute("imagesrcset", rewriteSrcset(raw, url, resolve));
559
681
  }
560
682
  }
561
683
  });
@@ -596,26 +718,28 @@ function buildMetadata(attrs, url) {
596
718
 
597
719
  // src/runtime/html/parse-remote-html.ts
598
720
  function validateSingleComponent(doc, name, url) {
599
- 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}"]`)) {
721
+ if (doc.querySelectorAll(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`).length > 1 && !doc.querySelector(
722
+ `div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`
723
+ ) || doc.querySelectorAll(`${TAG_REMOTE_COMPONENT}:not([src])`).length > 1 && !doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]`)) {
600
724
  throw multipleRemoteComponentsError(url);
601
725
  }
602
726
  }
603
727
  function findComponentElement(doc, name) {
604
- 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])");
728
+ 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])`);
605
729
  }
606
730
  function parseNextData(doc) {
607
731
  return JSON.parse(
608
- (doc.querySelector("#__NEXT_DATA__") ?? doc.querySelector("#__REMOTE_NEXT_DATA__"))?.textContent ?? "null"
732
+ (doc.querySelector(`#${NEXT_DATA_ID}`) ?? doc.querySelector(`#${REMOTE_NEXT_DATA_ID}`))?.textContent ?? "null"
609
733
  );
610
734
  }
611
735
  function resolveComponentName(component, nextData, fallbackName) {
612
- const isRemoteComponent = component?.tagName.toLowerCase() === "remote-component";
613
- const name = component?.getAttribute("id")?.replace(/_ssr$/, "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
736
+ const isRemoteComponent = component?.tagName.toLowerCase() === TAG_REMOTE_COMPONENT;
737
+ const name = component?.getAttribute("id")?.replace(new RegExp(`${ID_SUFFIX_SSR}$`), "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
614
738
  return { name, isRemoteComponent };
615
739
  }
616
740
  function extractRemoteShared(doc, name, nextData) {
617
741
  const remoteSharedEl = doc.querySelector(
618
- `#${name}_shared[data-remote-components-shared]`
742
+ `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`
619
743
  );
620
744
  const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
621
745
  remoteSharedEl?.remove();
@@ -636,7 +760,7 @@ function extractLinks(doc, component) {
636
760
  function extractScripts(doc, component, isRemoteComponent) {
637
761
  return Array.from(
638
762
  (isRemoteComponent ? component : doc).querySelectorAll(
639
- "script[src],script[data-src]"
763
+ `script[src],script[${DATA_SRC}]`
640
764
  )
641
765
  );
642
766
  }
@@ -649,15 +773,15 @@ function parseRemoteComponentDocument(doc, name, url) {
649
773
  nextData,
650
774
  name
651
775
  );
652
- const rsc = doc.querySelector(`#${resolvedName}_rsc`);
776
+ const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);
653
777
  const metadata = buildMetadata(
654
778
  {
655
779
  name: resolvedName,
656
- bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle,
657
- route: component?.getAttribute("data-route") ?? nextData?.page,
658
- runtime: component?.getAttribute("data-runtime") ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
780
+ bundle: component?.getAttribute(DATA_BUNDLE) || nextData?.props.__REMOTE_COMPONENT__?.bundle,
781
+ route: component?.getAttribute(DATA_ROUTE) ?? nextData?.page,
782
+ runtime: component?.getAttribute(DATA_RUNTIME) ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
659
783
  id: component?.getAttribute("id"),
660
- type: component?.getAttribute("data-type")
784
+ type: component?.getAttribute(DATA_TYPE)
661
785
  },
662
786
  url
663
787
  );
@@ -685,48 +809,6 @@ function parseRemoteComponentDocument(doc, name, url) {
685
809
  };
686
810
  }
687
811
 
688
- // src/runtime/html/set-attributes-from-props.ts
689
- var DOMAttributeNames = {
690
- acceptCharset: "accept-charset",
691
- className: "class",
692
- htmlFor: "for",
693
- httpEquiv: "http-equiv",
694
- noModule: "noModule"
695
- };
696
- var ignoreProps = [
697
- "onLoad",
698
- "onReady",
699
- "dangerouslySetInnerHTML",
700
- "children",
701
- "onError",
702
- "strategy",
703
- "stylesheets"
704
- ];
705
- function isBooleanScriptAttribute(attr) {
706
- return ["async", "defer", "noModule"].includes(attr);
707
- }
708
- function setAttributesFromProps(el, props) {
709
- for (const [p, value] of Object.entries(props)) {
710
- if (!Object.hasOwn(props, p))
711
- continue;
712
- if (ignoreProps.includes(p))
713
- continue;
714
- if (value === void 0) {
715
- continue;
716
- }
717
- const attr = DOMAttributeNames[p] || p.toLowerCase();
718
- if (el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr)) {
719
- el[attr] = Boolean(value);
720
- } else {
721
- el.setAttribute(attr, String(value));
722
- }
723
- if (value === false || el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr) && (!value || value === "false")) {
724
- el.setAttribute(attr, "");
725
- el.removeAttribute(attr);
726
- }
727
- }
728
- }
729
-
730
812
  // src/runtime/loaders/component-loader.ts
731
813
  import * as React from "react";
732
814
  import * as JSXDevRuntime from "react/jsx-dev-runtime";
@@ -746,13 +828,15 @@ function applySharedModules(bundle, resolve) {
746
828
  `Shared modules to resolve: ${Object.keys(resolve)}`
747
829
  );
748
830
  const self = globalThis;
749
- if (self.__remote_webpack_require__?.[bundle]) {
831
+ const scope = getScope(bundle);
832
+ const webpackBundle = scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];
833
+ if (webpackBundle) {
750
834
  const modulePaths = Object.keys(
751
- self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
835
+ self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {}
752
836
  );
753
837
  logDebug(
754
838
  "SharedModules",
755
- `Available module paths in __remote_webpack_require__[${bundle}]: ${modulePaths}`
839
+ `Available module paths for bundle "${bundle}": ${modulePaths}`
756
840
  );
757
841
  for (const [key, value] of Object.entries(resolve)) {
758
842
  const exactIds = modulePaths.filter((p) => p === key);
@@ -764,7 +848,6 @@ function applySharedModules(bundle, resolve) {
764
848
  );
765
849
  }
766
850
  for (const id of ids) {
767
- const webpackBundle = self.__remote_webpack_require__[bundle];
768
851
  if (webpackBundle.m) {
769
852
  const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
770
853
  if (resolvedId !== id) {
@@ -862,10 +945,8 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
862
945
  ];
863
946
  const { default: Component } = componentLoader();
864
947
  const { default: App } = appLoader();
865
- if (!self.__remote_next_css__) {
866
- self.__remote_next_css__ = {};
867
- }
868
- if (!self.__remote_next_css__[bundle]) {
948
+ const cssCache = getNamespace().cssCache;
949
+ if (!cssCache[bundle]) {
869
950
  const cssRE = /\.s?css$/;
870
951
  Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
871
952
  self.__remote_webpack_require__?.[bundle]?.(id);
@@ -883,15 +964,15 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
883
964
  node.remove();
884
965
  node = nextCss.previousSibling;
885
966
  }
886
- self.__remote_next_css__[bundle] = elements;
967
+ cssCache[bundle] = elements;
887
968
  }
888
969
  if (styleContainer) {
889
- const elements = self.__remote_next_css__[bundle];
970
+ const elements = cssCache[bundle];
890
971
  elements.forEach((el) => {
891
972
  styleContainer.appendChild(el.cloneNode(true));
892
973
  });
893
974
  } else {
894
- const elements = self.__remote_next_css__[bundle];
975
+ const elements = cssCache[bundle];
895
976
  elements.forEach((el) => {
896
977
  document.head.appendChild(el);
897
978
  });
@@ -928,6 +1009,18 @@ function fixPayload(payload) {
928
1009
  }
929
1010
  }
930
1011
  }
1012
+ function buildRSCChunks(rscName, data) {
1013
+ const chunks = [];
1014
+ for (const chunk of data) {
1015
+ for (const line of chunk.split("\n")) {
1016
+ const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1017
+ if (match?.groups?.rsc) {
1018
+ chunks.push(JSON.parse(`"${match.groups.rsc}"`));
1019
+ }
1020
+ }
1021
+ }
1022
+ return chunks;
1023
+ }
931
1024
  function createRSCStream(rscName, data) {
932
1025
  return new ReadableStream({
933
1026
  type: "bytes",
@@ -935,16 +1028,11 @@ function createRSCStream(rscName, data) {
935
1028
  const encoder = new TextEncoder();
936
1029
  const self = globalThis;
937
1030
  if (data.length > 0) {
938
- data.forEach((chunk) => {
939
- const lines = chunk.split("\n");
940
- for (const line of lines) {
941
- const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
942
- if (match?.groups?.rsc) {
943
- self[rscName] = self[rscName] ?? [];
944
- self[rscName].push(JSON.parse(`"${match.groups.rsc}"`));
945
- }
946
- }
947
- });
1031
+ const parsed = buildRSCChunks(rscName, data);
1032
+ if (parsed.length > 0) {
1033
+ self[rscName] = self[rscName] ?? [];
1034
+ self[rscName].push(...parsed);
1035
+ }
948
1036
  }
949
1037
  const allChunks = (self[rscName] ?? [`0:[null]
950
1038
  `]).join("");
@@ -974,12 +1062,38 @@ function createRSCStream(rscName, data) {
974
1062
  });
975
1063
  }
976
1064
 
1065
+ // src/runtime/rsc-imports.ts
1066
+ async function importRSCClientBrowser() {
1067
+ try {
1068
+ return await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1069
+ } catch {
1070
+ const mod = await import("react-server-dom-webpack/client.browser");
1071
+ return mod.default ?? mod;
1072
+ }
1073
+ }
1074
+
977
1075
  // src/runtime/turbopack/patterns.ts
1076
+ var MODULE_ID_PATTERN = '"[^"]+"|[0-9]+';
1077
+ function stripQuotes(value) {
1078
+ if (value.startsWith('"') && value.endsWith('"')) {
1079
+ return value.slice(1, -1);
1080
+ }
1081
+ return value;
1082
+ }
1083
+ function extractGroup(re, input, group) {
1084
+ const raw = re.exec(input)?.groups?.[group];
1085
+ return raw ? stripQuotes(raw) : void 0;
1086
+ }
978
1087
  var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
979
- var REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
980
- var ASYNC_MODULE_LOADER_RE = /(?:__turbopack_context__|e)\.A\((?<asyncSharedModuleId>[0-9]+)\)/;
981
- var ASYNC_MODULE_RESOLVE_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<inner>parentImport|e)=>Promise\.resolve\(\)\.then\(\(\)=>\k<inner>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
982
- 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]+)\)\)\)\}/;
1088
+ var REMOTE_SHARED_ASSIGNMENT_RE = new RegExp(
1089
+ `\\.TURBOPACK_REMOTE_SHARED\\s*=\\s*await (?:__turbopack_context__|[a-z])\\.A\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1090
+ );
1091
+ var ASYNC_MODULE_LOADER_RE = new RegExp(
1092
+ `(?:__turbopack_context__|[a-z])\\.A\\((?<asyncSharedModuleId>${MODULE_ID_PATTERN})\\)`
1093
+ );
1094
+ var ASYNC_MODULE_CALLBACK_RE = new RegExp(
1095
+ `(?:parentImport|[a-z])\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1096
+ );
983
1097
  var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
984
1098
 
985
1099
  // src/runtime/turbopack/chunk-loader.ts
@@ -989,6 +1103,7 @@ function loadChunkWithScope(scope, chunkId) {
989
1103
  `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
990
1104
  );
991
1105
  const self = globalThis;
1106
+ const ns = getNamespace();
992
1107
  const { bundle, path, prefix } = parseRemoteId(chunkId);
993
1108
  const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
994
1109
  if (remoteRuntime === RUNTIME_WEBPACK) {
@@ -999,35 +1114,31 @@ function loadChunkWithScope(scope, chunkId) {
999
1114
  if (url.endsWith(".css")) {
1000
1115
  return;
1001
1116
  }
1002
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
1003
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
1004
- }
1005
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
1006
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1117
+ if (ns.chunkCache[url]) {
1118
+ logDebug("ChunkLoader", `Cache hit for "${chunkId}" (url="${url}")`);
1119
+ return ns.chunkCache[url];
1007
1120
  }
1008
1121
  const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1009
1122
  if (resolvedUrl !== url) {
1010
1123
  logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1011
1124
  }
1012
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
1013
- (resolve, reject) => {
1014
- fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1015
- const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1016
- if (hasTurbopack) {
1017
- return handleTurbopackChunk(code, scope, url);
1018
- }
1019
- }).then(resolve).catch((error) => {
1020
- const isProxied = isProxiedUrl(resolvedUrl);
1021
- if (isProxied) {
1022
- reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1023
- } else {
1024
- warnCrossOriginFetchError("ChunkLoader", url);
1025
- reject(error);
1026
- }
1027
- });
1028
- }
1029
- );
1030
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
1125
+ ns.chunkCache[url] = new Promise((resolve, reject) => {
1126
+ fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1127
+ const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1128
+ if (hasTurbopack) {
1129
+ return handleTurbopackChunk(code, scope, url);
1130
+ }
1131
+ }).then(resolve).catch((error) => {
1132
+ const isProxied = isProxiedUrl(resolvedUrl);
1133
+ if (isProxied) {
1134
+ reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1135
+ } else {
1136
+ warnCrossOriginFetchError("ChunkLoader", url);
1137
+ reject(error);
1138
+ }
1139
+ });
1140
+ });
1141
+ return ns.chunkCache[url];
1031
1142
  }
1032
1143
  function createChunkDispatcher() {
1033
1144
  return function __chunk_dispatcher__(chunkId, scriptBundle) {
@@ -1076,19 +1187,39 @@ async function handleTurbopackChunk(code, scope, url) {
1076
1187
  `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1077
1188
  );
1078
1189
  if (!self[`TURBOPACK_${globalKey}`]) {
1079
- const chunkData = [];
1080
- const turbopackObject = {
1081
- push: (item) => {
1082
- if (Array.isArray(item)) {
1083
- chunkData.push(item);
1084
- } else {
1085
- chunkData.push([item]);
1190
+ const wrapPush = (target) => {
1191
+ const originalPush = target.push;
1192
+ if (typeof originalPush !== "function")
1193
+ return target;
1194
+ target.push = (...items) => {
1195
+ for (const item of items) {
1196
+ if (Array.isArray(item)) {
1197
+ for (const entry of item) {
1198
+ scope.turbopackModules.push(entry);
1199
+ }
1200
+ } else {
1201
+ scope.turbopackModules.push(item);
1202
+ }
1086
1203
  }
1087
- return chunkData.length;
1088
- },
1089
- __chunks__: chunkData
1204
+ return originalPush.apply(target, items);
1205
+ };
1206
+ return target;
1090
1207
  };
1091
- self[`TURBOPACK_${globalKey}`] = turbopackObject;
1208
+ const globalProp = `TURBOPACK_${globalKey}`;
1209
+ let currentValue = wrapPush([]);
1210
+ Object.defineProperty(self, globalProp, {
1211
+ get() {
1212
+ return currentValue;
1213
+ },
1214
+ set(newValue) {
1215
+ if (newValue && typeof newValue === "object") {
1216
+ wrapPush(newValue);
1217
+ }
1218
+ currentValue = newValue;
1219
+ },
1220
+ configurable: true,
1221
+ enumerable: true
1222
+ });
1092
1223
  }
1093
1224
  await new Promise((scriptResolve, scriptReject) => {
1094
1225
  const blob = new Blob([transformedCode], {
@@ -1140,13 +1271,13 @@ async function handleTurbopackChunk(code, scope, url) {
1140
1271
  // src/runtime/turbopack/shared-modules.ts
1141
1272
  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).";
1142
1273
  function getTurbopackModules(scope) {
1274
+ if (scope.turbopackModules.length > 0) {
1275
+ return scope.turbopackModules;
1276
+ }
1143
1277
  const self = globalThis;
1144
1278
  const raw = self[`TURBOPACK_${scope.globalKey}`];
1145
1279
  if (!raw)
1146
1280
  return void 0;
1147
- if (typeof raw === "object" && "__chunks__" in raw) {
1148
- return raw.__chunks__.flat();
1149
- }
1150
1281
  if (Array.isArray(raw)) {
1151
1282
  return raw.flat();
1152
1283
  }
@@ -1170,7 +1301,11 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1170
1301
  if (sharedModuleInitializerIndex > 0) {
1171
1302
  const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1172
1303
  const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1173
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1304
+ const sharedModuleId = extractGroup(
1305
+ REMOTE_SHARED_ASSIGNMENT_RE,
1306
+ sharedModuleInitializerCode,
1307
+ "sharedModuleId"
1308
+ );
1174
1309
  if (sharedModuleId) {
1175
1310
  const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1176
1311
  scope,
@@ -1228,20 +1363,22 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1228
1363
  }
1229
1364
  function extractSharedModuleIds(shared, scope) {
1230
1365
  return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1231
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1366
+ const asyncSharedModuleId = extractGroup(
1367
+ ASYNC_MODULE_LOADER_RE,
1368
+ value.toString(),
1369
+ "asyncSharedModuleId"
1370
+ );
1232
1371
  if (asyncSharedModuleId) {
1233
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1234
- let asyncSharedModule;
1235
- const turbopackModules = getTurbopackModules(scope) ?? [];
1236
- const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1237
- asyncSharedModuleIdNumber
1372
+ const asyncSharedModule = findModuleInit(
1373
+ getTurbopackModules(scope),
1374
+ asyncSharedModuleId
1238
1375
  );
1239
- if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1240
- asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1241
- }
1242
1376
  if (asyncSharedModule) {
1243
- const asyncSharedModuleCode = asyncSharedModule.toString();
1244
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1377
+ const sharedModuleId = extractGroup(
1378
+ ASYNC_MODULE_CALLBACK_RE,
1379
+ asyncSharedModule.toString(),
1380
+ "sharedModuleId"
1381
+ );
1245
1382
  acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1246
1383
  "__remote_shared_module_",
1247
1384
  ""
@@ -1332,9 +1469,17 @@ function findModuleInit(modules, moduleId) {
1332
1469
  if (idx >= 0) {
1333
1470
  return flat.slice(idx + 1).find((e) => typeof e === "function");
1334
1471
  }
1335
- return flat.find(
1336
- (e) => Boolean(e && typeof e === "object" && moduleId in e)
1337
- )?.[moduleId];
1472
+ for (const entry of flat) {
1473
+ if (!entry || typeof entry !== "object")
1474
+ continue;
1475
+ const obj = entry;
1476
+ if (moduleId in obj)
1477
+ return obj[moduleId];
1478
+ const prefixKey = Object.keys(obj).find((k) => k.startsWith(moduleId));
1479
+ if (prefixKey)
1480
+ return obj[prefixKey];
1481
+ }
1482
+ return void 0;
1338
1483
  }
1339
1484
  function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1340
1485
  const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
@@ -1413,7 +1558,10 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1413
1558
  }
1414
1559
  if (typeof mod !== "object" || mod === null) {
1415
1560
  mod = { default: mod };
1416
- } else if (!("default" in mod) && mod.toString() !== "[object Module]") {
1561
+ } else if (!("default" in mod) && // ES module namespace objects have a null prototype, so calling
1562
+ // mod.toString() directly throws. Use Object.prototype.toString
1563
+ // to safely detect them.
1564
+ Object.prototype.toString.call(mod) !== "[object Module]") {
1417
1565
  try {
1418
1566
  mod.default = mod;
1419
1567
  } catch {
@@ -1477,21 +1625,38 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1477
1625
  };
1478
1626
  }
1479
1627
 
1480
- // src/runtime/turbopack/webpack-runtime.ts
1481
- async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1628
+ // src/runtime/turbopack/remote-scope-setup.ts
1629
+ async function setupRemoteScope(runtime, scripts = [], url = new URL(location.href), bundle, resolveClientUrl) {
1482
1630
  const self = globalThis;
1631
+ const ns = getNamespace();
1483
1632
  const bundleName = bundle ?? "default";
1633
+ const existingScope = getScope(bundleName);
1634
+ if (existingScope && existingScope.url.origin === url.origin) {
1635
+ logDebug(
1636
+ "WebpackRuntime",
1637
+ `Reusing scope "${existingScope.scopedName}" (turbopackModules=${existingScope.turbopackModules.length})`
1638
+ );
1639
+ existingScope.resolveClientUrl = resolveClientUrl;
1640
+ if (runtime === RUNTIME_TURBOPACK) {
1641
+ await Promise.allSettled(
1642
+ scripts.map(
1643
+ (script) => script.src ? loadChunkWithScope(existingScope, script.src) : Promise.resolve(void 0)
1644
+ )
1645
+ );
1646
+ }
1647
+ return existingScope;
1648
+ }
1484
1649
  const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1485
1650
  registerScope(scope);
1486
- if (!self.__remote_bundle_url__) {
1487
- self.__remote_bundle_url__ = {};
1651
+ if (runtime === RUNTIME_WEBPACK && self.__remote_webpack_require__?.[bundleName]) {
1652
+ scope.webpackRequire = self.__remote_webpack_require__[bundleName];
1488
1653
  }
1489
- self.__remote_bundle_url__[bundleName] = url;
1654
+ ns.bundleUrls[bundleName] = url;
1490
1655
  if (scope.scopedName !== bundleName) {
1491
- self.__remote_bundle_url__[scope.scopedName] = url;
1656
+ ns.bundleUrls[scope.scopedName] = url;
1492
1657
  }
1493
1658
  self.__webpack_get_script_filename__ = () => null;
1494
- const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1659
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || ns.dispatcherRuntime !== "turbopack";
1495
1660
  if (willCreateDispatchers) {
1496
1661
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1497
1662
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
@@ -1499,6 +1664,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1499
1664
  }
1500
1665
  self.__webpack_chunk_load__ = createChunkDispatcher();
1501
1666
  self.__webpack_require__ = createModuleDispatcher(runtime);
1667
+ ns.dispatcherRuntime = runtime;
1502
1668
  self.__webpack_require_type__ = runtime;
1503
1669
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1504
1670
  self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
@@ -1526,15 +1692,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1526
1692
  }
1527
1693
  }
1528
1694
  }
1529
- const coreShared = {
1530
- react: async () => (await import("react")).default,
1531
- "react-dom": async () => (await import("react-dom")).default,
1532
- "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
1533
- "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
1534
- "react-dom/client": async () => (await import("react-dom/client")).default,
1535
- ...shared
1536
- };
1537
- await initializeSharedModules(scope, coreShared, remoteShared);
1695
+ return scope;
1538
1696
  }
1539
1697
  function createModuleDispatcher(runtime) {
1540
1698
  return (id) => {
@@ -1551,6 +1709,9 @@ function createModuleDispatcher(runtime) {
1551
1709
  );
1552
1710
  try {
1553
1711
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1712
+ const scope2 = getScope(bundle);
1713
+ if (scope2?.webpackRequire)
1714
+ return scope2.webpackRequire(moduleId);
1554
1715
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1555
1716
  }
1556
1717
  const scope = getScope(bundleName);
@@ -1668,44 +1829,33 @@ async function loadRemoteComponent({
1668
1829
  "ComponentLoader",
1669
1830
  `Remote shared modules requested: ${JSON.stringify(remoteShared)}`
1670
1831
  );
1671
- await setupWebpackRuntime(
1832
+ const scope = await setupRemoteScope(
1672
1833
  runtime,
1673
1834
  scripts,
1674
1835
  url,
1675
1836
  bundle,
1676
- hostShared,
1677
- remoteShared,
1678
1837
  resolveClientUrl
1679
1838
  );
1839
+ if (runtime === "turbopack") {
1840
+ await initializeSharedModules(
1841
+ scope,
1842
+ buildCoreShared(hostShared),
1843
+ remoteShared
1844
+ );
1845
+ }
1680
1846
  if (bundle) {
1681
- const resolve = {
1682
- "/react/index.js": React,
1683
- "/react/jsx-dev-runtime.js": JSXDevRuntime,
1684
- "/react/jsx-runtime.js": JSXRuntime,
1685
- "/react-dom/index.js": ReactDOM,
1686
- "/react-dom/client.js": ReactDOMClient,
1687
- ...Object.entries(remoteShared).reduce(
1688
- (acc, [key, value]) => {
1689
- if (typeof hostShared[value] !== "undefined") {
1690
- acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
1691
- } else {
1692
- logDebug(
1693
- "ComponentLoader",
1694
- `Remote requests "${value}" but host doesn't provide it`
1695
- );
1696
- }
1697
- return acc;
1698
- },
1699
- {}
1700
- )
1701
- };
1702
- await Promise.all(
1703
- Object.entries(resolve).map(async ([key, value]) => {
1704
- if (typeof value === "function") {
1705
- resolve[key] = await value(bundle);
1706
- }
1707
- return Promise.resolve(value);
1708
- })
1847
+ const resolve = await buildWebpackResolve(
1848
+ hostShared,
1849
+ remoteShared,
1850
+ bundle,
1851
+ {
1852
+ "/react/index.js": React,
1853
+ "/react/jsx-dev-runtime.js": JSXDevRuntime,
1854
+ "/react/jsx-runtime.js": JSXRuntime,
1855
+ "/react-dom/index.js": ReactDOM,
1856
+ "/react-dom/client.js": ReactDOMClient
1857
+ },
1858
+ "ComponentLoader"
1709
1859
  );
1710
1860
  applySharedModules(bundle, resolve);
1711
1861
  } else {
@@ -1733,19 +1883,8 @@ async function loadRemoteComponent({
1733
1883
  };
1734
1884
  }
1735
1885
  }
1736
- async function importCreateFromReadableStream() {
1737
- try {
1738
- const { createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1739
- return createFromReadableStream;
1740
- } catch {
1741
- const {
1742
- default: { createFromReadableStream }
1743
- } = await import("react-server-dom-webpack/client.browser");
1744
- return createFromReadableStream;
1745
- }
1746
- }
1747
1886
  async function loadRSCComponent(rscName, data) {
1748
- const createFromReadableStream = await importCreateFromReadableStream();
1887
+ const { createFromReadableStream } = await importRSCClientBrowser();
1749
1888
  if (typeof createFromReadableStream !== "function") {
1750
1889
  throw new RemoteComponentsError(
1751
1890
  'Failed to import "react-server-dom-webpack". Is Next.js installed correctly?'
@@ -1809,10 +1948,9 @@ async function importViaCallback(absoluteSrc, resolveClientUrl) {
1809
1948
  URL.revokeObjectURL(moduleBlobUrl);
1810
1949
  URL.revokeObjectURL(wrapperBlobUrl);
1811
1950
  }
1812
- const registry = globalThis.__rc_module_registry__;
1813
- const mod = registry?.[absoluteSrc] ?? {};
1814
- if (registry)
1815
- delete registry[absoluteSrc];
1951
+ const registry = getNamespace().moduleRegistry;
1952
+ const mod = registry[absoluteSrc] ?? {};
1953
+ delete registry[absoluteSrc];
1816
1954
  return mod;
1817
1955
  }
1818
1956
  async function importDirectly(absoluteSrc) {
@@ -1842,12 +1980,12 @@ function resolveScriptSrc(script, url) {
1842
1980
  return rawSrc;
1843
1981
  }
1844
1982
  async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1845
- const self = globalThis;
1846
- if (self.__remote_script_entrypoint_mount__?.[url.href]) {
1847
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
1983
+ const ns = getNamespace();
1984
+ if (ns.mountFns[url.href]) {
1985
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1848
1986
  }
1849
- if (self.__remote_script_entrypoint_unmount__?.[url.href]) {
1850
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
1987
+ if (ns.unmountFns[url.href]) {
1988
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1851
1989
  }
1852
1990
  const mountUnmountSets = await Promise.all(
1853
1991
  scripts.map(async (script) => {
@@ -1859,25 +1997,19 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1859
1997
  URL.revokeObjectURL(src);
1860
1998
  }
1861
1999
  if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
1862
- if (!self.__remote_script_entrypoint_mount__) {
1863
- self.__remote_script_entrypoint_mount__ = {};
1864
- }
1865
- if (!self.__remote_script_entrypoint_mount__[url.href]) {
1866
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
2000
+ if (!ns.mountFns[url.href]) {
2001
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1867
2002
  }
1868
- self.__remote_script_entrypoint_mount__[url.href]?.add(
2003
+ ns.mountFns[url.href]?.add(
1869
2004
  mod.mount || mod.default?.mount || (() => {
1870
2005
  })
1871
2006
  );
1872
2007
  }
1873
2008
  if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
1874
- if (!self.__remote_script_entrypoint_unmount__) {
1875
- self.__remote_script_entrypoint_unmount__ = {};
2009
+ if (!ns.unmountFns[url.href]) {
2010
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1876
2011
  }
1877
- if (!self.__remote_script_entrypoint_unmount__[url.href]) {
1878
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
1879
- }
1880
- self.__remote_script_entrypoint_unmount__[url.href]?.add(
2012
+ ns.unmountFns[url.href]?.add(
1881
2013
  mod.unmount || mod.default?.unmount || (() => {
1882
2014
  })
1883
2015
  );
@@ -1916,6 +2048,188 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1916
2048
  );
1917
2049
  }
1918
2050
 
2051
+ // src/host/shared/pipeline.ts
2052
+ function preparePipeline(input) {
2053
+ const parser = new DOMParser();
2054
+ const doc = parser.parseFromString(input.html, "text/html");
2055
+ const parsed = parseRemoteComponentDocument(doc, input.name, input.url);
2056
+ const remoteShared = input.remoteShared ?? parsed.remoteShared;
2057
+ if ("__remote_components_missing_shared__" in remoteShared) {
2058
+ throw new RemoteComponentsError(
2059
+ remoteShared.__remote_components_missing_shared__
2060
+ );
2061
+ }
2062
+ applyOriginToNodes(doc, input.url, input.resolveClientUrl);
2063
+ const scriptDescriptors = buildScriptDescriptors(parsed.scripts, input.url);
2064
+ return { doc, parsed, scriptDescriptors };
2065
+ }
2066
+ async function loadPrepared(input) {
2067
+ const { prepared, url, signal, resolveClientUrl, container, rscName } = input;
2068
+ const { doc, parsed, scriptDescriptors } = prepared;
2069
+ if (signal.aborted) {
2070
+ return { status: "aborted" };
2071
+ }
2072
+ const userShared = await input.shared;
2073
+ if (signal.aborted) {
2074
+ return { status: "aborted" };
2075
+ }
2076
+ if (parsed.isRemoteComponent) {
2077
+ return loadStaticPath({
2078
+ parsed,
2079
+ doc,
2080
+ url,
2081
+ resolveClientUrl
2082
+ });
2083
+ }
2084
+ return loadDynamicPath({
2085
+ parsed,
2086
+ doc,
2087
+ url,
2088
+ scriptDescriptors,
2089
+ shared: userShared,
2090
+ resolveClientUrl,
2091
+ container,
2092
+ rscName
2093
+ });
2094
+ }
2095
+ function buildScriptDescriptors(scripts, url) {
2096
+ return scripts.map((script) => {
2097
+ const scriptSrc = script.getAttribute("data-src") || script.getAttribute("src") || script.src;
2098
+ const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(scriptSrc)?.groups ?? {
2099
+ prefix: void 0,
2100
+ id: scriptSrc
2101
+ };
2102
+ return {
2103
+ src: new URL(collapseDoubleSlashes(`${prefix ?? ""}${path}`), url).href
2104
+ };
2105
+ });
2106
+ }
2107
+ async function loadStaticPath(input) {
2108
+ const { parsed, doc, url, resolveClientUrl } = input;
2109
+ const scripts = Array.from(
2110
+ parsed.component.querySelectorAll("script")
2111
+ );
2112
+ const { mount, unmount } = await loadStaticRemoteComponent(
2113
+ scripts,
2114
+ url,
2115
+ resolveClientUrl
2116
+ );
2117
+ return {
2118
+ status: "static",
2119
+ mount,
2120
+ unmount,
2121
+ metadata: parsed.metadata,
2122
+ parsed,
2123
+ doc
2124
+ };
2125
+ }
2126
+ async function loadDynamicPath(input) {
2127
+ const {
2128
+ parsed,
2129
+ doc,
2130
+ url,
2131
+ scriptDescriptors,
2132
+ shared,
2133
+ resolveClientUrl,
2134
+ container
2135
+ } = input;
2136
+ const rscName = input.rscName ?? (parsed.rsc ? `__remote_component_rsc_${escapeString(url.href)}_${escapeString(parsed.name)}` : void 0);
2137
+ const rscData = parsed.rsc ? (parsed.rsc.textContent || "").split("\n").filter(Boolean) : [];
2138
+ const result = await loadRemoteComponent({
2139
+ url,
2140
+ name: parsed.name,
2141
+ rscName,
2142
+ bundle: parsed.metadata.bundle,
2143
+ route: parsed.metadata.route,
2144
+ runtime: parsed.metadata.runtime,
2145
+ data: rscData,
2146
+ nextData: parsed.nextData,
2147
+ scripts: scriptDescriptors,
2148
+ shared: buildHostShared(shared, resolveClientUrl),
2149
+ remoteShared: parsed.remoteShared,
2150
+ container,
2151
+ resolveClientUrl
2152
+ });
2153
+ if (result.error) {
2154
+ return { status: "error", error: result.error };
2155
+ }
2156
+ return {
2157
+ status: "loaded",
2158
+ component: result.component,
2159
+ metadata: parsed.metadata,
2160
+ parsed,
2161
+ doc
2162
+ };
2163
+ }
2164
+
2165
+ // src/host/shared/state.ts
2166
+ function createHostState() {
2167
+ return {
2168
+ stage: "idle",
2169
+ prevSrc: void 0,
2170
+ prevUrl: void 0,
2171
+ prevName: void 0,
2172
+ prevIsRemoteComponent: false,
2173
+ abortController: void 0
2174
+ };
2175
+ }
2176
+
2177
+ // src/host/utils/resolve-name-from-src.ts
2178
+ function resolveNameFromSrc(src, defaultName) {
2179
+ if (!src) {
2180
+ return defaultName;
2181
+ }
2182
+ const hash = typeof src === "string" ? src : src.hash;
2183
+ const hashIndex = hash.indexOf("#");
2184
+ if (hashIndex < 0) {
2185
+ return defaultName;
2186
+ }
2187
+ const name = hash.slice(hashIndex + 1);
2188
+ return name || defaultName;
2189
+ }
2190
+
2191
+ // src/runtime/html/set-attributes-from-props.ts
2192
+ var DOMAttributeNames = {
2193
+ acceptCharset: "accept-charset",
2194
+ className: "class",
2195
+ htmlFor: "for",
2196
+ httpEquiv: "http-equiv",
2197
+ noModule: "noModule"
2198
+ };
2199
+ var ignoreProps = [
2200
+ "onLoad",
2201
+ "onReady",
2202
+ "dangerouslySetInnerHTML",
2203
+ "children",
2204
+ "onError",
2205
+ "strategy",
2206
+ "stylesheets"
2207
+ ];
2208
+ function isBooleanScriptAttribute(attr) {
2209
+ return ["async", "defer", "noModule"].includes(attr);
2210
+ }
2211
+ function setAttributesFromProps(el, props) {
2212
+ for (const [p, value] of Object.entries(props)) {
2213
+ if (!Object.hasOwn(props, p))
2214
+ continue;
2215
+ if (ignoreProps.includes(p))
2216
+ continue;
2217
+ if (value === void 0) {
2218
+ continue;
2219
+ }
2220
+ const attr = DOMAttributeNames[p] || p.toLowerCase();
2221
+ if (el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr)) {
2222
+ el[attr] = Boolean(value);
2223
+ } else {
2224
+ el.setAttribute(attr, String(value));
2225
+ }
2226
+ if (value === false || el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr) && (!value || value === "false")) {
2227
+ el.setAttribute(attr, "");
2228
+ el.removeAttribute(attr);
2229
+ }
2230
+ }
2231
+ }
2232
+
1919
2233
  // src/host/react/hooks/use-resolve-client-url.ts
1920
2234
  import { useMemo } from "react";
1921
2235
  import { useRemoteComponentsContext } from "#internal/host/react/context";
@@ -1960,27 +2274,25 @@ function useShadowRoot({
1960
2274
  }) {
1961
2275
  const shadowRootContainerRef = useRef(null);
1962
2276
  const [shadowRoot, setShadowRoot] = useState(() => {
1963
- const self = globalThis;
1964
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2277
+ const shadowRoots = getNamespace().shadowRoots;
1965
2278
  const ssrShadowRoot = typeof document !== "undefined" ? document.querySelector(
1966
2279
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
1967
- )?.shadowRoot ?? self[shadowRootKey] ?? null : null;
1968
- self[shadowRootKey] = null;
2280
+ )?.shadowRoot ?? shadowRoots[keySuffix] ?? null : null;
2281
+ shadowRoots[keySuffix] = null;
1969
2282
  return ssrShadowRoot;
1970
2283
  });
1971
2284
  useLayoutEffect(() => {
2285
+ const shadowRoots = getNamespace().shadowRoots;
1972
2286
  if (isolate !== false && typeof document !== "undefined" && (!shadowRoot || !shadowRoot.isConnected)) {
1973
- const self = globalThis;
1974
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
1975
2287
  let shadowRootElement = null;
1976
2288
  const element = document.querySelector(
1977
2289
  `[data-remote-component-id="shadowroot_${keySuffix}"]`
1978
2290
  );
1979
- shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;
2291
+ shadowRootElement = shadowRoots[keySuffix] ?? element?.shadowRoot ?? null;
1980
2292
  if (!shadowRootElement && element) {
1981
2293
  try {
1982
2294
  shadowRootElement = element.attachShadow({ mode });
1983
- self[shadowRootKey] = shadowRootElement;
2295
+ shadowRoots[keySuffix] = shadowRootElement;
1984
2296
  } catch {
1985
2297
  }
1986
2298
  }
@@ -1991,9 +2303,7 @@ function useShadowRoot({
1991
2303
  setShadowRoot(shadowRootElement);
1992
2304
  }
1993
2305
  } else if (isolate === false && shadowRoot) {
1994
- const self = globalThis;
1995
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
1996
- self[shadowRootKey] = null;
2306
+ shadowRoots[keySuffix] = null;
1997
2307
  setShadowRoot(null);
1998
2308
  }
1999
2309
  }, [isolate, shadowRoot, mode, keySuffix]);
@@ -2046,6 +2356,10 @@ function ConsumeRemoteComponent({
2046
2356
  const { credentials: contextCredentials, shared: contextShared } = useRemoteComponentsContext2();
2047
2357
  const credentials = credentialsProp ?? contextCredentials ?? "same-origin";
2048
2358
  const shared = sharedProp ?? contextShared ?? {};
2359
+ const emitter = useMemo2(
2360
+ () => makeReactEmitter({ onBeforeLoad, onLoad, onError, onChange }),
2361
+ [onBeforeLoad, onLoad, onError, onChange]
2362
+ );
2049
2363
  const name = useMemo2(
2050
2364
  () => resolveNameFromSrc(src, nameProp),
2051
2365
  [src, nameProp]
@@ -2089,9 +2403,8 @@ function ConsumeRemoteComponent({
2089
2403
  const prevRemoteComponentContainerRef = useRef2(null);
2090
2404
  const unmountRef = useRef2(null);
2091
2405
  useLayoutEffect2(() => {
2092
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
2093
2406
  return () => {
2094
- delete globalThis[shadowRootKey];
2407
+ delete getNamespace().shadowRoots[keySuffix];
2095
2408
  };
2096
2409
  }, [keySuffix]);
2097
2410
  useLayoutEffect2(() => {
@@ -2136,7 +2449,7 @@ function ConsumeRemoteComponent({
2136
2449
  hostStateRef.current.abortController?.abort();
2137
2450
  hostStateRef.current.abortController = new AbortController();
2138
2451
  const { signal } = hostStateRef.current.abortController;
2139
- onBeforeLoad?.(src);
2452
+ emitter.beforeLoad(src);
2140
2453
  hostStateRef.current.stage = "loading";
2141
2454
  startTransition(async () => {
2142
2455
  try {
@@ -2167,26 +2480,32 @@ function ConsumeRemoteComponent({
2167
2480
  }
2168
2481
  if (signal.aborted)
2169
2482
  return;
2170
- const parser = new DOMParser();
2171
- const doc = parser.parseFromString(html, "text/html");
2483
+ const userShared = await shared;
2484
+ if (signal.aborted)
2485
+ return;
2486
+ const prepared = preparePipeline({
2487
+ html,
2488
+ name,
2489
+ url,
2490
+ shared: userShared,
2491
+ resolveClientUrl
2492
+ });
2493
+ const { doc, parsed } = prepared;
2172
2494
  const {
2173
2495
  component,
2174
2496
  name: remoteName,
2175
2497
  isRemoteComponent,
2176
2498
  metadata,
2177
- nextData,
2178
2499
  rsc,
2179
2500
  remoteShared,
2180
- links: linkElements,
2181
- scripts: scriptElements
2182
- } = parseRemoteComponentDocument(doc, name, url);
2501
+ links: linkElements
2502
+ } = parsed;
2183
2503
  if (hostStateRef.current.prevIsRemoteComponent) {
2184
2504
  if (shadowRoot) {
2185
2505
  shadowRoot.innerHTML = "";
2186
2506
  }
2187
- const self = globalThis;
2188
2507
  const prevUrl = hostStateRef.current.prevUrl;
2189
- if (prevUrl && self.__remote_script_entrypoint_unmount__?.[prevUrl.href]) {
2508
+ if (prevUrl && getNamespace().unmountFns[prevUrl.href]) {
2190
2509
  const unmountPromises = Promise.all(
2191
2510
  Array.from(unmountRef.current ?? []).map(
2192
2511
  async (unmount) => unmount(
@@ -2201,7 +2520,6 @@ function ConsumeRemoteComponent({
2201
2520
  hostStateRef.current.prevIsRemoteComponent = isRemoteComponent;
2202
2521
  hostStateRef.current.prevUrl = url;
2203
2522
  hostStateRef.current.prevName = remoteName;
2204
- applyOriginToNodes(doc, url, resolveClientUrl);
2205
2523
  const links = linkElements.map((link) => ({
2206
2524
  href: new URL(link.getAttribute("href") ?? link.href, url).href,
2207
2525
  ...link.getAttributeNames().reduce((acc, key) => {
@@ -2211,7 +2529,6 @@ function ConsumeRemoteComponent({
2211
2529
  return acc;
2212
2530
  }, {})
2213
2531
  }));
2214
- const scripts = scriptElements;
2215
2532
  const inlineScripts = (isRemoteComponent ? component : doc).querySelectorAll(
2216
2533
  "script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])"
2217
2534
  );
@@ -2290,20 +2607,10 @@ function ConsumeRemoteComponent({
2290
2607
  componentHydrationHtml.current = `${Array.from(
2291
2608
  doc.querySelectorAll("link,style")
2292
2609
  ).map((link) => link.outerHTML).join("")}${reset ? `<style data-remote-components-reset="">:host { all: initial; }</style>` : ""}${component.innerHTML}`;
2293
- const userShared = await shared;
2294
- if ("__remote_components_missing_shared__" in userShared) {
2295
- userShared.__remote_components_missing_shared__().catch((e) => {
2296
- throw e;
2297
- });
2298
- } else if ("__remote_components_missing_shared__" in remoteShared) {
2299
- throw new RemoteComponentsError(
2300
- remoteShared.__remote_components_missing_shared__
2301
- );
2302
- }
2303
2610
  if (isRemoteComponent) {
2304
2611
  if (previousSrc !== void 0) {
2305
- onChange?.({
2306
- previousSrc,
2612
+ emitter.change({
2613
+ previousSrc: previousSrc ?? null,
2307
2614
  nextSrc: src,
2308
2615
  previousName,
2309
2616
  nextName: remoteName
@@ -2324,7 +2631,7 @@ function ConsumeRemoteComponent({
2324
2631
  await Promise.all(
2325
2632
  Array.from(mount).map((mountFn) => mountFn(shadowRoot))
2326
2633
  );
2327
- onLoad?.(src);
2634
+ emitter.load(src);
2328
2635
  } else if (isolate === false) {
2329
2636
  setRemoteComponent(
2330
2637
  // TODO: remove wrapper div by converting HTML to RSC or React tree
@@ -2348,62 +2655,42 @@ function ConsumeRemoteComponent({
2348
2655
  (mountFn) => mountFn(prevRemoteComponentContainerRef.current)
2349
2656
  )
2350
2657
  );
2351
- onLoad?.(src);
2658
+ emitter.load(src);
2352
2659
  }
2353
2660
  hostStateRef.current.stage = "loaded";
2354
2661
  } else {
2355
- const result = await loadRemoteComponent({
2662
+ const result = await loadPrepared({
2663
+ prepared,
2356
2664
  url,
2357
- name: remoteName,
2358
- rscName,
2359
- bundle: metadata.bundle,
2360
- route: metadata.route,
2361
- runtime: metadata.runtime,
2362
- data: newData.data,
2363
- nextData,
2364
- scripts: Array.from(scripts).map((script) => {
2365
- const scriptSrc = script.getAttribute("data-src") || script.getAttribute("src") || script.src;
2366
- const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(
2367
- scriptSrc
2368
- )?.groups ?? {
2369
- prefix: void 0,
2370
- id: scriptSrc
2371
- };
2372
- return {
2373
- src: new URL(
2374
- collapseDoubleSlashes(`${prefix ?? ""}${path}`),
2375
- url
2376
- ).href
2377
- };
2378
- }),
2379
- shared: {
2380
- ...sharedPolyfills(userShared, resolveClientUrl),
2381
- ...userShared
2382
- },
2383
- remoteShared,
2665
+ signal,
2666
+ shared: userShared,
2667
+ resolveClientUrl,
2384
2668
  container: shadowRoot,
2385
- resolveClientUrl
2669
+ rscName
2386
2670
  });
2387
2671
  if (rsc) {
2388
2672
  rsc.remove();
2389
2673
  }
2390
2674
  setData(newData);
2391
2675
  if (previousSrc !== void 0) {
2392
- onChange?.({
2393
- previousSrc,
2676
+ emitter.change({
2677
+ previousSrc: previousSrc ?? null,
2394
2678
  nextSrc: src,
2395
2679
  previousName,
2396
2680
  nextName: remoteName
2397
2681
  });
2398
2682
  }
2399
- if (result.error) {
2683
+ if (result.status === "aborted") {
2684
+ return;
2685
+ }
2686
+ if (result.status === "error") {
2400
2687
  hostStateRef.current.stage = "error";
2401
2688
  setRemoteComponent(result.error);
2402
- onError?.(result.error);
2403
- } else {
2689
+ emitter.error(result.error);
2690
+ } else if (result.status === "loaded") {
2404
2691
  hostStateRef.current.stage = "loaded";
2405
2692
  setRemoteComponent(result.component);
2406
- onLoad?.(src);
2693
+ emitter.load(src);
2407
2694
  }
2408
2695
  }
2409
2696
  } catch (error) {
@@ -2413,7 +2700,7 @@ function ConsumeRemoteComponent({
2413
2700
  }
2414
2701
  hostStateRef.current.stage = "error";
2415
2702
  setRemoteComponent(error);
2416
- onError?.(error);
2703
+ emitter.error(error);
2417
2704
  }
2418
2705
  });
2419
2706
  }
@@ -2427,10 +2714,10 @@ function ConsumeRemoteComponent({
2427
2714
  shadowRoot,
2428
2715
  reset,
2429
2716
  id,
2430
- onBeforeLoad,
2431
- onLoad,
2432
- onError,
2433
- onChange,
2717
+ emitter.beforeLoad,
2718
+ emitter.load,
2719
+ emitter.error,
2720
+ emitter.change,
2434
2721
  onRequest,
2435
2722
  onResponse,
2436
2723
  resolveClientUrl
@@ -2472,7 +2759,7 @@ function ConsumeRemoteComponent({
2472
2759
  );
2473
2760
  }).then(() => {
2474
2761
  if (src) {
2475
- onLoad?.(src);
2762
+ emitter.load(src);
2476
2763
  }
2477
2764
  }).catch((e) => {
2478
2765
  const error = new RemoteComponentsError(
@@ -2482,7 +2769,7 @@ function ConsumeRemoteComponent({
2482
2769
  }
2483
2770
  );
2484
2771
  setRemoteComponent(error);
2485
- onError?.(error);
2772
+ emitter.error(error);
2486
2773
  });
2487
2774
  }
2488
2775
  }
@@ -2511,8 +2798,10 @@ function ConsumeRemoteComponent({
2511
2798
  alt="" decoding="async" style="display:none"
2512
2799
  src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
2513
2800
  onload="(function(el){
2801
+ // Capture the shadow root during SSR hydration so the client-side
2802
+ // useShadowRoot hook can find it.
2514
2803
  const root = el.getRootNode();
2515
- globalThis.__remote_components_shadowroot_${keySuffix} = root;
2804
+ globalThis.__remote_components_shadowroot_${keySuffix}=root;
2516
2805
  el.parentElement.remove();
2517
2806
  })(this)"
2518
2807
  />`