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
package/dist/host/html.js CHANGED
@@ -183,7 +183,7 @@ var init_logger = __esm({
183
183
  init_constants();
184
184
  init_error();
185
185
  PREFIX = "remote-components";
186
- DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
186
+ DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true" || typeof process !== "undefined" && process.env.RC_DEBUG === "true";
187
187
  }
188
188
  });
189
189
 
@@ -218,190 +218,65 @@ var init_constants2 = __esm({
218
218
  }
219
219
  });
220
220
 
221
- // src/config/webpack/apply-shared-modules.ts
222
- function applySharedModules(bundle, resolve) {
223
- logDebug(
224
- "SharedModules",
225
- `applySharedModules called for bundle: "${bundle}"`
226
- );
227
- logDebug(
228
- "SharedModules",
229
- `Shared modules to resolve: ${Object.keys(resolve)}`
230
- );
231
- const self = globalThis;
232
- if (self.__remote_webpack_require__?.[bundle]) {
233
- const modulePaths = Object.keys(
234
- self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
235
- );
236
- logDebug(
237
- "SharedModules",
238
- `Available module paths in __remote_webpack_require__[${bundle}]: ${modulePaths}`
239
- );
240
- for (const [key, value] of Object.entries(resolve)) {
241
- const exactIds = modulePaths.filter((p) => p === key);
242
- const ids = exactIds.length > 0 ? exactIds : modulePaths.filter((p) => p.includes(key));
243
- if (ids.length === 0) {
244
- logDebug(
245
- "SharedModules",
246
- `No matching module path found for shared module "${key}"`
247
- );
248
- }
249
- for (const id of ids) {
250
- const webpackBundle = self.__remote_webpack_require__[bundle];
251
- if (webpackBundle.m) {
252
- const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
253
- if (resolvedId !== id) {
254
- logDebug(
255
- "SharedModules",
256
- `Mapped module id: "${id}" -> "${resolvedId}"`
257
- );
258
- }
259
- webpackBundle.m[resolvedId] = (module) => {
260
- module.exports = value;
261
- };
262
- } else {
263
- logWarn(
264
- "SharedModules",
265
- `webpackBundle.m is not available for bundle "${bundle}" \u2014 ${DEDUPLICATION_SKIPPED}`
266
- );
267
- }
268
- }
269
- }
270
- } else {
271
- logWarn(
272
- "SharedModules",
273
- `No webpack require found for bundle "${bundle}" \u2014 ${DEDUPLICATION_SKIPPED}`
274
- );
275
- logDebug(
276
- "SharedModules",
277
- `Available bundles: ${Object.keys(self.__remote_webpack_require__ ?? {})}`
278
- );
279
- }
280
- }
281
- var DEDUPLICATION_SKIPPED;
282
- var init_apply_shared_modules = __esm({
283
- "src/config/webpack/apply-shared-modules.ts"() {
284
- "use strict";
285
- init_logger();
286
- DEDUPLICATION_SKIPPED = "shared module deduplication skipped. The remote may load its own copy of shared dependencies.";
287
- }
288
- });
289
-
290
- // src/config/webpack/next-client-pages-loader.ts
291
- function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
292
- const self = globalThis;
293
- const nextCssOriginal = document.querySelector(
294
- `[id="__next_css__DO_NOT_USE__"]:not([data-bundle="${bundle}"][data-route="${route}"])`
295
- );
296
- if (nextCssOriginal) {
297
- nextCssOriginal.parentNode?.removeChild(nextCssOriginal);
298
- }
299
- const nextCss = document.createElement("noscript");
300
- nextCss.id = "__next_css__DO_NOT_USE__";
301
- nextCss.setAttribute("data-bundle", bundle);
302
- nextCss.setAttribute("data-route", route);
303
- const nextCssEnd = document.createElement("noscript");
304
- nextCssEnd.id = "__next_css__DO_NOT_USE_END__";
305
- nextCssEnd.setAttribute("data-bundle", bundle);
306
- nextCssEnd.setAttribute("data-route", route);
307
- document.head.appendChild(nextCssEnd);
308
- document.head.appendChild(nextCss);
309
- const componentLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
310
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
311
- ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
312
- (key) => key.includes("/next/dist/client/page-loader.js")
313
- ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
314
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
315
- ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
316
- (key) => key.includes("/next/dist/client/page-loader.js")
317
- ) ?? ""] ?? -1;
318
- const appLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
319
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
320
- ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
321
- (key) => key.includes("/next/dist/client/page-loader.js")
322
- ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
323
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
324
- ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
325
- (key) => key.includes("/next/dist/client/page-loader.js")
326
- ) ?? ""] ?? -1;
327
- if (!(componentLoaderChunk && appLoaderChunk)) {
328
- throw new RemoteComponentsError(
329
- `Next.js client pages loader not found in bundle "${bundle}".`
330
- );
331
- }
332
- const __NEXT_P_ORIGINAL = self.__NEXT_P;
333
- const selfOriginal = self;
334
- delete selfOriginal.__NEXT_P;
335
- self.__remote_webpack_require__?.[bundle]?.(
336
- self.__remote_webpack_require__[bundle].type !== "turbopack" ? componentLoaderChunk : `[${bundle}] ${componentLoaderChunk}`
337
- );
338
- if (typeof appLoaderChunk === "string" || typeof appLoaderChunk === "number" && appLoaderChunk !== -1) {
339
- self.__remote_webpack_require__?.[bundle]?.(
340
- self.__remote_webpack_require__[bundle].type !== "turbopack" ? appLoaderChunk : `[${bundle}] ${appLoaderChunk}`
341
- );
342
- }
343
- if (self.__NEXT_P) {
344
- const [, componentLoader] = self.__NEXT_P[0] ?? [
345
- void 0,
346
- () => ({ default: null })
347
- ];
348
- const [, appLoader] = self.__NEXT_P[2] ?? [
349
- void 0,
350
- () => ({
351
- default: null
352
- })
353
- ];
354
- const { default: Component } = componentLoader();
355
- const { default: App } = appLoader();
356
- if (!self.__remote_next_css__) {
357
- self.__remote_next_css__ = {};
358
- }
359
- if (!self.__remote_next_css__[bundle]) {
360
- const cssRE = /\.s?css$/;
361
- Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
362
- self.__remote_webpack_require__?.[bundle]?.(id);
363
- });
364
- Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {}).filter((path) => cssRE.test(path)).forEach((path) => {
365
- const id = self.__remote_webpack_module_map__?.[bundle]?.[path];
366
- if (id) {
367
- self.__remote_webpack_require__?.[bundle]?.(id);
368
- }
369
- });
370
- const elements = [];
371
- let node = nextCss.previousSibling;
372
- while (node && node !== nextCssEnd) {
373
- elements.push(node);
374
- node.remove();
375
- node = nextCss.previousSibling;
376
- }
377
- self.__remote_next_css__[bundle] = elements;
378
- }
379
- if (styleContainer) {
380
- const elements = self.__remote_next_css__[bundle];
381
- elements.forEach((el) => {
382
- styleContainer.appendChild(el.cloneNode(true));
383
- });
384
- } else {
385
- const elements = self.__remote_next_css__[bundle];
386
- elements.forEach((el) => {
387
- document.head.appendChild(el);
388
- });
221
+ // src/runtime/namespace.ts
222
+ function getNamespace() {
223
+ const g = globalThis;
224
+ const existing = g.__remote_components__;
225
+ if (existing) {
226
+ return existing;
227
+ }
228
+ const ns = {
229
+ scopes: /* @__PURE__ */ new Map(),
230
+ chunkCache: {},
231
+ mountFns: {},
232
+ unmountFns: {},
233
+ bundleUrls: {},
234
+ moduleRegistry: {},
235
+ dispatcherRuntime: void 0,
236
+ hostSharedModules: {},
237
+ cssCache: {},
238
+ shadowRoots: {}
239
+ };
240
+ const nsRecord = ns;
241
+ for (const { global, prop } of LEGACY_ALIASES) {
242
+ const legacyValue = g[global];
243
+ if (legacyValue != null) {
244
+ nsRecord[prop] = legacyValue;
389
245
  }
390
- delete self.__NEXT_P;
391
- self.__NEXT_P = __NEXT_P_ORIGINAL;
392
- if (nextCssOriginal) {
393
- nextCssOriginal.parentNode?.appendChild(nextCssOriginal);
246
+ g[global] = ns[prop];
247
+ }
248
+ const gRecord = g;
249
+ for (const key of Object.keys(gRecord)) {
250
+ if (key.startsWith(SHADOW_ROOT_PREFIX)) {
251
+ const suffix = key.slice(SHADOW_ROOT_PREFIX.length);
252
+ ns.shadowRoots[suffix] = gRecord[key];
253
+ delete gRecord[key];
394
254
  }
395
- nextCss.remove();
396
- nextCssEnd.remove();
397
- return { Component, App };
398
255
  }
399
- return { Component: null, App: null };
256
+ g.__remote_components__ = ns;
257
+ return ns;
400
258
  }
401
- var init_next_client_pages_loader = __esm({
402
- "src/config/webpack/next-client-pages-loader.ts"() {
259
+ var SHADOW_ROOT_PREFIX, LEGACY_ALIASES;
260
+ var init_namespace = __esm({
261
+ "src/runtime/namespace.ts"() {
403
262
  "use strict";
404
- init_error();
263
+ SHADOW_ROOT_PREFIX = "__remote_components_shadowroot_";
264
+ LEGACY_ALIASES = [
265
+ { global: "__remote_component_scopes__", prop: "scopes" },
266
+ {
267
+ global: "__remote_components_turbopack_chunk_loader_promise__",
268
+ prop: "chunkCache"
269
+ },
270
+ { global: "__remote_script_entrypoint_mount__", prop: "mountFns" },
271
+ { global: "__remote_script_entrypoint_unmount__", prop: "unmountFns" },
272
+ { global: "__remote_bundle_url__", prop: "bundleUrls" },
273
+ { global: "__rc_module_registry__", prop: "moduleRegistry" },
274
+ {
275
+ global: "__remote_component_host_shared_modules__",
276
+ prop: "hostSharedModules"
277
+ },
278
+ { global: "__remote_next_css__", prop: "cssCache" }
279
+ ];
405
280
  }
406
281
  });
407
282
 
@@ -421,11 +296,7 @@ var init_patterns = __esm({
421
296
 
422
297
  // src/runtime/turbopack/remote-scope.ts
423
298
  function getRegistry() {
424
- const self = globalThis;
425
- if (!self.__remote_component_scopes__) {
426
- self.__remote_component_scopes__ = /* @__PURE__ */ new Map();
427
- }
428
- return self.__remote_component_scopes__;
299
+ return getNamespace().scopes;
429
300
  }
430
301
  function createScope(name, url, runtime, resolveClientUrl) {
431
302
  const isCrossOrigin = url.origin !== location.origin;
@@ -443,7 +314,8 @@ function createScope(name, url, runtime, resolveClientUrl) {
443
314
  resolveClientUrl,
444
315
  moduleCache: {},
445
316
  sharedModules: {},
446
- moduleGlobal: {}
317
+ moduleGlobal: {},
318
+ turbopackModules: []
447
319
  };
448
320
  }
449
321
  function registerScope(scope) {
@@ -485,6 +357,7 @@ var init_remote_scope = __esm({
485
357
  "src/runtime/turbopack/remote-scope.ts"() {
486
358
  "use strict";
487
359
  init_constants2();
360
+ init_namespace();
488
361
  init_patterns();
489
362
  init_utils();
490
363
  init_logger();
@@ -523,9 +396,9 @@ var init_remote_image_loader = __esm({
523
396
  // src/host/shared/polyfill.tsx
524
397
  import { jsx } from "react/jsx-runtime";
525
398
  function sharedPolyfills(shared, resolveClientUrl) {
526
- const self = globalThis;
399
+ const hostShared = getNamespace().hostSharedModules;
527
400
  const polyfill = {
528
- "next/dist/client/components/navigation": self.__remote_component_host_shared_modules__?.["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
401
+ "next/dist/client/components/navigation": hostShared["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
529
402
  useRouter() {
530
403
  return {
531
404
  push: (routerUrl) => {
@@ -556,7 +429,7 @@ function sharedPolyfills(shared, resolveClientUrl) {
556
429
  },
557
430
  __esModule: true
558
431
  })),
559
- "next/dist/client/app-dir/link": self.__remote_component_host_shared_modules__?.["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
432
+ "next/dist/client/app-dir/link": hostShared["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
560
433
  default: ({
561
434
  scroll: _,
562
435
  replace,
@@ -606,7 +479,7 @@ function sharedPolyfills(shared, resolveClientUrl) {
606
479
  },
607
480
  __esModule: true
608
481
  })),
609
- "next/dist/client/app-dir/form": self.__remote_component_host_shared_modules__?.["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
482
+ "next/dist/client/app-dir/form": hostShared["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
610
483
  default: () => {
611
484
  throw new Error("Next.js <Form> component not implemented");
612
485
  },
@@ -617,17 +490,17 @@ function sharedPolyfills(shared, resolveClientUrl) {
617
490
  // This gives us full next/image fidelity (fill, priority, srcSet, blur
618
491
  // placeholders, error handling) while routing image optimization through the
619
492
  // remote app's /_next/image endpoint.
620
- "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({
493
+ "next/dist/shared/lib/image-loader": hostShared["next/dist/shared/lib/image-loader"] ?? shared?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
621
494
  default: createRemoteImageLoader(bundle, resolveClientUrl),
622
495
  __esModule: true
623
496
  })),
624
- "next/dist/client/script": self.__remote_component_host_shared_modules__?.["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
497
+ "next/dist/client/script": hostShared["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
625
498
  // TODO: implement <Script> component for non-Next.js host applications
626
499
  // do not throw an error for now
627
500
  default: () => null,
628
501
  __esModule: true
629
502
  })),
630
- "next/router": self.__remote_component_host_shared_modules__?.["next/router"] ?? shared?.["next/router"] ?? (() => (
503
+ "next/router": hostShared["next/router"] ?? shared?.["next/router"] ?? (() => (
631
504
  // TODO: incomplete implementation
632
505
  Promise.resolve({
633
506
  useRouter() {
@@ -666,170 +539,295 @@ var init_polyfill = __esm({
666
539
  "src/host/shared/polyfill.tsx"() {
667
540
  "use strict";
668
541
  init_remote_image_loader();
542
+ init_namespace();
669
543
  init_logger();
670
544
  }
671
545
  });
672
546
 
673
- // src/runtime/loaders/script-loader.ts
674
- async function loadScripts(scripts, resolveClientUrl) {
675
- await Promise.all(
676
- scripts.map((script) => {
677
- return new Promise((resolve, reject) => {
678
- const newSrc = new URL(
679
- // remove the remote component bundle name identifier from the script src
680
- script.src.replace(NEXT_BUNDLE_PATH_RE, "/_next/"),
681
- location.origin
682
- ).href;
683
- const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;
684
- const alreadyLoaded = Array.from(
685
- document.querySelectorAll("script[src]")
686
- ).some((s) => s.src === resolvedSrc);
687
- if (alreadyLoaded) {
688
- resolve();
689
- return;
547
+ // src/host/shared/shared-module-resolver.ts
548
+ function buildCoreShared(userShared) {
549
+ return {
550
+ react: async () => (await import("react")).default,
551
+ "react-dom": async () => (await import("react-dom")).default,
552
+ "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
553
+ "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
554
+ "react-dom/client": async () => (await import("react-dom/client")).default,
555
+ ...userShared
556
+ };
557
+ }
558
+ function buildHostShared(userShared, resolveClientUrl, options) {
559
+ const self = globalThis;
560
+ const result = {
561
+ ...sharedPolyfills(userShared, resolveClientUrl),
562
+ ...self.__remote_component_host_shared_modules__,
563
+ ...userShared
564
+ };
565
+ if (options?.includeRemoteComponentShared) {
566
+ Object.assign(result, self.__remote_component_shared__);
567
+ }
568
+ return result;
569
+ }
570
+ async function buildWebpackResolve(hostShared, remoteShared, bundle, reactModules, callerTag = "SharedModuleResolver") {
571
+ const resolve = {
572
+ ...reactModules,
573
+ ...Object.entries(remoteShared).reduce(
574
+ (acc, [key, value]) => {
575
+ if (typeof hostShared[value] !== "undefined") {
576
+ acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
577
+ } else {
578
+ logDebug(
579
+ callerTag,
580
+ `Remote requests "${value}" but host doesn't provide it`
581
+ );
690
582
  }
691
- const newScript = document.createElement("script");
692
- newScript.onload = () => resolve();
693
- newScript.onerror = () => {
694
- const isProxied = isProxiedUrl(resolvedSrc);
695
- if (isProxied) {
696
- reject(failedProxiedAssetError("script", newSrc, resolvedSrc));
697
- } else {
698
- warnCrossOriginFetchError("ScriptLoader", newSrc);
699
- reject(
700
- new RemoteComponentsError(
701
- `Failed to load <script src="${newSrc}"> for Remote Component. Check the URL is correct.`
702
- )
703
- );
704
- }
705
- };
706
- newScript.src = resolvedSrc;
707
- newScript.async = true;
708
- document.head.appendChild(newScript);
709
- });
583
+ return acc;
584
+ },
585
+ {}
586
+ )
587
+ };
588
+ await Promise.all(
589
+ Object.entries(resolve).map(async ([key, value]) => {
590
+ if (typeof value === "function") {
591
+ resolve[key] = await value(bundle);
592
+ }
593
+ return Promise.resolve(value);
710
594
  })
711
595
  );
596
+ return resolve;
712
597
  }
713
- var init_script_loader = __esm({
714
- "src/runtime/loaders/script-loader.ts"() {
598
+ var CORE_REACT_PATH_MAP, VENDOR_SHARED;
599
+ var init_shared_module_resolver = __esm({
600
+ "src/host/shared/shared-module-resolver.ts"() {
715
601
  "use strict";
716
- init_patterns();
717
- init_protected_rc_fallback();
718
- init_error();
602
+ init_polyfill();
719
603
  init_logger();
604
+ CORE_REACT_PATH_MAP = {
605
+ react: "/react/index.js",
606
+ "react/jsx-dev-runtime": "/react/jsx-dev-runtime.js",
607
+ "react/jsx-runtime": "/react/jsx-runtime.js",
608
+ "react-dom": "/react-dom/index.js",
609
+ "react-dom/client": "/react-dom/client.js"
610
+ };
611
+ VENDOR_SHARED = Object.fromEntries(
612
+ Object.entries(CORE_REACT_PATH_MAP).filter(([key]) => key !== "react-dom/client").map(([key, path]) => [key, `'${path}'`])
613
+ );
720
614
  }
721
615
  });
722
616
 
723
- // src/host/html/runtime/webpack.ts
724
- var webpack_exports = {};
725
- __export(webpack_exports, {
726
- webpackRuntime: () => webpackRuntime
727
- });
728
- async function webpackRuntime(bundle, shared, remoteShared, resolveClientUrl) {
617
+ // src/config/webpack/apply-shared-modules.ts
618
+ function applySharedModules(bundle, resolve) {
619
+ logDebug(
620
+ "SharedModules",
621
+ `applySharedModules called for bundle: "${bundle}"`
622
+ );
623
+ logDebug(
624
+ "SharedModules",
625
+ `Shared modules to resolve: ${Object.keys(resolve)}`
626
+ );
729
627
  const self = globalThis;
730
- if (!self.__DISABLE_WEBPACK_EXEC__) {
731
- self.__DISABLE_WEBPACK_EXEC__ = {};
732
- }
733
- self.__DISABLE_WEBPACK_EXEC__[bundle] = true;
734
- if (typeof self.__webpack_require__ !== "function" && self.__webpack_require_type__ !== "turbopack") {
735
- self.__webpack_require__ = (remoteId) => {
736
- const re = /\[(?<bundle>[^\]]+)\] (?<id>.*)/;
737
- const match = re.exec(remoteId);
738
- const remoteBundle = match?.groups?.bundle;
739
- const id = match?.groups?.id;
740
- if (!(id && remoteBundle)) {
741
- throw new RemoteComponentsError(
742
- `Remote Component module "${remoteId}" not found. Did you forget to wrap the Next.js config with \`withRemoteComponentsConfig\` on both host and remote?`
743
- );
744
- }
745
- if (typeof self.__remote_webpack_require__?.[remoteBundle] !== "function") {
746
- throw new RemoteComponentsError(
747
- `Remote Components are not available in "${remoteBundle}". Did you forget to wrap the Next.js config with \`withRemoteComponentsConfig\` on both host and remote?`
628
+ const scope = getScope(bundle);
629
+ const webpackBundle = scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];
630
+ if (webpackBundle) {
631
+ const modulePaths = Object.keys(
632
+ self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {}
633
+ );
634
+ logDebug(
635
+ "SharedModules",
636
+ `Available module paths for bundle "${bundle}": ${modulePaths}`
637
+ );
638
+ for (const [key, value] of Object.entries(resolve)) {
639
+ const exactIds = modulePaths.filter((p) => p === key);
640
+ const ids = exactIds.length > 0 ? exactIds : modulePaths.filter((p) => p.includes(key));
641
+ if (ids.length === 0) {
642
+ logDebug(
643
+ "SharedModules",
644
+ `No matching module path found for shared module "${key}"`
748
645
  );
749
646
  }
750
- return self.__remote_webpack_require__[remoteBundle](id);
751
- };
752
- self.__webpack_chunk_load__ = () => {
753
- return Promise.resolve([]);
754
- };
755
- }
756
- const {
757
- default: { createFromReadableStream }
758
- } = await import("react-server-dom-webpack/client.browser");
759
- async function preloadScripts(scripts, url, remoteBundle, _) {
760
- const scriptSrcs = scripts.flatMap((script) => {
761
- const scriptSrc = script.getAttribute("src") || script.getAttribute("data-src");
762
- script.parentElement?.removeChild(script);
763
- if (!scriptSrc)
764
- return [];
765
- return [
766
- {
767
- src: new URL(scriptSrc.replace(NEXT_BUNDLE_PATH_RE, "/_next/"), url).href
768
- }
769
- ];
770
- });
771
- await loadScripts(scriptSrcs, resolveClientUrl);
772
- const hostShared = {
773
- ...sharedPolyfills(shared, resolveClientUrl),
774
- ...self.__remote_component_host_shared_modules__,
775
- ...shared
776
- };
777
- const resolve = {
778
- "/react/index.js": (await import("react")).default,
779
- "/react/jsx-dev-runtime.js": (await import("react/jsx-dev-runtime")).default,
780
- "/react/jsx-runtime.js": (await import("react/jsx-runtime")).default,
781
- "/react-dom/index.js": (await import("react-dom")).default,
782
- "/react-dom/client.js": (await import("react-dom/client")).default,
783
- ...Object.entries(remoteShared ?? {}).reduce(
784
- (acc, [key, value]) => {
785
- if (typeof hostShared[value] !== "undefined") {
786
- acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
647
+ for (const id of ids) {
648
+ if (webpackBundle.m) {
649
+ const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
650
+ if (resolvedId !== id) {
651
+ logDebug(
652
+ "SharedModules",
653
+ `Mapped module id: "${id}" -> "${resolvedId}"`
654
+ );
787
655
  }
788
- return acc;
789
- },
790
- {}
791
- )
792
- };
793
- await Promise.all(
794
- Object.entries(resolve).map(async ([key, value]) => {
795
- if (typeof value === "function") {
796
- resolve[key] = await value(remoteBundle);
656
+ webpackBundle.m[resolvedId] = (module) => {
657
+ module.exports = value;
658
+ };
659
+ } else {
660
+ logWarn(
661
+ "SharedModules",
662
+ `webpackBundle.m is not available for bundle "${bundle}" \u2014 ${DEDUPLICATION_SKIPPED}`
663
+ );
797
664
  }
798
- return Promise.resolve(value);
799
- })
665
+ }
666
+ }
667
+ } else {
668
+ logWarn(
669
+ "SharedModules",
670
+ `No webpack require found for bundle "${bundle}" \u2014 ${DEDUPLICATION_SKIPPED}`
671
+ );
672
+ logDebug(
673
+ "SharedModules",
674
+ `Available bundles: ${Object.keys(self.__remote_webpack_require__ ?? {})}`
800
675
  );
801
- applySharedModules(remoteBundle, resolve);
802
676
  }
803
- return {
804
- self,
805
- createFromReadableStream,
806
- applySharedModules,
807
- nextClientPagesLoader,
808
- preloadScripts
809
- };
810
677
  }
811
- var init_webpack = __esm({
812
- "src/host/html/runtime/webpack.ts"() {
678
+ var DEDUPLICATION_SKIPPED;
679
+ var init_apply_shared_modules = __esm({
680
+ "src/config/webpack/apply-shared-modules.ts"() {
813
681
  "use strict";
814
- init_apply_shared_modules();
815
- init_next_client_pages_loader();
816
- init_polyfill();
817
- init_script_loader();
818
- init_patterns();
682
+ init_remote_scope();
683
+ init_logger();
684
+ DEDUPLICATION_SKIPPED = "shared module deduplication skipped. The remote may load its own copy of shared dependencies.";
685
+ }
686
+ });
687
+
688
+ // src/config/webpack/next-client-pages-loader.ts
689
+ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
690
+ const self = globalThis;
691
+ const nextCssOriginal = document.querySelector(
692
+ `[id="__next_css__DO_NOT_USE__"]:not([data-bundle="${bundle}"][data-route="${route}"])`
693
+ );
694
+ if (nextCssOriginal) {
695
+ nextCssOriginal.parentNode?.removeChild(nextCssOriginal);
696
+ }
697
+ const nextCss = document.createElement("noscript");
698
+ nextCss.id = "__next_css__DO_NOT_USE__";
699
+ nextCss.setAttribute("data-bundle", bundle);
700
+ nextCss.setAttribute("data-route", route);
701
+ const nextCssEnd = document.createElement("noscript");
702
+ nextCssEnd.id = "__next_css__DO_NOT_USE_END__";
703
+ nextCssEnd.setAttribute("data-bundle", bundle);
704
+ nextCssEnd.setAttribute("data-route", route);
705
+ document.head.appendChild(nextCssEnd);
706
+ document.head.appendChild(nextCss);
707
+ const componentLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
708
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
709
+ ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
710
+ (key) => key.includes("/next/dist/client/page-loader.js")
711
+ ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
712
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
713
+ ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
714
+ (key) => key.includes("/next/dist/client/page-loader.js")
715
+ ) ?? ""] ?? -1;
716
+ const appLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
717
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
718
+ ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
719
+ (key) => key.includes("/next/dist/client/page-loader.js")
720
+ ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
721
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
722
+ ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
723
+ (key) => key.includes("/next/dist/client/page-loader.js")
724
+ ) ?? ""] ?? -1;
725
+ if (!(componentLoaderChunk && appLoaderChunk)) {
726
+ throw new RemoteComponentsError(
727
+ `Next.js client pages loader not found in bundle "${bundle}".`
728
+ );
729
+ }
730
+ const __NEXT_P_ORIGINAL = self.__NEXT_P;
731
+ const selfOriginal = self;
732
+ delete selfOriginal.__NEXT_P;
733
+ self.__remote_webpack_require__?.[bundle]?.(
734
+ self.__remote_webpack_require__[bundle].type !== "turbopack" ? componentLoaderChunk : `[${bundle}] ${componentLoaderChunk}`
735
+ );
736
+ if (typeof appLoaderChunk === "string" || typeof appLoaderChunk === "number" && appLoaderChunk !== -1) {
737
+ self.__remote_webpack_require__?.[bundle]?.(
738
+ self.__remote_webpack_require__[bundle].type !== "turbopack" ? appLoaderChunk : `[${bundle}] ${appLoaderChunk}`
739
+ );
740
+ }
741
+ if (self.__NEXT_P) {
742
+ const [, componentLoader] = self.__NEXT_P[0] ?? [
743
+ void 0,
744
+ () => ({ default: null })
745
+ ];
746
+ const [, appLoader] = self.__NEXT_P[2] ?? [
747
+ void 0,
748
+ () => ({
749
+ default: null
750
+ })
751
+ ];
752
+ const { default: Component } = componentLoader();
753
+ const { default: App } = appLoader();
754
+ const cssCache = getNamespace().cssCache;
755
+ if (!cssCache[bundle]) {
756
+ const cssRE = /\.s?css$/;
757
+ Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
758
+ self.__remote_webpack_require__?.[bundle]?.(id);
759
+ });
760
+ Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {}).filter((path) => cssRE.test(path)).forEach((path) => {
761
+ const id = self.__remote_webpack_module_map__?.[bundle]?.[path];
762
+ if (id) {
763
+ self.__remote_webpack_require__?.[bundle]?.(id);
764
+ }
765
+ });
766
+ const elements = [];
767
+ let node = nextCss.previousSibling;
768
+ while (node && node !== nextCssEnd) {
769
+ elements.push(node);
770
+ node.remove();
771
+ node = nextCss.previousSibling;
772
+ }
773
+ cssCache[bundle] = elements;
774
+ }
775
+ if (styleContainer) {
776
+ const elements = cssCache[bundle];
777
+ elements.forEach((el) => {
778
+ styleContainer.appendChild(el.cloneNode(true));
779
+ });
780
+ } else {
781
+ const elements = cssCache[bundle];
782
+ elements.forEach((el) => {
783
+ document.head.appendChild(el);
784
+ });
785
+ }
786
+ delete self.__NEXT_P;
787
+ self.__NEXT_P = __NEXT_P_ORIGINAL;
788
+ if (nextCssOriginal) {
789
+ nextCssOriginal.parentNode?.appendChild(nextCssOriginal);
790
+ }
791
+ nextCss.remove();
792
+ nextCssEnd.remove();
793
+ return { Component, App };
794
+ }
795
+ return { Component: null, App: null };
796
+ }
797
+ var init_next_client_pages_loader = __esm({
798
+ "src/config/webpack/next-client-pages-loader.ts"() {
799
+ "use strict";
800
+ init_namespace();
819
801
  init_error();
820
802
  }
821
803
  });
822
804
 
823
805
  // src/runtime/turbopack/patterns.ts
824
- var REMOTE_SHARED_MARKER_RE, REMOTE_SHARED_ASSIGNMENT_RE, ASYNC_MODULE_LOADER_RE, ASYNC_MODULE_RESOLVE_RE, ASYNC_MODULE_ALL_RE, TURBOPACK_GLOBAL_RE;
806
+ function stripQuotes(value) {
807
+ if (value.startsWith('"') && value.endsWith('"')) {
808
+ return value.slice(1, -1);
809
+ }
810
+ return value;
811
+ }
812
+ function extractGroup(re, input, group) {
813
+ const raw = re.exec(input)?.groups?.[group];
814
+ return raw ? stripQuotes(raw) : void 0;
815
+ }
816
+ var MODULE_ID_PATTERN, REMOTE_SHARED_MARKER_RE, REMOTE_SHARED_ASSIGNMENT_RE, ASYNC_MODULE_LOADER_RE, ASYNC_MODULE_CALLBACK_RE, TURBOPACK_GLOBAL_RE;
825
817
  var init_patterns2 = __esm({
826
818
  "src/runtime/turbopack/patterns.ts"() {
827
819
  "use strict";
820
+ MODULE_ID_PATTERN = '"[^"]+"|[0-9]+';
828
821
  REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
829
- REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|[a-z])\.A\((?<sharedModuleId>[0-9]+)\)/;
830
- ASYNC_MODULE_LOADER_RE = /(?:__turbopack_context__|e)\.A\((?<asyncSharedModuleId>[0-9]+)\)/;
831
- ASYNC_MODULE_RESOLVE_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<inner>parentImport|e)=>Promise\.resolve\(\)\.then\(\(\)=>\k<inner>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
832
- 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]+)\)\)\)\}/;
822
+ REMOTE_SHARED_ASSIGNMENT_RE = new RegExp(
823
+ `\\.TURBOPACK_REMOTE_SHARED\\s*=\\s*await (?:__turbopack_context__|[a-z])\\.A\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
824
+ );
825
+ ASYNC_MODULE_LOADER_RE = new RegExp(
826
+ `(?:__turbopack_context__|[a-z])\\.A\\((?<asyncSharedModuleId>${MODULE_ID_PATTERN})\\)`
827
+ );
828
+ ASYNC_MODULE_CALLBACK_RE = new RegExp(
829
+ `(?:parentImport|[a-z])\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
830
+ );
833
831
  TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
834
832
  }
835
833
  });
@@ -841,6 +839,7 @@ function loadChunkWithScope(scope, chunkId) {
841
839
  `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
842
840
  );
843
841
  const self = globalThis;
842
+ const ns = getNamespace();
844
843
  const { bundle, path, prefix } = parseRemoteId(chunkId);
845
844
  const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
846
845
  if (remoteRuntime === RUNTIME_WEBPACK) {
@@ -851,35 +850,31 @@ function loadChunkWithScope(scope, chunkId) {
851
850
  if (url.endsWith(".css")) {
852
851
  return;
853
852
  }
854
- if (!self.__remote_components_turbopack_chunk_loader_promise__) {
855
- self.__remote_components_turbopack_chunk_loader_promise__ = {};
856
- }
857
- if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
858
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
853
+ if (ns.chunkCache[url]) {
854
+ logDebug("ChunkLoader", `Cache hit for "${chunkId}" (url="${url}")`);
855
+ return ns.chunkCache[url];
859
856
  }
860
857
  const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
861
858
  if (resolvedUrl !== url) {
862
859
  logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
863
860
  }
864
- self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise(
865
- (resolve, reject) => {
866
- fetch(resolvedUrl).then((res) => res.text()).then((code) => {
867
- const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
868
- if (hasTurbopack) {
869
- return handleTurbopackChunk(code, scope, url);
870
- }
871
- }).then(resolve).catch((error) => {
872
- const isProxied = isProxiedUrl(resolvedUrl);
873
- if (isProxied) {
874
- reject(failedProxiedAssetError("chunk", url, resolvedUrl));
875
- } else {
876
- warnCrossOriginFetchError("ChunkLoader", url);
877
- reject(error);
878
- }
879
- });
880
- }
881
- );
882
- return self.__remote_components_turbopack_chunk_loader_promise__[url];
861
+ ns.chunkCache[url] = new Promise((resolve, reject) => {
862
+ fetch(resolvedUrl).then((res) => res.text()).then((code) => {
863
+ const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
864
+ if (hasTurbopack) {
865
+ return handleTurbopackChunk(code, scope, url);
866
+ }
867
+ }).then(resolve).catch((error) => {
868
+ const isProxied = isProxiedUrl(resolvedUrl);
869
+ if (isProxied) {
870
+ reject(failedProxiedAssetError("chunk", url, resolvedUrl));
871
+ } else {
872
+ warnCrossOriginFetchError("ChunkLoader", url);
873
+ reject(error);
874
+ }
875
+ });
876
+ });
877
+ return ns.chunkCache[url];
883
878
  }
884
879
  function createChunkDispatcher() {
885
880
  return function __chunk_dispatcher__(chunkId, scriptBundle) {
@@ -928,19 +923,39 @@ async function handleTurbopackChunk(code, scope, url) {
928
923
  `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
929
924
  );
930
925
  if (!self[`TURBOPACK_${globalKey}`]) {
931
- const chunkData = [];
932
- const turbopackObject = {
933
- push: (item) => {
934
- if (Array.isArray(item)) {
935
- chunkData.push(item);
936
- } else {
937
- chunkData.push([item]);
926
+ const wrapPush = (target) => {
927
+ const originalPush = target.push;
928
+ if (typeof originalPush !== "function")
929
+ return target;
930
+ target.push = (...items) => {
931
+ for (const item of items) {
932
+ if (Array.isArray(item)) {
933
+ for (const entry of item) {
934
+ scope.turbopackModules.push(entry);
935
+ }
936
+ } else {
937
+ scope.turbopackModules.push(item);
938
+ }
938
939
  }
939
- return chunkData.length;
940
- },
941
- __chunks__: chunkData
940
+ return originalPush.apply(target, items);
941
+ };
942
+ return target;
942
943
  };
943
- self[`TURBOPACK_${globalKey}`] = turbopackObject;
944
+ const globalProp = `TURBOPACK_${globalKey}`;
945
+ let currentValue = wrapPush([]);
946
+ Object.defineProperty(self, globalProp, {
947
+ get() {
948
+ return currentValue;
949
+ },
950
+ set(newValue) {
951
+ if (newValue && typeof newValue === "object") {
952
+ wrapPush(newValue);
953
+ }
954
+ currentValue = newValue;
955
+ },
956
+ configurable: true,
957
+ enumerable: true
958
+ });
944
959
  }
945
960
  await new Promise((scriptResolve, scriptReject) => {
946
961
  const blob = new Blob([transformedCode], {
@@ -992,6 +1007,7 @@ var init_chunk_loader = __esm({
992
1007
  "src/runtime/turbopack/chunk-loader.ts"() {
993
1008
  "use strict";
994
1009
  init_constants2();
1010
+ init_namespace();
995
1011
  init_patterns();
996
1012
  init_protected_rc_fallback();
997
1013
  init_error();
@@ -1003,13 +1019,13 @@ var init_chunk_loader = __esm({
1003
1019
 
1004
1020
  // src/runtime/turbopack/shared-modules.ts
1005
1021
  function getTurbopackModules(scope) {
1022
+ if (scope.turbopackModules.length > 0) {
1023
+ return scope.turbopackModules;
1024
+ }
1006
1025
  const self = globalThis;
1007
1026
  const raw = self[`TURBOPACK_${scope.globalKey}`];
1008
1027
  if (!raw)
1009
1028
  return void 0;
1010
- if (typeof raw === "object" && "__chunks__" in raw) {
1011
- return raw.__chunks__.flat();
1012
- }
1013
1029
  if (Array.isArray(raw)) {
1014
1030
  return raw.flat();
1015
1031
  }
@@ -1033,7 +1049,11 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1033
1049
  if (sharedModuleInitializerIndex > 0) {
1034
1050
  const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1035
1051
  const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1036
- const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1052
+ const sharedModuleId = extractGroup(
1053
+ REMOTE_SHARED_ASSIGNMENT_RE,
1054
+ sharedModuleInitializerCode,
1055
+ "sharedModuleId"
1056
+ );
1037
1057
  if (sharedModuleId) {
1038
1058
  const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1039
1059
  scope,
@@ -1091,20 +1111,22 @@ async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}
1091
1111
  }
1092
1112
  function extractSharedModuleIds(shared, scope) {
1093
1113
  return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1094
- const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1114
+ const asyncSharedModuleId = extractGroup(
1115
+ ASYNC_MODULE_LOADER_RE,
1116
+ value.toString(),
1117
+ "asyncSharedModuleId"
1118
+ );
1095
1119
  if (asyncSharedModuleId) {
1096
- const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1097
- let asyncSharedModule;
1098
- const turbopackModules = getTurbopackModules(scope) ?? [];
1099
- const asyncSharedModuleIdIndex = turbopackModules.indexOf(
1100
- asyncSharedModuleIdNumber
1120
+ const asyncSharedModule = findModuleInit(
1121
+ getTurbopackModules(scope),
1122
+ asyncSharedModuleId
1101
1123
  );
1102
- if (asyncSharedModuleIdIndex !== -1 && typeof turbopackModules[asyncSharedModuleIdIndex + 1] === "function") {
1103
- asyncSharedModule = turbopackModules[asyncSharedModuleIdIndex + 1];
1104
- }
1105
1124
  if (asyncSharedModule) {
1106
- const asyncSharedModuleCode = asyncSharedModule.toString();
1107
- const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1125
+ const sharedModuleId = extractGroup(
1126
+ ASYNC_MODULE_CALLBACK_RE,
1127
+ asyncSharedModule.toString(),
1128
+ "sharedModuleId"
1129
+ );
1108
1130
  acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1109
1131
  "__remote_shared_module_",
1110
1132
  ""
@@ -1206,9 +1228,17 @@ function findModuleInit(modules, moduleId) {
1206
1228
  if (idx >= 0) {
1207
1229
  return flat.slice(idx + 1).find((e) => typeof e === "function");
1208
1230
  }
1209
- return flat.find(
1210
- (e) => Boolean(e && typeof e === "object" && moduleId in e)
1211
- )?.[moduleId];
1231
+ for (const entry of flat) {
1232
+ if (!entry || typeof entry !== "object")
1233
+ continue;
1234
+ const obj = entry;
1235
+ if (moduleId in obj)
1236
+ return obj[moduleId];
1237
+ const prefixKey = Object.keys(obj).find((k) => k.startsWith(moduleId));
1238
+ if (prefixKey)
1239
+ return obj[prefixKey];
1240
+ }
1241
+ return void 0;
1212
1242
  }
1213
1243
  function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1214
1244
  const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
@@ -1287,7 +1317,10 @@ function createTurbopackContext(scope, exports, moduleExports, modules, moduleIn
1287
1317
  }
1288
1318
  if (typeof mod !== "object" || mod === null) {
1289
1319
  mod = { default: mod };
1290
- } else if (!("default" in mod) && mod.toString() !== "[object Module]") {
1320
+ } else if (!("default" in mod) && // ES module namespace objects have a null prototype, so calling
1321
+ // mod.toString() directly throws. Use Object.prototype.toString
1322
+ // to safely detect them.
1323
+ Object.prototype.toString.call(mod) !== "[object Module]") {
1291
1324
  try {
1292
1325
  mod.default = mod;
1293
1326
  } catch {
@@ -1360,21 +1393,38 @@ var init_module = __esm({
1360
1393
  }
1361
1394
  });
1362
1395
 
1363
- // src/runtime/turbopack/webpack-runtime.ts
1364
- async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
1396
+ // src/runtime/turbopack/remote-scope-setup.ts
1397
+ async function setupRemoteScope(runtime, scripts = [], url = new URL(location.href), bundle, resolveClientUrl) {
1365
1398
  const self = globalThis;
1399
+ const ns = getNamespace();
1366
1400
  const bundleName = bundle ?? "default";
1401
+ const existingScope = getScope(bundleName);
1402
+ if (existingScope && existingScope.url.origin === url.origin) {
1403
+ logDebug(
1404
+ "WebpackRuntime",
1405
+ `Reusing scope "${existingScope.scopedName}" (turbopackModules=${existingScope.turbopackModules.length})`
1406
+ );
1407
+ existingScope.resolveClientUrl = resolveClientUrl;
1408
+ if (runtime === RUNTIME_TURBOPACK) {
1409
+ await Promise.allSettled(
1410
+ scripts.map(
1411
+ (script) => script.src ? loadChunkWithScope(existingScope, script.src) : Promise.resolve(void 0)
1412
+ )
1413
+ );
1414
+ }
1415
+ return existingScope;
1416
+ }
1367
1417
  const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1368
1418
  registerScope(scope);
1369
- if (!self.__remote_bundle_url__) {
1370
- self.__remote_bundle_url__ = {};
1419
+ if (runtime === RUNTIME_WEBPACK && self.__remote_webpack_require__?.[bundleName]) {
1420
+ scope.webpackRequire = self.__remote_webpack_require__[bundleName];
1371
1421
  }
1372
- self.__remote_bundle_url__[bundleName] = url;
1422
+ ns.bundleUrls[bundleName] = url;
1373
1423
  if (scope.scopedName !== bundleName) {
1374
- self.__remote_bundle_url__[scope.scopedName] = url;
1424
+ ns.bundleUrls[scope.scopedName] = url;
1375
1425
  }
1376
1426
  self.__webpack_get_script_filename__ = () => null;
1377
- const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack";
1427
+ const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || ns.dispatcherRuntime !== "turbopack";
1378
1428
  if (willCreateDispatchers) {
1379
1429
  if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1380
1430
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
@@ -1382,6 +1432,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1382
1432
  }
1383
1433
  self.__webpack_chunk_load__ = createChunkDispatcher();
1384
1434
  self.__webpack_require__ = createModuleDispatcher(runtime);
1435
+ ns.dispatcherRuntime = runtime;
1385
1436
  self.__webpack_require_type__ = runtime;
1386
1437
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1387
1438
  self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
@@ -1409,15 +1460,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
1409
1460
  }
1410
1461
  }
1411
1462
  }
1412
- const coreShared = {
1413
- react: async () => (await import("react")).default,
1414
- "react-dom": async () => (await import("react-dom")).default,
1415
- "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
1416
- "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
1417
- "react-dom/client": async () => (await import("react-dom/client")).default,
1418
- ...shared
1419
- };
1420
- await initializeSharedModules(scope, coreShared, remoteShared);
1463
+ return scope;
1421
1464
  }
1422
1465
  function createModuleDispatcher(runtime) {
1423
1466
  return (id) => {
@@ -1434,6 +1477,9 @@ function createModuleDispatcher(runtime) {
1434
1477
  );
1435
1478
  try {
1436
1479
  if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1480
+ const scope2 = getScope(bundle);
1481
+ if (scope2?.webpackRequire)
1482
+ return scope2.webpackRequire(moduleId);
1437
1483
  return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1438
1484
  }
1439
1485
  const scope = getScope(bundleName);
@@ -1471,73 +1517,67 @@ function createModuleDispatcher(runtime) {
1471
1517
  }
1472
1518
  };
1473
1519
  }
1474
- var init_webpack_runtime = __esm({
1475
- "src/runtime/turbopack/webpack-runtime.ts"() {
1520
+ var init_remote_scope_setup = __esm({
1521
+ "src/runtime/turbopack/remote-scope-setup.ts"() {
1476
1522
  "use strict";
1477
1523
  init_constants2();
1524
+ init_namespace();
1478
1525
  init_patterns();
1479
1526
  init_error();
1480
1527
  init_logger();
1481
1528
  init_chunk_loader();
1482
1529
  init_module();
1483
1530
  init_remote_scope();
1484
- init_shared_modules();
1485
1531
  }
1486
1532
  });
1487
1533
 
1488
- // src/host/html/runtime/turbopack.ts
1489
- var turbopack_exports = {};
1490
- __export(turbopack_exports, {
1491
- turbopackRuntime: () => turbopackRuntime
1492
- });
1493
- async function turbopackRuntime(url, bundle, shared, remoteShared, resolveClientUrl) {
1494
- const self = globalThis;
1495
- const hostShared = {
1496
- ...sharedPolyfills(shared, resolveClientUrl),
1497
- ...self.__remote_component_host_shared_modules__,
1498
- ...shared,
1499
- ...self.__remote_component_shared__
1500
- };
1501
- await setupWebpackRuntime(
1502
- "turbopack",
1503
- [],
1504
- url,
1505
- bundle,
1506
- hostShared,
1507
- remoteShared,
1508
- resolveClientUrl
1509
- );
1510
- const {
1511
- default: { createFromReadableStream }
1512
- } = await import("react-server-dom-webpack/client.browser");
1513
- function preloadScripts(scripts, __) {
1514
- return setupWebpackRuntime(
1515
- "turbopack",
1516
- scripts.map((script) => ({
1517
- src: script.getAttribute("src") || script.getAttribute("data-src") || script.src
1518
- })),
1519
- url,
1520
- bundle,
1521
- hostShared,
1522
- remoteShared,
1523
- resolveClientUrl
1524
- );
1525
- }
1526
- return {
1527
- self,
1528
- createFromReadableStream,
1529
- applySharedModules,
1530
- nextClientPagesLoader,
1531
- preloadScripts
1532
- };
1534
+ // src/runtime/loaders/script-loader.ts
1535
+ async function loadScripts(scripts, resolveClientUrl) {
1536
+ await Promise.all(
1537
+ scripts.map((script) => {
1538
+ return new Promise((resolve, reject) => {
1539
+ const newSrc = new URL(
1540
+ // remove the remote component bundle name identifier from the script src
1541
+ script.src.replace(NEXT_BUNDLE_PATH_RE, "/_next/"),
1542
+ location.origin
1543
+ ).href;
1544
+ const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;
1545
+ const alreadyLoaded = Array.from(
1546
+ document.querySelectorAll("script[src]")
1547
+ ).some((s) => s.src === resolvedSrc);
1548
+ if (alreadyLoaded) {
1549
+ resolve();
1550
+ return;
1551
+ }
1552
+ const newScript = document.createElement("script");
1553
+ newScript.onload = () => resolve();
1554
+ newScript.onerror = () => {
1555
+ const isProxied = isProxiedUrl(resolvedSrc);
1556
+ if (isProxied) {
1557
+ reject(failedProxiedAssetError("script", newSrc, resolvedSrc));
1558
+ } else {
1559
+ warnCrossOriginFetchError("ScriptLoader", newSrc);
1560
+ reject(
1561
+ new RemoteComponentsError(
1562
+ `Failed to load <script src="${newSrc}"> for Remote Component. Check the URL is correct.`
1563
+ )
1564
+ );
1565
+ }
1566
+ };
1567
+ newScript.src = resolvedSrc;
1568
+ newScript.async = true;
1569
+ document.head.appendChild(newScript);
1570
+ });
1571
+ })
1572
+ );
1533
1573
  }
1534
- var init_turbopack = __esm({
1535
- "src/host/html/runtime/turbopack.ts"() {
1574
+ var init_script_loader = __esm({
1575
+ "src/runtime/loaders/script-loader.ts"() {
1536
1576
  "use strict";
1537
- init_apply_shared_modules();
1538
- init_next_client_pages_loader();
1539
- init_polyfill();
1540
- init_webpack_runtime();
1577
+ init_patterns();
1578
+ init_protected_rc_fallback();
1579
+ init_error();
1580
+ init_logger();
1541
1581
  }
1542
1582
  });
1543
1583
 
@@ -1584,10 +1624,9 @@ async function importViaCallback(absoluteSrc, resolveClientUrl) {
1584
1624
  URL.revokeObjectURL(moduleBlobUrl);
1585
1625
  URL.revokeObjectURL(wrapperBlobUrl);
1586
1626
  }
1587
- const registry = globalThis.__rc_module_registry__;
1588
- const mod = registry?.[absoluteSrc] ?? {};
1589
- if (registry)
1590
- delete registry[absoluteSrc];
1627
+ const registry = getNamespace().moduleRegistry;
1628
+ const mod = registry[absoluteSrc] ?? {};
1629
+ delete registry[absoluteSrc];
1591
1630
  return mod;
1592
1631
  }
1593
1632
  async function importDirectly(absoluteSrc) {
@@ -1617,12 +1656,12 @@ function resolveScriptSrc(script, url) {
1617
1656
  return rawSrc;
1618
1657
  }
1619
1658
  async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1620
- const self = globalThis;
1621
- if (self.__remote_script_entrypoint_mount__?.[url.href]) {
1622
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
1659
+ const ns = getNamespace();
1660
+ if (ns.mountFns[url.href]) {
1661
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1623
1662
  }
1624
- if (self.__remote_script_entrypoint_unmount__?.[url.href]) {
1625
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
1663
+ if (ns.unmountFns[url.href]) {
1664
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1626
1665
  }
1627
1666
  const mountUnmountSets = await Promise.all(
1628
1667
  scripts.map(async (script) => {
@@ -1634,25 +1673,19 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1634
1673
  URL.revokeObjectURL(src);
1635
1674
  }
1636
1675
  if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
1637
- if (!self.__remote_script_entrypoint_mount__) {
1638
- self.__remote_script_entrypoint_mount__ = {};
1676
+ if (!ns.mountFns[url.href]) {
1677
+ ns.mountFns[url.href] = /* @__PURE__ */ new Set();
1639
1678
  }
1640
- if (!self.__remote_script_entrypoint_mount__[url.href]) {
1641
- self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
1642
- }
1643
- self.__remote_script_entrypoint_mount__[url.href]?.add(
1679
+ ns.mountFns[url.href]?.add(
1644
1680
  mod.mount || mod.default?.mount || (() => {
1645
1681
  })
1646
1682
  );
1647
1683
  }
1648
1684
  if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
1649
- if (!self.__remote_script_entrypoint_unmount__) {
1650
- self.__remote_script_entrypoint_unmount__ = {};
1651
- }
1652
- if (!self.__remote_script_entrypoint_unmount__[url.href]) {
1653
- self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
1685
+ if (!ns.unmountFns[url.href]) {
1686
+ ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
1654
1687
  }
1655
- self.__remote_script_entrypoint_unmount__[url.href]?.add(
1688
+ ns.unmountFns[url.href]?.add(
1656
1689
  mod.unmount || mod.default?.unmount || (() => {
1657
1690
  })
1658
1691
  );
@@ -1693,10 +1726,145 @@ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1693
1726
  var init_static_loader = __esm({
1694
1727
  "src/runtime/loaders/static-loader.ts"() {
1695
1728
  "use strict";
1729
+ init_namespace();
1696
1730
  init_logger();
1697
1731
  }
1698
1732
  });
1699
1733
 
1734
+ // src/host/html/runtime/webpack.ts
1735
+ var webpack_exports = {};
1736
+ __export(webpack_exports, {
1737
+ webpackRuntime: () => webpackRuntime
1738
+ });
1739
+ async function webpackRuntime(bundle, shared, remoteShared, resolveClientUrl) {
1740
+ const self = globalThis;
1741
+ if (!self.__DISABLE_WEBPACK_EXEC__) {
1742
+ self.__DISABLE_WEBPACK_EXEC__ = {};
1743
+ }
1744
+ self.__DISABLE_WEBPACK_EXEC__[bundle] = true;
1745
+ if (typeof self.__webpack_require__ !== "function" && self.__webpack_require_type__ !== "turbopack") {
1746
+ self.__webpack_require__ = (remoteId) => {
1747
+ const re = /\[(?<bundle>[^\]]+)\] (?<id>.*)/;
1748
+ const match = re.exec(remoteId);
1749
+ const remoteBundle = match?.groups?.bundle;
1750
+ const id = match?.groups?.id;
1751
+ if (!(id && remoteBundle)) {
1752
+ throw new RemoteComponentsError(
1753
+ `Remote Component module "${remoteId}" not found. Did you forget to wrap the Next.js config with \`withRemoteComponentsConfig\` on both host and remote?`
1754
+ );
1755
+ }
1756
+ if (typeof self.__remote_webpack_require__?.[remoteBundle] !== "function") {
1757
+ throw new RemoteComponentsError(
1758
+ `Remote Components are not available in "${remoteBundle}". Did you forget to wrap the Next.js config with \`withRemoteComponentsConfig\` on both host and remote?`
1759
+ );
1760
+ }
1761
+ return self.__remote_webpack_require__[remoteBundle](id);
1762
+ };
1763
+ self.__webpack_chunk_load__ = () => {
1764
+ return Promise.resolve([]);
1765
+ };
1766
+ }
1767
+ const {
1768
+ default: { createFromReadableStream }
1769
+ } = await import("react-server-dom-webpack/client.browser");
1770
+ async function preloadScripts(scripts, url, remoteBundle, _) {
1771
+ const scriptSrcs = scripts.flatMap((script) => {
1772
+ const scriptSrc = script.getAttribute("src") || script.getAttribute("data-src");
1773
+ script.parentElement?.removeChild(script);
1774
+ if (!scriptSrc)
1775
+ return [];
1776
+ return [
1777
+ {
1778
+ src: new URL(scriptSrc.replace(NEXT_BUNDLE_PATH_RE, "/_next/"), url).href
1779
+ }
1780
+ ];
1781
+ });
1782
+ await loadScripts(scriptSrcs, resolveClientUrl);
1783
+ const hostShared = buildHostShared(shared, resolveClientUrl);
1784
+ const resolve = await buildWebpackResolve(
1785
+ hostShared,
1786
+ remoteShared ?? {},
1787
+ remoteBundle,
1788
+ {
1789
+ "/react/index.js": (await import("react")).default,
1790
+ "/react/jsx-dev-runtime.js": (await import("react/jsx-dev-runtime")).default,
1791
+ "/react/jsx-runtime.js": (await import("react/jsx-runtime")).default,
1792
+ "/react-dom/index.js": (await import("react-dom")).default,
1793
+ "/react-dom/client.js": (await import("react-dom/client")).default
1794
+ },
1795
+ "WebpackRuntime"
1796
+ );
1797
+ applySharedModules(remoteBundle, resolve);
1798
+ }
1799
+ return {
1800
+ self,
1801
+ createFromReadableStream,
1802
+ applySharedModules,
1803
+ nextClientPagesLoader,
1804
+ preloadScripts
1805
+ };
1806
+ }
1807
+ var init_webpack = __esm({
1808
+ "src/host/html/runtime/webpack.ts"() {
1809
+ "use strict";
1810
+ init_apply_shared_modules();
1811
+ init_next_client_pages_loader();
1812
+ init_shared_module_resolver();
1813
+ init_script_loader();
1814
+ init_patterns();
1815
+ init_error();
1816
+ }
1817
+ });
1818
+
1819
+ // src/host/html/runtime/turbopack.ts
1820
+ var turbopack_exports = {};
1821
+ __export(turbopack_exports, {
1822
+ turbopackRuntime: () => turbopackRuntime
1823
+ });
1824
+ async function turbopackRuntime(url, bundle, shared, remoteShared, resolveClientUrl) {
1825
+ const self = globalThis;
1826
+ const hostShared = buildHostShared(shared, resolveClientUrl, {
1827
+ includeRemoteComponentShared: true
1828
+ });
1829
+ await setupRemoteScope("turbopack", [], url, bundle, resolveClientUrl);
1830
+ const {
1831
+ default: { createFromReadableStream }
1832
+ } = await import("react-server-dom-webpack/client.browser");
1833
+ async function preloadScripts(scripts, __) {
1834
+ const scope = await setupRemoteScope(
1835
+ "turbopack",
1836
+ scripts.map((script) => ({
1837
+ src: script.getAttribute("src") || script.getAttribute("data-src") || script.src
1838
+ })),
1839
+ url,
1840
+ bundle,
1841
+ resolveClientUrl
1842
+ );
1843
+ await initializeSharedModules(
1844
+ scope,
1845
+ buildCoreShared(hostShared),
1846
+ remoteShared ?? {}
1847
+ );
1848
+ }
1849
+ return {
1850
+ self,
1851
+ createFromReadableStream,
1852
+ applySharedModules,
1853
+ nextClientPagesLoader,
1854
+ preloadScripts
1855
+ };
1856
+ }
1857
+ var init_turbopack = __esm({
1858
+ "src/host/html/runtime/turbopack.ts"() {
1859
+ "use strict";
1860
+ init_apply_shared_modules();
1861
+ init_next_client_pages_loader();
1862
+ init_shared_module_resolver();
1863
+ init_remote_scope_setup();
1864
+ init_shared_modules();
1865
+ }
1866
+ });
1867
+
1700
1868
  // src/host/html/runtime/script.ts
1701
1869
  var script_exports = {};
1702
1870
  __export(script_exports, {
@@ -1784,37 +1952,36 @@ function getClientOrServerUrl(src, serverFallback) {
1784
1952
  return typeof src === "string" ? new URL(src, fallback) : src;
1785
1953
  }
1786
1954
 
1787
- // src/host/shared/state.ts
1788
- function createHostState() {
1955
+ // src/host/shared/lifecycle.ts
1956
+ function makeEventEmitter(element) {
1957
+ function dispatch(type, detail) {
1958
+ const event = new Event(type, { bubbles: true, composed: true });
1959
+ if (detail) {
1960
+ Object.assign(event, detail);
1961
+ }
1962
+ element.dispatchEvent(event);
1963
+ }
1789
1964
  return {
1790
- stage: "idle",
1791
- prevSrc: void 0,
1792
- prevUrl: void 0,
1793
- prevName: void 0,
1794
- prevIsRemoteComponent: false,
1795
- abortController: void 0
1965
+ beforeLoad(src) {
1966
+ dispatch("beforeload", { src });
1967
+ },
1968
+ load(src) {
1969
+ dispatch("load", { src });
1970
+ },
1971
+ error(error, src) {
1972
+ dispatch("error", src != null ? { error, src } : { error });
1973
+ },
1974
+ change(info) {
1975
+ dispatch("change", info);
1976
+ }
1796
1977
  };
1797
1978
  }
1798
1979
 
1799
- // src/host/utils/resolve-name-from-src.ts
1800
- function resolveNameFromSrc(src, defaultName) {
1801
- if (!src) {
1802
- return defaultName;
1803
- }
1804
- const hash = typeof src === "string" ? src : src.hash;
1805
- const hashIndex = hash.indexOf("#");
1806
- if (hashIndex < 0) {
1807
- return defaultName;
1808
- }
1809
- const name = hash.slice(hashIndex + 1);
1810
- return name || defaultName;
1811
- }
1812
-
1813
- // src/host/html/index.tsx
1814
- init_constants2();
1980
+ // src/host/shared/pipeline.ts
1981
+ init_shared_module_resolver();
1815
1982
 
1816
- // src/runtime/html/apply-origin.ts
1817
- var tagNames = [
1983
+ // src/runtime/html/html-spec.ts
1984
+ var ORIGIN_REWRITE_TAGS = [
1818
1985
  "img",
1819
1986
  "source",
1820
1987
  "video",
@@ -1825,10 +1992,37 @@ var tagNames = [
1825
1992
  "script",
1826
1993
  "link"
1827
1994
  ];
1995
+ var ID_SUFFIX_RSC = "_rsc";
1996
+ var ID_SUFFIX_SSR = "_ssr";
1997
+ var ID_SUFFIX_SHARED = "_shared";
1998
+ var DATA_BUNDLE = "data-bundle";
1999
+ var DATA_ROUTE = "data-route";
2000
+ var DATA_RUNTIME = "data-runtime";
2001
+ var DATA_TYPE = "data-type";
2002
+ var DATA_SRC = "data-src";
2003
+ var DATA_REMOTE_COMPONENTS_SHARED = "data-remote-components-shared";
2004
+ var TAG_REMOTE_COMPONENT = "remote-component";
2005
+ var NEXT_DATA_ID = "__NEXT_DATA__";
2006
+ var REMOTE_NEXT_DATA_ID = "__REMOTE_NEXT_DATA__";
2007
+ var NEXT_CONTAINER_ID = "__next";
2008
+
2009
+ // src/runtime/html/rewrite-srcset.ts
2010
+ function rewriteSrcset(srcset, base, resolve) {
2011
+ return srcset.split(",").map((entry) => {
2012
+ const [url, descriptor] = entry.trim().split(/\s+/);
2013
+ if (!url)
2014
+ return entry;
2015
+ const absoluteUrl = new URL(url, base).href;
2016
+ const resolvedUrl = resolve ? resolve(absoluteUrl) : absoluteUrl;
2017
+ return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
2018
+ }).join(", ");
2019
+ }
2020
+
2021
+ // src/runtime/html/apply-origin.ts
1828
2022
  function applyOriginToNodes(doc, url, resolveClientUrl) {
1829
2023
  if (url.origin !== location.origin) {
1830
2024
  const nodes = doc.querySelectorAll(
1831
- tagNames.map(
2025
+ ORIGIN_REWRITE_TAGS.map(
1832
2026
  (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
1833
2027
  ).join(",")
1834
2028
  );
@@ -1846,29 +2040,17 @@ function applyOriginToNodes(doc, url, resolveClientUrl) {
1846
2040
  );
1847
2041
  }
1848
2042
  if (node.hasAttribute("srcset")) {
1849
- const srcSet = node.getAttribute("srcset")?.split(",").map((entry) => {
1850
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
1851
- if (!urlPart)
1852
- return entry;
1853
- const absoluteUrl = new URL(urlPart, url).href;
1854
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
1855
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
1856
- }).join(", ");
1857
- if (srcSet) {
1858
- node.setAttribute("srcset", srcSet);
2043
+ const raw = node.getAttribute("srcset");
2044
+ if (raw) {
2045
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
2046
+ node.setAttribute("srcset", rewriteSrcset(raw, url, resolve));
1859
2047
  }
1860
2048
  }
1861
2049
  if (node.hasAttribute("imagesrcset")) {
1862
- const srcSet = node.getAttribute("imagesrcset")?.split(",").map((entry) => {
1863
- const [urlPart, descriptor] = entry.trim().split(/\s+/);
1864
- if (!urlPart)
1865
- return entry;
1866
- const absoluteUrl = new URL(urlPart, url).href;
1867
- const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
1868
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
1869
- }).join(", ");
1870
- if (srcSet) {
1871
- node.setAttribute("imagesrcset", srcSet);
2050
+ const raw = node.getAttribute("imagesrcset");
2051
+ if (raw) {
2052
+ const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
2053
+ node.setAttribute("imagesrcset", rewriteSrcset(raw, url, resolve));
1872
2054
  }
1873
2055
  }
1874
2056
  });
@@ -1914,26 +2096,28 @@ function buildMetadata(attrs, url) {
1914
2096
  // src/runtime/html/parse-remote-html.ts
1915
2097
  init_error();
1916
2098
  function validateSingleComponent(doc, name, url) {
1917
- 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}"]`)) {
2099
+ if (doc.querySelectorAll(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`).length > 1 && !doc.querySelector(
2100
+ `div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`
2101
+ ) || doc.querySelectorAll(`${TAG_REMOTE_COMPONENT}:not([src])`).length > 1 && !doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]`)) {
1918
2102
  throw multipleRemoteComponentsError(url);
1919
2103
  }
1920
2104
  }
1921
2105
  function findComponentElement(doc, name) {
1922
- 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])");
2106
+ 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])`);
1923
2107
  }
1924
2108
  function parseNextData(doc) {
1925
2109
  return JSON.parse(
1926
- (doc.querySelector("#__NEXT_DATA__") ?? doc.querySelector("#__REMOTE_NEXT_DATA__"))?.textContent ?? "null"
2110
+ (doc.querySelector(`#${NEXT_DATA_ID}`) ?? doc.querySelector(`#${REMOTE_NEXT_DATA_ID}`))?.textContent ?? "null"
1927
2111
  );
1928
2112
  }
1929
2113
  function resolveComponentName(component, nextData, fallbackName) {
1930
- const isRemoteComponent = component?.tagName.toLowerCase() === "remote-component";
1931
- const name = component?.getAttribute("id")?.replace(/_ssr$/, "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
2114
+ const isRemoteComponent = component?.tagName.toLowerCase() === TAG_REMOTE_COMPONENT;
2115
+ const name = component?.getAttribute("id")?.replace(new RegExp(`${ID_SUFFIX_SSR}$`), "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
1932
2116
  return { name, isRemoteComponent };
1933
2117
  }
1934
2118
  function extractRemoteShared(doc, name, nextData) {
1935
2119
  const remoteSharedEl = doc.querySelector(
1936
- `#${name}_shared[data-remote-components-shared]`
2120
+ `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`
1937
2121
  );
1938
2122
  const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
1939
2123
  remoteSharedEl?.remove();
@@ -1954,7 +2138,7 @@ function extractLinks(doc, component) {
1954
2138
  function extractScripts(doc, component, isRemoteComponent) {
1955
2139
  return Array.from(
1956
2140
  (isRemoteComponent ? component : doc).querySelectorAll(
1957
- "script[src],script[data-src]"
2141
+ `script[src],script[${DATA_SRC}]`
1958
2142
  )
1959
2143
  );
1960
2144
  }
@@ -1967,15 +2151,15 @@ function parseRemoteComponentDocument(doc, name, url) {
1967
2151
  nextData,
1968
2152
  name
1969
2153
  );
1970
- const rsc = doc.querySelector(`#${resolvedName}_rsc`);
2154
+ const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);
1971
2155
  const metadata = buildMetadata(
1972
2156
  {
1973
2157
  name: resolvedName,
1974
- bundle: component?.getAttribute("data-bundle") || nextData?.props.__REMOTE_COMPONENT__?.bundle,
1975
- route: component?.getAttribute("data-route") ?? nextData?.page,
1976
- runtime: component?.getAttribute("data-runtime") ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
2158
+ bundle: component?.getAttribute(DATA_BUNDLE) || nextData?.props.__REMOTE_COMPONENT__?.bundle,
2159
+ route: component?.getAttribute(DATA_ROUTE) ?? nextData?.page,
2160
+ runtime: component?.getAttribute(DATA_RUNTIME) ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
1977
2161
  id: component?.getAttribute("id"),
1978
- type: component?.getAttribute("data-type")
2162
+ type: component?.getAttribute(DATA_TYPE)
1979
2163
  },
1980
2164
  url
1981
2165
  );
@@ -2003,6 +2187,16 @@ function parseRemoteComponentDocument(doc, name, url) {
2003
2187
  };
2004
2188
  }
2005
2189
 
2190
+ // src/runtime/loaders/component-loader.ts
2191
+ init_apply_shared_modules();
2192
+ init_next_client_pages_loader();
2193
+ init_shared_module_resolver();
2194
+ import * as React from "react";
2195
+ import * as JSXDevRuntime from "react/jsx-dev-runtime";
2196
+ import * as JSXRuntime from "react/jsx-runtime";
2197
+ import * as ReactDOM from "react-dom";
2198
+ import * as ReactDOMClient from "react-dom/client";
2199
+
2006
2200
  // src/runtime/rsc.ts
2007
2201
  import { ReadableStream } from "web-streams-polyfill";
2008
2202
  function fixPayload(payload) {
@@ -2023,6 +2217,18 @@ function fixPayload(payload) {
2023
2217
  }
2024
2218
  }
2025
2219
  }
2220
+ function buildRSCChunks(rscName, data) {
2221
+ const chunks = [];
2222
+ for (const chunk of data) {
2223
+ for (const line of chunk.split("\n")) {
2224
+ const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
2225
+ if (match?.groups?.rsc) {
2226
+ chunks.push(JSON.parse(`"${match.groups.rsc}"`));
2227
+ }
2228
+ }
2229
+ }
2230
+ return chunks;
2231
+ }
2026
2232
  function createRSCStream(rscName, data) {
2027
2233
  return new ReadableStream({
2028
2234
  type: "bytes",
@@ -2030,16 +2236,11 @@ function createRSCStream(rscName, data) {
2030
2236
  const encoder = new TextEncoder();
2031
2237
  const self = globalThis;
2032
2238
  if (data.length > 0) {
2033
- data.forEach((chunk) => {
2034
- const lines = chunk.split("\n");
2035
- for (const line of lines) {
2036
- const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
2037
- if (match?.groups?.rsc) {
2038
- self[rscName] = self[rscName] ?? [];
2039
- self[rscName].push(JSON.parse(`"${match.groups.rsc}"`));
2040
- }
2041
- }
2042
- });
2239
+ const parsed = buildRSCChunks(rscName, data);
2240
+ if (parsed.length > 0) {
2241
+ self[rscName] = self[rscName] ?? [];
2242
+ self[rscName].push(...parsed);
2243
+ }
2043
2244
  }
2044
2245
  const allChunks = (self[rscName] ?? [`0:[null]
2045
2246
  `]).join("");
@@ -2069,6 +2270,75 @@ function createRSCStream(rscName, data) {
2069
2270
  });
2070
2271
  }
2071
2272
 
2273
+ // src/runtime/loaders/component-loader.ts
2274
+ init_remote_scope_setup();
2275
+ init_shared_modules();
2276
+ init_error();
2277
+ init_logger();
2278
+ init_script_loader();
2279
+
2280
+ // src/host/shared/pipeline.ts
2281
+ init_static_loader();
2282
+ init_patterns();
2283
+ init_utils();
2284
+ init_error();
2285
+ function preparePipeline(input) {
2286
+ const parser = new DOMParser();
2287
+ const doc = parser.parseFromString(input.html, "text/html");
2288
+ const parsed = parseRemoteComponentDocument(doc, input.name, input.url);
2289
+ const remoteShared = input.remoteShared ?? parsed.remoteShared;
2290
+ if ("__remote_components_missing_shared__" in remoteShared) {
2291
+ throw new RemoteComponentsError(
2292
+ remoteShared.__remote_components_missing_shared__
2293
+ );
2294
+ }
2295
+ applyOriginToNodes(doc, input.url, input.resolveClientUrl);
2296
+ const scriptDescriptors = buildScriptDescriptors(parsed.scripts, input.url);
2297
+ return { doc, parsed, scriptDescriptors };
2298
+ }
2299
+ function buildScriptDescriptors(scripts, url) {
2300
+ return scripts.map((script) => {
2301
+ const scriptSrc = script.getAttribute("data-src") || script.getAttribute("src") || script.src;
2302
+ const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(scriptSrc)?.groups ?? {
2303
+ prefix: void 0,
2304
+ id: scriptSrc
2305
+ };
2306
+ return {
2307
+ src: new URL(collapseDoubleSlashes(`${prefix ?? ""}${path}`), url).href
2308
+ };
2309
+ });
2310
+ }
2311
+
2312
+ // src/host/shared/state.ts
2313
+ function createHostState() {
2314
+ return {
2315
+ stage: "idle",
2316
+ prevSrc: void 0,
2317
+ prevUrl: void 0,
2318
+ prevName: void 0,
2319
+ prevIsRemoteComponent: false,
2320
+ abortController: void 0
2321
+ };
2322
+ }
2323
+
2324
+ // src/host/utils/resolve-name-from-src.ts
2325
+ function resolveNameFromSrc(src, defaultName) {
2326
+ if (!src) {
2327
+ return defaultName;
2328
+ }
2329
+ const hash = typeof src === "string" ? src : src.hash;
2330
+ const hashIndex = hash.indexOf("#");
2331
+ if (hashIndex < 0) {
2332
+ return defaultName;
2333
+ }
2334
+ const name = hash.slice(hashIndex + 1);
2335
+ return name || defaultName;
2336
+ }
2337
+
2338
+ // src/host/html/index.tsx
2339
+ init_constants2();
2340
+ init_namespace();
2341
+
2072
2342
  // src/runtime/url/resolve-client-url.ts
2073
2343
  function withRemoteSrc(resolveClientUrl, remoteSrc) {
2074
2344
  const remoteOrigin = parseOrigin(remoteSrc);
@@ -2223,6 +2493,7 @@ if (typeof HTMLElement !== "undefined") {
2223
2493
  hostState = createHostState();
2224
2494
  root = null;
2225
2495
  reactRoot;
2496
+ emitter = makeEventEmitter(this);
2226
2497
  onRequest;
2227
2498
  onResponse;
2228
2499
  resolveClientUrl;
@@ -2273,13 +2544,6 @@ if (typeof HTMLElement !== "undefined") {
2273
2544
  static get observedAttributes() {
2274
2545
  return ["src", "name", "mode"];
2275
2546
  }
2276
- dispatchLifecycleEvent(type, detail) {
2277
- const event = new Event(type, { bubbles: true, composed: true });
2278
- if (detail) {
2279
- Object.assign(event, detail);
2280
- }
2281
- this.dispatchEvent(event);
2282
- }
2283
2547
  attributeChangedCallback(name, oldValue, newValue) {
2284
2548
  if ((name === "src" || name === "name") && oldValue !== newValue) {
2285
2549
  if (this.src) {
@@ -2288,7 +2552,7 @@ if (typeof HTMLElement !== "undefined") {
2288
2552
  return;
2289
2553
  }
2290
2554
  logError("HtmlHost", "Error loading remote component.", e);
2291
- this.dispatchLifecycleEvent("error", { error: e, src: this.src });
2555
+ this.emitter.error(e, this.src);
2292
2556
  this.hostState.stage = "error";
2293
2557
  });
2294
2558
  }
@@ -2305,7 +2569,7 @@ if (typeof HTMLElement !== "undefined") {
2305
2569
  return;
2306
2570
  }
2307
2571
  logError("HtmlHost", "Error reloading remote component.", e);
2308
- this.dispatchLifecycleEvent("error", { error: e, src: this.src });
2572
+ this.emitter.error(e, this.src);
2309
2573
  });
2310
2574
  }
2311
2575
  }
@@ -2343,7 +2607,7 @@ if (typeof HTMLElement !== "undefined") {
2343
2607
  this.hostState.stage = "idle";
2344
2608
  }
2345
2609
  };
2346
- this.dispatchLifecycleEvent("beforeload", { src });
2610
+ this.emitter.beforeLoad(src ?? "");
2347
2611
  const remoteComponentChild = this.querySelector("div#__REMOTE_COMPONENT__") || this.querySelector("div[data-bundle][data-route]");
2348
2612
  if (!src && !remoteComponentChild) {
2349
2613
  throw new RemoteComponentsError('"src" attribute is required');
@@ -2391,13 +2655,14 @@ if (typeof HTMLElement !== "undefined") {
2391
2655
  return abandonLoad();
2392
2656
  }
2393
2657
  }
2394
- const parser = new DOMParser();
2395
- const doc = parser.parseFromString(html, "text/html");
2396
- const parsed = parseRemoteComponentDocument(
2397
- doc,
2398
- this.name,
2399
- url ?? new URL(window.location.href)
2400
- );
2658
+ const effectiveUrl = url ?? new URL(window.location.href);
2659
+ const { doc, parsed } = preparePipeline({
2660
+ html,
2661
+ name: this.name,
2662
+ url: effectiveUrl,
2663
+ shared: {},
2664
+ resolveClientUrl
2665
+ });
2401
2666
  const {
2402
2667
  component,
2403
2668
  name: resolvedName,
@@ -2415,11 +2680,7 @@ if (typeof HTMLElement !== "undefined") {
2415
2680
  this.name = resolvedName;
2416
2681
  this.bundle = parsedMetadata.bundle;
2417
2682
  if (url) {
2418
- const self2 = globalThis;
2419
- if (!self2.__remote_bundle_url__) {
2420
- self2.__remote_bundle_url__ = {};
2421
- }
2422
- self2.__remote_bundle_url__[this.bundle] = url;
2683
+ getNamespace().bundleUrls[this.bundle] = url;
2423
2684
  }
2424
2685
  const metadataEl = document.createElement("script");
2425
2686
  metadataEl.type = "application/json";
@@ -2435,30 +2696,25 @@ if (typeof HTMLElement !== "undefined") {
2435
2696
  this.previousElementSibling?.remove();
2436
2697
  }
2437
2698
  this.parentElement?.insertBefore(metadataEl, this);
2438
- if ("__remote_components_missing_shared__" in remoteShared) {
2439
- throw new RemoteComponentsError(
2440
- remoteShared.__remote_components_missing_shared__
2441
- );
2442
- }
2443
2699
  if (this.hostState.prevIsRemoteComponent) {
2444
2700
  if (this.hostState.prevUrl) {
2445
2701
  const prevUrl = this.hostState.prevUrl;
2446
- const self2 = globalThis;
2447
- if (self2.__remote_script_entrypoint_unmount__?.[prevUrl.href]) {
2702
+ const nsUnmount = getNamespace();
2703
+ if (nsUnmount.unmountFns[prevUrl.href]) {
2448
2704
  await Promise.all(
2449
- Array.from(
2450
- self2.__remote_script_entrypoint_unmount__[prevUrl.href] ?? []
2451
- ).map(async (unmount) => {
2452
- try {
2453
- await unmount(this.root);
2454
- } catch (e) {
2455
- logError(
2456
- "HtmlHost",
2457
- `Error while calling unmount() for Remote Component from ${prevUrl.href}.`,
2458
- e
2459
- );
2705
+ Array.from(nsUnmount.unmountFns[prevUrl.href] ?? []).map(
2706
+ async (unmount) => {
2707
+ try {
2708
+ await unmount(this.root);
2709
+ } catch (e) {
2710
+ logError(
2711
+ "HtmlHost",
2712
+ `Error while calling unmount() for Remote Component from ${prevUrl.href}.`,
2713
+ e
2714
+ );
2715
+ }
2460
2716
  }
2461
- })
2717
+ )
2462
2718
  );
2463
2719
  if (!isCurrentLoad()) {
2464
2720
  return abandonLoad();
@@ -2468,14 +2724,14 @@ if (typeof HTMLElement !== "undefined") {
2468
2724
  this.root.innerHTML = "";
2469
2725
  }
2470
2726
  if (this.hostState.prevSrc !== void 0) {
2471
- this.dispatchLifecycleEvent("change", {
2472
- previousSrc: this.hostState.prevSrc,
2473
- nextSrc: src,
2727
+ this.emitter.change({
2728
+ previousSrc: this.hostState.prevSrc ?? null,
2729
+ nextSrc: src ?? null,
2474
2730
  previousName: this.hostState.prevName,
2475
2731
  nextName: this.name
2476
2732
  });
2477
2733
  }
2478
- this.hostState.prevUrl = url ?? new URL(window.location.href);
2734
+ this.hostState.prevUrl = effectiveUrl;
2479
2735
  this.hostState.prevIsRemoteComponent = isRemoteComponent;
2480
2736
  this.hostState.prevSrc = src;
2481
2737
  this.hostState.prevName = this.name;
@@ -2508,11 +2764,6 @@ if (typeof HTMLElement !== "undefined") {
2508
2764
  return abandonLoad();
2509
2765
  }
2510
2766
  }
2511
- applyOriginToNodes(
2512
- doc,
2513
- url ?? new URL(window.location.href),
2514
- resolveClientUrl
2515
- );
2516
2767
  if (!this.reactRoot) {
2517
2768
  Array.from(component.children).forEach((el) => {
2518
2769
  if (!isRemoteComponent && el.tagName.toLowerCase() === "script") {
@@ -2587,7 +2838,7 @@ if (typeof HTMLElement !== "undefined") {
2587
2838
  preloadScripts
2588
2839
  } = await getRuntime(
2589
2840
  metadataObj.runtime,
2590
- url ?? new URL(window.location.href),
2841
+ effectiveUrl,
2591
2842
  this.bundle,
2592
2843
  {
2593
2844
  react: async () => (await import("react")).default,
@@ -2678,7 +2929,7 @@ if (typeof HTMLElement !== "undefined") {
2678
2929
  if (isCurrentLoad()) {
2679
2930
  this.hostState.stage = "loaded";
2680
2931
  }
2681
- this.dispatchLifecycleEvent("load", { src: this.src });
2932
+ this.emitter.load(this.src ?? "");
2682
2933
  }, [initial, name]);
2683
2934
  return Component;
2684
2935
  };
@@ -2722,9 +2973,7 @@ if (typeof HTMLElement !== "undefined") {
2722
2973
  if (isCurrentLoad()) {
2723
2974
  remoteComponent.hostState.stage = "loaded";
2724
2975
  }
2725
- remoteComponent.dispatchLifecycleEvent("load", {
2726
- src: remoteComponent.src
2727
- });
2976
+ remoteComponent.emitter.load(remoteComponent.src ?? "");
2728
2977
  }, [initial, remoteComponent]);
2729
2978
  return NextApp ? /* @__PURE__ */ jsx2(NextApp, { Component: NextComponent, ...nextData.props }) : /* @__PURE__ */ jsx2(NextComponent, { ...nextData.props });
2730
2979
  })(App, Component, this);
@@ -2749,25 +2998,25 @@ if (typeof HTMLElement !== "undefined") {
2749
2998
  if (this.fouc) {
2750
2999
  this.root.removeChild(this.fouc);
2751
3000
  }
2752
- } else if (self.__remote_script_entrypoint_mount__?.[url.href]) {
3001
+ } else if (getNamespace().mountFns[url.href]) {
2753
3002
  await Promise.all(
2754
- Array.from(
2755
- self.__remote_script_entrypoint_mount__[url.href] ?? []
2756
- ).map(async (mount) => {
2757
- try {
2758
- await mount(this.root);
2759
- } catch (e) {
2760
- logError(
2761
- "HtmlHost",
2762
- `Error while calling mount() for Remote Component from ${url.href}.`,
2763
- e
2764
- );
3003
+ Array.from(getNamespace().mountFns[url.href] ?? []).map(
3004
+ async (mount) => {
3005
+ try {
3006
+ await mount(this.root);
3007
+ } catch (e) {
3008
+ logError(
3009
+ "HtmlHost",
3010
+ `Error while calling mount() for Remote Component from ${url.href}.`,
3011
+ e
3012
+ );
3013
+ }
2765
3014
  }
2766
- })
3015
+ )
2767
3016
  );
2768
- this.dispatchLifecycleEvent("load", { src: this.src });
3017
+ this.emitter.load(this.src ?? "");
2769
3018
  } else {
2770
- this.dispatchLifecycleEvent("load", { src: this.src });
3019
+ this.emitter.load(this.src ?? "");
2771
3020
  }
2772
3021
  if (isCurrentLoad()) {
2773
3022
  this.hostState.stage = "loaded";
@@ -2777,14 +3026,9 @@ if (typeof HTMLElement !== "undefined") {
2777
3026
  customElements.define("remote-component", RemoteComponent);
2778
3027
  }
2779
3028
  function registerSharedModules(modules = {}) {
2780
- const self = globalThis;
2781
- if (!self.__remote_component_host_shared_modules__) {
2782
- self.__remote_component_host_shared_modules__ = {};
2783
- }
3029
+ const ns = getNamespace();
2784
3030
  Object.entries(modules).forEach(([key, value]) => {
2785
- if (self.__remote_component_host_shared_modules__) {
2786
- self.__remote_component_host_shared_modules__[key] = value;
2787
- }
3031
+ ns.hostSharedModules[key] = value;
2788
3032
  });
2789
3033
  }
2790
3034
  export {