remote-components 0.3.4 → 0.3.6

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