remote-components 0.0.50 → 0.1.0

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 (119) hide show
  1. package/dist/{component-loader-1838f572.d.ts → component-loader-76eb1b8b.d.ts} +3 -1
  2. package/dist/html/host.cjs +486 -242
  3. package/dist/html/host.cjs.map +1 -1
  4. package/dist/html/host.d.ts +2 -0
  5. package/dist/html/host.js +485 -242
  6. package/dist/html/host.js.map +1 -1
  7. package/dist/html/remote.cjs +123 -21
  8. package/dist/html/remote.cjs.map +1 -1
  9. package/dist/html/remote.js +123 -21
  10. package/dist/html/remote.js.map +1 -1
  11. package/dist/internal/next/host/app-router-client.cjs +12 -3
  12. package/dist/internal/next/host/app-router-client.cjs.map +1 -1
  13. package/dist/internal/next/host/app-router-client.d.ts +11 -2
  14. package/dist/internal/next/host/app-router-client.js +12 -3
  15. package/dist/internal/next/host/app-router-client.js.map +1 -1
  16. package/dist/internal/react/context.cjs +43 -0
  17. package/dist/internal/react/context.cjs.map +1 -0
  18. package/dist/internal/react/context.d.ts +20 -0
  19. package/dist/internal/react/context.js +18 -0
  20. package/dist/internal/react/context.js.map +1 -0
  21. package/dist/internal/react/hooks/use-resolve-client-url.cjs +39 -0
  22. package/dist/internal/react/hooks/use-resolve-client-url.cjs.map +1 -0
  23. package/dist/internal/react/hooks/use-resolve-client-url.d.ts +5 -0
  24. package/dist/internal/react/hooks/use-resolve-client-url.js +15 -0
  25. package/dist/internal/react/hooks/use-resolve-client-url.js.map +1 -0
  26. package/dist/internal/shared/client/apply-origin.cjs +10 -5
  27. package/dist/internal/shared/client/apply-origin.cjs.map +1 -1
  28. package/dist/internal/shared/client/apply-origin.d.ts +3 -1
  29. package/dist/internal/shared/client/apply-origin.js +10 -5
  30. package/dist/internal/shared/client/apply-origin.js.map +1 -1
  31. package/dist/internal/shared/client/default-resolve-client-url.cjs +32 -0
  32. package/dist/internal/shared/client/default-resolve-client-url.cjs.map +1 -0
  33. package/dist/internal/shared/client/default-resolve-client-url.d.ts +5 -0
  34. package/dist/internal/shared/client/default-resolve-client-url.js +10 -0
  35. package/dist/internal/shared/client/default-resolve-client-url.js.map +1 -0
  36. package/dist/internal/shared/client/protected-rc-fallback.cjs +41 -0
  37. package/dist/internal/shared/client/protected-rc-fallback.cjs.map +1 -0
  38. package/dist/internal/shared/client/protected-rc-fallback.d.ts +7 -0
  39. package/dist/internal/shared/client/protected-rc-fallback.js +16 -0
  40. package/dist/internal/shared/client/protected-rc-fallback.js.map +1 -0
  41. package/dist/internal/shared/client/proxy-through-host.cjs +51 -0
  42. package/dist/internal/shared/client/proxy-through-host.cjs.map +1 -0
  43. package/dist/internal/shared/client/proxy-through-host.d.ts +57 -0
  44. package/dist/internal/shared/client/proxy-through-host.js +26 -0
  45. package/dist/internal/shared/client/proxy-through-host.js.map +1 -0
  46. package/dist/internal/shared/client/remote-component.cjs +208 -134
  47. package/dist/internal/shared/client/remote-component.cjs.map +1 -1
  48. package/dist/internal/shared/client/remote-component.d.ts +7 -5
  49. package/dist/internal/shared/client/remote-component.js +207 -134
  50. package/dist/internal/shared/client/remote-component.js.map +1 -1
  51. package/dist/internal/shared/constants.cjs +32 -0
  52. package/dist/internal/shared/constants.cjs.map +1 -0
  53. package/dist/internal/shared/constants.d.ts +4 -0
  54. package/dist/internal/shared/constants.js +7 -0
  55. package/dist/internal/shared/constants.js.map +1 -0
  56. package/dist/internal/shared/error.cjs +70 -0
  57. package/dist/internal/shared/error.cjs.map +1 -1
  58. package/dist/internal/shared/error.d.ts +3 -1
  59. package/dist/internal/shared/error.js +71 -0
  60. package/dist/internal/shared/error.js.map +1 -1
  61. package/dist/internal/shared/ssr/fetch-remote-component.cjs +1 -2
  62. package/dist/internal/shared/ssr/fetch-remote-component.cjs.map +1 -1
  63. package/dist/internal/shared/ssr/fetch-remote-component.js +1 -2
  64. package/dist/internal/shared/ssr/fetch-remote-component.js.map +1 -1
  65. package/dist/internal/shared/ssr/fetch-with-hooks.cjs +7 -2
  66. package/dist/internal/shared/ssr/fetch-with-hooks.cjs.map +1 -1
  67. package/dist/internal/shared/ssr/fetch-with-hooks.js +7 -2
  68. package/dist/internal/shared/ssr/fetch-with-hooks.js.map +1 -1
  69. package/dist/internal/shared/utils/logger.cjs +26 -10
  70. package/dist/internal/shared/utils/logger.cjs.map +1 -1
  71. package/dist/internal/shared/utils/logger.d.ts +7 -2
  72. package/dist/internal/shared/utils/logger.js +24 -9
  73. package/dist/internal/shared/utils/logger.js.map +1 -1
  74. package/dist/next/config.cjs +2 -2
  75. package/dist/next/config.cjs.map +1 -1
  76. package/dist/next/config.js +2 -2
  77. package/dist/next/config.js.map +1 -1
  78. package/dist/next/host/client/index.cjs +363 -207
  79. package/dist/next/host/client/index.cjs.map +1 -1
  80. package/dist/next/host/client/index.d.ts +3 -1
  81. package/dist/next/host/client/index.js +336 -181
  82. package/dist/next/host/client/index.js.map +1 -1
  83. package/dist/next/host/pages-router-client.cjs +15 -2
  84. package/dist/next/host/pages-router-client.cjs.map +1 -1
  85. package/dist/next/host/pages-router-client.d.ts +12 -1
  86. package/dist/next/host/pages-router-client.js +15 -2
  87. package/dist/next/host/pages-router-client.js.map +1 -1
  88. package/dist/next/host/pages-router-server.cjs +3 -2
  89. package/dist/next/host/pages-router-server.cjs.map +1 -1
  90. package/dist/next/host/pages-router-server.d.ts +16 -0
  91. package/dist/next/host/pages-router-server.js +3 -2
  92. package/dist/next/host/pages-router-server.js.map +1 -1
  93. package/dist/next/proxy.cjs +66 -27
  94. package/dist/next/proxy.cjs.map +1 -1
  95. package/dist/next/proxy.d.ts +0 -1
  96. package/dist/next/proxy.js +66 -27
  97. package/dist/next/proxy.js.map +1 -1
  98. package/dist/proxy-through-host-a676a522.d.ts +52 -0
  99. package/dist/react/index.cjs +381 -206
  100. package/dist/react/index.cjs.map +1 -1
  101. package/dist/react/index.d.ts +28 -4
  102. package/dist/react/index.js +354 -181
  103. package/dist/react/index.js.map +1 -1
  104. package/dist/shared/host/proxy.cjs +52 -23
  105. package/dist/shared/host/proxy.cjs.map +1 -1
  106. package/dist/shared/host/proxy.d.ts +0 -3
  107. package/dist/shared/host/proxy.js +55 -22
  108. package/dist/shared/host/proxy.js.map +1 -1
  109. package/dist/shared/remote/proxy.cjs +9 -1
  110. package/dist/shared/remote/proxy.cjs.map +1 -1
  111. package/dist/shared/remote/proxy.d.ts +7 -1
  112. package/dist/shared/remote/proxy.js +8 -1
  113. package/dist/shared/remote/proxy.js.map +1 -1
  114. package/package.json +1 -1
  115. package/dist/internal/shared/ssr/fetch-with-protected-rc-fallback.cjs +0 -62
  116. package/dist/internal/shared/ssr/fetch-with-protected-rc-fallback.cjs.map +0 -1
  117. package/dist/internal/shared/ssr/fetch-with-protected-rc-fallback.d.ts +0 -14
  118. package/dist/internal/shared/ssr/fetch-with-protected-rc-fallback.js +0 -37
  119. package/dist/internal/shared/ssr/fetch-with-protected-rc-fallback.js.map +0 -1
package/dist/html/host.js CHANGED
@@ -8,6 +8,51 @@ var __export = (target, all) => {
8
8
  __defProp(target, name, { get: all[name], enumerable: true });
9
9
  };
10
10
 
11
+ // src/shared/constants.ts
12
+ var RC_PROTECTED_REMOTE_FETCH_PATHNAME, CORS_DOCS_URL;
13
+ var init_constants = __esm({
14
+ "src/shared/constants.ts"() {
15
+ "use strict";
16
+ RC_PROTECTED_REMOTE_FETCH_PATHNAME = "/rc-fetch-protected-remote";
17
+ CORS_DOCS_URL = "https://vercel.com/docs/remote-components/concepts/cors-external-urls#accessing-cross-site-protected-remote-components";
18
+ }
19
+ });
20
+
21
+ // src/shared/client/protected-rc-fallback.ts
22
+ function generateProtectedRcFallbackSrc(url) {
23
+ return `${RC_PROTECTED_REMOTE_FETCH_PATHNAME}?url=${encodeURIComponent(url)}`;
24
+ }
25
+ function isProxiedUrl(url) {
26
+ try {
27
+ return new URL(url, location.href).pathname === RC_PROTECTED_REMOTE_FETCH_PATHNAME;
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
32
+ var init_protected_rc_fallback = __esm({
33
+ "src/shared/client/protected-rc-fallback.ts"() {
34
+ "use strict";
35
+ init_constants();
36
+ }
37
+ });
38
+
39
+ // src/shared/utils/abort.ts
40
+ function isAbortError(error) {
41
+ if (error instanceof DOMException && error.name === "AbortError") {
42
+ return true;
43
+ }
44
+ if (error !== null && typeof error === "object" && "name" in error && error.name === "AbortError" && "message" in error && typeof error.message === "string") {
45
+ const e = error;
46
+ return typeof e.code === "number" || e.constructor?.name === "DOMException";
47
+ }
48
+ return false;
49
+ }
50
+ var init_abort = __esm({
51
+ "src/shared/utils/abort.ts"() {
52
+ "use strict";
53
+ }
54
+ });
55
+
11
56
  // src/shared/error.ts
12
57
  function multipleRemoteComponentsError(url) {
13
58
  return new RemoteComponentsError(
@@ -20,10 +65,76 @@ function failedToFetchRemoteComponentError(url, { status, statusText }, help = "
20
65
  { cause: new Error(`${status} ${statusText}`) }
21
66
  );
22
67
  }
68
+ async function errorFromFailedFetch(originalUrl, resolvedUrl, res) {
69
+ const isProxied = isProxiedUrl(resolvedUrl.href);
70
+ if (isProxied && res) {
71
+ const body = await res.text().catch(() => "");
72
+ return failedProxyFetchError(
73
+ originalUrl,
74
+ resolvedUrl.href,
75
+ res.status,
76
+ body
77
+ );
78
+ }
79
+ const fallback = failedToFetchRemoteComponentError(
80
+ originalUrl,
81
+ res ?? { status: 0, statusText: "No Response" }
82
+ );
83
+ if (!res)
84
+ return fallback;
85
+ try {
86
+ const body = await res.text();
87
+ const parser = new DOMParser();
88
+ const doc = parser.parseFromString(body, "text/html");
89
+ const errorTemplate = doc.querySelector(
90
+ "template[data-next-error-message]"
91
+ );
92
+ const errorMessage = errorTemplate?.getAttribute("data-next-error-message");
93
+ if (errorMessage) {
94
+ const error = new RemoteComponentsError(errorMessage);
95
+ const errorStack = errorTemplate?.getAttribute("data-next-error-stack");
96
+ if (errorStack) {
97
+ error.stack = errorStack;
98
+ }
99
+ return error;
100
+ }
101
+ } catch (parseError) {
102
+ if (isAbortError(parseError))
103
+ throw parseError;
104
+ }
105
+ return fallback;
106
+ }
107
+ function failedProxyFetchError(originalUrl, proxyUrl, status, responseBody) {
108
+ if (status === 404) {
109
+ return new RemoteComponentsError(
110
+ `Could not proxy the request to "${originalUrl}" \u2014 the proxy endpoint "${RC_PROTECTED_REMOTE_FETCH_PATHNAME}" returned 404.
111
+
112
+ The host server needs middleware or a route that handles "${RC_PROTECTED_REMOTE_FETCH_PATHNAME}".
113
+
114
+ Proxying requires two pieces:
115
+ 1. resolveClientUrl={proxyClientRequestsThroughHost} on <RemoteComponent>
116
+ 2. Middleware or a route for "${RC_PROTECTED_REMOTE_FETCH_PATHNAME}" on the host server
117
+
118
+ Docs: ${CORS_DOCS_URL}`
119
+ );
120
+ }
121
+ if (status === 403) {
122
+ const detail = responseBody ? ` ${responseBody}` : "";
123
+ return new RemoteComponentsError(
124
+ `Proxied request to "${proxyUrl}" was forbidden.${detail} See: ${CORS_DOCS_URL}`
125
+ );
126
+ }
127
+ return new RemoteComponentsError(
128
+ `Proxied request for "${originalUrl}" via "${proxyUrl}" failed with status ${status}. See: ${CORS_DOCS_URL}`
129
+ );
130
+ }
23
131
  var RemoteComponentsError;
24
132
  var init_error = __esm({
25
133
  "src/shared/error.ts"() {
26
134
  "use strict";
135
+ init_protected_rc_fallback();
136
+ init_constants();
137
+ init_abort();
27
138
  RemoteComponentsError = class extends Error {
28
139
  code = "REMOTE_COMPONENTS_ERROR";
29
140
  constructor(message, options) {
@@ -40,9 +151,6 @@ function logDebug(location2, message) {
40
151
  console.debug(`[${PREFIX}:${location2}]: ${message}`);
41
152
  }
42
153
  }
43
- function logInfo(location2, message) {
44
- console.info(`[${PREFIX}:${location2}]: ${message}`);
45
- }
46
154
  function logWarn(location2, message) {
47
155
  console.warn(`[${PREFIX}:${location2}]: ${message}`);
48
156
  }
@@ -53,10 +161,24 @@ function logError(location2, message, cause) {
53
161
  })
54
162
  );
55
163
  }
164
+ function warnCrossOriginFetchError(logLocation, url) {
165
+ try {
166
+ const parsed = typeof url === "string" ? new URL(url) : url;
167
+ if (typeof location === "undefined" || parsed.origin === location.origin) {
168
+ return;
169
+ }
170
+ logWarn(
171
+ logLocation,
172
+ `Failed to fetch cross-origin resource "${parsed.href}". If this is a protected deployment, ensure withRemoteComponentsHost middleware is configured in your host and that the remote URL is included in allowedProxyUrls. See: ${CORS_DOCS_URL}`
173
+ );
174
+ } catch {
175
+ }
176
+ }
56
177
  var PREFIX, DEBUG;
57
178
  var init_logger = __esm({
58
179
  "src/shared/utils/logger.ts"() {
59
180
  "use strict";
181
+ init_constants();
60
182
  init_error();
61
183
  PREFIX = "remote-components";
62
184
  DEBUG = typeof window !== "undefined" && localStorage.getItem("RC_DEBUG") === "true";
@@ -248,60 +370,60 @@ var init_shared_modules = __esm({
248
370
  }
249
371
  });
250
372
 
251
- // src/shared/utils/abort.ts
252
- function isAbortError(error) {
253
- if (error instanceof DOMException && error.name === "AbortError") {
254
- return true;
255
- }
256
- if (error !== null && typeof error === "object" && "name" in error && error.name === "AbortError" && "message" in error && typeof error.message === "string") {
257
- const e = error;
258
- return typeof e.code === "number" || e.constructor?.name === "DOMException";
259
- }
260
- return false;
261
- }
262
- var init_abort = __esm({
263
- "src/shared/utils/abort.ts"() {
373
+ // src/shared/client/webpack-patterns.ts
374
+ var NEXT_BUNDLE_PATH_RE;
375
+ var init_webpack_patterns = __esm({
376
+ "src/shared/client/webpack-patterns.ts"() {
264
377
  "use strict";
378
+ NEXT_BUNDLE_PATH_RE = /\/_next\/\[.+\](?:%20| )/;
265
379
  }
266
380
  });
267
381
 
268
- // src/shared/ssr/fetch-with-protected-rc-fallback.ts
269
- async function fetchWithProtectedRcFallback(url, init) {
270
- try {
271
- const res = await fetch(url, init);
272
- return res;
273
- } catch (error) {
274
- if (isAbortError(error)) {
275
- throw error;
276
- }
277
- if (typeof document === "object" && typeof document.location === "object" && document.location.origin !== new URL(url).origin) {
278
- logInfo(
279
- "FetchRemoteComponent",
280
- "Request failed due to CORS, attempting to fetch it via the withRemoteComponentsHost proxy."
281
- );
282
- const proxiedRes = await fetch(
283
- `${RC_PROTECTED_REMOTE_FETCH_PATHNAME}?url=${url}`,
284
- init?.signal ? { signal: init.signal } : void 0
285
- );
286
- if (proxiedRes.status === 200) {
287
- return proxiedRes;
288
- } else {
289
- logError(
290
- "FetchRemoteComponent",
291
- `Could not proxy remote: [response status ${proxiedRes.status}] ${await proxiedRes.text()}`
292
- );
293
- }
294
- }
295
- throw error;
296
- }
382
+ // src/shared/client/script-loader.ts
383
+ async function loadScripts(scripts, resolveClientUrl) {
384
+ await Promise.all(
385
+ scripts.map((script) => {
386
+ return new Promise((resolve, reject) => {
387
+ const newSrc = new URL(
388
+ // remove the remote component bundle name identifier from the script src
389
+ script.src.replace(NEXT_BUNDLE_PATH_RE, "/_next/"),
390
+ location.origin
391
+ ).href;
392
+ const resolvedSrc = resolveClientUrl?.(newSrc) ?? newSrc;
393
+ const newScript = document.createElement("script");
394
+ newScript.onload = () => resolve();
395
+ newScript.onerror = () => {
396
+ const isProxied = isProxiedUrl(resolvedSrc);
397
+ if (isProxied) {
398
+ reject(
399
+ new RemoteComponentsError(
400
+ `Failed to load script "${newSrc}" via proxy "${resolvedSrc}". Ensure withRemoteComponentsHost middleware is configured and "${RC_PROTECTED_REMOTE_FETCH_PATHNAME}" is in the matcher. See: ${CORS_DOCS_URL}`
401
+ )
402
+ );
403
+ } else {
404
+ warnCrossOriginFetchError("ScriptLoader", newSrc);
405
+ reject(
406
+ new RemoteComponentsError(
407
+ `Failed to load <script src="${newSrc}"> for Remote Component. Check the URL is correct.`
408
+ )
409
+ );
410
+ }
411
+ };
412
+ newScript.src = resolvedSrc;
413
+ newScript.async = true;
414
+ document.head.appendChild(newScript);
415
+ });
416
+ })
417
+ );
297
418
  }
298
- var RC_PROTECTED_REMOTE_FETCH_PATHNAME;
299
- var init_fetch_with_protected_rc_fallback = __esm({
300
- "src/shared/ssr/fetch-with-protected-rc-fallback.ts"() {
419
+ var init_script_loader = __esm({
420
+ "src/shared/client/script-loader.ts"() {
301
421
  "use strict";
302
- init_abort();
422
+ init_constants();
423
+ init_error();
303
424
  init_logger();
304
- RC_PROTECTED_REMOTE_FETCH_PATHNAME = "/rc-fetch-protected-remote";
425
+ init_protected_rc_fallback();
426
+ init_webpack_patterns();
305
427
  }
306
428
  });
307
429
 
@@ -331,7 +453,7 @@ var init_const = __esm({
331
453
  });
332
454
 
333
455
  // src/shared/client/turbopack-patterns.ts
334
- var REMOTE_SHARED_MARKER_RE, REMOTE_SHARED_ASSIGNMENT_RE, ASYNC_MODULE_LOADER_RE, ASYNC_MODULE_RESOLVE_RE, ASYNC_MODULE_ALL_RE, NUMERIC_MODULE_ID_RE, TURBOPACK_GLOBAL_RE;
456
+ var REMOTE_SHARED_MARKER_RE, REMOTE_SHARED_ASSIGNMENT_RE, ASYNC_MODULE_LOADER_RE, ASYNC_MODULE_RESOLVE_RE, ASYNC_MODULE_ALL_RE, TURBOPACK_GLOBAL_RE;
335
457
  var init_turbopack_patterns = __esm({
336
458
  "src/shared/client/turbopack-patterns.ts"() {
337
459
  "use strict";
@@ -340,13 +462,12 @@ var init_turbopack_patterns = __esm({
340
462
  ASYNC_MODULE_LOADER_RE = /(?:__turbopack_context__|e)\.A\((?<asyncSharedModuleId>[0-9]+)\)/;
341
463
  ASYNC_MODULE_RESOLVE_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<inner>parentImport|e)=>Promise\.resolve\(\)\.then\(\(\)=>\k<inner>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
342
464
  ASYNC_MODULE_ALL_RE = /(?<ctx>__turbopack_context__|e)=>\{\k<ctx>\.v\((?<vCb>parentImport|t)=>Promise\.all\(\["[^"]+"\]\.map\((?<mapCb>chunk|t)=>\k<ctx>\.l\(\k<mapCb>\)\)\)\.then\(\(\)=>\k<vCb>\((?<sharedModuleId>[0-9]+)\)\)\)\}/;
343
- NUMERIC_MODULE_ID_RE = /^[0-9]+$/;
344
465
  TURBOPACK_GLOBAL_RE = /(?:globalThis|self)\s*(?:\.TURBOPACK|\[\s*["']TURBOPACK["']\s*\])/;
345
466
  }
346
467
  });
347
468
 
348
469
  // src/shared/client/chunk-loader.ts
349
- function createChunkLoader(runtime) {
470
+ function createChunkLoader(runtime, resolveClientUrl) {
350
471
  return function __turbopack_chunk_load__(chunkId, scriptBundle) {
351
472
  logDebug("ChunkLoader", `Loading chunk: "${chunkId}"`);
352
473
  const self = globalThis;
@@ -386,9 +507,10 @@ function createChunkLoader(runtime) {
386
507
  logDebug("ChunkLoader", `Returning cached promise for: "${url}"`);
387
508
  return self.__remote_components_turbopack_chunk_loader_promise__[url];
388
509
  }
389
- logDebug("ChunkLoader", `Fetching chunk from: "${url}"`);
510
+ const resolvedUrl = resolveClientUrl?.(url) ?? url;
511
+ logDebug("ChunkLoader", `Fetching chunk from: "${resolvedUrl}"`);
390
512
  self.__remote_components_turbopack_chunk_loader_promise__[url] = new Promise((resolve, reject) => {
391
- fetchWithProtectedRcFallback(url).then((res) => res.text()).then((code) => {
513
+ fetch(resolvedUrl).then((res) => res.text()).then((code) => {
392
514
  const hasTurbopack = TURBOPACK_GLOBAL_RE.test(code);
393
515
  if (hasTurbopack) {
394
516
  return handleTurbopackChunk(code, bundle ?? "", url);
@@ -401,7 +523,19 @@ function createChunkLoader(runtime) {
401
523
  "ChunkLoader",
402
524
  `First 500 chars of chunk: ${code.slice(0, 500)}`
403
525
  );
404
- }).then(resolve).catch(reject);
526
+ }).then(resolve).catch((error) => {
527
+ const isProxied = isProxiedUrl(resolvedUrl);
528
+ if (isProxied) {
529
+ reject(
530
+ new RemoteComponentsError(
531
+ `Failed to load chunk "${url}" via proxy "${resolvedUrl}". Ensure withRemoteComponentsHost middleware is configured and "${RC_PROTECTED_REMOTE_FETCH_PATHNAME}" is in the matcher. See: ${CORS_DOCS_URL}`
532
+ )
533
+ );
534
+ } else {
535
+ warnCrossOriginFetchError("ChunkLoader", url);
536
+ reject(error);
537
+ }
538
+ });
405
539
  });
406
540
  return self.__remote_components_turbopack_chunk_loader_promise__[url];
407
541
  };
@@ -546,10 +680,11 @@ async function handleTurbopackChunk(code, bundle, url) {
546
680
  var init_chunk_loader = __esm({
547
681
  "src/shared/client/chunk-loader.ts"() {
548
682
  "use strict";
683
+ init_constants();
549
684
  init_error();
550
- init_fetch_with_protected_rc_fallback();
551
685
  init_logger();
552
686
  init_const();
687
+ init_protected_rc_fallback();
553
688
  init_turbopack_patterns();
554
689
  }
555
690
  });
@@ -558,10 +693,14 @@ var init_chunk_loader = __esm({
558
693
  function handleTurbopackModule(bundle, moduleId, id) {
559
694
  const self = globalThis;
560
695
  const bundleKey = getBundleKey(bundle);
561
- let modules = self[`TURBOPACK_${bundleKey}`];
562
- if (modules && typeof modules === "object" && "__chunks__" in modules) {
563
- const chunks = modules.__chunks__;
564
- modules = chunks.flat();
696
+ const raw = self[`TURBOPACK_${bundleKey}`];
697
+ let modules;
698
+ if (raw && typeof raw === "object" && "__chunks__" in raw) {
699
+ modules = raw.__chunks__.flat();
700
+ } else if (Array.isArray(raw)) {
701
+ modules = raw.flat();
702
+ } else {
703
+ modules = raw;
565
704
  }
566
705
  if (!self.__remote_components_turbopack_modules__) {
567
706
  self.__remote_components_turbopack_modules__ = {};
@@ -590,13 +729,12 @@ function handleTurbopackModule(bundle, moduleId, id) {
590
729
  if (!self.__remote_components_turbopack_global__[bundle]) {
591
730
  self.__remote_components_turbopack_global__[bundle] = {};
592
731
  }
593
- const allModules = Array.isArray(modules) ? modules.flat() : modules ? Object.values(modules) : [];
594
732
  moduleInit(
595
733
  createTurbopackContext(
596
734
  bundle,
597
735
  exports,
598
736
  moduleExports,
599
- allModules,
737
+ modules,
600
738
  moduleInit,
601
739
  id,
602
740
  self
@@ -610,46 +748,27 @@ function handleTurbopackModule(bundle, moduleId, id) {
610
748
  return moduleExports.exports;
611
749
  }
612
750
  function findModuleInit(modules, moduleId) {
613
- if (modules && !Array.isArray(modules) && typeof modules === "object") {
614
- const normalizedId = NUMERIC_MODULE_ID_RE.test(moduleId) ? Number(moduleId) : moduleId;
615
- if (normalizedId in modules) {
616
- return modules[normalizedId];
617
- }
618
- if (typeof normalizedId === "number" && String(normalizedId) in modules) {
619
- return modules[String(normalizedId)];
620
- }
621
- const matchingKey = Object.keys(modules).find(
622
- (key) => typeof key === "string" && key.includes(String(moduleId))
751
+ if (!modules || typeof modules !== "object")
752
+ return;
753
+ if (!Array.isArray(modules)) {
754
+ const key = moduleId in modules ? moduleId : Object.keys(modules).find((k) => k.startsWith(moduleId));
755
+ return key !== void 0 ? modules[key] : void 0;
756
+ }
757
+ const flat = modules.flat();
758
+ let idx = flat.findIndex((e) => String(e) === String(moduleId));
759
+ if (idx < 0) {
760
+ idx = flat.findIndex(
761
+ (e) => typeof e === "string" && e.startsWith(moduleId)
623
762
  );
624
- if (matchingKey) {
625
- return modules[matchingKey];
626
- }
627
- logError("TurbopackModule", `No match found for module ID: ${moduleId}`);
628
- return void 0;
629
763
  }
630
- const allModules = modules?.flat() ?? [];
631
- if (typeof allModules[1] === "string" || typeof allModules[1] === "number") {
632
- const normalizedId = NUMERIC_MODULE_ID_RE.test(moduleId) ? Number(moduleId) : moduleId;
633
- let moduleIdIndex = allModules.indexOf(normalizedId);
634
- if (moduleIdIndex === -1) {
635
- moduleIdIndex = allModules.findIndex(
636
- (bundleEntry) => typeof bundleEntry === "string" && bundleEntry.startsWith(moduleId) || bundleEntry === normalizedId
637
- );
638
- }
639
- if (moduleIdIndex !== -1) {
640
- while (typeof allModules[moduleIdIndex] !== "function" && moduleIdIndex < allModules.length) {
641
- moduleIdIndex++;
642
- }
643
- return allModules[moduleIdIndex];
644
- }
645
- } else {
646
- return allModules.find(
647
- (bundleEntry) => typeof bundleEntry === "object" && bundleEntry !== null && moduleId in bundleEntry
648
- )?.[moduleId];
764
+ if (idx >= 0) {
765
+ return flat.slice(idx + 1).find((e) => typeof e === "function");
649
766
  }
650
- return void 0;
767
+ return flat.find(
768
+ (e) => Boolean(e && typeof e === "object" && moduleId in e)
769
+ )?.[moduleId];
651
770
  }
652
- function createTurbopackContext(bundle, exports, moduleExports, allModules, moduleInit, id, self) {
771
+ function createTurbopackContext(bundle, exports, moduleExports, modules, moduleInit, id, self) {
653
772
  return {
654
773
  // HMR not implemented for Remote Components
655
774
  k: {
@@ -770,13 +889,17 @@ function createTurbopackContext(bundle, exports, moduleExports, allModules, modu
770
889
  (parentId) => self.__webpack_require__?.(`[${bundle}] ${parentId}`)
771
890
  );
772
891
  },
892
+ // dynamic import tracking — no-op for remote components
893
+ j() {
894
+ },
773
895
  // chunk loader
774
896
  l(url) {
775
- const moduleInitIndex = allModules.indexOf(moduleInit);
897
+ const flatModules = Array.isArray(modules) ? modules : [];
898
+ const moduleInitIndex = flatModules.indexOf(moduleInit);
776
899
  if (moduleInitIndex !== -1) {
777
- const scriptIndex = allModules.slice(0, moduleInitIndex).findLastIndex((bundleEntry) => bundleEntry instanceof Element);
900
+ const scriptIndex = flatModules.slice(0, moduleInitIndex).findLastIndex((bundleEntry) => bundleEntry instanceof Element);
778
901
  if (scriptIndex !== -1) {
779
- const script = allModules[scriptIndex];
902
+ const script = flatModules[scriptIndex];
780
903
  const scriptSrc = script.getAttribute("data-turbopack-src") || "";
781
904
  const nextIndex = scriptSrc.indexOf("/_next");
782
905
  const baseUrl = nextIndex !== -1 ? scriptSrc.slice(0, nextIndex) : "";
@@ -799,7 +922,6 @@ var init_turbopack_module = __esm({
799
922
  "use strict";
800
923
  init_logger();
801
924
  init_const();
802
- init_turbopack_patterns();
803
925
  }
804
926
  });
805
927
 
@@ -933,7 +1055,7 @@ var init_shared_modules2 = __esm({
933
1055
  });
934
1056
 
935
1057
  // src/shared/client/webpack-adapter.ts
936
- async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}) {
1058
+ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location.href), bundle, shared = {}, remoteShared = {}, resolveClientUrl) {
937
1059
  const self = globalThis;
938
1060
  if (!self.__remote_bundle_url__) {
939
1061
  self.__remote_bundle_url__ = {};
@@ -945,7 +1067,7 @@ async function setupWebpackRuntime(runtime, scripts = [], url = new URL(location
945
1067
  self.__original_webpack_chunk_load__ = self.__webpack_chunk_load__;
946
1068
  self.__original_webpack_require__ = self.__webpack_require__;
947
1069
  }
948
- self.__webpack_chunk_load__ = createChunkLoader(runtime);
1070
+ self.__webpack_chunk_load__ = createChunkLoader(runtime, resolveClientUrl);
949
1071
  self.__webpack_require__ = createModuleRequire(runtime);
950
1072
  self.__webpack_require_type__ = runtime;
951
1073
  if (self.__remote_webpack_require__ && runtime === RUNTIME_TURBOPACK) {
@@ -1039,7 +1161,81 @@ var init_webpack_adapter = __esm({
1039
1161
  });
1040
1162
 
1041
1163
  // src/shared/client/static-loader.ts
1042
- async function loadStaticRemoteComponent(scripts, url) {
1164
+ async function importViaCallback(absoluteSrc, resolveClientUrl) {
1165
+ const resolvedUrl = resolveClientUrl(absoluteSrc) ?? absoluteSrc;
1166
+ const fetchUrl = new URL(resolvedUrl, location.href).href;
1167
+ const response = await fetch(fetchUrl);
1168
+ if (!response.ok)
1169
+ throw new Error(`Proxied fetch failed: ${response.status}`);
1170
+ const content = (await response.text()).replace(/import\.meta\.url/g, JSON.stringify(absoluteSrc)).replace(
1171
+ /\b(from|import)\s*(["'])(\.\.?\/[^"']+)\2/g,
1172
+ (_, keyword, quote, relativePath) => {
1173
+ const absoluteImportUrl = new URL(relativePath, absoluteSrc).href;
1174
+ const resolvedImportUrl = new URL(
1175
+ resolveClientUrl(absoluteImportUrl) ?? absoluteImportUrl,
1176
+ location.href
1177
+ ).href;
1178
+ return `${keyword} ${quote}${resolvedImportUrl}${quote}`;
1179
+ }
1180
+ );
1181
+ const moduleBlobUrl = URL.createObjectURL(
1182
+ new Blob([content], { type: "text/javascript" })
1183
+ );
1184
+ const wrapperContent = [
1185
+ `import*as m from${JSON.stringify(moduleBlobUrl)};`,
1186
+ `globalThis.__rc_module_registry__=globalThis.__rc_module_registry__||{};`,
1187
+ `globalThis.__rc_module_registry__[${JSON.stringify(absoluteSrc)}]=m;`
1188
+ ].join("");
1189
+ const wrapperBlobUrl = URL.createObjectURL(
1190
+ new Blob([wrapperContent], { type: "text/javascript" })
1191
+ );
1192
+ const scriptEl = document.createElement("script");
1193
+ scriptEl.type = "module";
1194
+ scriptEl.src = wrapperBlobUrl;
1195
+ try {
1196
+ await new Promise((resolve, reject) => {
1197
+ scriptEl.onload = () => resolve();
1198
+ scriptEl.onerror = () => reject(new Error(`Failed to load module for ${absoluteSrc}`));
1199
+ document.head.appendChild(scriptEl);
1200
+ });
1201
+ } finally {
1202
+ scriptEl.remove();
1203
+ URL.revokeObjectURL(moduleBlobUrl);
1204
+ URL.revokeObjectURL(wrapperBlobUrl);
1205
+ }
1206
+ const registry = globalThis.__rc_module_registry__;
1207
+ const mod = registry?.[absoluteSrc] ?? {};
1208
+ if (registry)
1209
+ delete registry[absoluteSrc];
1210
+ return mod;
1211
+ }
1212
+ async function importDirectly(absoluteSrc) {
1213
+ try {
1214
+ return await import(
1215
+ /* @vite-ignore */
1216
+ /* webpackIgnore: true */
1217
+ absoluteSrc
1218
+ );
1219
+ } catch (importError) {
1220
+ if (!absoluteSrc.startsWith("blob:")) {
1221
+ warnCrossOriginFetchError("StaticLoader", absoluteSrc);
1222
+ }
1223
+ throw importError;
1224
+ }
1225
+ }
1226
+ function resolveScriptSrc(script, url) {
1227
+ const rawSrc = typeof script.getAttribute === "function" ? script.getAttribute("src") ?? script.src : script.src;
1228
+ if (!rawSrc && script.textContent) {
1229
+ return URL.createObjectURL(
1230
+ new Blob(
1231
+ [script.textContent.replace(/import\.meta\.url/g, JSON.stringify(url))],
1232
+ { type: "text/javascript" }
1233
+ )
1234
+ );
1235
+ }
1236
+ return rawSrc;
1237
+ }
1238
+ async function loadStaticRemoteComponent(scripts, url, resolveClientUrl) {
1043
1239
  const self = globalThis;
1044
1240
  if (self.__remote_script_entrypoint_mount__?.[url.href]) {
1045
1241
  self.__remote_script_entrypoint_mount__[url.href] = /* @__PURE__ */ new Set();
@@ -1050,26 +1246,9 @@ async function loadStaticRemoteComponent(scripts, url) {
1050
1246
  const mountUnmountSets = await Promise.all(
1051
1247
  scripts.map(async (script) => {
1052
1248
  try {
1053
- let src = typeof script.getAttribute === "function" ? script.getAttribute("src") ?? script.src : script.src;
1054
- if (!src && script.textContent) {
1055
- const blob = new Blob(
1056
- [
1057
- script.textContent.replace(
1058
- /import\.meta\.url/g,
1059
- JSON.stringify(url)
1060
- )
1061
- ],
1062
- {
1063
- type: "text/javascript"
1064
- }
1065
- );
1066
- src = URL.createObjectURL(blob);
1067
- }
1068
- const mod = await import(
1069
- /* @vite-ignore */
1070
- /* webpackIgnore: true */
1071
- new URL(src, url).href
1072
- );
1249
+ const src = resolveScriptSrc(script, url);
1250
+ const absoluteSrc = new URL(src, url).href;
1251
+ const mod = resolveClientUrl ? await importViaCallback(absoluteSrc, resolveClientUrl) : await importDirectly(absoluteSrc);
1073
1252
  if (src.startsWith("blob:")) {
1074
1253
  URL.revokeObjectURL(src);
1075
1254
  }
@@ -1345,7 +1524,7 @@ var webpack_exports = {};
1345
1524
  __export(webpack_exports, {
1346
1525
  webpackRuntime: () => webpackRuntime
1347
1526
  });
1348
- async function webpackRuntime(bundle, shared, remoteShared) {
1527
+ async function webpackRuntime(bundle, shared, remoteShared, resolveClientUrl) {
1349
1528
  const self = globalThis;
1350
1529
  if (!self.__DISABLE_WEBPACK_EXEC__) {
1351
1530
  self.__DISABLE_WEBPACK_EXEC__ = {};
@@ -1377,35 +1556,18 @@ async function webpackRuntime(bundle, shared, remoteShared) {
1377
1556
  default: { createFromReadableStream }
1378
1557
  } = await import("react-server-dom-webpack/client.browser");
1379
1558
  async function preloadScripts(scripts, url, remoteBundle, _) {
1380
- await Promise.all(
1381
- scripts.map((script) => {
1382
- return new Promise((resolve2, reject) => {
1383
- const newScript = document.createElement("script");
1384
- newScript.onload = () => {
1385
- resolve2();
1386
- newScript.remove();
1387
- };
1388
- newScript.onerror = () => {
1389
- reject(
1390
- new RemoteComponentsError(
1391
- `Failed to load <script src="${script.src}"> for Remote Component. Check the URL is correct.`
1392
- )
1393
- );
1394
- newScript.remove();
1395
- };
1396
- const scriptSrc = script.getAttribute("src") || script.getAttribute("data-src");
1397
- if (scriptSrc) {
1398
- newScript.src = new URL(
1399
- scriptSrc.replace(/\/_next\/\[(?:.+)\](?:%20| )/, "/_next/"),
1400
- url
1401
- ).href;
1402
- }
1403
- newScript.async = true;
1404
- document.body.appendChild(newScript);
1405
- script.parentElement?.removeChild(script);
1406
- });
1407
- })
1408
- );
1559
+ const scriptSrcs = scripts.flatMap((script) => {
1560
+ const scriptSrc = script.getAttribute("src") || script.getAttribute("data-src");
1561
+ script.parentElement?.removeChild(script);
1562
+ if (!scriptSrc)
1563
+ return [];
1564
+ return [
1565
+ {
1566
+ src: new URL(scriptSrc.replace(NEXT_BUNDLE_PATH_RE, "/_next/"), url).href
1567
+ }
1568
+ ];
1569
+ });
1570
+ await loadScripts(scriptSrcs, resolveClientUrl);
1409
1571
  const hostShared = {
1410
1572
  ...sharedPolyfills(shared),
1411
1573
  ...self.__remote_component_host_shared_modules__,
@@ -1449,6 +1611,8 @@ var init_webpack = __esm({
1449
1611
  "src/html/host/runtime/webpack.ts"() {
1450
1612
  "use strict";
1451
1613
  init_polyfill();
1614
+ init_script_loader();
1615
+ init_webpack_patterns();
1452
1616
  init_error();
1453
1617
  init_next_client_pages_loader();
1454
1618
  init_shared_modules();
@@ -1460,7 +1624,7 @@ var turbopack_exports = {};
1460
1624
  __export(turbopack_exports, {
1461
1625
  turbopackRuntime: () => turbopackRuntime
1462
1626
  });
1463
- async function turbopackRuntime(url, bundle, shared, remoteShared) {
1627
+ async function turbopackRuntime(url, bundle, shared, remoteShared, resolveClientUrl) {
1464
1628
  const self = globalThis;
1465
1629
  const hostShared = {
1466
1630
  ...sharedPolyfills(shared),
@@ -1474,7 +1638,8 @@ async function turbopackRuntime(url, bundle, shared, remoteShared) {
1474
1638
  url,
1475
1639
  bundle,
1476
1640
  hostShared,
1477
- remoteShared
1641
+ remoteShared,
1642
+ resolveClientUrl
1478
1643
  );
1479
1644
  const {
1480
1645
  default: { createFromReadableStream }
@@ -1488,7 +1653,8 @@ async function turbopackRuntime(url, bundle, shared, remoteShared) {
1488
1653
  url,
1489
1654
  bundle,
1490
1655
  hostShared,
1491
- remoteShared
1656
+ remoteShared,
1657
+ resolveClientUrl
1492
1658
  );
1493
1659
  }
1494
1660
  return {
@@ -1514,7 +1680,7 @@ var script_exports = {};
1514
1680
  __export(script_exports, {
1515
1681
  scriptRuntime: () => scriptRuntime
1516
1682
  });
1517
- function scriptRuntime() {
1683
+ function scriptRuntime(resolveClientUrl) {
1518
1684
  const self = globalThis;
1519
1685
  return {
1520
1686
  self,
@@ -1524,7 +1690,7 @@ function scriptRuntime() {
1524
1690
  Component: null,
1525
1691
  App: null
1526
1692
  }),
1527
- preloadScripts: loadStaticRemoteComponent
1693
+ preloadScripts: (scripts, url) => loadStaticRemoteComponent(scripts, url, resolveClientUrl)
1528
1694
  };
1529
1695
  }
1530
1696
  var init_script = __esm({
@@ -1550,7 +1716,7 @@ var tagNames = [
1550
1716
  "script",
1551
1717
  "link"
1552
1718
  ];
1553
- function applyOriginToNodes(doc, url) {
1719
+ function applyOriginToNodes(doc, url, resolveClientUrl) {
1554
1720
  if (url.origin !== location.origin) {
1555
1721
  const nodes = doc.querySelectorAll(
1556
1722
  tagNames.map(
@@ -1559,12 +1725,15 @@ function applyOriginToNodes(doc, url) {
1559
1725
  );
1560
1726
  nodes.forEach((node) => {
1561
1727
  if (node.hasAttribute("src") && /^[./]+\/?/.test(node.getAttribute("src") ?? "")) {
1562
- node.src = new URL(node.getAttribute("src") ?? "/", url).href;
1728
+ const absoluteSrc = new URL(node.getAttribute("src") ?? "/", url).href;
1729
+ const isScript = node.tagName.toLowerCase() === "script";
1730
+ node.src = isScript ? absoluteSrc : resolveClientUrl?.(absoluteSrc) ?? absoluteSrc;
1563
1731
  }
1564
1732
  if (node.hasAttribute("href") && /^[./]+\/?/.test(node.getAttribute("href") ?? "")) {
1733
+ const absoluteHref = new URL(node.getAttribute("href") ?? "/", url).href;
1565
1734
  node.setAttribute(
1566
1735
  "href",
1567
- new URL(node.getAttribute("href") ?? "/", url).href
1736
+ resolveClientUrl?.(absoluteHref) ?? absoluteHref
1568
1737
  );
1569
1738
  }
1570
1739
  if (node.hasAttribute("srcset")) {
@@ -1573,7 +1742,8 @@ function applyOriginToNodes(doc, url) {
1573
1742
  if (!urlPart)
1574
1743
  return entry;
1575
1744
  const absoluteUrl = new URL(urlPart, url).href;
1576
- return descriptor ? `${absoluteUrl} ${descriptor}` : absoluteUrl;
1745
+ const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
1746
+ return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
1577
1747
  }).join(", ");
1578
1748
  if (srcSet) {
1579
1749
  node.setAttribute("srcset", srcSet);
@@ -1585,7 +1755,8 @@ function applyOriginToNodes(doc, url) {
1585
1755
  if (!urlPart)
1586
1756
  return entry;
1587
1757
  const absoluteUrl = new URL(urlPart, url).href;
1588
- return descriptor ? `${absoluteUrl} ${descriptor}` : absoluteUrl;
1758
+ const resolvedUrl = resolveClientUrl?.(absoluteUrl) ?? absoluteUrl;
1759
+ return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl;
1589
1760
  }).join(", ");
1590
1761
  if (srcSet) {
1591
1762
  node.setAttribute("imagesrcset", srcSet);
@@ -1595,6 +1766,34 @@ function applyOriginToNodes(doc, url) {
1595
1766
  }
1596
1767
  }
1597
1768
 
1769
+ // src/shared/client/proxy-through-host.ts
1770
+ init_protected_rc_fallback();
1771
+ function withRemoteSrc(resolveClientUrl, remoteSrc) {
1772
+ return (url) => resolveClientUrl(remoteSrc, url);
1773
+ }
1774
+ var proxyClientRequestsThroughHost = (remoteSrc, url) => {
1775
+ if (typeof location === "undefined") {
1776
+ return void 0;
1777
+ }
1778
+ const remoteOrigin = new URL(remoteSrc, location.href).origin;
1779
+ if (remoteOrigin === location.origin) {
1780
+ return void 0;
1781
+ }
1782
+ try {
1783
+ const parsed = new URL(url, location.href);
1784
+ if (parsed.origin === remoteOrigin) {
1785
+ return generateProtectedRcFallbackSrc(url);
1786
+ }
1787
+ } catch {
1788
+ }
1789
+ return void 0;
1790
+ };
1791
+
1792
+ // src/shared/client/default-resolve-client-url.ts
1793
+ function bindResolveClientUrl(prop, remoteSrc) {
1794
+ return prop ? withRemoteSrc(prop, remoteSrc) : void 0;
1795
+ }
1796
+
1598
1797
  // src/shared/client/remote-component.ts
1599
1798
  init_error();
1600
1799
 
@@ -1675,20 +1874,22 @@ function createRSCStream(rscName, data) {
1675
1874
  });
1676
1875
  }
1677
1876
 
1678
- // src/shared/client/script-loader.ts
1679
- init_error();
1680
-
1681
1877
  // src/shared/client/component-loader.ts
1878
+ init_script_loader();
1682
1879
  init_webpack_adapter();
1683
1880
 
1684
1881
  // src/shared/client/remote-component.ts
1685
1882
  init_const();
1883
+ init_script_loader();
1686
1884
  init_static_loader();
1687
1885
  init_webpack_adapter();
1688
1886
 
1689
1887
  // src/html/host/index.tsx
1690
1888
  init_error();
1691
1889
 
1890
+ // src/shared/ssr/fetch-with-hooks.ts
1891
+ init_logger();
1892
+
1692
1893
  // src/shared/ssr/fetch-headers.ts
1693
1894
  function remoteFetchHeaders() {
1694
1895
  return {
@@ -1706,7 +1907,6 @@ function remoteFetchHeaders() {
1706
1907
  }
1707
1908
 
1708
1909
  // src/shared/ssr/fetch-with-hooks.ts
1709
- init_fetch_with_protected_rc_fallback();
1710
1910
  async function fetchWithHooks(url, additionalInit, options = {}) {
1711
1911
  const {
1712
1912
  onRequest,
@@ -1726,7 +1926,12 @@ async function fetchWithHooks(url, additionalInit, options = {}) {
1726
1926
  };
1727
1927
  let res = await onRequest?.(url, init, hookOptions);
1728
1928
  if (!res) {
1729
- res = await fetchWithProtectedRcFallback(url, init);
1929
+ try {
1930
+ res = await fetch(url, init);
1931
+ } catch (error) {
1932
+ warnCrossOriginFetchError("FetchRemoteComponent", url);
1933
+ throw error;
1934
+ }
1730
1935
  }
1731
1936
  const transformedRes = await onResponse?.(url, res, hookOptions);
1732
1937
  if (transformedRes) {
@@ -1749,7 +1954,8 @@ async function attachStyles({
1749
1954
  signal,
1750
1955
  baseUrl,
1751
1956
  remoteComponentSrc,
1752
- root
1957
+ root,
1958
+ resolveClientUrl
1753
1959
  }) {
1754
1960
  const appendedLinks = [];
1755
1961
  let abortReject = null;
@@ -1784,9 +1990,13 @@ async function attachStyles({
1784
1990
  });
1785
1991
  for (const attr of link.attributes) {
1786
1992
  if (attr.name === "href") {
1993
+ const absoluteHref = new URL(
1994
+ attr.value,
1995
+ baseUrl ?? location.origin
1996
+ ).href;
1787
1997
  newLink.setAttribute(
1788
1998
  attr.name,
1789
- new URL(attr.value, baseUrl ?? location.origin).href
1999
+ resolveClientUrl?.(absoluteHref) ?? absoluteHref
1790
2000
  );
1791
2001
  } else {
1792
2002
  newLink.setAttribute(attr.name, attr.value);
@@ -1820,7 +2030,7 @@ async function attachStyles({
1820
2030
 
1821
2031
  // src/html/host/runtime/index.ts
1822
2032
  init_error();
1823
- async function getRuntime(type, url, bundle, shared, remoteShared) {
2033
+ async function getRuntime(type, url, bundle, shared, remoteShared, resolveClientUrl) {
1824
2034
  if (typeof globalThis.process === "undefined") {
1825
2035
  globalThis.process = {
1826
2036
  env: {}
@@ -1828,13 +2038,24 @@ async function getRuntime(type, url, bundle, shared, remoteShared) {
1828
2038
  }
1829
2039
  if (type === "webpack") {
1830
2040
  const { webpackRuntime: webpackRuntime2 } = await Promise.resolve().then(() => (init_webpack(), webpack_exports));
1831
- return webpackRuntime2(bundle ?? "default", shared, remoteShared);
2041
+ return webpackRuntime2(
2042
+ bundle ?? "default",
2043
+ shared,
2044
+ remoteShared,
2045
+ resolveClientUrl
2046
+ );
1832
2047
  } else if (type === "turbopack") {
1833
2048
  const { turbopackRuntime: turbopackRuntime2 } = await Promise.resolve().then(() => (init_turbopack(), turbopack_exports));
1834
- return turbopackRuntime2(url, bundle, shared, remoteShared);
2049
+ return turbopackRuntime2(
2050
+ url,
2051
+ bundle,
2052
+ shared,
2053
+ remoteShared,
2054
+ resolveClientUrl
2055
+ );
1835
2056
  } else if (type === "script") {
1836
2057
  const { scriptRuntime: scriptRuntime2 } = await Promise.resolve().then(() => (init_script(), script_exports));
1837
- return scriptRuntime2();
2058
+ return scriptRuntime2(resolveClientUrl);
1838
2059
  }
1839
2060
  throw new RemoteComponentsError(
1840
2061
  `Remote Components runtime "${type}" is not supported. Supported runtimes are "webpack", "turbopack", and "script".`
@@ -1859,6 +2080,7 @@ if (typeof HTMLElement !== "undefined") {
1859
2080
  reactRoot;
1860
2081
  onRequest;
1861
2082
  onResponse;
2083
+ resolveClientUrl;
1862
2084
  /** Current AbortController for the loading operation - can be used to cancel loading via controller.abort() */
1863
2085
  abortController;
1864
2086
  static get observedAttributes() {
@@ -1872,7 +2094,6 @@ if (typeof HTMLElement !== "undefined") {
1872
2094
  if (this.getAttribute("src")) {
1873
2095
  this.load().catch((e) => {
1874
2096
  if (isAbortError(e)) {
1875
- this.isLoading = false;
1876
2097
  return;
1877
2098
  }
1878
2099
  logError("HtmlHost", "Error loading remote component.", e);
@@ -1898,7 +2119,6 @@ if (typeof HTMLElement !== "undefined") {
1898
2119
  this.root = newRoot;
1899
2120
  this.load().catch((e) => {
1900
2121
  if (isAbortError(e)) {
1901
- this.isLoading = false;
1902
2122
  return;
1903
2123
  }
1904
2124
  logError("HtmlHost", "Error reloading remote component.", e);
@@ -1921,7 +2141,14 @@ if (typeof HTMLElement !== "undefined") {
1921
2141
  });
1922
2142
  });
1923
2143
  if (this.isLoading) {
1924
- return;
2144
+ this.abortController?.abort();
2145
+ this.isLoading = false;
2146
+ if (this.root && !this.reactRoot) {
2147
+ this.root.innerHTML = "";
2148
+ this.fouc = null;
2149
+ this.fallbackSlot = document.createElement("slot");
2150
+ this.root.appendChild(this.fallbackSlot);
2151
+ }
1925
2152
  }
1926
2153
  if (!this.root) {
1927
2154
  this.root = this.attachShadow({
@@ -1932,28 +2159,16 @@ if (typeof HTMLElement !== "undefined") {
1932
2159
  }
1933
2160
  this.name = this.getAttribute("name") || "__vercel_remote_component";
1934
2161
  this.bundle = "default";
1935
- if (this.hasAttribute("src") || this.querySelector("div#__REMOTE_COMPONENT__") || this.hasAttribute("data-ssr")) {
1936
- this.load().catch((e) => {
1937
- if (isAbortError(e)) {
1938
- this.isLoading = false;
1939
- return;
1940
- }
1941
- logError("HtmlHost", "Error loading remote component.", e);
1942
- const errorEvent = new Event("error", {
1943
- bubbles: true,
1944
- composed: true
1945
- });
1946
- Object.assign(errorEvent, {
1947
- error: e,
1948
- src: this.getAttribute("src")
1949
- });
1950
- this.dispatchEvent(errorEvent);
1951
- });
1952
- }
1953
2162
  this.isLoading = true;
1954
2163
  const src = this.getAttribute("src");
1955
2164
  this.abortController = new AbortController();
1956
2165
  const signal = this.abortController.signal;
2166
+ const isCurrentLoad = () => !signal.aborted && this.getAttribute("src") === src;
2167
+ const abandonLoad = () => {
2168
+ if (this.abortController?.signal === signal && this.isLoading) {
2169
+ this.isLoading = false;
2170
+ }
2171
+ };
1957
2172
  const beforeLoadEvent = new Event("beforeload", {
1958
2173
  bubbles: true,
1959
2174
  composed: true
@@ -1972,46 +2187,42 @@ if (typeof HTMLElement !== "undefined") {
1972
2187
  this.name = url.hash.slice(1);
1973
2188
  }
1974
2189
  }
2190
+ const resolveClientUrl = url ? bindResolveClientUrl(this.resolveClientUrl, url.href) : void 0;
1975
2191
  if (!remoteComponentChild && url) {
1976
2192
  const fetchInit = {
1977
2193
  credentials: this.getAttribute("credentials") || "same-origin"
1978
2194
  };
1979
- const res = await fetchWithHooks(url, fetchInit, {
1980
- onRequest: this.onRequest,
1981
- onResponse: this.onResponse,
1982
- abortController: this.abortController
1983
- });
2195
+ const resolvedUrl = new URL(
2196
+ resolveClientUrl?.(url.href) ?? url.href,
2197
+ window.location.href
2198
+ );
2199
+ let res;
2200
+ try {
2201
+ res = await fetchWithHooks(resolvedUrl, fetchInit, {
2202
+ onRequest: this.onRequest,
2203
+ onResponse: this.onResponse,
2204
+ abortController: this.abortController
2205
+ });
2206
+ } catch (e) {
2207
+ if (isAbortError(e)) {
2208
+ return abandonLoad();
2209
+ }
2210
+ throw e;
2211
+ }
1984
2212
  if (!res || !res.ok) {
1985
- let error = failedToFetchRemoteComponentError(
1986
- url.href,
1987
- res ?? new Response(null, { status: 0 })
1988
- );
1989
- try {
1990
- const body = res ? await res.text() : "";
1991
- const parser2 = new DOMParser();
1992
- const doc2 = parser2.parseFromString(body, "text/html");
1993
- const errorTemplate = doc2.querySelector(
1994
- "template[data-next-error-message]"
1995
- );
1996
- const errorMessage = errorTemplate?.getAttribute(
1997
- "data-next-error-message"
1998
- );
1999
- const errorStack = errorTemplate?.getAttribute(
2000
- "data-next-error-stack"
2001
- );
2002
- if (errorMessage) {
2003
- error = new RemoteComponentsError(errorMessage);
2004
- if (errorStack) {
2005
- error.stack = errorStack;
2006
- }
2007
- }
2008
- } catch (parseError) {
2009
- if (isAbortError(parseError))
2010
- throw parseError;
2213
+ throw await errorFromFailedFetch(url.href, resolvedUrl, res);
2214
+ }
2215
+ try {
2216
+ html = await res.text();
2217
+ } catch (e) {
2218
+ if (isAbortError(e)) {
2219
+ return abandonLoad();
2011
2220
  }
2012
- throw error;
2221
+ throw e;
2222
+ }
2223
+ if (!isCurrentLoad()) {
2224
+ return abandonLoad();
2013
2225
  }
2014
- html = await res.text();
2015
2226
  }
2016
2227
  const parser = new DOMParser();
2017
2228
  const doc = parser.parseFromString(html, "text/html");
@@ -2094,6 +2305,9 @@ if (typeof HTMLElement !== "undefined") {
2094
2305
  }
2095
2306
  })
2096
2307
  );
2308
+ if (!isCurrentLoad()) {
2309
+ return abandonLoad();
2310
+ }
2097
2311
  }
2098
2312
  }
2099
2313
  this.root.innerHTML = "";
@@ -2111,7 +2325,7 @@ if (typeof HTMLElement !== "undefined") {
2111
2325
  });
2112
2326
  this.dispatchEvent(changeEvent);
2113
2327
  }
2114
- this.prevUrl = url ?? new URL(location.href);
2328
+ this.prevUrl = url ?? new URL(window.location.href);
2115
2329
  this.prevIsRemoteComponent = isRemoteComponent;
2116
2330
  this.prevSrc = src;
2117
2331
  this.prevName = this.name;
@@ -2126,7 +2340,8 @@ if (typeof HTMLElement !== "undefined") {
2126
2340
  // Effects run after load, no abort needed
2127
2341
  baseUrl: url?.href,
2128
2342
  remoteComponentSrc,
2129
- root: this.root ?? null
2343
+ root: this.root ?? null,
2344
+ resolveClientUrl
2130
2345
  });
2131
2346
  if (!this.reactRoot) {
2132
2347
  await attachStyles({
@@ -2136,19 +2351,31 @@ if (typeof HTMLElement !== "undefined") {
2136
2351
  signal,
2137
2352
  baseUrl: url?.href,
2138
2353
  remoteComponentSrc,
2139
- root: this.root
2354
+ root: this.root,
2355
+ resolveClientUrl
2140
2356
  });
2357
+ if (!isCurrentLoad()) {
2358
+ return abandonLoad();
2359
+ }
2141
2360
  }
2142
- applyOriginToNodes(doc, url ?? new URL(location.href));
2361
+ applyOriginToNodes(
2362
+ doc,
2363
+ url ?? new URL(window.location.href),
2364
+ resolveClientUrl
2365
+ );
2143
2366
  if (!this.reactRoot) {
2144
2367
  Array.from(component.children).forEach((el) => {
2145
2368
  if (!isRemoteComponent && el.tagName.toLowerCase() === "script") {
2146
2369
  const newScript = document.createElement("script");
2147
2370
  for (const attr of el.attributes) {
2148
2371
  if (attr.name === "src") {
2372
+ const absoluteSrc = new URL(
2373
+ attr.value,
2374
+ url ?? window.location.origin
2375
+ ).href;
2149
2376
  newScript.setAttribute(
2150
2377
  attr.name,
2151
- new URL(attr.value, url ?? location.origin).href
2378
+ resolveClientUrl?.(absoluteSrc) ?? absoluteSrc
2152
2379
  );
2153
2380
  } else {
2154
2381
  newScript.setAttribute(attr.name, attr.value);
@@ -2210,7 +2437,7 @@ if (typeof HTMLElement !== "undefined") {
2210
2437
  preloadScripts
2211
2438
  } = await getRuntime(
2212
2439
  metadataObj.runtime,
2213
- url ?? new URL(location.href),
2440
+ url ?? new URL(window.location.href),
2214
2441
  this.bundle,
2215
2442
  {
2216
2443
  react: async () => (await import("react")).default,
@@ -2219,8 +2446,12 @@ if (typeof HTMLElement !== "undefined") {
2219
2446
  "react-dom": async () => (await import("react-dom")).default,
2220
2447
  "react-dom/client": async () => (await import("react-dom/client")).default
2221
2448
  },
2222
- remoteShared
2449
+ remoteShared,
2450
+ resolveClientUrl
2223
2451
  );
2452
+ if (!isCurrentLoad()) {
2453
+ return abandonLoad();
2454
+ }
2224
2455
  const scripts = isRemoteComponent ? component.querySelectorAll("script") : doc.querySelectorAll(
2225
2456
  "script[src],script[data-src],script[data-remote-component-entrypoint]"
2226
2457
  );
@@ -2236,6 +2467,9 @@ if (typeof HTMLElement !== "undefined") {
2236
2467
  this.bundle ?? "default",
2237
2468
  this.name ?? "__vercel_remote_component"
2238
2469
  );
2470
+ if (!isCurrentLoad()) {
2471
+ return abandonLoad();
2472
+ }
2239
2473
  if (isRemoteComponent) {
2240
2474
  Array.from(component.children).forEach((child) => {
2241
2475
  if (child.tagName === "SCRIPT") {
@@ -2296,7 +2530,9 @@ if (typeof HTMLElement !== "undefined") {
2296
2530
  logError("HtmlHost", "Error attaching styles.", e);
2297
2531
  });
2298
2532
  }
2299
- this.isLoading = false;
2533
+ if (isCurrentLoad()) {
2534
+ this.isLoading = false;
2535
+ }
2300
2536
  const loadEvent = new Event("load", {
2301
2537
  bubbles: true,
2302
2538
  composed: true
@@ -2349,7 +2585,9 @@ if (typeof HTMLElement !== "undefined") {
2349
2585
  logError("HtmlHost", "Error attaching styles.", e);
2350
2586
  });
2351
2587
  }
2352
- remoteComponent.isLoading = false;
2588
+ if (isCurrentLoad()) {
2589
+ remoteComponent.isLoading = false;
2590
+ }
2353
2591
  const loadEvent = new Event("load", {
2354
2592
  bubbles: true,
2355
2593
  composed: true
@@ -2366,7 +2604,9 @@ if (typeof HTMLElement !== "undefined") {
2366
2604
  startTransition(() => {
2367
2605
  root.render(/* @__PURE__ */ jsx2(RemoteComponentFromNext, { initial: false }));
2368
2606
  doCleanup();
2369
- this.isLoading = false;
2607
+ if (isCurrentLoad()) {
2608
+ this.isLoading = false;
2609
+ }
2370
2610
  });
2371
2611
  return;
2372
2612
  }
@@ -2410,7 +2650,9 @@ if (typeof HTMLElement !== "undefined") {
2410
2650
  Object.assign(loadEvent, { src: this.getAttribute("src") });
2411
2651
  this.dispatchEvent(loadEvent);
2412
2652
  }
2413
- this.isLoading = false;
2653
+ if (isCurrentLoad()) {
2654
+ this.isLoading = false;
2655
+ }
2414
2656
  }
2415
2657
  }
2416
2658
  customElements.define("remote-component", RemoteComponent);
@@ -2427,6 +2669,7 @@ function registerSharedModules(modules = {}) {
2427
2669
  });
2428
2670
  }
2429
2671
  export {
2672
+ proxyClientRequestsThroughHost,
2430
2673
  registerSharedModules
2431
2674
  };
2432
2675
  //# sourceMappingURL=host.js.map