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