remote-components 0.0.42 → 0.0.44

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 (85) hide show
  1. package/dist/{component-loader-2ca91ad8.d.ts → component-loader-26b1f55e.d.ts} +63 -1
  2. package/dist/html/host.cjs +55 -19
  3. package/dist/html/host.cjs.map +1 -1
  4. package/dist/html/host.js +55 -19
  5. package/dist/html/host.js.map +1 -1
  6. package/dist/internal/next/host/app-router-client.d.ts +30 -3
  7. package/dist/internal/next/remote/render-client.cjs +1 -1
  8. package/dist/internal/next/remote/render-client.cjs.map +1 -1
  9. package/dist/internal/next/remote/render-client.js +1 -1
  10. package/dist/internal/next/remote/render-client.js.map +1 -1
  11. package/dist/internal/shared/client/remote-component.cjs +29 -0
  12. package/dist/internal/shared/client/remote-component.cjs.map +1 -1
  13. package/dist/internal/shared/client/remote-component.d.ts +2 -2
  14. package/dist/internal/shared/client/remote-component.js +29 -0
  15. package/dist/internal/shared/client/remote-component.js.map +1 -1
  16. package/dist/internal/shared/ssr/dom-flight.d.ts +1 -1
  17. package/dist/internal/shared/ssr/fetch-headers.cjs +4 -6
  18. package/dist/internal/shared/ssr/fetch-headers.cjs.map +1 -1
  19. package/dist/internal/shared/ssr/fetch-headers.d.ts +1 -1
  20. package/dist/internal/shared/ssr/fetch-headers.js +4 -6
  21. package/dist/internal/shared/ssr/fetch-headers.js.map +1 -1
  22. package/dist/internal/shared/ssr/fetch-remote-component.cjs +14 -23
  23. package/dist/internal/shared/ssr/fetch-remote-component.cjs.map +1 -1
  24. package/dist/internal/shared/ssr/fetch-remote-component.d.ts +5 -9
  25. package/dist/internal/shared/ssr/fetch-remote-component.js +13 -21
  26. package/dist/internal/shared/ssr/fetch-remote-component.js.map +1 -1
  27. package/dist/internal/shared/ssr/fetch-with-hooks.cjs +40 -0
  28. package/dist/internal/shared/ssr/fetch-with-hooks.cjs.map +1 -0
  29. package/dist/internal/shared/ssr/fetch-with-hooks.d.ts +39 -0
  30. package/dist/internal/shared/ssr/fetch-with-hooks.js +16 -0
  31. package/dist/internal/shared/ssr/fetch-with-hooks.js.map +1 -0
  32. package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.cjs.map +1 -1
  33. package/dist/internal/shared/ssr/get-ssr-relative-path-base-url.js.map +1 -1
  34. package/dist/next/config.cjs +1 -9
  35. package/dist/next/config.cjs.map +1 -1
  36. package/dist/next/config.js +1 -9
  37. package/dist/next/config.js.map +1 -1
  38. package/dist/next/host/app-router-server.cjs +7 -8
  39. package/dist/next/host/app-router-server.cjs.map +1 -1
  40. package/dist/next/host/app-router-server.d.ts +13 -4
  41. package/dist/next/host/app-router-server.js +7 -8
  42. package/dist/next/host/app-router-server.js.map +1 -1
  43. package/dist/next/host/client/index.cjs +149 -72
  44. package/dist/next/host/client/index.cjs.map +1 -1
  45. package/dist/next/host/client/index.d.ts +2 -49
  46. package/dist/next/host/client/index.js +144 -66
  47. package/dist/next/host/client/index.js.map +1 -1
  48. package/dist/next/host/pages-router-client.cjs +62 -2
  49. package/dist/next/host/pages-router-client.cjs.map +1 -1
  50. package/dist/next/host/pages-router-client.d.ts +26 -1
  51. package/dist/next/host/pages-router-client.js +63 -3
  52. package/dist/next/host/pages-router-client.js.map +1 -1
  53. package/dist/next/host/pages-router-server.cjs +18 -22
  54. package/dist/next/host/pages-router-server.cjs.map +1 -1
  55. package/dist/next/host/pages-router-server.d.ts +36 -3
  56. package/dist/next/host/pages-router-server.js +18 -22
  57. package/dist/next/host/pages-router-server.js.map +1 -1
  58. package/dist/next/index.cjs.map +1 -1
  59. package/dist/next/index.d.ts +1 -1
  60. package/dist/next/index.js.map +1 -1
  61. package/dist/react/index.cjs +1581 -87
  62. package/dist/react/index.cjs.map +1 -1
  63. package/dist/react/index.d.ts +13 -14
  64. package/dist/react/index.js +1559 -87
  65. package/dist/react/index.js.map +1 -1
  66. package/dist/shared/host/app.cjs +1 -1
  67. package/dist/shared/host/app.cjs.map +1 -1
  68. package/dist/shared/host/app.js +1 -1
  69. package/dist/shared/host/app.js.map +1 -1
  70. package/dist/shared/host/pages.cjs +1 -1
  71. package/dist/shared/host/pages.cjs.map +1 -1
  72. package/dist/shared/host/pages.js +1 -1
  73. package/dist/shared/host/pages.js.map +1 -1
  74. package/dist/shared/remote/app.cjs +1 -1
  75. package/dist/shared/remote/app.cjs.map +1 -1
  76. package/dist/shared/remote/app.js +1 -1
  77. package/dist/shared/remote/app.js.map +1 -1
  78. package/dist/shared/remote/pages.cjs +1 -1
  79. package/dist/shared/remote/pages.cjs.map +1 -1
  80. package/dist/shared/remote/pages.js +1 -1
  81. package/dist/shared/remote/pages.js.map +1 -1
  82. package/dist/types-2ab78f67.d.ts +71 -0
  83. package/package.json +54 -32
  84. package/dist/types-235b68a5.d.ts +0 -32
  85. package/dist/types-cbf6c34f.d.ts +0 -9
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,26 +17,1527 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/react/index.tsx
19
31
  var react_exports = {};
20
32
  __export(react_exports, {
21
33
  RemoteComponent: () => RemoteComponent
22
34
  });
23
35
  module.exports = __toCommonJS(react_exports);
36
+ var import_react2 = require("react");
37
+ var import_react_dom = require("react-dom");
38
+
39
+ // src/shared/client/apply-origin.ts
40
+ var tagNames = [
41
+ "img",
42
+ "source",
43
+ "video",
44
+ "audio",
45
+ "track",
46
+ "iframe",
47
+ "embed",
48
+ "script",
49
+ "link"
50
+ ];
51
+ function applyOriginToNodes(doc, url) {
52
+ if (url.origin !== location.origin) {
53
+ const nodes = doc.querySelectorAll(
54
+ tagNames.map(
55
+ (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
56
+ ).join(",")
57
+ );
58
+ nodes.forEach((node) => {
59
+ if (node.hasAttribute("src") && /^[./]+\/?/.test(node.getAttribute("src") ?? "")) {
60
+ node.src = new URL(node.getAttribute("src") ?? "/", url).href;
61
+ }
62
+ if (node.hasAttribute("href") && /^[./]+\/?/.test(node.getAttribute("href") ?? "")) {
63
+ node.setAttribute(
64
+ "href",
65
+ new URL(node.getAttribute("href") ?? "/", url).href
66
+ );
67
+ }
68
+ if (node.hasAttribute("srcset")) {
69
+ const srcSet = node.getAttribute("srcset")?.split(",").map((entry) => {
70
+ const [urlPart, descriptor] = entry.trim().split(/\s+/);
71
+ if (!urlPart)
72
+ return entry;
73
+ const absoluteUrl = new URL(urlPart, url).href;
74
+ return descriptor ? `${absoluteUrl} ${descriptor}` : absoluteUrl;
75
+ }).join(", ");
76
+ if (srcSet) {
77
+ node.setAttribute("srcset", srcSet);
78
+ }
79
+ }
80
+ if (node.hasAttribute("imagesrcset")) {
81
+ const srcSet = node.getAttribute("imagesrcset")?.split(",").map((entry) => {
82
+ const [urlPart, descriptor] = entry.trim().split(/\s+/);
83
+ if (!urlPart)
84
+ return entry;
85
+ const absoluteUrl = new URL(urlPart, url).href;
86
+ return descriptor ? `${absoluteUrl} ${descriptor}` : absoluteUrl;
87
+ }).join(", ");
88
+ if (srcSet) {
89
+ node.setAttribute("imagesrcset", srcSet);
90
+ }
91
+ }
92
+ });
93
+ }
94
+ }
95
+
96
+ // src/shared/client/polyfill.tsx
24
97
  var import_jsx_runtime = (
25
- // TODO: remove wrapper div by converting HTML to RSC or React tree
98
+ // eslint-disable-next-line @next/next/no-img-element, jsx-a11y/alt-text
26
99
  require("react/jsx-runtime")
27
100
  );
101
+ function applyBundleUrlToSrc(bundle, src) {
102
+ const self = globalThis;
103
+ if (self.__remote_bundle_url__?.[bundle]?.origin === location.origin) {
104
+ return src;
105
+ }
106
+ const { assetPrefix, path } = /^(?<assetPrefix>.*?)\/_next\/(?<path>.*)/.exec(src)?.groups ?? {};
107
+ if (!path) {
108
+ return new URL(src, self.__remote_bundle_url__?.[bundle]?.origin).href;
109
+ }
110
+ return `${self.__remote_bundle_url__?.[bundle]?.origin ?? ""}${assetPrefix}/_next/${path}`;
111
+ }
112
+ function applyBundleUrlToImagePropsSrc(bundle, src) {
113
+ if (typeof src === "string") {
114
+ return applyBundleUrlToSrc(bundle, src);
115
+ }
116
+ const propSrc = src;
117
+ return applyBundleUrlToSrc(bundle, propSrc.src);
118
+ }
119
+ var imageImpl = (bundle) => function RemoteImage({
120
+ fill: _fill,
121
+ loader: _loader,
122
+ quality: _quality,
123
+ priority: _priority,
124
+ loading: _loading,
125
+ placeholder: _placeholder,
126
+ blurDataURL: _blurDataURL,
127
+ unoptimized: _unoptimized,
128
+ overrideSrc: _overrideSrc,
129
+ src,
130
+ ...props
131
+ }) {
132
+ const newSrc = applyBundleUrlToImagePropsSrc(
133
+ bundle,
134
+ typeof src === "string" ? src : src.src
135
+ );
136
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
137
+ "img",
138
+ {
139
+ decoding: "async",
140
+ style: { color: "transparent" },
141
+ ...props,
142
+ src: newSrc,
143
+ suppressHydrationWarning: true
144
+ }
145
+ );
146
+ };
147
+ function sharedPolyfills(shared) {
148
+ const self = globalThis;
149
+ const polyfill = {
150
+ "next/dist/client/components/navigation": self.__remote_component_host_shared_modules__?.["next/navigation"] ?? shared?.["next/navigation"] ?? (() => Promise.resolve({
151
+ useRouter() {
152
+ return {
153
+ push: (routerUrl) => {
154
+ history.pushState({}, "", routerUrl);
155
+ },
156
+ replace: (routerUrl) => {
157
+ history.replaceState({}, "", routerUrl);
158
+ },
159
+ back: () => {
160
+ history.back();
161
+ }
162
+ };
163
+ },
164
+ usePathname() {
165
+ return location.pathname;
166
+ },
167
+ useParams() {
168
+ return {};
169
+ },
170
+ useSearchParams() {
171
+ return new URLSearchParams(location.search);
172
+ },
173
+ useSelectedLayoutSegment() {
174
+ return null;
175
+ },
176
+ useSelectedLayoutSegments() {
177
+ return [];
178
+ },
179
+ __esModule: true
180
+ })),
181
+ "next/dist/client/app-dir/link": self.__remote_component_host_shared_modules__?.["next/link"] ?? shared?.["next/link"] ?? (() => Promise.resolve({
182
+ default: ({
183
+ scroll: _,
184
+ replace,
185
+ prefetch,
186
+ onNavigate,
187
+ children,
188
+ ...props
189
+ }) => {
190
+ if (prefetch) {
191
+ console.warn(
192
+ "Next.js Link prefetch is not supported in remote components"
193
+ );
194
+ }
195
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
196
+ "a",
197
+ {
198
+ ...props,
199
+ href: props.href,
200
+ onClick: (e) => {
201
+ e.preventDefault();
202
+ let preventDefaulted = false;
203
+ e.preventDefault = () => {
204
+ preventDefaulted = true;
205
+ e.defaultPrevented = true;
206
+ };
207
+ if (typeof props.onClick === "function") {
208
+ props.onClick(e);
209
+ }
210
+ onNavigate?.(e);
211
+ if (preventDefaulted) {
212
+ return;
213
+ }
214
+ if (replace) {
215
+ history.replaceState({}, "", props.href);
216
+ } else {
217
+ history.pushState({}, "", props.href);
218
+ }
219
+ },
220
+ suppressHydrationWarning: true,
221
+ children: children ?? null
222
+ }
223
+ );
224
+ },
225
+ useLinkStatus() {
226
+ return { pending: false };
227
+ },
228
+ __esModule: true
229
+ })),
230
+ "next/dist/client/app-dir/form": self.__remote_component_host_shared_modules__?.["next/form"] ?? shared?.["next/form"] ?? (() => Promise.resolve({
231
+ default: () => {
232
+ throw new Error("Next.js <Form> component not implemented");
233
+ },
234
+ __esModule: true
235
+ })),
236
+ "next/dist/client/image-component": self.__remote_component_host_shared_modules__?.["next/image"] ?? shared?.["next/image"] ?? ((bundle) => Promise.resolve({
237
+ Image: imageImpl(bundle),
238
+ __esModule: true
239
+ })),
240
+ "next/image": self.__remote_component_host_shared_modules__?.["next/image"] ?? shared?.["next/image"] ?? ((bundle) => Promise.resolve({
241
+ default: imageImpl(bundle),
242
+ getImageProps: (_imgProps) => {
243
+ throw new Error(
244
+ "Next.js getImageProps() is not implemented in remote components"
245
+ );
246
+ },
247
+ __esModule: true
248
+ })),
249
+ "next/dist/client/script": self.__remote_component_host_shared_modules__?.["next/script"] ?? shared?.["next/script"] ?? (() => Promise.resolve({
250
+ // TODO: implement <Script> component for non-Next.js host applications
251
+ // do not throw an error for now
252
+ default: () => null,
253
+ __esModule: true
254
+ })),
255
+ "next/router": self.__remote_component_host_shared_modules__?.["next/router"] ?? shared?.["next/router"] ?? (() => (
256
+ // TODO: incomplete implementation
257
+ Promise.resolve({
258
+ useRouter() {
259
+ return {
260
+ push: (routerUrl) => {
261
+ history.pushState({}, "", routerUrl);
262
+ },
263
+ replace: (routerUrl) => {
264
+ history.replaceState({}, "", routerUrl);
265
+ },
266
+ back: () => {
267
+ history.back();
268
+ }
269
+ };
270
+ },
271
+ __esModule: true
272
+ })
273
+ )),
274
+ "next/dist/build/polyfills/process": () => Promise.resolve({
275
+ default: {
276
+ env: {
277
+ NODE_ENV: "production"
278
+ }
279
+ },
280
+ __esModule: true
281
+ })
282
+ };
283
+ polyfill["next/navigation"] = polyfill["next/dist/client/components/navigation"];
284
+ polyfill["next/link"] = polyfill["next/dist/client/app-dir/link"];
285
+ polyfill["next/form"] = polyfill["next/dist/client/app-dir/form"];
286
+ polyfill["next/dist/api/image"] = polyfill["next/dist/client/image-component"];
287
+ polyfill["next/script"] = polyfill["next/dist/client/script"];
288
+ return polyfill;
289
+ }
290
+
291
+ // src/shared/error.ts
292
+ var RemoteComponentsError = class extends Error {
293
+ code = "REMOTE_COMPONENTS_ERROR";
294
+ constructor(message, options) {
295
+ super(message, options);
296
+ this.name = "RemoteComponentsError";
297
+ }
298
+ };
299
+ function multipleRemoteComponentsError(url) {
300
+ return new RemoteComponentsError(
301
+ `Multiple Remote Components found at "${url}". When a page exposes multiple Remote Components you must specify the "name" prop to select which one to load.`
302
+ );
303
+ }
304
+ function failedToFetchRemoteComponentError(url, { status, statusText }, help = "Is the URL correct and accessible?") {
305
+ return new RemoteComponentsError(
306
+ `Failed to fetch Remote Component from "${url}". ${help}`,
307
+ { cause: new Error(`${status} ${statusText}`) }
308
+ );
309
+ }
310
+
311
+ // src/shared/client/component-loader.ts
312
+ var React = __toESM(require("react"), 1);
313
+ var JSXDevRuntime = __toESM(require("react/jsx-dev-runtime"), 1);
314
+ var JSXRuntime = __toESM(require("react/jsx-runtime"), 1);
315
+ var ReactDOM = __toESM(require("react-dom"), 1);
316
+ var ReactDOMClient = __toESM(require("react-dom/client"), 1);
317
+
318
+ // src/shared/utils/logger.ts
319
+ var PREFIX = "remote-components";
320
+ var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
321
+ function logDebug(location2, message) {
322
+ if (DEBUG) {
323
+ console.debug(`[${PREFIX}:${location2}]: ${message}`);
324
+ }
325
+ }
326
+ function logWarn(location2, message) {
327
+ console.warn(`[${PREFIX}:${location2}]: ${message}`);
328
+ }
329
+
330
+ // src/shared/webpack/next-client-pages-loader.ts
331
+ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
332
+ const self = globalThis;
333
+ const nextCssOriginal = document.querySelector(
334
+ `[id="__next_css__DO_NOT_USE__"]:not([data-bundle="${bundle}"][data-route="${route}"])`
335
+ );
336
+ if (nextCssOriginal) {
337
+ nextCssOriginal.parentNode?.removeChild(nextCssOriginal);
338
+ }
339
+ const nextCss = document.createElement("noscript");
340
+ nextCss.id = "__next_css__DO_NOT_USE__";
341
+ nextCss.setAttribute("data-bundle", bundle);
342
+ nextCss.setAttribute("data-route", route);
343
+ const nextCssEnd = document.createElement("noscript");
344
+ nextCssEnd.id = "__next_css__DO_NOT_USE_END__";
345
+ nextCssEnd.setAttribute("data-bundle", bundle);
346
+ nextCssEnd.setAttribute("data-route", route);
347
+ document.head.appendChild(nextCssEnd);
348
+ document.head.appendChild(nextCss);
349
+ const componentLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
350
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
351
+ ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
352
+ (key) => key.includes("/next/dist/client/page-loader.js")
353
+ ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
354
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
355
+ ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
356
+ (key) => key.includes("/next/dist/client/page-loader.js")
357
+ ) ?? ""] ?? -1;
358
+ const appLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
359
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
360
+ ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
361
+ (key) => key.includes("/next/dist/client/page-loader.js")
362
+ ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
363
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
364
+ ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
365
+ (key) => key.includes("/next/dist/client/page-loader.js")
366
+ ) ?? ""] ?? -1;
367
+ if (!(componentLoaderChunk && appLoaderChunk)) {
368
+ throw new RemoteComponentsError(
369
+ `Next.js client pages loader not found in bundle "${bundle}".`
370
+ );
371
+ }
372
+ const __NEXT_P_ORIGINAL = self.__NEXT_P;
373
+ const selfOriginal = self;
374
+ delete selfOriginal.__NEXT_P;
375
+ self.__remote_webpack_require__?.[bundle]?.(
376
+ self.__remote_webpack_require__[bundle].type !== "turbopack" ? componentLoaderChunk : `[${bundle}] ${componentLoaderChunk}`
377
+ );
378
+ if (typeof appLoaderChunk === "string" || typeof appLoaderChunk === "number" && appLoaderChunk !== -1) {
379
+ self.__remote_webpack_require__?.[bundle]?.(
380
+ self.__remote_webpack_require__[bundle].type !== "turbopack" ? appLoaderChunk : `[${bundle}] ${appLoaderChunk}`
381
+ );
382
+ }
383
+ if (self.__NEXT_P) {
384
+ const [, componentLoader] = self.__NEXT_P[0] ?? [
385
+ void 0,
386
+ () => ({ default: null })
387
+ ];
388
+ const [, appLoader] = self.__NEXT_P[2] ?? [
389
+ void 0,
390
+ () => ({
391
+ default: null
392
+ })
393
+ ];
394
+ const { default: Component } = componentLoader();
395
+ const { default: App } = appLoader();
396
+ if (!self.__remote_next_css__) {
397
+ self.__remote_next_css__ = {};
398
+ }
399
+ if (!self.__remote_next_css__[bundle]) {
400
+ const cssRE = /\.s?css$/;
401
+ Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
402
+ self.__remote_webpack_require__?.[bundle]?.(id);
403
+ });
404
+ Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {}).filter((path) => cssRE.test(path)).forEach((path) => {
405
+ const id = self.__remote_webpack_module_map__?.[bundle]?.[path];
406
+ if (id) {
407
+ self.__remote_webpack_require__?.[bundle]?.(id);
408
+ }
409
+ });
410
+ const elements = [];
411
+ let node = nextCss.previousSibling;
412
+ while (node && node !== nextCssEnd) {
413
+ elements.push(node);
414
+ node.remove();
415
+ node = nextCss.previousSibling;
416
+ }
417
+ self.__remote_next_css__[bundle] = elements;
418
+ }
419
+ if (styleContainer) {
420
+ const elements = self.__remote_next_css__[bundle];
421
+ elements.forEach((el) => {
422
+ styleContainer.appendChild(el.cloneNode(true));
423
+ });
424
+ } else {
425
+ const elements = self.__remote_next_css__[bundle];
426
+ elements.forEach((el) => {
427
+ document.head.appendChild(el);
428
+ });
429
+ }
430
+ delete self.__NEXT_P;
431
+ self.__NEXT_P = __NEXT_P_ORIGINAL;
432
+ if (nextCssOriginal) {
433
+ nextCssOriginal.parentNode?.appendChild(nextCssOriginal);
434
+ }
435
+ nextCss.remove();
436
+ nextCssEnd.remove();
437
+ return { Component, App };
438
+ }
439
+ return { Component: null, App: null };
440
+ }
441
+
442
+ // src/shared/webpack/shared-modules.ts
443
+ function applySharedModules(bundle, resolve) {
444
+ logDebug(
445
+ "SharedModules",
446
+ `applySharedModules called for bundle: "${bundle}"`
447
+ );
448
+ logDebug(
449
+ "SharedModules",
450
+ `Shared modules to resolve: ${Object.keys(resolve)}`
451
+ );
452
+ const self = globalThis;
453
+ if (self.__remote_webpack_require__?.[bundle]) {
454
+ const modulePaths = Object.keys(
455
+ self.__remote_webpack_module_map__?.[bundle] ?? self.__remote_webpack_require__[bundle].m ?? {}
456
+ );
457
+ logDebug(
458
+ "SharedModules",
459
+ `Available module paths in __remote_webpack_require__[${bundle}]: ${modulePaths}`
460
+ );
461
+ for (const [key, value] of Object.entries(resolve)) {
462
+ let ids = modulePaths.filter((p) => p === key);
463
+ if (ids.length === 0) {
464
+ ids = modulePaths.filter((p) => p.includes(key));
465
+ }
466
+ if (ids.length === 0) {
467
+ logDebug(
468
+ "SharedModules",
469
+ `No matching module path found for shared module "${key}"`
470
+ );
471
+ }
472
+ for (let id of ids) {
473
+ const webpackBundle = self.__remote_webpack_require__[bundle];
474
+ if (webpackBundle.m) {
475
+ if (self.__remote_webpack_module_map__?.[bundle]?.[id]) {
476
+ const mappedId = `${self.__remote_webpack_module_map__[bundle][id]}`;
477
+ logDebug(
478
+ "SharedModules",
479
+ `Mapped module id: "${id}" -> "${mappedId}"`
480
+ );
481
+ id = mappedId;
482
+ }
483
+ webpackBundle.m[id] = (module2) => {
484
+ module2.exports = value;
485
+ };
486
+ } else {
487
+ logWarn(
488
+ "SharedModules",
489
+ `webpackBundle.m is not available for bundle "${bundle}"`
490
+ );
491
+ }
492
+ }
493
+ }
494
+ } else {
495
+ logWarn("SharedModules", `No webpack require found for bundle "${bundle}"`);
496
+ logDebug(
497
+ "SharedModules",
498
+ `Available bundles: ${Object.keys(self.__remote_webpack_require__ ?? {})}`
499
+ );
500
+ }
501
+ }
502
+
503
+ // src/shared/client/rsc.ts
504
+ var import_web_streams_polyfill = require("web-streams-polyfill");
505
+ function fixPayload(payload) {
506
+ if (Array.isArray(payload)) {
507
+ if (payload[0] === "$") {
508
+ fixPayload(payload[3]);
509
+ if (payload.length === 4) {
510
+ payload.push(null, null, 1);
511
+ }
512
+ } else {
513
+ for (const item of payload) {
514
+ fixPayload(item);
515
+ }
516
+ }
517
+ } else if (typeof payload === "object" && payload !== null) {
518
+ for (const key in payload) {
519
+ fixPayload(payload[key]);
520
+ }
521
+ }
522
+ }
523
+ function createRSCStream(rscName, data) {
524
+ return new import_web_streams_polyfill.ReadableStream({
525
+ type: "bytes",
526
+ start(controller) {
527
+ const encoder = new TextEncoder();
528
+ const self = globalThis;
529
+ if (data.length > 0) {
530
+ data.forEach((chunk) => {
531
+ const lines = chunk.split("\n");
532
+ for (const line of lines) {
533
+ const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
534
+ if (match?.groups?.rsc) {
535
+ self[rscName] = self[rscName] ?? [];
536
+ self[rscName].push(JSON.parse(`"${match.groups.rsc}"`));
537
+ }
538
+ }
539
+ });
540
+ }
541
+ const allChunks = (self[rscName] ?? [`0:[null]
542
+ `]).join("");
543
+ self[rscName] = null;
544
+ allChunks.split("\n").forEach((chunk) => {
545
+ if (chunk.length > 0) {
546
+ const { before, id, prefix, payload } = /^(?<before>[^:]*?)?(?<id>[0-9a-zA-Z]+):(?<prefix>[A-Z])?(?<payload>\[.*\])/.exec(
547
+ chunk
548
+ )?.groups ?? {};
549
+ if (payload) {
550
+ const jsonPayload = JSON.parse(payload);
551
+ fixPayload(jsonPayload);
552
+ const reconstruct = `${before ?? ""}${id}:${prefix ?? ""}${JSON.stringify(jsonPayload)}`;
553
+ controller.enqueue(encoder.encode(`${reconstruct}
554
+ `));
555
+ } else {
556
+ controller.enqueue(encoder.encode(`${chunk}
557
+ `));
558
+ }
559
+ } else {
560
+ controller.enqueue(encoder.encode(`${chunk}
561
+ `));
562
+ }
563
+ });
564
+ controller.close();
565
+ }
566
+ });
567
+ }
568
+
569
+ // src/shared/client/script-loader.ts
570
+ async function loadScripts(scripts) {
571
+ await Promise.all(
572
+ scripts.map((script) => {
573
+ return new Promise((resolve, reject) => {
574
+ const newSrc = new URL(
575
+ // remove the remote component bundle name identifier from the script src
576
+ script.src.replace(/\/_next\/\[.+\](?<whitespace>%20| )/, "/_next/"),
577
+ location.origin
578
+ ).href;
579
+ const newScript = document.createElement("script");
580
+ newScript.onload = () => {
581
+ resolve();
582
+ };
583
+ newScript.onerror = () => {
584
+ reject(
585
+ new RemoteComponentsError(
586
+ `Failed to load <script src="${script.src}"> for Remote Component. Check the URL is correct.`
587
+ )
588
+ );
589
+ };
590
+ newScript.src = newSrc;
591
+ newScript.async = true;
592
+ document.head.appendChild(newScript);
593
+ });
594
+ })
595
+ );
596
+ }
597
+
598
+ // src/shared/utils/index.ts
599
+ function escapeString(str) {
600
+ return str.replace(/[^a-z0-9]/g, "_");
601
+ }
602
+ var attrToProp = {
603
+ fetchpriority: "fetchPriority",
604
+ crossorigin: "crossOrigin",
605
+ imagesrcset: "imageSrcSet",
606
+ imagesizes: "imageSizes",
607
+ srcset: "srcSet"
608
+ };
609
+
610
+ // src/shared/client/const.ts
611
+ var DEFAULT_ROUTE = "/";
612
+ var RUNTIME_WEBPACK = "webpack";
613
+ var RUNTIME_TURBOPACK = "turbopack";
614
+ var RUNTIME_SCRIPT = "script";
615
+ var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
616
+ function getBundleKey(bundle) {
617
+ return escapeString(bundle);
618
+ }
619
+
620
+ // src/shared/client/chunk-loader.ts
621
+ function createChunkLoader(runtime) {
622
+ return function __turbopack_chunk_load__(chunkId, scriptBundle) {
623
+ logDebug("ChunkLoader", `Loading chunk: "${chunkId}"`);
624
+ const self = globalThis;
625
+ const {
626
+ bundle,
627
+ id: path,
628
+ prefix
629
+ } = REMOTE_COMPONENT_REGEX.exec(chunkId)?.groups ?? {
630
+ bundle: scriptBundle ?? "",
631
+ id: chunkId
632
+ };
633
+ logDebug(
634
+ "ChunkLoader",
635
+ `Parsed chunk - bundle: "${bundle}", path: "${path}", prefix: "${prefix}"`
636
+ );
637
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
638
+ logDebug("ChunkLoader", `Remote runtime: "${remoteRuntime}"`);
639
+ if (remoteRuntime === RUNTIME_WEBPACK) {
640
+ logDebug("ChunkLoader", "Skipping chunk load - webpack runtime detected");
641
+ return Promise.resolve(void 0);
642
+ }
643
+ const url = new URL(
644
+ path ? `${prefix ?? ""}${path}`.replace(
645
+ /(?<char>[^:])(?<double>\/\/)/g,
646
+ "$1/"
647
+ ) : "/",
648
+ self.__remote_bundle_url__?.[bundle ?? "default"] ?? new URL(location.origin)
649
+ ).href;
650
+ if (url.endsWith(".css")) {
651
+ logDebug("ChunkLoader", `Skipping CSS file: "${url}"`);
652
+ return;
653
+ }
654
+ if (!self.__remote_components_turbopack_chunk_loader_promise__) {
655
+ self.__remote_components_turbopack_chunk_loader_promise__ = {};
656
+ }
657
+ if (self.__remote_components_turbopack_chunk_loader_promise__[url]) {
658
+ logDebug("ChunkLoader", `Returning cached promise for: "${url}"`);
659
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
660
+ }
661
+ logDebug("ChunkLoader", `Fetching chunk from: "${url}"`);
662
+ self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise((resolve, reject) => {
663
+ fetch(url).then((res) => res.text()).then((code) => {
664
+ if (code.includes("globalThis.TURBOPACK")) {
665
+ return handleTurbopackChunk(code, bundle ?? "", url);
666
+ }
667
+ }).then(resolve).catch(reject);
668
+ });
669
+ return self.__remote_components_turbopack_chunk_loader_promise__[url];
670
+ };
671
+ }
672
+ async function handleTurbopackChunk(code, bundle, url) {
673
+ logDebug(
674
+ "ChunkLoader",
675
+ `Handling Turbopack chunk - bundle: "${bundle}", url: "${url}"`
676
+ );
677
+ if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
678
+ logDebug("ChunkLoader", `Skipping worker chunk: "${url}"`);
679
+ const preloadLinks = document.querySelectorAll(
680
+ `link[rel="preload"][href="${new URL(url).pathname}"]`
681
+ );
682
+ preloadLinks.forEach((preloadLink) => preloadLink.remove());
683
+ return;
684
+ }
685
+ const self = globalThis;
686
+ const bundleKey = getBundleKey(bundle);
687
+ logDebug("ChunkLoader", `Bundle key: "${bundleKey}"`);
688
+ const transformedCode = code.replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${bundleKey}`).replace(
689
+ /TURBOPACK_WORKER_LOCATION/g,
690
+ `TURBOPACK_WORKER_LOCATION_${bundleKey}`
691
+ ).replace(
692
+ /TURBOPACK_NEXT_CHUNK_URLS/g,
693
+ `TURBOPACK_NEXT_CHUNK_URLS_${bundleKey}`
694
+ ).replace(
695
+ /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
696
+ `TURBOPACK_CHUNK_UPDATE_LISTENERS_${bundleKey}`
697
+ ).replace(/__next_require__/g, `__${bundleKey}_next_require__`).replace(
698
+ /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
699
+ `//# sourceMappingURL=${new URL(
700
+ ".",
701
+ new URL(
702
+ url,
703
+ self.__remote_bundle_url__?.[bundle] ?? new URL(location.origin)
704
+ )
705
+ ).href}$1$2.js.map`
706
+ );
707
+ logDebug("ChunkLoader", `Creating blob script for: "${url}"`);
708
+ await new Promise((scriptResolve, scriptReject) => {
709
+ const blob = new Blob([transformedCode], {
710
+ type: "application/javascript; charset=UTF-8"
711
+ });
712
+ const scriptUrl = URL.createObjectURL(blob);
713
+ const script = document.createElement("script");
714
+ script.setAttribute("data-turbopack-src", url);
715
+ script.src = scriptUrl;
716
+ script.async = true;
717
+ script.onload = () => {
718
+ URL.revokeObjectURL(scriptUrl);
719
+ scriptResolve(void 0);
720
+ script.remove();
721
+ };
722
+ script.onerror = () => {
723
+ URL.revokeObjectURL(scriptUrl);
724
+ scriptReject(
725
+ new RemoteComponentsError(
726
+ `Failed to load <script src="${script.src}"> for Remote Component. Check the URL is correct.`
727
+ )
728
+ );
729
+ script.remove();
730
+ };
731
+ document.head.appendChild(script);
732
+ });
733
+ const chunkLists = self[`TURBOPACK_${bundleKey}_CHUNK_LISTS`];
734
+ logDebug(
735
+ "ChunkLoader",
736
+ `Processing chunk lists for bundle "${bundle}": ${chunkLists?.length ?? 0} lists`
737
+ );
738
+ const loadChunkLists = [];
739
+ while (chunkLists?.length) {
740
+ const { chunks } = chunkLists.shift() ?? { chunks: [] };
741
+ if (chunks.length > 0) {
742
+ logDebug(
743
+ "ChunkLoader",
744
+ `Loading ${chunks.length} additional chunks for bundle "${bundle}": [${chunks.join(", ")}]`
745
+ );
746
+ chunks.forEach((id) => {
747
+ const chunkLoadResult = self.__webpack_chunk_load__?.(
748
+ `[${bundle}] ${url.slice(0, url.indexOf("/_next"))}/_next/${id}`
749
+ );
750
+ if (chunkLoadResult) {
751
+ loadChunkLists.push(chunkLoadResult);
752
+ }
753
+ });
754
+ }
755
+ }
756
+ if (loadChunkLists.length > 0) {
757
+ logDebug(
758
+ "ChunkLoader",
759
+ `Waiting for ${loadChunkLists.length} additional chunks to load`
760
+ );
761
+ await Promise.all(loadChunkLists);
762
+ }
763
+ }
764
+
765
+ // src/shared/client/turbopack-module.ts
766
+ function handleTurbopackModule(bundle, moduleId, id) {
767
+ const self = globalThis;
768
+ const bundleKey = getBundleKey(bundle);
769
+ const modules = self[`TURBOPACK_${bundleKey}`];
770
+ const moduleInit = findModuleInit(modules, moduleId);
771
+ const exports = {};
772
+ const moduleExports = { exports };
773
+ if (!self.__remote_components_turbopack_modules__) {
774
+ self.__remote_components_turbopack_modules__ = {};
775
+ }
776
+ if (!self.__remote_components_turbopack_modules__[bundle]) {
777
+ self.__remote_components_turbopack_modules__[bundle] = {};
778
+ }
779
+ if (self.__remote_components_turbopack_modules__[bundle][moduleId]) {
780
+ return self.__remote_components_turbopack_modules__[bundle][moduleId];
781
+ }
782
+ if (typeof moduleInit !== "function") {
783
+ throw new Error(
784
+ `Module ${id} not found in bundle ${bundle} with id ${moduleId}`
785
+ );
786
+ }
787
+ self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
788
+ if (!self.__remote_components_turbopack_global__) {
789
+ self.__remote_components_turbopack_global__ = {};
790
+ }
791
+ if (!self.__remote_components_turbopack_global__[bundle]) {
792
+ self.__remote_components_turbopack_global__[bundle] = {};
793
+ }
794
+ const allModules = modules?.flat() ?? [];
795
+ moduleInit(
796
+ createTurbopackContext(
797
+ bundle,
798
+ exports,
799
+ moduleExports,
800
+ allModules,
801
+ moduleInit,
802
+ id,
803
+ self
804
+ ),
805
+ moduleExports,
806
+ exports
807
+ );
808
+ if (self.__remote_components_turbopack_modules__[bundle][moduleId] !== moduleExports.exports) {
809
+ self.__remote_components_turbopack_modules__[bundle][moduleId] = moduleExports.exports;
810
+ }
811
+ return moduleExports.exports;
812
+ }
813
+ function findModuleInit(modules, moduleId) {
814
+ const allModules = modules?.flat() ?? [];
815
+ if (typeof allModules[1] === "string" || typeof allModules[1] === "number") {
816
+ const normalizedId = /^[0-9]+$/.test(moduleId) ? Number(moduleId) : moduleId;
817
+ let moduleIdIndex = allModules.indexOf(normalizedId);
818
+ if (moduleIdIndex === -1) {
819
+ moduleIdIndex = allModules.findIndex(
820
+ (bundleEntry) => typeof bundleEntry === "string" && bundleEntry.startsWith(moduleId) || bundleEntry === normalizedId
821
+ );
822
+ }
823
+ if (moduleIdIndex !== -1) {
824
+ while (typeof allModules[moduleIdIndex] !== "function" && moduleIdIndex < allModules.length) {
825
+ moduleIdIndex++;
826
+ }
827
+ return allModules[moduleIdIndex];
828
+ }
829
+ } else {
830
+ return allModules.find(
831
+ (bundleEntry) => typeof bundleEntry === "object" && bundleEntry !== null && moduleId in bundleEntry
832
+ )?.[moduleId];
833
+ }
834
+ return void 0;
835
+ }
836
+ function createTurbopackContext(bundle, exports, moduleExports, allModules, moduleInit, id, self) {
837
+ return {
838
+ // HMR not implemented for Remote Components
839
+ k: {
840
+ register() {
841
+ },
842
+ registerExports() {
843
+ },
844
+ signature() {
845
+ return (fn) => fn;
846
+ }
847
+ },
848
+ // ESM exports setup
849
+ s(bindings, esmId) {
850
+ let mod = exports;
851
+ if (typeof esmId === "string" || typeof esmId === "number") {
852
+ if (!self.__remote_components_turbopack_modules__) {
853
+ self.__remote_components_turbopack_modules__ = {};
854
+ }
855
+ if (!self.__remote_components_turbopack_modules__[bundle]) {
856
+ self.__remote_components_turbopack_modules__[bundle] = {};
857
+ }
858
+ if (!self.__remote_components_turbopack_modules__[bundle][esmId]) {
859
+ self.__remote_components_turbopack_modules__[bundle][esmId] = {};
860
+ }
861
+ mod = self.__remote_components_turbopack_modules__[bundle][esmId];
862
+ }
863
+ Object.defineProperty(mod, "__esModule", { value: true });
864
+ if (Array.isArray(bindings)) {
865
+ let i = 0;
866
+ while (i < bindings.length) {
867
+ const propName = bindings[i++];
868
+ const tagOrFunc = bindings[i++];
869
+ if (typeof tagOrFunc === "number") {
870
+ Object.defineProperty(mod, propName, {
871
+ value: bindings[i++],
872
+ enumerable: true,
873
+ writable: false
874
+ });
875
+ } else {
876
+ const getterFn = tagOrFunc;
877
+ if (typeof bindings[i] === "function") {
878
+ const setterFn = bindings[i++];
879
+ Object.defineProperty(mod, propName, {
880
+ get: getterFn,
881
+ set: setterFn,
882
+ enumerable: true
883
+ });
884
+ } else {
885
+ Object.defineProperty(mod, propName, {
886
+ get: getterFn,
887
+ enumerable: true
888
+ });
889
+ }
890
+ }
891
+ }
892
+ }
893
+ },
894
+ // import
895
+ i(importId) {
896
+ let mod;
897
+ if (typeof importId === "string") {
898
+ const { exportSource, exportName } = /\s+<export (?<exportSource>.*?) as (?<exportName>.*?)>$/.exec(
899
+ importId
900
+ )?.groups ?? {};
901
+ const normalizedId = importId.replace(
902
+ /\s+<export(?<specifier>.*)>$/,
903
+ ""
904
+ );
905
+ mod = self.__webpack_require__?.(`[${bundle}] ${normalizedId}`);
906
+ if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
907
+ if (exportSource === "*") {
908
+ mod[exportName] = mod;
909
+ } else {
910
+ mod[exportName] = mod[exportSource];
911
+ }
912
+ }
913
+ } else {
914
+ mod = self.__webpack_require__?.(`[${bundle}] ${importId}`);
915
+ }
916
+ if (typeof mod !== "object" || mod === null) {
917
+ mod = { default: mod };
918
+ } else if (!("default" in mod) && mod.toString() !== "[object Module]") {
919
+ try {
920
+ mod.default = mod;
921
+ } catch {
922
+ }
923
+ }
924
+ return mod;
925
+ },
926
+ // require
927
+ r(requireId) {
928
+ return self.__webpack_require__?.(`[${bundle}] ${requireId}`);
929
+ },
930
+ // value exports
931
+ v(value) {
932
+ if (typeof value === "function") {
933
+ exports.default = value((vid) => {
934
+ return self.__webpack_require__?.(`[${bundle}] ${vid}`);
935
+ });
936
+ } else {
937
+ moduleExports.exports = value;
938
+ }
939
+ },
940
+ // async module initializer
941
+ async a(mod) {
942
+ let result;
943
+ await mod(
944
+ () => {
945
+ },
946
+ (value) => result = value
947
+ );
948
+ exports.default = result;
949
+ },
950
+ // async module loader
951
+ async A(Aid) {
952
+ const mod = self.__webpack_require__?.(`[${bundle}] ${Aid}`);
953
+ return mod.default(
954
+ (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
955
+ );
956
+ },
957
+ // chunk loader
958
+ l(url) {
959
+ const moduleInitIndex = allModules.indexOf(moduleInit);
960
+ if (moduleInitIndex !== -1) {
961
+ const scriptIndex = allModules.slice(0, moduleInitIndex).findLastIndex((bundleEntry) => bundleEntry instanceof Element);
962
+ if (scriptIndex !== -1) {
963
+ const script = allModules[scriptIndex];
964
+ const scriptSrc = script.getAttribute("data-turbopack-src") || "";
965
+ const nextIndex = scriptSrc.indexOf("/_next");
966
+ const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
967
+ const bundleUrl = `[${bundle}] ${baseUrl}/_next/${url}`;
968
+ return self.__webpack_chunk_load__?.(bundleUrl, bundle);
969
+ }
970
+ }
971
+ throw new Error(
972
+ `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
973
+ );
974
+ },
975
+ // global object for this bundle
976
+ g: self.__remote_components_turbopack_global__?.[bundle],
977
+ m: moduleExports,
978
+ e: exports
979
+ };
980
+ }
981
+
982
+ // src/shared/client/turbopack-patterns.ts
983
+ var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
984
+ var REMOTE_SHARED_ASSIGNMENT_RE = /\.TURBOPACK_REMOTE_SHARED=await (?:__turbopack_context__|e)\.A\((?<sharedModuleId>[0-9]+)\)/;
985
+ var ASYNC_MODULE_LOADER_RE = /(?:__turbopack_context__|e)\.A\((?<asyncSharedModuleId>[0-9]+)\)/;
986
+ var ASYNC_MODULE_RESOLVE_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<inner>parentImport|e)=>Promise\.resolve\(\)\.then\(\(\)=>\k<inner>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
987
+ var ASYNC_MODULE_ALL_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<vCb>parentImport|t)=>Promise\.all\(\["[^"]+"\]\.map\((?<mapCb>chunk|t)=>\k<ctx>\.l\(\k<mapCb>\)\)\)\.then\(\(\)=>\k<vCb>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
988
+
989
+ // src/shared/client/shared-modules.ts
990
+ async function initializeSharedModules(bundle, hostShared = {}, remoteShared = {}) {
991
+ const self = globalThis;
992
+ self.__remote_shared_modules__ = self.__remote_shared_modules__ ?? {};
993
+ if (!self.__remote_shared_modules__[bundle]) {
994
+ self.__remote_shared_modules__[bundle] = {};
995
+ }
996
+ const bundleKey = getBundleKey(bundle);
997
+ const modules = self[`TURBOPACK_${bundleKey}`];
998
+ let sharedModuleInitializer = null;
999
+ if (modules && Array.isArray(modules)) {
1000
+ const allModules = modules.flat();
1001
+ const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1002
+ if (typeof idOrFunc !== "function") {
1003
+ return false;
1004
+ }
1005
+ const funcCode = idOrFunc.toString();
1006
+ return REMOTE_SHARED_MARKER_RE.test(funcCode);
1007
+ });
1008
+ if (sharedModuleInitializerIndex > 0) {
1009
+ const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1010
+ const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1011
+ const { sharedModuleId } = REMOTE_SHARED_ASSIGNMENT_RE.exec(sharedModuleInitializerCode)?.groups ?? {};
1012
+ if (sharedModuleId) {
1013
+ const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1014
+ bundle,
1015
+ sharedModuleId,
1016
+ `[${bundle}] ${sharedModuleInitializerId}`
1017
+ );
1018
+ sharedModuleInitializer = sharedModuleInitializerInstance;
1019
+ }
1020
+ }
1021
+ if (sharedModuleInitializer) {
1022
+ const { shared } = await sharedModuleInitializer;
1023
+ const sharedModuleIds = extractSharedModuleIds(
1024
+ shared,
1025
+ bundleKey,
1026
+ self
1027
+ );
1028
+ return Promise.all(
1029
+ Object.entries(sharedModuleIds).map(async ([id, module2]) => {
1030
+ if (self.__remote_shared_modules__?.[bundle]) {
1031
+ if (hostShared[module2]) {
1032
+ self.__remote_shared_modules__[bundle][id] = await hostShared[module2](bundle);
1033
+ }
1034
+ }
1035
+ })
1036
+ );
1037
+ }
1038
+ }
1039
+ return Promise.all(
1040
+ Object.entries(remoteShared).map(async ([id, module2]) => {
1041
+ if (self.__remote_shared_modules__?.[bundle]) {
1042
+ if (hostShared[module2]) {
1043
+ self.__remote_shared_modules__[bundle][id.replace("[app-ssr]", "[app-client]")] = await hostShared[module2](bundle);
1044
+ } else {
1045
+ console.error(`Shared module "${module2}" not found for "${bundle}".`);
1046
+ }
1047
+ }
1048
+ })
1049
+ );
1050
+ }
1051
+ function extractSharedModuleIds(shared, bundleKey, self) {
1052
+ return Object.entries(shared).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1053
+ const { asyncSharedModuleId } = ASYNC_MODULE_LOADER_RE.exec(value.toString())?.groups ?? {};
1054
+ if (asyncSharedModuleId) {
1055
+ const asyncSharedModuleIdNumber = Number(asyncSharedModuleId);
1056
+ let asyncSharedModule;
1057
+ const newAllModules = self[`TURBOPACK_${bundleKey}`]?.flat() ?? [];
1058
+ const asyncSharedModuleIdIndex = newAllModules.indexOf(
1059
+ asyncSharedModuleIdNumber
1060
+ );
1061
+ if (asyncSharedModuleIdIndex !== -1 && typeof newAllModules[asyncSharedModuleIdIndex + 1] === "function") {
1062
+ asyncSharedModule = newAllModules[asyncSharedModuleIdIndex + 1];
1063
+ }
1064
+ if (asyncSharedModule) {
1065
+ const asyncSharedModuleCode = asyncSharedModule.toString();
1066
+ const { sharedModuleId } = ASYNC_MODULE_RESOLVE_RE.exec(asyncSharedModuleCode)?.groups ?? ASYNC_MODULE_ALL_RE.exec(asyncSharedModuleCode)?.groups ?? {};
1067
+ acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1068
+ "__remote_shared_module_",
1069
+ ""
1070
+ );
1071
+ }
1072
+ }
1073
+ return acc;
1074
+ }, {});
1075
+ }
1076
+ function getSharedModule(bundle, id) {
1077
+ const self = globalThis;
1078
+ for (const [key, value] of Object.entries(
1079
+ self.__remote_shared_modules__?.[bundle] ?? {}
1080
+ )) {
1081
+ if (typeof value !== "undefined" && (typeof id === "string" && id.includes(key) || id === key)) {
1082
+ return value;
1083
+ }
1084
+ }
1085
+ return null;
1086
+ }
1087
+
1088
+ // src/shared/client/webpack-adapter.ts
1089
+ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}) {
1090
+ const self = globalThis;
1091
+ if (!self.__remote_bundle_url__) {
1092
+ self.__remote_bundle_url__ = {};
1093
+ }
1094
+ self.__remote_bundle_url__[bundle ?? "default"] = url;
1095
+ self.__webpack_get_script_filename__ = () => null;
1096
+ if (typeof self.__webpack_require__ !== "function" || self.__webpack_require_type__ !== "turbopack") {
1097
+ if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1098
+ self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1099
+ self.__original_webpack_require__ = self.__webpack_require__;
1100
+ }
1101
+ self.__webpack_chunk_load__ = createChunkLoader(runtime);
1102
+ self.__webpack_require__ = createModuleRequire(runtime);
1103
+ self.__webpack_require_type__ = runtime;
1104
+ if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1105
+ const remoteBundle = bundle ?? "default";
1106
+ self.__remote_webpack_require__[remoteBundle] = self.__webpack_require__;
1107
+ self.__remote_webpack_require__[remoteBundle].type = "turbopack";
1108
+ }
1109
+ }
1110
+ if (runtime === RUNTIME_TURBOPACK) {
1111
+ await Promise.all(
1112
+ scripts.map((script) => {
1113
+ if (script.src) {
1114
+ return self.__webpack_chunk_load__?.(script.src, bundle);
1115
+ }
1116
+ return Promise.resolve(void 0);
1117
+ })
1118
+ );
1119
+ }
1120
+ const coreShared = {
1121
+ react: async () => (await import("react")).default,
1122
+ "react-dom": async () => (await import("react-dom")).default,
1123
+ "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
1124
+ "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
1125
+ "react-dom/client": async () => (await import("react-dom/client")).default,
1126
+ ...shared
1127
+ };
1128
+ await initializeSharedModules(
1129
+ bundle ?? "default",
1130
+ // include all core modules as shared
1131
+ coreShared,
1132
+ remoteShared
1133
+ );
1134
+ }
1135
+ function createModuleRequire(runtime) {
1136
+ return (id) => {
1137
+ const self = globalThis;
1138
+ const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1139
+ bundle: "default",
1140
+ id
1141
+ };
1142
+ const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : runtime;
1143
+ logDebug("WebpackAdapter", `remoteRuntime: "${remoteRuntime}"`);
1144
+ try {
1145
+ if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1146
+ return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1147
+ }
1148
+ const sharedModuleId = moduleId ?? id;
1149
+ const sharedModule = getSharedModule(bundle ?? "default", sharedModuleId);
1150
+ if (sharedModule) {
1151
+ return sharedModule;
1152
+ }
1153
+ if (bundle && moduleId) {
1154
+ return handleTurbopackModule(bundle, moduleId, id);
1155
+ }
1156
+ throw new Error(`Module "${id}" not found.`);
1157
+ } catch (requireError) {
1158
+ logWarn(
1159
+ "WebpackAdapter",
1160
+ `Module require failed: ${String(requireError)}`
1161
+ );
1162
+ if (typeof self.__original_webpack_require__ !== "function") {
1163
+ throw new RemoteComponentsError(
1164
+ `Module "${id}" not found in remote component bundle "${bundle}".`,
1165
+ {
1166
+ cause: requireError instanceof Error ? requireError : void 0
1167
+ }
1168
+ );
1169
+ }
1170
+ try {
1171
+ logDebug("WebpackAdapter", "Falling back to original webpack require");
1172
+ return self.__original_webpack_require__(id);
1173
+ } catch (originalError) {
1174
+ throw new RemoteComponentsError(
1175
+ `Module "${id}" not found in remote component bundle "${bundle}".`,
1176
+ { cause: originalError instanceof Error ? originalError : void 0 }
1177
+ );
1178
+ }
1179
+ }
1180
+ };
1181
+ }
1182
+
1183
+ // src/shared/client/component-loader.ts
1184
+ async function loadRemoteComponent({
1185
+ url,
1186
+ name,
1187
+ rscName,
1188
+ bundle,
1189
+ route = "/",
1190
+ runtime = "webpack",
1191
+ data,
1192
+ nextData,
1193
+ scripts = [],
1194
+ shared = Promise.resolve({}),
1195
+ remoteShared = {},
1196
+ container
1197
+ }) {
1198
+ try {
1199
+ if (runtime === "webpack") {
1200
+ const self = globalThis;
1201
+ if (!self.__DISABLE_WEBPACK_EXEC__) {
1202
+ self.__DISABLE_WEBPACK_EXEC__ = {};
1203
+ }
1204
+ self.__DISABLE_WEBPACK_EXEC__[bundle] = true;
1205
+ await loadScripts(scripts);
1206
+ }
1207
+ const hostShared = await shared;
1208
+ logDebug(
1209
+ "ComponentLoader",
1210
+ `loadRemoteComponent: bundle="${bundle}", name="${name}"`
1211
+ );
1212
+ logDebug(
1213
+ "ComponentLoader",
1214
+ `Host shared modules available: ${Object.keys(hostShared)}`
1215
+ );
1216
+ logDebug(
1217
+ "ComponentLoader",
1218
+ `Remote shared modules requested: ${JSON.stringify(remoteShared)}`
1219
+ );
1220
+ await setupWebpackRuntime(
1221
+ runtime,
1222
+ scripts,
1223
+ url,
1224
+ bundle,
1225
+ hostShared,
1226
+ remoteShared
1227
+ );
1228
+ if (bundle) {
1229
+ const resolve = {
1230
+ "/react/index.js": React,
1231
+ "/react/jsx-dev-runtime.js": JSXDevRuntime,
1232
+ "/react/jsx-runtime.js": JSXRuntime,
1233
+ "/react-dom/index.js": ReactDOM,
1234
+ "/react-dom/client.js": ReactDOMClient,
1235
+ ...Object.entries(remoteShared).reduce(
1236
+ (acc, [key, value]) => {
1237
+ if (typeof hostShared[value] !== "undefined") {
1238
+ acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
1239
+ } else {
1240
+ logDebug(
1241
+ "ComponentLoader",
1242
+ `Remote requests "${value}" but host doesn't provide it`
1243
+ );
1244
+ }
1245
+ return acc;
1246
+ },
1247
+ {}
1248
+ )
1249
+ };
1250
+ await Promise.all(
1251
+ Object.entries(resolve).map(async ([key, value]) => {
1252
+ if (typeof value === "function") {
1253
+ resolve[key] = await value(bundle);
1254
+ }
1255
+ return Promise.resolve(value);
1256
+ })
1257
+ );
1258
+ applySharedModules(bundle, resolve);
1259
+ } else {
1260
+ logWarn(
1261
+ "ComponentLoader",
1262
+ "No bundle specified, skipping shared module setup"
1263
+ );
1264
+ }
1265
+ if (data.length > 0) {
1266
+ return await loadRSCComponent(rscName ?? name, data);
1267
+ } else if (nextData) {
1268
+ return loadNextPagesComponent(bundle, route, nextData, name, container);
1269
+ }
1270
+ return loadRSCComponent(rscName ?? name, [`0:[null]
1271
+ `]);
1272
+ } catch (error) {
1273
+ return {
1274
+ component: null,
1275
+ error: new RemoteComponentsError(
1276
+ `Failed to load remote component "${name}".`,
1277
+ {
1278
+ cause: error instanceof Error ? error : new Error(String(error))
1279
+ }
1280
+ )
1281
+ };
1282
+ }
1283
+ }
1284
+ async function loadRSCComponent(rscName, data) {
1285
+ let createFromReadableStream;
1286
+ try {
1287
+ const { createFromReadableStream: _createFromReadableStream } = await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1288
+ createFromReadableStream = _createFromReadableStream;
1289
+ } catch {
1290
+ const {
1291
+ default: { createFromReadableStream: _createFromReadableStream }
1292
+ } = await import("react-server-dom-webpack/client.browser");
1293
+ createFromReadableStream = _createFromReadableStream;
1294
+ }
1295
+ if (typeof createFromReadableStream !== "function") {
1296
+ throw new RemoteComponentsError(
1297
+ 'Failed to import "react-server-dom-webpack". Is Next.js installed correctly?'
1298
+ );
1299
+ }
1300
+ const stream = createRSCStream(rscName, data);
1301
+ const component = createFromReadableStream(stream);
1302
+ return { component };
1303
+ }
1304
+ function loadNextPagesComponent(bundle, route, nextData, name, container) {
1305
+ const { Component, App } = nextClientPagesLoader(bundle, route, container);
1306
+ if (!Component) {
1307
+ throw new RemoteComponentsError(
1308
+ `Remote Component "${name}" is trying to load the component for route "${route}" but it is not available.`
1309
+ );
1310
+ }
1311
+ const component = App ? React.createElement(App, { Component, ...nextData.props }) : React.createElement(Component, nextData.props);
1312
+ return { component };
1313
+ }
1314
+
1315
+ // src/shared/client/set-attributes-from-props.ts
1316
+ var DOMAttributeNames = {
1317
+ acceptCharset: "accept-charset",
1318
+ className: "class",
1319
+ htmlFor: "for",
1320
+ httpEquiv: "http-equiv",
1321
+ noModule: "noModule"
1322
+ };
1323
+ var ignoreProps = [
1324
+ "onLoad",
1325
+ "onReady",
1326
+ "dangerouslySetInnerHTML",
1327
+ "children",
1328
+ "onError",
1329
+ "strategy",
1330
+ "stylesheets"
1331
+ ];
1332
+ function isBooleanScriptAttribute(attr) {
1333
+ return ["async", "defer", "noModule"].includes(attr);
1334
+ }
1335
+ function setAttributesFromProps(el, props) {
1336
+ for (const [p, value] of Object.entries(props)) {
1337
+ if (!Object.hasOwn(props, p))
1338
+ continue;
1339
+ if (ignoreProps.includes(p))
1340
+ continue;
1341
+ if (value === void 0) {
1342
+ continue;
1343
+ }
1344
+ const attr = DOMAttributeNames[p] || p.toLowerCase();
1345
+ if (el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr)) {
1346
+ el[attr] = Boolean(value);
1347
+ } else {
1348
+ el.setAttribute(attr, String(value));
1349
+ }
1350
+ if (value === false || el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr) && (!value || value === "false")) {
1351
+ el.setAttribute(attr, "");
1352
+ el.removeAttribute(attr);
1353
+ }
1354
+ }
1355
+ }
1356
+
1357
+ // src/shared/client/static-loader.ts
1358
+ async function loadStaticRemoteComponent(scripts, url) {
1359
+ const self = globalThis;
1360
+ if (self.__remote_script_entrypoint_mount__?.[url.href]) {
1361
+ self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
1362
+ }
1363
+ if (self.__remote_script_entrypoint_unmount__?.[url.href]) {
1364
+ self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
1365
+ }
1366
+ const mountUnmountSets = await Promise.all(
1367
+ scripts.map(async (script) => {
1368
+ try {
1369
+ let src = typeof script.getAttribute === "function" ? script.getAttribute("src") ?? script.src : script.src;
1370
+ if (!src && script.textContent) {
1371
+ const blob = new Blob(
1372
+ [
1373
+ script.textContent.replace(
1374
+ /import\.meta\.url/g,
1375
+ JSON.stringify(url)
1376
+ )
1377
+ ],
1378
+ {
1379
+ type: "text/javascript"
1380
+ }
1381
+ );
1382
+ src = URL.createObjectURL(blob);
1383
+ }
1384
+ const mod = await import(
1385
+ /* @vite-ignore */
1386
+ /* webpackIgnore: true */
1387
+ new URL(src, url).href
1388
+ );
1389
+ if (src.startsWith("blob:")) {
1390
+ URL.revokeObjectURL(src);
1391
+ }
1392
+ if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
1393
+ if (!self.__remote_script_entrypoint_mount__) {
1394
+ self.__remote_script_entrypoint_mount__ = {};
1395
+ }
1396
+ if (!self.__remote_script_entrypoint_mount__[url.href]) {
1397
+ self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
1398
+ }
1399
+ self.__remote_script_entrypoint_mount__[url.href]?.add(
1400
+ mod.mount || mod.default?.mount || (() => {
1401
+ })
1402
+ );
1403
+ }
1404
+ if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
1405
+ if (!self.__remote_script_entrypoint_unmount__) {
1406
+ self.__remote_script_entrypoint_unmount__ = {};
1407
+ }
1408
+ if (!self.__remote_script_entrypoint_unmount__[url.href]) {
1409
+ self.__remote_script_entrypoint_unmount__[url.href] = /* @__PURE__ */ new Set();
1410
+ }
1411
+ self.__remote_script_entrypoint_unmount__[url.href]?.add(
1412
+ mod.unmount || mod.default?.unmount || (() => {
1413
+ })
1414
+ );
1415
+ }
1416
+ return {
1417
+ mount: mod.mount || mod.default?.mount,
1418
+ unmount: mod.unmount || mod.default?.unmount
1419
+ };
1420
+ } catch (e) {
1421
+ console.error(
1422
+ new RemoteComponentsError(
1423
+ `Error loading remote component script from "${script.src || url.href}".`,
1424
+ { cause: e }
1425
+ )
1426
+ );
1427
+ return {
1428
+ mount: void 0,
1429
+ unmount: void 0
1430
+ };
1431
+ }
1432
+ })
1433
+ );
1434
+ return mountUnmountSets.reduce(
1435
+ (acc, { mount, unmount }) => {
1436
+ if (typeof mount === "function") {
1437
+ acc.mount.add(mount);
1438
+ }
1439
+ if (typeof unmount === "function") {
1440
+ acc.unmount.add(unmount);
1441
+ }
1442
+ return acc;
1443
+ },
1444
+ {
1445
+ mount: /* @__PURE__ */ new Set(),
1446
+ unmount: /* @__PURE__ */ new Set()
1447
+ }
1448
+ );
1449
+ }
1450
+
1451
+ // src/shared/ssr/fetch-headers.ts
1452
+ function remoteFetchHeaders() {
1453
+ return {
1454
+ /**
1455
+ * Authenticates deployment protection for the remote. Needed for SSR and SSG clients.
1456
+ * If the remote component uses vercel deployment protection, ensure the host and remote vercel
1457
+ * projects share a common automation bypass secret, and the shared secret is used as the
1458
+ * VERCEL_AUTOMATION_BYPASS_SECRET env var in the host project.
1459
+ */
1460
+ ...typeof process === "object" && typeof process.env === "object" && typeof process.env.VERCEL_AUTOMATION_BYPASS_SECRET === "string" ? {
1461
+ "x-vercel-protection-bypass": process.env.VERCEL_AUTOMATION_BYPASS_SECRET
1462
+ } : {},
1463
+ Accept: "text/html"
1464
+ };
1465
+ }
1466
+
1467
+ // src/shared/ssr/fetch-with-hooks.ts
1468
+ async function fetchWithHooks(url, init, options = {}) {
1469
+ const { onRequest, onResponse } = options;
1470
+ let res = await onRequest?.(url, init);
1471
+ if (!res) {
1472
+ res = await fetch(url, init);
1473
+ }
1474
+ const transformedRes = await onResponse?.(url, res);
1475
+ if (transformedRes) {
1476
+ res = transformedRes;
1477
+ }
1478
+ return res;
1479
+ }
1480
+
1481
+ // src/shared/ssr/get-client-or-server-url.ts
1482
+ function getClientOrServerUrl(src, serverFallback) {
1483
+ const fallback = typeof location !== "undefined" ? location.href : serverFallback;
1484
+ if (!src) {
1485
+ return new URL(fallback);
1486
+ }
1487
+ return typeof src === "string" ? new URL(src, fallback) : src;
1488
+ }
1489
+
1490
+ // src/react/hooks/use-shadow-root.ts
28
1491
  var import_react = require("react");
29
- var import_react2 = require("react");
30
- var import_react_dom = require("react-dom");
31
- var import_apply_origin = require("#internal/shared/client/apply-origin");
32
- var import_polyfill = require("#internal/shared/client/polyfill");
33
- var import_remote_component = require("#internal/shared/client/remote-component");
34
- var import_error = require("#internal/shared/error");
35
- var import_fetch_headers = require("#internal/shared/ssr/fetch-headers");
36
- var import_get_client_or_server_url = require("#internal/shared/ssr/get-client-or-server-url");
37
- var import_utils = require("#internal/shared/utils");
1492
+ function useShadowRoot({
1493
+ isolate,
1494
+ mode,
1495
+ keySuffix
1496
+ }) {
1497
+ const shadowRootContainerRef = (0, import_react.useRef)(null);
1498
+ const [shadowRoot, setShadowRoot] = (0, import_react.useState)(() => {
1499
+ const self = globalThis;
1500
+ const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
1501
+ const ssrShadowRoot = typeof document !== "undefined" ? document.querySelector(
1502
+ `[data-remote-component-id="shadowroot_${keySuffix}"]`
1503
+ )?.shadowRoot ?? self[shadowRootKey] ?? null : null;
1504
+ self[shadowRootKey] = null;
1505
+ return ssrShadowRoot;
1506
+ });
1507
+ (0, import_react.useLayoutEffect)(() => {
1508
+ if (isolate !== false && typeof document !== "undefined" && (!shadowRoot || !shadowRoot.isConnected)) {
1509
+ const self = globalThis;
1510
+ const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
1511
+ let shadowRootElement = null;
1512
+ const element = document.querySelector(
1513
+ `[data-remote-component-id="shadowroot_${keySuffix}"]`
1514
+ );
1515
+ shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;
1516
+ if (!shadowRootElement && element) {
1517
+ try {
1518
+ shadowRootElement = element.attachShadow({ mode });
1519
+ self[shadowRootKey] = shadowRootElement;
1520
+ } catch {
1521
+ }
1522
+ }
1523
+ if (shadowRootElement) {
1524
+ shadowRootElement.querySelectorAll("*:not(link)").forEach((node) => {
1525
+ node.remove();
1526
+ });
1527
+ setShadowRoot(shadowRootElement);
1528
+ }
1529
+ } else if (isolate === false && shadowRoot) {
1530
+ const self = globalThis;
1531
+ const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
1532
+ self[shadowRootKey] = null;
1533
+ setShadowRoot(null);
1534
+ }
1535
+ }, [isolate, shadowRoot, mode, keySuffix]);
1536
+ return { shadowRoot, shadowRootContainerRef };
1537
+ }
1538
+
1539
+ // src/react/utils/parse-remote-html.ts
1540
+ var DUMMY_FALLBACK = "http://remote-components-dummy-fallback";
38
1541
  function getRemoteComponentHtml(html) {
39
1542
  if (typeof document === "undefined")
40
1543
  return html;
@@ -54,7 +1557,13 @@ function getRemoteComponentHtml(html) {
54
1557
  }
55
1558
  return "";
56
1559
  }
57
- const DUMMY_FALLBACK = "http://remote-components-dummy-fallback";
1560
+
1561
+ // src/react/index.tsx
1562
+ var import_jsx_runtime2 = (
1563
+ // TODO: remove wrapper div by converting HTML to RSC or React tree
1564
+ require("react/jsx-runtime")
1565
+ );
1566
+ var import_react3 = require("react");
58
1567
  function RemoteComponent({
59
1568
  src,
60
1569
  isolate,
@@ -63,13 +1572,15 @@ function RemoteComponent({
63
1572
  credentials = "same-origin",
64
1573
  name: nameProp = "__vercel_remote_component",
65
1574
  shared = {},
66
- additionalHeaders,
67
1575
  children,
68
1576
  onBeforeLoad,
69
1577
  onLoad,
70
1578
  onError,
71
- onChange
1579
+ onChange,
1580
+ onRequest,
1581
+ onResponse
72
1582
  }) {
1583
+ const instanceId = (0, import_react2.useId)();
73
1584
  const name = (0, import_react2.useMemo)(() => {
74
1585
  if (typeof src === "string") {
75
1586
  const url2 = new URL(
@@ -85,19 +1596,14 @@ function RemoteComponent({
85
1596
  return nameProp;
86
1597
  }, [src, nameProp]);
87
1598
  const [data, setData] = (0, import_react2.useState)(null);
88
- const url = (0, import_react2.useMemo)(() => (0, import_get_client_or_server_url.getClientOrServerUrl)(src, DUMMY_FALLBACK), [src]);
1599
+ const url = (0, import_react2.useMemo)(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);
89
1600
  const id = url.origin === (typeof location !== "undefined" ? location.origin : DUMMY_FALLBACK) ? url.pathname : url.href;
90
- const keySuffix = `${(0, import_utils.escapeString)(id)}_${(0, import_utils.escapeString)(data?.name ?? name)}`;
1601
+ const keySuffix = `${escapeString(id)}_${escapeString(data?.name ?? name)}_${escapeString(instanceId)}`;
91
1602
  const [remoteComponent, setRemoteComponent] = (0, import_react2.useState)(null);
92
- const shadowRootContainerRef = (0, import_react2.useRef)(null);
93
- const [shadowRoot, setShadowRoot] = (0, import_react2.useState)(() => {
94
- const self = globalThis;
95
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
96
- const ssrShadowRoot = typeof document !== "undefined" ? document.querySelector(
97
- `[data-remote-component-id="shadowroot_${keySuffix}"]`
98
- )?.shadowRoot ?? self[shadowRootKey] ?? null : null;
99
- self[shadowRootKey] = null;
100
- return ssrShadowRoot;
1603
+ const { shadowRoot, shadowRootContainerRef } = useShadowRoot({
1604
+ isolate,
1605
+ mode,
1606
+ keySuffix
101
1607
  });
102
1608
  const htmlRef = (0, import_react2.useRef)(
103
1609
  typeof document !== "undefined" ? document.querySelector(
@@ -125,6 +1631,12 @@ function RemoteComponent({
125
1631
  const prevRemoteComponentContainerRef = (0, import_react2.useRef)(null);
126
1632
  const unmountRef = (0, import_react2.useRef)(null);
127
1633
  const prevNameRef = (0, import_react2.useRef)(void 0);
1634
+ (0, import_react2.useLayoutEffect)(() => {
1635
+ const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
1636
+ return () => {
1637
+ delete globalThis[shadowRootKey];
1638
+ };
1639
+ }, [keySuffix]);
128
1640
  (0, import_react2.useLayoutEffect)(() => {
129
1641
  if (childrenRef.current.length > 0 && remoteComponent) {
130
1642
  childrenRef.current.forEach((el) => {
@@ -132,29 +1644,7 @@ function RemoteComponent({
132
1644
  });
133
1645
  childrenRef.current = [];
134
1646
  }
135
- if (isolate !== false && typeof document !== "undefined" && (!shadowRoot || !shadowRoot.isConnected)) {
136
- const self = globalThis;
137
- const shadowRootKey = `__remote_components_shadowroot_${keySuffix}`;
138
- let shadowRootElement = null;
139
- const element = document.querySelector(
140
- `[data-remote-component-id="shadowroot_${keySuffix}"]`
141
- );
142
- shadowRootElement = self[shadowRootKey] ?? element?.shadowRoot ?? null;
143
- if (!shadowRootElement && element) {
144
- try {
145
- shadowRootElement = element.attachShadow({ mode });
146
- self[shadowRootKey] = shadowRootElement;
147
- } catch {
148
- }
149
- }
150
- if (shadowRootElement) {
151
- shadowRootElement.querySelectorAll("*:not(link)").forEach((node) => {
152
- node.remove();
153
- });
154
- setShadowRoot(shadowRootElement);
155
- }
156
- }
157
- }, [isolate, shadowRoot, remoteComponent, mode, keySuffix]);
1647
+ }, [remoteComponent]);
158
1648
  (0, import_react2.useLayoutEffect)(() => {
159
1649
  if (shadowRoot && remoteComponent) {
160
1650
  const resetStyles = shadowRoot.querySelectorAll(
@@ -192,12 +1682,15 @@ function RemoteComponent({
192
1682
  if (!html && src) {
193
1683
  const fetchInit = {
194
1684
  method: "GET",
195
- headers: (0, import_fetch_headers.remoteFetchHeaders)(additionalHeaders),
1685
+ headers: remoteFetchHeaders(),
196
1686
  credentials
197
1687
  };
198
- const res = await fetch(url, fetchInit);
1688
+ const res = await fetchWithHooks(url, fetchInit, {
1689
+ onRequest,
1690
+ onResponse
1691
+ });
199
1692
  if (!res.ok) {
200
- let error = (0, import_error.failedToFetchRemoteComponentError)(
1693
+ let error = failedToFetchRemoteComponentError(
201
1694
  url.href,
202
1695
  res
203
1696
  );
@@ -215,7 +1708,7 @@ function RemoteComponent({
215
1708
  "data-next-error-stack"
216
1709
  );
217
1710
  if (errorMessage) {
218
- error = new import_remote_component.RemoteComponentsError(errorMessage);
1711
+ error = new RemoteComponentsError(errorMessage);
219
1712
  if (errorStack) {
220
1713
  error.stack = errorStack;
221
1714
  }
@@ -233,7 +1726,7 @@ function RemoteComponent({
233
1726
  if (doc.querySelectorAll("div[data-bundle][data-route]").length > 1 && !doc.querySelector(
234
1727
  `div[data-bundle][data-route][id^="${name}"]`
235
1728
  ) || doc.querySelectorAll("remote-component:not([src])").length > 1 && !doc.querySelector(`remote-component[name="${name}"]`)) {
236
- throw (0, import_error.multipleRemoteComponentsError)(url.href);
1729
+ throw multipleRemoteComponentsError(url.href);
237
1730
  }
238
1731
  const component = doc.querySelector(`div[data-bundle][data-route][id^="${name}"]`) ?? // fallback to the first element with the data-bundle and data-route attributes when not using a named remote component
239
1732
  doc.querySelector("div[data-bundle][data-route]") ?? // fallback to Next.js Pages Router
@@ -249,8 +1742,8 @@ function RemoteComponent({
249
1742
  const metadata = {
250
1743
  name: remoteName,
251
1744
  bundle,
252
- route: component?.getAttribute("data-route") ?? nextData?.page ?? (url.pathname || import_remote_component.DEFAULT_ROUTE),
253
- runtime: component?.getAttribute("data-runtime") ?? (nextData?.props.__REMOTE_COMPONENT__?.runtime || import_remote_component.RUNTIME_SCRIPT)
1745
+ route: component?.getAttribute("data-route") ?? nextData?.page ?? (url.pathname || DEFAULT_ROUTE),
1746
+ runtime: component?.getAttribute("data-runtime") ?? (nextData?.props.__REMOTE_COMPONENT__?.runtime || RUNTIME_SCRIPT)
254
1747
  };
255
1748
  const remoteSharedEl = doc.querySelector(
256
1749
  `#${remoteName}_shared[data-remote-components-shared]`
@@ -258,7 +1751,7 @@ function RemoteComponent({
258
1751
  const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
259
1752
  remoteSharedEl?.remove();
260
1753
  if (!component || !(rsc || nextData || isRemoteComponent)) {
261
- throw new import_remote_component.RemoteComponentsError(
1754
+ throw new RemoteComponentsError(
262
1755
  `Remote Component not found on ${url.href}.${remoteName !== "__vercel_remote_component" ? `The name for the <RemoteComponent> is "${remoteName}". Check <RemoteComponent> usage.` : ""} Did you forget to wrap the content in <RemoteComponent>?`
263
1756
  );
264
1757
  }
@@ -283,7 +1776,7 @@ function RemoteComponent({
283
1776
  prevIsRemoteComponentRef.current = isRemoteComponent;
284
1777
  prevUrlRef.current = url;
285
1778
  prevNameRef.current = remoteName;
286
- (0, import_apply_origin.applyOriginToNodes)(doc, url);
1779
+ applyOriginToNodes(doc, url);
287
1780
  const links = Array.from(
288
1781
  doc.querySelectorAll("link[href]")
289
1782
  ).filter((link) => {
@@ -292,7 +1785,7 @@ function RemoteComponent({
292
1785
  href: new URL(link.getAttribute("href") ?? link.href, url).href,
293
1786
  ...link.getAttributeNames().reduce((acc, key) => {
294
1787
  if (key !== "href") {
295
- acc[import_utils.attrToProp[key] ?? key] = link.getAttribute(key) ?? "";
1788
+ acc[attrToProp[key] ?? key] = link.getAttribute(key) ?? "";
296
1789
  }
297
1790
  return acc;
298
1791
  }, {})
@@ -350,16 +1843,16 @@ function RemoteComponent({
350
1843
  if (typeof props.children === "string") {
351
1844
  script.textContent = props.children;
352
1845
  }
353
- (0, import_remote_component.setAttributesFromProps)(script, props);
1846
+ setAttributesFromProps(script, props);
354
1847
  document.head.appendChild(script);
355
1848
  });
356
1849
  self.__next_s = prevNextScripts;
357
1850
  }
358
1851
  let rscName;
359
1852
  if (rsc) {
360
- rscName = `__remote_component_rsc_${(0, import_utils.escapeString)(
1853
+ rscName = `__remote_component_rsc_${escapeString(
361
1854
  id
362
- )}_${(0, import_utils.escapeString)(remoteName)}`;
1855
+ )}_${escapeString(remoteName)}`;
363
1856
  rsc.textContent = rsc.textContent?.replace(
364
1857
  new RegExp(`self\\["${remoteName}"\\]`, "g"),
365
1858
  `self["${rscName}"]`
@@ -383,7 +1876,7 @@ function RemoteComponent({
383
1876
  throw e;
384
1877
  });
385
1878
  } else if ("__remote_components_missing_shared__" in remoteShared) {
386
- throw new import_remote_component.RemoteComponentsError(
1879
+ throw new RemoteComponentsError(
387
1880
  remoteShared.__remote_components_missing_shared__
388
1881
  );
389
1882
  }
@@ -404,7 +1897,7 @@ function RemoteComponent({
404
1897
  }
405
1898
  shadowRoot.innerHTML = shadowRootHtml;
406
1899
  setRemoteComponent(null);
407
- const { mount, unmount } = await (0, import_remote_component.loadStaticRemoteComponent)(
1900
+ const { mount, unmount } = await loadStaticRemoteComponent(
408
1901
  Array.from(shadowRoot.querySelectorAll("script")),
409
1902
  url
410
1903
  );
@@ -415,7 +1908,7 @@ function RemoteComponent({
415
1908
  onLoad?.(src);
416
1909
  } else if (isolate === false) {
417
1910
  setRemoteComponent(
418
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1911
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
419
1912
  "div",
420
1913
  {
421
1914
  dangerouslySetInnerHTML: { __html: component.innerHTML },
@@ -423,7 +1916,7 @@ function RemoteComponent({
423
1916
  }
424
1917
  )
425
1918
  );
426
- const { mount, unmount } = await (0, import_remote_component.loadStaticRemoteComponent)(
1919
+ const { mount, unmount } = await loadStaticRemoteComponent(
427
1920
  Array.from(component.querySelectorAll("script")),
428
1921
  url
429
1922
  );
@@ -436,7 +1929,7 @@ function RemoteComponent({
436
1929
  onLoad?.(src);
437
1930
  }
438
1931
  } else {
439
- const result = await (0, import_remote_component.loadRemoteComponent)({
1932
+ const result = await loadRemoteComponent({
440
1933
  url,
441
1934
  name: remoteName,
442
1935
  rscName,
@@ -447,7 +1940,7 @@ function RemoteComponent({
447
1940
  nextData,
448
1941
  scripts: Array.from(scripts).map((script) => {
449
1942
  const scriptSrc = script.getAttribute("data-src") || script.getAttribute("src") || script.src;
450
- const { prefix, id: path } = import_remote_component.REMOTE_COMPONENT_REGEX.exec(
1943
+ const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(
451
1944
  scriptSrc
452
1945
  )?.groups ?? {
453
1946
  prefix: void 0,
@@ -464,7 +1957,7 @@ function RemoteComponent({
464
1957
  };
465
1958
  }),
466
1959
  shared: {
467
- ...(0, import_polyfill.sharedPolyfills)(userShared),
1960
+ ...sharedPolyfills(userShared),
468
1961
  ...userShared
469
1962
  },
470
1963
  remoteShared,
@@ -504,25 +1997,26 @@ function RemoteComponent({
504
1997
  name,
505
1998
  shared,
506
1999
  shadowRoot,
507
- additionalHeaders,
508
2000
  reset,
509
2001
  id,
510
2002
  onBeforeLoad,
511
2003
  onLoad,
512
2004
  onError,
513
- onChange
2005
+ onChange,
2006
+ onRequest,
2007
+ onResponse
514
2008
  ]);
515
2009
  if (remoteComponent instanceof Error) {
516
2010
  throw remoteComponent;
517
2011
  }
518
- const metadataJson = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("script", { "data-remote-component": true, type: "application/json", children: JSON.stringify({
2012
+ const metadataJson = /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("script", { "data-remote-component": true, type: "application/json", children: JSON.stringify({
519
2013
  name: data?.name || name,
520
2014
  bundle: data?.bundle || "default",
521
- route: data?.route || import_remote_component.DEFAULT_ROUTE,
522
- runtime: prevIsRemoteComponentRef.current ? import_remote_component.RUNTIME_SCRIPT : data?.runtime || import_remote_component.RUNTIME_WEBPACK
2015
+ route: data?.route || DEFAULT_ROUTE,
2016
+ runtime: prevIsRemoteComponentRef.current ? RUNTIME_SCRIPT : data?.runtime || RUNTIME_WEBPACK
523
2017
  }) });
524
- const resetStyle = reset ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("style", { "data-remote-components-reset": "react", children: `:host { all: initial; }` }) : null;
525
- const linksToRender = data?.links?.map((link) => /* @__PURE__ */ (0, import_react.createElement)(
2018
+ const resetStyle = reset ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("style", { "data-remote-components-reset": "react", children: `:host { all: initial; }` }) : null;
2019
+ const linksToRender = data?.links?.map((link) => /* @__PURE__ */ (0, import_react3.createElement)(
526
2020
  "link",
527
2021
  {
528
2022
  ...link,
@@ -530,7 +2024,7 @@ function RemoteComponent({
530
2024
  key: JSON.stringify(link)
531
2025
  }
532
2026
  )) || null;
533
- const componentToRender = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
2027
+ const componentToRender = /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
534
2028
  resetStyle,
535
2029
  linksToRender,
536
2030
  remoteComponent ?? children
@@ -539,7 +2033,7 @@ function RemoteComponent({
539
2033
  shadowRoot.innerHTML = componentHydrationHtml.current;
540
2034
  componentHydrationHtml.current = null;
541
2035
  if (prevIsRemoteComponentRef.current) {
542
- (0, import_remote_component.loadStaticRemoteComponent)(
2036
+ loadStaticRemoteComponent(
543
2037
  Array.from(shadowRoot.querySelectorAll("script")),
544
2038
  url
545
2039
  ).then(({ mount }) => {
@@ -551,7 +2045,7 @@ function RemoteComponent({
551
2045
  onLoad?.(src);
552
2046
  }
553
2047
  }).catch((e) => {
554
- const error = new import_remote_component.RemoteComponentsError(
2048
+ const error = new RemoteComponentsError(
555
2049
  `Error mounting remote component from "${url.href}"`,
556
2050
  {
557
2051
  cause: e
@@ -567,9 +2061,9 @@ function RemoteComponent({
567
2061
  if (shadowRemoteComponentHtml) {
568
2062
  shadowRemoteComponentHtml.remove();
569
2063
  }
570
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
2064
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
571
2065
  metadataJson,
572
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
2066
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
573
2067
  "div",
574
2068
  {
575
2069
  "data-remote-component-id": `shadowroot_${keySuffix}`,
@@ -578,8 +2072,8 @@ function RemoteComponent({
578
2072
  children: [
579
2073
  typeof document === "undefined" ? (
580
2074
  // eslint-disable-next-line react/no-unknown-property
581
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("template", { shadowrootmode: mode, children: [
582
- typeof document === "undefined" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
2075
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("template", { shadowrootmode: mode, children: [
2076
+ typeof document === "undefined" ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
583
2077
  "div",
584
2078
  {
585
2079
  dangerouslySetInnerHTML: {
@@ -601,12 +2095,12 @@ function RemoteComponent({
601
2095
  ] })
602
2096
  ) : null,
603
2097
  shadowRoot && remoteComponent ? (0, import_react_dom.createPortal)(
604
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
605
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("template", { id: `${name}_start` }),
2098
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
2099
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("template", { id: `${name}_start` }),
606
2100
  resetStyle,
607
2101
  linksToRender,
608
2102
  remoteComponent,
609
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("template", { id: `${name}_end`, ref: endTemplateRef })
2103
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("template", { id: `${name}_end`, ref: endTemplateRef })
610
2104
  ] }),
611
2105
  shadowRoot
612
2106
  ) : null
@@ -616,11 +2110,11 @@ function RemoteComponent({
616
2110
  ] });
617
2111
  }
618
2112
  htmlRef.current = null;
619
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
620
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("template", { id: `${name}_start` }),
2113
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
2114
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("template", { id: `${name}_start` }),
621
2115
  metadataJson,
622
2116
  componentToRender,
623
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("template", { id: `${name}_end`, ref: endTemplateRef })
2117
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("template", { id: `${name}_end`, ref: endTemplateRef })
624
2118
  ] });
625
2119
  }
626
2120
  // Annotate the CommonJS export names for ESM import in node: