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