remote-components 0.3.4 → 0.3.6

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 (153) hide show
  1. package/dist/app-63L5THIQ.js +12 -0
  2. package/dist/app-63L5THIQ.js.map +1 -0
  3. package/dist/app-A5QE7XRH.cjs +12 -0
  4. package/dist/app-A5QE7XRH.cjs.map +1 -0
  5. package/dist/chunk-2VQGCACH.js +190 -0
  6. package/dist/chunk-2VQGCACH.js.map +1 -0
  7. package/dist/chunk-42N2ZLE2.js +703 -0
  8. package/dist/chunk-42N2ZLE2.js.map +1 -0
  9. package/dist/chunk-6IUP26UK.cjs +57 -0
  10. package/dist/chunk-6IUP26UK.cjs.map +1 -0
  11. package/dist/chunk-7MVFHOIP.cjs +60 -0
  12. package/dist/chunk-7MVFHOIP.cjs.map +1 -0
  13. package/dist/chunk-CREXMFMF.cjs +155 -0
  14. package/dist/chunk-CREXMFMF.cjs.map +1 -0
  15. package/dist/chunk-CTUJSWCM.js +215 -0
  16. package/dist/chunk-CTUJSWCM.js.map +1 -0
  17. package/dist/chunk-ENYGL5CO.js +11 -0
  18. package/dist/chunk-ENYGL5CO.js.map +1 -0
  19. package/dist/chunk-ER73O65F.cjs +703 -0
  20. package/dist/chunk-ER73O65F.cjs.map +1 -0
  21. package/dist/chunk-F44NODUS.cjs +709 -0
  22. package/dist/chunk-F44NODUS.cjs.map +1 -0
  23. package/dist/chunk-GAXJTFBV.js +20 -0
  24. package/dist/chunk-GAXJTFBV.js.map +1 -0
  25. package/dist/chunk-HNZVEIKN.js +358 -0
  26. package/dist/chunk-HNZVEIKN.js.map +1 -0
  27. package/dist/chunk-KE7QPAQ4.cjs +21 -0
  28. package/dist/chunk-KE7QPAQ4.cjs.map +1 -0
  29. package/dist/chunk-KEPHL25S.js +60 -0
  30. package/dist/chunk-KEPHL25S.js.map +1 -0
  31. package/dist/chunk-KKBEMQU7.cjs +670 -0
  32. package/dist/chunk-KKBEMQU7.cjs.map +1 -0
  33. package/dist/chunk-KYJWRZ2B.js +709 -0
  34. package/dist/chunk-KYJWRZ2B.js.map +1 -0
  35. package/dist/chunk-N5VQR2PW.cjs +215 -0
  36. package/dist/chunk-N5VQR2PW.cjs.map +1 -0
  37. package/dist/chunk-OO4AMJWO.js +155 -0
  38. package/dist/chunk-OO4AMJWO.js.map +1 -0
  39. package/dist/chunk-R4QFK5TN.cjs +358 -0
  40. package/dist/chunk-R4QFK5TN.cjs.map +1 -0
  41. package/dist/chunk-RUWR74XQ.cjs +152 -0
  42. package/dist/chunk-RUWR74XQ.cjs.map +1 -0
  43. package/dist/chunk-S2A4TFLS.js +152 -0
  44. package/dist/chunk-S2A4TFLS.js.map +1 -0
  45. package/dist/chunk-SHFJ5OQA.cjs +11 -0
  46. package/dist/chunk-SHFJ5OQA.cjs.map +1 -0
  47. package/dist/chunk-TCFLEBQM.cjs +20 -0
  48. package/dist/chunk-TCFLEBQM.cjs.map +1 -0
  49. package/dist/chunk-W5ESPGHH.js +670 -0
  50. package/dist/chunk-W5ESPGHH.js.map +1 -0
  51. package/dist/chunk-X6YKUJKH.js +21 -0
  52. package/dist/chunk-X6YKUJKH.js.map +1 -0
  53. package/dist/chunk-XCFYWSLD.cjs +190 -0
  54. package/dist/chunk-XCFYWSLD.cjs.map +1 -0
  55. package/dist/chunk-ZPMTZ3KJ.js +57 -0
  56. package/dist/chunk-ZPMTZ3KJ.js.map +1 -0
  57. package/dist/config/nextjs.cjs +76 -351
  58. package/dist/config/nextjs.cjs.map +1 -1
  59. package/dist/config/nextjs.js +26 -266
  60. package/dist/config/nextjs.js.map +1 -1
  61. package/dist/config/webpack.cjs +12 -240
  62. package/dist/config/webpack.cjs.map +1 -1
  63. package/dist/config/webpack.js +6 -207
  64. package/dist/config/webpack.js.map +1 -1
  65. package/dist/host/html.cjs +139 -2447
  66. package/dist/host/html.cjs.map +1 -1
  67. package/dist/host/html.js +66 -2345
  68. package/dist/host/html.js.map +1 -1
  69. package/dist/host/nextjs/app/client-only.cjs +53 -2825
  70. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  71. package/dist/host/nextjs/app/client-only.js +31 -2780
  72. package/dist/host/nextjs/app/client-only.js.map +1 -1
  73. package/dist/host/nextjs/app.cjs +34 -2
  74. package/dist/host/nextjs/app.cjs.map +1 -1
  75. package/dist/host/nextjs/app.js +35 -3
  76. package/dist/host/nextjs/app.js.map +1 -1
  77. package/dist/host/proxy/client.cjs +8 -38
  78. package/dist/host/proxy/client.cjs.map +1 -1
  79. package/dist/host/proxy/client.js +4 -7
  80. package/dist/host/proxy/client.js.map +1 -1
  81. package/dist/host/proxy.cjs +19 -56
  82. package/dist/host/proxy.cjs.map +1 -1
  83. package/dist/host/proxy.js +8 -20
  84. package/dist/host/proxy.js.map +1 -1
  85. package/dist/host/react.cjs +17 -2756
  86. package/dist/host/react.cjs.map +1 -1
  87. package/dist/host/react.js +13 -2723
  88. package/dist/host/react.js.map +1 -1
  89. package/dist/internal/host/nextjs/app-client.cjs +38 -24
  90. package/dist/internal/host/nextjs/app-client.cjs.map +1 -1
  91. package/dist/internal/host/nextjs/app-client.js +38 -24
  92. package/dist/internal/host/nextjs/app-client.js.map +1 -1
  93. package/dist/internal/host/nextjs/remote-component-links.cjs +24 -13
  94. package/dist/internal/host/nextjs/remote-component-links.cjs.map +1 -1
  95. package/dist/internal/host/nextjs/remote-component-links.d.ts +3 -0
  96. package/dist/internal/host/nextjs/remote-component-links.js +24 -13
  97. package/dist/internal/host/nextjs/remote-component-links.js.map +1 -1
  98. package/dist/internal/host/server/fetch-remote-component.cjs +1 -18
  99. package/dist/internal/host/server/fetch-remote-component.cjs.map +1 -1
  100. package/dist/internal/host/server/fetch-remote-component.js +1 -18
  101. package/dist/internal/host/server/fetch-remote-component.js.map +1 -1
  102. package/dist/internal/host/shared/lifecycle.cjs +69 -0
  103. package/dist/internal/host/shared/lifecycle.cjs.map +1 -0
  104. package/dist/internal/host/shared/lifecycle.d.ts +34 -0
  105. package/dist/internal/host/shared/lifecycle.js +44 -0
  106. package/dist/internal/host/shared/lifecycle.js.map +1 -0
  107. package/dist/internal/host/shared/pipeline.cjs +222 -0
  108. package/dist/internal/host/shared/pipeline.cjs.map +1 -0
  109. package/dist/internal/host/shared/pipeline.d.ts +153 -0
  110. package/dist/internal/host/shared/pipeline.js +200 -0
  111. package/dist/internal/host/shared/pipeline.js.map +1 -0
  112. package/dist/internal/runtime/loaders/component-loader.cjs +5 -2
  113. package/dist/internal/runtime/loaders/component-loader.cjs.map +1 -1
  114. package/dist/internal/runtime/loaders/component-loader.js +5 -2
  115. package/dist/internal/runtime/loaders/component-loader.js.map +1 -1
  116. package/dist/internal/runtime/turbopack/patterns.cjs +1 -1
  117. package/dist/internal/runtime/turbopack/patterns.cjs.map +1 -1
  118. package/dist/internal/runtime/turbopack/patterns.js +1 -1
  119. package/dist/internal/runtime/turbopack/patterns.js.map +1 -1
  120. package/dist/internal/runtime/turbopack/remote-scope-setup.cjs.map +1 -1
  121. package/dist/internal/runtime/turbopack/remote-scope-setup.js.map +1 -1
  122. package/dist/internal/runtime/turbopack/remote-scope.cjs +1 -5
  123. package/dist/internal/runtime/turbopack/remote-scope.cjs.map +1 -1
  124. package/dist/internal/runtime/turbopack/remote-scope.js +1 -5
  125. package/dist/internal/runtime/turbopack/remote-scope.js.map +1 -1
  126. package/dist/internal/utils.cjs +1 -1
  127. package/dist/internal/utils.cjs.map +1 -1
  128. package/dist/internal/utils.d.ts +5 -5
  129. package/dist/internal/utils.js +1 -1
  130. package/dist/internal/utils.js.map +1 -1
  131. package/dist/remote/html.cjs +15 -314
  132. package/dist/remote/html.cjs.map +1 -1
  133. package/dist/remote/html.js +7 -305
  134. package/dist/remote/html.js.map +1 -1
  135. package/dist/remote/middleware.cjs +16 -41
  136. package/dist/remote/middleware.cjs.map +1 -1
  137. package/dist/script-6W5JRBZK.cjs +26 -0
  138. package/dist/script-6W5JRBZK.cjs.map +1 -0
  139. package/dist/script-IFEBOLIA.js +26 -0
  140. package/dist/script-IFEBOLIA.js.map +1 -0
  141. package/dist/static-loader-X4TSF5KW.js +11 -0
  142. package/dist/static-loader-X4TSF5KW.js.map +1 -0
  143. package/dist/static-loader-ZYD5BO4D.cjs +11 -0
  144. package/dist/static-loader-ZYD5BO4D.cjs.map +1 -0
  145. package/dist/turbopack-NPGO3MWS.js +55 -0
  146. package/dist/turbopack-NPGO3MWS.js.map +1 -0
  147. package/dist/turbopack-WRMKPNN4.cjs +55 -0
  148. package/dist/turbopack-WRMKPNN4.cjs.map +1 -0
  149. package/dist/webpack-DUBHPYD6.js +92 -0
  150. package/dist/webpack-DUBHPYD6.js.map +1 -0
  151. package/dist/webpack-KSCMCL7M.cjs +92 -0
  152. package/dist/webpack-KSCMCL7M.cjs.map +1 -0
  153. package/package.json +10 -3
@@ -1,399 +1,31 @@
1
1
  "use client";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __esm = (fn, res) => function __init() {
5
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
- };
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
-
12
- // src/utils/constants.ts
13
- var RC_PROTECTED_REMOTE_FETCH_PATHNAME, MISSING_SHARED_MODULES_MESSAGE, CORS_DOCS_URL;
14
- var init_constants = __esm({
15
- "src/utils/constants.ts"() {
16
- "use strict";
17
- RC_PROTECTED_REMOTE_FETCH_PATHNAME = "/rc-fetch-protected-remote";
18
- MISSING_SHARED_MODULES_MESSAGE = "Remote Components shared modules not found. Did you forget to wrap your config with `withRemoteComponentsConfig` on both host and remote?";
19
- CORS_DOCS_URL = "https://vercel.com/docs/remote-components/concepts/cors-external-urls#accessing-cross-site-protected-remote-components";
20
- }
21
- });
22
-
23
- // src/host/defaults/shared.ts
24
- var shared;
25
- var init_shared = __esm({
26
- "src/host/defaults/shared.ts"() {
27
- "use strict";
28
- init_constants();
29
- shared = {
30
- __remote_components_missing_shared__: () => Promise.reject(new Error(MISSING_SHARED_MODULES_MESSAGE))
31
- };
32
- }
33
- });
34
-
35
- // src/host/defaults/app.ts
36
- var app_exports = {};
37
- __export(app_exports, {
38
- shared: () => shared
39
- });
40
- var init_app = __esm({
41
- "src/host/defaults/app.ts"() {
42
- "use strict";
43
- init_shared();
44
- }
45
- });
2
+ import {
3
+ ConsumeRemoteComponent
4
+ } from "../../../chunk-W5ESPGHH.js";
5
+ import {
6
+ bindResolveClientUrl
7
+ } from "../../../chunk-42N2ZLE2.js";
8
+ import "../../../chunk-ZPMTZ3KJ.js";
9
+ import "../../../chunk-KYJWRZ2B.js";
10
+ import "../../../chunk-2VQGCACH.js";
11
+ import "../../../chunk-OO4AMJWO.js";
12
+ import {
13
+ createRemoteImageLoader,
14
+ getScope
15
+ } from "../../../chunk-HNZVEIKN.js";
16
+ import "../../../chunk-KEPHL25S.js";
17
+ import {
18
+ logWarn
19
+ } from "../../../chunk-S2A4TFLS.js";
20
+ import "../../../chunk-GAXJTFBV.js";
21
+ import "../../../chunk-X6YKUJKH.js";
22
+ import "../../../chunk-ENYGL5CO.js";
46
23
 
47
24
  // src/host/nextjs/app-client-only.tsx
48
- import { useMemo as useMemo3 } from "react";
25
+ import { useMemo } from "react";
49
26
 
50
27
  // src/host/nextjs/image-shared.ts
51
28
  import { createElement, forwardRef } from "react";
52
-
53
- // src/utils/index.ts
54
- function escapeString(str) {
55
- return str.replace(/[^a-z0-9]/g, "_");
56
- }
57
- function computeScopedName(name, options) {
58
- return options.isCrossOrigin ? `${name}_${escapeString(options.remoteHost.toLowerCase())}` : name;
59
- }
60
- var attrToProp = {
61
- fetchpriority: "fetchPriority",
62
- crossorigin: "crossOrigin",
63
- imagesrcset: "imageSrcSet",
64
- imagesizes: "imageSizes",
65
- srcset: "srcSet"
66
- };
67
-
68
- // src/runtime/constants.ts
69
- var DEFAULT_BUNDLE_NAME = "__vercel_remote_bundle";
70
- var DEFAULT_COMPONENT_NAME = "__vercel_remote_component";
71
- var DEFAULT_ROUTE = "/";
72
- var RUNTIME_WEBPACK = "webpack";
73
- var RUNTIME_TURBOPACK = "turbopack";
74
- var RUNTIME_SCRIPT = "script";
75
- function getBundleKey(bundle) {
76
- return escapeString(bundle);
77
- }
78
-
79
- // src/runtime/namespace.ts
80
- var SHADOW_ROOT_PREFIX = "__remote_components_shadowroot_";
81
- var LEGACY_ALIASES = [
82
- { global: "__remote_component_scopes__", prop: "scopes" },
83
- {
84
- global: "__remote_components_turbopack_chunk_loader_promise__",
85
- prop: "chunkCache"
86
- },
87
- { global: "__remote_script_entrypoint_mount__", prop: "mountFns" },
88
- { global: "__remote_script_entrypoint_unmount__", prop: "unmountFns" },
89
- { global: "__remote_bundle_url__", prop: "bundleUrls" },
90
- { global: "__rc_module_registry__", prop: "moduleRegistry" },
91
- {
92
- global: "__remote_component_host_shared_modules__",
93
- prop: "hostSharedModules"
94
- },
95
- { global: "__remote_next_css__", prop: "cssCache" }
96
- ];
97
- function getNamespace() {
98
- const g = globalThis;
99
- const existing = g.__remote_components__;
100
- if (existing) {
101
- return existing;
102
- }
103
- const ns = {
104
- scopes: /* @__PURE__ */ new Map(),
105
- chunkCache: {},
106
- mountFns: {},
107
- unmountFns: {},
108
- bundleUrls: {},
109
- moduleRegistry: {},
110
- dispatcherRuntime: void 0,
111
- hostSharedModules: {},
112
- cssCache: {},
113
- shadowRoots: {}
114
- };
115
- const nsRecord = ns;
116
- for (const { global, prop } of LEGACY_ALIASES) {
117
- const legacyValue = g[global];
118
- if (legacyValue != null) {
119
- nsRecord[prop] = legacyValue;
120
- }
121
- g[global] = ns[prop];
122
- }
123
- const gRecord = g;
124
- for (const key of Object.keys(gRecord)) {
125
- if (key.startsWith(SHADOW_ROOT_PREFIX)) {
126
- const suffix = key.slice(SHADOW_ROOT_PREFIX.length);
127
- ns.shadowRoots[suffix] = gRecord[key];
128
- delete gRecord[key];
129
- }
130
- }
131
- g.__remote_components__ = ns;
132
- return ns;
133
- }
134
-
135
- // src/runtime/patterns.ts
136
- var REMOTE_COMPONENT_REGEX = /(?<prefix>.*?)\[(?<bundle>[^\]]+)\](?:%20| )(?<id>.+)/;
137
- var NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
138
- var DOUBLE_SLASH_RE = /(?<!:)\/\//g;
139
- function collapseDoubleSlashes(path) {
140
- return path.replace(DOUBLE_SLASH_RE, "/");
141
- }
142
-
143
- // src/utils/logger.ts
144
- init_constants();
145
-
146
- // src/runtime/url/protected-rc-fallback.ts
147
- init_constants();
148
- function isProxiedUrl(url) {
149
- try {
150
- return new URL(url, location.href).pathname === RC_PROTECTED_REMOTE_FETCH_PATHNAME;
151
- } catch {
152
- return false;
153
- }
154
- }
155
-
156
- // src/utils/abort.ts
157
- function isAbortError(error) {
158
- if (error instanceof DOMException && error.name === "AbortError") {
159
- return true;
160
- }
161
- if (error !== null && typeof error === "object" && "name" in error && error.name === "AbortError" && "message" in error && typeof error.message === "string") {
162
- const e = error;
163
- return typeof e.code === "number" || e.constructor?.name === "DOMException";
164
- }
165
- return false;
166
- }
167
-
168
- // src/utils/error.ts
169
- init_constants();
170
- var RemoteComponentsError = class extends Error {
171
- code = "REMOTE_COMPONENTS_ERROR";
172
- constructor(message, options) {
173
- super(message, options);
174
- this.name = "RemoteComponentsError";
175
- }
176
- };
177
- function multipleRemoteComponentsError(url) {
178
- return new RemoteComponentsError(
179
- `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.`
180
- );
181
- }
182
- function failedToFetchRemoteComponentError(url, { status, statusText }, help = "Is the URL correct and accessible?") {
183
- return new RemoteComponentsError(
184
- `Failed to fetch Remote Component from "${url}". ${help}`,
185
- { cause: new Error(`${status} ${statusText}`) }
186
- );
187
- }
188
- async function errorFromFailedFetch(originalUrl, resolvedUrl, res) {
189
- const isProxied = isProxiedUrl(resolvedUrl.href);
190
- if (isProxied && res) {
191
- const body = await res.text().catch(() => "");
192
- return failedProxyFetchError(
193
- originalUrl,
194
- resolvedUrl.href,
195
- res.status,
196
- body
197
- );
198
- }
199
- const fallback = failedToFetchRemoteComponentError(
200
- originalUrl,
201
- res ?? { status: 0, statusText: "No Response" }
202
- );
203
- if (!res)
204
- return fallback;
205
- try {
206
- const body = await res.text();
207
- const parser = new DOMParser();
208
- const doc = parser.parseFromString(body, "text/html");
209
- const errorTemplate = doc.querySelector(
210
- "template[data-next-error-message]"
211
- );
212
- const errorMessage = errorTemplate?.getAttribute("data-next-error-message");
213
- if (errorMessage) {
214
- const error = new RemoteComponentsError(errorMessage);
215
- const errorStack = errorTemplate?.getAttribute("data-next-error-stack");
216
- if (errorStack) {
217
- error.stack = errorStack;
218
- }
219
- return error;
220
- }
221
- } catch (parseError) {
222
- if (isAbortError(parseError))
223
- throw parseError;
224
- }
225
- return fallback;
226
- }
227
- function failedProxiedAssetError(kind, url, resolvedUrl) {
228
- return new RemoteComponentsError(
229
- `Failed to load ${kind} "${url}" via proxy "${resolvedUrl}". Ensure withRemoteComponentsHostProxy middleware is configured, "${RC_PROTECTED_REMOTE_FETCH_PATHNAME}" is in the matcher, and the remote URL is included in allowedProxyUrls. See: ${CORS_DOCS_URL}`
230
- );
231
- }
232
- function failedProxyFetchError(originalUrl, proxyUrl, status, responseBody) {
233
- if (status === 404) {
234
- return new RemoteComponentsError(
235
- `Could not proxy the request to "${originalUrl}" \u2014 the proxy endpoint "${RC_PROTECTED_REMOTE_FETCH_PATHNAME}" returned 404.
236
-
237
- The host server needs middleware or a route that handles "${RC_PROTECTED_REMOTE_FETCH_PATHNAME}".
238
-
239
- Proxying requires two pieces:
240
- 1. resolveClientUrl={routeThroughHostProxy} on <RemoteComponent>
241
- 2. Middleware or a route for "${RC_PROTECTED_REMOTE_FETCH_PATHNAME}" on the host server
242
-
243
- Docs: ${CORS_DOCS_URL}`
244
- );
245
- }
246
- if (status === 403) {
247
- const detail = responseBody ? ` ${responseBody}` : "";
248
- return new RemoteComponentsError(
249
- `Proxied request to "${proxyUrl}" was forbidden.${detail} See: ${CORS_DOCS_URL}`
250
- );
251
- }
252
- return new RemoteComponentsError(
253
- `Proxied request for "${originalUrl}" via "${proxyUrl}" failed with status ${status}. See: ${CORS_DOCS_URL}`
254
- );
255
- }
256
-
257
- // src/utils/logger.ts
258
- var PREFIX = "remote-components";
259
- var DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true" || typeof process !== "undefined" && process.env.RC_DEBUG === "true";
260
- function logDebug(location2, message) {
261
- if (DEBUG) {
262
- console.debug(`[${PREFIX}:${location2}]: ${message}`);
263
- }
264
- }
265
- function logWarn(location2, message) {
266
- console.warn(`[${PREFIX}:${location2}]: ${message}`);
267
- }
268
- function logError(location2, message, cause) {
269
- console.error(
270
- new RemoteComponentsError(`[${PREFIX}:${location2}]: ${message}`, {
271
- cause
272
- })
273
- );
274
- }
275
- function warnCrossOriginFetchError(logLocation, url) {
276
- try {
277
- const parsed = typeof url === "string" ? new URL(url) : url;
278
- if (typeof location === "undefined" || parsed.origin === location.origin) {
279
- return;
280
- }
281
- logWarn(
282
- logLocation,
283
- `Failed to fetch cross-origin resource "${parsed.href}". To load assets from a protected deployment, two steps are required: (1) configure withRemoteComponentsHostProxy middleware in your host with the remote URL in allowedProxyUrls, and (2) provide a resolveClientUrl prop that rewrites cross-origin asset URLs to go through the proxy. See: ${CORS_DOCS_URL}`
284
- );
285
- } catch {
286
- }
287
- }
288
-
289
- // src/runtime/turbopack/remote-scope.ts
290
- function getRegistry() {
291
- return getNamespace().scopes;
292
- }
293
- function createScope(name, url, runtime, resolveClientUrl) {
294
- const isCrossOrigin = url.origin !== location.origin;
295
- const scopedName = computeScopedName(name, {
296
- remoteHost: url.host,
297
- isCrossOrigin
298
- });
299
- const globalKey = getBundleKey(scopedName);
300
- return {
301
- name,
302
- scopedName,
303
- globalKey,
304
- url,
305
- runtime,
306
- resolveClientUrl,
307
- moduleCache: {},
308
- sharedModules: {},
309
- moduleGlobal: {},
310
- turbopackModules: []
311
- };
312
- }
313
- function registerScope(scope) {
314
- const registry = getRegistry();
315
- registry.set(scope.scopedName, scope);
316
- if (scope.scopedName !== scope.name) {
317
- const existing = registry.get(scope.name);
318
- if (existing && existing.scopedName !== scope.scopedName) {
319
- logWarn(
320
- "RemoteScope",
321
- `Plain name "${scope.name}" already registered by scope "${existing.scopedName}" \u2014 overwriting with "${scope.scopedName}". Static hosts will only resolve the latest one.`
322
- );
323
- }
324
- registry.set(scope.name, scope);
325
- }
326
- logDebug(
327
- "RemoteScope",
328
- `Registered scope "${scope.scopedName}" (${registry.size} total)`
329
- );
330
- }
331
- function getScope(name) {
332
- return getRegistry().get(name);
333
- }
334
- function formatRemoteId(scope, path) {
335
- return `[${scope.scopedName}] ${path}`;
336
- }
337
- function parseRemoteId(id) {
338
- const groups = REMOTE_COMPONENT_REGEX.exec(id)?.groups;
339
- if (groups?.bundle && groups.id) {
340
- return {
341
- bundle: groups.bundle,
342
- path: groups.id,
343
- prefix: groups.prefix ?? ""
344
- };
345
- }
346
- return { bundle: "default", path: id, prefix: "" };
347
- }
348
-
349
- // src/host/shared/remote-image-loader.ts
350
- function createRemoteImageLoader(bundle, resolveClientUrl) {
351
- const loader = Object.assign(
352
- ({
353
- config,
354
- src,
355
- width,
356
- quality
357
- }) => {
358
- const q = quality ?? 75;
359
- const remoteOrigin = getScope(bundle)?.url.origin ?? "";
360
- const isCrossOrigin = remoteOrigin && remoteOrigin !== location.origin;
361
- const basePath = isCrossOrigin ? `${remoteOrigin}${config.path ?? "/_next/image"}` : config.path ?? `${remoteOrigin}/_next/image`;
362
- const url = `${basePath}?url=${encodeURIComponent(src)}&w=${width}&q=${q}`;
363
- return resolveClientUrl?.(url) ?? url;
364
- },
365
- // Signals to getImgProps that this is a default loader (not a user-defined
366
- // one), enabling srcSet generation with device/image sizes from the config.
367
- { __next_img_default: true }
368
- );
369
- return loader;
370
- }
371
-
372
- // src/runtime/url/resolve-client-url.ts
373
- function withRemoteSrc(resolveClientUrl, remoteSrc) {
374
- const remoteOrigin = parseOrigin(remoteSrc);
375
- return (url) => {
376
- const urlOrigin = parseOrigin(url);
377
- if (remoteOrigin && urlOrigin && urlOrigin !== remoteOrigin) {
378
- return void 0;
379
- }
380
- return resolveClientUrl(remoteSrc, url);
381
- };
382
- }
383
- function parseOrigin(url) {
384
- try {
385
- return new URL(url).origin;
386
- } catch {
387
- return void 0;
388
- }
389
- }
390
-
391
- // src/runtime/url/default-resolve-client-url.ts
392
- function bindResolveClientUrl(prop, remoteSrc) {
393
- return prop ? withRemoteSrc(prop, remoteSrc) : void 0;
394
- }
395
-
396
- // src/host/nextjs/image-shared.ts
397
29
  function resolveForBundle(unbound, bundle) {
398
30
  if (!unbound)
399
31
  return void 0;
@@ -445,8 +77,8 @@ function createImageLoaderSharedEntries({
445
77
  // src/host/nextjs/shared-import.ts
446
78
  async function tryImportShared() {
447
79
  try {
448
- const { shared: shared2 } = await Promise.resolve().then(() => (init_app(), app_exports));
449
- return shared2;
80
+ const { shared } = await import("../../../app-63L5THIQ.js");
81
+ return shared;
450
82
  } catch {
451
83
  return {};
452
84
  }
@@ -455,2387 +87,6 @@ async function tryImportShared() {
455
87
  // src/host/nextjs/app-client-only.tsx
456
88
  import { RemoteComponentsContext } from "#internal/host/react/context";
457
89
 
458
- // src/host/react/index.tsx
459
- import {
460
- startTransition,
461
- useEffect,
462
- useId,
463
- useLayoutEffect as useLayoutEffect2,
464
- useMemo as useMemo2,
465
- useRef as useRef2,
466
- useState as useState2
467
- } from "react";
468
- import { createPortal } from "react-dom";
469
- import { useRemoteComponentsContext as useRemoteComponentsContext2 } from "#internal/host/react/context";
470
-
471
- // src/host/server/fetch-headers.ts
472
- function remoteFetchHeaders() {
473
- return {
474
- /**
475
- * Authenticates deployment protection for the remote. Needed for SSR and SSG clients.
476
- * If the remote component uses vercel deployment protection, ensure the host and remote vercel
477
- * projects share a common automation bypass secret, and the shared secret is used as the
478
- * VERCEL_AUTOMATION_BYPASS_SECRET env var in the host project.
479
- */
480
- ...typeof process === "object" && typeof process.env === "object" && typeof process.env.VERCEL_AUTOMATION_BYPASS_SECRET === "string" ? {
481
- "x-vercel-protection-bypass": process.env.VERCEL_AUTOMATION_BYPASS_SECRET
482
- } : {},
483
- Accept: "text/html"
484
- };
485
- }
486
-
487
- // src/host/server/fetch-with-hooks.ts
488
- async function fetchWithWarning(url, init) {
489
- try {
490
- return await fetch(url, init);
491
- } catch (error) {
492
- warnCrossOriginFetchError("FetchRemoteComponent", url);
493
- throw error;
494
- }
495
- }
496
- async function fetchWithHooks(url, additionalInit, options = {}) {
497
- const {
498
- onRequest,
499
- onResponse,
500
- abortController = new AbortController()
501
- } = options;
502
- const signal = abortController.signal;
503
- const hookOptions = {
504
- signal,
505
- abort: (reason) => abortController.abort(reason)
506
- };
507
- const init = {
508
- method: "GET",
509
- headers: remoteFetchHeaders(),
510
- signal,
511
- ...additionalInit
512
- };
513
- const res = await onRequest?.(url, init, hookOptions) ?? await fetchWithWarning(url, init);
514
- return await onResponse?.(url, res, hookOptions) ?? res;
515
- }
516
-
517
- // src/host/server/get-client-or-server-url.ts
518
- function getClientOrServerUrl(src, serverFallback) {
519
- const fallback = typeof location !== "undefined" ? location.href : serverFallback;
520
- if (!src) {
521
- return new URL(fallback);
522
- }
523
- return typeof src === "string" ? new URL(src, fallback) : src;
524
- }
525
-
526
- // src/host/shared/polyfill.tsx
527
- import { jsx } from "react/jsx-runtime";
528
- function sharedPolyfills(shared2, resolveClientUrl) {
529
- const hostShared = getNamespace().hostSharedModules;
530
- const polyfill = {
531
- "next/dist/client/components/navigation": hostShared["next/navigation"] ?? shared2?.["next/navigation"] ?? (() => Promise.resolve({
532
- useRouter() {
533
- return {
534
- push: (routerUrl) => {
535
- history.pushState({}, "", routerUrl);
536
- },
537
- replace: (routerUrl) => {
538
- history.replaceState({}, "", routerUrl);
539
- },
540
- back: () => {
541
- history.back();
542
- }
543
- };
544
- },
545
- usePathname() {
546
- return location.pathname;
547
- },
548
- useParams() {
549
- return {};
550
- },
551
- useSearchParams() {
552
- return new URLSearchParams(location.search);
553
- },
554
- useSelectedLayoutSegment() {
555
- return null;
556
- },
557
- useSelectedLayoutSegments() {
558
- return [];
559
- },
560
- __esModule: true
561
- })),
562
- "next/dist/client/app-dir/link": hostShared["next/link"] ?? shared2?.["next/link"] ?? (() => Promise.resolve({
563
- default: ({
564
- scroll: _,
565
- replace,
566
- prefetch,
567
- onNavigate,
568
- children,
569
- ...props
570
- }) => {
571
- if (prefetch) {
572
- logWarn(
573
- "Polyfill",
574
- "Next.js Link prefetch is not supported in remote components"
575
- );
576
- }
577
- return /* @__PURE__ */ jsx(
578
- "a",
579
- {
580
- ...props,
581
- href: props.href,
582
- onClick: (e) => {
583
- e.preventDefault();
584
- let preventDefaulted = false;
585
- e.preventDefault = () => {
586
- preventDefaulted = true;
587
- e.defaultPrevented = true;
588
- };
589
- if (typeof props.onClick === "function") {
590
- props.onClick(e);
591
- }
592
- onNavigate?.(e);
593
- if (preventDefaulted) {
594
- return;
595
- }
596
- if (replace) {
597
- history.replaceState({}, "", props.href);
598
- } else {
599
- history.pushState({}, "", props.href);
600
- }
601
- },
602
- suppressHydrationWarning: true,
603
- children: children ?? null
604
- }
605
- );
606
- },
607
- useLinkStatus() {
608
- return { pending: false };
609
- },
610
- __esModule: true
611
- })),
612
- "next/dist/client/app-dir/form": hostShared["next/form"] ?? shared2?.["next/form"] ?? (() => Promise.resolve({
613
- default: () => {
614
- throw new Error("Next.js <Form> component not implemented");
615
- },
616
- __esModule: true
617
- })),
618
- // Instead of replacing next/image entirely, we let the real Next.js Image
619
- // component load from the remote bundle and only replace its default loader.
620
- // This gives us full next/image fidelity (fill, priority, srcSet, blur
621
- // placeholders, error handling) while routing image optimization through the
622
- // remote app's /_next/image endpoint.
623
- "next/dist/shared/lib/image-loader": hostShared["next/dist/shared/lib/image-loader"] ?? shared2?.["next/dist/shared/lib/image-loader"] ?? ((bundle) => Promise.resolve({
624
- default: createRemoteImageLoader(bundle, resolveClientUrl),
625
- __esModule: true
626
- })),
627
- "next/dist/client/script": hostShared["next/script"] ?? shared2?.["next/script"] ?? (() => Promise.resolve({
628
- // TODO: implement <Script> component for non-Next.js host applications
629
- // do not throw an error for now
630
- default: () => null,
631
- __esModule: true
632
- })),
633
- "next/router": hostShared["next/router"] ?? shared2?.["next/router"] ?? (() => (
634
- // TODO: incomplete implementation
635
- Promise.resolve({
636
- useRouter() {
637
- return {
638
- push: (routerUrl) => {
639
- history.pushState({}, "", routerUrl);
640
- },
641
- replace: (routerUrl) => {
642
- history.replaceState({}, "", routerUrl);
643
- },
644
- back: () => {
645
- history.back();
646
- }
647
- };
648
- },
649
- __esModule: true
650
- })
651
- )),
652
- "next/dist/build/polyfills/process": () => Promise.resolve({
653
- default: {
654
- env: {
655
- NODE_ENV: "production"
656
- }
657
- },
658
- __esModule: true
659
- })
660
- };
661
- polyfill["next/navigation"] = polyfill["next/dist/client/components/navigation"];
662
- polyfill["next/link"] = polyfill["next/dist/client/app-dir/link"];
663
- polyfill["next/form"] = polyfill["next/dist/client/app-dir/form"];
664
- polyfill["next/dist/esm/shared/lib/image-loader"] = polyfill["next/dist/shared/lib/image-loader"];
665
- polyfill["next/script"] = polyfill["next/dist/client/script"];
666
- return polyfill;
667
- }
668
-
669
- // src/host/shared/shared-module-resolver.ts
670
- var CORE_REACT_PATH_MAP = {
671
- react: "/react/index.js",
672
- "react/jsx-dev-runtime": "/react/jsx-dev-runtime.js",
673
- "react/jsx-runtime": "/react/jsx-runtime.js",
674
- "react-dom": "/react-dom/index.js",
675
- "react-dom/client": "/react-dom/client.js"
676
- };
677
- var VENDOR_SHARED = Object.fromEntries(
678
- Object.entries(CORE_REACT_PATH_MAP).filter(([key]) => key !== "react-dom/client").map(([key, path]) => [key, `'${path}'`])
679
- );
680
- function buildCoreShared(userShared) {
681
- return {
682
- react: async () => (await import("react")).default,
683
- "react-dom": async () => (await import("react-dom")).default,
684
- "react/jsx-dev-runtime": async () => (await import("react/jsx-dev-runtime")).default,
685
- "react/jsx-runtime": async () => (await import("react/jsx-runtime")).default,
686
- "react-dom/client": async () => (await import("react-dom/client")).default,
687
- ...userShared
688
- };
689
- }
690
- function buildHostShared(userShared, resolveClientUrl, options) {
691
- const self = globalThis;
692
- const result = {
693
- ...sharedPolyfills(userShared, resolveClientUrl),
694
- ...self.__remote_component_host_shared_modules__,
695
- ...userShared
696
- };
697
- if (options?.includeRemoteComponentShared) {
698
- Object.assign(result, self.__remote_component_shared__);
699
- }
700
- return result;
701
- }
702
- async function buildWebpackResolve(hostShared, remoteShared, bundle, reactModules, callerTag = "SharedModuleResolver") {
703
- const resolve = {
704
- ...reactModules,
705
- ...Object.entries(remoteShared).reduce(
706
- (acc, [key, value]) => {
707
- if (typeof hostShared[value] !== "undefined") {
708
- acc[key.replace(/^\(ssr\)\/(?<relative>\.\/)?/, "")] = hostShared[value];
709
- } else {
710
- logDebug(
711
- callerTag,
712
- `Remote requests "${value}" but host doesn't provide it`
713
- );
714
- }
715
- return acc;
716
- },
717
- {}
718
- )
719
- };
720
- await Promise.all(
721
- Object.entries(resolve).map(async ([key, value]) => {
722
- if (typeof value === "function") {
723
- resolve[key] = await value(bundle);
724
- }
725
- return Promise.resolve(value);
726
- })
727
- );
728
- return resolve;
729
- }
730
-
731
- // src/host/shared/state.ts
732
- function createHostState() {
733
- return {
734
- stage: "idle",
735
- prevSrc: void 0,
736
- prevUrl: void 0,
737
- prevName: void 0,
738
- prevIsRemoteComponent: false,
739
- abortController: void 0
740
- };
741
- }
742
-
743
- // src/host/utils/resolve-name-from-src.ts
744
- function resolveNameFromSrc(src, defaultName) {
745
- if (!src) {
746
- return defaultName;
747
- }
748
- const hash = typeof src === "string" ? src : src.hash;
749
- const hashIndex = hash.indexOf("#");
750
- if (hashIndex < 0) {
751
- return defaultName;
752
- }
753
- const name = hash.slice(hashIndex + 1);
754
- return name || defaultName;
755
- }
756
-
757
- // src/runtime/html/html-spec.ts
758
- var ORIGIN_REWRITE_TAGS = [
759
- "img",
760
- "source",
761
- "video",
762
- "audio",
763
- "track",
764
- "iframe",
765
- "embed",
766
- "script",
767
- "link"
768
- ];
769
- var ID_SUFFIX_RSC = "_rsc";
770
- var ID_SUFFIX_SSR = "_ssr";
771
- var ID_SUFFIX_SHARED = "_shared";
772
- var DATA_BUNDLE = "data-bundle";
773
- var DATA_ROUTE = "data-route";
774
- var DATA_RUNTIME = "data-runtime";
775
- var DATA_TYPE = "data-type";
776
- var DATA_SRC = "data-src";
777
- var DATA_REMOTE_COMPONENTS_SHARED = "data-remote-components-shared";
778
- var TAG_REMOTE_COMPONENT = "remote-component";
779
- var NEXT_DATA_ID = "__NEXT_DATA__";
780
- var REMOTE_NEXT_DATA_ID = "__REMOTE_NEXT_DATA__";
781
- var NEXT_CONTAINER_ID = "__next";
782
-
783
- // src/runtime/html/rewrite-srcset.ts
784
- function rewriteSrcset(srcset, base, resolve) {
785
- return srcset.split(",").map((entry) => {
786
- const [url, descriptor] = entry.trim().split(/\s+/);
787
- if (!url)
788
- return entry;
789
- const absoluteUrl = new URL(url, base).href;
790
- const resolvedUrl = resolve ? resolve(absoluteUrl) : absoluteUrl;
791
- return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
792
- }).join(", ");
793
- }
794
-
795
- // src/runtime/html/apply-origin.ts
796
- function applyOriginToNodes(doc, url, resolveClientUrl) {
797
- if (url.origin !== location.origin) {
798
- const nodes = doc.querySelectorAll(
799
- ORIGIN_REWRITE_TAGS.map(
800
- (type) => `${type}[src],${type}[srcset],${type}[href],${type}[imagesrcset]`
801
- ).join(",")
802
- );
803
- nodes.forEach((node) => {
804
- if (node.hasAttribute("src") && /^[./]+\/?/.test(node.getAttribute("src") ?? "")) {
805
- const absoluteSrc = new URL(node.getAttribute("src") ?? "/", url).href;
806
- const isScript = node.tagName.toLowerCase() === "script";
807
- node.src = isScript ? absoluteSrc : resolveClientUrl?.(absoluteSrc) ?? absoluteSrc;
808
- }
809
- if (node.hasAttribute("href") && /^[./]+\/?/.test(node.getAttribute("href") ?? "")) {
810
- const absoluteHref = new URL(node.getAttribute("href") ?? "/", url).href;
811
- node.setAttribute(
812
- "href",
813
- resolveClientUrl?.(absoluteHref) ?? absoluteHref
814
- );
815
- }
816
- if (node.hasAttribute("srcset")) {
817
- const raw = node.getAttribute("srcset");
818
- if (raw) {
819
- const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
820
- node.setAttribute("srcset", rewriteSrcset(raw, url, resolve));
821
- }
822
- }
823
- if (node.hasAttribute("imagesrcset")) {
824
- const raw = node.getAttribute("imagesrcset");
825
- if (raw) {
826
- const resolve = resolveClientUrl ? (abs) => resolveClientUrl(abs) ?? abs : void 0;
827
- node.setAttribute("imagesrcset", rewriteSrcset(raw, url, resolve));
828
- }
829
- }
830
- });
831
- }
832
- }
833
-
834
- // src/runtime/metadata.ts
835
- var VALID_RUNTIMES = /* @__PURE__ */ new Set(["webpack", "turbopack", "script"]);
836
- var VALID_TYPES = /* @__PURE__ */ new Set([
837
- "nextjs",
838
- "remote-component",
839
- "unknown"
840
- ]);
841
- function isRuntime(value) {
842
- return VALID_RUNTIMES.has(value);
843
- }
844
- function isComponentType(value) {
845
- return VALID_TYPES.has(value);
846
- }
847
- function toRuntime(value) {
848
- return value && isRuntime(value) ? value : "webpack";
849
- }
850
- function toComponentType(value) {
851
- return value && isComponentType(value) ? value : "unknown";
852
- }
853
- function buildMetadata(attrs, url) {
854
- const id = attrs.id || DEFAULT_COMPONENT_NAME;
855
- const bundle = attrs.bundle || process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION || DEFAULT_BUNDLE_NAME;
856
- return {
857
- name: attrs.name || id.replace(/_ssr$/, ""),
858
- bundle,
859
- route: attrs.route || url.pathname || DEFAULT_ROUTE,
860
- runtime: toRuntime(attrs.runtime),
861
- id,
862
- type: toComponentType(attrs.type)
863
- };
864
- }
865
-
866
- // src/runtime/html/parse-remote-html.ts
867
- function validateSingleComponent(doc, name, url) {
868
- if (doc.querySelectorAll(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`).length > 1 && !doc.querySelector(
869
- `div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`
870
- ) || doc.querySelectorAll(`${TAG_REMOTE_COMPONENT}:not([src])`).length > 1 && !doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]`)) {
871
- throw multipleRemoteComponentsError(url);
872
- }
873
- }
874
- function findComponentElement(doc, name) {
875
- return doc.querySelector(`div[${DATA_BUNDLE}][${DATA_ROUTE}][id^="${name}"]`) ?? doc.querySelector(`div[${DATA_BUNDLE}][${DATA_ROUTE}]`) ?? doc.querySelector(`div#${NEXT_CONTAINER_ID}`) ?? doc.querySelector(`${TAG_REMOTE_COMPONENT}[name="${name}"]:not([src])`) ?? doc.querySelector(`${TAG_REMOTE_COMPONENT}:not([src])`);
876
- }
877
- function parseNextData(doc) {
878
- return JSON.parse(
879
- (doc.querySelector(`#${NEXT_DATA_ID}`) ?? doc.querySelector(`#${REMOTE_NEXT_DATA_ID}`))?.textContent ?? "null"
880
- );
881
- }
882
- function resolveComponentName(component, nextData, fallbackName) {
883
- const isRemoteComponent = component?.tagName.toLowerCase() === TAG_REMOTE_COMPONENT;
884
- const name = component?.getAttribute("id")?.replace(new RegExp(`${ID_SUFFIX_SSR}$`), "") || isRemoteComponent && component?.getAttribute("name") || (nextData ? "__next" : fallbackName);
885
- return { name, isRemoteComponent };
886
- }
887
- function extractRemoteShared(doc, name, nextData) {
888
- const remoteSharedEl = doc.querySelector(
889
- `#${name}${ID_SUFFIX_SHARED}[${DATA_REMOTE_COMPONENTS_SHARED}]`
890
- );
891
- const remoteShared = nextData?.props.__REMOTE_COMPONENT__?.shared ?? (JSON.parse(remoteSharedEl?.textContent ?? "{}") ?? {});
892
- remoteSharedEl?.remove();
893
- return remoteShared;
894
- }
895
- function validateComponentFound(component, rsc, nextData, isRemoteComponent, url, name) {
896
- if (!component || !(rsc || nextData || isRemoteComponent)) {
897
- throw new RemoteComponentsError(
898
- `Remote Component not found on ${url}.${name !== DEFAULT_COMPONENT_NAME ? ` The name for the <RemoteComponent> is "${name}". Check <RemoteComponent> usage.` : ""} Did you forget to wrap the content in <RemoteComponent>?`
899
- );
900
- }
901
- }
902
- function extractLinks(doc, component) {
903
- return Array.from(doc.querySelectorAll("link[href]")).filter(
904
- (link) => !component.contains(link)
905
- );
906
- }
907
- function extractScripts(doc, component, isRemoteComponent) {
908
- return Array.from(
909
- (isRemoteComponent ? component : doc).querySelectorAll(
910
- `script[src],script[${DATA_SRC}]`
911
- )
912
- );
913
- }
914
- function parseRemoteComponentDocument(doc, name, url) {
915
- validateSingleComponent(doc, name, url.href);
916
- const component = findComponentElement(doc, name);
917
- const nextData = parseNextData(doc);
918
- const { name: resolvedName, isRemoteComponent } = resolveComponentName(
919
- component,
920
- nextData,
921
- name
922
- );
923
- const rsc = doc.querySelector(`#${resolvedName}${ID_SUFFIX_RSC}`);
924
- const metadata = buildMetadata(
925
- {
926
- name: resolvedName,
927
- bundle: component?.getAttribute(DATA_BUNDLE) || nextData?.props.__REMOTE_COMPONENT__?.bundle,
928
- route: component?.getAttribute(DATA_ROUTE) ?? nextData?.page,
929
- runtime: component?.getAttribute(DATA_RUNTIME) ?? nextData?.props.__REMOTE_COMPONENT__?.runtime ?? RUNTIME_SCRIPT,
930
- id: component?.getAttribute("id"),
931
- type: component?.getAttribute(DATA_TYPE)
932
- },
933
- url
934
- );
935
- const remoteShared = extractRemoteShared(doc, resolvedName, nextData);
936
- validateComponentFound(
937
- component,
938
- rsc,
939
- nextData,
940
- isRemoteComponent,
941
- url.href,
942
- resolvedName
943
- );
944
- const links = extractLinks(doc, component);
945
- const scripts = extractScripts(doc, component, isRemoteComponent);
946
- return {
947
- component,
948
- name: resolvedName,
949
- isRemoteComponent,
950
- metadata,
951
- nextData,
952
- rsc,
953
- remoteShared,
954
- links,
955
- scripts
956
- };
957
- }
958
-
959
- // src/runtime/html/set-attributes-from-props.ts
960
- var DOMAttributeNames = {
961
- acceptCharset: "accept-charset",
962
- className: "class",
963
- htmlFor: "for",
964
- httpEquiv: "http-equiv",
965
- noModule: "noModule"
966
- };
967
- var ignoreProps = [
968
- "onLoad",
969
- "onReady",
970
- "dangerouslySetInnerHTML",
971
- "children",
972
- "onError",
973
- "strategy",
974
- "stylesheets"
975
- ];
976
- function isBooleanScriptAttribute(attr) {
977
- return ["async", "defer", "noModule"].includes(attr);
978
- }
979
- function setAttributesFromProps(el, props) {
980
- for (const [p, value] of Object.entries(props)) {
981
- if (!Object.hasOwn(props, p))
982
- continue;
983
- if (ignoreProps.includes(p))
984
- continue;
985
- if (value === void 0) {
986
- continue;
987
- }
988
- const attr = DOMAttributeNames[p] || p.toLowerCase();
989
- if (el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr)) {
990
- el[attr] = Boolean(value);
991
- } else {
992
- el.setAttribute(attr, String(value));
993
- }
994
- if (value === false || el.tagName === "SCRIPT" && isBooleanScriptAttribute(attr) && (!value || value === "false")) {
995
- el.setAttribute(attr, "");
996
- el.removeAttribute(attr);
997
- }
998
- }
999
- }
1000
-
1001
- // src/runtime/loaders/component-loader.ts
1002
- import * as React from "react";
1003
- import * as JSXDevRuntime from "react/jsx-dev-runtime";
1004
- import * as JSXRuntime from "react/jsx-runtime";
1005
- import * as ReactDOM from "react-dom";
1006
- import * as ReactDOMClient from "react-dom/client";
1007
-
1008
- // src/config/webpack/apply-shared-modules.ts
1009
- var DEDUPLICATION_SKIPPED = "shared module deduplication skipped. The remote may load its own copy of shared dependencies.";
1010
- function applySharedModules(bundle, resolve) {
1011
- logDebug(
1012
- "SharedModules",
1013
- `applySharedModules called for bundle: "${bundle}"`
1014
- );
1015
- logDebug(
1016
- "SharedModules",
1017
- `Shared modules to resolve: ${Object.keys(resolve)}`
1018
- );
1019
- const self = globalThis;
1020
- const scope = getScope(bundle);
1021
- const webpackBundle = scope?.webpackRequire ?? self.__remote_webpack_require__?.[bundle];
1022
- if (webpackBundle) {
1023
- const modulePaths = Object.keys(
1024
- self.__remote_webpack_module_map__?.[bundle] ?? webpackBundle.m ?? {}
1025
- );
1026
- logDebug(
1027
- "SharedModules",
1028
- `Available module paths for bundle "${bundle}": ${modulePaths}`
1029
- );
1030
- for (const [key, value] of Object.entries(resolve)) {
1031
- const exactIds = modulePaths.filter((p) => p === key);
1032
- const ids = exactIds.length > 0 ? exactIds : modulePaths.filter((p) => p.includes(key));
1033
- if (ids.length === 0) {
1034
- logDebug(
1035
- "SharedModules",
1036
- `No matching module path found for shared module "${key}"`
1037
- );
1038
- }
1039
- for (const id of ids) {
1040
- if (webpackBundle.m) {
1041
- const resolvedId = self.__remote_webpack_module_map__?.[bundle]?.[id] ? `${self.__remote_webpack_module_map__[bundle][id]}` : id;
1042
- if (resolvedId !== id) {
1043
- logDebug(
1044
- "SharedModules",
1045
- `Mapped module id: "${id}" -> "${resolvedId}"`
1046
- );
1047
- }
1048
- webpackBundle.m[resolvedId] = (module) => {
1049
- module.exports = value;
1050
- };
1051
- } else {
1052
- logWarn(
1053
- "SharedModules",
1054
- `webpackBundle.m is not available for bundle "${bundle}" \u2014 ${DEDUPLICATION_SKIPPED}`
1055
- );
1056
- }
1057
- }
1058
- }
1059
- } else {
1060
- logWarn(
1061
- "SharedModules",
1062
- `No webpack require found for bundle "${bundle}" \u2014 ${DEDUPLICATION_SKIPPED}`
1063
- );
1064
- logDebug(
1065
- "SharedModules",
1066
- `Available bundles: ${Object.keys(self.__remote_webpack_require__ ?? {})}`
1067
- );
1068
- }
1069
- }
1070
-
1071
- // src/config/webpack/next-client-pages-loader.ts
1072
- function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
1073
- const self = globalThis;
1074
- const nextCssOriginal = document.querySelector(
1075
- `[id="__next_css__DO_NOT_USE__"]:not([data-bundle="${bundle}"][data-route="${route}"])`
1076
- );
1077
- if (nextCssOriginal) {
1078
- nextCssOriginal.parentNode?.removeChild(nextCssOriginal);
1079
- }
1080
- const nextCss = document.createElement("noscript");
1081
- nextCss.id = "__next_css__DO_NOT_USE__";
1082
- nextCss.setAttribute("data-bundle", bundle);
1083
- nextCss.setAttribute("data-route", route);
1084
- const nextCssEnd = document.createElement("noscript");
1085
- nextCssEnd.id = "__next_css__DO_NOT_USE_END__";
1086
- nextCssEnd.setAttribute("data-bundle", bundle);
1087
- nextCssEnd.setAttribute("data-route", route);
1088
- document.head.appendChild(nextCssEnd);
1089
- document.head.appendChild(nextCss);
1090
- const componentLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
1091
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
1092
- ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
1093
- (key) => key.includes("/next/dist/client/page-loader.js")
1094
- ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
1095
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
1096
- ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
1097
- (key) => key.includes("/next/dist/client/page-loader.js")
1098
- ) ?? ""] ?? -1;
1099
- const appLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
1100
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
1101
- ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
1102
- (key) => key.includes("/next/dist/client/page-loader.js")
1103
- ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
1104
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=%2F_app`)
1105
- ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
1106
- (key) => key.includes("/next/dist/client/page-loader.js")
1107
- ) ?? ""] ?? -1;
1108
- if (!(componentLoaderChunk && appLoaderChunk)) {
1109
- throw new RemoteComponentsError(
1110
- `Next.js client pages loader not found in bundle "${bundle}".`
1111
- );
1112
- }
1113
- const __NEXT_P_ORIGINAL = self.__NEXT_P;
1114
- const selfOriginal = self;
1115
- delete selfOriginal.__NEXT_P;
1116
- self.__remote_webpack_require__?.[bundle]?.(
1117
- self.__remote_webpack_require__[bundle].type !== "turbopack" ? componentLoaderChunk : `[${bundle}] ${componentLoaderChunk}`
1118
- );
1119
- if (typeof appLoaderChunk === "string" || typeof appLoaderChunk === "number" && appLoaderChunk !== -1) {
1120
- self.__remote_webpack_require__?.[bundle]?.(
1121
- self.__remote_webpack_require__[bundle].type !== "turbopack" ? appLoaderChunk : `[${bundle}] ${appLoaderChunk}`
1122
- );
1123
- }
1124
- if (self.__NEXT_P) {
1125
- const [, componentLoader] = self.__NEXT_P[0] ?? [
1126
- void 0,
1127
- () => ({ default: null })
1128
- ];
1129
- const [, appLoader] = self.__NEXT_P[2] ?? [
1130
- void 0,
1131
- () => ({
1132
- default: null
1133
- })
1134
- ];
1135
- const { default: Component } = componentLoader();
1136
- const { default: App } = appLoader();
1137
- const cssCache = getNamespace().cssCache;
1138
- if (!cssCache[bundle]) {
1139
- const cssRE = /\.s?css$/;
1140
- Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
1141
- self.__remote_webpack_require__?.[bundle]?.(id);
1142
- });
1143
- Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {}).filter((path) => cssRE.test(path)).forEach((path) => {
1144
- const id = self.__remote_webpack_module_map__?.[bundle]?.[path];
1145
- if (id) {
1146
- self.__remote_webpack_require__?.[bundle]?.(id);
1147
- }
1148
- });
1149
- const elements = [];
1150
- let node = nextCss.previousSibling;
1151
- while (node && node !== nextCssEnd) {
1152
- elements.push(node);
1153
- node.remove();
1154
- node = nextCss.previousSibling;
1155
- }
1156
- cssCache[bundle] = elements;
1157
- }
1158
- if (styleContainer) {
1159
- const elements = cssCache[bundle];
1160
- elements.forEach((el) => {
1161
- styleContainer.appendChild(el.cloneNode(true));
1162
- });
1163
- } else {
1164
- const elements = cssCache[bundle];
1165
- elements.forEach((el) => {
1166
- document.head.appendChild(el);
1167
- });
1168
- }
1169
- delete self.__NEXT_P;
1170
- self.__NEXT_P = __NEXT_P_ORIGINAL;
1171
- if (nextCssOriginal) {
1172
- nextCssOriginal.parentNode?.appendChild(nextCssOriginal);
1173
- }
1174
- nextCss.remove();
1175
- nextCssEnd.remove();
1176
- return { Component, App };
1177
- }
1178
- return { Component: null, App: null };
1179
- }
1180
-
1181
- // src/runtime/rsc.ts
1182
- import { ReadableStream } from "web-streams-polyfill";
1183
- function fixPayload(payload) {
1184
- if (Array.isArray(payload)) {
1185
- if (payload[0] === "$") {
1186
- fixPayload(payload[3]);
1187
- if (payload.length === 4) {
1188
- payload.push(null, null, 1);
1189
- }
1190
- } else {
1191
- for (const item of payload) {
1192
- fixPayload(item);
1193
- }
1194
- }
1195
- } else if (typeof payload === "object" && payload !== null) {
1196
- for (const key in payload) {
1197
- fixPayload(payload[key]);
1198
- }
1199
- }
1200
- }
1201
- function buildRSCChunks(rscName, data) {
1202
- const chunks = [];
1203
- for (const chunk of data) {
1204
- for (const line of chunk.split("\n")) {
1205
- const match = /\.push\("(?<rsc>.*)"\);$/.exec(line);
1206
- if (match?.groups?.rsc) {
1207
- chunks.push(JSON.parse(`"${match.groups.rsc}"`));
1208
- }
1209
- }
1210
- }
1211
- return chunks;
1212
- }
1213
- function createRSCStream(rscName, data) {
1214
- return new ReadableStream({
1215
- type: "bytes",
1216
- start(controller) {
1217
- const encoder = new TextEncoder();
1218
- const self = globalThis;
1219
- if (data.length > 0) {
1220
- const parsed = buildRSCChunks(rscName, data);
1221
- if (parsed.length > 0) {
1222
- self[rscName] = self[rscName] ?? [];
1223
- self[rscName].push(...parsed);
1224
- }
1225
- }
1226
- const allChunks = (self[rscName] ?? [`0:[null]
1227
- `]).join("");
1228
- self[rscName] = null;
1229
- allChunks.split("\n").forEach((chunk) => {
1230
- if (chunk.length > 0) {
1231
- const { before, id, prefix, payload } = /^(?<before>[^:]*?)?(?<id>[0-9a-zA-Z]+):(?<prefix>[A-Z])?(?<payload>\[.*\])/.exec(
1232
- chunk
1233
- )?.groups ?? {};
1234
- if (payload) {
1235
- const jsonPayload = JSON.parse(payload);
1236
- fixPayload(jsonPayload);
1237
- const reconstruct = `${before ?? ""}${id}:${prefix ?? ""}${JSON.stringify(jsonPayload)}`;
1238
- controller.enqueue(encoder.encode(`${reconstruct}
1239
- `));
1240
- } else {
1241
- controller.enqueue(encoder.encode(`${chunk}
1242
- `));
1243
- }
1244
- } else {
1245
- controller.enqueue(encoder.encode(`${chunk}
1246
- `));
1247
- }
1248
- });
1249
- controller.close();
1250
- }
1251
- });
1252
- }
1253
-
1254
- // src/runtime/rsc-imports.ts
1255
- async function importRSCClientBrowser() {
1256
- try {
1257
- return await import("next/dist/compiled/react-server-dom-webpack/client.browser");
1258
- } catch {
1259
- const mod = await import("react-server-dom-webpack/client.browser");
1260
- return mod.default ?? mod;
1261
- }
1262
- }
1263
-
1264
- // src/runtime/turbopack/patterns.ts
1265
- var MODULE_ID_PATTERN = '"[^"]+"|[0-9]+';
1266
- function stripQuotes(value) {
1267
- if (value.startsWith('"') && value.endsWith('"')) {
1268
- return value.slice(1, -1);
1269
- }
1270
- return value;
1271
- }
1272
- function extractGroup(re, input, group) {
1273
- const raw = re.exec(input)?.groups?.[group];
1274
- return raw ? stripQuotes(raw) : void 0;
1275
- }
1276
- var REMOTE_SHARED_MARKER_RE = /(?:self|[a-z])\.TURBOPACK_REMOTE_SHARED/;
1277
- var REMOTE_SHARED_ASSIGNMENT_RE = new RegExp(
1278
- `\\.TURBOPACK_REMOTE_SHARED\\s*=\\s*await (?:__turbopack_context__|[a-z])\\.A\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1279
- );
1280
- var ASYNC_MODULE_LOADER_RE = new RegExp(
1281
- `(?:__turbopack_context__|e)\\.A\\((?<asyncSharedModuleId>${MODULE_ID_PATTERN})\\)`
1282
- );
1283
- var ASYNC_MODULE_CALLBACK_RE = new RegExp(
1284
- `(?:parentImport|[a-z])\\((?<sharedModuleId>${MODULE_ID_PATTERN})\\)`
1285
- );
1286
- var TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
1287
-
1288
- // src/runtime/turbopack/chunk-loader.ts
1289
- function loadChunkWithScope(scope, chunkId) {
1290
- logDebug(
1291
- "ChunkLoader",
1292
- `loadChunkWithScope: "${chunkId}" (scope: "${scope.scopedName}")`
1293
- );
1294
- const self = globalThis;
1295
- const ns = getNamespace();
1296
- const { bundle, path, prefix } = parseRemoteId(chunkId);
1297
- const remoteRuntime = self.__remote_webpack_require__?.[bundle ?? "default"] ? self.__remote_webpack_require__[bundle ?? "default"]?.type || "webpack" : scope.runtime;
1298
- if (remoteRuntime === RUNTIME_WEBPACK) {
1299
- return Promise.resolve(void 0);
1300
- }
1301
- const rawPath = path ? collapseDoubleSlashes(`${prefix}${path}`) : "/";
1302
- const url = new URL(rawPath, scope.url).href;
1303
- if (url.endsWith(".css")) {
1304
- return;
1305
- }
1306
- if (ns.chunkCache[url]) {
1307
- logDebug("ChunkLoader", `Cache hit for "${chunkId}" (url="${url}")`);
1308
- return ns.chunkCache[url];
1309
- }
1310
- const resolvedUrl = scope.resolveClientUrl?.(url) ?? url;
1311
- if (resolvedUrl !== url) {
1312
- logDebug("ChunkLoader", `Proxied chunk URL: "${url}" \u2192 "${resolvedUrl}"`);
1313
- }
1314
- ns.chunkCache[url] = new Promise((resolve, reject) => {
1315
- fetch(resolvedUrl).then((res) => res.text()).then((code) => {
1316
- const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
1317
- if (hasTurbopack) {
1318
- return handleTurbopackChunk(code, scope, url);
1319
- }
1320
- }).then(resolve).catch((error) => {
1321
- const isProxied = isProxiedUrl(resolvedUrl);
1322
- if (isProxied) {
1323
- reject(failedProxiedAssetError("chunk", url, resolvedUrl));
1324
- } else {
1325
- warnCrossOriginFetchError("ChunkLoader", url);
1326
- reject(error);
1327
- }
1328
- });
1329
- });
1330
- return ns.chunkCache[url];
1331
- }
1332
- function createChunkDispatcher() {
1333
- return function __chunk_dispatcher__(chunkId, scriptBundle) {
1334
- logDebug("ChunkDispatcher", `Dispatching chunk: "${chunkId}"`);
1335
- const { bundle } = parseRemoteId(chunkId);
1336
- const bundleName = bundle || scriptBundle || "default";
1337
- const scope = getScope(bundleName);
1338
- logDebug(
1339
- "ChunkDispatcher",
1340
- `Scope resolution: bundle="${bundleName}", scope=${scope?.scopedName ?? "null"}`
1341
- );
1342
- if (!scope) {
1343
- logWarn("ChunkDispatcher", `No scope found for bundle "${bundleName}"`);
1344
- return Promise.resolve(void 0);
1345
- }
1346
- return loadChunkWithScope(scope, chunkId);
1347
- };
1348
- }
1349
- async function handleTurbopackChunk(code, scope, url) {
1350
- if (/importScripts\(\.\.\.self.TURBOPACK_NEXT_CHUNK_URLS/.test(code)) {
1351
- const preloadLinks = document.querySelectorAll(
1352
- `link[rel="preload"][href="${new URL(url).pathname}"]`
1353
- );
1354
- preloadLinks.forEach((preloadLink) => preloadLink.remove());
1355
- return;
1356
- }
1357
- const self = globalThis;
1358
- const { globalKey } = scope;
1359
- const transformedCode = code.replace(
1360
- /globalThis\[\s*["']TURBOPACK["']\s*\]/g,
1361
- `globalThis["TURBOPACK_${globalKey}"]`
1362
- ).replace(
1363
- /self\[\s*["']TURBOPACK["']\s*\]/g,
1364
- `self["TURBOPACK_${globalKey}"]`
1365
- ).replace(/globalThis\.TURBOPACK/g, `globalThis.TURBOPACK_${globalKey}`).replace(/self\.TURBOPACK(?!_)/g, `self.TURBOPACK_${globalKey}`).replace(
1366
- /TURBOPACK_WORKER_LOCATION/g,
1367
- `TURBOPACK_WORKER_LOCATION_${globalKey}`
1368
- ).replace(
1369
- /TURBOPACK_NEXT_CHUNK_URLS/g,
1370
- `TURBOPACK_NEXT_CHUNK_URLS_${globalKey}`
1371
- ).replace(
1372
- /TURBOPACK_CHUNK_UPDATE_LISTENERS/g,
1373
- `TURBOPACK_CHUNK_UPDATE_LISTENERS_${globalKey}`
1374
- ).replace(/__next_require__/g, `__${globalKey}_next_require__`).replace(
1375
- /\/\/# sourceMappingURL=(?<name>.+)(?<optional>\._)?\.js\.map/g,
1376
- `//# sourceMappingURL=${new URL(".", new URL(url, scope.url)).href}$1$2.js.map`
1377
- );
1378
- if (!self[`TURBOPACK_${globalKey}`]) {
1379
- const wrapPush = (target) => {
1380
- const originalPush = target.push;
1381
- if (typeof originalPush !== "function")
1382
- return target;
1383
- target.push = (...items) => {
1384
- for (const item of items) {
1385
- if (Array.isArray(item)) {
1386
- for (const entry of item) {
1387
- scope.turbopackModules.push(entry);
1388
- }
1389
- } else {
1390
- scope.turbopackModules.push(item);
1391
- }
1392
- }
1393
- return originalPush.apply(target, items);
1394
- };
1395
- return target;
1396
- };
1397
- const globalProp = `TURBOPACK_${globalKey}`;
1398
- let currentValue = wrapPush([]);
1399
- Object.defineProperty(self, globalProp, {
1400
- get() {
1401
- return currentValue;
1402
- },
1403
- set(newValue) {
1404
- if (newValue && typeof newValue === "object") {
1405
- wrapPush(newValue);
1406
- }
1407
- currentValue = newValue;
1408
- },
1409
- configurable: true,
1410
- enumerable: true
1411
- });
1412
- }
1413
- await new Promise((scriptResolve, scriptReject) => {
1414
- const blob = new Blob([transformedCode], {
1415
- type: "application/javascript; charset=UTF-8"
1416
- });
1417
- const scriptUrl = URL.createObjectURL(blob);
1418
- const script = document.createElement("script");
1419
- script.setAttribute("data-turbopack-src", url);
1420
- script.src = scriptUrl;
1421
- script.async = true;
1422
- script.onload = () => {
1423
- URL.revokeObjectURL(scriptUrl);
1424
- scriptResolve(void 0);
1425
- script.remove();
1426
- };
1427
- script.onerror = () => {
1428
- URL.revokeObjectURL(scriptUrl);
1429
- scriptReject(
1430
- new RemoteComponentsError(
1431
- `Failed to load <script src="${script.src}"> for Remote Component. Check the URL is correct.`
1432
- )
1433
- );
1434
- script.remove();
1435
- };
1436
- document.head.appendChild(script);
1437
- });
1438
- const chunkLists = self[`TURBOPACK_${globalKey}_CHUNK_LISTS`];
1439
- const loadChunkPromises = [];
1440
- while (chunkLists?.length) {
1441
- const { chunks } = chunkLists.shift() ?? { chunks: [] };
1442
- if (chunks.length > 0) {
1443
- for (const id of chunks) {
1444
- const baseUrl = url.slice(0, url.indexOf("/_next"));
1445
- const chunkLoadResult = loadChunkWithScope(
1446
- scope,
1447
- formatRemoteId(scope, `${baseUrl}/_next/${id}`)
1448
- );
1449
- if (chunkLoadResult) {
1450
- loadChunkPromises.push(chunkLoadResult);
1451
- }
1452
- }
1453
- }
1454
- }
1455
- if (loadChunkPromises.length > 0) {
1456
- await Promise.all(loadChunkPromises);
1457
- }
1458
- }
1459
-
1460
- // src/runtime/turbopack/shared-modules.ts
1461
- var DEDUPLICATION_WARNING = "This module will not be deduplicated \u2014 the remote may load its own copy, which can cause duplicate instance errors (e.g. invalid hook calls if React is loaded twice).";
1462
- function getTurbopackModules(scope) {
1463
- if (scope.turbopackModules.length > 0) {
1464
- return scope.turbopackModules;
1465
- }
1466
- const self = globalThis;
1467
- const raw = self[`TURBOPACK_${scope.globalKey}`];
1468
- if (!raw)
1469
- return void 0;
1470
- if (Array.isArray(raw)) {
1471
- return raw.flat();
1472
- }
1473
- return Object.entries(raw).flat();
1474
- }
1475
- async function initializeSharedModules(scope, hostShared = {}, remoteShared = {}) {
1476
- const allModules = getTurbopackModules(scope);
1477
- logDebug(
1478
- "SharedModules",
1479
- `initializeSharedModules: scope="${scope.scopedName}", allModules=${allModules ? allModules.length : "null"}, hostShared=[${Object.keys(hostShared).join(", ")}], remoteShared=${JSON.stringify(remoteShared)}`
1480
- );
1481
- let sharedModuleInitializer = null;
1482
- if (allModules) {
1483
- const sharedModuleInitializerIndex = allModules.findIndex((idOrFunc) => {
1484
- if (typeof idOrFunc !== "function") {
1485
- return false;
1486
- }
1487
- const funcCode = idOrFunc.toString();
1488
- return REMOTE_SHARED_MARKER_RE.test(funcCode);
1489
- });
1490
- if (sharedModuleInitializerIndex > 0) {
1491
- const sharedModuleInitializerCode = allModules[sharedModuleInitializerIndex].toString();
1492
- const sharedModuleInitializerId = allModules[sharedModuleInitializerIndex - 1];
1493
- const sharedModuleId = extractGroup(
1494
- REMOTE_SHARED_ASSIGNMENT_RE,
1495
- sharedModuleInitializerCode,
1496
- "sharedModuleId"
1497
- );
1498
- if (sharedModuleId) {
1499
- const { default: sharedModuleInitializerInstance } = handleTurbopackModule(
1500
- scope,
1501
- sharedModuleId,
1502
- formatRemoteId(scope, String(sharedModuleInitializerId))
1503
- );
1504
- sharedModuleInitializer = sharedModuleInitializerInstance;
1505
- }
1506
- }
1507
- if (sharedModuleInitializer) {
1508
- const { shared: shared2 } = await sharedModuleInitializer;
1509
- const sharedModuleIds = extractSharedModuleIds(shared2, scope);
1510
- logDebug(
1511
- "SharedModules",
1512
- `Resolved shared modules for scope="${scope.scopedName}": ${JSON.stringify(sharedModuleIds)}`
1513
- );
1514
- return Promise.all(
1515
- Object.entries(sharedModuleIds).map(async ([id, module]) => {
1516
- if (hostShared[module]) {
1517
- scope.sharedModules[id] = await hostShared[module](scope.name);
1518
- } else {
1519
- logError(
1520
- "SharedModules",
1521
- `Host shared module "${module}" not found for ID ${id}. ${DEDUPLICATION_WARNING}`
1522
- );
1523
- }
1524
- })
1525
- );
1526
- }
1527
- logWarn(
1528
- "SharedModules",
1529
- `No shared module initializer found in bundle for scope="${scope.scopedName}" \u2014 falling back to remoteShared mapping`
1530
- );
1531
- } else {
1532
- logWarn(
1533
- "SharedModules",
1534
- `No TURBOPACK modules found for scope="${scope.scopedName}" (TURBOPACK_${scope.globalKey} is empty)`
1535
- );
1536
- }
1537
- return Promise.all(
1538
- Object.entries(remoteShared).map(async ([id, module]) => {
1539
- if (hostShared[module]) {
1540
- const normalizedId = id.replace("[app-ssr]", "[app-client]");
1541
- scope.sharedModules[normalizedId] = await hostShared[module](
1542
- scope.name
1543
- );
1544
- } else {
1545
- logError(
1546
- "SharedModules",
1547
- `Shared module "${module}" not found for "${scope.name}". ${DEDUPLICATION_WARNING}`
1548
- );
1549
- }
1550
- })
1551
- );
1552
- }
1553
- function extractSharedModuleIds(shared2, scope) {
1554
- return Object.entries(shared2).filter(([, value]) => typeof value === "function").reduce((acc, [key, value]) => {
1555
- const asyncSharedModuleId = extractGroup(
1556
- ASYNC_MODULE_LOADER_RE,
1557
- value.toString(),
1558
- "asyncSharedModuleId"
1559
- );
1560
- if (asyncSharedModuleId) {
1561
- const asyncSharedModule = findModuleInit(
1562
- getTurbopackModules(scope),
1563
- asyncSharedModuleId
1564
- );
1565
- if (asyncSharedModule) {
1566
- const sharedModuleId = extractGroup(
1567
- ASYNC_MODULE_CALLBACK_RE,
1568
- asyncSharedModule.toString(),
1569
- "sharedModuleId"
1570
- );
1571
- acc[sharedModuleId ?? asyncSharedModuleId] = key.replace(
1572
- "__remote_shared_module_",
1573
- ""
1574
- );
1575
- }
1576
- }
1577
- return acc;
1578
- }, {});
1579
- }
1580
- function getSharedModule(scope, id) {
1581
- const idStr = String(id);
1582
- if (scope.sharedModules[idStr] !== void 0) {
1583
- return scope.sharedModules[idStr];
1584
- }
1585
- for (const [key, value] of Object.entries(scope.sharedModules)) {
1586
- if (typeof value !== "undefined" && idStr !== key && idStr.endsWith(key)) {
1587
- return value;
1588
- }
1589
- }
1590
- return null;
1591
- }
1592
-
1593
- // src/runtime/turbopack/module.ts
1594
- function requireModule(scope, moduleId, fullId) {
1595
- const idStr = String(moduleId);
1596
- if (scope.moduleCache[idStr])
1597
- return scope.moduleCache[idStr];
1598
- const sharedModule = getSharedModule(scope, moduleId);
1599
- if (sharedModule)
1600
- return sharedModule;
1601
- return handleTurbopackModule(
1602
- scope,
1603
- idStr,
1604
- fullId ?? formatRemoteId(scope, idStr)
1605
- );
1606
- }
1607
- function handleTurbopackModule(scope, moduleId, id) {
1608
- if (scope.moduleCache[moduleId]) {
1609
- return scope.moduleCache[moduleId];
1610
- }
1611
- const modules = getTurbopackModules(scope);
1612
- if (!modules) {
1613
- logError(
1614
- "TurbopackModule",
1615
- `TURBOPACK_${scope.globalKey} is undefined (scope: "${scope.scopedName}")`
1616
- );
1617
- }
1618
- const moduleInit = findModuleInit(modules, moduleId);
1619
- const exports = {};
1620
- const moduleExports = { exports };
1621
- if (typeof moduleInit !== "function") {
1622
- throw new Error(
1623
- `Module ${id} not found in bundle ${scope.name} with id ${moduleId}`
1624
- );
1625
- }
1626
- scope.moduleCache[moduleId] = moduleExports.exports;
1627
- moduleInit(
1628
- createTurbopackContext(
1629
- scope,
1630
- exports,
1631
- moduleExports,
1632
- modules,
1633
- moduleInit,
1634
- id
1635
- ),
1636
- moduleExports,
1637
- exports
1638
- );
1639
- if (scope.moduleCache[moduleId] !== moduleExports.exports) {
1640
- scope.moduleCache[moduleId] = moduleExports.exports;
1641
- }
1642
- return moduleExports.exports;
1643
- }
1644
- function findModuleInit(modules, moduleId) {
1645
- if (!modules || typeof modules !== "object")
1646
- return;
1647
- if (!Array.isArray(modules)) {
1648
- const key = moduleId in modules ? moduleId : Object.keys(modules).find((k) => k.startsWith(moduleId));
1649
- return key !== void 0 ? modules[key] : void 0;
1650
- }
1651
- const flat = modules.flat();
1652
- let idx = flat.findIndex((e) => String(e) === String(moduleId));
1653
- if (idx < 0) {
1654
- idx = flat.findIndex(
1655
- (e) => typeof e === "string" && e.startsWith(moduleId)
1656
- );
1657
- }
1658
- if (idx >= 0) {
1659
- return flat.slice(idx + 1).find((e) => typeof e === "function");
1660
- }
1661
- for (const entry of flat) {
1662
- if (!entry || typeof entry !== "object")
1663
- continue;
1664
- const obj = entry;
1665
- if (moduleId in obj)
1666
- return obj[moduleId];
1667
- const prefixKey = Object.keys(obj).find((k) => k.startsWith(moduleId));
1668
- if (prefixKey)
1669
- return obj[prefixKey];
1670
- }
1671
- return void 0;
1672
- }
1673
- function createTurbopackContext(scope, exports, moduleExports, modules, moduleInit, id) {
1674
- const scopedRequire = (moduleId) => requireModule(scope, moduleId, formatRemoteId(scope, String(moduleId)));
1675
- return {
1676
- // HMR not implemented for Remote Components
1677
- k: {
1678
- register() {
1679
- },
1680
- registerExports() {
1681
- },
1682
- signature() {
1683
- return (fn) => fn;
1684
- }
1685
- },
1686
- // ESM exports setup
1687
- s(bindings, esmId) {
1688
- let mod = exports;
1689
- if (typeof esmId === "string" || typeof esmId === "number") {
1690
- if (!scope.moduleCache[esmId]) {
1691
- scope.moduleCache[esmId] = {};
1692
- }
1693
- mod = scope.moduleCache[esmId];
1694
- }
1695
- Object.defineProperty(mod, "__esModule", { value: true });
1696
- if (Array.isArray(bindings)) {
1697
- let i = 0;
1698
- while (i < bindings.length) {
1699
- const propName = bindings[i++];
1700
- const tagOrFunc = bindings[i++];
1701
- if (typeof tagOrFunc === "number") {
1702
- Object.defineProperty(mod, propName, {
1703
- value: bindings[i++],
1704
- enumerable: true,
1705
- writable: false
1706
- });
1707
- } else {
1708
- const getterFn = tagOrFunc;
1709
- if (typeof bindings[i] === "function") {
1710
- const setterFn = bindings[i++];
1711
- Object.defineProperty(mod, propName, {
1712
- get: getterFn,
1713
- set: setterFn,
1714
- enumerable: true
1715
- });
1716
- } else {
1717
- Object.defineProperty(mod, propName, {
1718
- get: getterFn,
1719
- enumerable: true
1720
- });
1721
- }
1722
- }
1723
- }
1724
- }
1725
- },
1726
- // import — resolves directly via scope, no global dispatch
1727
- i(importId) {
1728
- let mod;
1729
- if (typeof importId === "string") {
1730
- const { exportSource, exportName } = /\s+<export (?<exportSource>.*?) as (?<exportName>.*?)>$/.exec(
1731
- importId
1732
- )?.groups ?? {};
1733
- const normalizedId = importId.replace(
1734
- /\s+<export(?<specifier>.*)>$/,
1735
- ""
1736
- );
1737
- mod = scopedRequire(normalizedId);
1738
- if (mod && exportSource && exportName && (exportSource === "*" || typeof mod[exportSource] !== "undefined") && typeof mod[exportName] === "undefined") {
1739
- if (exportSource === "*") {
1740
- mod[exportName] = mod;
1741
- } else {
1742
- mod[exportName] = mod[exportSource];
1743
- }
1744
- }
1745
- } else {
1746
- mod = scopedRequire(importId);
1747
- }
1748
- if (typeof mod !== "object" || mod === null) {
1749
- mod = { default: mod };
1750
- } else if (!("default" in mod) && // ES module namespace objects have a null prototype, so calling
1751
- // mod.toString() directly throws. Use Object.prototype.toString
1752
- // to safely detect them.
1753
- Object.prototype.toString.call(mod) !== "[object Module]") {
1754
- try {
1755
- mod.default = mod;
1756
- } catch {
1757
- }
1758
- }
1759
- return mod;
1760
- },
1761
- // require — resolves directly via scope
1762
- r(requireId) {
1763
- return scopedRequire(requireId);
1764
- },
1765
- // value exports
1766
- v(value) {
1767
- if (typeof value === "function") {
1768
- exports.default = value((vid) => scopedRequire(vid));
1769
- } else {
1770
- moduleExports.exports = value;
1771
- }
1772
- },
1773
- // async module initializer
1774
- async a(mod) {
1775
- let result;
1776
- await mod(
1777
- () => {
1778
- },
1779
- (value) => result = value
1780
- );
1781
- exports.default = result;
1782
- },
1783
- // async module loader — resolves directly via scope
1784
- async A(Aid) {
1785
- const mod = scopedRequire(Aid);
1786
- return mod.default((parentId) => scopedRequire(parentId));
1787
- },
1788
- // dynamic import tracking — no-op for remote components
1789
- j() {
1790
- },
1791
- // chunk loader — loads directly via scope, no global dispatch
1792
- l(url) {
1793
- const flatModules = Array.isArray(modules) ? modules : [];
1794
- const moduleInitIndex = flatModules.indexOf(moduleInit);
1795
- if (moduleInitIndex !== -1) {
1796
- const scriptIndex = flatModules.slice(0, moduleInitIndex).findLastIndex((bundleEntry) => bundleEntry instanceof Element);
1797
- if (scriptIndex !== -1) {
1798
- const script = flatModules[scriptIndex];
1799
- const scriptSrc = script.getAttribute("data-turbopack-src") || "";
1800
- const nextIndex = scriptSrc.indexOf("/_next");
1801
- const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
1802
- const chunkUrl = `${baseUrl}/_next/${url}`;
1803
- return loadChunkWithScope(scope, formatRemoteId(scope, chunkUrl));
1804
- }
1805
- }
1806
- throw new Error(
1807
- `Failed to load Turbopack chunk "${url}" for module "${id}". Check the URL is correct.`
1808
- );
1809
- },
1810
- // globalThis substitute shared across all modules in this scope
1811
- g: scope.moduleGlobal,
1812
- m: moduleExports,
1813
- e: exports
1814
- };
1815
- }
1816
-
1817
- // src/runtime/turbopack/remote-scope-setup.ts
1818
- async function setupRemoteScope(runtime, scripts = [], url = new URL(location.href), bundle, resolveClientUrl) {
1819
- const self = globalThis;
1820
- const ns = getNamespace();
1821
- const bundleName = bundle ?? "default";
1822
- const existingScope = getScope(bundleName);
1823
- if (existingScope && existingScope.url.origin === url.origin) {
1824
- logDebug(
1825
- "WebpackRuntime",
1826
- `Reusing scope "${existingScope.scopedName}" (turbopackModules=${existingScope.turbopackModules.length})`
1827
- );
1828
- existingScope.resolveClientUrl = resolveClientUrl;
1829
- if (runtime === RUNTIME_TURBOPACK) {
1830
- await Promise.allSettled(
1831
- scripts.map(
1832
- (script) => script.src ? loadChunkWithScope(existingScope, script.src) : Promise.resolve(void 0)
1833
- )
1834
- );
1835
- }
1836
- return existingScope;
1837
- }
1838
- const scope = createScope(bundleName, url, runtime, resolveClientUrl);
1839
- registerScope(scope);
1840
- if (runtime === RUNTIME_WEBPACK && self.__remote_webpack_require__?.[bundleName]) {
1841
- scope.webpackRequire = self.__remote_webpack_require__[bundleName];
1842
- }
1843
- ns.bundleUrls[bundleName] = url;
1844
- if (scope.scopedName !== bundleName) {
1845
- ns.bundleUrls[scope.scopedName] = url;
1846
- }
1847
- self.__webpack_get_script_filename__ = () => null;
1848
- const willCreateDispatchers = typeof self.__webpack_require__ !== "function" || ns.dispatcherRuntime !== "turbopack";
1849
- if (willCreateDispatchers) {
1850
- if (!self.__original_webpack_require__ && !self.__original_webpack_chunk_load__) {
1851
- self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
1852
- self.__original_webpack_require__ = self.__webpack_require__;
1853
- }
1854
- self.__webpack_chunk_load__ = createChunkDispatcher();
1855
- self.__webpack_require__ = createModuleDispatcher(runtime);
1856
- ns.dispatcherRuntime = runtime;
1857
- self.__webpack_require_type__ = runtime;
1858
- if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
1859
- self.__remote_webpack_require__[bundleName] = self.__webpack_require__;
1860
- self.__remote_webpack_require__[bundleName].type = "turbopack";
1861
- }
1862
- }
1863
- if (self.__remote_webpack_require__?.[bundleName] && scope.scopedName !== bundleName) {
1864
- self.__remote_webpack_require__[scope.scopedName] = self.__remote_webpack_require__[bundleName];
1865
- }
1866
- if (runtime === RUNTIME_TURBOPACK) {
1867
- const results = await Promise.allSettled(
1868
- scripts.map((script) => {
1869
- if (script.src) {
1870
- return loadChunkWithScope(scope, script.src);
1871
- }
1872
- return Promise.resolve(void 0);
1873
- })
1874
- );
1875
- for (const result of results) {
1876
- if (result.status === "rejected") {
1877
- logWarn(
1878
- "WebpackRuntime",
1879
- `Initial chunk load failed: ${String(result.reason)}`
1880
- );
1881
- }
1882
- }
1883
- }
1884
- return scope;
1885
- }
1886
- function createModuleDispatcher(runtime) {
1887
- return (id) => {
1888
- const self = globalThis;
1889
- const { bundle, id: moduleId } = id.match(REMOTE_COMPONENT_REGEX)?.groups ?? {
1890
- bundle: "default",
1891
- id
1892
- };
1893
- const bundleName = bundle ?? "default";
1894
- const remoteRuntime = self.__remote_webpack_require__?.[bundleName] ? self.__remote_webpack_require__[bundleName]?.type || "webpack" : runtime;
1895
- logDebug(
1896
- "ModuleDispatcher",
1897
- `Resolving "${id}" (bundle: "${bundleName}", runtime: "${remoteRuntime}")`
1898
- );
1899
- try {
1900
- if (remoteRuntime === RUNTIME_WEBPACK && bundle && moduleId) {
1901
- const scope2 = getScope(bundle);
1902
- if (scope2?.webpackRequire)
1903
- return scope2.webpackRequire(moduleId);
1904
- return self.__remote_webpack_require__?.[bundle]?.(moduleId);
1905
- }
1906
- const scope = getScope(bundleName);
1907
- if (scope) {
1908
- return requireModule(scope, moduleId ?? id, id);
1909
- }
1910
- throw new Error(
1911
- `Module "${id}" not found \u2014 no scope for bundle "${bundleName}".`
1912
- );
1913
- } catch (requireError) {
1914
- logWarn(
1915
- "ModuleDispatcher",
1916
- `Module require failed: ${String(requireError)}`
1917
- );
1918
- if (typeof self.__original_webpack_require__ !== "function") {
1919
- throw new RemoteComponentsError(
1920
- `Module "${id}" not found in remote component bundle "${bundleName}".`,
1921
- {
1922
- cause: requireError instanceof Error ? requireError : void 0
1923
- }
1924
- );
1925
- }
1926
- try {
1927
- logDebug(
1928
- "ModuleDispatcher",
1929
- "Falling back to original webpack require"
1930
- );
1931
- return self.__original_webpack_require__(id);
1932
- } catch (originalError) {
1933
- throw new RemoteComponentsError(
1934
- `Module "${id}" not found in remote component bundle "${bundleName}".`,
1935
- { cause: originalError instanceof Error ? originalError : void 0 }
1936
- );
1937
- }
1938
- }
1939
- };
1940
- }
1941
-
1942
- // src/runtime/loaders/script-loader.ts
1943
- async function loadScripts(scripts, resolveClientUrl) {
1944
- await Promise.all(
1945
- scripts.map((script) => {
1946
- return new Promise((resolve, reject) => {
1947
- const newSrc = new URL(
1948
- // remove the remote component bundle name identifier from the script src
1949
- script.src.replace(NEXT_BUNDLE_PATH_RE, "/_next/"),
1950
- location.origin
1951
- ).href;
1952
- const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;
1953
- const alreadyLoaded = Array.from(
1954
- document.querySelectorAll("script[src]")
1955
- ).some((s) => s.src === resolvedSrc);
1956
- if (alreadyLoaded) {
1957
- resolve();
1958
- return;
1959
- }
1960
- const newScript = document.createElement("script");
1961
- newScript.onload = () => resolve();
1962
- newScript.onerror = () => {
1963
- const isProxied = isProxiedUrl(resolvedSrc);
1964
- if (isProxied) {
1965
- reject(failedProxiedAssetError("script", newSrc, resolvedSrc));
1966
- } else {
1967
- warnCrossOriginFetchError("ScriptLoader", newSrc);
1968
- reject(
1969
- new RemoteComponentsError(
1970
- `Failed to load <script src="${newSrc}"> for Remote Component. Check the URL is correct.`
1971
- )
1972
- );
1973
- }
1974
- };
1975
- newScript.src = resolvedSrc;
1976
- newScript.async = true;
1977
- document.head.appendChild(newScript);
1978
- });
1979
- })
1980
- );
1981
- }
1982
-
1983
- // src/runtime/loaders/component-loader.ts
1984
- async function loadRemoteComponent({
1985
- url,
1986
- name,
1987
- rscName,
1988
- bundle,
1989
- route = "/",
1990
- runtime = "webpack",
1991
- data,
1992
- nextData,
1993
- scripts = [],
1994
- shared: shared2 = Promise.resolve({}),
1995
- remoteShared = {},
1996
- container,
1997
- resolveClientUrl
1998
- }) {
1999
- try {
2000
- if (runtime === "webpack") {
2001
- const self = globalThis;
2002
- if (!self.__DISABLE_WEBPACK_EXEC__) {
2003
- self.__DISABLE_WEBPACK_EXEC__ = {};
2004
- }
2005
- self.__DISABLE_WEBPACK_EXEC__[bundle] = true;
2006
- await loadScripts(scripts, resolveClientUrl);
2007
- }
2008
- const hostShared = await shared2;
2009
- logDebug(
2010
- "ComponentLoader",
2011
- `loadRemoteComponent: bundle="${bundle}", name="${name}"`
2012
- );
2013
- logDebug(
2014
- "ComponentLoader",
2015
- `Host shared modules available: ${Object.keys(hostShared)}`
2016
- );
2017
- logDebug(
2018
- "ComponentLoader",
2019
- `Remote shared modules requested: ${JSON.stringify(remoteShared)}`
2020
- );
2021
- const scope = await setupRemoteScope(
2022
- runtime,
2023
- scripts,
2024
- url,
2025
- bundle,
2026
- resolveClientUrl
2027
- );
2028
- if (runtime === "turbopack") {
2029
- await initializeSharedModules(
2030
- scope,
2031
- buildCoreShared(hostShared),
2032
- remoteShared
2033
- );
2034
- }
2035
- if (bundle) {
2036
- const resolve = await buildWebpackResolve(
2037
- hostShared,
2038
- remoteShared,
2039
- bundle,
2040
- {
2041
- "/react/index.js": React,
2042
- "/react/jsx-dev-runtime.js": JSXDevRuntime,
2043
- "/react/jsx-runtime.js": JSXRuntime,
2044
- "/react-dom/index.js": ReactDOM,
2045
- "/react-dom/client.js": ReactDOMClient
2046
- },
2047
- "ComponentLoader"
2048
- );
2049
- applySharedModules(bundle, resolve);
2050
- } else {
2051
- logWarn(
2052
- "ComponentLoader",
2053
- "No bundle specified, skipping shared module setup"
2054
- );
2055
- }
2056
- if (data.length > 0) {
2057
- return await loadRSCComponent(rscName ?? name, data);
2058
- } else if (nextData) {
2059
- return loadNextPagesComponent(bundle, route, nextData, name, container);
2060
- }
2061
- return loadRSCComponent(rscName ?? name, [`0:[null]
2062
- `]);
2063
- } catch (error) {
2064
- return {
2065
- component: null,
2066
- error: new RemoteComponentsError(
2067
- `Failed to load remote component "${name}".`,
2068
- {
2069
- cause: error instanceof Error ? error : new Error(String(error))
2070
- }
2071
- )
2072
- };
2073
- }
2074
- }
2075
- async function loadRSCComponent(rscName, data) {
2076
- const { createFromReadableStream } = await importRSCClientBrowser();
2077
- if (typeof createFromReadableStream !== "function") {
2078
- throw new RemoteComponentsError(
2079
- 'Failed to import "react-server-dom-webpack". Is Next.js installed correctly?'
2080
- );
2081
- }
2082
- const stream = createRSCStream(rscName, data);
2083
- const component = createFromReadableStream(stream);
2084
- return { component };
2085
- }
2086
- function loadNextPagesComponent(bundle, route, nextData, name, container) {
2087
- const { Component, App } = nextClientPagesLoader(bundle, route, container);
2088
- if (!Component) {
2089
- throw new RemoteComponentsError(
2090
- `Remote Component "${name}" is trying to load the component for route "${route}" but it is not available.`
2091
- );
2092
- }
2093
- const component = App ? React.createElement(App, { Component, ...nextData.props }) : React.createElement(Component, nextData.props);
2094
- return { component };
2095
- }
2096
-
2097
- // src/runtime/loaders/static-loader.ts
2098
- async function importViaCallback(absoluteSrc, resolveClientUrl) {
2099
- const resolvedUrl = resolveClientUrl(absoluteSrc) ?? absoluteSrc;
2100
- const fetchUrl = new URL(resolvedUrl, location.href).href;
2101
- const response = await fetch(fetchUrl);
2102
- if (!response.ok)
2103
- throw new Error(`Proxied fetch failed: ${response.status}`);
2104
- const content = (await response.text()).replace(/import\.meta\.url/g, JSON.stringify(absoluteSrc)).replace(
2105
- /\b(from|import)\s*(["'])(\.\.?\/[^"']+)\2/g,
2106
- (_, keyword, quote, relativePath) => {
2107
- const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;
2108
- const resolvedImportUrl = new URL(
2109
- resolveClientUrl(absoluteImportUrl) ?? absoluteImportUrl,
2110
- location.href
2111
- ).href;
2112
- return `${keyword} ${quote}${resolvedImportUrl}${quote}`;
2113
- }
2114
- );
2115
- const moduleBlobUrl = URL.createObjectURL(
2116
- new Blob([content], { type: "text/javascript" })
2117
- );
2118
- const wrapperContent = [
2119
- `import*as m from${JSON.stringify(moduleBlobUrl)};`,
2120
- `globalThis.__rc_module_registry__=globalThis.__rc_module_registry__||{};`,
2121
- `globalThis.__rc_module_registry__[${JSON.stringify(absoluteSrc)}]=m;`
2122
- ].join("");
2123
- const wrapperBlobUrl = URL.createObjectURL(
2124
- new Blob([wrapperContent], { type: "text/javascript" })
2125
- );
2126
- const scriptEl = document.createElement("script");
2127
- scriptEl.type = "module";
2128
- scriptEl.src = wrapperBlobUrl;
2129
- try {
2130
- await new Promise((resolve, reject) => {
2131
- scriptEl.onload = () => resolve();
2132
- scriptEl.onerror = () => reject(new Error(`Failed to load module for ${absoluteSrc}`));
2133
- document.head.appendChild(scriptEl);
2134
- });
2135
- } finally {
2136
- scriptEl.remove();
2137
- URL.revokeObjectURL(moduleBlobUrl);
2138
- URL.revokeObjectURL(wrapperBlobUrl);
2139
- }
2140
- const registry = getNamespace().moduleRegistry;
2141
- const mod = registry[absoluteSrc] ?? {};
2142
- delete registry[absoluteSrc];
2143
- return mod;
2144
- }
2145
- async function importDirectly(absoluteSrc) {
2146
- try {
2147
- return await import(
2148
- /* @vite-ignore */
2149
- /* webpackIgnore: true */
2150
- absoluteSrc
2151
- );
2152
- } catch (importError) {
2153
- if (!absoluteSrc.startsWith("blob:")) {
2154
- warnCrossOriginFetchError("StaticLoader", absoluteSrc);
2155
- }
2156
- throw importError;
2157
- }
2158
- }
2159
- function resolveScriptSrc(script, url) {
2160
- const rawSrc = typeof script.getAttribute === "function" ? script.getAttribute("src") ?? script.src : script.src;
2161
- if (!rawSrc && script.textContent) {
2162
- return URL.createObjectURL(
2163
- new Blob(
2164
- [script.textContent.replace(/import\.meta\.url/g, JSON.stringify(url))],
2165
- { type: "text/javascript" }
2166
- )
2167
- );
2168
- }
2169
- return rawSrc;
2170
- }
2171
- async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
2172
- const ns = getNamespace();
2173
- if (ns.mountFns[url.href]) {
2174
- ns.mountFns[url.href] = /* @__PURE__ */ new Set();
2175
- }
2176
- if (ns.unmountFns[url.href]) {
2177
- ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
2178
- }
2179
- const mountUnmountSets = await Promise.all(
2180
- scripts.map(async (script) => {
2181
- try {
2182
- const src = resolveScriptSrc(script, url);
2183
- const absoluteSrc = new URL(src, url).href;
2184
- const mod = resolveClientUrl ? await importViaCallback(absoluteSrc, resolveClientUrl) : await importDirectly(absoluteSrc);
2185
- if (src.startsWith("blob:")) {
2186
- URL.revokeObjectURL(src);
2187
- }
2188
- if (typeof mod.mount === "function" || typeof mod.default?.mount === "function") {
2189
- if (!ns.mountFns[url.href]) {
2190
- ns.mountFns[url.href] = /* @__PURE__ */ new Set();
2191
- }
2192
- ns.mountFns[url.href]?.add(
2193
- mod.mount || mod.default?.mount || (() => {
2194
- })
2195
- );
2196
- }
2197
- if (typeof mod.unmount === "function" || typeof mod.default?.unmount === "function") {
2198
- if (!ns.unmountFns[url.href]) {
2199
- ns.unmountFns[url.href] = /* @__PURE__ */ new Set();
2200
- }
2201
- ns.unmountFns[url.href]?.add(
2202
- mod.unmount || mod.default?.unmount || (() => {
2203
- })
2204
- );
2205
- }
2206
- return {
2207
- mount: mod.mount || mod.default?.mount,
2208
- unmount: mod.unmount || mod.default?.unmount
2209
- };
2210
- } catch (e) {
2211
- logError(
2212
- "StaticLoader",
2213
- `Error loading remote component script from "${script.src || url.href}".`,
2214
- e
2215
- );
2216
- return {
2217
- mount: void 0,
2218
- unmount: void 0
2219
- };
2220
- }
2221
- })
2222
- );
2223
- return mountUnmountSets.reduce(
2224
- (acc, { mount, unmount }) => {
2225
- if (typeof mount === "function") {
2226
- acc.mount.add(mount);
2227
- }
2228
- if (typeof unmount === "function") {
2229
- acc.unmount.add(unmount);
2230
- }
2231
- return acc;
2232
- },
2233
- {
2234
- mount: /* @__PURE__ */ new Set(),
2235
- unmount: /* @__PURE__ */ new Set()
2236
- }
2237
- );
2238
- }
2239
-
2240
- // src/host/react/hooks/use-resolve-client-url.ts
2241
- import { useMemo } from "react";
2242
- import { useRemoteComponentsContext } from "#internal/host/react/context";
2243
- function useResolveClientUrl(prop, urlHref) {
2244
- const { resolveClientUrl: contextValue } = useRemoteComponentsContext();
2245
- const raw = prop ?? contextValue;
2246
- return useMemo(() => bindResolveClientUrl(raw, urlHref), [raw, urlHref]);
2247
- }
2248
-
2249
- // src/host/react/hooks/use-shadow-root.ts
2250
- import { useLayoutEffect, useRef, useState } from "react";
2251
- function useShadowRoot({
2252
- isolate,
2253
- mode,
2254
- keySuffix
2255
- }) {
2256
- const shadowRootContainerRef = useRef(null);
2257
- const [shadowRoot, setShadowRoot] = useState(() => {
2258
- const shadowRoots = getNamespace().shadowRoots;
2259
- const ssrShadowRoot = typeof document !== "undefined" ? document.querySelector(
2260
- `[data-remote-component-id="shadowroot_${keySuffix}"]`
2261
- )?.shadowRoot ?? shadowRoots[keySuffix] ?? null : null;
2262
- shadowRoots[keySuffix] = null;
2263
- return ssrShadowRoot;
2264
- });
2265
- useLayoutEffect(() => {
2266
- const shadowRoots = getNamespace().shadowRoots;
2267
- if (isolate !== false && typeof document !== "undefined" && (!shadowRoot || !shadowRoot.isConnected)) {
2268
- let shadowRootElement = null;
2269
- const element = document.querySelector(
2270
- `[data-remote-component-id="shadowroot_${keySuffix}"]`
2271
- );
2272
- shadowRootElement = shadowRoots[keySuffix] ?? element?.shadowRoot ?? null;
2273
- if (!shadowRootElement && element) {
2274
- try {
2275
- shadowRootElement = element.attachShadow({ mode });
2276
- shadowRoots[keySuffix] = shadowRootElement;
2277
- } catch {
2278
- }
2279
- }
2280
- if (shadowRootElement) {
2281
- shadowRootElement.querySelectorAll("*:not(link)").forEach((node) => {
2282
- node.remove();
2283
- });
2284
- setShadowRoot(shadowRootElement);
2285
- }
2286
- } else if (isolate === false && shadowRoot) {
2287
- shadowRoots[keySuffix] = null;
2288
- setShadowRoot(null);
2289
- }
2290
- }, [isolate, shadowRoot, mode, keySuffix]);
2291
- return { shadowRoot, shadowRootContainerRef };
2292
- }
2293
-
2294
- // src/host/react/utils/extract-remote-html.ts
2295
- var DUMMY_FALLBACK = "http://remote-components-dummy-fallback";
2296
- function getRemoteComponentHtml(html) {
2297
- if (typeof document === "undefined")
2298
- return html;
2299
- const parser = new DOMParser();
2300
- const temp = parser.parseFromString(html, "text/html");
2301
- const ssrRemoteComponentContainer = temp.querySelector(
2302
- 'div[id^="__REMOTE_COMPONENT"]'
2303
- );
2304
- if (ssrRemoteComponentContainer) {
2305
- return ssrRemoteComponentContainer.innerHTML;
2306
- }
2307
- const remoteComponentContainer = temp.querySelectorAll(
2308
- `div[data-bundle][data-route][data-runtime][id^="${DEFAULT_COMPONENT_NAME}"],div[data-bundle][data-route],div#__next,remote-component:not([src])`
2309
- );
2310
- if (remoteComponentContainer.length > 0) {
2311
- return `${Array.from(temp.querySelectorAll("link,script")).map((link) => link.outerHTML).join("")}${Array.from(remoteComponentContainer).map((container) => container.outerHTML).join("")}`;
2312
- }
2313
- return "";
2314
- }
2315
-
2316
- // src/host/react/index.tsx
2317
- import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
2318
- import { createElement as createElement3 } from "react";
2319
- function ConsumeRemoteComponent({
2320
- src,
2321
- isolate,
2322
- mode = "open",
2323
- reset,
2324
- credentials: credentialsProp,
2325
- name: nameProp = DEFAULT_COMPONENT_NAME,
2326
- shared: sharedProp,
2327
- children,
2328
- onBeforeLoad,
2329
- onLoad,
2330
- onError,
2331
- onChange,
2332
- onRequest,
2333
- onResponse,
2334
- resolveClientUrl: resolveClientUrlProp
2335
- }) {
2336
- const instanceId = useId();
2337
- const { credentials: contextCredentials, shared: contextShared } = useRemoteComponentsContext2();
2338
- const credentials = credentialsProp ?? contextCredentials ?? "same-origin";
2339
- const shared2 = sharedProp ?? contextShared ?? {};
2340
- const name = useMemo2(
2341
- () => resolveNameFromSrc(src, nameProp),
2342
- [src, nameProp]
2343
- );
2344
- const [data, setData] = useState2(
2345
- null
2346
- );
2347
- const url = useMemo2(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);
2348
- const resolveClientUrl = useResolveClientUrl(resolveClientUrlProp, url.href);
2349
- const id = url.origin === (typeof location !== "undefined" ? location.origin : DUMMY_FALLBACK) ? url.pathname : url.href;
2350
- const keySuffix = `${escapeString(id)}_${escapeString(
2351
- data?.name ?? name
2352
- )}_${escapeString(instanceId)}`;
2353
- const [remoteComponent, setRemoteComponent] = useState2(null);
2354
- const { shadowRoot, shadowRootContainerRef } = useShadowRoot({
2355
- isolate,
2356
- mode,
2357
- keySuffix
2358
- });
2359
- const htmlRef = useRef2(
2360
- typeof document !== "undefined" ? document.querySelector(
2361
- `[data-remote-component-id="shadowroot_${keySuffix}"]`
2362
- )?.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
2363
- );
2364
- const endTemplateRef = useRef2(null);
2365
- const childrenRef = useRef2(
2366
- typeof document !== "undefined" ? (() => {
2367
- let el = document.querySelector(`template[id="${name}_start"]`);
2368
- const elements = [];
2369
- while (el && el.id !== `${name}_end`) {
2370
- if (el.id !== `${name}_start` && !el.getAttribute("data-remote-component")) {
2371
- elements.push(el);
2372
- }
2373
- el = el.nextElementSibling;
2374
- }
2375
- return elements;
2376
- })() : []
2377
- );
2378
- const hostStateRef = useRef2(createHostState());
2379
- const componentHydrationHtml = useRef2(null);
2380
- const prevRemoteComponentContainerRef = useRef2(null);
2381
- const unmountRef = useRef2(null);
2382
- useLayoutEffect2(() => {
2383
- return () => {
2384
- delete getNamespace().shadowRoots[keySuffix];
2385
- };
2386
- }, [keySuffix]);
2387
- useLayoutEffect2(() => {
2388
- if (childrenRef.current.length > 0 && remoteComponent) {
2389
- childrenRef.current.forEach((el) => {
2390
- el.remove();
2391
- });
2392
- childrenRef.current = [];
2393
- }
2394
- }, [remoteComponent]);
2395
- useLayoutEffect2(() => {
2396
- if (shadowRoot && remoteComponent) {
2397
- const resetStyles = shadowRoot.querySelectorAll(
2398
- "style[data-remote-components-reset]"
2399
- );
2400
- if (resetStyles.length > 1) {
2401
- resetStyles.forEach((style, index) => {
2402
- if (index > 0 && style.getAttribute("data-remote-components-reset") !== "react") {
2403
- style.remove();
2404
- }
2405
- });
2406
- }
2407
- htmlRef.current = null;
2408
- let el = shadowRoot.childNodes[0] ?? null;
2409
- while (el && (!("id" in el) || el.id !== `${name}_start`)) {
2410
- const nextEl = el.nextSibling;
2411
- if (el.nodeName !== "LINK" && el.nodeName !== "STYLE") {
2412
- el.parentNode?.removeChild(el);
2413
- }
2414
- el = nextEl;
2415
- }
2416
- }
2417
- }, [shadowRoot, remoteComponent, name]);
2418
- useEffect(() => {
2419
- if (src && src !== hostStateRef.current.prevSrc) {
2420
- const previousSrc = hostStateRef.current.prevSrc;
2421
- const previousName = hostStateRef.current.prevName;
2422
- hostStateRef.current.prevSrc = src;
2423
- if (previousSrc !== null) {
2424
- htmlRef.current = null;
2425
- }
2426
- hostStateRef.current.abortController?.abort();
2427
- hostStateRef.current.abortController = new AbortController();
2428
- const { signal } = hostStateRef.current.abortController;
2429
- onBeforeLoad?.(src);
2430
- hostStateRef.current.stage = "loading";
2431
- startTransition(async () => {
2432
- try {
2433
- let html = getRemoteComponentHtml(
2434
- htmlRef.current ?? (endTemplateRef.current?.previousElementSibling?.tagName === "div" ? endTemplateRef.current.previousElementSibling.innerHTML : "")
2435
- );
2436
- if (!html && src) {
2437
- const fetchInit = {
2438
- credentials
2439
- };
2440
- const resolvedUrl = new URL(
2441
- resolveClientUrl?.(url.href) ?? url.href,
2442
- location.href
2443
- );
2444
- const res = await fetchWithHooks(resolvedUrl, fetchInit, {
2445
- onRequest,
2446
- onResponse,
2447
- abortController: hostStateRef.current.abortController
2448
- });
2449
- if (!res || !res.ok) {
2450
- throw await errorFromFailedFetch(url.href, resolvedUrl, res);
2451
- }
2452
- const remoteHtml = await res.text();
2453
- if (signal.aborted)
2454
- return;
2455
- htmlRef.current = remoteHtml;
2456
- html = getRemoteComponentHtml(remoteHtml);
2457
- }
2458
- if (signal.aborted)
2459
- return;
2460
- const parser = new DOMParser();
2461
- const doc = parser.parseFromString(html, "text/html");
2462
- const {
2463
- component,
2464
- name: remoteName,
2465
- isRemoteComponent,
2466
- metadata,
2467
- nextData,
2468
- rsc,
2469
- remoteShared,
2470
- links: linkElements,
2471
- scripts: scriptElements
2472
- } = parseRemoteComponentDocument(doc, name, url);
2473
- if (hostStateRef.current.prevIsRemoteComponent) {
2474
- if (shadowRoot) {
2475
- shadowRoot.innerHTML = "";
2476
- }
2477
- const prevUrl = hostStateRef.current.prevUrl;
2478
- if (prevUrl && getNamespace().unmountFns[prevUrl.href]) {
2479
- const unmountPromises = Promise.all(
2480
- Array.from(unmountRef.current ?? []).map(
2481
- async (unmount) => unmount(
2482
- shadowRoot ?? prevRemoteComponentContainerRef.current
2483
- )
2484
- )
2485
- );
2486
- unmountRef.current = null;
2487
- await unmountPromises;
2488
- }
2489
- }
2490
- hostStateRef.current.prevIsRemoteComponent = isRemoteComponent;
2491
- hostStateRef.current.prevUrl = url;
2492
- hostStateRef.current.prevName = remoteName;
2493
- applyOriginToNodes(doc, url, resolveClientUrl);
2494
- const links = linkElements.map((link) => ({
2495
- href: new URL(link.getAttribute("href") ?? link.href, url).href,
2496
- ...link.getAttributeNames().reduce((acc, key) => {
2497
- if (key !== "href") {
2498
- acc[attrToProp[key] ?? key] = link.getAttribute(key) ?? "";
2499
- }
2500
- return acc;
2501
- }, {})
2502
- }));
2503
- const scripts = scriptElements;
2504
- const inlineScripts = (isRemoteComponent ? component : doc).querySelectorAll(
2505
- "script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])"
2506
- );
2507
- if (!isRemoteComponent) {
2508
- const self = globalThis;
2509
- const prevNextScripts = self.__next_s;
2510
- const nextScripts = [];
2511
- self.__next_s = nextScripts;
2512
- await Promise.all(
2513
- Array.from(inlineScripts).filter(
2514
- (script) => !(script.id.endsWith("_shared") && script.getAttribute("type") === "application/json" && typeof script.getAttribute(
2515
- "data-remote-components-shared"
2516
- ) === "string")
2517
- ).map((script) => {
2518
- return new Promise((resolve) => {
2519
- if (script.textContent && !script.textContent.includes("self.__next_f=") && !script.textContent.includes("self.__next_f.push")) {
2520
- if (!script.getAttribute("type") || script.getAttribute("type") === "text/javascript" || script.getAttribute("type") === "application/javascript") {
2521
- const newScript = document.createElement("script");
2522
- const blob = new Blob([script.textContent], {
2523
- type: "application/javascript"
2524
- });
2525
- const blobUrl = URL.createObjectURL(blob);
2526
- newScript.onload = () => {
2527
- resolve(void 0);
2528
- URL.revokeObjectURL(blobUrl);
2529
- newScript.remove();
2530
- };
2531
- newScript.onerror = () => {
2532
- URL.revokeObjectURL(blobUrl);
2533
- newScript.remove();
2534
- resolve(void 0);
2535
- };
2536
- newScript.src = blobUrl;
2537
- document.body.appendChild(newScript);
2538
- } else {
2539
- resolve(void 0);
2540
- document.body.appendChild(script);
2541
- }
2542
- } else {
2543
- resolve(void 0);
2544
- }
2545
- });
2546
- })
2547
- );
2548
- nextScripts.forEach(([scriptSrc, props]) => {
2549
- const script = document.createElement("script");
2550
- if (scriptSrc) {
2551
- script.src = scriptSrc;
2552
- }
2553
- if (typeof props.children === "string") {
2554
- script.textContent = props.children;
2555
- }
2556
- setAttributesFromProps(script, props);
2557
- document.head.appendChild(script);
2558
- });
2559
- self.__next_s = prevNextScripts;
2560
- }
2561
- const rscName = rsc ? `__remote_component_rsc_${escapeString(id)}_${escapeString(
2562
- remoteName
2563
- )}` : void 0;
2564
- if (rsc) {
2565
- rsc.textContent = rsc.textContent?.replace(
2566
- new RegExp(`self\\["${remoteName}"\\]`, "g"),
2567
- `self["${rscName}"]`
2568
- ) ?? "";
2569
- document.body.appendChild(rsc);
2570
- }
2571
- const newData = {
2572
- ...metadata,
2573
- links,
2574
- remoteShared,
2575
- src: typeof src === "string" ? src : src.href,
2576
- serverUrl: url.href,
2577
- data: rsc ? (rsc.textContent || "").split("\n").filter(Boolean) : []
2578
- };
2579
- componentHydrationHtml.current = `${Array.from(
2580
- doc.querySelectorAll("link,style")
2581
- ).map((link) => link.outerHTML).join("")}${reset ? `<style data-remote-components-reset="">:host { all: initial; }</style>` : ""}${component.innerHTML}`;
2582
- const userShared = await shared2;
2583
- if ("__remote_components_missing_shared__" in userShared) {
2584
- userShared.__remote_components_missing_shared__().catch((e) => {
2585
- throw e;
2586
- });
2587
- } else if ("__remote_components_missing_shared__" in remoteShared) {
2588
- throw new RemoteComponentsError(
2589
- remoteShared.__remote_components_missing_shared__
2590
- );
2591
- }
2592
- if (isRemoteComponent) {
2593
- if (previousSrc !== void 0) {
2594
- onChange?.({
2595
- previousSrc,
2596
- nextSrc: src,
2597
- previousName,
2598
- nextName: remoteName
2599
- });
2600
- }
2601
- setData(newData);
2602
- if (shadowRoot) {
2603
- const shadowRootHtml = reset ? `<style data-remote-components-reset="">:host { all: initial; }</style>${component.innerHTML}` : component.innerHTML;
2604
- shadowRoot.innerHTML = shadowRootHtml;
2605
- htmlRef.current = null;
2606
- setRemoteComponent(null);
2607
- const { mount, unmount } = await loadStaticRemoteComponent(
2608
- Array.from(shadowRoot.querySelectorAll("script")),
2609
- url,
2610
- resolveClientUrl
2611
- );
2612
- unmountRef.current = unmount;
2613
- await Promise.all(
2614
- Array.from(mount).map((mountFn) => mountFn(shadowRoot))
2615
- );
2616
- onLoad?.(src);
2617
- } else if (isolate === false) {
2618
- setRemoteComponent(
2619
- // TODO: remove wrapper div by converting HTML to RSC or React tree
2620
- /* @__PURE__ */ jsx2(
2621
- "div",
2622
- {
2623
- dangerouslySetInnerHTML: { __html: component.innerHTML },
2624
- ref: prevRemoteComponentContainerRef
2625
- }
2626
- )
2627
- );
2628
- htmlRef.current = null;
2629
- const { mount, unmount } = await loadStaticRemoteComponent(
2630
- Array.from(component.querySelectorAll("script")),
2631
- url,
2632
- resolveClientUrl
2633
- );
2634
- unmountRef.current = unmount;
2635
- await Promise.all(
2636
- Array.from(mount).map(
2637
- (mountFn) => mountFn(prevRemoteComponentContainerRef.current)
2638
- )
2639
- );
2640
- onLoad?.(src);
2641
- }
2642
- hostStateRef.current.stage = "loaded";
2643
- } else {
2644
- const result = await loadRemoteComponent({
2645
- url,
2646
- name: remoteName,
2647
- rscName,
2648
- bundle: metadata.bundle,
2649
- route: metadata.route,
2650
- runtime: metadata.runtime,
2651
- data: newData.data,
2652
- nextData,
2653
- scripts: Array.from(scripts).map((script) => {
2654
- const scriptSrc = script.getAttribute("data-src") || script.getAttribute("src") || script.src;
2655
- const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(
2656
- scriptSrc
2657
- )?.groups ?? {
2658
- prefix: void 0,
2659
- id: scriptSrc
2660
- };
2661
- return {
2662
- src: new URL(
2663
- collapseDoubleSlashes(`${prefix ?? ""}${path}`),
2664
- url
2665
- ).href
2666
- };
2667
- }),
2668
- shared: buildHostShared(userShared, resolveClientUrl),
2669
- remoteShared,
2670
- container: shadowRoot,
2671
- resolveClientUrl
2672
- });
2673
- if (rsc) {
2674
- rsc.remove();
2675
- }
2676
- setData(newData);
2677
- if (previousSrc !== void 0) {
2678
- onChange?.({
2679
- previousSrc,
2680
- nextSrc: src,
2681
- previousName,
2682
- nextName: remoteName
2683
- });
2684
- }
2685
- if (result.error) {
2686
- hostStateRef.current.stage = "error";
2687
- setRemoteComponent(result.error);
2688
- onError?.(result.error);
2689
- } else {
2690
- hostStateRef.current.stage = "loaded";
2691
- setRemoteComponent(result.component);
2692
- onLoad?.(src);
2693
- }
2694
- }
2695
- } catch (error) {
2696
- if (isAbortError(error)) {
2697
- hostStateRef.current.stage = "idle";
2698
- return;
2699
- }
2700
- hostStateRef.current.stage = "error";
2701
- setRemoteComponent(error);
2702
- onError?.(error);
2703
- }
2704
- });
2705
- }
2706
- }, [
2707
- url,
2708
- src,
2709
- isolate,
2710
- credentials,
2711
- name,
2712
- shared2,
2713
- shadowRoot,
2714
- reset,
2715
- id,
2716
- onBeforeLoad,
2717
- onLoad,
2718
- onError,
2719
- onChange,
2720
- onRequest,
2721
- onResponse,
2722
- resolveClientUrl
2723
- ]);
2724
- if (remoteComponent instanceof Error) {
2725
- throw remoteComponent;
2726
- }
2727
- const metadataJson = /* @__PURE__ */ jsx2("script", { "data-remote-component": true, type: "application/json", children: JSON.stringify({
2728
- name: data?.name || name,
2729
- bundle: data?.bundle || "default",
2730
- route: data?.route || DEFAULT_ROUTE,
2731
- runtime: hostStateRef.current.prevIsRemoteComponent ? RUNTIME_SCRIPT : data?.runtime || RUNTIME_WEBPACK
2732
- }) });
2733
- const resetStyle = reset ? /* @__PURE__ */ jsx2("style", { "data-remote-components-reset": "react", children: `:host { all: initial; }` }) : null;
2734
- const linksToRender = data?.links?.map((link) => /* @__PURE__ */ createElement3(
2735
- "link",
2736
- {
2737
- ...link,
2738
- href: new URL(link.href, url).href,
2739
- key: JSON.stringify(link)
2740
- }
2741
- )) || null;
2742
- const componentToRender = /* @__PURE__ */ jsxs(Fragment, { children: [
2743
- resetStyle,
2744
- linksToRender,
2745
- remoteComponent ?? children
2746
- ] });
2747
- if (componentHydrationHtml.current && shadowRoot && !shadowRoot.innerHTML) {
2748
- shadowRoot.innerHTML = componentHydrationHtml.current;
2749
- componentHydrationHtml.current = null;
2750
- if (hostStateRef.current.prevIsRemoteComponent) {
2751
- loadStaticRemoteComponent(
2752
- Array.from(shadowRoot.querySelectorAll("script")),
2753
- url,
2754
- resolveClientUrl
2755
- ).then(({ mount }) => {
2756
- return Promise.all(
2757
- Array.from(mount).map((mountFn) => mountFn(shadowRoot))
2758
- );
2759
- }).then(() => {
2760
- if (src) {
2761
- onLoad?.(src);
2762
- }
2763
- }).catch((e) => {
2764
- const error = new RemoteComponentsError(
2765
- `Error mounting remote component from "${url.href}"`,
2766
- {
2767
- cause: e
2768
- }
2769
- );
2770
- setRemoteComponent(error);
2771
- onError?.(error);
2772
- });
2773
- }
2774
- }
2775
- if (isolate !== false) {
2776
- const shadowRemoteComponentHtml = shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ?? shadowRoot?.querySelector("div[data-bundle][data-route]");
2777
- if (shadowRemoteComponentHtml) {
2778
- shadowRemoteComponentHtml.remove();
2779
- }
2780
- return /* @__PURE__ */ jsxs(Fragment, { children: [
2781
- metadataJson,
2782
- /* @__PURE__ */ jsxs(
2783
- "div",
2784
- {
2785
- "data-remote-component-id": `shadowroot_${keySuffix}`,
2786
- id: `shadowroot_${data?.name ?? name}`,
2787
- ref: shadowRootContainerRef,
2788
- children: [
2789
- typeof document === "undefined" ? (
2790
- // eslint-disable-next-line react/no-unknown-property
2791
- /* @__PURE__ */ jsxs("template", { shadowrootmode: mode, children: [
2792
- typeof document === "undefined" ? /* @__PURE__ */ jsx2(
2793
- "div",
2794
- {
2795
- dangerouslySetInnerHTML: {
2796
- __html: `<img
2797
- alt="" decoding="async" style="display:none"
2798
- src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
2799
- onload="(function(el){
2800
- // Capture the shadow root during SSR hydration so the client-side
2801
- // useShadowRoot hook can find it.
2802
- const root = el.getRootNode();
2803
- globalThis.__remote_components_shadowroot_${keySuffix}=root;
2804
- el.parentElement.remove();
2805
- })(this)"
2806
- />`
2807
- }
2808
- }
2809
- ) : null,
2810
- resetStyle,
2811
- linksToRender,
2812
- children
2813
- ] })
2814
- ) : null,
2815
- shadowRoot && remoteComponent ? createPortal(
2816
- /* @__PURE__ */ jsxs(Fragment, { children: [
2817
- /* @__PURE__ */ jsx2("template", { id: `${name}_start` }),
2818
- resetStyle,
2819
- linksToRender,
2820
- remoteComponent,
2821
- /* @__PURE__ */ jsx2("template", { id: `${name}_end`, ref: endTemplateRef })
2822
- ] }),
2823
- shadowRoot
2824
- ) : null
2825
- ]
2826
- }
2827
- )
2828
- ] });
2829
- }
2830
- htmlRef.current = null;
2831
- return /* @__PURE__ */ jsxs(Fragment, { children: [
2832
- /* @__PURE__ */ jsx2("template", { id: `${name}_start` }),
2833
- metadataJson,
2834
- componentToRender,
2835
- /* @__PURE__ */ jsx2("template", { id: `${name}_end`, ref: endTemplateRef })
2836
- ] });
2837
- }
2838
-
2839
90
  // src/host/nextjs/app-compat.tsx
2840
91
  import { usePathname, useSearchParams } from "next/navigation";
2841
92
  var routerImpl = async () => {
@@ -2902,7 +153,7 @@ var routerImpl = async () => {
2902
153
  };
2903
154
 
2904
155
  // src/host/nextjs/app-client-only.tsx
2905
- import { jsx as jsx3 } from "react/jsx-runtime";
156
+ import { jsx } from "react/jsx-runtime";
2906
157
  var sharedModules = async (userShared, resolveClientUrl) => {
2907
158
  const [resolvedShared, resolvedUserShared] = await Promise.all([
2908
159
  tryImportShared(),
@@ -2916,16 +167,16 @@ var sharedModules = async (userShared, resolveClientUrl) => {
2916
167
  };
2917
168
  };
2918
169
  function RemoteComponentsClientProvider({
2919
- shared: shared2,
170
+ shared,
2920
171
  resolveClientUrl,
2921
172
  children,
2922
173
  ...props
2923
174
  }) {
2924
- const mergedShared = useMemo3(
2925
- () => sharedModules(shared2, resolveClientUrl),
2926
- [shared2, resolveClientUrl]
175
+ const mergedShared = useMemo(
176
+ () => sharedModules(shared, resolveClientUrl),
177
+ [shared, resolveClientUrl]
2927
178
  );
2928
- return /* @__PURE__ */ jsx3(
179
+ return /* @__PURE__ */ jsx(
2929
180
  RemoteComponentsContext,
2930
181
  {
2931
182
  value: { shared: mergedShared, resolveClientUrl, ...props },
@@ -2937,7 +188,7 @@ function ConsumeRemoteComponent2(props) {
2937
188
  if (typeof props.src !== "string" && !(props.src instanceof URL)) {
2938
189
  return props.children ?? null;
2939
190
  }
2940
- return /* @__PURE__ */ jsx3(
191
+ return /* @__PURE__ */ jsx(
2941
192
  ConsumeRemoteComponent,
2942
193
  {
2943
194
  ...props,