remote-components 0.3.7 → 0.4.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 (85) hide show
  1. package/dist/{chunk-LCXO7BUY.cjs → chunk-42TVDI3G.cjs} +5 -4
  2. package/dist/chunk-42TVDI3G.cjs.map +1 -0
  3. package/dist/chunk-5KTAEO52.cjs +28 -0
  4. package/dist/chunk-5KTAEO52.cjs.map +1 -0
  5. package/dist/{chunk-NZAB7REE.js → chunk-5WL3FP4V.js} +5 -5
  6. package/dist/{chunk-SZFCBE54.js → chunk-AKOMV2UF.js} +4 -3
  7. package/dist/chunk-AKOMV2UF.js.map +1 -0
  8. package/dist/{chunk-I47KE3EC.cjs → chunk-AYC2AWUG.cjs} +21 -21
  9. package/dist/{chunk-RJW3EZJP.cjs → chunk-EYALF655.cjs} +23 -23
  10. package/dist/{chunk-T64P7BAG.cjs → chunk-JJTCFQHE.cjs} +3 -3
  11. package/dist/{chunk-52BJ7VFA.js → chunk-MKO52FRO.js} +2 -2
  12. package/dist/{chunk-QKB74MLO.js → chunk-N3KPUFOB.js} +2 -2
  13. package/dist/chunk-N3SQTOSE.cjs +25 -0
  14. package/dist/chunk-N3SQTOSE.cjs.map +1 -0
  15. package/dist/{chunk-GBFUPMMI.js → chunk-NN5V3FVD.js} +25 -13
  16. package/dist/chunk-NN5V3FVD.js.map +1 -0
  17. package/dist/chunk-RHGEBXPL.js +25 -0
  18. package/dist/chunk-RHGEBXPL.js.map +1 -0
  19. package/dist/{chunk-X6W464D6.cjs → chunk-RLI4YTBJ.cjs} +17 -1
  20. package/dist/chunk-RLI4YTBJ.cjs.map +1 -0
  21. package/dist/{chunk-SJM7AAGU.js → chunk-SAGYPGIQ.js} +17 -1
  22. package/dist/chunk-SAGYPGIQ.js.map +1 -0
  23. package/dist/chunk-STIJO4AG.js +28 -0
  24. package/dist/chunk-STIJO4AG.js.map +1 -0
  25. package/dist/{chunk-AWWWK2ZY.cjs → chunk-Y4GMYUJT.cjs} +32 -20
  26. package/dist/chunk-Y4GMYUJT.cjs.map +1 -0
  27. package/dist/config/nextjs.cjs +6 -5
  28. package/dist/config/nextjs.cjs.map +1 -1
  29. package/dist/config/nextjs.js +3 -2
  30. package/dist/config/nextjs.js.map +1 -1
  31. package/dist/host/html.cjs +21 -20
  32. package/dist/host/html.cjs.map +1 -1
  33. package/dist/host/html.js +9 -8
  34. package/dist/host/html.js.map +1 -1
  35. package/dist/host/navigation.cjs +8 -0
  36. package/dist/host/navigation.cjs.map +1 -0
  37. package/dist/host/navigation.d.ts +30 -0
  38. package/dist/host/navigation.js +8 -0
  39. package/dist/host/navigation.js.map +1 -0
  40. package/dist/host/nextjs/app/client-only.cjs +14 -12
  41. package/dist/host/nextjs/app/client-only.cjs.map +1 -1
  42. package/dist/host/nextjs/app/client-only.d.ts +2 -1
  43. package/dist/host/nextjs/app/client-only.js +9 -7
  44. package/dist/host/nextjs/app/client-only.js.map +1 -1
  45. package/dist/host/react.cjs +12 -8
  46. package/dist/host/react.d.ts +2 -1
  47. package/dist/host/react.js +13 -9
  48. package/dist/{index-4c65355c.d.ts → index-d2ce8a3f.d.ts} +22 -2
  49. package/dist/internal/host/shared/navigate-event.cjs +51 -0
  50. package/dist/internal/host/shared/navigate-event.cjs.map +1 -0
  51. package/dist/internal/host/shared/navigate-event.d.ts +21 -0
  52. package/dist/internal/host/shared/navigate-event.js +26 -0
  53. package/dist/internal/host/shared/navigate-event.js.map +1 -0
  54. package/dist/internal/host/shared/polyfill.cjs +14 -0
  55. package/dist/internal/host/shared/polyfill.cjs.map +1 -1
  56. package/dist/internal/host/shared/polyfill.js +16 -0
  57. package/dist/internal/host/shared/polyfill.js.map +1 -1
  58. package/dist/internal/runtime/loaders/script-loader.cjs +2 -1
  59. package/dist/internal/runtime/loaders/script-loader.cjs.map +1 -1
  60. package/dist/internal/runtime/loaders/script-loader.js +2 -1
  61. package/dist/internal/runtime/loaders/script-loader.js.map +1 -1
  62. package/dist/navigate-event-baee0b63.d.ts +14 -0
  63. package/dist/{turbopack-5LW6V6IT.js → turbopack-DK6L7P3J.js} +5 -4
  64. package/dist/{turbopack-5LW6V6IT.js.map → turbopack-DK6L7P3J.js.map} +1 -1
  65. package/dist/{turbopack-KRKECGY2.cjs → turbopack-PSD4THQE.cjs} +12 -11
  66. package/dist/turbopack-PSD4THQE.cjs.map +1 -0
  67. package/dist/{webpack-NPZNXRNL.js → webpack-KSDNIXMS.js} +5 -4
  68. package/dist/{webpack-NPZNXRNL.js.map → webpack-KSDNIXMS.js.map} +1 -1
  69. package/dist/{webpack-TTZDARNY.cjs → webpack-SIFRCBIN.cjs} +12 -11
  70. package/dist/webpack-SIFRCBIN.cjs.map +1 -0
  71. package/package.json +9 -1
  72. package/dist/chunk-AWWWK2ZY.cjs.map +0 -1
  73. package/dist/chunk-GBFUPMMI.js.map +0 -1
  74. package/dist/chunk-LCXO7BUY.cjs.map +0 -1
  75. package/dist/chunk-SJM7AAGU.js.map +0 -1
  76. package/dist/chunk-SZFCBE54.js.map +0 -1
  77. package/dist/chunk-X6W464D6.cjs.map +0 -1
  78. package/dist/turbopack-KRKECGY2.cjs.map +0 -1
  79. package/dist/webpack-TTZDARNY.cjs.map +0 -1
  80. /package/dist/{chunk-NZAB7REE.js.map → chunk-5WL3FP4V.js.map} +0 -0
  81. /package/dist/{chunk-I47KE3EC.cjs.map → chunk-AYC2AWUG.cjs.map} +0 -0
  82. /package/dist/{chunk-RJW3EZJP.cjs.map → chunk-EYALF655.cjs.map} +0 -0
  83. /package/dist/{chunk-T64P7BAG.cjs.map → chunk-JJTCFQHE.cjs.map} +0 -0
  84. /package/dist/{chunk-52BJ7VFA.js.map → chunk-MKO52FRO.js.map} +0 -0
  85. /package/dist/{chunk-QKB74MLO.js.map → chunk-N3KPUFOB.js.map} +0 -0
@@ -7,18 +7,21 @@
7
7
 
8
8
 
9
9
 
10
- var _chunkI47KE3ECcjs = require('./chunk-I47KE3EC.cjs');
10
+ var _chunkAYC2AWUGcjs = require('./chunk-AYC2AWUG.cjs');
11
11
 
12
12
 
13
13
  var _chunkTZT7DLO5cjs = require('./chunk-TZT7DLO5.cjs');
14
14
 
15
15
 
16
+ var _chunkN3SQTOSEcjs = require('./chunk-N3SQTOSE.cjs');
16
17
 
17
18
 
18
19
 
19
20
 
20
21
 
21
- var _chunkX6W464D6cjs = require('./chunk-X6W464D6.cjs');
22
+
23
+
24
+ var _chunkRLI4YTBJcjs = require('./chunk-RLI4YTBJ.cjs');
22
25
 
23
26
 
24
27
  var _chunkZ2SLBFQLcjs = require('./chunk-Z2SLBFQL.cjs');
@@ -89,7 +92,7 @@ function setAttributesFromProps(el, props) {
89
92
  function useResolveClientUrl(prop, urlHref) {
90
93
  const { resolveClientUrl: contextValue } = _context.useRemoteComponentsContext.call(void 0, );
91
94
  const raw = _nullishCoalesce(prop, () => ( contextValue));
92
- return _react.useMemo.call(void 0, () => _chunkI47KE3ECcjs.bindResolveClientUrl.call(void 0, raw, urlHref), [raw, urlHref]);
95
+ return _react.useMemo.call(void 0, () => _chunkAYC2AWUGcjs.bindResolveClientUrl.call(void 0, raw, urlHref), [raw, urlHref]);
93
96
  }
94
97
 
95
98
  // src/host/react/hooks/use-shadow-root.ts
@@ -151,7 +154,7 @@ function getRemoteComponentHtml(html) {
151
154
  return ssrRemoteComponentContainer.innerHTML;
152
155
  }
153
156
  const remoteComponentContainer = temp.querySelectorAll(
154
- `div[data-bundle][data-route][data-runtime][id^="${_chunkX6W464D6cjs.DEFAULT_COMPONENT_NAME}"],div[data-bundle][data-route],div#__next,remote-component:not([src])`
157
+ `div[data-bundle][data-route][data-runtime][id^="${_chunkRLI4YTBJcjs.DEFAULT_COMPONENT_NAME}"],div[data-bundle][data-route],div#__next,remote-component:not([src])`
155
158
  );
156
159
  if (remoteComponentContainer.length > 0) {
157
160
  return `${Array.from(temp.querySelectorAll("link,script")).map((link) => link.outerHTML).join("")}${Array.from(remoteComponentContainer).map((container) => container.outerHTML).join("")}`;
@@ -159,6 +162,14 @@ function getRemoteComponentHtml(html) {
159
162
  return "";
160
163
  }
161
164
 
165
+ // src/host/react/hooks/use-remote-navigate.ts
166
+
167
+ function useRemoteNavigate(callback) {
168
+ const callbackRef = _react.useRef.call(void 0, callback);
169
+ callbackRef.current = callback;
170
+ _react.useEffect.call(void 0, () => _chunkN3SQTOSEcjs.onRemoteNavigate.call(void 0, (event) => callbackRef.current(event)), []);
171
+ }
172
+
162
173
  // src/host/react/index.tsx
163
174
  var _jsxruntime = require('react/jsx-runtime');
164
175
 
@@ -168,7 +179,7 @@ function ConsumeRemoteComponent({
168
179
  mode = "open",
169
180
  reset,
170
181
  credentials: credentialsProp,
171
- name: nameProp = _chunkX6W464D6cjs.DEFAULT_COMPONENT_NAME,
182
+ name: nameProp = _chunkRLI4YTBJcjs.DEFAULT_COMPONENT_NAME,
172
183
  shared: sharedProp,
173
184
  children,
174
185
  onBeforeLoad,
@@ -184,22 +195,22 @@ function ConsumeRemoteComponent({
184
195
  const credentials = _nullishCoalesce(_nullishCoalesce(credentialsProp, () => ( contextCredentials)), () => ( "same-origin"));
185
196
  const shared = _nullishCoalesce(_nullishCoalesce(sharedProp, () => ( contextShared)), () => ( {}));
186
197
  const emitter = _react.useMemo.call(void 0,
187
- () => _chunkI47KE3ECcjs.makeReactEmitter.call(void 0, { onBeforeLoad, onLoad, onError, onChange }),
198
+ () => _chunkAYC2AWUGcjs.makeReactEmitter.call(void 0, { onBeforeLoad, onLoad, onError, onChange }),
188
199
  [onBeforeLoad, onLoad, onError, onChange]
189
200
  );
190
201
  const name = _react.useMemo.call(void 0,
191
- () => _chunkI47KE3ECcjs.resolveNameFromSrc.call(void 0, src, nameProp),
202
+ () => _chunkAYC2AWUGcjs.resolveNameFromSrc.call(void 0, src, nameProp),
192
203
  [src, nameProp]
193
204
  );
194
205
  const [data, setData] = _react.useState.call(void 0,
195
206
  null
196
207
  );
197
- const url = _react.useMemo.call(void 0, () => _chunkI47KE3ECcjs.getClientOrServerUrl.call(void 0, src, DUMMY_FALLBACK), [src]);
208
+ const url = _react.useMemo.call(void 0, () => _chunkAYC2AWUGcjs.getClientOrServerUrl.call(void 0, src, DUMMY_FALLBACK), [src]);
198
209
  const resolveClientUrl = useResolveClientUrl(resolveClientUrlProp, url.href);
199
210
  const id = url.origin === (typeof location !== "undefined" ? location.origin : DUMMY_FALLBACK) ? url.pathname : url.href;
200
- const keySuffix = `${_chunkX6W464D6cjs.escapeString.call(void 0, id)}_${_chunkX6W464D6cjs.escapeString.call(void 0,
211
+ const keySuffix = `${_chunkRLI4YTBJcjs.escapeString.call(void 0, id)}_${_chunkRLI4YTBJcjs.escapeString.call(void 0,
201
212
  _nullishCoalesce(_optionalChain([data, 'optionalAccess', _5 => _5.name]), () => ( name))
202
- )}_${_chunkX6W464D6cjs.escapeString.call(void 0, instanceId)}`;
213
+ )}_${_chunkRLI4YTBJcjs.escapeString.call(void 0, instanceId)}`;
203
214
  const [remoteComponent, setRemoteComponent] = _react.useState.call(void 0, null);
204
215
  const { shadowRoot, shadowRootContainerRef } = useShadowRoot({
205
216
  isolate,
@@ -225,7 +236,7 @@ function ConsumeRemoteComponent({
225
236
  return elements;
226
237
  })() : []
227
238
  );
228
- const hostStateRef = _react.useRef.call(void 0, _chunkI47KE3ECcjs.createHostState.call(void 0, ));
239
+ const hostStateRef = _react.useRef.call(void 0, _chunkAYC2AWUGcjs.createHostState.call(void 0, ));
229
240
  const componentHydrationHtml = _react.useRef.call(void 0, null);
230
241
  const prevRemoteComponentContainerRef = _react.useRef.call(void 0, null);
231
242
  const unmountRef = _react.useRef.call(void 0, null);
@@ -291,7 +302,7 @@ function ConsumeRemoteComponent({
291
302
  _nullishCoalesce(_optionalChain([resolveClientUrl, 'optionalCall', _29 => _29(url.href)]), () => ( url.href)),
292
303
  location.href
293
304
  );
294
- const res = await _chunkI47KE3ECcjs.fetchWithHooks.call(void 0, resolvedUrl, fetchInit, {
305
+ const res = await _chunkAYC2AWUGcjs.fetchWithHooks.call(void 0, resolvedUrl, fetchInit, {
295
306
  onRequest,
296
307
  onResponse,
297
308
  abortController: hostStateRef.current.abortController
@@ -310,7 +321,7 @@ function ConsumeRemoteComponent({
310
321
  const userShared = await shared;
311
322
  if (signal.aborted)
312
323
  return;
313
- const prepared = _chunkI47KE3ECcjs.preparePipeline.call(void 0, {
324
+ const prepared = _chunkAYC2AWUGcjs.preparePipeline.call(void 0, {
314
325
  html,
315
326
  name,
316
327
  url,
@@ -351,7 +362,7 @@ function ConsumeRemoteComponent({
351
362
  href: new URL(_nullishCoalesce(link.getAttribute("href"), () => ( link.href)), url).href,
352
363
  ...link.getAttributeNames().reduce((acc, key) => {
353
364
  if (key !== "href") {
354
- acc[_nullishCoalesce(_chunkX6W464D6cjs.attrToProp[key], () => ( key))] = _nullishCoalesce(link.getAttribute(key), () => ( ""));
365
+ acc[_nullishCoalesce(_chunkRLI4YTBJcjs.attrToProp[key], () => ( key))] = _nullishCoalesce(link.getAttribute(key), () => ( ""));
355
366
  }
356
367
  return acc;
357
368
  }, {})
@@ -413,7 +424,7 @@ function ConsumeRemoteComponent({
413
424
  });
414
425
  self.__next_s = prevNextScripts;
415
426
  }
416
- const rscName = rsc ? `__remote_component_rsc_${_chunkX6W464D6cjs.escapeString.call(void 0, id)}_${_chunkX6W464D6cjs.escapeString.call(void 0,
427
+ const rscName = rsc ? `__remote_component_rsc_${_chunkRLI4YTBJcjs.escapeString.call(void 0, id)}_${_chunkRLI4YTBJcjs.escapeString.call(void 0,
417
428
  remoteName
418
429
  )}` : void 0;
419
430
  if (rsc) {
@@ -486,7 +497,7 @@ function ConsumeRemoteComponent({
486
497
  }
487
498
  hostStateRef.current.stage = "loaded";
488
499
  } else {
489
- const result = await _chunkI47KE3ECcjs.loadPrepared.call(void 0, {
500
+ const result = await _chunkAYC2AWUGcjs.loadPrepared.call(void 0, {
490
501
  prepared,
491
502
  url,
492
503
  signal,
@@ -555,8 +566,8 @@ function ConsumeRemoteComponent({
555
566
  const metadataJson = /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "script", { "data-remote-component": true, type: "application/json", children: JSON.stringify({
556
567
  name: _optionalChain([data, 'optionalAccess', _33 => _33.name]) || name,
557
568
  bundle: _optionalChain([data, 'optionalAccess', _34 => _34.bundle]) || "default",
558
- route: _optionalChain([data, 'optionalAccess', _35 => _35.route]) || _chunkX6W464D6cjs.DEFAULT_ROUTE,
559
- runtime: hostStateRef.current.prevIsRemoteComponent ? _chunkX6W464D6cjs.RUNTIME_SCRIPT : _optionalChain([data, 'optionalAccess', _36 => _36.runtime]) || _chunkX6W464D6cjs.RUNTIME_WEBPACK
569
+ route: _optionalChain([data, 'optionalAccess', _35 => _35.route]) || _chunkRLI4YTBJcjs.DEFAULT_ROUTE,
570
+ runtime: hostStateRef.current.prevIsRemoteComponent ? _chunkRLI4YTBJcjs.RUNTIME_SCRIPT : _optionalChain([data, 'optionalAccess', _36 => _36.runtime]) || _chunkRLI4YTBJcjs.RUNTIME_WEBPACK
560
571
  }) });
561
572
  const resetStyle = reset ? /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "style", { "data-remote-components-reset": "react", children: `:host { all: initial; }` }) : null;
562
573
  const linksToRender = _optionalChain([data, 'optionalAccess', _37 => _37.links, 'optionalAccess', _38 => _38.map, 'call', _39 => _39((link) => /* @__PURE__ */ _react.createElement.call(void 0,
@@ -666,5 +677,6 @@ function ConsumeRemoteComponent({
666
677
 
667
678
 
668
679
 
669
- exports.ConsumeRemoteComponent = ConsumeRemoteComponent;
670
- //# sourceMappingURL=chunk-AWWWK2ZY.cjs.map
680
+
681
+ exports.useRemoteNavigate = useRemoteNavigate; exports.ConsumeRemoteComponent = ConsumeRemoteComponent;
682
+ //# sourceMappingURL=chunk-Y4GMYUJT.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/host/react/index.tsx","../src/runtime/html/set-attributes-from-props.ts","../src/host/react/hooks/use-resolve-client-url.ts","../src/host/react/hooks/use-shadow-root.ts","../src/host/react/utils/extract-remote-html.ts","../src/host/react/hooks/use-remote-navigate.ts"],"names":["useEffect","useLayoutEffect","useMemo","useRef","useState","useRemoteComponentsContext"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA,aAAAA;AAAA,EACA;AAAA,EACA,mBAAAC;AAAA,EACA,WAAAC;AAAA,EACA,UAAAC;AAAA,EACA,YAAAC;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,8BAAAC,mCAAkC;;;ACR3C,IAAM,oBAA4C;AAAA,EAChD,eAAe;AAAA,EACf,WAAW;AAAA,EACX,SAAS;AAAA,EACT,WAAW;AAAA,EACX,UAAU;AACZ;AAEA,IAAM,cAAc;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,yBACP,MACwC;AACxC,SAAO,CAAC,SAAS,SAAS,UAAU,EAAE,SAAS,IAAI;AACrD;AAEO,SAAS,uBAAuB,IAAiB,OAAe;AACrE,aAAW,CAAC,GAAG,KAAK,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC9C,QAAI,CAAC,OAAO,OAAO,OAAO,CAAC;AAAG;AAC9B,QAAI,YAAY,SAAS,CAAC;AAAG;AAG7B,QAAI,UAAU,QAAW;AACvB;AAAA,IACF;AAEA,UAAM,OAAO,kBAAkB,CAAC,KAAK,EAAE,YAAY;AAEnD,QAAI,GAAG,YAAY,YAAY,yBAAyB,IAAI,GAAG;AAG7D,MAAC,GAAyB,IAAI,IAAI,QAAQ,KAAK;AAAA,IACjD,OAAO;AACL,SAAG,aAAa,MAAM,OAAO,KAAK,CAAC;AAAA,IACrC;AAIA,QACE,UAAU,SACT,GAAG,YAAY,YACd,yBAAyB,IAAI,MAC5B,CAAC,SAAS,UAAU,UACvB;AAGA,SAAG,aAAa,MAAM,EAAE;AACxB,SAAG,gBAAgB,IAAI;AAAA,IACzB;AAAA,EACF;AACF;;;AC5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AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oDAOwB;AAAA;AAAA;AAAA;AAAA,oBAIlC;AAAA;AAAA,gBACF,IACE;AAAA,gBACH;AAAA,gBACA;AAAA,gBACA;AAAA,iBACH;AAAA,gBACE;AAAA,YACH,cAAc,kBACX;AAAA,cACE,iCACE;AAAA,oCAAC,cAAS,IAAI,GAAG,cAAc;AAAA,gBAC9B;AAAA,gBACA;AAAA,gBACA;AAAA,gBACD,oBAAC,cAAS,IAAI,GAAG,YAAY,KAAK,gBAAgB;AAAA,iBACpD;AAAA,cACA;AAAA,YACF,IACA;AAAA;AAAA;AAAA,MACN;AAAA,OACF;AAAA,EAEJ;AACA,UAAQ,UAAU;AAGlB,SACE,iCACE;AAAA,wBAAC,cAAS,IAAI,GAAG,cAAc;AAAA,IAC9B;AAAA,IACA;AAAA,IACD,oBAAC,cAAS,IAAI,GAAG,YAAY,KAAK,gBAAgB;AAAA,KACpD;AAEJ","sourcesContent":["import {\n startTransition,\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { useRemoteComponentsContext } from '#internal/host/react/context';\nimport { fetchWithHooks } from '#internal/host/server/fetch-with-hooks';\nimport { getClientOrServerUrl } from '#internal/host/server/get-client-or-server-url';\nimport type { ConsumeRemoteComponentConfig } from '#internal/host/shared/config';\nimport { makeReactEmitter } from '#internal/host/shared/lifecycle';\nimport { loadPrepared, preparePipeline } from '#internal/host/shared/pipeline';\nimport type { ConsumeServerData } from '#internal/host/shared/server-handoff';\nimport { createHostState } from '#internal/host/shared/state';\nimport { resolveNameFromSrc } from '#internal/host/utils/resolve-name-from-src';\nimport {\n DEFAULT_COMPONENT_NAME,\n DEFAULT_ROUTE,\n RUNTIME_SCRIPT,\n RUNTIME_WEBPACK,\n} from '#internal/runtime/constants';\nimport { setAttributesFromProps } from '#internal/runtime/html/set-attributes-from-props';\nimport { loadStaticRemoteComponent } from '#internal/runtime/loaders/static-loader';\nimport { getNamespace } from '#internal/runtime/namespace';\nimport { attrToProp, escapeString } from '#internal/utils';\nimport { isAbortError } from '#internal/utils/abort';\nimport {\n errorFromFailedFetch,\n RemoteComponentsError,\n} from '#internal/utils/error';\nimport type { MountOrUnmountFunction } from '#remote-components/runtime/types';\nimport { useResolveClientUrl } from './hooks/use-resolve-client-url';\nimport { useShadowRoot } from './hooks/use-shadow-root';\nimport {\n DUMMY_FALLBACK,\n getRemoteComponentHtml,\n} from './utils/extract-remote-html';\n\n/**\n * Props for the React remote component host.\n *\n * Extends {@link ConsumeRemoteComponentConfig} with `children` for loading\n * fallback content.\n *\n * To react to navigations originating from embedded remote components, set up\n * a single top-level subscription with `onRemoteNavigate` from\n * `remote-components/host/navigation` and route the event to your host's\n * router.\n */\nexport interface ConsumeRemoteComponentProps\n extends ConsumeRemoteComponentConfig {\n /** Loading fallback content displayed while the remote component is being fetched. */\n children?: React.ReactNode;\n}\n\n/**\n * ConsumeRemoteComponent is a React component that fetches and renders a remote component.\n * It supports SSR and can isolate the remote component in a shadow DOM.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n *\n * @example\n *\n * Use the `<ConsumeRemoteComponent>` in your React application to consume a remote component from a remote application:\n *\n * ```tsx\n * import { ConsumeRemoteComponent } from 'remote-components/host/react';\n *\n * export default function App() {\n * return (\n * <>\n * <h1>Welcome to My App</h1>\n * <p>This page consumes a remote component from another application.</p>\n * <ConsumeRemoteComponent src=\"/nextjs-app-remote/components/header\" />\n * </>\n * );\n * }\n * ```\n *\n * To share modules, you can provide a shared module map with references to the shared modules:\n *\n * ```tsx\n * <ConsumeRemoteComponent\n * src=\"/nextjs-app-remote/components/header\"\n * shared={{\n * '@/components/provider': () => import('@/components/host-provider')\n * }}\n * />\n * ```\n */\nexport function ConsumeRemoteComponent({\n src,\n isolate,\n mode = 'open',\n reset,\n credentials: credentialsProp,\n name: nameProp = DEFAULT_COMPONENT_NAME,\n shared: sharedProp,\n children,\n onBeforeLoad,\n onLoad,\n onError,\n onChange,\n onRequest,\n onResponse,\n resolveClientUrl: resolveClientUrlProp,\n}: ConsumeRemoteComponentProps) {\n const instanceId = useId();\n\n const { credentials: contextCredentials, shared: contextShared } =\n useRemoteComponentsContext();\n const credentials = credentialsProp ?? contextCredentials ?? 'same-origin';\n const shared = sharedProp ?? contextShared ?? {};\n const emitter = useMemo(\n () => makeReactEmitter({ onBeforeLoad, onLoad, onError, onChange }),\n [onBeforeLoad, onLoad, onError, onChange],\n );\n\n const name = useMemo(\n () => resolveNameFromSrc(src, nameProp),\n [src, nameProp],\n );\n\n const [data, setData] = useState<Omit<ConsumeServerData, 'children'> | null>(\n null,\n );\n\n const url = useMemo(() => getClientOrServerUrl(src, DUMMY_FALLBACK), [src]);\n\n const resolveClientUrl = useResolveClientUrl(resolveClientUrlProp, url.href);\n\n // for relative src paths, use just the pathname as the unique id.\n // for static urls, use the full url as the unique id as the path may not be unique.\n // this id needs to be the same for server and client side rendering.\n // note that if this needs to be more unique, can pass through the bundle as an id prop and ammend it to this id.\n const id =\n url.origin ===\n (typeof location !== 'undefined' ? location.origin : DUMMY_FALLBACK)\n ? url.pathname\n : url.href;\n\n //instanceId prevents multiple components with the same src from sharing a shadow root\n const keySuffix = `${escapeString(id)}_${escapeString(\n data?.name ?? name,\n )}_${escapeString(instanceId)}`;\n\n const [remoteComponent, setRemoteComponent] = useState<\n React.ReactNode | Error\n >(null);\n\n const { shadowRoot, shadowRootContainerRef } = useShadowRoot({\n isolate,\n mode,\n keySuffix,\n });\n\n const htmlRef = useRef<string | null>(\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n )?.shadowRoot?.innerHTML ??\n document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ??\n document.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`)\n ?.innerHTML ??\n document.querySelector('div[data-bundle][data-route]')?.innerHTML)\n : null,\n );\n const endTemplateRef = useRef<HTMLTemplateElement | null>(null);\n // collect initial content that needs to be removed after remote component renders\n const childrenRef = useRef(\n typeof document !== 'undefined'\n ? (() => {\n let el = document.querySelector(`template[id=\"${name}_start\"]`);\n const elements = [];\n while (el && el.id !== `${name}_end`) {\n if (\n el.id !== `${name}_start` &&\n !el.getAttribute('data-remote-component')\n ) {\n elements.push(el);\n }\n el = el.nextElementSibling as HTMLTemplateElement | null;\n }\n return elements;\n })()\n : [],\n );\n const hostStateRef = useRef(createHostState());\n const componentHydrationHtml = useRef<string | null>(null);\n const prevRemoteComponentContainerRef = useRef<HTMLDivElement | null>(null);\n const unmountRef = useRef<Set<MountOrUnmountFunction> | null>(null);\n\n // Clean up the shadow root cache on unmount to prevent memory leaks\n useLayoutEffect(() => {\n return () => {\n delete getNamespace().shadowRoots[keySuffix];\n };\n }, [keySuffix]);\n\n useLayoutEffect(() => {\n // Clear initial content after remote component renders\n if (childrenRef.current.length > 0 && remoteComponent) {\n childrenRef.current.forEach((el) => {\n el.remove();\n });\n childrenRef.current = [];\n }\n }, [remoteComponent]);\n\n useLayoutEffect(() => {\n if (shadowRoot && remoteComponent) {\n const resetStyles = shadowRoot.querySelectorAll(\n 'style[data-remote-components-reset]',\n );\n // ensure we only have one reset style in the shadow root\n if (resetStyles.length > 1) {\n resetStyles.forEach((style, index) => {\n if (\n index > 0 &&\n style.getAttribute('data-remote-components-reset') !== 'react'\n ) {\n style.remove();\n }\n });\n }\n\n // clear the html ref after hydration\n htmlRef.current = null;\n\n // clear all nodes except links and styles until the start marker\n // the marker gets only rendered on hydration\n let el: ChildNode | null = shadowRoot.childNodes[0] ?? null;\n while (el && (!('id' in el) || el.id !== `${name}_start`)) {\n const nextEl = el.nextSibling;\n if (el.nodeName !== 'LINK' && el.nodeName !== 'STYLE') {\n el.parentNode?.removeChild(el);\n }\n el = nextEl;\n }\n }\n }, [shadowRoot, remoteComponent, name]);\n\n useEffect(() => {\n if (src && src !== hostStateRef.current.prevSrc) {\n const previousSrc = hostStateRef.current.prevSrc;\n const previousName = hostStateRef.current.prevName;\n hostStateRef.current.prevSrc = src;\n\n if (previousSrc !== null) {\n htmlRef.current = null;\n }\n\n // Abort any in-progress load so the latest src always wins.\n hostStateRef.current.abortController?.abort();\n hostStateRef.current.abortController = new AbortController();\n const { signal } = hostStateRef.current.abortController;\n\n emitter.beforeLoad(src);\n hostStateRef.current.stage = 'loading';\n\n startTransition(async () => {\n try {\n let html = getRemoteComponentHtml(\n htmlRef.current ??\n (endTemplateRef.current?.previousElementSibling?.tagName === 'div'\n ? endTemplateRef.current.previousElementSibling.innerHTML\n : ''),\n );\n\n if (!html && src) {\n // fetch the remote component\n const fetchInit = {\n credentials,\n } as RequestInit;\n\n const resolvedUrl = new URL(\n resolveClientUrl?.(url.href) ?? url.href,\n location.href,\n );\n const res = await fetchWithHooks(resolvedUrl, fetchInit, {\n onRequest,\n onResponse,\n abortController: hostStateRef.current.abortController,\n });\n\n if (!res || !res.ok) {\n throw await errorFromFailedFetch(url.href, resolvedUrl, res);\n }\n\n // get the full HTML content as a string\n const remoteHtml = await res.text();\n if (signal.aborted) return;\n htmlRef.current = remoteHtml;\n html = getRemoteComponentHtml(remoteHtml);\n }\n\n if (signal.aborted) return;\n\n const userShared = await shared;\n if (signal.aborted) return;\n\n const prepared = preparePipeline({\n html,\n name,\n url,\n shared: userShared,\n resolveClientUrl,\n });\n const { doc, parsed } = prepared;\n const {\n component,\n name: remoteName,\n isRemoteComponent,\n metadata,\n rsc,\n remoteShared,\n links: linkElements,\n } = parsed;\n\n if (hostStateRef.current.prevIsRemoteComponent) {\n if (shadowRoot) {\n shadowRoot.innerHTML = '';\n }\n const prevUrl = hostStateRef.current.prevUrl;\n if (prevUrl && getNamespace().unmountFns[prevUrl.href]) {\n const unmountPromises = Promise.all(\n Array.from(unmountRef.current ?? []).map(async (unmount) =>\n unmount(\n shadowRoot ?? prevRemoteComponentContainerRef.current,\n ),\n ),\n );\n unmountRef.current = null;\n await unmountPromises;\n }\n }\n hostStateRef.current.prevIsRemoteComponent = isRemoteComponent;\n hostStateRef.current.prevUrl = url;\n hostStateRef.current.prevName = remoteName;\n\n const links = linkElements.map((link) => ({\n href: new URL(link.getAttribute('href') ?? link.href, url).href,\n ...link\n .getAttributeNames()\n .reduce<Record<string, string>>((acc, key) => {\n if (key !== 'href') {\n acc[attrToProp[key] ?? key] = link.getAttribute(key) ?? '';\n }\n return acc;\n }, {}),\n }));\n\n // handle inline scripts in the remote component\n const inlineScripts = (\n isRemoteComponent ? component : doc\n ).querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])\",\n );\n\n if (!isRemoteComponent) {\n // Next.js Script support\n const self = globalThis as typeof globalThis & {\n __next_s: [string, Record<string, string>][];\n };\n const prevNextScripts = self.__next_s;\n const nextScripts = [] as [string, Record<string, string>][];\n // eslint-disable-next-line camelcase\n self.__next_s = nextScripts;\n\n // TODO: needs to be cancellable with a singular listener for the abort signal https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\n await Promise.all(\n Array.from(inlineScripts)\n .filter(\n (script) =>\n !(\n script.id.endsWith('_shared') &&\n script.getAttribute('type') === 'application/json' &&\n typeof script.getAttribute(\n 'data-remote-components-shared',\n ) === 'string'\n ),\n )\n .map((script) => {\n return new Promise((resolve) => {\n // only handle inline scripts with content, but not Next.js RSC scripts\n if (\n script.textContent &&\n !script.textContent.includes('self.__next_f=') &&\n !script.textContent.includes('self.__next_f.push')\n ) {\n // if script is inline javascript, then execute using blob\n if (\n !script.getAttribute('type') ||\n script.getAttribute('type') === 'text/javascript' ||\n script.getAttribute('type') === 'application/javascript'\n ) {\n const newScript = document.createElement('script');\n\n // scripts loaded from external sources needs this workaround\n const blob = new Blob([script.textContent], {\n type: 'application/javascript',\n });\n const blobUrl = URL.createObjectURL(blob);\n\n newScript.onload = () => {\n resolve(undefined);\n // script executed and safe to remove\n URL.revokeObjectURL(blobUrl);\n newScript.remove();\n };\n // on error we still want to resolve to not block the remote component loading\n newScript.onerror = () => {\n URL.revokeObjectURL(blobUrl);\n newScript.remove();\n resolve(undefined);\n };\n\n newScript.src = blobUrl;\n // TODO: needs to be cancellable https://linear.app/vercel/issue/MFES-1253/handle-abortcontroller-clean-up-scenarios\n document.body.appendChild(newScript);\n } else {\n resolve(undefined);\n document.body.appendChild(script);\n }\n } else {\n resolve(undefined);\n }\n });\n }),\n );\n // process the remote component Next.js Script container\n nextScripts.forEach(([scriptSrc, props]) => {\n const script = document.createElement('script');\n // when we have a script src, apply it (inline scripts have `0` as src)\n if (scriptSrc) {\n script.src = scriptSrc;\n }\n // apply Script props\n if (typeof props.children === 'string') {\n script.textContent = props.children;\n }\n setAttributesFromProps(script, props);\n document.head.appendChild(script);\n });\n // restore previous Next.js Script container\n // eslint-disable-next-line camelcase\n self.__next_s = prevNextScripts;\n }\n\n const rscName = rsc\n ? `__remote_component_rsc_${escapeString(id)}_${escapeString(\n remoteName,\n )}`\n : undefined;\n if (rsc) {\n rsc.textContent =\n rsc.textContent?.replace(\n new RegExp(`self\\\\[\"${remoteName}\"\\\\]`, 'g'),\n `self[\"${rscName}\"]`,\n ) ?? '';\n document.body.appendChild(rsc);\n }\n\n const newData = {\n ...metadata,\n links,\n remoteShared,\n src: typeof src === 'string' ? src : src.href,\n serverUrl: url.href,\n data: rsc\n ? (rsc.textContent || '').split('\\n').filter(Boolean)\n : [],\n };\n\n componentHydrationHtml.current = `${Array.from(\n doc.querySelectorAll('link,style'),\n )\n .map((link) => link.outerHTML)\n .join('')}${\n reset\n ? `<style data-remote-components-reset=\"\">:host { all: initial; }</style>`\n : ''\n }${component.innerHTML}`;\n\n if (isRemoteComponent) {\n // Only call onChange when not on first load (matching HTML implementation)\n if (previousSrc !== undefined) {\n emitter.change({\n previousSrc: previousSrc ?? null,\n nextSrc: src,\n previousName,\n nextName: remoteName,\n });\n }\n setData(newData);\n if (shadowRoot) {\n const shadowRootHtml = reset\n ? `<style data-remote-components-reset=\"\">:host { all: initial; }</style>${component.innerHTML}`\n : component.innerHTML;\n shadowRoot.innerHTML = shadowRootHtml;\n htmlRef.current = null;\n setRemoteComponent(null);\n const { mount, unmount } = await loadStaticRemoteComponent(\n Array.from(shadowRoot.querySelectorAll('script')),\n url,\n resolveClientUrl,\n );\n unmountRef.current = unmount;\n await Promise.all(\n Array.from(mount).map((mountFn) => mountFn(shadowRoot)),\n );\n emitter.load(src);\n } else if (isolate === false) {\n setRemoteComponent(\n // TODO: remove wrapper div by converting HTML to RSC or React tree\n <div\n dangerouslySetInnerHTML={{ __html: component.innerHTML }}\n ref={prevRemoteComponentContainerRef}\n />,\n );\n htmlRef.current = null;\n const { mount, unmount } = await loadStaticRemoteComponent(\n Array.from(component.querySelectorAll('script')),\n url,\n resolveClientUrl,\n );\n unmountRef.current = unmount;\n await Promise.all(\n Array.from(mount).map((mountFn) =>\n mountFn(prevRemoteComponentContainerRef.current),\n ),\n );\n emitter.load(src);\n }\n hostStateRef.current.stage = 'loaded';\n } else {\n const result = await loadPrepared({\n prepared,\n url,\n signal,\n shared: userShared,\n resolveClientUrl,\n container: shadowRoot,\n rscName,\n });\n if (rsc) {\n rsc.remove();\n }\n\n setData(newData);\n // Only call onChange when not on first load (matching HTML implementation)\n if (previousSrc !== undefined) {\n emitter.change({\n previousSrc: previousSrc ?? null,\n nextSrc: src,\n previousName,\n nextName: remoteName,\n });\n }\n if (result.status === 'aborted') {\n return;\n }\n if (result.status === 'error') {\n hostStateRef.current.stage = 'error';\n setRemoteComponent(result.error);\n emitter.error(result.error);\n } else if (result.status === 'loaded') {\n hostStateRef.current.stage = 'loaded';\n setRemoteComponent(result.component);\n emitter.load(src);\n }\n }\n } catch (error) {\n // AbortError is expected when loading is cancelled - exit cleanly\n if (isAbortError(error)) {\n hostStateRef.current.stage = 'idle';\n return;\n }\n hostStateRef.current.stage = 'error';\n setRemoteComponent(error as Error);\n emitter.error(error);\n }\n });\n }\n }, [\n url,\n src,\n isolate,\n credentials,\n name,\n shared,\n shadowRoot,\n reset,\n id,\n emitter.beforeLoad,\n emitter.load,\n emitter.error,\n emitter.change,\n onRequest,\n onResponse,\n resolveClientUrl,\n ]);\n\n if (remoteComponent instanceof Error) {\n throw remoteComponent;\n }\n\n const metadataJson = (\n <script data-remote-component type=\"application/json\">\n {JSON.stringify({\n name: data?.name || name,\n bundle: data?.bundle || 'default',\n route: data?.route || DEFAULT_ROUTE,\n runtime: hostStateRef.current.prevIsRemoteComponent\n ? RUNTIME_SCRIPT\n : data?.runtime || RUNTIME_WEBPACK,\n })}\n </script>\n );\n const resetStyle = reset ? (\n <style data-remote-components-reset=\"react\">{`:host { all: initial; }`}</style>\n ) : null;\n const linksToRender: React.ReactNode[] | null =\n data?.links?.map((link) => (\n <link\n {...link}\n href={new URL(link.href as string, url).href}\n key={JSON.stringify(link)}\n />\n )) || null;\n const componentToRender = (\n <>\n {resetStyle}\n {linksToRender}\n {remoteComponent ?? children}\n </>\n );\n\n if (componentHydrationHtml.current && shadowRoot && !shadowRoot.innerHTML) {\n shadowRoot.innerHTML = componentHydrationHtml.current;\n componentHydrationHtml.current = null;\n\n if (hostStateRef.current.prevIsRemoteComponent) {\n // ensure we load static resources when hydrating a remote component in shadow DOM\n loadStaticRemoteComponent(\n Array.from(shadowRoot.querySelectorAll('script')),\n url,\n resolveClientUrl,\n )\n .then(({ mount }) => {\n return Promise.all(\n Array.from(mount).map((mountFn) => mountFn(shadowRoot)),\n );\n })\n .then(() => {\n if (src) {\n emitter.load(src);\n }\n })\n .catch((e) => {\n const error = new RemoteComponentsError(\n `Error mounting remote component from \"${url.href}\"`,\n {\n cause: e,\n },\n );\n setRemoteComponent(error);\n emitter.error(error);\n });\n }\n }\n\n if (isolate !== false) {\n const shadowRemoteComponentHtml =\n shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ??\n shadowRoot?.querySelector('div[data-bundle][data-route]');\n if (shadowRemoteComponentHtml) {\n shadowRemoteComponentHtml.remove();\n }\n\n return (\n <>\n {metadataJson}\n <div\n data-remote-component-id={`shadowroot_${keySuffix}`}\n id={`shadowroot_${data?.name ?? name}`}\n ref={shadowRootContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode={mode}>\n {typeof document === 'undefined' ? (\n <div\n dangerouslySetInnerHTML={{\n __html: `<img\n alt=\"\" decoding=\"async\" style=\"display:none\"\n src=\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==\"\n onload=\"(function(el){\n // Capture the shadow root during SSR hydration so the client-side\n // useShadowRoot hook can find it.\n const root = el.getRootNode();\n globalThis.__remote_components_shadowroot_${keySuffix}=root;\n el.parentElement.remove();\n })(this)\"\n />`,\n }}\n />\n ) : null}\n {resetStyle}\n {linksToRender}\n {children}\n </template>\n ) : null}\n {shadowRoot && remoteComponent\n ? createPortal(\n <>\n <template id={`${name}_start`} />\n {resetStyle}\n {linksToRender}\n {remoteComponent}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>,\n shadowRoot,\n )\n : null}\n </div>\n </>\n );\n }\n htmlRef.current = null;\n\n // render start/end markers for the remote component\n return (\n <>\n <template id={`${name}_start`} />\n {metadataJson}\n {componentToRender}\n <template id={`${name}_end`} ref={endTemplateRef} />\n </>\n );\n}\n\nexport type {\n HookOptions,\n OnRequestHook,\n OnResponseHook,\n} from '#internal/host/shared/fetch-interceptors';\nexport type { RemoteNavigateEvent } from '#internal/host/shared/navigate-event';\nexport { useRemoteNavigate } from './hooks/use-remote-navigate';\n","// extracted from Next.js source at https://github.com/vercel/next.js/blob/canary/packages/next/src/client/set-attributes-from-props.ts\n\nconst DOMAttributeNames: Record<string, string> = {\n acceptCharset: 'accept-charset',\n className: 'class',\n htmlFor: 'for',\n httpEquiv: 'http-equiv',\n noModule: 'noModule',\n};\n\nconst ignoreProps = [\n 'onLoad',\n 'onReady',\n 'dangerouslySetInnerHTML',\n 'children',\n 'onError',\n 'strategy',\n 'stylesheets',\n];\n\nfunction isBooleanScriptAttribute(\n attr: string,\n): attr is 'async' | 'defer' | 'noModule' {\n return ['async', 'defer', 'noModule'].includes(attr);\n}\n\nexport function setAttributesFromProps(el: HTMLElement, props: object) {\n for (const [p, value] of Object.entries(props)) {\n if (!Object.hasOwn(props, p)) continue;\n if (ignoreProps.includes(p)) continue;\n\n // we don't render undefined props to the DOM\n if (value === undefined) {\n continue;\n }\n\n const attr = DOMAttributeNames[p] || p.toLowerCase();\n\n if (el.tagName === 'SCRIPT' && isBooleanScriptAttribute(attr)) {\n // Correctly assign boolean script attributes\n // https://github.com/vercel/next.js/pull/20748\n (el as HTMLScriptElement)[attr] = Boolean(value);\n } else {\n el.setAttribute(attr, String(value));\n }\n\n // Remove falsy non-zero boolean attributes so they are correctly interpreted\n // (e.g. if we set them to false, this coerces to the string \"false\", which the browser interprets as true)\n if (\n value === false ||\n (el.tagName === 'SCRIPT' &&\n isBooleanScriptAttribute(attr) &&\n (!value || value === 'false'))\n ) {\n // Call setAttribute before, as we need to set and unset the attribute to override force async:\n // https://html.spec.whatwg.org/multipage/scripting.html#script-force-async\n el.setAttribute(attr, '');\n el.removeAttribute(attr);\n }\n }\n}\n","import { useMemo } from 'react';\nimport { useRemoteComponentsContext } from '#internal/host/react/context';\nimport { bindResolveClientUrl } from '#internal/runtime/url/default-resolve-client-url';\nimport type { ResolveClientUrl } from '#internal/runtime/url/resolve-client-url';\n\nexport function useResolveClientUrl(\n prop: ResolveClientUrl | undefined,\n urlHref: string,\n) {\n const { resolveClientUrl: contextValue } = useRemoteComponentsContext();\n const raw = prop ?? contextValue;\n return useMemo(() => bindResolveClientUrl(raw, urlHref), [raw, urlHref]);\n}\n","import { useLayoutEffect, useRef, useState } from 'react';\nimport { getNamespace } from '#internal/runtime/namespace';\n\ninterface UseShadowRootOptions {\n /** Whether CSS isolation is enabled */\n isolate: boolean | undefined;\n /** Shadow DOM mode */\n mode: 'open' | 'closed';\n /** Unique key suffix for identifying this shadow root */\n keySuffix: string;\n}\n\ninterface UseShadowRootResult {\n /** The shadow root element, or null if not isolated */\n shadowRoot: ShadowRoot | null;\n /** Ref to attach to the shadow host container element */\n shadowRootContainerRef: React.RefObject<HTMLDivElement | null>;\n}\n\n/**\n * Manages shadow root lifecycle for CSS isolation.\n *\n * Handles:\n * - Initial shadow root discovery from SSR or declarative shadow DOM\n * - Creating shadow root as fallback for browsers without declarative shadow DOM support\n * - Cleanup when isolation is disabled\n * - Re-attachment when isolation is re-enabled\n */\nexport function useShadowRoot({\n isolate,\n mode,\n keySuffix,\n}: UseShadowRootOptions): UseShadowRootResult {\n const shadowRootContainerRef = useRef<HTMLDivElement | null>(null);\n\n const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(() => {\n const shadowRoots = getNamespace().shadowRoots;\n const ssrShadowRoot =\n typeof document !== 'undefined'\n ? (document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n )?.shadowRoot ??\n shadowRoots[keySuffix] ??\n null)\n : null;\n // Clear the reference after reading it\n shadowRoots[keySuffix] = null;\n return ssrShadowRoot;\n });\n\n useLayoutEffect(() => {\n const shadowRoots = getNamespace().shadowRoots;\n if (\n isolate !== false &&\n typeof document !== 'undefined' &&\n (!shadowRoot || !shadowRoot.isConnected)\n ) {\n let shadowRootElement: ShadowRoot | null = null;\n const element = document.querySelector(\n `[data-remote-component-id=\"shadowroot_${keySuffix}\"]`,\n );\n shadowRootElement = shadowRoots[keySuffix] ?? element?.shadowRoot ?? null;\n\n if (!shadowRootElement && element) {\n // Create a shadow root if it doesn't exist.\n // This is a fallback for browsers that don't support declarative shadow DOM.\n try {\n shadowRootElement = element.attachShadow({ mode });\n shadowRoots[keySuffix] = shadowRootElement;\n } catch {\n // Do nothing if attachShadow fails because of existing shadow root\n }\n }\n\n if (shadowRootElement) {\n // Remove all nodes from the shadow root except links (preserves stylesheets)\n shadowRootElement.querySelectorAll('*:not(link)').forEach((node) => {\n node.remove();\n });\n setShadowRoot(shadowRootElement);\n }\n } else if (isolate === false && shadowRoot) {\n shadowRoots[keySuffix] = null;\n setShadowRoot(null);\n }\n }, [isolate, shadowRoot, mode, keySuffix]);\n\n return { shadowRoot, shadowRootContainerRef };\n}\n","import { DEFAULT_COMPONENT_NAME } from '#internal/runtime/constants';\n\n/**\n * Dummy URL used as a fallback base for URL parsing when no real base URL is available.\n * This is used during SSR or when location is not defined.\n */\nexport const DUMMY_FALLBACK = 'http://remote-components-dummy-fallback';\n\n/**\n * Extracts the relevant HTML content from a remote component response.\n *\n * Handles multiple remote component formats:\n * - Next.js Pages Router SSR wrapper (`div[id^=\"__REMOTE_COMPONENT\"]`)\n * - App Router remote components (`div[data-bundle][data-route]`)\n * - Next.js pages (`div#__next`)\n * - Web component format (`remote-component:not([src])`)\n *\n * @param html - Raw HTML string from the remote component response\n * @returns Extracted HTML content with links and scripts, or empty string if not found\n */\nexport function getRemoteComponentHtml(html: string): string {\n if (typeof document === 'undefined') return html;\n\n const parser = new DOMParser();\n const temp = parser.parseFromString(html, 'text/html');\n\n // Used by the Next.js Pages Router remote as a wrapper\n const ssrRemoteComponentContainer = temp.querySelector(\n 'div[id^=\"__REMOTE_COMPONENT\"]',\n );\n if (ssrRemoteComponentContainer) {\n return ssrRemoteComponentContainer.innerHTML;\n }\n\n // Remote component content from various sources\n const remoteComponentContainer = temp.querySelectorAll(\n `div[data-bundle][data-route][data-runtime][id^=\"${DEFAULT_COMPONENT_NAME}\"],div[data-bundle][data-route],div#__next,remote-component:not([src])`,\n );\n if (remoteComponentContainer.length > 0) {\n return `${Array.from(temp.querySelectorAll('link,script'))\n .map((link) => link.outerHTML)\n .join('')}${Array.from(remoteComponentContainer)\n .map((container) => container.outerHTML)\n .join('')}`;\n }\n\n return '';\n}\n","import { useEffect, useRef } from 'react';\nimport { onRemoteNavigate } from '#internal/host/navigation';\nimport type { RemoteNavigateEvent } from '#internal/host/shared/navigate-event';\n\n/**\n * Subscribe to remote component navigations. The callback is captured in a ref\n * so the listener is registered once — no `useCallback` or dep array needed.\n *\n * @example React Router\n * ```tsx\n * const navigate = useNavigate();\n * // Always replace — the polyfill already pushed/replaced the browser history entry.\n * useRemoteNavigate((e) => navigate(e.pathname + e.search, { replace: true }));\n * ```\n */\nexport function useRemoteNavigate(\n callback: (event: RemoteNavigateEvent) => void,\n): void {\n const callbackRef = useRef(callback);\n // Written during render (not in an effect) — the standard useCallbackRef\n // pattern. Safe under concurrent rendering: navigation events are user-driven\n // and can't fire mid-render.\n callbackRef.current = callback;\n useEffect(() => onRemoteNavigate((event) => callbackRef.current(event)), []);\n}\n"]}
@@ -1,20 +1,21 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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; }
2
2
 
3
3
 
4
- var _chunkX6W464D6cjs = require('../chunk-X6W464D6.cjs');
4
+ var _chunkRLI4YTBJcjs = require('../chunk-RLI4YTBJ.cjs');
5
5
  require('../chunk-Z2SLBFQL.cjs');
6
+ require('../chunk-5KTAEO52.cjs');
6
7
 
7
8
 
8
9
 
9
10
 
10
11
  var _chunkRUWR74XQcjs = require('../chunk-RUWR74XQ.cjs');
12
+ require('../chunk-KE7QPAQ4.cjs');
11
13
 
12
14
 
13
15
 
14
16
 
15
17
 
16
18
  var _chunkN5VQR2PWcjs = require('../chunk-N5VQR2PW.cjs');
17
- require('../chunk-KE7QPAQ4.cjs');
18
19
  require('../chunk-SHFJ5OQA.cjs');
19
20
 
20
21
  // src/config/nextjs/index.ts
@@ -141,7 +142,7 @@ function withRemoteComponentsConfig(nextConfig, options) {
141
142
  ".remote-components/shared/pages-host.tsx"
142
143
  );
143
144
  const appShared = /* @__PURE__ */ new Set([
144
- ..._chunkX6W464D6cjs.CORE_REACT_SHARED_KEYS,
145
+ ..._chunkRLI4YTBJcjs.CORE_REACT_SHARED_KEYS,
145
146
  "next/navigation",
146
147
  "next/dist/client/components/navigation",
147
148
  "next/link",
@@ -155,7 +156,7 @@ function withRemoteComponentsConfig(nextConfig, options) {
155
156
  ..._nullishCoalesce(_optionalChain([options, 'optionalAccess', _ => _.shared]), () => ( []))
156
157
  ]);
157
158
  const pagesShared = /* @__PURE__ */ new Set([
158
- ..._chunkX6W464D6cjs.CORE_REACT_SHARED_KEYS,
159
+ ..._chunkRLI4YTBJcjs.CORE_REACT_SHARED_KEYS,
159
160
  "next/router",
160
161
  "next/link",
161
162
  "next/dist/shared/lib/image-loader",
@@ -163,7 +164,7 @@ function withRemoteComponentsConfig(nextConfig, options) {
163
164
  "next/form",
164
165
  ..._nullishCoalesce(_optionalChain([options, 'optionalAccess', _2 => _2.shared]), () => ( []))
165
166
  ]);
166
- const vendorShared = { ..._chunkX6W464D6cjs.VENDOR_SHARED };
167
+ const vendorShared = { ..._chunkRLI4YTBJcjs.VENDOR_SHARED };
167
168
  const resolve = _enhancedresolve2.default.create.sync({
168
169
  conditionNames: ["browser", "import", "module", "require"],
169
170
  ..._fs.existsSync.call(void 0, _path.join.call(void 0, process.cwd(), "tsconfig.json")) ? {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config/nextjs/index.ts","../../src/utils/project-id.ts","../../src/utils/project-id-env.ts","../../src/config/webpack/nextjs.ts"],"names":["readFileSync","join","findUpSync"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,WAAW,gBAAAA,eAAc,qBAAqB;AACnE,SAAS,UAAU,SAAS,QAAAC,OAAM,gBAAgB;AACl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AK,EAAE,MAAM,UAAU;AAAA,IACvB;AAAA,IACA;AAAA,EACF,CAAC;AACH","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, dirname, join, relative } from 'node:path';\nimport enhancedResolve from 'enhanced-resolve';\nimport { findUpSync } from 'find-up';\nimport type { NextConfig } from 'next';\nimport { configSchema } from 'next/dist/server/config-schema.js';\nimport TsConfigPathsWebpackPlugin from 'tsconfig-paths-webpack-plugin';\nimport {\n CORE_REACT_SHARED_KEYS,\n VENDOR_SHARED,\n} from '#internal/host/shared/shared-module-resolver';\nimport { logDebug, logError, logWarn } from '#internal/utils/logger';\nimport { resolveProjectId } from '#internal/utils/project-id';\nimport { transform as webpackTransform } from '../webpack/nextjs';\n\nfunction getNextMajorVersion(): number | undefined {\n try {\n const nextPkgPath = findUpSync('node_modules/next/package.json', {\n cwd: process.cwd(),\n });\n if (!nextPkgPath) return undefined;\n const { version } = JSON.parse(readFileSync(nextPkgPath, 'utf8')) as {\n version: string;\n };\n const major = version.split('.')[0];\n return major ? Number.parseInt(major, 10) : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction hasPagesDirectory(): boolean {\n return (\n existsSync(join(process.cwd(), 'pages')) ||\n existsSync(join(process.cwd(), 'src/pages'))\n );\n}\n\ninterface ZodSchema {\n safeParse: (data: unknown) => { success: boolean };\n}\n\nfunction readProjectPackageJson(): { name: string; type: string } {\n const defaults = { name: basename(process.cwd()), type: 'module' };\n try {\n const packageJsonPath = findUpSync('package.json', {\n cwd: process.cwd(),\n });\n if (packageJsonPath) {\n return {\n ...defaults,\n ...(JSON.parse(readFileSync(packageJsonPath, 'utf8')) as {\n name: string;\n type: string;\n }),\n };\n }\n } catch {\n // noop\n }\n return defaults;\n}\n\ninterface WithRemoteComponentsOptions {\n /**\n * An array of package names that should be shared between the host and remote components.\n * This is useful for ensuring that both the host and remote components use the same version\n * of shared libraries.\n *\n * Essential packages are included by default: `react`, `react-dom`, `next/navigation`, `next/link`, `next/form`, `next/image` (loader only), and `next/script`.\n */\n shared?: string[];\n}\n\n/**\n * This function configures Next.js to support Remote Components.\n * You need to also use the `withMicrofrontends` function to extend your Next.js configuration.\n *\n * @param nextConfig - The Next.js configuration object.\n * @param options - Optional configuration for remote components.\n * @returns The modified Next.js configuration object with remote components support.\n *\n * @example\n *\n * ```js\n * import { withMicrofrontends } from '@vercel/microfrontends/next/config';\n * import { withRemoteComponentsConfig } from 'remote-components/config/nextjs';\n *\n * const nextConfig = {\n * // your Next.js configuration\n * };\n *\n * export default withRemoteComponentsConfig(\n * withMicrofrontends(nextConfig),\n * {\n * shared: ['some-package', 'another-package'],\n * },\n * );\n * ```\n */\nexport function withRemoteComponentsConfig(\n nextConfig: NextConfig,\n options?: WithRemoteComponentsOptions,\n) {\n const virtualRemoteComponentAppSharedRemote = join(\n process.cwd(),\n '.remote-components/shared/app-remote.tsx',\n );\n const virtualRemoteComponentPagesSharedRemote = join(\n process.cwd(),\n '.remote-components/shared/pages-remote.tsx',\n );\n const virtualRemoteComponentAppSharedHost = join(\n process.cwd(),\n '.remote-components/shared/app-host.tsx',\n );\n const virtualRemoteComponentPagesSharedHost = join(\n process.cwd(),\n '.remote-components/shared/pages-host.tsx',\n );\n\n const appShared = new Set([\n ...CORE_REACT_SHARED_KEYS,\n 'next/navigation',\n 'next/dist/client/components/navigation',\n 'next/link',\n 'next/dist/client/app-dir/link',\n 'next/form',\n 'next/dist/client/app-dir/form',\n 'next/dist/shared/lib/image-loader',\n 'next/script',\n 'next/dist/client/script',\n 'next/dist/build/polyfills/process',\n ...(options?.shared ?? []),\n ]);\n const pagesShared = new Set([\n ...CORE_REACT_SHARED_KEYS,\n 'next/router',\n 'next/link',\n 'next/dist/shared/lib/image-loader',\n 'next/script',\n 'next/form',\n ...(options?.shared ?? []),\n ]);\n\n const vendorShared = { ...VENDOR_SHARED };\n\n // resolve using enhanced-resolve\n // named import does not work with enhanced-resolve when using cjs\n // eslint-disable-next-line import/no-named-as-default-member\n const resolve = enhancedResolve.create.sync({\n conditionNames: ['browser', 'import', 'module', 'require'],\n ...(existsSync(join(process.cwd(), 'tsconfig.json'))\n ? {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n plugins: [\n new TsConfigPathsWebpackPlugin({\n configFile: join(process.cwd(), 'tsconfig.json'),\n }) as unknown as enhancedResolve.Plugin,\n ],\n }\n : {}),\n });\n\n const packageJson = readProjectPackageJson();\n\n const exportPre =\n packageJson.type !== 'module'\n ? 'module.exports = { shared: { '\n : 'export const shared = { ';\n const exportPost = packageJson.type !== 'module' ? '} };\\n' : '};\\n';\n\n const resolveSharedPath = (moduleName: string): string | undefined => {\n try {\n const resolved = resolve(process.cwd(), moduleName);\n if (resolved) {\n return relative(process.cwd(), resolved).replace(\n /^(?<relative>\\.\\.\\/)+/,\n '',\n );\n }\n } catch {\n // if module resolution using enhanced-resolve fails, fallback to require.resolve called in the shared/remote file\n }\n };\n\n const generateSharedRemote = (sharedRemote: Set<string>) =>\n `'use client';\\n${exportPre}${Array.from(sharedRemote)\n .reduce<string[]>((acc, curr) => {\n const path = resolveSharedPath(curr);\n acc.push(\n `[${\n vendorShared[curr] ??\n (path ? `'${path}'` : `require.resolve('${curr}')`)\n }]: '${curr}',`,\n );\n acc.push(\n `['__remote_shared_module_${curr}']: () => import('${curr}'),`,\n );\n return acc;\n }, [])\n .join('\\n')}${exportPost}`;\n const generateSharedHost = (sharedHost: Set<string>) =>\n `'use client';\\n${exportPre}${Array.from(sharedHost)\n .reduce<string[]>((acc, curr) => {\n acc.push(`['${curr}']: () => import('${curr}'),`);\n return acc;\n }, [])\n .join('\\n')}${exportPost}`;\n\n const appSharedRemote = generateSharedRemote(appShared);\n const pagesSharedRemote = generateSharedRemote(pagesShared);\n\n const appSharedHost = generateSharedHost(appShared);\n const pagesSharedHost = generateSharedHost(pagesShared);\n\n const emitSharedFiles = () => {\n mkdirSync(dirname(virtualRemoteComponentAppSharedRemote), {\n recursive: true,\n });\n\n writeFileSync(\n virtualRemoteComponentAppSharedRemote,\n appSharedRemote,\n 'utf-8',\n );\n writeFileSync(\n virtualRemoteComponentPagesSharedRemote,\n pagesSharedRemote,\n 'utf-8',\n );\n writeFileSync(virtualRemoteComponentAppSharedHost, appSharedHost, 'utf-8');\n writeFileSync(\n virtualRemoteComponentPagesSharedHost,\n pagesSharedHost,\n 'utf-8',\n );\n };\n\n nextConfig.transpilePackages = [\n ...(nextConfig.transpilePackages ?? []),\n 'remote-components',\n ];\n\n nextConfig.env = {\n ...nextConfig.env,\n REMOTE_COMPONENTS_CONFIGURED: '1',\n };\n\n const alias = {\n '#remote-components/remote/defaults/app': `./${relative(\n process.cwd(),\n virtualRemoteComponentAppSharedRemote,\n )}`,\n '#remote-components/remote/defaults/pages': `./${relative(\n process.cwd(),\n virtualRemoteComponentPagesSharedRemote,\n )}`,\n '#remote-components/host/defaults/app': `./${relative(\n process.cwd(),\n virtualRemoteComponentAppSharedHost,\n )}`,\n '#remote-components/host/defaults/pages': `./${relative(\n process.cwd(),\n virtualRemoteComponentPagesSharedHost,\n )}`,\n };\n\n const projectId = resolveProjectId(packageJson.name);\n process.env.REMOTE_COMPONENTS_PROJECT_ID = projectId;\n\n if (hasPagesDirectory()) {\n // Log instead of throwing for the version check because\n // withRemoteComponentsConfig is shared by both hosts and remotes.\n // Only Pages Router hosts are broken on Next.js < 16 — remotes\n // work fine and must not have their builds blocked.\n const nextMajor = getNextMajorVersion();\n if (nextMajor !== undefined && nextMajor < 16) {\n const log =\n process.env.NODE_ENV !== 'production' ||\n process.env.VERCEL_ENV === 'preview'\n ? logWarn\n : logDebug;\n log(\n 'Config',\n `Remote Components does not support Pages Router hosts on Next.js ${nextMajor}. ` +\n 'Pages Router remotes are unaffected. Upgrade to Next.js 16+ for host support.',\n );\n }\n }\n\n if (process.env.TURBOPACK) {\n if (\n !(configSchema as ZodSchema).safeParse({\n turbopack: {\n resolveAlias: {\n ...alias,\n },\n },\n compiler: {\n defineServer: {\n REMOTE_COMPONENTS_PROJECT_ID: projectId,\n },\n },\n }).success\n ) {\n logError(\n 'Config',\n 'Turbopack support requires a Next.js version that includes `compiler.defineServer`. ' +\n 'Upgrade Next.js to continue using Remote Components with Turbopack.',\n );\n process.exit(1);\n }\n nextConfig.turbopack = {\n ...nextConfig.turbopack,\n resolveAlias: {\n ...nextConfig.turbopack?.resolveAlias,\n ...alias,\n },\n };\n nextConfig.compiler = {\n ...nextConfig.compiler,\n defineServer: {\n ...nextConfig.compiler?.defineServer,\n 'process.env.REMOTE_COMPONENTS_PROJECT_ID': projectId,\n },\n };\n emitSharedFiles();\n return nextConfig;\n }\n\n // apply the webpack transform\n return webpackTransform(nextConfig, {\n app: { name: projectId },\n alias,\n emitSharedFiles,\n });\n}\n","import { readFileSync } from 'node:fs';\nimport { findUpSync } from 'find-up';\nimport { resolveProjectIdFromEnv } from './project-id-env';\n\n/**\n * Resolves the project ID using environment variables first, then\n * falling back to `.vercel/project.json` and finally the package name.\n * Node-only — requires file system access.\n */\nexport function resolveProjectId(packageName: string): string {\n const fromEnv = resolveProjectIdFromEnv();\n if (fromEnv) return fromEnv;\n\n try {\n const projectPath = findUpSync('.vercel/project.json', {\n cwd: process.cwd(),\n });\n if (projectPath) {\n return (\n JSON.parse(readFileSync(projectPath, 'utf8')) as { projectId: string }\n ).projectId;\n }\n } catch {\n // fallback below\n }\n\n return packageName;\n}\n","/**\n * Resolves the project ID from environment variables only.\n * Safe for edge/browser contexts where file system access is unavailable.\n */\nexport function resolveProjectIdFromEnv(): string | undefined {\n return (\n process.env.REMOTE_COMPONENTS_PROJECT_ID ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n process.env.VERCEL_PROJECT_ID ||\n undefined\n );\n}\n","import { join } from 'node:path';\nimport type { NextConfig } from 'next';\nimport type { WebpackOptionsNormalized } from 'webpack';\nimport { ConditionalExecPlugin } from './plugins/conditional-exec';\nimport { ModuleIdEmbedPlugin } from './plugins/module-id-embed';\nimport { PatchRequirePlugin } from './plugins/patch-require';\nimport { RemoteWebpackRequirePlugin } from './plugins/remote-webpack-require';\n\nexport function transform(\n nextConfig: NextConfig,\n {\n app,\n alias = {},\n emitSharedFiles = () => {\n // no-op by default\n },\n }: {\n app: { name: string };\n alias?: Record<string, string>;\n emitSharedFiles?: () => void;\n },\n) {\n const webpackConfig = nextConfig.webpack;\n\n nextConfig.webpack = (\n baseConfig: WebpackOptionsNormalized,\n webpackContext,\n ) => {\n // execute the client config first, otherwise their config may accidentally\n // overwrite our required config - leading to unexpected errors.\n const config = (\n typeof webpackConfig === 'function'\n ? (webpackConfig(baseConfig, webpackContext) ?? baseConfig)\n : baseConfig\n ) as WebpackOptionsNormalized;\n\n // remote component specific plugins\n config.plugins.push(\n new RemoteWebpackRequirePlugin(app.name),\n new ModuleIdEmbedPlugin(app.name, { isServer: webpackContext.isServer }),\n new ConditionalExecPlugin(app.name),\n new PatchRequirePlugin(app.name),\n );\n if (!webpackContext.isServer) {\n // change the chunk loading global to avoid conflicts with other remote components\n config.output.chunkLoadingGlobal = `__remote_chunk_loading_global_${app.name}__`;\n }\n\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve.alias,\n ...Object.fromEntries(\n Object.entries(alias).map(([key, value]) => [\n key,\n join(process.cwd(), value),\n ]),\n ),\n },\n };\n\n emitSharedFiles();\n return config;\n };\n\n return nextConfig;\n}\n"]}
1
+ {"version":3,"sources":["../../src/config/nextjs/index.ts","../../src/utils/project-id.ts","../../src/utils/project-id-env.ts","../../src/config/webpack/nextjs.ts"],"names":["readFileSync","join","findUpSync"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,WAAW,gBAAAA,eAAc,qBAAqB;AACnE,SAAS,UAAU,SAAS,QAAAC,OAAM,gBAAgB;AAClD,OAAO,qBAAqB;AAC5B,SAAS,cAAAC,mBAAkB;AAE3B,SAAS,oBAAoB;AAC7B,OAAO,gCAAgC;;;ACNvC,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;;;AC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AK;AAAA,MAC3C,QAAQ,IAAI;AAAA,MACZ;AAAA,IACF;AAAA,IACA,0CAA0C,KAAK;AAAA,MAC7C,QAAQ,IAAI;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AAEA,QAAM,YAAY,iBAAiB,YAAY,IAAI;AACnD,UAAQ,IAAI,+BAA+B;AAE3C,MAAI,kBAAkB,GAAG;AAKvB,UAAM,YAAY,oBAAoB;AACtC,QAAI,cAAc,UAAa,YAAY,IAAI;AAC7C,YAAM,MACJ,QAAQ,IAAI,aAAa,gBACzB,QAAQ,IAAI,eAAe,YACvB,UACA;AACN;AAAA,QACE;AAAA,QACA,oEAAoE;AAAA,MAEtE;AAAA,IACF;AAAA,EACF;AAEA,MAAI,QAAQ,IAAI,WAAW;AACzB,QACE,CAAE,aAA2B,UAAU;AAAA,MACrC,WAAW;AAAA,QACT,cAAc;AAAA,UACZ,GAAG;AAAA,QACL;AAAA,MACF;AAAA,MACA,UAAU;AAAA,QACR,cAAc;AAAA,UACZ,8BAA8B;AAAA,QAChC;AAAA,MACF;AAAA,IACF,CAAC,EAAE,SACH;AACA;AAAA,QACE;AAAA,QACA;AAAA,MAEF;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,eAAW,YAAY;AAAA,MACrB,GAAG,WAAW;AAAA,MACd,cAAc;AAAA,QACZ,GAAG,WAAW,WAAW;AAAA,QACzB,GAAG;AAAA,MACL;AAAA,IACF;AACA,eAAW,WAAW;AAAA,MACpB,GAAG,WAAW;AAAA,MACd,cAAc;AAAA,QACZ,GAAG,WAAW,UAAU;AAAA,QACxB,4CAA4C;AAAA,MAC9C;AAAA,IACF;AACA,oBAAgB;AAChB,WAAO;AAAA,EACT;AAGA,SAAO,UAAiB,YAAY;AAAA,IAClC,KAAK,EAAE,MAAM,UAAU;AAAA,IACvB;AAAA,IACA;AAAA,EACF,CAAC;AACH","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, dirname, join, relative } from 'node:path';\nimport enhancedResolve from 'enhanced-resolve';\nimport { findUpSync } from 'find-up';\nimport type { NextConfig } from 'next';\nimport { configSchema } from 'next/dist/server/config-schema.js';\nimport TsConfigPathsWebpackPlugin from 'tsconfig-paths-webpack-plugin';\nimport {\n CORE_REACT_SHARED_KEYS,\n VENDOR_SHARED,\n} from '#internal/host/shared/shared-module-resolver';\nimport { logDebug, logError, logWarn } from '#internal/utils/logger';\nimport { resolveProjectId } from '#internal/utils/project-id';\nimport { transform as webpackTransform } from '../webpack/nextjs';\n\nfunction getNextMajorVersion(): number | undefined {\n try {\n const nextPkgPath = findUpSync('node_modules/next/package.json', {\n cwd: process.cwd(),\n });\n if (!nextPkgPath) return undefined;\n const { version } = JSON.parse(readFileSync(nextPkgPath, 'utf8')) as {\n version: string;\n };\n const major = version.split('.')[0];\n return major ? Number.parseInt(major, 10) : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction hasPagesDirectory(): boolean {\n return (\n existsSync(join(process.cwd(), 'pages')) ||\n existsSync(join(process.cwd(), 'src/pages'))\n );\n}\n\ninterface ZodSchema {\n safeParse: (data: unknown) => { success: boolean };\n}\n\nfunction readProjectPackageJson(): { name: string; type: string } {\n const defaults = { name: basename(process.cwd()), type: 'module' };\n try {\n const packageJsonPath = findUpSync('package.json', {\n cwd: process.cwd(),\n });\n if (packageJsonPath) {\n return {\n ...defaults,\n ...(JSON.parse(readFileSync(packageJsonPath, 'utf8')) as {\n name: string;\n type: string;\n }),\n };\n }\n } catch {\n // noop\n }\n return defaults;\n}\n\ninterface WithRemoteComponentsOptions {\n /**\n * An array of package names that should be shared between the host and remote components.\n * This is useful for ensuring that both the host and remote components use the same version\n * of shared libraries.\n *\n * Essential packages are included by default: `react`, `react-dom`, `next/navigation`, `next/link`, `next/form`, `next/image` (loader only), and `next/script`.\n */\n shared?: string[];\n}\n\n/**\n * This function configures Next.js to support Remote Components.\n * You need to also use the `withMicrofrontends` function to extend your Next.js configuration.\n *\n * @param nextConfig - The Next.js configuration object.\n * @param options - Optional configuration for remote components.\n * @returns The modified Next.js configuration object with remote components support.\n *\n * @example\n *\n * ```js\n * import { withMicrofrontends } from '@vercel/microfrontends/next/config';\n * import { withRemoteComponentsConfig } from 'remote-components/config/nextjs';\n *\n * const nextConfig = {\n * // your Next.js configuration\n * };\n *\n * export default withRemoteComponentsConfig(\n * withMicrofrontends(nextConfig),\n * {\n * shared: ['some-package', 'another-package'],\n * },\n * );\n * ```\n */\nexport function withRemoteComponentsConfig(\n nextConfig: NextConfig,\n options?: WithRemoteComponentsOptions,\n) {\n const virtualRemoteComponentAppSharedRemote = join(\n process.cwd(),\n '.remote-components/shared/app-remote.tsx',\n );\n const virtualRemoteComponentPagesSharedRemote = join(\n process.cwd(),\n '.remote-components/shared/pages-remote.tsx',\n );\n const virtualRemoteComponentAppSharedHost = join(\n process.cwd(),\n '.remote-components/shared/app-host.tsx',\n );\n const virtualRemoteComponentPagesSharedHost = join(\n process.cwd(),\n '.remote-components/shared/pages-host.tsx',\n );\n\n const appShared = new Set([\n ...CORE_REACT_SHARED_KEYS,\n 'next/navigation',\n 'next/dist/client/components/navigation',\n 'next/link',\n 'next/dist/client/app-dir/link',\n 'next/form',\n 'next/dist/client/app-dir/form',\n 'next/dist/shared/lib/image-loader',\n 'next/script',\n 'next/dist/client/script',\n 'next/dist/build/polyfills/process',\n ...(options?.shared ?? []),\n ]);\n const pagesShared = new Set([\n ...CORE_REACT_SHARED_KEYS,\n 'next/router',\n 'next/link',\n 'next/dist/shared/lib/image-loader',\n 'next/script',\n 'next/form',\n ...(options?.shared ?? []),\n ]);\n\n const vendorShared = { ...VENDOR_SHARED };\n\n // resolve using enhanced-resolve\n // named import does not work with enhanced-resolve when using cjs\n // eslint-disable-next-line import/no-named-as-default-member\n const resolve = enhancedResolve.create.sync({\n conditionNames: ['browser', 'import', 'module', 'require'],\n ...(existsSync(join(process.cwd(), 'tsconfig.json'))\n ? {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n plugins: [\n new TsConfigPathsWebpackPlugin({\n configFile: join(process.cwd(), 'tsconfig.json'),\n }) as unknown as enhancedResolve.Plugin,\n ],\n }\n : {}),\n });\n\n const packageJson = readProjectPackageJson();\n\n const exportPre =\n packageJson.type !== 'module'\n ? 'module.exports = { shared: { '\n : 'export const shared = { ';\n const exportPost = packageJson.type !== 'module' ? '} };\\n' : '};\\n';\n\n const resolveSharedPath = (moduleName: string): string | undefined => {\n try {\n const resolved = resolve(process.cwd(), moduleName);\n if (resolved) {\n return relative(process.cwd(), resolved).replace(\n /^(?<relative>\\.\\.\\/)+/,\n '',\n );\n }\n } catch {\n // if module resolution using enhanced-resolve fails, fallback to require.resolve called in the shared/remote file\n }\n };\n\n const generateSharedRemote = (sharedRemote: Set<string>) =>\n `'use client';\\n${exportPre}${Array.from(sharedRemote)\n .reduce<string[]>((acc, curr) => {\n const path = resolveSharedPath(curr);\n acc.push(\n `[${\n vendorShared[curr] ??\n (path ? `'${path}'` : `require.resolve('${curr}')`)\n }]: '${curr}',`,\n );\n acc.push(\n `['__remote_shared_module_${curr}']: () => import('${curr}'),`,\n );\n return acc;\n }, [])\n .join('\\n')}${exportPost}`;\n const generateSharedHost = (sharedHost: Set<string>) =>\n `'use client';\\n${exportPre}${Array.from(sharedHost)\n .reduce<string[]>((acc, curr) => {\n acc.push(`['${curr}']: () => import('${curr}'),`);\n return acc;\n }, [])\n .join('\\n')}${exportPost}`;\n\n const appSharedRemote = generateSharedRemote(appShared);\n const pagesSharedRemote = generateSharedRemote(pagesShared);\n\n const appSharedHost = generateSharedHost(appShared);\n const pagesSharedHost = generateSharedHost(pagesShared);\n\n const emitSharedFiles = () => {\n mkdirSync(dirname(virtualRemoteComponentAppSharedRemote), {\n recursive: true,\n });\n\n writeFileSync(\n virtualRemoteComponentAppSharedRemote,\n appSharedRemote,\n 'utf-8',\n );\n writeFileSync(\n virtualRemoteComponentPagesSharedRemote,\n pagesSharedRemote,\n 'utf-8',\n );\n writeFileSync(virtualRemoteComponentAppSharedHost, appSharedHost, 'utf-8');\n writeFileSync(\n virtualRemoteComponentPagesSharedHost,\n pagesSharedHost,\n 'utf-8',\n );\n };\n\n nextConfig.transpilePackages = [\n ...(nextConfig.transpilePackages ?? []),\n 'remote-components',\n ];\n\n nextConfig.env = {\n ...nextConfig.env,\n REMOTE_COMPONENTS_CONFIGURED: '1',\n };\n\n const alias = {\n '#remote-components/remote/defaults/app': `./${relative(\n process.cwd(),\n virtualRemoteComponentAppSharedRemote,\n )}`,\n '#remote-components/remote/defaults/pages': `./${relative(\n process.cwd(),\n virtualRemoteComponentPagesSharedRemote,\n )}`,\n '#remote-components/host/defaults/app': `./${relative(\n process.cwd(),\n virtualRemoteComponentAppSharedHost,\n )}`,\n '#remote-components/host/defaults/pages': `./${relative(\n process.cwd(),\n virtualRemoteComponentPagesSharedHost,\n )}`,\n };\n\n const projectId = resolveProjectId(packageJson.name);\n process.env.REMOTE_COMPONENTS_PROJECT_ID = projectId;\n\n if (hasPagesDirectory()) {\n // Log instead of throwing for the version check because\n // withRemoteComponentsConfig is shared by both hosts and remotes.\n // Only Pages Router hosts are broken on Next.js < 16 — remotes\n // work fine and must not have their builds blocked.\n const nextMajor = getNextMajorVersion();\n if (nextMajor !== undefined && nextMajor < 16) {\n const log =\n process.env.NODE_ENV !== 'production' ||\n process.env.VERCEL_ENV === 'preview'\n ? logWarn\n : logDebug;\n log(\n 'Config',\n `Remote Components does not support Pages Router hosts on Next.js ${nextMajor}. ` +\n 'Pages Router remotes are unaffected. Upgrade to Next.js 16+ for host support.',\n );\n }\n }\n\n if (process.env.TURBOPACK) {\n if (\n !(configSchema as ZodSchema).safeParse({\n turbopack: {\n resolveAlias: {\n ...alias,\n },\n },\n compiler: {\n defineServer: {\n REMOTE_COMPONENTS_PROJECT_ID: projectId,\n },\n },\n }).success\n ) {\n logError(\n 'Config',\n 'Turbopack support requires a Next.js version that includes `compiler.defineServer`. ' +\n 'Upgrade Next.js to continue using Remote Components with Turbopack.',\n );\n process.exit(1);\n }\n nextConfig.turbopack = {\n ...nextConfig.turbopack,\n resolveAlias: {\n ...nextConfig.turbopack?.resolveAlias,\n ...alias,\n },\n };\n nextConfig.compiler = {\n ...nextConfig.compiler,\n defineServer: {\n ...nextConfig.compiler?.defineServer,\n 'process.env.REMOTE_COMPONENTS_PROJECT_ID': projectId,\n },\n };\n emitSharedFiles();\n return nextConfig;\n }\n\n // apply the webpack transform\n return webpackTransform(nextConfig, {\n app: { name: projectId },\n alias,\n emitSharedFiles,\n });\n}\n","import { readFileSync } from 'node:fs';\nimport { findUpSync } from 'find-up';\nimport { resolveProjectIdFromEnv } from './project-id-env';\n\n/**\n * Resolves the project ID using environment variables first, then\n * falling back to `.vercel/project.json` and finally the package name.\n * Node-only — requires file system access.\n */\nexport function resolveProjectId(packageName: string): string {\n const fromEnv = resolveProjectIdFromEnv();\n if (fromEnv) return fromEnv;\n\n try {\n const projectPath = findUpSync('.vercel/project.json', {\n cwd: process.cwd(),\n });\n if (projectPath) {\n return (\n JSON.parse(readFileSync(projectPath, 'utf8')) as { projectId: string }\n ).projectId;\n }\n } catch {\n // fallback below\n }\n\n return packageName;\n}\n","/**\n * Resolves the project ID from environment variables only.\n * Safe for edge/browser contexts where file system access is unavailable.\n */\nexport function resolveProjectIdFromEnv(): string | undefined {\n return (\n process.env.REMOTE_COMPONENTS_PROJECT_ID ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n process.env.VERCEL_PROJECT_ID ||\n undefined\n );\n}\n","import { join } from 'node:path';\nimport type { NextConfig } from 'next';\nimport type { WebpackOptionsNormalized } from 'webpack';\nimport { ConditionalExecPlugin } from './plugins/conditional-exec';\nimport { ModuleIdEmbedPlugin } from './plugins/module-id-embed';\nimport { PatchRequirePlugin } from './plugins/patch-require';\nimport { RemoteWebpackRequirePlugin } from './plugins/remote-webpack-require';\n\nexport function transform(\n nextConfig: NextConfig,\n {\n app,\n alias = {},\n emitSharedFiles = () => {\n // no-op by default\n },\n }: {\n app: { name: string };\n alias?: Record<string, string>;\n emitSharedFiles?: () => void;\n },\n) {\n const webpackConfig = nextConfig.webpack;\n\n nextConfig.webpack = (\n baseConfig: WebpackOptionsNormalized,\n webpackContext,\n ) => {\n // execute the client config first, otherwise their config may accidentally\n // overwrite our required config - leading to unexpected errors.\n const config = (\n typeof webpackConfig === 'function'\n ? (webpackConfig(baseConfig, webpackContext) ?? baseConfig)\n : baseConfig\n ) as WebpackOptionsNormalized;\n\n // remote component specific plugins\n config.plugins.push(\n new RemoteWebpackRequirePlugin(app.name),\n new ModuleIdEmbedPlugin(app.name, { isServer: webpackContext.isServer }),\n new ConditionalExecPlugin(app.name),\n new PatchRequirePlugin(app.name),\n );\n if (!webpackContext.isServer) {\n // change the chunk loading global to avoid conflicts with other remote components\n config.output.chunkLoadingGlobal = `__remote_chunk_loading_global_${app.name}__`;\n }\n\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve.alias,\n ...Object.fromEntries(\n Object.entries(alias).map(([key, value]) => [\n key,\n join(process.cwd(), value),\n ]),\n ),\n },\n };\n\n emitSharedFiles();\n return config;\n };\n\n return nextConfig;\n}\n"]}
@@ -1,20 +1,21 @@
1
1
  import {
2
2
  CORE_REACT_SHARED_KEYS,
3
3
  VENDOR_SHARED
4
- } from "../chunk-SJM7AAGU.js";
4
+ } from "../chunk-SAGYPGIQ.js";
5
5
  import "../chunk-D5GNZB6O.js";
6
+ import "../chunk-STIJO4AG.js";
6
7
  import {
7
8
  logDebug,
8
9
  logError,
9
10
  logWarn
10
11
  } from "../chunk-S2A4TFLS.js";
12
+ import "../chunk-X6YKUJKH.js";
11
13
  import {
12
14
  ConditionalExecPlugin,
13
15
  ModuleIdEmbedPlugin,
14
16
  PatchRequirePlugin,
15
17
  RemoteWebpackRequirePlugin
16
18
  } from "../chunk-CTUJSWCM.js";
17
- import "../chunk-X6YKUJKH.js";
18
19
  import "../chunk-ENYGL5CO.js";
19
20
 
20
21
  // src/config/nextjs/index.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config/nextjs/index.ts","../../src/utils/project-id.ts","../../src/utils/project-id-env.ts","../../src/config/webpack/nextjs.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, dirname, join, relative } from 'node:path';\nimport enhancedResolve from 'enhanced-resolve';\nimport { findUpSync } from 'find-up';\nimport type { NextConfig } from 'next';\nimport { configSchema } from 'next/dist/server/config-schema.js';\nimport TsConfigPathsWebpackPlugin from 'tsconfig-paths-webpack-plugin';\nimport {\n CORE_REACT_SHARED_KEYS,\n VENDOR_SHARED,\n} from '#internal/host/shared/shared-module-resolver';\nimport { logDebug, logError, logWarn } from '#internal/utils/logger';\nimport { resolveProjectId } from '#internal/utils/project-id';\nimport { transform as webpackTransform } from '../webpack/nextjs';\n\nfunction getNextMajorVersion(): number | undefined {\n try {\n const nextPkgPath = findUpSync('node_modules/next/package.json', {\n cwd: process.cwd(),\n });\n if (!nextPkgPath) return undefined;\n const { version } = JSON.parse(readFileSync(nextPkgPath, 'utf8')) as {\n version: string;\n };\n const major = version.split('.')[0];\n return major ? Number.parseInt(major, 10) : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction hasPagesDirectory(): boolean {\n return (\n existsSync(join(process.cwd(), 'pages')) ||\n existsSync(join(process.cwd(), 'src/pages'))\n );\n}\n\ninterface ZodSchema {\n safeParse: (data: unknown) => { success: boolean };\n}\n\nfunction readProjectPackageJson(): { name: string; type: string } {\n const defaults = { name: basename(process.cwd()), type: 'module' };\n try {\n const packageJsonPath = findUpSync('package.json', {\n cwd: process.cwd(),\n });\n if (packageJsonPath) {\n return {\n ...defaults,\n ...(JSON.parse(readFileSync(packageJsonPath, 'utf8')) as {\n name: string;\n type: string;\n }),\n };\n }\n } catch {\n // noop\n }\n return defaults;\n}\n\ninterface WithRemoteComponentsOptions {\n /**\n * An array of package names that should be shared between the host and remote components.\n * This is useful for ensuring that both the host and remote components use the same version\n * of shared libraries.\n *\n * Essential packages are included by default: `react`, `react-dom`, `next/navigation`, `next/link`, `next/form`, `next/image` (loader only), and `next/script`.\n */\n shared?: string[];\n}\n\n/**\n * This function configures Next.js to support Remote Components.\n * You need to also use the `withMicrofrontends` function to extend your Next.js configuration.\n *\n * @param nextConfig - The Next.js configuration object.\n * @param options - Optional configuration for remote components.\n * @returns The modified Next.js configuration object with remote components support.\n *\n * @example\n *\n * ```js\n * import { withMicrofrontends } from '@vercel/microfrontends/next/config';\n * import { withRemoteComponentsConfig } from 'remote-components/config/nextjs';\n *\n * const nextConfig = {\n * // your Next.js configuration\n * };\n *\n * export default withRemoteComponentsConfig(\n * withMicrofrontends(nextConfig),\n * {\n * shared: ['some-package', 'another-package'],\n * },\n * );\n * ```\n */\nexport function withRemoteComponentsConfig(\n nextConfig: NextConfig,\n options?: WithRemoteComponentsOptions,\n) {\n const virtualRemoteComponentAppSharedRemote = join(\n process.cwd(),\n '.remote-components/shared/app-remote.tsx',\n );\n const virtualRemoteComponentPagesSharedRemote = join(\n process.cwd(),\n '.remote-components/shared/pages-remote.tsx',\n );\n const virtualRemoteComponentAppSharedHost = join(\n process.cwd(),\n '.remote-components/shared/app-host.tsx',\n );\n const virtualRemoteComponentPagesSharedHost = join(\n process.cwd(),\n '.remote-components/shared/pages-host.tsx',\n );\n\n const appShared = new Set([\n ...CORE_REACT_SHARED_KEYS,\n 'next/navigation',\n 'next/dist/client/components/navigation',\n 'next/link',\n 'next/dist/client/app-dir/link',\n 'next/form',\n 'next/dist/client/app-dir/form',\n 'next/dist/shared/lib/image-loader',\n 'next/script',\n 'next/dist/client/script',\n 'next/dist/build/polyfills/process',\n ...(options?.shared ?? []),\n ]);\n const pagesShared = new Set([\n ...CORE_REACT_SHARED_KEYS,\n 'next/router',\n 'next/link',\n 'next/dist/shared/lib/image-loader',\n 'next/script',\n 'next/form',\n ...(options?.shared ?? []),\n ]);\n\n const vendorShared = { ...VENDOR_SHARED };\n\n // resolve using enhanced-resolve\n // named import does not work with enhanced-resolve when using cjs\n // eslint-disable-next-line import/no-named-as-default-member\n const resolve = enhancedResolve.create.sync({\n conditionNames: ['browser', 'import', 'module', 'require'],\n ...(existsSync(join(process.cwd(), 'tsconfig.json'))\n ? {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n plugins: [\n new TsConfigPathsWebpackPlugin({\n configFile: join(process.cwd(), 'tsconfig.json'),\n }) as unknown as enhancedResolve.Plugin,\n ],\n }\n : {}),\n });\n\n const packageJson = readProjectPackageJson();\n\n const exportPre =\n packageJson.type !== 'module'\n ? 'module.exports = { shared: { '\n : 'export const shared = { ';\n const exportPost = packageJson.type !== 'module' ? '} };\\n' : '};\\n';\n\n const resolveSharedPath = (moduleName: string): string | undefined => {\n try {\n const resolved = resolve(process.cwd(), moduleName);\n if (resolved) {\n return relative(process.cwd(), resolved).replace(\n /^(?<relative>\\.\\.\\/)+/,\n '',\n );\n }\n } catch {\n // if module resolution using enhanced-resolve fails, fallback to require.resolve called in the shared/remote file\n }\n };\n\n const generateSharedRemote = (sharedRemote: Set<string>) =>\n `'use client';\\n${exportPre}${Array.from(sharedRemote)\n .reduce<string[]>((acc, curr) => {\n const path = resolveSharedPath(curr);\n acc.push(\n `[${\n vendorShared[curr] ??\n (path ? `'${path}'` : `require.resolve('${curr}')`)\n }]: '${curr}',`,\n );\n acc.push(\n `['__remote_shared_module_${curr}']: () => import('${curr}'),`,\n );\n return acc;\n }, [])\n .join('\\n')}${exportPost}`;\n const generateSharedHost = (sharedHost: Set<string>) =>\n `'use client';\\n${exportPre}${Array.from(sharedHost)\n .reduce<string[]>((acc, curr) => {\n acc.push(`['${curr}']: () => import('${curr}'),`);\n return acc;\n }, [])\n .join('\\n')}${exportPost}`;\n\n const appSharedRemote = generateSharedRemote(appShared);\n const pagesSharedRemote = generateSharedRemote(pagesShared);\n\n const appSharedHost = generateSharedHost(appShared);\n const pagesSharedHost = generateSharedHost(pagesShared);\n\n const emitSharedFiles = () => {\n mkdirSync(dirname(virtualRemoteComponentAppSharedRemote), {\n recursive: true,\n });\n\n writeFileSync(\n virtualRemoteComponentAppSharedRemote,\n appSharedRemote,\n 'utf-8',\n );\n writeFileSync(\n virtualRemoteComponentPagesSharedRemote,\n pagesSharedRemote,\n 'utf-8',\n );\n writeFileSync(virtualRemoteComponentAppSharedHost, appSharedHost, 'utf-8');\n writeFileSync(\n virtualRemoteComponentPagesSharedHost,\n pagesSharedHost,\n 'utf-8',\n );\n };\n\n nextConfig.transpilePackages = [\n ...(nextConfig.transpilePackages ?? []),\n 'remote-components',\n ];\n\n nextConfig.env = {\n ...nextConfig.env,\n REMOTE_COMPONENTS_CONFIGURED: '1',\n };\n\n const alias = {\n '#remote-components/remote/defaults/app': `./${relative(\n process.cwd(),\n virtualRemoteComponentAppSharedRemote,\n )}`,\n '#remote-components/remote/defaults/pages': `./${relative(\n process.cwd(),\n virtualRemoteComponentPagesSharedRemote,\n )}`,\n '#remote-components/host/defaults/app': `./${relative(\n process.cwd(),\n virtualRemoteComponentAppSharedHost,\n )}`,\n '#remote-components/host/defaults/pages': `./${relative(\n process.cwd(),\n virtualRemoteComponentPagesSharedHost,\n )}`,\n };\n\n const projectId = resolveProjectId(packageJson.name);\n process.env.REMOTE_COMPONENTS_PROJECT_ID = projectId;\n\n if (hasPagesDirectory()) {\n // Log instead of throwing for the version check because\n // withRemoteComponentsConfig is shared by both hosts and remotes.\n // Only Pages Router hosts are broken on Next.js < 16 — remotes\n // work fine and must not have their builds blocked.\n const nextMajor = getNextMajorVersion();\n if (nextMajor !== undefined && nextMajor < 16) {\n const log =\n process.env.NODE_ENV !== 'production' ||\n process.env.VERCEL_ENV === 'preview'\n ? logWarn\n : logDebug;\n log(\n 'Config',\n `Remote Components does not support Pages Router hosts on Next.js ${nextMajor}. ` +\n 'Pages Router remotes are unaffected. Upgrade to Next.js 16+ for host support.',\n );\n }\n }\n\n if (process.env.TURBOPACK) {\n if (\n !(configSchema as ZodSchema).safeParse({\n turbopack: {\n resolveAlias: {\n ...alias,\n },\n },\n compiler: {\n defineServer: {\n REMOTE_COMPONENTS_PROJECT_ID: projectId,\n },\n },\n }).success\n ) {\n logError(\n 'Config',\n 'Turbopack support requires a Next.js version that includes `compiler.defineServer`. ' +\n 'Upgrade Next.js to continue using Remote Components with Turbopack.',\n );\n process.exit(1);\n }\n nextConfig.turbopack = {\n ...nextConfig.turbopack,\n resolveAlias: {\n ...nextConfig.turbopack?.resolveAlias,\n ...alias,\n },\n };\n nextConfig.compiler = {\n ...nextConfig.compiler,\n defineServer: {\n ...nextConfig.compiler?.defineServer,\n 'process.env.REMOTE_COMPONENTS_PROJECT_ID': projectId,\n },\n };\n emitSharedFiles();\n return nextConfig;\n }\n\n // apply the webpack transform\n return webpackTransform(nextConfig, {\n app: { name: projectId },\n alias,\n emitSharedFiles,\n });\n}\n","import { readFileSync } from 'node:fs';\nimport { findUpSync } from 'find-up';\nimport { resolveProjectIdFromEnv } from './project-id-env';\n\n/**\n * Resolves the project ID using environment variables first, then\n * falling back to `.vercel/project.json` and finally the package name.\n * Node-only — requires file system access.\n */\nexport function resolveProjectId(packageName: string): string {\n const fromEnv = resolveProjectIdFromEnv();\n if (fromEnv) return fromEnv;\n\n try {\n const projectPath = findUpSync('.vercel/project.json', {\n cwd: process.cwd(),\n });\n if (projectPath) {\n return (\n JSON.parse(readFileSync(projectPath, 'utf8')) as { projectId: string }\n ).projectId;\n }\n } catch {\n // fallback below\n }\n\n return packageName;\n}\n","/**\n * Resolves the project ID from environment variables only.\n * Safe for edge/browser contexts where file system access is unavailable.\n */\nexport function resolveProjectIdFromEnv(): string | undefined {\n return (\n process.env.REMOTE_COMPONENTS_PROJECT_ID ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n process.env.VERCEL_PROJECT_ID ||\n undefined\n );\n}\n","import { join } from 'node:path';\nimport type { NextConfig } from 'next';\nimport type { WebpackOptionsNormalized } from 'webpack';\nimport { ConditionalExecPlugin } from './plugins/conditional-exec';\nimport { ModuleIdEmbedPlugin } from './plugins/module-id-embed';\nimport { PatchRequirePlugin } from './plugins/patch-require';\nimport { RemoteWebpackRequirePlugin } from './plugins/remote-webpack-require';\n\nexport function transform(\n nextConfig: NextConfig,\n {\n app,\n alias = {},\n emitSharedFiles = () => {\n // no-op by default\n },\n }: {\n app: { name: string };\n alias?: Record<string, string>;\n emitSharedFiles?: () => void;\n },\n) {\n const webpackConfig = nextConfig.webpack;\n\n nextConfig.webpack = (\n baseConfig: WebpackOptionsNormalized,\n webpackContext,\n ) => {\n // execute the client config first, otherwise their config may accidentally\n // overwrite our required config - leading to unexpected errors.\n const config = (\n typeof webpackConfig === 'function'\n ? (webpackConfig(baseConfig, webpackContext) ?? baseConfig)\n : baseConfig\n ) as WebpackOptionsNormalized;\n\n // remote component specific plugins\n config.plugins.push(\n new RemoteWebpackRequirePlugin(app.name),\n new ModuleIdEmbedPlugin(app.name, { isServer: webpackContext.isServer }),\n new ConditionalExecPlugin(app.name),\n new PatchRequirePlugin(app.name),\n );\n if (!webpackContext.isServer) {\n // change the chunk loading global to avoid conflicts with other remote components\n config.output.chunkLoadingGlobal = `__remote_chunk_loading_global_${app.name}__`;\n }\n\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve.alias,\n ...Object.fromEntries(\n Object.entries(alias).map(([key, value]) => [\n key,\n join(process.cwd(), value),\n ]),\n ),\n },\n };\n\n emitSharedFiles();\n return config;\n };\n\n return nextConfig;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,WAAW,gBAAAA,eAAc,qBAAqB;AACnE,SAAS,UAAU,SAAS,QAAAC,OAAM,gBAAgB;AAClD,OAAO,qBAAqB;AAC5B,SAAS,cAAAC,mBAAkB;AAE3B,SAAS,oBAAoB;AAC7B,OAAO,gCAAgC;;;ACNvC,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;;;ACGpB,SAAS,0BAA8C;AAC5D,SACE,QAAQ,IAAI,gCACZ,QAAQ,IAAI,uCACZ,QAAQ,IAAI,qBACZ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QAAQ,IAAI;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AAEA,QAAM,YAAY,iBAAiB,YAAY,IAAI;AACnD,UAAQ,IAAI,+BAA+B;AAE3C,MAAI,kBAAkB,GAAG;AAKvB,UAAM,YAAY,oBAAoB;AACtC,QAAI,cAAc,UAAa,YAAY,IAAI;AAC7C,YAAM,MACJ,QAAQ,IAAI,aAAa,gBACzB,QAAQ,IAAI,eAAe,YACvB,UACA;AACN;AAAA,QACE;AAAA,QACA,oEAAoE;AAAA,MAEtE;AAAA,IACF;AAAA,EACF;AAEA,MAAI,QAAQ,IAAI,WAAW;AACzB,QACE,CAAE,aAA2B,UAAU;AAAA,MACrC,WAAW;AAAA,QACT,cAAc;AAAA,UACZ,GAAG;AAAA,QACL;AAAA,MACF;AAAA,MACA,UAAU;AAAA,QACR,cAAc;AAAA,UACZ,8BAA8B;AAAA,QAChC;AAAA,MACF;AAAA,IACF,CAAC,EAAE,SACH;AACA;AAAA,QACE;AAAA,QACA;AAAA,MAEF;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,eAAW,YAAY;AAAA,MACrB,GAAG,WAAW;AAAA,MACd,cAAc;AAAA,QACZ,GAAG,WAAW,WAAW;AAAA,QACzB,GAAG;AAAA,MACL;AAAA,IACF;AACA,eAAW,WAAW;AAAA,MACpB,GAAG,WAAW;AAAA,MACd,cAAc;AAAA,QACZ,GAAG,WAAW,UAAU;AAAA,QACxB,4CAA4C;AAAA,MAC9C;AAAA,IACF;AACA,oBAAgB;AAChB,WAAO;AAAA,EACT;AAGA,SAAO,UAAiB,YAAY;AAAA,IAClC,KAAK,EAAE,MAAM,UAAU;AAAA,IACvB;AAAA,IACA;AAAA,EACF,CAAC;AACH;","names":["readFileSync","join","findUpSync","findUpSync","readFileSync","join"]}
1
+ {"version":3,"sources":["../../src/config/nextjs/index.ts","../../src/utils/project-id.ts","../../src/utils/project-id-env.ts","../../src/config/webpack/nextjs.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, dirname, join, relative } from 'node:path';\nimport enhancedResolve from 'enhanced-resolve';\nimport { findUpSync } from 'find-up';\nimport type { NextConfig } from 'next';\nimport { configSchema } from 'next/dist/server/config-schema.js';\nimport TsConfigPathsWebpackPlugin from 'tsconfig-paths-webpack-plugin';\nimport {\n CORE_REACT_SHARED_KEYS,\n VENDOR_SHARED,\n} from '#internal/host/shared/shared-module-resolver';\nimport { logDebug, logError, logWarn } from '#internal/utils/logger';\nimport { resolveProjectId } from '#internal/utils/project-id';\nimport { transform as webpackTransform } from '../webpack/nextjs';\n\nfunction getNextMajorVersion(): number | undefined {\n try {\n const nextPkgPath = findUpSync('node_modules/next/package.json', {\n cwd: process.cwd(),\n });\n if (!nextPkgPath) return undefined;\n const { version } = JSON.parse(readFileSync(nextPkgPath, 'utf8')) as {\n version: string;\n };\n const major = version.split('.')[0];\n return major ? Number.parseInt(major, 10) : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction hasPagesDirectory(): boolean {\n return (\n existsSync(join(process.cwd(), 'pages')) ||\n existsSync(join(process.cwd(), 'src/pages'))\n );\n}\n\ninterface ZodSchema {\n safeParse: (data: unknown) => { success: boolean };\n}\n\nfunction readProjectPackageJson(): { name: string; type: string } {\n const defaults = { name: basename(process.cwd()), type: 'module' };\n try {\n const packageJsonPath = findUpSync('package.json', {\n cwd: process.cwd(),\n });\n if (packageJsonPath) {\n return {\n ...defaults,\n ...(JSON.parse(readFileSync(packageJsonPath, 'utf8')) as {\n name: string;\n type: string;\n }),\n };\n }\n } catch {\n // noop\n }\n return defaults;\n}\n\ninterface WithRemoteComponentsOptions {\n /**\n * An array of package names that should be shared between the host and remote components.\n * This is useful for ensuring that both the host and remote components use the same version\n * of shared libraries.\n *\n * Essential packages are included by default: `react`, `react-dom`, `next/navigation`, `next/link`, `next/form`, `next/image` (loader only), and `next/script`.\n */\n shared?: string[];\n}\n\n/**\n * This function configures Next.js to support Remote Components.\n * You need to also use the `withMicrofrontends` function to extend your Next.js configuration.\n *\n * @param nextConfig - The Next.js configuration object.\n * @param options - Optional configuration for remote components.\n * @returns The modified Next.js configuration object with remote components support.\n *\n * @example\n *\n * ```js\n * import { withMicrofrontends } from '@vercel/microfrontends/next/config';\n * import { withRemoteComponentsConfig } from 'remote-components/config/nextjs';\n *\n * const nextConfig = {\n * // your Next.js configuration\n * };\n *\n * export default withRemoteComponentsConfig(\n * withMicrofrontends(nextConfig),\n * {\n * shared: ['some-package', 'another-package'],\n * },\n * );\n * ```\n */\nexport function withRemoteComponentsConfig(\n nextConfig: NextConfig,\n options?: WithRemoteComponentsOptions,\n) {\n const virtualRemoteComponentAppSharedRemote = join(\n process.cwd(),\n '.remote-components/shared/app-remote.tsx',\n );\n const virtualRemoteComponentPagesSharedRemote = join(\n process.cwd(),\n '.remote-components/shared/pages-remote.tsx',\n );\n const virtualRemoteComponentAppSharedHost = join(\n process.cwd(),\n '.remote-components/shared/app-host.tsx',\n );\n const virtualRemoteComponentPagesSharedHost = join(\n process.cwd(),\n '.remote-components/shared/pages-host.tsx',\n );\n\n const appShared = new Set([\n ...CORE_REACT_SHARED_KEYS,\n 'next/navigation',\n 'next/dist/client/components/navigation',\n 'next/link',\n 'next/dist/client/app-dir/link',\n 'next/form',\n 'next/dist/client/app-dir/form',\n 'next/dist/shared/lib/image-loader',\n 'next/script',\n 'next/dist/client/script',\n 'next/dist/build/polyfills/process',\n ...(options?.shared ?? []),\n ]);\n const pagesShared = new Set([\n ...CORE_REACT_SHARED_KEYS,\n 'next/router',\n 'next/link',\n 'next/dist/shared/lib/image-loader',\n 'next/script',\n 'next/form',\n ...(options?.shared ?? []),\n ]);\n\n const vendorShared = { ...VENDOR_SHARED };\n\n // resolve using enhanced-resolve\n // named import does not work with enhanced-resolve when using cjs\n // eslint-disable-next-line import/no-named-as-default-member\n const resolve = enhancedResolve.create.sync({\n conditionNames: ['browser', 'import', 'module', 'require'],\n ...(existsSync(join(process.cwd(), 'tsconfig.json'))\n ? {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n plugins: [\n new TsConfigPathsWebpackPlugin({\n configFile: join(process.cwd(), 'tsconfig.json'),\n }) as unknown as enhancedResolve.Plugin,\n ],\n }\n : {}),\n });\n\n const packageJson = readProjectPackageJson();\n\n const exportPre =\n packageJson.type !== 'module'\n ? 'module.exports = { shared: { '\n : 'export const shared = { ';\n const exportPost = packageJson.type !== 'module' ? '} };\\n' : '};\\n';\n\n const resolveSharedPath = (moduleName: string): string | undefined => {\n try {\n const resolved = resolve(process.cwd(), moduleName);\n if (resolved) {\n return relative(process.cwd(), resolved).replace(\n /^(?<relative>\\.\\.\\/)+/,\n '',\n );\n }\n } catch {\n // if module resolution using enhanced-resolve fails, fallback to require.resolve called in the shared/remote file\n }\n };\n\n const generateSharedRemote = (sharedRemote: Set<string>) =>\n `'use client';\\n${exportPre}${Array.from(sharedRemote)\n .reduce<string[]>((acc, curr) => {\n const path = resolveSharedPath(curr);\n acc.push(\n `[${\n vendorShared[curr] ??\n (path ? `'${path}'` : `require.resolve('${curr}')`)\n }]: '${curr}',`,\n );\n acc.push(\n `['__remote_shared_module_${curr}']: () => import('${curr}'),`,\n );\n return acc;\n }, [])\n .join('\\n')}${exportPost}`;\n const generateSharedHost = (sharedHost: Set<string>) =>\n `'use client';\\n${exportPre}${Array.from(sharedHost)\n .reduce<string[]>((acc, curr) => {\n acc.push(`['${curr}']: () => import('${curr}'),`);\n return acc;\n }, [])\n .join('\\n')}${exportPost}`;\n\n const appSharedRemote = generateSharedRemote(appShared);\n const pagesSharedRemote = generateSharedRemote(pagesShared);\n\n const appSharedHost = generateSharedHost(appShared);\n const pagesSharedHost = generateSharedHost(pagesShared);\n\n const emitSharedFiles = () => {\n mkdirSync(dirname(virtualRemoteComponentAppSharedRemote), {\n recursive: true,\n });\n\n writeFileSync(\n virtualRemoteComponentAppSharedRemote,\n appSharedRemote,\n 'utf-8',\n );\n writeFileSync(\n virtualRemoteComponentPagesSharedRemote,\n pagesSharedRemote,\n 'utf-8',\n );\n writeFileSync(virtualRemoteComponentAppSharedHost, appSharedHost, 'utf-8');\n writeFileSync(\n virtualRemoteComponentPagesSharedHost,\n pagesSharedHost,\n 'utf-8',\n );\n };\n\n nextConfig.transpilePackages = [\n ...(nextConfig.transpilePackages ?? []),\n 'remote-components',\n ];\n\n nextConfig.env = {\n ...nextConfig.env,\n REMOTE_COMPONENTS_CONFIGURED: '1',\n };\n\n const alias = {\n '#remote-components/remote/defaults/app': `./${relative(\n process.cwd(),\n virtualRemoteComponentAppSharedRemote,\n )}`,\n '#remote-components/remote/defaults/pages': `./${relative(\n process.cwd(),\n virtualRemoteComponentPagesSharedRemote,\n )}`,\n '#remote-components/host/defaults/app': `./${relative(\n process.cwd(),\n virtualRemoteComponentAppSharedHost,\n )}`,\n '#remote-components/host/defaults/pages': `./${relative(\n process.cwd(),\n virtualRemoteComponentPagesSharedHost,\n )}`,\n };\n\n const projectId = resolveProjectId(packageJson.name);\n process.env.REMOTE_COMPONENTS_PROJECT_ID = projectId;\n\n if (hasPagesDirectory()) {\n // Log instead of throwing for the version check because\n // withRemoteComponentsConfig is shared by both hosts and remotes.\n // Only Pages Router hosts are broken on Next.js < 16 — remotes\n // work fine and must not have their builds blocked.\n const nextMajor = getNextMajorVersion();\n if (nextMajor !== undefined && nextMajor < 16) {\n const log =\n process.env.NODE_ENV !== 'production' ||\n process.env.VERCEL_ENV === 'preview'\n ? logWarn\n : logDebug;\n log(\n 'Config',\n `Remote Components does not support Pages Router hosts on Next.js ${nextMajor}. ` +\n 'Pages Router remotes are unaffected. Upgrade to Next.js 16+ for host support.',\n );\n }\n }\n\n if (process.env.TURBOPACK) {\n if (\n !(configSchema as ZodSchema).safeParse({\n turbopack: {\n resolveAlias: {\n ...alias,\n },\n },\n compiler: {\n defineServer: {\n REMOTE_COMPONENTS_PROJECT_ID: projectId,\n },\n },\n }).success\n ) {\n logError(\n 'Config',\n 'Turbopack support requires a Next.js version that includes `compiler.defineServer`. ' +\n 'Upgrade Next.js to continue using Remote Components with Turbopack.',\n );\n process.exit(1);\n }\n nextConfig.turbopack = {\n ...nextConfig.turbopack,\n resolveAlias: {\n ...nextConfig.turbopack?.resolveAlias,\n ...alias,\n },\n };\n nextConfig.compiler = {\n ...nextConfig.compiler,\n defineServer: {\n ...nextConfig.compiler?.defineServer,\n 'process.env.REMOTE_COMPONENTS_PROJECT_ID': projectId,\n },\n };\n emitSharedFiles();\n return nextConfig;\n }\n\n // apply the webpack transform\n return webpackTransform(nextConfig, {\n app: { name: projectId },\n alias,\n emitSharedFiles,\n });\n}\n","import { readFileSync } from 'node:fs';\nimport { findUpSync } from 'find-up';\nimport { resolveProjectIdFromEnv } from './project-id-env';\n\n/**\n * Resolves the project ID using environment variables first, then\n * falling back to `.vercel/project.json` and finally the package name.\n * Node-only — requires file system access.\n */\nexport function resolveProjectId(packageName: string): string {\n const fromEnv = resolveProjectIdFromEnv();\n if (fromEnv) return fromEnv;\n\n try {\n const projectPath = findUpSync('.vercel/project.json', {\n cwd: process.cwd(),\n });\n if (projectPath) {\n return (\n JSON.parse(readFileSync(projectPath, 'utf8')) as { projectId: string }\n ).projectId;\n }\n } catch {\n // fallback below\n }\n\n return packageName;\n}\n","/**\n * Resolves the project ID from environment variables only.\n * Safe for edge/browser contexts where file system access is unavailable.\n */\nexport function resolveProjectIdFromEnv(): string | undefined {\n return (\n process.env.REMOTE_COMPONENTS_PROJECT_ID ||\n process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION ||\n process.env.VERCEL_PROJECT_ID ||\n undefined\n );\n}\n","import { join } from 'node:path';\nimport type { NextConfig } from 'next';\nimport type { WebpackOptionsNormalized } from 'webpack';\nimport { ConditionalExecPlugin } from './plugins/conditional-exec';\nimport { ModuleIdEmbedPlugin } from './plugins/module-id-embed';\nimport { PatchRequirePlugin } from './plugins/patch-require';\nimport { RemoteWebpackRequirePlugin } from './plugins/remote-webpack-require';\n\nexport function transform(\n nextConfig: NextConfig,\n {\n app,\n alias = {},\n emitSharedFiles = () => {\n // no-op by default\n },\n }: {\n app: { name: string };\n alias?: Record<string, string>;\n emitSharedFiles?: () => void;\n },\n) {\n const webpackConfig = nextConfig.webpack;\n\n nextConfig.webpack = (\n baseConfig: WebpackOptionsNormalized,\n webpackContext,\n ) => {\n // execute the client config first, otherwise their config may accidentally\n // overwrite our required config - leading to unexpected errors.\n const config = (\n typeof webpackConfig === 'function'\n ? (webpackConfig(baseConfig, webpackContext) ?? baseConfig)\n : baseConfig\n ) as WebpackOptionsNormalized;\n\n // remote component specific plugins\n config.plugins.push(\n new RemoteWebpackRequirePlugin(app.name),\n new ModuleIdEmbedPlugin(app.name, { isServer: webpackContext.isServer }),\n new ConditionalExecPlugin(app.name),\n new PatchRequirePlugin(app.name),\n );\n if (!webpackContext.isServer) {\n // change the chunk loading global to avoid conflicts with other remote components\n config.output.chunkLoadingGlobal = `__remote_chunk_loading_global_${app.name}__`;\n }\n\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve.alias,\n ...Object.fromEntries(\n Object.entries(alias).map(([key, value]) => [\n key,\n join(process.cwd(), value),\n ]),\n ),\n },\n };\n\n emitSharedFiles();\n return config;\n };\n\n return nextConfig;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,WAAW,gBAAAA,eAAc,qBAAqB;AACnE,SAAS,UAAU,SAAS,QAAAC,OAAM,gBAAgB;AAClD,OAAO,qBAAqB;AAC5B,SAAS,cAAAC,mBAAkB;AAE3B,SAAS,oBAAoB;AAC7B,OAAO,gCAAgC;;;ACNvC,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;;;ACGpB,SAAS,0BAA8C;AAC5D,SACE,QAAQ,IAAI,gCACZ,QAAQ,IAAI,uCACZ,QAAQ,IAAI,qBACZ;AAEJ;;;ADFO,SAAS,iBAAiB,aAA6B;AAC5D,QAAM,UAAU,wBAAwB;AACxC,MAAI;AAAS,WAAO;AAEpB,MAAI;AACF,UAAM,cAAc,W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