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
@@ -205,7 +205,7 @@ var init_logger = __esm({
205
205
  init_constants();
206
206
  init_error();
207
207
  PREFIX = "remote-components";
208
- DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
208
+ DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true" || typeof process !== "undefined" && process.env.RC_DEBUG === "true";
209
209
  }
210
210
  });
211
211
 
@@ -240,190 +240,65 @@ var init_constants2 = __esm({
240
240
  }
241
241
  });
242
242
 
243
- // src/config/webpack/apply-shared-modules.ts
244
- function applySharedModules(bundle, resolve) {
245
- logDebug(
246
- "SharedModules",
247
- `applySharedModules called for bundle: "${bundle}"`
248
- );
249
- logDebug(
250
- "SharedModules",
251
- `Shared modules to resolve: ${Object.keys(resolve)}`
252
- );
253
- const self = globalThis;
254
- if (self.__remote_webpack_require__?.[bundle]) {
255
- const modulePaths = Object.keys(
256
- self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
257
- );
258
- logDebug(
259
- "SharedModules",
260
- `Available module paths in __remote_webpack_require__[${bundle}]: ${modulePaths}`
261
- );
262
- for (const [key, value] of Object.entries(resolve)) {
263
- const exactIds = modulePaths.filter((p) => p === key);
264
- const ids = exactIds.length > 0 ? exactIds : modulePaths.filter((p) => p.includes(key));
265
- if (ids.length === 0) {
266
- logDebug(
267
- "SharedModules",
268
- `No matching module path found for shared module "${key}"`
269
- );
270
- }
271
- for (const id of ids) {
272
- const webpackBundle = self.__remote_webpack_require__[bundle];
273
- if (webpackBundle.m) {
274
- const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
275
- if (resolvedId !== id) {
276
- logDebug(
277
- "SharedModules",
278
- `Mapped module id: "${id}" -> "${resolvedId}"`
279
- );
280
- }
281
- webpackBundle.m[resolvedId] = (module2) => {
282
- module2.exports = value;
283
- };
284
- } else {
285
- logWarn(
286
- "SharedModules",
287
- `webpackBundle.m is not available for bundle "${bundle}" \u2014 ${DEDUPLICATION_SKIPPED}`
288
- );
289
- }
290
- }
291
- }
292
- } else {
293
- logWarn(
294
- "SharedModules",
295
- `No webpack require found for bundle "${bundle}" \u2014 ${DEDUPLICATION_SKIPPED}`
296
- );
297
- logDebug(
298
- "SharedModules",
299
- `Available bundles: ${Object.keys(self.__remote_webpack_require__ ?? {})}`
300
- );
301
- }
302
- }
303
- var DEDUPLICATION_SKIPPED;
304
- var init_apply_shared_modules = __esm({
305
- "src/config/webpack/apply-shared-modules.ts"() {
306
- "use strict";
307
- init_logger();
308
- DEDUPLICATION_SKIPPED = "shared module deduplication skipped. The remote may load its own copy of shared dependencies.";
309
- }
310
- });
311
-
312
- // src/config/webpack/next-client-pages-loader.ts
313
- function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
314
- const self = globalThis;
315
- const nextCssOriginal = document.querySelector(
316
- `[id="__next_css__DO_NOT_USE__"]:not([data-bundle="${bundle}"][data-route="${route}"])`
317
- );
318
- if (nextCssOriginal) {
319
- nextCssOriginal.parentNode?.removeChild(nextCssOriginal);
320
- }
321
- const nextCss = document.createElement("noscript");
322
- nextCss.id = "__next_css__DO_NOT_USE__";
323
- nextCss.setAttribute("data-bundle", bundle);
324
- nextCss.setAttribute("data-route", route);
325
- const nextCssEnd = document.createElement("noscript");
326
- nextCssEnd.id = "__next_css__DO_NOT_USE_END__";
327
- nextCssEnd.setAttribute("data-bundle", bundle);
328
- nextCssEnd.setAttribute("data-route", route);
329
- document.head.appendChild(nextCssEnd);
330
- document.head.appendChild(nextCss);
331
- const componentLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
332
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
333
- ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
334
- (key) => key.includes("/next/dist/client/page-loader.js")
335
- ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
336
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
337
- ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
338
- (key) => key.includes("/next/dist/client/page-loader.js")
339
- ) ?? ""] ?? -1;
340
- const appLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
341
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
342
- ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
343
- (key) => key.includes("/next/dist/client/page-loader.js")
344
- ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
345
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
346
- ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
347
- (key) => key.includes("/next/dist/client/page-loader.js")
348
- ) ?? ""] ?? -1;
349
- if (!(componentLoaderChunk && appLoaderChunk)) {
350
- throw new RemoteComponentsError(
351
- `Next.js client pages loader not found in bundle "${bundle}".`
352
- );
353
- }
354
- const __NEXT_P_ORIGINAL = self.__NEXT_P;
355
- const selfOriginal = self;
356
- delete selfOriginal.__NEXT_P;
357
- self.__remote_webpack_require__?.[bundle]?.(
358
- self.__remote_webpack_require__[bundle].type !== "turbopack" ? componentLoaderChunk : `[${bundle}] ${componentLoaderChunk}`
359
- );
360
- if (typeof appLoaderChunk === "string" || typeof appLoaderChunk === "number" && appLoaderChunk !== -1) {
361
- self.__remote_webpack_require__?.[bundle]?.(
362
- self.__remote_webpack_require__[bundle].type !== "turbopack" ? appLoaderChunk : `[${bundle}] ${appLoaderChunk}`
363
- );
364
- }
365
- if (self.__NEXT_P) {
366
- const [, componentLoader] = self.__NEXT_P[0] ?? [
367
- void 0,
368
- () => ({ default: null })
369
- ];
370
- const [, appLoader] = self.__NEXT_P[2] ?? [
371
- void 0,
372
- () => ({
373
- default: null
374
- })
375
- ];
376
- const { default: Component } = componentLoader();
377
- const { default: App } = appLoader();
378
- if (!self.__remote_next_css__) {
379
- self.__remote_next_css__ = {};
380
- }
381
- if (!self.__remote_next_css__[bundle]) {
382
- const cssRE = /\.s?css$/;
383
- Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
384
- self.__remote_webpack_require__?.[bundle]?.(id);
385
- });
386
- Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {}).filter((path) => cssRE.test(path)).forEach((path) => {
387
- const id = self.__remote_webpack_module_map__?.[bundle]?.[path];
388
- if (id) {
389
- self.__remote_webpack_require__?.[bundle]?.(id);
390
- }
391
- });
392
- const elements = [];
393
- let node = nextCss.previousSibling;
394
- while (node && node !== nextCssEnd) {
395
- elements.push(node);
396
- node.remove();
397
- node = nextCss.previousSibling;
398
- }
399
- self.__remote_next_css__[bundle] = elements;
400
- }
401
- if (styleContainer) {
402
- const elements = self.__remote_next_css__[bundle];
403
- elements.forEach((el) => {
404
- styleContainer.appendChild(el.cloneNode(true));
405
- });
406
- } else {
407
- const elements = self.__remote_next_css__[bundle];
408
- elements.forEach((el) => {
409
- document.head.appendChild(el);
410
- });
243
+ // src/runtime/namespace.ts
244
+ function getNamespace() {
245
+ const g = globalThis;
246
+ const existing = g.__remote_components__;
247
+ if (existing) {
248
+ return existing;
249
+ }
250
+ const ns = {
251
+ scopes: /* @__PURE__ */ new Map(),
252
+ chunkCache: {},
253
+ mountFns: {},
254
+ unmountFns: {},
255
+ bundleUrls: {},
256
+ moduleRegistry: {},
257
+ dispatcherRuntime: void 0,
258
+ hostSharedModules: {},
259
+ cssCache: {},
260
+ shadowRoots: {}
261
+ };
262
+ const nsRecord = ns;
263
+ for (const { global, prop } of LEGACY_ALIASES) {
264
+ const legacyValue = g[global];
265
+ if (legacyValue != null) {
266
+ nsRecord[prop] = legacyValue;
411
267
  }
412
- delete self.__NEXT_P;
413
- self.__NEXT_P = __NEXT_P_ORIGINAL;
414
- if (nextCssOriginal) {
415
- nextCssOriginal.parentNode?.appendChild(nextCssOriginal);
268
+ g[global] = ns[prop];
269
+ }
270
+ const gRecord = g;
271
+ for (const key of Object.keys(gRecord)) {
272
+ if (key.startsWith(SHADOW_ROOT_PREFIX)) {
273
+ const suffix = key.slice(SHADOW_ROOT_PREFIX.length);
274
+ ns.shadowRoots[suffix] = gRecord[key];
275
+ delete gRecord[key];
416
276
  }
417
- nextCss.remove();
418
- nextCssEnd.remove();
419
- return { Component, App };
420
277
  }
421
- return { Component: null, App: null };
278
+ g.__remote_components__ = ns;
279
+ return ns;
422
280
  }
423
- var init_next_client_pages_loader = __esm({
424
- "src/config/webpack/next-client-pages-loader.ts"() {
281
+ var SHADOW_ROOT_PREFIX, LEGACY_ALIASES;
282
+ var init_namespace = __esm({
283
+ "src/runtime/namespace.ts"() {
425
284
  "use strict";
426
- init_error();
285
+ SHADOW_ROOT_PREFIX = "__remote_components_shadowroot_";
286
+ LEGACY_ALIASES = [
287
+ { global: "__remote_component_scopes__", prop: "scopes" },
288
+ {
289
+ global: "__remote_components_turbopack_chunk_loader_promise__",
290
+ prop: "chunkCache"
291
+ },
292
+ { global: "__remote_script_entrypoint_mount__", prop: "mountFns" },
293
+ { global: "__remote_script_entrypoint_unmount__", prop: "unmountFns" },
294
+ { global: "__remote_bundle_url__", prop: "bundleUrls" },
295
+ { global: "__rc_module_registry__", prop: "moduleRegistry" },
296
+ {
297
+ global: "__remote_component_host_shared_modules__",
298
+ prop: "hostSharedModules"
299
+ },
300
+ { global: "__remote_next_css__", prop: "cssCache" }
301
+ ];
427
302
  }
428
303
  });
429
304
 
@@ -443,11 +318,7 @@ var init_patterns = __esm({
443
318
 
444
319
  // src/runtime/turbopack/remote-scope.ts
445
320
  function getRegistry() {
446
- const self = globalThis;
447
- if (!self.__remote_component_scopes__) {
448
- self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
449
- }
450
- return self.__remote_component_scopes__;
321
+ return getNamespace().scopes;
451
322
  }
452
323
  function createScope(name, url, runtime, resolveClientUrl) {
453
324
  const isCrossOrigin = url.origin !== location.origin;
@@ -465,7 +336,8 @@ function createScope(name, url, runtime, resolveClientUrl) {
465
336
  resolveClientUrl,
466
337
  moduleCache: {},
467
338
  sharedModules: {},
468
- moduleGlobal: {}
339
+ moduleGlobal: {},
340
+ turbopackModules: []
469
341
  };
470
342
  }
471
343
  function registerScope(scope) {
@@ -507,6 +379,7 @@ var init_remote_scope = __esm({
507
379
  "src/runtime/turbopack/remote-scope.ts"() {
508
380
  "use strict";
509
381
  init_constants2();
382
+ init_namespace();
510
383
  init_patterns();
511
384
  init_utils();
512
385
  init_logger();
@@ -544,9 +417,9 @@ var init_remote_image_loader = __esm({
544
417
 
545
418
  // src/host/shared/polyfill.tsx
546
419
  function sharedPolyfills(shared, resolveClientUrl) {
547
- const self = globalThis;
420
+ const hostShared = getNamespace().hostSharedModules;
548
421
  const polyfill = {
549
- "next/dist/client/components/navigation": self.__remote_component_host_shared_modules__?.["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
422
+ "next/dist/client/components/navigation": hostShared["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
550
423
  useRouter() {
551
424
  return {
552
425
  push: (routerUrl) => {
@@ -577,7 +450,7 @@ function sharedPolyfills(shared, resolveClientUrl) {
577
450
  },
578
451
  __esModule: true
579
452
  })),
580
- "next/dist/client/app-dir/link": self.__remote_component_host_shared_modules__?.["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
453
+ "next/dist/client/app-dir/link": hostShared["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
581
454
  default: ({
582
455
  scroll: _,
583
456
  replace,
@@ -627,7 +500,7 @@ function sharedPolyfills(shared, resolveClientUrl) {
627
500
  },
628
501
  __esModule: true
629
502
  })),
630
- "next/dist/client/app-dir/form": self.__remote_component_host_shared_modules__?.["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
503
+ "next/dist/client/app-dir/form": hostShared["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
631
504
  default: () => {
632
505
  throw new Error("Next.js <Form> component not implemented");
633
506
  },
@@ -638,17 +511,17 @@ function sharedPolyfills(shared, resolveClientUrl) {
638
511
  // This gives us full next/image fidelity (fill, priority, srcSet, blur
639
512
  // placeholders, error handling) while routing image optimization through the
640
513
  // remote app's /_next/image endpoint.
641
- "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({
514
+ "next/dist/shared/lib/image-loader": hostShared["next/dist/shared/lib/image-loader"] ?? shared?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
642
515
  default: createRemoteImageLoader(bundle, resolveClientUrl),
643
516
  __esModule: true
644
517
  })),
645
- "next/dist/client/script": self.__remote_component_host_shared_modules__?.["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
518
+ "next/dist/client/script": hostShared["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
646
519
  // TODO: implement <Script> component for non-Next.js host applications
647
520
  // do not throw an error for now
648
521
  default: () => null,
649
522
  __esModule: true
650
523
  })),
651
- "next/router": self.__remote_component_host_shared_modules__?.["next/router"] ?? shared?.["next/router"] ?? (() => (
524
+ "next/router": hostShared["next/router"] ?? shared?.["next/router"] ?? (() => (
652
525
  // TODO: incomplete implementation
653
526
  Promise.resolve({
654
527
  useRouter() {
@@ -688,171 +561,296 @@ var init_polyfill = __esm({
688
561
  "src/host/shared/polyfill.tsx"() {
689
562
  "use strict";
690
563
  init_remote_image_loader();
564
+ init_namespace();
691
565
  init_logger();
692
566
  import_jsx_runtime = require("react/jsx-runtime");
693
567
  }
694
568
  });
695
569
 
696
- // src/runtime/loaders/script-loader.ts
697
- async function loadScripts(scripts, resolveClientUrl) {
698
- await Promise.all(
699
- scripts.map((script) => {
700
- return new Promise((resolve, reject) => {
701
- const newSrc = new URL(
702
- // remove the remote component bundle name identifier from the script src
703
- script.src.replace(NEXT_BUNDLE_PATH_RE, "/_next/"),
704
- location.origin
705
- ).href;
706
- const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;
707
- const alreadyLoaded = Array.from(
708
- document.querySelectorAll("script[src]")
709
- ).some((s) => s.src === resolvedSrc);
710
- if (alreadyLoaded) {
711
- resolve();
712
- return;
570
+ // src/host/shared/shared-module-resolver.ts
571
+ function buildCoreShared(userShared) {
572
+ return {
573
+ react: async () => (await import("react")).default,
574
+ "react-dom": async () => (await import("react-dom")).default,
575
+ "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
576
+ "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
577
+ "react-dom/client": async () => (await import("react-dom/client")).default,
578
+ ...userShared
579
+ };
580
+ }
581
+ function buildHostShared(userShared, resolveClientUrl, options) {
582
+ const self = globalThis;
583
+ const result = {
584
+ ...sharedPolyfills(userShared, resolveClientUrl),
585
+ ...self.__remote_component_host_shared_modules__,
586
+ ...userShared
587
+ };
588
+ if (options?.includeRemoteComponentShared) {
589
+ Object.assign(result, self.__remote_component_shared__);
590
+ }
591
+ return result;
592
+ }
593
+ async function buildWebpackResolve(hostShared, remoteShared, bundle, reactModules, callerTag = "SharedModuleResolver") {
594
+ const resolve = {
595
+ ...reactModules,
596
+ ...Object.entries(remoteShared).reduce(
597
+ (acc, [key, value]) => {
598
+ if (typeof hostShared[value] !== "undefined") {
599
+ acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
600
+ } else {
601
+ logDebug(
602
+ callerTag,
603
+ `Remote requests "${value}" but host doesn't provide it`
604
+ );
713
605
  }
714
- const newScript = document.createElement("script");
715
- newScript.onload = () => resolve();
716
- newScript.onerror = () => {
717
- const isProxied = isProxiedUrl(resolvedSrc);
718
- if (isProxied) {
719
- reject(failedProxiedAssetError("script", newSrc, resolvedSrc));
720
- } else {
721
- warnCrossOriginFetchError("ScriptLoader", newSrc);
722
- reject(
723
- new RemoteComponentsError(
724
- `Failed to load <script src="${newSrc}"> for Remote Component. Check the URL is correct.`
725
- )
726
- );
727
- }
728
- };
729
- newScript.src = resolvedSrc;
730
- newScript.async = true;
731
- document.head.appendChild(newScript);
732
- });
606
+ return acc;
607
+ },
608
+ {}
609
+ )
610
+ };
611
+ await Promise.all(
612
+ Object.entries(resolve).map(async ([key, value]) => {
613
+ if (typeof value === "function") {
614
+ resolve[key] = await value(bundle);
615
+ }
616
+ return Promise.resolve(value);
733
617
  })
734
618
  );
619
+ return resolve;
735
620
  }
736
- var init_script_loader = __esm({
737
- "src/runtime/loaders/script-loader.ts"() {
621
+ var CORE_REACT_PATH_MAP, VENDOR_SHARED;
622
+ var init_shared_module_resolver = __esm({
623
+ "src/host/shared/shared-module-resolver.ts"() {
738
624
  "use strict";
739
- init_patterns();
740
- init_protected_rc_fallback();
741
- init_error();
625
+ init_polyfill();
742
626
  init_logger();
627
+ CORE_REACT_PATH_MAP = {
628
+ react: "/react/index.js",
629
+ "react/jsx-dev-runtime": "/react/jsx-dev-runtime.js",
630
+ "react/jsx-runtime": "/react/jsx-runtime.js",
631
+ "react-dom": "/react-dom/index.js",
632
+ "react-dom/client": "/react-dom/client.js"
633
+ };
634
+ VENDOR_SHARED = Object.fromEntries(
635
+ Object.entries(CORE_REACT_PATH_MAP).filter(([key]) => key !== "react-dom/client").map(([key, path]) => [key, `'${path}'`])
636
+ );
743
637
  }
744
638
  });
745
639
 
746
- // src/host/html/runtime/webpack.ts
747
- var webpack_exports = {};
748
- __export(webpack_exports, {
749
- webpackRuntime: () => webpackRuntime
750
- });
751
- async function webpackRuntime(bundle, shared, remoteShared, resolveClientUrl) {
640
+ // src/config/webpack/apply-shared-modules.ts
641
+ function applySharedModules(bundle, resolve) {
642
+ logDebug(
643
+ "SharedModules",
644
+ `applySharedModules called for bundle: "${bundle}"`
645
+ );
646
+ logDebug(
647
+ "SharedModules",
648
+ `Shared modules to resolve: ${Object.keys(resolve)}`
649
+ );
752
650
  const self = globalThis;
753
- if (!self.__DISABLE_WEBPACK_EXEC__) {
754
- self.__DISABLE_WEBPACK_EXEC__ = {};
755
- }
756
- self.__DISABLE_WEBPACK_EXEC__[bundle] = true;
757
- if (typeof self.__webpack_require__ !== "function" && self.__webpack_require_type__ !== "turbopack") {
758
- self.__webpack_require__ = (remoteId) => {
759
- const re = /\[(?<bundle>[^\]]+)\] (?<id>.*)/;
760
- const match = re.exec(remoteId);
761
- const remoteBundle = match?.groups?.bundle;
762
- const id = match?.groups?.id;
763
- if (!(id && remoteBundle)) {
764
- throw new RemoteComponentsError(
765
- `Remote Component module "${remoteId}" not found. Did you forget to wrap the Next.js config with \`withRemoteComponentsConfig\` on both host and remote?`
766
- );
767
- }
768
- if (typeof self.__remote_webpack_require__?.[remoteBundle] !== "function") {
769
- throw new RemoteComponentsError(
770
- `Remote Components are not available in "${remoteBundle}". Did you forget to wrap the Next.js config with \`withRemoteComponentsConfig\` on both host and remote?`
651
+ const scope = getScope(bundle);
652
+ const webpackBundle = scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];
653
+ if (webpackBundle) {
654
+ const modulePaths = Object.keys(
655
+ self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {}
656
+ );
657
+ logDebug(
658
+ "SharedModules",
659
+ `Available module paths for bundle "${bundle}": ${modulePaths}`
660
+ );
661
+ for (const [key, value] of Object.entries(resolve)) {
662
+ const exactIds = modulePaths.filter((p) => p === key);
663
+ const ids = exactIds.length > 0 ? exactIds : modulePaths.filter((p) => p.includes(key));
664
+ if (ids.length === 0) {
665
+ logDebug(
666
+ "SharedModules",
667
+ `No matching module path found for shared module "${key}"`
771
668
  );
772
669
  }
773
- return self.__remote_webpack_require__[remoteBundle](id);
774
- };
775
- self.__webpack_chunk_load__ = () => {
776
- return Promise.resolve([]);
777
- };
778
- }
779
- const {
780
- default: { createFromReadableStream }
781
- } = await import("react-server-dom-webpack/client.browser");
782
- async function preloadScripts(scripts, url, remoteBundle, _) {
783
- const scriptSrcs = scripts.flatMap((script) => {
784
- const scriptSrc = script.getAttribute("src") || script.getAttribute("data-src");
785
- script.parentElement?.removeChild(script);
786
- if (!scriptSrc)
787
- return [];
788
- return [
789
- {
790
- src: new URL(scriptSrc.replace(NEXT_BUNDLE_PATH_RE, "/_next/"), url).href
791
- }
792
- ];
793
- });
794
- await loadScripts(scriptSrcs, resolveClientUrl);
795
- const hostShared = {
796
- ...sharedPolyfills(shared, resolveClientUrl),
797
- ...self.__remote_component_host_shared_modules__,
798
- ...shared
799
- };
800
- const resolve = {
801
- "/react/index.js": (await import("react")).default,
802
- "/react/jsx-dev-runtime.js": (await import("react/jsx-dev-runtime")).default,
803
- "/react/jsx-runtime.js": (await import("react/jsx-runtime")).default,
804
- "/react-dom/index.js": (await import("react-dom")).default,
805
- "/react-dom/client.js": (await import("react-dom/client")).default,
806
- ...Object.entries(remoteShared ?? {}).reduce(
807
- (acc, [key, value]) => {
808
- if (typeof hostShared[value] !== "undefined") {
809
- acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
670
+ for (const id of ids) {
671
+ if (webpackBundle.m) {
672
+ const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
673
+ if (resolvedId !== id) {
674
+ logDebug(
675
+ "SharedModules",
676
+ `Mapped module id: "${id}" -> "${resolvedId}"`
677
+ );
810
678
  }
811
- return acc;
812
- },
813
- {}
814
- )
815
- };
816
- await Promise.all(
817
- Object.entries(resolve).map(async ([key, value]) => {
818
- if (typeof value === "function") {
819
- resolve[key] = await value(remoteBundle);
679
+ webpackBundle.m[resolvedId] = (module2) => {
680
+ module2.exports = value;
681
+ };
682
+ } else {
683
+ logWarn(
684
+ "SharedModules",
685
+ `webpackBundle.m is not available for bundle "${bundle}" \u2014 ${DEDUPLICATION_SKIPPED}`
686
+ );
820
687
  }
821
- return Promise.resolve(value);
822
- })
688
+ }
689
+ }
690
+ } else {
691
+ logWarn(
692
+ "SharedModules",
693
+ `No webpack require found for bundle "${bundle}" \u2014 ${DEDUPLICATION_SKIPPED}`
694
+ );
695
+ logDebug(
696
+ "SharedModules",
697
+ `Available bundles: ${Object.keys(self.__remote_webpack_require__ ?? {})}`
823
698
  );
824
- applySharedModules(remoteBundle, resolve);
825
699
  }
826
- return {
827
- self,
828
- createFromReadableStream,
829
- applySharedModules,
830
- nextClientPagesLoader,
831
- preloadScripts
832
- };
833
700
  }
834
- var init_webpack = __esm({
835
- "src/host/html/runtime/webpack.ts"() {
701
+ var DEDUPLICATION_SKIPPED;
702
+ var init_apply_shared_modules = __esm({
703
+ "src/config/webpack/apply-shared-modules.ts"() {
836
704
  "use strict";
837
- init_apply_shared_modules();
838
- init_next_client_pages_loader();
839
- init_polyfill();
840
- init_script_loader();
841
- init_patterns();
705
+ init_remote_scope();
706
+ init_logger();
707
+ DEDUPLICATION_SKIPPED = "shared module deduplication skipped. The remote may load its own copy of shared dependencies.";
708
+ }
709
+ });
710
+
711
+ // src/config/webpack/next-client-pages-loader.ts
712
+ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
713
+ const self = globalThis;
714
+ const nextCssOriginal = document.querySelector(
715
+ `[id="__next_css__DO_NOT_USE__"]:not([data-bundle="${bundle}"][data-route="${route}"])`
716
+ );
717
+ if (nextCssOriginal) {
718
+ nextCssOriginal.parentNode?.removeChild(nextCssOriginal);
719
+ }
720
+ const nextCss = document.createElement("noscript");
721
+ nextCss.id = "__next_css__DO_NOT_USE__";
722
+ nextCss.setAttribute("data-bundle", bundle);
723
+ nextCss.setAttribute("data-route", route);
724
+ const nextCssEnd = document.createElement("noscript");
725
+ nextCssEnd.id = "__next_css__DO_NOT_USE_END__";
726
+ nextCssEnd.setAttribute("data-bundle", bundle);
727
+ nextCssEnd.setAttribute("data-route", route);
728
+ document.head.appendChild(nextCssEnd);
729
+ document.head.appendChild(nextCss);
730
+ const componentLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
731
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
732
+ ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
733
+ (key) => key.includes("/next/dist/client/page-loader.js")
734
+ ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
735
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
736
+ ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
737
+ (key) => key.includes("/next/dist/client/page-loader.js")
738
+ ) ?? ""] ?? -1;
739
+ const appLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
740
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
741
+ ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
742
+ (key) => key.includes("/next/dist/client/page-loader.js")
743
+ ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
744
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
745
+ ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
746
+ (key) => key.includes("/next/dist/client/page-loader.js")
747
+ ) ?? ""] ?? -1;
748
+ if (!(componentLoaderChunk && appLoaderChunk)) {
749
+ throw new RemoteComponentsError(
750
+ `Next.js client pages loader not found in bundle "${bundle}".`
751
+ );
752
+ }
753
+ const __NEXT_P_ORIGINAL = self.__NEXT_P;
754
+ const selfOriginal = self;
755
+ delete selfOriginal.__NEXT_P;
756
+ self.__remote_webpack_require__?.[bundle]?.(
757
+ self.__remote_webpack_require__[bundle].type !== "turbopack" ? componentLoaderChunk : `[${bundle}] ${componentLoaderChunk}`
758
+ );
759
+ if (typeof appLoaderChunk === "string" || typeof appLoaderChunk === "number" && appLoaderChunk !== -1) {
760
+ self.__remote_webpack_require__?.[bundle]?.(
761
+ self.__remote_webpack_require__[bundle].type !== "turbopack" ? appLoaderChunk : `[${bundle}] ${appLoaderChunk}`
762
+ );
763
+ }
764
+ if (self.__NEXT_P) {
765
+ const [, componentLoader] = self.__NEXT_P[0] ?? [
766
+ void 0,
767
+ () => ({ default: null })
768
+ ];
769
+ const [, appLoader] = self.__NEXT_P[2] ?? [
770
+ void 0,
771
+ () => ({
772
+ default: null
773
+ })
774
+ ];
775
+ const { default: Component } = componentLoader();
776
+ const { default: App } = appLoader();
777
+ const cssCache = getNamespace().cssCache;
778
+ if (!cssCache[bundle]) {
779
+ const cssRE = /\.s?css$/;
780
+ Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
781
+ self.__remote_webpack_require__?.[bundle]?.(id);
782
+ });
783
+ Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {}).filter((path) => cssRE.test(path)).forEach((path) => {
784
+ const id = self.__remote_webpack_module_map__?.[bundle]?.[path];
785
+ if (id) {
786
+ self.__remote_webpack_require__?.[bundle]?.(id);
787
+ }
788
+ });
789
+ const elements = [];
790
+ let node = nextCss.previousSibling;
791
+ while (node && node !== nextCssEnd) {
792
+ elements.push(node);
793
+ node.remove();
794
+ node = nextCss.previousSibling;
795
+ }
796
+ cssCache[bundle] = elements;
797
+ }
798
+ if (styleContainer) {
799
+ const elements = cssCache[bundle];
800
+ elements.forEach((el) => {
801
+ styleContainer.appendChild(el.cloneNode(true));
802
+ });
803
+ } else {
804
+ const elements = cssCache[bundle];
805
+ elements.forEach((el) => {
806
+ document.head.appendChild(el);
807
+ });
808
+ }
809
+ delete self.__NEXT_P;
810
+ self.__NEXT_P = __NEXT_P_ORIGINAL;
811
+ if (nextCssOriginal) {
812
+ nextCssOriginal.parentNode?.appendChild(nextCssOriginal);
813
+ }
814
+ nextCss.remove();
815
+ nextCssEnd.remove();
816
+ return { Component, App };
817
+ }
818
+ return { Component: null, App: null };
819
+ }
820
+ var init_next_client_pages_loader = __esm({
821
+ "src/config/webpack/next-client-pages-loader.ts"() {
822
+ "use strict";
823
+ init_namespace();
842
824
  init_error();
843
825
  }
844
826
  });
845
827
 
846
828
  // src/runtime/turbopack/patterns.ts
847
- var REMOTE_SHARED_MARKER_RE, REMOTE_SHARED_ASSIGNMENT_RE, ASYNC_MODULE_LOADER_RE, ASYNC_MODULE_RESOLVE_RE, ASYNC_MODULE_ALL_RE, TURBOPACK_GLOBAL_RE;
829
+ function stripQuotes(value) {
830
+ if (value.startsWith('"') && value.endsWith('"')) {
831
+ return value.slice(1, -1);
832
+ }
833
+ return value;
834
+ }
835
+ function extractGroup(re, input, group) {
836
+ const raw = re.exec(input)?.groups?.[group];
837
+ return raw ? stripQuotes(raw) : void 0;
838
+ }
839
+ var MODULE_ID_PATTERN, REMOTE_SHARED_MARKER_RE, REMOTE_SHARED_ASSIGNMENT_RE, ASYNC_MODULE_LOADER_RE, ASYNC_MODULE_CALLBACK_RE, TURBOPACK_GLOBAL_RE;
848
840
  var init_patterns2 = __esm({
849
841
  "src/runtime/turbopack/patterns.ts"() {
850
842
  "use strict";
843
+ MODULE_ID_PATTERN = '"[^"]+"|[0-9]+';
851
844
  REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
852
- REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
853
- ASYNC_MODULE_LOADER_RE = /(?:__turbopack_context__|e)\.A\((?<asyncSharedModuleId>[0-9]+)\)/;
854
- ASYNC_MODULE_RESOLVE_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<inner>parentImport|e)=>Promise\.resolve\(\)\.then\(\(\)=>\k<inner>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
855
- 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]+)\)\)\)\}/;
845
+ REMOTE_SHARED_ASSIGNMENT_RE = new RegExp(
846
+ `\\.TURBOPACK_REMOTE_SHARED\\s*=\\s*await (?:__turbopack_context__|[a-z])\\.A\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
847
+ );
848
+ ASYNC_MODULE_LOADER_RE = new RegExp(
849
+ `(?:__turbopack_context__|[a-z])\\.A\\((?<asyncSharedModuleId>${MODULE_ID_PATTERN})\\)`
850
+ );
851
+ ASYNC_MODULE_CALLBACK_RE = new RegExp(
852
+ `(?:parentImport|[a-z])\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
853
+ );
856
854
  TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
857
855
  }
858
856
  });
@@ -864,6 +862,7 @@ function loadChunkWithScope(scope, chunkId) {
864
862
  `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
865
863
  );
866
864
  const self = globalThis;
865
+ const ns = getNamespace();
867
866
  const { bundle, path, prefix } = parseRemoteId(chunkId);
868
867
  const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
869
868
  if (remoteRuntime === RUNTIME_WEBPACK) {
@@ -874,35 +873,31 @@ function loadChunkWithScope(scope, chunkId) {
874
873
  if (url.endsWith(".css")) {
875
874
  return;
876
875
  }
877
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
878
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
879
- }
880
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
881
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
876
+ if (ns.chunkCache[url]) {
877
+ logDebug("ChunkLoader", `Cache hit for "${chunkId}" (url="${url}")`);
878
+ return ns.chunkCache[url];
882
879
  }
883
880
  const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
884
881
  if (resolvedUrl !== url) {
885
882
  logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
886
883
  }
887
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
888
- (resolve, reject) => {
889
- fetch(resolvedUrl).then((res) => res.text()).then((code) => {
890
- const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
891
- if (hasTurbopack) {
892
- return handleTurbopackChunk(code, scope, url);
893
- }
894
- }).then(resolve).catch((error) => {
895
- const isProxied = isProxiedUrl(resolvedUrl);
896
- if (isProxied) {
897
- reject(failedProxiedAssetError("chunk", url, resolvedUrl));
898
- } else {
899
- warnCrossOriginFetchError("ChunkLoader", url);
900
- reject(error);
901
- }
902
- });
903
- }
904
- );
905
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
884
+ ns.chunkCache[url] = new Promise((resolve, reject) => {
885
+ fetch(resolvedUrl).then((res) => res.text()).then((code) => {
886
+ const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
887
+ if (hasTurbopack) {
888
+ return handleTurbopackChunk(code, scope, url);
889
+ }
890
+ }).then(resolve).catch((error) => {
891
+ const isProxied = isProxiedUrl(resolvedUrl);
892
+ if (isProxied) {
893
+ reject(failedProxiedAssetError("chunk", url, resolvedUrl));
894
+ } else {
895
+ warnCrossOriginFetchError("ChunkLoader", url);
896
+ reject(error);
897
+ }
898
+ });
899
+ });
900
+ return ns.chunkCache[url];
906
901
  }
907
902
  function createChunkDispatcher() {
908
903
  return function __chunk_dispatcher__(chunkId, scriptBundle) {
@@ -951,19 +946,39 @@ async function handleTurbopackChunk(code, scope, url) {
951
946
  `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
952
947
  );
953
948
  if (!self[`TURBOPACK_${globalKey}`]) {
954
- const chunkData = [];
955
- const turbopackObject = {
956
- push: (item) => {
957
- if (Array.isArray(item)) {
958
- chunkData.push(item);
959
- } else {
960
- chunkData.push([item]);
949
+ const wrapPush = (target) => {
950
+ const originalPush = target.push;
951
+ if (typeof originalPush !== "function")
952
+ return target;
953
+ target.push = (...items) => {
954
+ for (const item of items) {
955
+ if (Array.isArray(item)) {
956
+ for (const entry of item) {
957
+ scope.turbopackModules.push(entry);
958
+ }
959
+ } else {
960
+ scope.turbopackModules.push(item);
961
+ }
961
962
  }
962
- return chunkData.length;
963
- },
964
- __chunks__: chunkData
963
+ return originalPush.apply(target, items);
964
+ };
965
+ return target;
965
966
  };
966
- self[`TURBOPACK_${globalKey}`] = turbopackObject;
967
+ const globalProp = `TURBOPACK_${globalKey}`;
968
+ let currentValue = wrapPush([]);
969
+ Object.defineProperty(self, globalProp, {
970
+ get() {
971
+ return currentValue;
972
+ },
973
+ set(newValue) {
974
+ if (newValue && typeof newValue === "object") {
975
+ wrapPush(newValue);
976
+ }
977
+ currentValue = newValue;
978
+ },
979
+ configurable: true,
980
+ enumerable: true
981
+ });
967
982
  }
968
983
  await new Promise((scriptResolve, scriptReject) => {
969
984
  const blob = new Blob([transformedCode], {
@@ -1015,6 +1030,7 @@ var init_chunk_loader = __esm({
1015
1030
  "src/runtime/turbopack/chunk-loader.ts"() {
1016
1031
  "use strict";
1017
1032
  init_constants2();
1033
+ init_namespace();
1018
1034
  init_patterns();
1019
1035
  init_protected_rc_fallback();
1020
1036
  init_error();
@@ -1026,13 +1042,13 @@ var init_chunk_loader = __esm({
1026
1042
 
1027
1043
  // src/runtime/turbopack/shared-modules.ts
1028
1044
  function getTurbopackModules(scope) {
1045
+ if (scope.turbopackModules.length > 0) {
1046
+ return scope.turbopackModules;
1047
+ }
1029
1048
  const self = globalThis;
1030
1049
  const raw = self[`TURBOPACK_${scope.globalKey}`];
1031
1050
  if (!raw)
1032
1051
  return void 0;
1033
- if (typeof raw === "object" && "__chunks__" in raw) {
1034
- return raw.__chunks__.flat();
1035
- }
1036
1052
  if (Array.isArray(raw)) {
1037
1053
  return raw.flat();
1038
1054
  }
@@ -1056,7 +1072,11 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1056
1072
  if (sharedModuleInitializerIndex > 0) {
1057
1073
  const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1058
1074
  const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1059
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1075
+ const sharedModuleId = extractGroup(
1076
+ REMOTE_SHARED_ASSIGNMENT_RE,
1077
+ sharedModuleInitializerCode,
1078
+ "sharedModuleId"
1079
+ );
1060
1080
  if (sharedModuleId) {
1061
1081
  const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1062
1082
  scope,
@@ -1114,20 +1134,22 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1114
1134
  }
1115
1135
  function extractSharedModuleIds(shared, scope) {
1116
1136
  return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1117
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1137
+ const asyncSharedModuleId = extractGroup(
1138
+ ASYNC_MODULE_LOADER_RE,
1139
+ value.toString(),
1140
+ "asyncSharedModuleId"
1141
+ );
1118
1142
  if (asyncSharedModuleId) {
1119
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1120
- let asyncSharedModule;
1121
- const turbopackModules = getTurbopackModules(scope) ?? [];
1122
- const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1123
- asyncSharedModuleIdNumber
1143
+ const asyncSharedModule = findModuleInit(
1144
+ getTurbopackModules(scope),
1145
+ asyncSharedModuleId
1124
1146
  );
1125
- if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1126
- asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1127
- }
1128
1147
  if (asyncSharedModule) {
1129
- const asyncSharedModuleCode = asyncSharedModule.toString();
1130
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1148
+ const sharedModuleId = extractGroup(
1149
+ ASYNC_MODULE_CALLBACK_RE,
1150
+ asyncSharedModule.toString(),
1151
+ "sharedModuleId"
1152
+ );
1131
1153
  acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1132
1154
  "__remote_shared_module_",
1133
1155
  ""
@@ -1229,9 +1251,17 @@ function findModuleInit(modules, moduleId) {
1229
1251
  if (idx >= 0) {
1230
1252
  return flat.slice(idx + 1).find((e) => typeof e === "function");
1231
1253
  }
1232
- return flat.find(
1233
- (e) => Boolean(e && typeof e === "object" && moduleId in e)
1234
- )?.[moduleId];
1254
+ for (const entry of flat) {
1255
+ if (!entry || typeof entry !== "object")
1256
+ continue;
1257
+ const obj = entry;
1258
+ if (moduleId in obj)
1259
+ return obj[moduleId];
1260
+ const prefixKey = Object.keys(obj).find((k) => k.startsWith(moduleId));
1261
+ if (prefixKey)
1262
+ return obj[prefixKey];
1263
+ }
1264
+ return void 0;
1235
1265
  }
1236
1266
  function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1237
1267
  const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
@@ -1310,7 +1340,10 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1310
1340
  }
1311
1341
  if (typeof mod !== "object" || mod === null) {
1312
1342
  mod = { default: mod };
1313
- } else if (!("default" in mod) && mod.toString() !== "[object Module]") {
1343
+ } else if (!("default" in mod) && // ES module namespace objects have a null prototype, so calling
1344
+ // mod.toString() directly throws. Use Object.prototype.toString
1345
+ // to safely detect them.
1346
+ Object.prototype.toString.call(mod) !== "[object Module]") {
1314
1347
  try {
1315
1348
  mod.default = mod;
1316
1349
  } catch {
@@ -1383,21 +1416,38 @@ var init_module = __esm({
1383
1416
  }
1384
1417
  });
1385
1418
 
1386
- // src/runtime/turbopack/webpack-runtime.ts
1387
- async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1419
+ // src/runtime/turbopack/remote-scope-setup.ts
1420
+ async function setupRemoteScope(runtime, scripts = [], url = new URL(location.href), bundle, resolveClientUrl) {
1388
1421
  const self = globalThis;
1422
+ const ns = getNamespace();
1389
1423
  const bundleName = bundle ?? "default";
1424
+ const existingScope = getScope(bundleName);
1425
+ if (existingScope && existingScope.url.origin === url.origin) {
1426
+ logDebug(
1427
+ "WebpackRuntime",
1428
+ `Reusing scope "${existingScope.scopedName}" (turbopackModules=${existingScope.turbopackModules.length})`
1429
+ );
1430
+ existingScope.resolveClientUrl = resolveClientUrl;
1431
+ if (runtime === RUNTIME_TURBOPACK) {
1432
+ await Promise.allSettled(
1433
+ scripts.map(
1434
+ (script) => script.src ? loadChunkWithScope(existingScope, script.src) : Promise.resolve(void 0)
1435
+ )
1436
+ );
1437
+ }
1438
+ return existingScope;
1439
+ }
1390
1440
  const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1391
1441
  registerScope(scope);
1392
- if (!self.__remote_bundle_url__) {
1393
- self.__remote_bundle_url__ = {};
1442
+ if (runtime === RUNTIME_WEBPACK && self.__remote_webpack_require__?.[bundleName]) {
1443
+ scope.webpackRequire = self.__remote_webpack_require__[bundleName];
1394
1444
  }
1395
- self.__remote_bundle_url__[bundleName] = url;
1445
+ ns.bundleUrls[bundleName] = url;
1396
1446
  if (scope.scopedName !== bundleName) {
1397
- self.__remote_bundle_url__[scope.scopedName] = url;
1447
+ ns.bundleUrls[scope.scopedName] = url;
1398
1448
  }
1399
1449
  self.__webpack_get_script_filename__ = () => null;
1400
- const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1450
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || ns.dispatcherRuntime !== "turbopack";
1401
1451
  if (willCreateDispatchers) {
1402
1452
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1403
1453
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
@@ -1405,6 +1455,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1405
1455
  }
1406
1456
  self.__webpack_chunk_load__ = createChunkDispatcher();
1407
1457
  self.__webpack_require__ = createModuleDispatcher(runtime);
1458
+ ns.dispatcherRuntime = runtime;
1408
1459
  self.__webpack_require_type__ = runtime;
1409
1460
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1410
1461
  self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
@@ -1432,15 +1483,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1432
1483
  }
1433
1484
  }
1434
1485
  }
1435
- const coreShared = {
1436
- react: async () => (await import("react")).default,
1437
- "react-dom": async () => (await import("react-dom")).default,
1438
- "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
1439
- "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
1440
- "react-dom/client": async () => (await import("react-dom/client")).default,
1441
- ...shared
1442
- };
1443
- await initializeSharedModules(scope, coreShared, remoteShared);
1486
+ return scope;
1444
1487
  }
1445
1488
  function createModuleDispatcher(runtime) {
1446
1489
  return (id) => {
@@ -1457,6 +1500,9 @@ function createModuleDispatcher(runtime) {
1457
1500
  );
1458
1501
  try {
1459
1502
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1503
+ const scope2 = getScope(bundle);
1504
+ if (scope2?.webpackRequire)
1505
+ return scope2.webpackRequire(moduleId);
1460
1506
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1461
1507
  }
1462
1508
  const scope = getScope(bundleName);
@@ -1494,73 +1540,67 @@ function createModuleDispatcher(runtime) {
1494
1540
  }
1495
1541
  };
1496
1542
  }
1497
- var init_webpack_runtime = __esm({
1498
- "src/runtime/turbopack/webpack-runtime.ts"() {
1543
+ var init_remote_scope_setup = __esm({
1544
+ "src/runtime/turbopack/remote-scope-setup.ts"() {
1499
1545
  "use strict";
1500
1546
  init_constants2();
1547
+ init_namespace();
1501
1548
  init_patterns();
1502
1549
  init_error();
1503
1550
  init_logger();
1504
1551
  init_chunk_loader();
1505
1552
  init_module();
1506
1553
  init_remote_scope();
1507
- init_shared_modules();
1508
1554
  }
1509
1555
  });
1510
1556
 
1511
- // src/host/html/runtime/turbopack.ts
1512
- var turbopack_exports = {};
1513
- __export(turbopack_exports, {
1514
- turbopackRuntime: () => turbopackRuntime
1515
- });
1516
- async function turbopackRuntime(url, bundle, shared, remoteShared, resolveClientUrl) {
1517
- const self = globalThis;
1518
- const hostShared = {
1519
- ...sharedPolyfills(shared, resolveClientUrl),
1520
- ...self.__remote_component_host_shared_modules__,
1521
- ...shared,
1522
- ...self.__remote_component_shared__
1523
- };
1524
- await setupWebpackRuntime(
1525
- "turbopack",
1526
- [],
1527
- url,
1528
- bundle,
1529
- hostShared,
1530
- remoteShared,
1531
- resolveClientUrl
1532
- );
1533
- const {
1534
- default: { createFromReadableStream }
1535
- } = await import("react-server-dom-webpack/client.browser");
1536
- function preloadScripts(scripts, __) {
1537
- return setupWebpackRuntime(
1538
- "turbopack",
1539
- scripts.map((script) => ({
1540
- src: script.getAttribute("src") || script.getAttribute("data-src") || script.src
1541
- })),
1542
- url,
1543
- bundle,
1544
- hostShared,
1545
- remoteShared,
1546
- resolveClientUrl
1547
- );
1548
- }
1549
- return {
1550
- self,
1551
- createFromReadableStream,
1552
- applySharedModules,
1553
- nextClientPagesLoader,
1554
- preloadScripts
1555
- };
1557
+ // src/runtime/loaders/script-loader.ts
1558
+ async function loadScripts(scripts, resolveClientUrl) {
1559
+ await Promise.all(
1560
+ scripts.map((script) => {
1561
+ return new Promise((resolve, reject) => {
1562
+ const newSrc = new URL(
1563
+ // remove the remote component bundle name identifier from the script src
1564
+ script.src.replace(NEXT_BUNDLE_PATH_RE, "/_next/"),
1565
+ location.origin
1566
+ ).href;
1567
+ const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;
1568
+ const alreadyLoaded = Array.from(
1569
+ document.querySelectorAll("script[src]")
1570
+ ).some((s) => s.src === resolvedSrc);
1571
+ if (alreadyLoaded) {
1572
+ resolve();
1573
+ return;
1574
+ }
1575
+ const newScript = document.createElement("script");
1576
+ newScript.onload = () => resolve();
1577
+ newScript.onerror = () => {
1578
+ const isProxied = isProxiedUrl(resolvedSrc);
1579
+ if (isProxied) {
1580
+ reject(failedProxiedAssetError("script", newSrc, resolvedSrc));
1581
+ } else {
1582
+ warnCrossOriginFetchError("ScriptLoader", newSrc);
1583
+ reject(
1584
+ new RemoteComponentsError(
1585
+ `Failed to load <script src="${newSrc}"> for Remote Component. Check the URL is correct.`
1586
+ )
1587
+ );
1588
+ }
1589
+ };
1590
+ newScript.src = resolvedSrc;
1591
+ newScript.async = true;
1592
+ document.head.appendChild(newScript);
1593
+ });
1594
+ })
1595
+ );
1556
1596
  }
1557
- var init_turbopack = __esm({
1558
- "src/host/html/runtime/turbopack.ts"() {
1597
+ var init_script_loader = __esm({
1598
+ "src/runtime/loaders/script-loader.ts"() {
1559
1599
  "use strict";
1560
- init_apply_shared_modules();
1561
- init_next_client_pages_loader();
1562
- init_polyfill();
1563
- init_webpack_runtime();
1600
+ init_patterns();
1601
+ init_protected_rc_fallback();
1602
+ init_error();
1603
+ init_logger();
1564
1604
  }
1565
1605
  });
1566
1606
 
@@ -1607,10 +1647,9 @@ async function importViaCallback(absoluteSrc, resolveClientUrl) {
1607
1647
  URL.revokeObjectURL(moduleBlobUrl);
1608
1648
  URL.revokeObjectURL(wrapperBlobUrl);
1609
1649
  }
1610
- const registry = globalThis.__rc_module_registry__;
1611
- const mod = registry?.[absoluteSrc] ?? {};
1612
- if (registry)
1613
- delete registry[absoluteSrc];
1650
+ const registry = getNamespace().moduleRegistry;
1651
+ const mod = registry[absoluteSrc] ?? {};
1652
+ delete registry[absoluteSrc];
1614
1653
  return mod;
1615
1654
  }
1616
1655
  async function importDirectly(absoluteSrc) {
@@ -1640,12 +1679,12 @@ function resolveScriptSrc(script, url) {
1640
1679
  return rawSrc;
1641
1680
  }
1642
1681
  async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1643
- const self = globalThis;
1644
- if (self.__remote_script_entrypoint_mount__?.[url.href]) {
1645
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
1682
+ const ns = getNamespace();
1683
+ if (ns.mountFns[url.href]) {
1684
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1646
1685
  }
1647
- if (self.__remote_script_entrypoint_unmount__?.[url.href]) {
1648
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
1686
+ if (ns.unmountFns[url.href]) {
1687
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1649
1688
  }
1650
1689
  const mountUnmountSets = await Promise.all(
1651
1690
  scripts.map(async (script) => {
@@ -1657,25 +1696,19 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1657
1696
  URL.revokeObjectURL(src);
1658
1697
  }
1659
1698
  if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
1660
- if (!self.__remote_script_entrypoint_mount__) {
1661
- self.__remote_script_entrypoint_mount__ = {};
1699
+ if (!ns.mountFns[url.href]) {
1700
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1662
1701
  }
1663
- if (!self.__remote_script_entrypoint_mount__[url.href]) {
1664
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
1665
- }
1666
- self.__remote_script_entrypoint_mount__[url.href]?.add(
1702
+ ns.mountFns[url.href]?.add(
1667
1703
  mod.mount || mod.default?.mount || (() => {
1668
1704
  })
1669
1705
  );
1670
1706
  }
1671
1707
  if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
1672
- if (!self.__remote_script_entrypoint_unmount__) {
1673
- self.__remote_script_entrypoint_unmount__ = {};
1674
- }
1675
- if (!self.__remote_script_entrypoint_unmount__[url.href]) {
1676
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
1708
+ if (!ns.unmountFns[url.href]) {
1709
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1677
1710
  }
1678
- self.__remote_script_entrypoint_unmount__[url.href]?.add(
1711
+ ns.unmountFns[url.href]?.add(
1679
1712
  mod.unmount || mod.default?.unmount || (() => {
1680
1713
  })
1681
1714
  );
@@ -1716,10 +1749,145 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1716
1749
  var init_static_loader = __esm({
1717
1750
  "src/runtime/loaders/static-loader.ts"() {
1718
1751
  "use strict";
1752
+ init_namespace();
1719
1753
  init_logger();
1720
1754
  }
1721
1755
  });
1722
1756
 
1757
+ // src/host/html/runtime/webpack.ts
1758
+ var webpack_exports = {};
1759
+ __export(webpack_exports, {
1760
+ webpackRuntime: () => webpackRuntime
1761
+ });
1762
+ async function webpackRuntime(bundle, shared, remoteShared, resolveClientUrl) {
1763
+ const self = globalThis;
1764
+ if (!self.__DISABLE_WEBPACK_EXEC__) {
1765
+ self.__DISABLE_WEBPACK_EXEC__ = {};
1766
+ }
1767
+ self.__DISABLE_WEBPACK_EXEC__[bundle] = true;
1768
+ if (typeof self.__webpack_require__ !== "function" && self.__webpack_require_type__ !== "turbopack") {
1769
+ self.__webpack_require__ = (remoteId) => {
1770
+ const re = /\[(?<bundle>[^\]]+)\] (?<id>.*)/;
1771
+ const match = re.exec(remoteId);
1772
+ const remoteBundle = match?.groups?.bundle;
1773
+ const id = match?.groups?.id;
1774
+ if (!(id && remoteBundle)) {
1775
+ throw new RemoteComponentsError(
1776
+ `Remote Component module "${remoteId}" not found. Did you forget to wrap the Next.js config with \`withRemoteComponentsConfig\` on both host and remote?`
1777
+ );
1778
+ }
1779
+ if (typeof self.__remote_webpack_require__?.[remoteBundle] !== "function") {
1780
+ throw new RemoteComponentsError(
1781
+ `Remote Components are not available in "${remoteBundle}". Did you forget to wrap the Next.js config with \`withRemoteComponentsConfig\` on both host and remote?`
1782
+ );
1783
+ }
1784
+ return self.__remote_webpack_require__[remoteBundle](id);
1785
+ };
1786
+ self.__webpack_chunk_load__ = () => {
1787
+ return Promise.resolve([]);
1788
+ };
1789
+ }
1790
+ const {
1791
+ default: { createFromReadableStream }
1792
+ } = await import("react-server-dom-webpack/client.browser");
1793
+ async function preloadScripts(scripts, url, remoteBundle, _) {
1794
+ const scriptSrcs = scripts.flatMap((script) => {
1795
+ const scriptSrc = script.getAttribute("src") || script.getAttribute("data-src");
1796
+ script.parentElement?.removeChild(script);
1797
+ if (!scriptSrc)
1798
+ return [];
1799
+ return [
1800
+ {
1801
+ src: new URL(scriptSrc.replace(NEXT_BUNDLE_PATH_RE, "/_next/"), url).href
1802
+ }
1803
+ ];
1804
+ });
1805
+ await loadScripts(scriptSrcs, resolveClientUrl);
1806
+ const hostShared = buildHostShared(shared, resolveClientUrl);
1807
+ const resolve = await buildWebpackResolve(
1808
+ hostShared,
1809
+ remoteShared ?? {},
1810
+ remoteBundle,
1811
+ {
1812
+ "/react/index.js": (await import("react")).default,
1813
+ "/react/jsx-dev-runtime.js": (await import("react/jsx-dev-runtime")).default,
1814
+ "/react/jsx-runtime.js": (await import("react/jsx-runtime")).default,
1815
+ "/react-dom/index.js": (await import("react-dom")).default,
1816
+ "/react-dom/client.js": (await import("react-dom/client")).default
1817
+ },
1818
+ "WebpackRuntime"
1819
+ );
1820
+ applySharedModules(remoteBundle, resolve);
1821
+ }
1822
+ return {
1823
+ self,
1824
+ createFromReadableStream,
1825
+ applySharedModules,
1826
+ nextClientPagesLoader,
1827
+ preloadScripts
1828
+ };
1829
+ }
1830
+ var init_webpack = __esm({
1831
+ "src/host/html/runtime/webpack.ts"() {
1832
+ "use strict";
1833
+ init_apply_shared_modules();
1834
+ init_next_client_pages_loader();
1835
+ init_shared_module_resolver();
1836
+ init_script_loader();
1837
+ init_patterns();
1838
+ init_error();
1839
+ }
1840
+ });
1841
+
1842
+ // src/host/html/runtime/turbopack.ts
1843
+ var turbopack_exports = {};
1844
+ __export(turbopack_exports, {
1845
+ turbopackRuntime: () => turbopackRuntime
1846
+ });
1847
+ async function turbopackRuntime(url, bundle, shared, remoteShared, resolveClientUrl) {
1848
+ const self = globalThis;
1849
+ const hostShared = buildHostShared(shared, resolveClientUrl, {
1850
+ includeRemoteComponentShared: true
1851
+ });
1852
+ await setupRemoteScope("turbopack", [], url, bundle, resolveClientUrl);
1853
+ const {
1854
+ default: { createFromReadableStream }
1855
+ } = await import("react-server-dom-webpack/client.browser");
1856
+ async function preloadScripts(scripts, __) {
1857
+ const scope = await setupRemoteScope(
1858
+ "turbopack",
1859
+ scripts.map((script) => ({
1860
+ src: script.getAttribute("src") || script.getAttribute("data-src") || script.src
1861
+ })),
1862
+ url,
1863
+ bundle,
1864
+ resolveClientUrl
1865
+ );
1866
+ await initializeSharedModules(
1867
+ scope,
1868
+ buildCoreShared(hostShared),
1869
+ remoteShared ?? {}
1870
+ );
1871
+ }
1872
+ return {
1873
+ self,
1874
+ createFromReadableStream,
1875
+ applySharedModules,
1876
+ nextClientPagesLoader,
1877
+ preloadScripts
1878
+ };
1879
+ }
1880
+ var init_turbopack = __esm({
1881
+ "src/host/html/runtime/turbopack.ts"() {
1882
+ "use strict";
1883
+ init_apply_shared_modules();
1884
+ init_next_client_pages_loader();
1885
+ init_shared_module_resolver();
1886
+ init_remote_scope_setup();
1887
+ init_shared_modules();
1888
+ }
1889
+ });
1890
+
1723
1891
  // src/host/html/runtime/script.ts
1724
1892
  var script_exports = {};
1725
1893
  __export(script_exports, {
@@ -1812,37 +1980,36 @@ function getClientOrServerUrl(src, serverFallback) {
1812
1980
  return typeof src === "string" ? new URL(src, fallback) : src;
1813
1981
  }
1814
1982
 
1815
- // src/host/shared/state.ts
1816
- function createHostState() {
1983
+ // src/host/shared/lifecycle.ts
1984
+ function makeEventEmitter(element) {
1985
+ function dispatch(type, detail) {
1986
+ const event = new Event(type, { bubbles: true, composed: true });
1987
+ if (detail) {
1988
+ Object.assign(event, detail);
1989
+ }
1990
+ element.dispatchEvent(event);
1991
+ }
1817
1992
  return {
1818
- stage: "idle",
1819
- prevSrc: void 0,
1820
- prevUrl: void 0,
1821
- prevName: void 0,
1822
- prevIsRemoteComponent: false,
1823
- abortController: void 0
1993
+ beforeLoad(src) {
1994
+ dispatch("beforeload", { src });
1995
+ },
1996
+ load(src) {
1997
+ dispatch("load", { src });
1998
+ },
1999
+ error(error, src) {
2000
+ dispatch("error", src != null ? { error, src } : { error });
2001
+ },
2002
+ change(info) {
2003
+ dispatch("change", info);
2004
+ }
1824
2005
  };
1825
2006
  }
1826
2007
 
1827
- // src/host/utils/resolve-name-from-src.ts
1828
- function resolveNameFromSrc(src, defaultName) {
1829
- if (!src) {
1830
- return defaultName;
1831
- }
1832
- const hash = typeof src === "string" ? src : src.hash;
1833
- const hashIndex = hash.indexOf("#");
1834
- if (hashIndex < 0) {
1835
- return defaultName;
1836
- }
1837
- const name = hash.slice(hashIndex + 1);
1838
- return name || defaultName;
1839
- }
1840
-
1841
- // src/host/html/index.tsx
1842
- init_constants2();
2008
+ // src/host/shared/pipeline.ts
2009
+ init_shared_module_resolver();
1843
2010
 
1844
- // src/runtime/html/apply-origin.ts
1845
- var tagNames = [
2011
+ // src/runtime/html/html-spec.ts
2012
+ var ORIGIN_REWRITE_TAGS = [
1846
2013
  "img",
1847
2014
  "source",
1848
2015
  "video",
@@ -1853,10 +2020,37 @@ var tagNames = [
1853
2020
  "script",
1854
2021
  "link"
1855
2022
  ];
2023
+ var ID_SUFFIX_RSC = "_rsc";
2024
+ var ID_SUFFIX_SSR = "_ssr";
2025
+ var ID_SUFFIX_SHARED = "_shared";
2026
+ var DATA_BUNDLE = "data-bundle";
2027
+ var DATA_ROUTE = "data-route";
2028
+ var DATA_RUNTIME = "data-runtime";
2029
+ var DATA_TYPE = "data-type";
2030
+ var DATA_SRC = "data-src";
2031
+ var DATA_REMOTE_COMPONENTS_SHARED = "data-remote-components-shared";
2032
+ var TAG_REMOTE_COMPONENT = "remote-component";
2033
+ var NEXT_DATA_ID = "__NEXT_DATA__";
2034
+ var REMOTE_NEXT_DATA_ID = "__REMOTE_NEXT_DATA__";
2035
+ var NEXT_CONTAINER_ID = "__next";
2036
+
2037
+ // src/runtime/html/rewrite-srcset.ts
2038
+ function rewriteSrcset(srcset, base, resolve) {
2039
+ return srcset.split(",").map((entry) => {
2040
+ const [url, descriptor] = entry.trim().split(/\s+/);
2041
+ if (!url)
2042
+ return entry;
2043
+ const absoluteUrl = new URL(url, base).href;
2044
+ const resolvedUrl = resolve ? resolve(absoluteUrl) : absoluteUrl;
2045
+ return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
2046
+ }).join(", ");
2047
+ }
2048
+
2049
+ // src/runtime/html/apply-origin.ts
1856
2050
  function applyOriginToNodes(doc, url, resolveClientUrl) {
1857
2051
  if (url.origin !== location.origin) {
1858
2052
  const nodes = doc.querySelectorAll(
1859
- tagNames.map(
2053
+ ORIGIN_REWRITE_TAGS.map(
1860
2054
  (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
1861
2055
  ).join(",")
1862
2056
  );
@@ -1874,29 +2068,17 @@ function applyOriginToNodes(doc, url, resolveClientUrl) {
1874
2068
  );
1875
2069
  }
1876
2070
  if (node.hasAttribute("srcset")) {
1877
- const srcSet = node.getAttribute("srcset")?.split(",").map((entry) => {
1878
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
1879
- if (!urlPart)
1880
- return entry;
1881
- const absoluteUrl = new URL(urlPart, url).href;
1882
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
1883
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
1884
- }).join(", ");
1885
- if (srcSet) {
1886
- node.setAttribute("srcset", srcSet);
2071
+ const raw = node.getAttribute("srcset");
2072
+ if (raw) {
2073
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
2074
+ node.setAttribute("srcset", rewriteSrcset(raw, url, resolve));
1887
2075
  }
1888
2076
  }
1889
2077
  if (node.hasAttribute("imagesrcset")) {
1890
- const srcSet = node.getAttribute("imagesrcset")?.split(",").map((entry) => {
1891
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
1892
- if (!urlPart)
1893
- return entry;
1894
- const absoluteUrl = new URL(urlPart, url).href;
1895
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
1896
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
1897
- }).join(", ");
1898
- if (srcSet) {
1899
- node.setAttribute("imagesrcset", srcSet);
2078
+ const raw = node.getAttribute("imagesrcset");
2079
+ if (raw) {
2080
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
2081
+ node.setAttribute("imagesrcset", rewriteSrcset(raw, url, resolve));
1900
2082
  }
1901
2083
  }
1902
2084
  });
@@ -1942,26 +2124,28 @@ function buildMetadata(attrs, url) {
1942
2124
  // src/runtime/html/parse-remote-html.ts
1943
2125
  init_error();
1944
2126
  function validateSingleComponent(doc, name, url) {
1945
- 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}"]`)) {
2127
+ if (doc.querySelectorAll(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`).length > 1 && !doc.querySelector(
2128
+ `div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`
2129
+ ) || doc.querySelectorAll(`${TAG_REMOTE_COMPONENT}:not([src])`).length > 1 && !doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]`)) {
1946
2130
  throw multipleRemoteComponentsError(url);
1947
2131
  }
1948
2132
  }
1949
2133
  function findComponentElement(doc, name) {
1950
- 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])");
2134
+ 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])`);
1951
2135
  }
1952
2136
  function parseNextData(doc) {
1953
2137
  return JSON.parse(
1954
- (doc.querySelector("#__NEXT_DATA__") ?? doc.querySelector("#__REMOTE_NEXT_DATA__"))?.textContent ?? "null"
2138
+ (doc.querySelector(`#${NEXT_DATA_ID}`) ?? doc.querySelector(`#${REMOTE_NEXT_DATA_ID}`))?.textContent ?? "null"
1955
2139
  );
1956
2140
  }
1957
2141
  function resolveComponentName(component, nextData, fallbackName) {
1958
- const isRemoteComponent = component?.tagName.toLowerCase() === "remote-component";
1959
- const name = component?.getAttribute("id")?.replace(/_ssr$/, "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
2142
+ const isRemoteComponent = component?.tagName.toLowerCase() === TAG_REMOTE_COMPONENT;
2143
+ const name = component?.getAttribute("id")?.replace(new RegExp(`${ID_SUFFIX_SSR}$`), "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
1960
2144
  return { name, isRemoteComponent };
1961
2145
  }
1962
2146
  function extractRemoteShared(doc, name, nextData) {
1963
2147
  const remoteSharedEl = doc.querySelector(
1964
- `#${name}_shared[data-remote-components-shared]`
2148
+ `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`
1965
2149
  );
1966
2150
  const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
1967
2151
  remoteSharedEl?.remove();
@@ -1982,7 +2166,7 @@ function extractLinks(doc, component) {
1982
2166
  function extractScripts(doc, component, isRemoteComponent) {
1983
2167
  return Array.from(
1984
2168
  (isRemoteComponent ? component : doc).querySelectorAll(
1985
- "script[src],script[data-src]"
2169
+ `script[src],script[${DATA_SRC}]`
1986
2170
  )
1987
2171
  );
1988
2172
  }
@@ -1995,15 +2179,15 @@ function parseRemoteComponentDocument(doc, name, url) {
1995
2179
  nextData,
1996
2180
  name
1997
2181
  );
1998
- const rsc = doc.querySelector(`#${resolvedName}_rsc`);
2182
+ const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);
1999
2183
  const metadata = buildMetadata(
2000
2184
  {
2001
2185
  name: resolvedName,
2002
- bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle,
2003
- route: component?.getAttribute("data-route") ?? nextData?.page,
2004
- runtime: component?.getAttribute("data-runtime") ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
2186
+ bundle: component?.getAttribute(DATA_BUNDLE) || nextData?.props.__REMOTE_COMPONENT__?.bundle,
2187
+ route: component?.getAttribute(DATA_ROUTE) ?? nextData?.page,
2188
+ runtime: component?.getAttribute(DATA_RUNTIME) ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
2005
2189
  id: component?.getAttribute("id"),
2006
- type: component?.getAttribute("data-type")
2190
+ type: component?.getAttribute(DATA_TYPE)
2007
2191
  },
2008
2192
  url
2009
2193
  );
@@ -2031,6 +2215,16 @@ function parseRemoteComponentDocument(doc, name, url) {
2031
2215
  };
2032
2216
  }
2033
2217
 
2218
+ // src/runtime/loaders/component-loader.ts
2219
+ var React = __toESM(require("react"), 1);
2220
+ var JSXDevRuntime = __toESM(require("react/jsx-dev-runtime"), 1);
2221
+ var JSXRuntime = __toESM(require("react/jsx-runtime"), 1);
2222
+ var ReactDOM = __toESM(require("react-dom"), 1);
2223
+ var ReactDOMClient = __toESM(require("react-dom/client"), 1);
2224
+ init_apply_shared_modules();
2225
+ init_next_client_pages_loader();
2226
+ init_shared_module_resolver();
2227
+
2034
2228
  // src/runtime/rsc.ts
2035
2229
  var import_web_streams_polyfill = require("web-streams-polyfill");
2036
2230
  function fixPayload(payload) {
@@ -2051,6 +2245,18 @@ function fixPayload(payload) {
2051
2245
  }
2052
2246
  }
2053
2247
  }
2248
+ function buildRSCChunks(rscName, data) {
2249
+ const chunks = [];
2250
+ for (const chunk of data) {
2251
+ for (const line of chunk.split("\n")) {
2252
+ const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
2253
+ if (match?.groups?.rsc) {
2254
+ chunks.push(JSON.parse(`"${match.groups.rsc}"`));
2255
+ }
2256
+ }
2257
+ }
2258
+ return chunks;
2259
+ }
2054
2260
  function createRSCStream(rscName, data) {
2055
2261
  return new import_web_streams_polyfill.ReadableStream({
2056
2262
  type: "bytes",
@@ -2058,16 +2264,11 @@ function createRSCStream(rscName, data) {
2058
2264
  const encoder = new TextEncoder();
2059
2265
  const self = globalThis;
2060
2266
  if (data.length > 0) {
2061
- data.forEach((chunk) => {
2062
- const lines = chunk.split("\n");
2063
- for (const line of lines) {
2064
- const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
2065
- if (match?.groups?.rsc) {
2066
- self[rscName] = self[rscName] ?? [];
2067
- self[rscName].push(JSON.parse(`"${match.groups.rsc}"`));
2068
- }
2069
- }
2070
- });
2267
+ const parsed = buildRSCChunks(rscName, data);
2268
+ if (parsed.length > 0) {
2269
+ self[rscName] = self[rscName] ?? [];
2270
+ self[rscName].push(...parsed);
2271
+ }
2071
2272
  }
2072
2273
  const allChunks = (self[rscName] ?? [`0:[null]
2073
2274
  `]).join("");
@@ -2097,6 +2298,75 @@ function createRSCStream(rscName, data) {
2097
2298
  });
2098
2299
  }
2099
2300
 
2301
+ // src/runtime/loaders/component-loader.ts
2302
+ init_remote_scope_setup();
2303
+ init_shared_modules();
2304
+ init_error();
2305
+ init_logger();
2306
+ init_script_loader();
2307
+
2308
+ // src/host/shared/pipeline.ts
2309
+ init_static_loader();
2310
+ init_patterns();
2311
+ init_utils();
2312
+ init_error();
2313
+ function preparePipeline(input) {
2314
+ const parser = new DOMParser();
2315
+ const doc = parser.parseFromString(input.html, "text/html");
2316
+ const parsed = parseRemoteComponentDocument(doc, input.name, input.url);
2317
+ const remoteShared = input.remoteShared ?? parsed.remoteShared;
2318
+ if ("__remote_components_missing_shared__" in remoteShared) {
2319
+ throw new RemoteComponentsError(
2320
+ remoteShared.__remote_components_missing_shared__
2321
+ );
2322
+ }
2323
+ applyOriginToNodes(doc, input.url, input.resolveClientUrl);
2324
+ const scriptDescriptors = buildScriptDescriptors(parsed.scripts, input.url);
2325
+ return { doc, parsed, scriptDescriptors };
2326
+ }
2327
+ function buildScriptDescriptors(scripts, url) {
2328
+ return scripts.map((script) => {
2329
+ const scriptSrc = script.getAttribute("data-src") || script.getAttribute("src") || script.src;
2330
+ const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(scriptSrc)?.groups ?? {
2331
+ prefix: void 0,
2332
+ id: scriptSrc
2333
+ };
2334
+ return {
2335
+ src: new URL(collapseDoubleSlashes(`${prefix ?? ""}${path}`), url).href
2336
+ };
2337
+ });
2338
+ }
2339
+
2340
+ // src/host/shared/state.ts
2341
+ function createHostState() {
2342
+ return {
2343
+ stage: "idle",
2344
+ prevSrc: void 0,
2345
+ prevUrl: void 0,
2346
+ prevName: void 0,
2347
+ prevIsRemoteComponent: false,
2348
+ abortController: void 0
2349
+ };
2350
+ }
2351
+
2352
+ // src/host/utils/resolve-name-from-src.ts
2353
+ function resolveNameFromSrc(src, defaultName) {
2354
+ if (!src) {
2355
+ return defaultName;
2356
+ }
2357
+ const hash = typeof src === "string" ? src : src.hash;
2358
+ const hashIndex = hash.indexOf("#");
2359
+ if (hashIndex < 0) {
2360
+ return defaultName;
2361
+ }
2362
+ const name = hash.slice(hashIndex + 1);
2363
+ return name || defaultName;
2364
+ }
2365
+
2366
+ // src/host/html/index.tsx
2367
+ init_constants2();
2368
+ init_namespace();
2369
+
2100
2370
  // src/runtime/url/resolve-client-url.ts
2101
2371
  function withRemoteSrc(resolveClientUrl, remoteSrc) {
2102
2372
  const remoteOrigin = parseOrigin(remoteSrc);
@@ -2251,6 +2521,7 @@ if (typeof HTMLElement !== "undefined") {
2251
2521
  hostState = createHostState();
2252
2522
  root = null;
2253
2523
  reactRoot;
2524
+ emitter = makeEventEmitter(this);
2254
2525
  onRequest;
2255
2526
  onResponse;
2256
2527
  resolveClientUrl;
@@ -2301,13 +2572,6 @@ if (typeof HTMLElement !== "undefined") {
2301
2572
  static get observedAttributes() {
2302
2573
  return ["src", "name", "mode"];
2303
2574
  }
2304
- dispatchLifecycleEvent(type, detail) {
2305
- const event = new Event(type, { bubbles: true, composed: true });
2306
- if (detail) {
2307
- Object.assign(event, detail);
2308
- }
2309
- this.dispatchEvent(event);
2310
- }
2311
2575
  attributeChangedCallback(name, oldValue, newValue) {
2312
2576
  if ((name === "src" || name === "name") && oldValue !== newValue) {
2313
2577
  if (this.src) {
@@ -2316,7 +2580,7 @@ if (typeof HTMLElement !== "undefined") {
2316
2580
  return;
2317
2581
  }
2318
2582
  logError("HtmlHost", "Error loading remote component.", e);
2319
- this.dispatchLifecycleEvent("error", { error: e, src: this.src });
2583
+ this.emitter.error(e, this.src);
2320
2584
  this.hostState.stage = "error";
2321
2585
  });
2322
2586
  }
@@ -2333,7 +2597,7 @@ if (typeof HTMLElement !== "undefined") {
2333
2597
  return;
2334
2598
  }
2335
2599
  logError("HtmlHost", "Error reloading remote component.", e);
2336
- this.dispatchLifecycleEvent("error", { error: e, src: this.src });
2600
+ this.emitter.error(e, this.src);
2337
2601
  });
2338
2602
  }
2339
2603
  }
@@ -2371,7 +2635,7 @@ if (typeof HTMLElement !== "undefined") {
2371
2635
  this.hostState.stage = "idle";
2372
2636
  }
2373
2637
  };
2374
- this.dispatchLifecycleEvent("beforeload", { src });
2638
+ this.emitter.beforeLoad(src ?? "");
2375
2639
  const remoteComponentChild = this.querySelector("div#__REMOTE_COMPONENT__") || this.querySelector("div[data-bundle][data-route]");
2376
2640
  if (!src && !remoteComponentChild) {
2377
2641
  throw new RemoteComponentsError('"src" attribute is required');
@@ -2419,13 +2683,14 @@ if (typeof HTMLElement !== "undefined") {
2419
2683
  return abandonLoad();
2420
2684
  }
2421
2685
  }
2422
- const parser = new DOMParser();
2423
- const doc = parser.parseFromString(html, "text/html");
2424
- const parsed = parseRemoteComponentDocument(
2425
- doc,
2426
- this.name,
2427
- url ?? new URL(window.location.href)
2428
- );
2686
+ const effectiveUrl = url ?? new URL(window.location.href);
2687
+ const { doc, parsed } = preparePipeline({
2688
+ html,
2689
+ name: this.name,
2690
+ url: effectiveUrl,
2691
+ shared: {},
2692
+ resolveClientUrl
2693
+ });
2429
2694
  const {
2430
2695
  component,
2431
2696
  name: resolvedName,
@@ -2443,11 +2708,7 @@ if (typeof HTMLElement !== "undefined") {
2443
2708
  this.name = resolvedName;
2444
2709
  this.bundle = parsedMetadata.bundle;
2445
2710
  if (url) {
2446
- const self2 = globalThis;
2447
- if (!self2.__remote_bundle_url__) {
2448
- self2.__remote_bundle_url__ = {};
2449
- }
2450
- self2.__remote_bundle_url__[this.bundle] = url;
2711
+ getNamespace().bundleUrls[this.bundle] = url;
2451
2712
  }
2452
2713
  const metadataEl = document.createElement("script");
2453
2714
  metadataEl.type = "application/json";
@@ -2463,30 +2724,25 @@ if (typeof HTMLElement !== "undefined") {
2463
2724
  this.previousElementSibling?.remove();
2464
2725
  }
2465
2726
  this.parentElement?.insertBefore(metadataEl, this);
2466
- if ("__remote_components_missing_shared__" in remoteShared) {
2467
- throw new RemoteComponentsError(
2468
- remoteShared.__remote_components_missing_shared__
2469
- );
2470
- }
2471
2727
  if (this.hostState.prevIsRemoteComponent) {
2472
2728
  if (this.hostState.prevUrl) {
2473
2729
  const prevUrl = this.hostState.prevUrl;
2474
- const self2 = globalThis;
2475
- if (self2.__remote_script_entrypoint_unmount__?.[prevUrl.href]) {
2730
+ const nsUnmount = getNamespace();
2731
+ if (nsUnmount.unmountFns[prevUrl.href]) {
2476
2732
  await Promise.all(
2477
- Array.from(
2478
- self2.__remote_script_entrypoint_unmount__[prevUrl.href] ?? []
2479
- ).map(async (unmount) => {
2480
- try {
2481
- await unmount(this.root);
2482
- } catch (e) {
2483
- logError(
2484
- "HtmlHost",
2485
- `Error while calling unmount() for Remote Component from ${prevUrl.href}.`,
2486
- e
2487
- );
2733
+ Array.from(nsUnmount.unmountFns[prevUrl.href] ?? []).map(
2734
+ async (unmount) => {
2735
+ try {
2736
+ await unmount(this.root);
2737
+ } catch (e) {
2738
+ logError(
2739
+ "HtmlHost",
2740
+ `Error while calling unmount() for Remote Component from ${prevUrl.href}.`,
2741
+ e
2742
+ );
2743
+ }
2488
2744
  }
2489
- })
2745
+ )
2490
2746
  );
2491
2747
  if (!isCurrentLoad()) {
2492
2748
  return abandonLoad();
@@ -2496,14 +2752,14 @@ if (typeof HTMLElement !== "undefined") {
2496
2752
  this.root.innerHTML = "";
2497
2753
  }
2498
2754
  if (this.hostState.prevSrc !== void 0) {
2499
- this.dispatchLifecycleEvent("change", {
2500
- previousSrc: this.hostState.prevSrc,
2501
- nextSrc: src,
2755
+ this.emitter.change({
2756
+ previousSrc: this.hostState.prevSrc ?? null,
2757
+ nextSrc: src ?? null,
2502
2758
  previousName: this.hostState.prevName,
2503
2759
  nextName: this.name
2504
2760
  });
2505
2761
  }
2506
- this.hostState.prevUrl = url ?? new URL(window.location.href);
2762
+ this.hostState.prevUrl = effectiveUrl;
2507
2763
  this.hostState.prevIsRemoteComponent = isRemoteComponent;
2508
2764
  this.hostState.prevSrc = src;
2509
2765
  this.hostState.prevName = this.name;
@@ -2536,11 +2792,6 @@ if (typeof HTMLElement !== "undefined") {
2536
2792
  return abandonLoad();
2537
2793
  }
2538
2794
  }
2539
- applyOriginToNodes(
2540
- doc,
2541
- url ?? new URL(window.location.href),
2542
- resolveClientUrl
2543
- );
2544
2795
  if (!this.reactRoot) {
2545
2796
  Array.from(component.children).forEach((el) => {
2546
2797
  if (!isRemoteComponent && el.tagName.toLowerCase() === "script") {
@@ -2615,7 +2866,7 @@ if (typeof HTMLElement !== "undefined") {
2615
2866
  preloadScripts
2616
2867
  } = await getRuntime(
2617
2868
  metadataObj.runtime,
2618
- url ?? new URL(window.location.href),
2869
+ effectiveUrl,
2619
2870
  this.bundle,
2620
2871
  {
2621
2872
  react: async () => (await import("react")).default,
@@ -2706,7 +2957,7 @@ if (typeof HTMLElement !== "undefined") {
2706
2957
  if (isCurrentLoad()) {
2707
2958
  this.hostState.stage = "loaded";
2708
2959
  }
2709
- this.dispatchLifecycleEvent("load", { src: this.src });
2960
+ this.emitter.load(this.src ?? "");
2710
2961
  }, [initial, name]);
2711
2962
  return Component;
2712
2963
  };
@@ -2750,9 +3001,7 @@ if (typeof HTMLElement !== "undefined") {
2750
3001
  if (isCurrentLoad()) {
2751
3002
  remoteComponent.hostState.stage = "loaded";
2752
3003
  }
2753
- remoteComponent.dispatchLifecycleEvent("load", {
2754
- src: remoteComponent.src
2755
- });
3004
+ remoteComponent.emitter.load(remoteComponent.src ?? "");
2756
3005
  }, [initial, remoteComponent]);
2757
3006
  return NextApp ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(NextApp, { Component: NextComponent, ...nextData.props }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(NextComponent, { ...nextData.props });
2758
3007
  })(App, Component, this);
@@ -2777,25 +3026,25 @@ if (typeof HTMLElement !== "undefined") {
2777
3026
  if (this.fouc) {
2778
3027
  this.root.removeChild(this.fouc);
2779
3028
  }
2780
- } else if (self.__remote_script_entrypoint_mount__?.[url.href]) {
3029
+ } else if (getNamespace().mountFns[url.href]) {
2781
3030
  await Promise.all(
2782
- Array.from(
2783
- self.__remote_script_entrypoint_mount__[url.href] ?? []
2784
- ).map(async (mount) => {
2785
- try {
2786
- await mount(this.root);
2787
- } catch (e) {
2788
- logError(
2789
- "HtmlHost",
2790
- `Error while calling mount() for Remote Component from ${url.href}.`,
2791
- e
2792
- );
3031
+ Array.from(getNamespace().mountFns[url.href] ?? []).map(
3032
+ async (mount) => {
3033
+ try {
3034
+ await mount(this.root);
3035
+ } catch (e) {
3036
+ logError(
3037
+ "HtmlHost",
3038
+ `Error while calling mount() for Remote Component from ${url.href}.`,
3039
+ e
3040
+ );
3041
+ }
2793
3042
  }
2794
- })
3043
+ )
2795
3044
  );
2796
- this.dispatchLifecycleEvent("load", { src: this.src });
3045
+ this.emitter.load(this.src ?? "");
2797
3046
  } else {
2798
- this.dispatchLifecycleEvent("load", { src: this.src });
3047
+ this.emitter.load(this.src ?? "");
2799
3048
  }
2800
3049
  if (isCurrentLoad()) {
2801
3050
  this.hostState.stage = "loaded";
@@ -2805,14 +3054,9 @@ if (typeof HTMLElement !== "undefined") {
2805
3054
  customElements.define("remote-component", RemoteComponent);
2806
3055
  }
2807
3056
  function registerSharedModules(modules = {}) {
2808
- const self = globalThis;
2809
- if (!self.__remote_component_host_shared_modules__) {
2810
- self.__remote_component_host_shared_modules__ = {};
2811
- }
3057
+ const ns = getNamespace();
2812
3058
  Object.entries(modules).forEach(([key, value]) => {
2813
- if (self.__remote_component_host_shared_modules__) {
2814
- self.__remote_component_host_shared_modules__[key] = value;
2815
- }
3059
+ ns.hostSharedModules[key] = value;
2816
3060
  });
2817
3061
  }
2818
3062
  // Annotate the CommonJS export names for ESM import in node: