remote-components 0.0.21 → 0.0.22

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 (29) hide show
  1. package/dist/html/host.cjs +44 -19
  2. package/dist/html/host.cjs.map +1 -1
  3. package/dist/html/host.js +44 -19
  4. package/dist/html/host.js.map +1 -1
  5. package/dist/internal/next/host/app-router-client.cjs +26 -18
  6. package/dist/internal/next/host/app-router-client.cjs.map +1 -1
  7. package/dist/internal/next/host/app-router-client.js +26 -18
  8. package/dist/internal/next/host/app-router-client.js.map +1 -1
  9. package/dist/internal/shared/client/remote-component.cjs +43 -16
  10. package/dist/internal/shared/client/remote-component.cjs.map +1 -1
  11. package/dist/internal/shared/client/remote-component.js +43 -16
  12. package/dist/internal/shared/client/remote-component.js.map +1 -1
  13. package/dist/internal/shared/ssr/fetch-remote-component.cjs +1 -3
  14. package/dist/internal/shared/ssr/fetch-remote-component.cjs.map +1 -1
  15. package/dist/internal/shared/ssr/fetch-remote-component.js +1 -3
  16. package/dist/internal/shared/ssr/fetch-remote-component.js.map +1 -1
  17. package/dist/internal/webpack/next-client-pages-loader.cjs +43 -16
  18. package/dist/internal/webpack/next-client-pages-loader.cjs.map +1 -1
  19. package/dist/internal/webpack/next-client-pages-loader.js +43 -16
  20. package/dist/internal/webpack/next-client-pages-loader.js.map +1 -1
  21. package/dist/next/middleware.cjs +1 -1
  22. package/dist/next/middleware.cjs.map +1 -1
  23. package/dist/next/middleware.js +1 -1
  24. package/dist/next/middleware.js.map +1 -1
  25. package/dist/react/index.cjs +9 -7
  26. package/dist/react/index.cjs.map +1 -1
  27. package/dist/react/index.js +9 -7
  28. package/dist/react/index.js.map +1 -1
  29. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/shared/webpack/next-client-pages-loader.ts"],"sourcesContent":["// module loader for Next.js Pages Router\nexport function nextClientPagesLoader(\n bundle: string,\n route: string,\n styleContainer: HTMLHeadElement | ShadowRoot | null = document.head,\n) {\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string | number) => unknown) & {\n c?: Record<\n string | number,\n { id: string; parents: string[]; children: string[] }\n >;\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n type?: 'turbopack' | 'webpack';\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n // Next.js client pages loader reference storage\n __NEXT_P?: [\n (\n | [\n string,\n () => { default?: React.ComponentType<Record<string, unknown>> },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n ];\n };\n\n // temporarily remove the original Next.js CSS loader\n const nextCssOriginal = document.getElementById('__next_css__DO_NOT_USE__');\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.removeChild(nextCssOriginal);\n }\n\n // create a new Next.js CSS loader element\n const nextCss = document.createElement('noscript');\n nextCss.id = '__next_css__DO_NOT_USE__';\n const lastNode =\n document.head.childNodes[document.head.childNodes.length - 1];\n document.head.appendChild(nextCss);\n\n // find the page component loader chunk\n const componentLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // find the app loader chunk\n const appLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // if we didn't find the component loader or app loader, throw an error\n if (!(componentLoaderChunk && appLoaderChunk)) {\n throw new Error(\n `Next.js client pages loader not found in bundle \"${bundle}\"`,\n );\n }\n\n // temporarily store the original __NEXT_P reference\n // this is required to avoid conflicts with the Next.js client pages loader\n // which uses the same global variable to store the page components\n const __NEXT_P_ORIGINAL = self.__NEXT_P;\n const selfOriginal = self;\n delete selfOriginal.__NEXT_P;\n\n // load the component and app loader chunks\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? componentLoaderChunk\n : `[${bundle}] ${componentLoaderChunk}`,\n );\n if (\n typeof appLoaderChunk === 'string' ||\n (typeof appLoaderChunk === 'number' && appLoaderChunk !== -1)\n ) {\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? appLoaderChunk\n : `[${bundle}] ${appLoaderChunk}`,\n );\n }\n\n // if we have the __NEXT_P global variable, we can extract the component and app\n if (self.__NEXT_P) {\n const [, componentLoader] = self.__NEXT_P[0] ?? [\n undefined,\n () => ({ default: null }),\n ];\n const [, appLoader] = self.__NEXT_P[2] ?? [\n undefined,\n () => ({\n default: null,\n }),\n ];\n const { default: Component } = componentLoader();\n const { default: App } = appLoader();\n\n // load the CSS files from the remote bundle\n const cssRE = /\\.s?css$/;\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {})\n .filter((id) => cssRE.test(id))\n .forEach((id) => {\n self.__remote_webpack_require__?.[bundle]?.(id);\n });\n\n Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {})\n .filter((path) => cssRE.test(path))\n .forEach((path) => {\n const id = self.__remote_webpack_module_map__?.[bundle]?.[path];\n if (id) {\n self.__remote_webpack_require__?.[bundle]?.(id);\n }\n });\n\n // if the styleContainer is provided, we need to move the styles to it\n if (styleContainer) {\n let node = nextCss.previousSibling;\n while (node && node !== lastNode) {\n styleContainer.appendChild(node);\n node = nextCss.previousSibling;\n }\n }\n\n // restore the original __NEXT_P reference\n delete self.__NEXT_P;\n self.__NEXT_P = __NEXT_P_ORIGINAL;\n\n // restore the original Next.js CSS loader\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.appendChild(nextCssOriginal);\n }\n\n return { Component, App };\n }\n\n return { Component: null, App: null };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACO,SAAS,sBACd,QACA,OACA,iBAAsD,SAAS,MAC/D;AAEA,QAAM,OAAO;AAsDb,QAAM,kBAAkB,SAAS,eAAe,0BAA0B;AAC1E,MAAI,iBAAiB;AACnB,oBAAgB,YAAY,YAAY,eAAe;AAAA,EACzD;AAGA,QAAM,UAAU,SAAS,cAAc,UAAU;AACjD,UAAQ,KAAK;AACb,QAAM,WACJ,SAAS,KAAK,WAAW,SAAS,KAAK,WAAW,SAAS,CAAC;AAC9D,WAAS,KAAK,YAAY,OAAO;AAGjC,QAAM,uBACJ,OAAO,KAA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AAI,EAAE;AAAA,MAChD;AAAA,IACF,CAAC;AAGH,QAAI,gBAAgB;AAClB,UAAI,OAAO,QAAQ;AACnB,aAAO,QAAQ,SAAS,UAAU;AAChC,uBAAe,YAAY,IAAI;AAC/B,eAAO,QAAQ;AAAA,MACjB;AAAA,IACF;AAGA,WAAO,KAAK;AACZ,SAAK,WAAW;AAGhB,QAAI,iBAAiB;AACnB,sBAAgB,YAAY,YAAY,eAAe;AAAA,IACzD;AAEA,WAAO,EAAE,WAAW,IAAI;AAAA,EAC1B;AAEA,SAAO,EAAE,WAAW,MAAM,KAAK,KAAK;AACtC;","names":[]}
1
+ {"version":3,"sources":["../../../src/shared/webpack/next-client-pages-loader.ts"],"sourcesContent":["// module loader for Next.js Pages Router\nexport function nextClientPagesLoader(\n bundle: string,\n route: string,\n styleContainer: HTMLHeadElement | ShadowRoot | null = document.head,\n) {\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string | number) => unknown) & {\n c?: Record<\n string | number,\n { id: string; parents: string[]; children: string[] }\n >;\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n type?: 'turbopack' | 'webpack';\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n // Next.js client pages loader reference storage\n __NEXT_P?: [\n (\n | [\n string,\n () => { default?: React.ComponentType<Record<string, unknown>> },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n ];\n // Next.js Pages Router CSS cache\n __remote_next_css__?: Record<string, ChildNode[]>;\n };\n\n // temporarily remove the original Next.js CSS loader\n const nextCssOriginal = document.querySelector(\n `[id=\"__next_css__DO_NOT_USE__\"]:not([data-bundle=\"${bundle}\"][data-route=\"${route}\"])`,\n );\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.removeChild(nextCssOriginal);\n }\n\n // create a new Next.js CSS loader element\n const nextCss = document.createElement('noscript');\n nextCss.id = '__next_css__DO_NOT_USE__';\n nextCss.setAttribute('data-bundle', bundle);\n nextCss.setAttribute('data-route', route);\n const nextCssEnd = document.createElement('noscript');\n nextCssEnd.id = '__next_css__DO_NOT_USE_END__';\n nextCssEnd.setAttribute('data-bundle', bundle);\n nextCssEnd.setAttribute('data-route', route);\n document.head.appendChild(nextCssEnd);\n document.head.appendChild(nextCss);\n\n // find the page component loader chunk\n const componentLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}!`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}!`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // find the app loader chunk\n const appLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // if we didn't find the component loader or app loader, throw an error\n if (!(componentLoaderChunk && appLoaderChunk)) {\n throw new Error(\n `Next.js client pages loader not found in bundle \"${bundle}\"`,\n );\n }\n\n // temporarily store the original __NEXT_P reference\n // this is required to avoid conflicts with the Next.js client pages loader\n // which uses the same global variable to store the page components\n const __NEXT_P_ORIGINAL = self.__NEXT_P;\n const selfOriginal = self;\n delete selfOriginal.__NEXT_P;\n\n // load the component and app loader chunks\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? componentLoaderChunk\n : `[${bundle}] ${componentLoaderChunk}`,\n );\n if (\n typeof appLoaderChunk === 'string' ||\n (typeof appLoaderChunk === 'number' && appLoaderChunk !== -1)\n ) {\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? appLoaderChunk\n : `[${bundle}] ${appLoaderChunk}`,\n );\n }\n\n // if we have the __NEXT_P global variable, we can extract the component and app\n if (self.__NEXT_P) {\n const [, componentLoader] = self.__NEXT_P[0] ?? [\n undefined,\n () => ({ default: null }),\n ];\n const [, appLoader] = self.__NEXT_P[2] ?? [\n undefined,\n () => ({\n default: null,\n }),\n ];\n const { default: Component } = componentLoader();\n const { default: App } = appLoader();\n\n if (!self.__remote_next_css__) {\n // eslint-disable-next-line camelcase\n self.__remote_next_css__ = {};\n }\n\n if (!self.__remote_next_css__[bundle]) {\n // load the CSS files from the remote bundle\n const cssRE = /\\.s?css$/;\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {})\n .filter((id) => cssRE.test(id))\n .forEach((id) => {\n self.__remote_webpack_require__?.[bundle]?.(id);\n });\n\n Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {})\n .filter((path) => cssRE.test(path))\n .forEach((path) => {\n const id = self.__remote_webpack_module_map__?.[bundle]?.[path];\n if (id) {\n self.__remote_webpack_require__?.[bundle]?.(id);\n }\n });\n\n const elements = [];\n let node = nextCss.previousSibling;\n while (node && node !== nextCssEnd) {\n elements.push(node);\n node.remove();\n node = nextCss.previousSibling;\n }\n self.__remote_next_css__[bundle] = elements;\n }\n\n // if the styleContainer is provided, we need to move the styles to it\n if (styleContainer) {\n const elements = self.__remote_next_css__[bundle];\n elements.forEach((el) => {\n styleContainer.appendChild(el.cloneNode(true));\n });\n } else {\n // if no styleContainer is provided, we need to move the styles back to the head\n const elements = self.__remote_next_css__[bundle];\n elements.forEach((el) => {\n document.head.appendChild(el);\n });\n }\n\n // restore the original __NEXT_P reference\n delete self.__NEXT_P;\n self.__NEXT_P = __NEXT_P_ORIGINAL;\n\n // restore the original Next.js CSS loader\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.appendChild(nextCssOriginal);\n }\n\n nextCss.remove();\n nextCssEnd.remove();\n\n return { Component, App };\n }\n\n return { Component: null, App: null };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACO,SAAS,sBACd,QACA,OACA,iBAAsD,SAAS,MAC/D;AAEA,QAAM,OAAO;AAwDb,QAAM,kBAAkB,SAAS;AAAA,IAC/B,qDAAqD,wBAAwB;AAAA,EAC/E;AACA,MAAI,iBAAiB;AACnB,oBAAgB,YAAY,YAAY,eAAe;AAAA,EACzD;AAGA,QAAM,UAAU,SAAS,cAAc,UAAU;AACjD,UAAQ,KAAK;AACb,UAAQ,aAAa,eAAe,MAAM;AAC1C,UAAQ,aAAa,cAAc,KAAK;AACxC,QAAM,aAAa,SAAS,cAAc,UAAU;AACpD,aAAW,KAAK;AAChB,aAAW,aAAa,eAAe,MAAM;AAC7C,aAAW,aAAa,cAAc,KAAK;AAC3C,WAAS,KAAK,YA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AAK,CAAC,CAAC,EAC3D,OAAO,CAAC,SAAS,MAAM,KAAK,IAAI,CAAC,EACjC,QAAQ,CAAC,SAAS;AACjB,cAAM,KAAK,KAAK,gCAAgC,MAAM,IAAI,IAAI;AAC9D,YAAI,IAAI;AACN,eAAK,6BAA6B,MAAM,IAAI,EAAE;AAAA,QAChD;AAAA,MACF,CAAC;AAEH,YAAM,WAAW,CAAC;AAClB,UAAI,OAAO,QAAQ;AACnB,aAAO,QAAQ,SAAS,YAAY;AAClC,iBAAS,KAAK,IAAI;AAClB,aAAK,OAAO;AACZ,eAAO,QAAQ;AAAA,MACjB;AACA,WAAK,oBAAoB,MAAM,IAAI;AAAA,IACrC;AAGA,QAAI,gBAAgB;AAClB,YAAM,WAAW,KAAK,oBAAoB,MAAM;AAChD,eAAS,QAAQ,CAAC,OAAO;AACvB,uBAAe,YAAY,GAAG,UAAU,IAAI,CAAC;AAAA,MAC/C,CAAC;AAAA,IACH,OAAO;AAEL,YAAM,WAAW,KAAK,oBAAoB,MAAM;AAChD,eAAS,QAAQ,CAAC,OAAO;AACvB,iBAAS,KAAK,YAAY,EAAE;AAAA,MAC9B,CAAC;AAAA,IACH;AAGA,WAAO,KAAK;AACZ,SAAK,WAAW;AAGhB,QAAI,iBAAiB;AACnB,sBAAgB,YAAY,YAAY,eAAe;AAAA,IACzD;AAEA,YAAQ,OAAO;AACf,eAAW,OAAO;AAElB,WAAO,EAAE,WAAW,IAAI;AAAA,EAC1B;AAEA,SAAO,EAAE,WAAW,MAAM,KAAK,KAAK;AACtC;","names":[]}
@@ -1,19 +1,27 @@
1
1
  function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
2
2
  const self = globalThis;
3
- const nextCssOriginal = document.getElementById("__next_css__DO_NOT_USE__");
3
+ const nextCssOriginal = document.querySelector(
4
+ `[id="__next_css__DO_NOT_USE__"]:not([data-bundle="${bundle}"][data-route="${route}"])`
5
+ );
4
6
  if (nextCssOriginal) {
5
7
  nextCssOriginal.parentNode?.removeChild(nextCssOriginal);
6
8
  }
7
9
  const nextCss = document.createElement("noscript");
8
10
  nextCss.id = "__next_css__DO_NOT_USE__";
9
- const lastNode = document.head.childNodes[document.head.childNodes.length - 1];
11
+ nextCss.setAttribute("data-bundle", bundle);
12
+ nextCss.setAttribute("data-route", route);
13
+ const nextCssEnd = document.createElement("noscript");
14
+ nextCssEnd.id = "__next_css__DO_NOT_USE_END__";
15
+ nextCssEnd.setAttribute("data-bundle", bundle);
16
+ nextCssEnd.setAttribute("data-route", route);
17
+ document.head.appendChild(nextCssEnd);
10
18
  document.head.appendChild(nextCss);
11
19
  const componentLoaderChunk = Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
12
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}`)
20
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
13
21
  ) ?? Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(
14
22
  (key) => key.includes("/next/dist/client/page-loader.js")
15
23
  ) ?? self.__remote_webpack_module_map__?.[bundle]?.[Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
16
- (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}`)
24
+ (key) => key.includes("/webpack/loaders/next-client-pages-loader.js") && key.includes(`page=${encodeURIComponent(route)}!`)
17
25
  ) ?? Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(
18
26
  (key) => key.includes("/next/dist/client/page-loader.js")
19
27
  ) ?? ""] ?? -1;
@@ -55,28 +63,47 @@ function nextClientPagesLoader(bundle, route, styleContainer = document.head) {
55
63
  ];
56
64
  const { default: Component } = componentLoader();
57
65
  const { default: App } = appLoader();
58
- const cssRE = /\.s?css$/;
59
- Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
60
- self.__remote_webpack_require__?.[bundle]?.(id);
61
- });
62
- Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {}).filter((path) => cssRE.test(path)).forEach((path) => {
63
- const id = self.__remote_webpack_module_map__?.[bundle]?.[path];
64
- if (id) {
66
+ if (!self.__remote_next_css__) {
67
+ self.__remote_next_css__ = {};
68
+ }
69
+ if (!self.__remote_next_css__[bundle]) {
70
+ const cssRE = /\.s?css$/;
71
+ Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).filter((id) => cssRE.test(id)).forEach((id) => {
65
72
  self.__remote_webpack_require__?.[bundle]?.(id);
66
- }
67
- });
68
- if (styleContainer) {
73
+ });
74
+ Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {}).filter((path) => cssRE.test(path)).forEach((path) => {
75
+ const id = self.__remote_webpack_module_map__?.[bundle]?.[path];
76
+ if (id) {
77
+ self.__remote_webpack_require__?.[bundle]?.(id);
78
+ }
79
+ });
80
+ const elements = [];
69
81
  let node = nextCss.previousSibling;
70
- while (node && node !== lastNode) {
71
- styleContainer.appendChild(node);
82
+ while (node && node !== nextCssEnd) {
83
+ elements.push(node);
84
+ node.remove();
72
85
  node = nextCss.previousSibling;
73
86
  }
87
+ self.__remote_next_css__[bundle] = elements;
88
+ }
89
+ if (styleContainer) {
90
+ const elements = self.__remote_next_css__[bundle];
91
+ elements.forEach((el) => {
92
+ styleContainer.appendChild(el.cloneNode(true));
93
+ });
94
+ } else {
95
+ const elements = self.__remote_next_css__[bundle];
96
+ elements.forEach((el) => {
97
+ document.head.appendChild(el);
98
+ });
74
99
  }
75
100
  delete self.__NEXT_P;
76
101
  self.__NEXT_P = __NEXT_P_ORIGINAL;
77
102
  if (nextCssOriginal) {
78
103
  nextCssOriginal.parentNode?.appendChild(nextCssOriginal);
79
104
  }
105
+ nextCss.remove();
106
+ nextCssEnd.remove();
80
107
  return { Component, App };
81
108
  }
82
109
  return { Component: null, App: null };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/shared/webpack/next-client-pages-loader.ts"],"sourcesContent":["// module loader for Next.js Pages Router\nexport function nextClientPagesLoader(\n bundle: string,\n route: string,\n styleContainer: HTMLHeadElement | ShadowRoot | null = document.head,\n) {\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string | number) => unknown) & {\n c?: Record<\n string | number,\n { id: string; parents: string[]; children: string[] }\n >;\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n type?: 'turbopack' | 'webpack';\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n // Next.js client pages loader reference storage\n __NEXT_P?: [\n (\n | [\n string,\n () => { default?: React.ComponentType<Record<string, unknown>> },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n ];\n };\n\n // temporarily remove the original Next.js CSS loader\n const nextCssOriginal = document.getElementById('__next_css__DO_NOT_USE__');\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.removeChild(nextCssOriginal);\n }\n\n // create a new Next.js CSS loader element\n const nextCss = document.createElement('noscript');\n nextCss.id = '__next_css__DO_NOT_USE__';\n const lastNode =\n document.head.childNodes[document.head.childNodes.length - 1];\n document.head.appendChild(nextCss);\n\n // find the page component loader chunk\n const componentLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // find the app loader chunk\n const appLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // if we didn't find the component loader or app loader, throw an error\n if (!(componentLoaderChunk && appLoaderChunk)) {\n throw new Error(\n `Next.js client pages loader not found in bundle \"${bundle}\"`,\n );\n }\n\n // temporarily store the original __NEXT_P reference\n // this is required to avoid conflicts with the Next.js client pages loader\n // which uses the same global variable to store the page components\n const __NEXT_P_ORIGINAL = self.__NEXT_P;\n const selfOriginal = self;\n delete selfOriginal.__NEXT_P;\n\n // load the component and app loader chunks\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? componentLoaderChunk\n : `[${bundle}] ${componentLoaderChunk}`,\n );\n if (\n typeof appLoaderChunk === 'string' ||\n (typeof appLoaderChunk === 'number' && appLoaderChunk !== -1)\n ) {\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? appLoaderChunk\n : `[${bundle}] ${appLoaderChunk}`,\n );\n }\n\n // if we have the __NEXT_P global variable, we can extract the component and app\n if (self.__NEXT_P) {\n const [, componentLoader] = self.__NEXT_P[0] ?? [\n undefined,\n () => ({ default: null }),\n ];\n const [, appLoader] = self.__NEXT_P[2] ?? [\n undefined,\n () => ({\n default: null,\n }),\n ];\n const { default: Component } = componentLoader();\n const { default: App } = appLoader();\n\n // load the CSS files from the remote bundle\n const cssRE = /\\.s?css$/;\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {})\n .filter((id) => cssRE.test(id))\n .forEach((id) => {\n self.__remote_webpack_require__?.[bundle]?.(id);\n });\n\n Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {})\n .filter((path) => cssRE.test(path))\n .forEach((path) => {\n const id = self.__remote_webpack_module_map__?.[bundle]?.[path];\n if (id) {\n self.__remote_webpack_require__?.[bundle]?.(id);\n }\n });\n\n // if the styleContainer is provided, we need to move the styles to it\n if (styleContainer) {\n let node = nextCss.previousSibling;\n while (node && node !== lastNode) {\n styleContainer.appendChild(node);\n node = nextCss.previousSibling;\n }\n }\n\n // restore the original __NEXT_P reference\n delete self.__NEXT_P;\n self.__NEXT_P = __NEXT_P_ORIGINAL;\n\n // restore the original Next.js CSS loader\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.appendChild(nextCssOriginal);\n }\n\n return { Component, App };\n }\n\n return { Component: null, App: null };\n}\n"],"mappings":"AACO,SAAS,sBACd,QACA,OACA,iBAAsD,SAAS,MAC/D;AAEA,QAAM,OAAO;AAsDb,QAAM,kBAAkB,SAAS,eAAe,0BAA0B;AAC1E,MAAI,iBAAiB;AACnB,oBAAgB,YAAY,YAAY,eAAe;AAAA,EACzD;AAGA,QAAM,UAAU,SAAS,cAAc,UAAU;AACjD,UAAQ,KAAK;AACb,QAAM,WACJ,SAAS,KAAK,WAAW,SAAS,KAAK,WAAW,SAAS,CAAC;AAC9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AAI,IAAI;AAC9D,UAAI,IAAI;AACN,aAAK,6BAA6B,MAAM,IAAI,EAAE;AAAA,MAChD;AAAA,IACF,CAAC;AAGH,QAAI,gBAAgB;AAClB,UAAI,OAAO,QAAQ;AACnB,aAAO,QAAQ,SAAS,UAAU;AAChC,uBAAe,YAAY,IAAI;AAC/B,eAAO,QAAQ;AAAA,MACjB;AAAA,IACF;AAGA,WAAO,KAAK;AACZ,SAAK,WAAW;AAGhB,QAAI,iBAAiB;AACnB,sBAAgB,YAAY,YAAY,eAAe;AAAA,IACzD;AAEA,WAAO,EAAE,WAAW,IAAI;AAAA,EAC1B;AAEA,SAAO,EAAE,WAAW,MAAM,KAAK,KAAK;AACtC;","names":[]}
1
+ {"version":3,"sources":["../../../src/shared/webpack/next-client-pages-loader.ts"],"sourcesContent":["// module loader for Next.js Pages Router\nexport function nextClientPagesLoader(\n bundle: string,\n route: string,\n styleContainer: HTMLHeadElement | ShadowRoot | null = document.head,\n) {\n // make a typed reference to the global scope\n const self = globalThis as typeof globalThis & {\n // webpack remote module loading function scoped for each bundle\n __remote_webpack_require__?: Record<\n string,\n ((remoteId: string | number) => unknown) & {\n c?: Record<\n string | number,\n { id: string; parents: string[]; children: string[] }\n >;\n m?: Record<string | number, (module: { exports: unknown }) => void>;\n type?: 'turbopack' | 'webpack';\n }\n >;\n // webpack module map for each bundle used in production builds\n __remote_webpack_module_map__?: Record<string, Record<string, number>>;\n // Next.js client pages loader reference storage\n __NEXT_P?: [\n (\n | [\n string,\n () => { default?: React.ComponentType<Record<string, unknown>> },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n (\n | [\n string,\n () => {\n default?: React.ComponentType<\n {\n Component: React.ComponentType<Record<string, unknown>>;\n } & Record<string, unknown>\n >;\n },\n ]\n | undefined\n ),\n ];\n // Next.js Pages Router CSS cache\n __remote_next_css__?: Record<string, ChildNode[]>;\n };\n\n // temporarily remove the original Next.js CSS loader\n const nextCssOriginal = document.querySelector(\n `[id=\"__next_css__DO_NOT_USE__\"]:not([data-bundle=\"${bundle}\"][data-route=\"${route}\"])`,\n );\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.removeChild(nextCssOriginal);\n }\n\n // create a new Next.js CSS loader element\n const nextCss = document.createElement('noscript');\n nextCss.id = '__next_css__DO_NOT_USE__';\n nextCss.setAttribute('data-bundle', bundle);\n nextCss.setAttribute('data-route', route);\n const nextCssEnd = document.createElement('noscript');\n nextCssEnd.id = '__next_css__DO_NOT_USE_END__';\n nextCssEnd.setAttribute('data-bundle', bundle);\n nextCssEnd.setAttribute('data-route', route);\n document.head.appendChild(nextCssEnd);\n document.head.appendChild(nextCss);\n\n // find the page component loader chunk\n const componentLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}!`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=${encodeURIComponent(route)}!`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // find the app loader chunk\n const appLoaderChunk =\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n self.__remote_webpack_module_map__?.[bundle]?.[\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) =>\n key.includes('/webpack/loaders/next-client-pages-loader.js') &&\n key.includes(`page=%2F_app`),\n ) ??\n Object.keys(self.__remote_webpack_module_map__[bundle] ?? {}).find(\n (key) => key.includes('/next/dist/client/page-loader.js'),\n ) ??\n ''\n ] ??\n -1;\n\n // if we didn't find the component loader or app loader, throw an error\n if (!(componentLoaderChunk && appLoaderChunk)) {\n throw new Error(\n `Next.js client pages loader not found in bundle \"${bundle}\"`,\n );\n }\n\n // temporarily store the original __NEXT_P reference\n // this is required to avoid conflicts with the Next.js client pages loader\n // which uses the same global variable to store the page components\n const __NEXT_P_ORIGINAL = self.__NEXT_P;\n const selfOriginal = self;\n delete selfOriginal.__NEXT_P;\n\n // load the component and app loader chunks\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? componentLoaderChunk\n : `[${bundle}] ${componentLoaderChunk}`,\n );\n if (\n typeof appLoaderChunk === 'string' ||\n (typeof appLoaderChunk === 'number' && appLoaderChunk !== -1)\n ) {\n self.__remote_webpack_require__?.[bundle]?.(\n self.__remote_webpack_require__[bundle].type !== 'turbopack'\n ? appLoaderChunk\n : `[${bundle}] ${appLoaderChunk}`,\n );\n }\n\n // if we have the __NEXT_P global variable, we can extract the component and app\n if (self.__NEXT_P) {\n const [, componentLoader] = self.__NEXT_P[0] ?? [\n undefined,\n () => ({ default: null }),\n ];\n const [, appLoader] = self.__NEXT_P[2] ?? [\n undefined,\n () => ({\n default: null,\n }),\n ];\n const { default: Component } = componentLoader();\n const { default: App } = appLoader();\n\n if (!self.__remote_next_css__) {\n // eslint-disable-next-line camelcase\n self.__remote_next_css__ = {};\n }\n\n if (!self.__remote_next_css__[bundle]) {\n // load the CSS files from the remote bundle\n const cssRE = /\\.s?css$/;\n Object.keys(self.__remote_webpack_require__?.[bundle]?.m ?? {})\n .filter((id) => cssRE.test(id))\n .forEach((id) => {\n self.__remote_webpack_require__?.[bundle]?.(id);\n });\n\n Object.keys(self.__remote_webpack_module_map__?.[bundle] ?? {})\n .filter((path) => cssRE.test(path))\n .forEach((path) => {\n const id = self.__remote_webpack_module_map__?.[bundle]?.[path];\n if (id) {\n self.__remote_webpack_require__?.[bundle]?.(id);\n }\n });\n\n const elements = [];\n let node = nextCss.previousSibling;\n while (node && node !== nextCssEnd) {\n elements.push(node);\n node.remove();\n node = nextCss.previousSibling;\n }\n self.__remote_next_css__[bundle] = elements;\n }\n\n // if the styleContainer is provided, we need to move the styles to it\n if (styleContainer) {\n const elements = self.__remote_next_css__[bundle];\n elements.forEach((el) => {\n styleContainer.appendChild(el.cloneNode(true));\n });\n } else {\n // if no styleContainer is provided, we need to move the styles back to the head\n const elements = self.__remote_next_css__[bundle];\n elements.forEach((el) => {\n document.head.appendChild(el);\n });\n }\n\n // restore the original __NEXT_P reference\n delete self.__NEXT_P;\n self.__NEXT_P = __NEXT_P_ORIGINAL;\n\n // restore the original Next.js CSS loader\n if (nextCssOriginal) {\n nextCssOriginal.parentNode?.appendChild(nextCssOriginal);\n }\n\n nextCss.remove();\n nextCssEnd.remove();\n\n return { Component, App };\n }\n\n return { Component: null, App: null };\n}\n"],"mappings":"AACO,SAAS,sBACd,QACA,OACA,iBAAsD,SAAS,MAC/D;AAEA,QAAM,OAAO;AAwDb,QAAM,kBAAkB,SAAS;AAAA,IAC/B,qDAAqD,wBAAwB;AAAA,EAC/E;AACA,MAAI,iBAAiB;AACnB,oBAAgB,YAAY,YAAY,eAAe;AAAA,EACzD;AAGA,QAAM,UAAU,SAAS,cAAc,UAAU;AACjD,UAAQ,KAAK;AACb,UAAQ,aAAa,eAAe,MAAM;AAC1C,UAAQ,aAAa,cAAc,KAAK;AACxC,QAAM,aAAa,SAAS,cAAc,UAAU;AACpD,aAAW,KAAK;AAChB,aAAW,aAAa,eAAe,MAAM;AAC7C,aAAW,aAAa,cAAc,KAAK;AAC3C,WAAS,KA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AAM,KAAK,CAAC,CAAC,EAC3D,OAAO,CAAC,SAAS,MAAM,KAAK,IAAI,CAAC,EACjC,QAAQ,CAAC,SAAS;AACjB,cAAM,KAAK,KAAK,gCAAgC,MAAM,IAAI,IAAI;AAC9D,YAAI,IAAI;AACN,eAAK,6BAA6B,MAAM,IAAI,EAAE;AAAA,QAChD;AAAA,MACF,CAAC;AAEH,YAAM,WAAW,CAAC;AAClB,UAAI,OAAO,QAAQ;AACnB,aAAO,QAAQ,SAAS,YAAY;AAClC,iBAAS,KAAK,IAAI;AAClB,aAAK,OAAO;AACZ,eAAO,QAAQ;AAAA,MACjB;AACA,WAAK,oBAAoB,MAAM,IAAI;AAAA,IACrC;AAGA,QAAI,gBAAgB;AAClB,YAAM,WAAW,KAAK,oBAAoB,MAAM;AAChD,eAAS,QAAQ,CAAC,OAAO;AACvB,uBAAe,YAAY,GAAG,UAAU,IAAI,CAAC;AAAA,MAC/C,CAAC;AAAA,IACH,OAAO;AAEL,YAAM,WAAW,KAAK,oBAAoB,MAAM;AAChD,eAAS,QAAQ,CAAC,OAAO;AACvB,iBAAS,KAAK,YAAY,EAAE;AAAA,MAC9B,CAAC;AAAA,IACH;AAGA,WAAO,KAAK;AACZ,SAAK,WAAW;AAGhB,QAAI,iBAAiB;AACnB,sBAAgB,YAAY,YAAY,eAAe;AAAA,IACzD;AAEA,YAAQ,OAAO;AACf,eAAW,OAAO;AAElB,WAAO,EAAE,WAAW,IAAI;AAAA,EAC1B;AAEA,SAAO,EAAE,WAAW,MAAM,KAAK,KAAK;AACtC;","names":[]}
@@ -29,7 +29,7 @@ function corsFromOptions(options) {
29
29
  const ALLOWED_ORIGINS = (process.env.REMOTE_COMPONENTS_ALLOWED_ORIGINS || (Array.isArray(options?.origin) ? options.origin.join(",") : options?.origin) || "*").split(",").map((origin) => origin.trim());
30
30
  const CORS_HEADERS = {
31
31
  "Access-Control-Allow-Methods": process.env.REMOTE_COMPONENTS_ALLOW_METHODS || (Array.isArray(options?.method) ? options.method.map((m) => m.trim()).join(",") : options?.method) || "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
32
- "Access-Control-Allow-Headers": `${process.env.REMOTE_COMPONENTS_ALLOW_HEADERS || (Array.isArray(options?.headers) ? options.headers.map((h) => h.trim()).join(",") : options?.headers) || "Content-Type,Authorization"},vercel-remote-component-url`,
32
+ "Access-Control-Allow-Headers": process.env.REMOTE_COMPONENTS_ALLOW_HEADERS || (Array.isArray(options?.headers) ? options.headers.map((h) => h.trim()).join(",") : options?.headers) || "Content-Type,Authorization",
33
33
  ...process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || options?.credentials ? {
34
34
  "Access-Control-Allow-Credentials": process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || "true"
35
35
  } : {}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/next/middleware/index.ts"],"sourcesContent":["import { type NextRequest, NextResponse } from 'next/server';\n\nexport interface RemoteComponentMiddlewareOptions {\n cors?: {\n origin?: string | string[];\n method?: string | string[];\n headers?: string | string[];\n credentials?: boolean;\n };\n}\n\nfunction corsFromOptions(options?: RemoteComponentMiddlewareOptions['cors']) {\n const ALLOWED_ORIGINS = (\n process.env.REMOTE_COMPONENTS_ALLOWED_ORIGINS ||\n (Array.isArray(options?.origin)\n ? options.origin.join(',')\n : options?.origin) ||\n '*'\n )\n .split(',')\n .map((origin) => origin.trim());\n\n const CORS_HEADERS = {\n 'Access-Control-Allow-Methods':\n process.env.REMOTE_COMPONENTS_ALLOW_METHODS ||\n (Array.isArray(options?.method)\n ? options.method.map((m) => m.trim()).join(',')\n : options?.method) ||\n 'GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS',\n 'Access-Control-Allow-Headers': `${\n process.env.REMOTE_COMPONENTS_ALLOW_HEADERS ||\n (Array.isArray(options?.headers)\n ? options.headers.map((h) => h.trim()).join(',')\n : options?.headers) ||\n 'Content-Type,Authorization'\n },vercel-remote-component-url`,\n ...(process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || options?.credentials\n ? {\n 'Access-Control-Allow-Credentials':\n process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || 'true',\n }\n : {}),\n };\n\n return { ALLOWED_ORIGINS, CORS_HEADERS };\n}\n\n/**\n * This middleware is used to handle CORS and other remote component related tasks.\n * It can be used to wrap a Next.js middleware function to add CORS headers and handle preflight requests.\n *\n * @param middleware - The Next.js middleware function to wrap.\n * @param options - Optional configuration for handling remote components.\n * @returns A Next.js middleware function that handles CORS and preflight requests\n */\nexport function withRemoteComponents(\n middleware?: (request: NextRequest) => NextResponse | Promise<NextResponse>,\n options?: RemoteComponentMiddlewareOptions,\n) {\n return async (request: NextRequest) => {\n const { ALLOWED_ORIGINS, CORS_HEADERS } = corsFromOptions(options?.cors);\n\n const origin = request.headers.get('origin') ?? '';\n const isAllowed =\n ALLOWED_ORIGINS.includes('*') || ALLOWED_ORIGINS.includes(origin);\n\n // Handle preflight\n if (request.method === 'OPTIONS') {\n return new Response(null, {\n status: 200,\n headers: isAllowed\n ? {\n 'Access-Control-Allow-Origin': origin,\n ...CORS_HEADERS,\n }\n : {},\n });\n }\n\n // For all other requests, continue and attach CORS\n const response =\n typeof middleware === 'function'\n ? await middleware(request)\n : NextResponse.next();\n\n if (isAllowed) {\n response.headers.set('Access-Control-Allow-Origin', origin);\n }\n\n Object.entries(CORS_HEADERS).forEach(([k, v]) =>\n response.headers.set(k, v),\n );\n\n return response;\n };\n}\n\n/**\n * This configuration is used to specify the paths that the middleware should match.\n * It matches all paths by default.\n */\nexport const config = {\n matcher: '/:path*',\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA+C;AAW/C,SAAS,gBAAgB,SAAoD;AAC3E,QAAM,mBACJ,QAAQ,IAAI,sCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,KAAK,GAAG,IACvB,SAAS,WACb,KAEC,MAAM,GAA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A,WAAO;AAAA,EACT;AACF;AAMO,IAAM,SAAS;AAAA,EACpB,SAAS;AACX;","names":[]}
1
+ {"version":3,"sources":["../../src/next/middleware/index.ts"],"sourcesContent":["import { type NextRequest, NextResponse } from 'next/server';\n\nexport interface RemoteComponentMiddlewareOptions {\n cors?: {\n origin?: string | string[];\n method?: string | string[];\n headers?: string | string[];\n credentials?: boolean;\n };\n}\n\nfunction corsFromOptions(options?: RemoteComponentMiddlewareOptions['cors']) {\n const ALLOWED_ORIGINS = (\n process.env.REMOTE_COMPONENTS_ALLOWED_ORIGINS ||\n (Array.isArray(options?.origin)\n ? options.origin.join(',')\n : options?.origin) ||\n '*'\n )\n .split(',')\n .map((origin) => origin.trim());\n\n const CORS_HEADERS = {\n 'Access-Control-Allow-Methods':\n process.env.REMOTE_COMPONENTS_ALLOW_METHODS ||\n (Array.isArray(options?.method)\n ? options.method.map((m) => m.trim()).join(',')\n : options?.method) ||\n 'GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS',\n 'Access-Control-Allow-Headers':\n process.env.REMOTE_COMPONENTS_ALLOW_HEADERS ||\n (Array.isArray(options?.headers)\n ? options.headers.map((h) => h.trim()).join(',')\n : options?.headers) ||\n 'Content-Type,Authorization',\n ...(process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || options?.credentials\n ? {\n 'Access-Control-Allow-Credentials':\n process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || 'true',\n }\n : {}),\n };\n\n return { ALLOWED_ORIGINS, CORS_HEADERS };\n}\n\n/**\n * This middleware is used to handle CORS and other remote component related tasks.\n * It can be used to wrap a Next.js middleware function to add CORS headers and handle preflight requests.\n *\n * @param middleware - The Next.js middleware function to wrap.\n * @param options - Optional configuration for handling remote components.\n * @returns A Next.js middleware function that handles CORS and preflight requests\n */\nexport function withRemoteComponents(\n middleware?: (request: NextRequest) => NextResponse | Promise<NextResponse>,\n options?: RemoteComponentMiddlewareOptions,\n) {\n return async (request: NextRequest) => {\n const { ALLOWED_ORIGINS, CORS_HEADERS } = corsFromOptions(options?.cors);\n\n const origin = request.headers.get('origin') ?? '';\n const isAllowed =\n ALLOWED_ORIGINS.includes('*') || ALLOWED_ORIGINS.includes(origin);\n\n // Handle preflight\n if (request.method === 'OPTIONS') {\n return new Response(null, {\n status: 200,\n headers: isAllowed\n ? {\n 'Access-Control-Allow-Origin': origin,\n ...CORS_HEADERS,\n }\n : {},\n });\n }\n\n // For all other requests, continue and attach CORS\n const response =\n typeof middleware === 'function'\n ? await middleware(request)\n : NextResponse.next();\n\n if (isAllowed) {\n response.headers.set('Access-Control-Allow-Origin', origin);\n }\n\n Object.entries(CORS_HEADERS).forEach(([k, v]) =>\n response.headers.set(k, v),\n );\n\n return response;\n };\n}\n\n/**\n * This configuration is used to specify the paths that the middleware should match.\n * It matches all paths by default.\n */\nexport const config = {\n matcher: '/:path*',\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA+C;AAW/C,SAAS,gBAAgB,SAAoD;AAC3E,QAAM,mBACJ,QAAQ,IAAI,sCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,KAAK,GAAG,IACvB,SAAS,WACb,KAEC,MAAM,GAAG,EACT,IAAI,CAAC,WAAW,OAAO,KAAK,CAAC;AAEhC,QAAM,eAAe;AAAA,IACnB,gCACE,QAAQ,IAAI,oCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAC5C,SAAS,WACb;AAAA,IACF,gCACE,QAAQ,IAAI,oCACX,MAAM,QAAQ,SAAS,OAAO,IAC3B,QAAQ,QAAQ,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAC7C,SAAS,YACb;AAAA,IACF,GAAI,QAAQ,IAAI,uCAAuC,SAAS,cAC5D;AAAA,MACE,oCACE,QAAQ,IAAI,uCAAuC;AAAA,IACvD,IACA,CAAC;AAAA,EACP;AAEA,SAAO,EAAE,iBAAiB,aAAa;AACzC;AAUO,SAAS,qBACd,YACA,SACA;AACA,SAAO,OAAO,YAAyB;AACrC,UAAM,EAAE,iBAAiB,aAAa,IAAI,gBAAgB,SAAS,IAAI;AAEvE,UAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ,KAAK;AAChD,UAAM,YACJ,gBAAgB,SAAS,GAAG,KAAK,gBAAgB,SAAS,MAAM;AAGlE,QAAI,QAAQ,WAAW,WAAW;AAChC,aAAO,IAAI,SAAS,MAAM;AAAA,QACxB,QAAQ;AAAA,QACR,SAAS,YACL;AAAA,UACE,+BAA+B;AAAA,UAC/B,GAAG;AAAA,QACL,IACA,CAAC;AAAA,MACP,CAAC;AAAA,IACH;AAGA,UAAM,WACJ,OAAO,eAAe,aAClB,MAAM,WAAW,OAAO,IACxB,2BAAa,KAAK;AAExB,QAAI,WAAW;AACb,eAAS,QAAQ,IAAI,+BAA+B,MAAM;AAAA,IAC5D;AAEA,WAAO,QAAQ,YAAY,EAAE;AAAA,MAAQ,CAAC,CAAC,GAAG,CAAC,MACzC,SAAS,QAAQ,IAAI,GAAG,CAAC;AAAA,IAC3B;AAEA,WAAO;AAAA,EACT;AACF;AAMO,IAAM,SAAS;AAAA,EACpB,SAAS;AACX;","names":[]}
@@ -4,7 +4,7 @@ function corsFromOptions(options) {
4
4
  const ALLOWED_ORIGINS = (process.env.REMOTE_COMPONENTS_ALLOWED_ORIGINS || (Array.isArray(options?.origin) ? options.origin.join(",") : options?.origin) || "*").split(",").map((origin) => origin.trim());
5
5
  const CORS_HEADERS = {
6
6
  "Access-Control-Allow-Methods": process.env.REMOTE_COMPONENTS_ALLOW_METHODS || (Array.isArray(options?.method) ? options.method.map((m) => m.trim()).join(",") : options?.method) || "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
7
- "Access-Control-Allow-Headers": `${process.env.REMOTE_COMPONENTS_ALLOW_HEADERS || (Array.isArray(options?.headers) ? options.headers.map((h) => h.trim()).join(",") : options?.headers) || "Content-Type,Authorization"},vercel-remote-component-url`,
7
+ "Access-Control-Allow-Headers": process.env.REMOTE_COMPONENTS_ALLOW_HEADERS || (Array.isArray(options?.headers) ? options.headers.map((h) => h.trim()).join(",") : options?.headers) || "Content-Type,Authorization",
8
8
  ...process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || options?.credentials ? {
9
9
  "Access-Control-Allow-Credentials": process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || "true"
10
10
  } : {}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/next/middleware/index.ts"],"sourcesContent":["import { type NextRequest, NextResponse } from 'next/server';\n\nexport interface RemoteComponentMiddlewareOptions {\n cors?: {\n origin?: string | string[];\n method?: string | string[];\n headers?: string | string[];\n credentials?: boolean;\n };\n}\n\nfunction corsFromOptions(options?: RemoteComponentMiddlewareOptions['cors']) {\n const ALLOWED_ORIGINS = (\n process.env.REMOTE_COMPONENTS_ALLOWED_ORIGINS ||\n (Array.isArray(options?.origin)\n ? options.origin.join(',')\n : options?.origin) ||\n '*'\n )\n .split(',')\n .map((origin) => origin.trim());\n\n const CORS_HEADERS = {\n 'Access-Control-Allow-Methods':\n process.env.REMOTE_COMPONENTS_ALLOW_METHODS ||\n (Array.isArray(options?.method)\n ? options.method.map((m) => m.trim()).join(',')\n : options?.method) ||\n 'GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS',\n 'Access-Control-Allow-Headers': `${\n process.env.REMOTE_COMPONENTS_ALLOW_HEADERS ||\n (Array.isArray(options?.headers)\n ? options.headers.map((h) => h.trim()).join(',')\n : options?.headers) ||\n 'Content-Type,Authorization'\n },vercel-remote-component-url`,\n ...(process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || options?.credentials\n ? {\n 'Access-Control-Allow-Credentials':\n process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || 'true',\n }\n : {}),\n };\n\n return { ALLOWED_ORIGINS, CORS_HEADERS };\n}\n\n/**\n * This middleware is used to handle CORS and other remote component related tasks.\n * It can be used to wrap a Next.js middleware function to add CORS headers and handle preflight requests.\n *\n * @param middleware - The Next.js middleware function to wrap.\n * @param options - Optional configuration for handling remote components.\n * @returns A Next.js middleware function that handles CORS and preflight requests\n */\nexport function withRemoteComponents(\n middleware?: (request: NextRequest) => NextResponse | Promise<NextResponse>,\n options?: RemoteComponentMiddlewareOptions,\n) {\n return async (request: NextRequest) => {\n const { ALLOWED_ORIGINS, CORS_HEADERS } = corsFromOptions(options?.cors);\n\n const origin = request.headers.get('origin') ?? '';\n const isAllowed =\n ALLOWED_ORIGINS.includes('*') || ALLOWED_ORIGINS.includes(origin);\n\n // Handle preflight\n if (request.method === 'OPTIONS') {\n return new Response(null, {\n status: 200,\n headers: isAllowed\n ? {\n 'Access-Control-Allow-Origin': origin,\n ...CORS_HEADERS,\n }\n : {},\n });\n }\n\n // For all other requests, continue and attach CORS\n const response =\n typeof middleware === 'function'\n ? await middleware(request)\n : NextResponse.next();\n\n if (isAllowed) {\n response.headers.set('Access-Control-Allow-Origin', origin);\n }\n\n Object.entries(CORS_HEADERS).forEach(([k, v]) =>\n response.headers.set(k, v),\n );\n\n return response;\n };\n}\n\n/**\n * This configuration is used to specify the paths that the middleware should match.\n * It matches all paths by default.\n */\nexport const config = {\n matcher: '/:path*',\n};\n"],"mappings":";AAAA,SAA2B,oBAAoB;AAW/C,SAAS,gBAAgB,SAAoD;AAC3E,QAAM,mBACJ,QAAQ,IAAI,sCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,KAAK,GAAG,IACvB,SAAS,WACb,KAEC,MAAM,GAAG,EACT,IAAI,CAAC,WAAW,OAAO,KAAK,CAAC;AAEhC,QAAM,eAAe;AAAA,IACnB,gCACE,QAAQ,IAAI,oCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAC5C,SAAS,WACb;AAAA,IACF,gCAAgC,GAC9B,QAAQ,IAAI,oCACX,MAAM,QAAQ,SAAS,OAAO,IAC3B,QAAQ,QAAQ,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAC7C,SAAS,YACb;AAAA,IAEF,GAAI,QAAQ,IAAI,uCAAuC,SAAS,cAC5D;AAAA,MACE,oCACE,QAAQ,IAAI,uCAAuC;AAAA,IACvD,IACA,CAAC;AAAA,EACP;AAEA,SAAO,EAAE,iBAAiB,aAAa;AACzC;AAUO,SAAS,qBACd,YACA,SACA;AACA,SAAO,OAAO,YAAyB;AACrC,UAAM,EAAE,iBAAiB,aAAa,IAAI,gBAAgB,SAAS,IAAI;AAEvE,UAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ,KAAK;AAChD,UAAM,YACJ,gBAAgB,SAAS,GAAG,KAAK,gBAAgB,SAAS,MAAM;AAGlE,QAAI,QAAQ,WAAW,WAAW;AAChC,aAAO,IAAI,SAAS,MAAM;AAAA,QACxB,QAAQ;AAAA,QACR,SAAS,YACL;AAAA,UACE,+BAA+B;AAAA,UAC/B,GAAG;AAAA,QACL,IACA,CAAC;AAAA,MACP,CAAC;AAAA,IACH;AAGA,UAAM,WACJ,OAAO,eAAe,aAClB,MAAM,WAAW,OAAO,IACxB,aAAa,KAAK;AAExB,QAAI,WAAW;AACb,eAAS,QAAQ,IAAI,+BAA+B,MAAM;AAAA,IAC5D;AAEA,WAAO,QAAQ,YAAY,EAAE;AAAA,MAAQ,CAAC,CAAC,GAAG,CAAC,MACzC,SAAS,QAAQ,IAAI,GAAG,CAAC;AAAA,IAC3B;AAEA,WAAO;AAAA,EACT;AACF;AAMO,IAAM,SAAS;AAAA,EACpB,SAAS;AACX;","names":[]}
1
+ {"version":3,"sources":["../../src/next/middleware/index.ts"],"sourcesContent":["import { type NextRequest, NextResponse } from 'next/server';\n\nexport interface RemoteComponentMiddlewareOptions {\n cors?: {\n origin?: string | string[];\n method?: string | string[];\n headers?: string | string[];\n credentials?: boolean;\n };\n}\n\nfunction corsFromOptions(options?: RemoteComponentMiddlewareOptions['cors']) {\n const ALLOWED_ORIGINS = (\n process.env.REMOTE_COMPONENTS_ALLOWED_ORIGINS ||\n (Array.isArray(options?.origin)\n ? options.origin.join(',')\n : options?.origin) ||\n '*'\n )\n .split(',')\n .map((origin) => origin.trim());\n\n const CORS_HEADERS = {\n 'Access-Control-Allow-Methods':\n process.env.REMOTE_COMPONENTS_ALLOW_METHODS ||\n (Array.isArray(options?.method)\n ? options.method.map((m) => m.trim()).join(',')\n : options?.method) ||\n 'GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS',\n 'Access-Control-Allow-Headers':\n process.env.REMOTE_COMPONENTS_ALLOW_HEADERS ||\n (Array.isArray(options?.headers)\n ? options.headers.map((h) => h.trim()).join(',')\n : options?.headers) ||\n 'Content-Type,Authorization',\n ...(process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || options?.credentials\n ? {\n 'Access-Control-Allow-Credentials':\n process.env.REMOTE_COMPONENTS_ALLOW_CREDENTIALS || 'true',\n }\n : {}),\n };\n\n return { ALLOWED_ORIGINS, CORS_HEADERS };\n}\n\n/**\n * This middleware is used to handle CORS and other remote component related tasks.\n * It can be used to wrap a Next.js middleware function to add CORS headers and handle preflight requests.\n *\n * @param middleware - The Next.js middleware function to wrap.\n * @param options - Optional configuration for handling remote components.\n * @returns A Next.js middleware function that handles CORS and preflight requests\n */\nexport function withRemoteComponents(\n middleware?: (request: NextRequest) => NextResponse | Promise<NextResponse>,\n options?: RemoteComponentMiddlewareOptions,\n) {\n return async (request: NextRequest) => {\n const { ALLOWED_ORIGINS, CORS_HEADERS } = corsFromOptions(options?.cors);\n\n const origin = request.headers.get('origin') ?? '';\n const isAllowed =\n ALLOWED_ORIGINS.includes('*') || ALLOWED_ORIGINS.includes(origin);\n\n // Handle preflight\n if (request.method === 'OPTIONS') {\n return new Response(null, {\n status: 200,\n headers: isAllowed\n ? {\n 'Access-Control-Allow-Origin': origin,\n ...CORS_HEADERS,\n }\n : {},\n });\n }\n\n // For all other requests, continue and attach CORS\n const response =\n typeof middleware === 'function'\n ? await middleware(request)\n : NextResponse.next();\n\n if (isAllowed) {\n response.headers.set('Access-Control-Allow-Origin', origin);\n }\n\n Object.entries(CORS_HEADERS).forEach(([k, v]) =>\n response.headers.set(k, v),\n );\n\n return response;\n };\n}\n\n/**\n * This configuration is used to specify the paths that the middleware should match.\n * It matches all paths by default.\n */\nexport const config = {\n matcher: '/:path*',\n};\n"],"mappings":";AAAA,SAA2B,oBAAoB;AAW/C,SAAS,gBAAgB,SAAoD;AAC3E,QAAM,mBACJ,QAAQ,IAAI,sCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,KAAK,GAAG,IACvB,SAAS,WACb,KAEC,MAAM,GAAG,EACT,IAAI,CAAC,WAAW,OAAO,KAAK,CAAC;AAEhC,QAAM,eAAe;AAAA,IACnB,gCACE,QAAQ,IAAI,oCACX,MAAM,QAAQ,SAAS,MAAM,IAC1B,QAAQ,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAC5C,SAAS,WACb;AAAA,IACF,gCACE,QAAQ,IAAI,oCACX,MAAM,QAAQ,SAAS,OAAO,IAC3B,QAAQ,QAAQ,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,IAC7C,SAAS,YACb;AAAA,IACF,GAAI,QAAQ,IAAI,uCAAuC,SAAS,cAC5D;AAAA,MACE,oCACE,QAAQ,IAAI,uCAAuC;AAAA,IACvD,IACA,CAAC;AAAA,EACP;AAEA,SAAO,EAAE,iBAAiB,aAAa;AACzC;AAUO,SAAS,qBACd,YACA,SACA;AACA,SAAO,OAAO,YAAyB;AACrC,UAAM,EAAE,iBAAiB,aAAa,IAAI,gBAAgB,SAAS,IAAI;AAEvE,UAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ,KAAK;AAChD,UAAM,YACJ,gBAAgB,SAAS,GAAG,KAAK,gBAAgB,SAAS,MAAM;AAGlE,QAAI,QAAQ,WAAW,WAAW;AAChC,aAAO,IAAI,SAAS,MAAM;AAAA,QACxB,QAAQ;AAAA,QACR,SAAS,YACL;AAAA,UACE,+BAA+B;AAAA,UAC/B,GAAG;AAAA,QACL,IACA,CAAC;AAAA,MACP,CAAC;AAAA,IACH;AAGA,UAAM,WACJ,OAAO,eAAe,aAClB,MAAM,WAAW,OAAO,IACxB,aAAa,KAAK;AAExB,QAAI,WAAW;AACb,eAAS,QAAQ,IAAI,+BAA+B,MAAM;AAAA,IAC5D;AAEA,WAAO,QAAQ,YAAY,EAAE;AAAA,MAAQ,CAAC,CAAC,GAAG,CAAC,MACzC,SAAS,QAAQ,IAAI,GAAG,CAAC;AAAA,IAC3B;AAEA,WAAO;AAAA,EACT;AACF;AAMO,IAAM,SAAS;AAAA,EACpB,SAAS;AACX;","names":[]}
@@ -70,10 +70,14 @@ function RemoteComponent({
70
70
  const [remoteComponent, setRemoteComponent] = (0, import_react.useState)(null);
71
71
  const shadowRootContainerRef = (0, import_react.useRef)(null);
72
72
  const [shadowRoot, setShadowRoot] = (0, import_react.useState)(
73
- typeof document !== "undefined" ? document.getElementById(`shadowroot_${name}`)?.shadowRoot ?? null : null
73
+ typeof document !== "undefined" ? document.getElementById(
74
+ `shadowroot_${src ? new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href.replace(/[^a-z0-9]/g, "_") : ""}_${name}`
75
+ )?.shadowRoot ?? null : null
74
76
  );
75
77
  const htmlRef = (0, import_react.useRef)(
76
- typeof document !== "undefined" ? document.getElementById(`shadowroot_${name}`)?.shadowRoot?.innerHTML ?? document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML : null
78
+ typeof document !== "undefined" ? document.getElementById(
79
+ `shadowroot_${src ? new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href.replace(/[^a-z0-9]/g, "_") : ""}_${name}`
80
+ )?.shadowRoot?.innerHTML ?? document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML : null
77
81
  );
78
82
  const endTemplateRef = (0, import_react.useRef)(null);
79
83
  const childrenRef = (0, import_react.useRef)(
@@ -134,9 +138,7 @@ function RemoteComponent({
134
138
  const fetchInit = {
135
139
  method: "GET",
136
140
  headers: {
137
- Accept: "text/html",
138
- // pass the public address of the remote component to the server used for module map mutation
139
- "Vercel-Remote-Component-Url": url.href
141
+ Accept: "text/html"
140
142
  },
141
143
  credentials
142
144
  };
@@ -184,7 +186,7 @@ function RemoteComponent({
184
186
  "script[src],script[data-src]"
185
187
  );
186
188
  const inlineScripts = doc.querySelectorAll(
187
- "script:not([src]):not([data-src]):not([id*='_rsc'])"
189
+ "script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])"
188
190
  );
189
191
  const self = globalThis;
190
192
  const prevNextScripts = self.__next_s;
@@ -333,7 +335,7 @@ function RemoteComponent({
333
335
  /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
334
336
  "div",
335
337
  {
336
- id: `shadowroot_${data?.name ?? name}`,
338
+ id: `shadowroot_${src ? new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href.replace(/[^a-z0-9]/g, "_") : ""}_${data?.name ?? name}`,
337
339
  ref: shadowRootContainerRef,
338
340
  children: [
339
341
  typeof document === "undefined" ? (
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/react/index.tsx"],"sourcesContent":["import {\n useState,\n useEffect,\n useLayoutEffect,\n useRef,\n useMemo,\n startTransition,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport {\n loadRemoteComponent,\n setAttributesFromProps,\n DEFAULT_ROUTE,\n RUNTIME_WEBPACK,\n REMOTE_COMPONENT_REGEX,\n type LoadRemoteComponentProps,\n} from '#internal/shared/client/remote-component';\nimport type { RemoteComponentProps as RemoteComponentPropsType } from '#remote-components/shared/client/types';\n\n// patch react/jsx-runtime to support the shadowrootmode attribute on template elements\ndeclare module 'react/jsx-runtime' {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace JSX {\n interface IntrinsicElements {\n template: {\n shadowrootmode?: 'open' | 'closed';\n id?: string;\n ref?: React.Ref<HTMLTemplateElement>;\n dangerouslySetInnerHTML?: {\n __html: string;\n };\n children?: React.ReactNode;\n };\n }\n }\n}\n\nexport interface RemoteComponentProps {\n /** The source URL of the remote component. */\n src?: string | URL;\n /** Whether to isolate the remote component using a Shadow DOM wrapper. */\n isolate?: boolean;\n /** The credentials to use for the fetch request. Defaults to `same-origin`. */\n credentials?: RequestCredentials;\n name?: string;\n /** Shared modules to include in the remote component's context. */\n shared?: LoadRemoteComponentProps['shared'];\n /** The children to use as a loading fallback until the remote component is loaded. */\n children?: React.ReactNode;\n}\n\nfunction getRemoteComponentHtml(html: string) {\n if (typeof document === 'undefined') return html;\n\n const temp = document.createElement('div');\n temp.innerHTML = 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\n const remoteComponentContainer = temp.querySelectorAll(\n `div[data-bundle][data-route][data-runtime][id^=\"__vercel_remote_component\"],div[data-bundle][data-route],div#__next`,\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\n/**\n * RemoteComponent 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 `<RemoteComponent>` in your React application to consume a remote component from a remote application:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/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 * <RemoteComponent 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 * <RemoteComponent\n * src=\"/nextjs-app-remote/components/header\"\n * shared={{\n * '@/components/provider': () => import('@/components/host-provider')\n * }}\n * />\n * ```\n */\nexport function RemoteComponent({\n src,\n isolate,\n credentials = 'same-origin',\n name: nameProp = '__vercel_remote_component',\n shared = {},\n children,\n}: RemoteComponentProps) {\n const name = useMemo(() => {\n if (typeof src === 'string') {\n const url = new URL(\n src,\n typeof document !== 'undefined' ? location.href : 'http://localhost',\n );\n if (url.hash) {\n return url.hash.slice(1);\n }\n } else if (typeof src === 'object' && 'hash' in src && src.hash) {\n return src.hash.slice(1) || nameProp;\n }\n return nameProp;\n }, [src, nameProp]);\n\n const [data, setData] = useState<Omit<\n RemoteComponentPropsType,\n 'children'\n > | null>(null);\n const [remoteComponent, setRemoteComponent] = useState<\n React.ReactNode | Error\n >(null);\n const shadowRootContainerRef = useRef<HTMLDivElement | null>(null);\n const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(\n typeof document !== 'undefined'\n ? (document.getElementById(`shadowroot_${name}`)?.shadowRoot ?? null)\n : null,\n );\n const htmlRef = useRef<string | null>(\n typeof document !== 'undefined'\n ? (document.getElementById(`shadowroot_${name}`)?.shadowRoot?.innerHTML ??\n document.getElementById(`__REMOTE_COMPONENT${name}`)?.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\n useLayoutEffect(() => {\n // clear initial content\n if (childrenRef.current.length > 0 && remoteComponent) {\n childrenRef.current.forEach((el) => {\n el.remove();\n });\n childrenRef.current = [];\n }\n\n if (isolate !== false && typeof document !== 'undefined' && !shadowRoot) {\n let shadowRootElement: ShadowRoot | null = null;\n const element = document.getElementById(`shadowroot_${name}`);\n shadowRootElement = 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 element.attachShadow({ mode: 'open' });\n shadowRootElement = element.shadowRoot;\n }\n\n if (shadowRootElement) {\n // remove all nodes from the shadow root except links\n shadowRootElement.querySelectorAll('*:not(link)').forEach((node) => {\n node.remove();\n });\n setShadowRoot(shadowRootElement);\n }\n }\n }, [name, isolate, shadowRoot, remoteComponent]);\n\n const url = useMemo(() => {\n if (typeof src !== 'string')\n return new URL(\n typeof document !== 'undefined' ? location.href : 'http://localhost',\n );\n try {\n return typeof document !== 'undefined'\n ? new URL(src, location.href)\n : new URL(src);\n } catch {\n return new URL(src, 'http://localhost');\n }\n }, [src]);\n\n useEffect(() => {\n let mounted = true;\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 method: 'GET',\n headers: {\n Accept: 'text/html',\n // pass the public address of the remote component to the server used for module map mutation\n 'Vercel-Remote-Component-Url': url.href,\n },\n credentials,\n } as RequestInit;\n\n const res = await fetch(url, fetchInit);\n\n if (!res.ok) {\n throw new Error(\n `Failed to fetch remote component \"${name}\": ${res.status}`,\n );\n }\n\n // get the full HTML content as a string\n const remoteHtml = await res.text();\n htmlRef.current = remoteHtml;\n html = getRemoteComponentHtml(remoteHtml);\n }\n\n // create a virtual element which will be used to parse the HTML and extract the component and RSC flight data\n const doc = document.createElement('div');\n doc.innerHTML = html;\n\n // reference to the remote component content\n const component =\n doc.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`) ??\n // fallback to the first element with the data-bundle and data-route attributes when not using a named remote component\n doc.querySelector('div[data-bundle][data-route]') ??\n // fallback to Next.js Pages Router\n doc.querySelector('div#__next');\n const nextData = JSON.parse(\n (\n doc.querySelector('#__NEXT_DATA__') ??\n doc.querySelector('#__REMOTE_NEXT_DATA__')\n )?.textContent ?? 'null',\n ) as {\n props: {\n pageProps: Record<string, unknown>;\n __REMOTE_COMPONENT__?: {\n bundle: string;\n runtime: 'turbopack' | 'webpack';\n };\n };\n page: string;\n buildId: string;\n } | null;\n\n const remoteName =\n component?.getAttribute('id')?.replace(/_ssr$/, '') ||\n (nextData ? '__next' : name);\n // reference to the RSC flight data\n const rsc = doc.querySelector(`#${remoteName}_rsc`);\n\n // reference to the bundle containing the client components\n const bundle =\n component?.getAttribute('data-bundle') ||\n nextData?.props.__REMOTE_COMPONENT__?.bundle ||\n 'default';\n\n const metadata = {\n name: remoteName,\n bundle,\n route:\n component?.getAttribute('data-route') ??\n nextData?.page ??\n DEFAULT_ROUTE,\n runtime: (component?.getAttribute('data-runtime') ??\n (nextData?.props.__REMOTE_COMPONENT__?.runtime ||\n RUNTIME_WEBPACK)) as RemoteComponentPropsType['runtime'],\n };\n\n const remoteSharedEl = doc.querySelector(`#${remoteName}_shared`);\n const remoteShared = (JSON.parse(remoteSharedEl?.textContent ?? '{}') ??\n {}) as Record<string, string>;\n remoteSharedEl?.parentElement?.removeChild(remoteSharedEl);\n\n if (!component || !(rsc || nextData)) {\n throw new Error(`Failed to find component with id \"${remoteName}\"`);\n }\n\n // reference to all link elements in the remote component\n const links = Array.from(\n doc.querySelectorAll<HTMLLinkElement>('link[href]'),\n ).map((link) => ({\n rel: link.rel,\n href: new URL(link.getAttribute('href') ?? link.href, url).href,\n as: link.getAttribute('as') || undefined,\n }));\n\n const scripts = doc.querySelectorAll<HTMLScriptElement>(\n 'script[src],script[data-src]',\n );\n\n // handle inline scripts in the remote component\n const inlineScripts = doc.querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc'])\",\n );\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 await Promise.all(\n Array.from(inlineScripts).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 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 if (mounted) {\n if (rsc) {\n document.body.appendChild(rsc);\n }\n\n const newData = {\n ...metadata,\n links,\n remoteShared,\n url: url.href,\n data: rsc\n ? (rsc.textContent || '').split('\\n').filter(Boolean)\n : [],\n };\n\n const result = await loadRemoteComponent({\n url: new URL(url, location.origin),\n name: remoteName,\n bundle,\n route: metadata.route,\n runtime: metadata.runtime,\n data: newData.data,\n nextData,\n scripts: Array.from(scripts).map((script) => {\n const scriptSrc =\n script.getAttribute('data-src') ||\n script.getAttribute('src') ||\n script.src;\n const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(\n scriptSrc,\n )?.groups ?? {\n prefix: undefined,\n id: scriptSrc,\n };\n return {\n src: new URL(\n `${prefix ?? ''}${path}`.replace(\n /(?<char>[^:])(?<double>\\/\\/)/g,\n '$1/',\n ),\n url,\n ).href,\n };\n }),\n shared,\n remoteShared,\n container: shadowRoot,\n });\n\n // we need to re-check mounted state after await loadRemoteComponent\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (mounted) {\n setData(newData);\n if (result.error) {\n setRemoteComponent(result.error);\n } else {\n setRemoteComponent(result.component);\n }\n }\n }\n } catch (error) {\n if (mounted) {\n setRemoteComponent(error as Error);\n }\n }\n });\n\n return () => {\n mounted = false;\n };\n }, [url, src, isolate, credentials, name, shared, shadowRoot]);\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: data?.runtime || RUNTIME_WEBPACK,\n })}\n </script>\n );\n const linksToRender: React.ReactNode[] | null =\n data?.links?.map((link) => (\n <link\n as={link.as as string}\n href={new URL(link.href as string, url).href}\n key={`${link.href as string}_${link.rel}`}\n rel={link.rel as string}\n />\n )) || null;\n const componentToRender = (\n <>\n {linksToRender}\n {remoteComponent ?? children}\n </>\n );\n\n if (isolate !== false) {\n const shadowRemoteComponentHtml = shadowRoot?.querySelector(\n `#__REMOTE_COMPONENT${name}`,\n );\n if (shadowRemoteComponentHtml) {\n shadowRemoteComponentHtml.remove();\n }\n\n if (shadowRoot && remoteComponent && htmlRef.current) {\n const content = shadowRoot.querySelectorAll(':not(link,style)');\n content.forEach((node) => node.remove());\n htmlRef.current = null;\n }\n\n return (\n <>\n {metadataJson}\n <div\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=\"open\">\n {linksToRender}\n {children}\n </template>\n ) : null}\n {shadowRoot && remoteComponent\n ? createPortal(\n <>\n {linksToRender}\n {remoteComponent}\n </>,\n shadowRoot,\n )\n : null}\n </div>\n </>\n );\n }\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"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA4eI;AA5eJ,mBAOO;AACP,uBAA6B;AAC7B,8BAOO;AAmCP,SAAS,uBAAuB,MAAc;AAC5C,MAAI,OAAO,aAAa;AAAa,WAAO;AAE5C,QAAM,OAAO,SAAS,cAAc,KAAK;AACzC,OAAK,YAAY;AAGjB,QAAM,8BAA8B,KAAK;AAAA,IACvC;AAAA,EACF;AACA,MAAI,6BAA6B;AAC/B,WAAO,4BAA4B;AAAA,EACrC;AAGA,QAAM,2BAA2B,KAAK;AAAA,IACpC;AAAA,EACF;AACA,MAAI,yBAAyB,SAAS,GAAG;AACvC,WAAO,GAAG,MAAM,KAAK,KAAK,iBAAiB,aAAa,CAAC,EACtD,IAAI,CAAC,SAAS,KAAK,SAAS,EAC5B,KAAK,EAAE,IAAI,MAAM,KAAK,wBAAwB,EAC9C,IAAI,CAAC,cAAc,UAAU,SAAS,EACtC,KAAK,EAAE;AAAA,EACZ;AAEA,SA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AAAA,IACxB;AACA,QAAI,2BAA2B;AAC7B,gCAA0B,OAAO;AAAA,IACnC;AAEA,QAAI,cAAc,mBAAmB,QAAQ,SAAS;AACpD,YAAM,UAAU,WAAW,iBAAiB,kBAAkB;AAC9D,cAAQ,QAAQ,CAAC,SAAS,KAAK,OAAO,CAAC;AACvC,cAAQ,UAAU;AAAA,IACpB;AAEA,WACE,4EACG;AAAA;AAAA,MACD;AAAA,QAAC;AAAA;AAAA,UACC,IAAI,cAAc,MAAM,QAAQ;AAAA,UAChC,KAAK;AAAA,UAEJ;AAAA,mBAAO,aAAa;AAAA;AAAA,cAEnB,6CAAC,cAAS,gBAAe,QACtB;AAAA;AAAA,gBACA;AAAA,iBACH;AAAA,gBACE;AAAA,YACH,cAAc,sBACX;AAAA,cACE,4EACG;AAAA;AAAA,gBACA;AAAA,iBACH;AAAA,cACA;AAAA,YACF,IACA;AAAA;AAAA;AAAA,MACN;AAAA,OACF;AAAA,EAEJ;AAGA,SACE,4EACE;AAAA,gDAAC,cAAS,IAAI,GAAG,cAAc;AAAA,IAC9B;AAAA,IACA;AAAA,IACD,4CAAC,cAAS,IAAI,GAAG,YAAY,KAAK,gBAAgB;AAAA,KACpD;AAEJ;","names":["url"]}
1
+ {"version":3,"sources":["../../src/react/index.tsx"],"sourcesContent":["import {\n useState,\n useEffect,\n useLayoutEffect,\n useRef,\n useMemo,\n startTransition,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport {\n loadRemoteComponent,\n setAttributesFromProps,\n DEFAULT_ROUTE,\n RUNTIME_WEBPACK,\n REMOTE_COMPONENT_REGEX,\n type LoadRemoteComponentProps,\n} from '#internal/shared/client/remote-component';\nimport type { RemoteComponentProps as RemoteComponentPropsType } from '#remote-components/shared/client/types';\n\n// patch react/jsx-runtime to support the shadowrootmode attribute on template elements\ndeclare module 'react/jsx-runtime' {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace JSX {\n interface IntrinsicElements {\n template: {\n shadowrootmode?: 'open' | 'closed';\n id?: string;\n ref?: React.Ref<HTMLTemplateElement>;\n dangerouslySetInnerHTML?: {\n __html: string;\n };\n children?: React.ReactNode;\n };\n }\n }\n}\n\nexport interface RemoteComponentProps {\n /** The source URL of the remote component. */\n src?: string | URL;\n /** Whether to isolate the remote component using a Shadow DOM wrapper. */\n isolate?: boolean;\n /** The credentials to use for the fetch request. Defaults to `same-origin`. */\n credentials?: RequestCredentials;\n name?: string;\n /** Shared modules to include in the remote component's context. */\n shared?: LoadRemoteComponentProps['shared'];\n /** The children to use as a loading fallback until the remote component is loaded. */\n children?: React.ReactNode;\n}\n\nfunction getRemoteComponentHtml(html: string) {\n if (typeof document === 'undefined') return html;\n\n const temp = document.createElement('div');\n temp.innerHTML = 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\n const remoteComponentContainer = temp.querySelectorAll(\n `div[data-bundle][data-route][data-runtime][id^=\"__vercel_remote_component\"],div[data-bundle][data-route],div#__next`,\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\n/**\n * RemoteComponent 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 `<RemoteComponent>` in your React application to consume a remote component from a remote application:\n *\n * ```tsx\n * import { RemoteComponent } from 'remote-components/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 * <RemoteComponent 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 * <RemoteComponent\n * src=\"/nextjs-app-remote/components/header\"\n * shared={{\n * '@/components/provider': () => import('@/components/host-provider')\n * }}\n * />\n * ```\n */\nexport function RemoteComponent({\n src,\n isolate,\n credentials = 'same-origin',\n name: nameProp = '__vercel_remote_component',\n shared = {},\n children,\n}: RemoteComponentProps) {\n const name = useMemo(() => {\n if (typeof src === 'string') {\n const url = new URL(\n src,\n typeof document !== 'undefined' ? location.href : 'http://localhost',\n );\n if (url.hash) {\n return url.hash.slice(1);\n }\n } else if (typeof src === 'object' && 'hash' in src && src.hash) {\n return src.hash.slice(1) || nameProp;\n }\n return nameProp;\n }, [src, nameProp]);\n\n const [data, setData] = useState<Omit<\n RemoteComponentPropsType,\n 'children'\n > | null>(null);\n const [remoteComponent, setRemoteComponent] = useState<\n React.ReactNode | Error\n >(null);\n const shadowRootContainerRef = useRef<HTMLDivElement | null>(null);\n const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(\n typeof document !== 'undefined'\n ? (document.getElementById(\n `shadowroot_${src ? new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href.replace(/[^a-z0-9]/g, '_') : ''}_${name}`,\n )?.shadowRoot ?? null)\n : null,\n );\n const htmlRef = useRef<string | null>(\n typeof document !== 'undefined'\n ? (document.getElementById(\n `shadowroot_${src ? new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href.replace(/[^a-z0-9]/g, '_') : ''}_${name}`,\n )?.shadowRoot?.innerHTML ??\n document.getElementById(`__REMOTE_COMPONENT${name}`)?.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\n useLayoutEffect(() => {\n // clear initial content\n if (childrenRef.current.length > 0 && remoteComponent) {\n childrenRef.current.forEach((el) => {\n el.remove();\n });\n childrenRef.current = [];\n }\n\n if (isolate !== false && typeof document !== 'undefined' && !shadowRoot) {\n let shadowRootElement: ShadowRoot | null = null;\n const element = document.getElementById(`shadowroot_${name}`);\n shadowRootElement = 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 element.attachShadow({ mode: 'open' });\n shadowRootElement = element.shadowRoot;\n }\n\n if (shadowRootElement) {\n // remove all nodes from the shadow root except links\n shadowRootElement.querySelectorAll('*:not(link)').forEach((node) => {\n node.remove();\n });\n setShadowRoot(shadowRootElement);\n }\n }\n }, [name, isolate, shadowRoot, remoteComponent]);\n\n const url = useMemo(() => {\n if (typeof src !== 'string')\n return new URL(\n typeof document !== 'undefined' ? location.href : 'http://localhost',\n );\n try {\n return typeof document !== 'undefined'\n ? new URL(src, location.href)\n : new URL(src);\n } catch {\n return new URL(src, 'http://localhost');\n }\n }, [src]);\n\n useEffect(() => {\n let mounted = true;\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 method: 'GET',\n headers: {\n Accept: 'text/html',\n },\n credentials,\n } as RequestInit;\n\n const res = await fetch(url, fetchInit);\n\n if (!res.ok) {\n throw new Error(\n `Failed to fetch remote component \"${name}\": ${res.status}`,\n );\n }\n\n // get the full HTML content as a string\n const remoteHtml = await res.text();\n htmlRef.current = remoteHtml;\n html = getRemoteComponentHtml(remoteHtml);\n }\n\n // create a virtual element which will be used to parse the HTML and extract the component and RSC flight data\n const doc = document.createElement('div');\n doc.innerHTML = html;\n\n // reference to the remote component content\n const component =\n doc.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`) ??\n // fallback to the first element with the data-bundle and data-route attributes when not using a named remote component\n doc.querySelector('div[data-bundle][data-route]') ??\n // fallback to Next.js Pages Router\n doc.querySelector('div#__next');\n const nextData = JSON.parse(\n (\n doc.querySelector('#__NEXT_DATA__') ??\n doc.querySelector('#__REMOTE_NEXT_DATA__')\n )?.textContent ?? 'null',\n ) as {\n props: {\n pageProps: Record<string, unknown>;\n __REMOTE_COMPONENT__?: {\n bundle: string;\n runtime: 'turbopack' | 'webpack';\n };\n };\n page: string;\n buildId: string;\n } | null;\n\n const remoteName =\n component?.getAttribute('id')?.replace(/_ssr$/, '') ||\n (nextData ? '__next' : name);\n // reference to the RSC flight data\n const rsc = doc.querySelector(`#${remoteName}_rsc`);\n\n // reference to the bundle containing the client components\n const bundle =\n component?.getAttribute('data-bundle') ||\n nextData?.props.__REMOTE_COMPONENT__?.bundle ||\n 'default';\n\n const metadata = {\n name: remoteName,\n bundle,\n route:\n component?.getAttribute('data-route') ??\n nextData?.page ??\n DEFAULT_ROUTE,\n runtime: (component?.getAttribute('data-runtime') ??\n (nextData?.props.__REMOTE_COMPONENT__?.runtime ||\n RUNTIME_WEBPACK)) as RemoteComponentPropsType['runtime'],\n };\n\n const remoteSharedEl = doc.querySelector(`#${remoteName}_shared`);\n const remoteShared = (JSON.parse(remoteSharedEl?.textContent ?? '{}') ??\n {}) as Record<string, string>;\n remoteSharedEl?.parentElement?.removeChild(remoteSharedEl);\n\n if (!component || !(rsc || nextData)) {\n throw new Error(`Failed to find component with id \"${remoteName}\"`);\n }\n\n // reference to all link elements in the remote component\n const links = Array.from(\n doc.querySelectorAll<HTMLLinkElement>('link[href]'),\n ).map((link) => ({\n rel: link.rel,\n href: new URL(link.getAttribute('href') ?? link.href, url).href,\n as: link.getAttribute('as') || undefined,\n }));\n\n const scripts = doc.querySelectorAll<HTMLScriptElement>(\n 'script[src],script[data-src]',\n );\n\n // handle inline scripts in the remote component\n const inlineScripts = doc.querySelectorAll(\n \"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])\",\n );\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 await Promise.all(\n Array.from(inlineScripts).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 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 if (mounted) {\n if (rsc) {\n document.body.appendChild(rsc);\n }\n\n const newData = {\n ...metadata,\n links,\n remoteShared,\n url: url.href,\n data: rsc\n ? (rsc.textContent || '').split('\\n').filter(Boolean)\n : [],\n };\n\n const result = await loadRemoteComponent({\n url: new URL(url, location.origin),\n name: remoteName,\n bundle,\n route: metadata.route,\n runtime: metadata.runtime,\n data: newData.data,\n nextData,\n scripts: Array.from(scripts).map((script) => {\n const scriptSrc =\n script.getAttribute('data-src') ||\n script.getAttribute('src') ||\n script.src;\n const { prefix, id: path } = REMOTE_COMPONENT_REGEX.exec(\n scriptSrc,\n )?.groups ?? {\n prefix: undefined,\n id: scriptSrc,\n };\n return {\n src: new URL(\n `${prefix ?? ''}${path}`.replace(\n /(?<char>[^:])(?<double>\\/\\/)/g,\n '$1/',\n ),\n url,\n ).href,\n };\n }),\n shared,\n remoteShared,\n container: shadowRoot,\n });\n\n // we need to re-check mounted state after await loadRemoteComponent\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (mounted) {\n setData(newData);\n if (result.error) {\n setRemoteComponent(result.error);\n } else {\n setRemoteComponent(result.component);\n }\n }\n }\n } catch (error) {\n if (mounted) {\n setRemoteComponent(error as Error);\n }\n }\n });\n\n return () => {\n mounted = false;\n };\n }, [url, src, isolate, credentials, name, shared, shadowRoot]);\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: data?.runtime || RUNTIME_WEBPACK,\n })}\n </script>\n );\n const linksToRender: React.ReactNode[] | null =\n data?.links?.map((link) => (\n <link\n as={link.as as string}\n href={new URL(link.href as string, url).href}\n key={`${link.href as string}_${link.rel}`}\n rel={link.rel as string}\n />\n )) || null;\n const componentToRender = (\n <>\n {linksToRender}\n {remoteComponent ?? children}\n </>\n );\n\n if (isolate !== false) {\n const shadowRemoteComponentHtml = shadowRoot?.querySelector(\n `#__REMOTE_COMPONENT${name}`,\n );\n if (shadowRemoteComponentHtml) {\n shadowRemoteComponentHtml.remove();\n }\n\n if (shadowRoot && remoteComponent && htmlRef.current) {\n const content = shadowRoot.querySelectorAll(':not(link,style)');\n content.forEach((node) => node.remove());\n htmlRef.current = null;\n }\n\n return (\n <>\n {metadataJson}\n <div\n id={`shadowroot_${src ? new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href.replace(/[^a-z0-9]/g, '_') : ''}_${data?.name ?? name}`}\n ref={shadowRootContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode=\"open\">\n {linksToRender}\n {children}\n </template>\n ) : null}\n {shadowRoot && remoteComponent\n ? createPortal(\n <>\n {linksToRender}\n {remoteComponent}\n </>,\n shadowRoot,\n )\n : null}\n </div>\n </>\n );\n }\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"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA8eI;AA9eJ,mBAOO;AACP,uBAA6B;AAC7B,8BAOO;AAmCP,SAAS,uBAAuB,MAAc;AAC5C,MAAI,OAAO,aAAa;AAAa,WAAO;AAE5C,QAAM,OAAO,SAAS,cAAc,KAAK;AACzC,OAAK,YAAY;AAGjB,QAAM,8BAA8B,KAAK;AAAA,IACvC;AAAA,EACF;AACA,MAAI,6BAA6B;AAC/B,WAAO,4BAA4B;AAAA,EACrC;AAGA,QAAM,2BAA2B,KAAK;AAAA,IACpC;AAAA,EACF;AACA,MAAI,yBAAyB,SAAS,GAAG;AACvC,WAAO,GAAG,MAAM,KAAK,KAAK,iBAAiB,aAAa,CAAC,EACtD,IAAI,CAAC,SAAS,KAAK,SAAS,EAC5B,KAAK,EAAE,IAAI,MAAM,KAAK,wBAAwB,EAC9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ACT,MAAM,IAAI,IAAI,KAAK,MAAgB,GAAG,EAAE;AAAA,MAExC,KAAK,KAAK;AAAA;AAAA,IADL,GAAG,KAAK,QAAkB,KAAK;AAAA,EAEtC,CACD,KAAK;AACR,QAAM,oBACJ,4EACG;AAAA;AAAA,IACA,mBAAmB;AAAA,KACtB;AAGF,MAAI,YAAY,OAAO;AACrB,UAAM,4BAA4B,YAAY;AAAA,MAC5C,sBAAsB;AAAA,IACxB;AACA,QAAI,2BAA2B;AAC7B,gCAA0B,OAAO;AAAA,IACnC;AAEA,QAAI,cAAc,mBAAmB,QAAQ,SAAS;AACpD,YAAM,UAAU,WAAW,iBAAiB,kBAAkB;AAC9D,cAAQ,QAAQ,CAAC,SAAS,KAAK,OAAO,CAAC;AACvC,cAAQ,UAAU;AAAA,IACpB;AAEA,WACE,4EACG;AAAA;AAAA,MACD;AAAA,QAAC;AAAA;AAAA,UACC,IAAI,cAAc,MAAM,IAAI,IAAI,KAAK,OAAO,aAAa,cAAc,SAAS,SAAS,kBAAkB,EAAE,KAAK,QAAQ,cAAc,GAAG,IAAI,MAAM,MAAM,QAAQ;AAAA,UACnK,KAAK;AAAA,UAEJ;AAAA,mBAAO,aAAa;AAAA;AAAA,cAEnB,6CAAC,cAAS,gBAAe,QACtB;AAAA;AAAA,gBACA;AAAA,iBACH;AAAA,gBACE;AAAA,YACH,cAAc,sBACX;AAAA,cACE,4EACG;AAAA;AAAA,gBACA;AAAA,iBACH;AAAA,cACA;AAAA,YACF,IACA;AAAA;AAAA;AAAA,MACN;AAAA,OACF;AAAA,EAEJ;AAGA,SACE,4EACE;AAAA,gDAAC,cAAS,IAAI,GAAG,cAAc;AAAA,IAC9B;AAAA,IACA;AAAA,IACD,4CAAC,cAAS,IAAI,GAAG,YAAY,KAAK,gBAAgB;AAAA,KACpD;AAEJ;","names":["url"]}
@@ -60,10 +60,14 @@ function RemoteComponent({
60
60
  const [remoteComponent, setRemoteComponent] = useState(null);
61
61
  const shadowRootContainerRef = useRef(null);
62
62
  const [shadowRoot, setShadowRoot] = useState(
63
- typeof document !== "undefined" ? document.getElementById(`shadowroot_${name}`)?.shadowRoot ?? null : null
63
+ typeof document !== "undefined" ? document.getElementById(
64
+ `shadowroot_${src ? new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href.replace(/[^a-z0-9]/g, "_") : ""}_${name}`
65
+ )?.shadowRoot ?? null : null
64
66
  );
65
67
  const htmlRef = useRef(
66
- typeof document !== "undefined" ? document.getElementById(`shadowroot_${name}`)?.shadowRoot?.innerHTML ?? document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML : null
68
+ typeof document !== "undefined" ? document.getElementById(
69
+ `shadowroot_${src ? new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href.replace(/[^a-z0-9]/g, "_") : ""}_${name}`
70
+ )?.shadowRoot?.innerHTML ?? document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML : null
67
71
  );
68
72
  const endTemplateRef = useRef(null);
69
73
  const childrenRef = useRef(
@@ -124,9 +128,7 @@ function RemoteComponent({
124
128
  const fetchInit = {
125
129
  method: "GET",
126
130
  headers: {
127
- Accept: "text/html",
128
- // pass the public address of the remote component to the server used for module map mutation
129
- "Vercel-Remote-Component-Url": url.href
131
+ Accept: "text/html"
130
132
  },
131
133
  credentials
132
134
  };
@@ -174,7 +176,7 @@ function RemoteComponent({
174
176
  "script[src],script[data-src]"
175
177
  );
176
178
  const inlineScripts = doc.querySelectorAll(
177
- "script:not([src]):not([data-src]):not([id*='_rsc'])"
179
+ "script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])"
178
180
  );
179
181
  const self = globalThis;
180
182
  const prevNextScripts = self.__next_s;
@@ -323,7 +325,7 @@ function RemoteComponent({
323
325
  /* @__PURE__ */ jsxs(
324
326
  "div",
325
327
  {
326
- id: `shadowroot_${data?.name ?? name}`,
328
+ id: `shadowroot_${src ? new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href.replace(/[^a-z0-9]/g, "_") : ""}_${data?.name ?? name}`,
327
329
  ref: shadowRootContainerRef,
328
330
  children: [
329
331
  typeof document === "undefined" ? (