remote-components 0.0.29 → 0.0.31

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