remote-components 0.0.21 → 0.0.23
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.
- package/dist/html/host.cjs +115 -40
- package/dist/html/host.cjs.map +1 -1
- package/dist/html/host.js +115 -40
- package/dist/html/host.js.map +1 -1
- package/dist/internal/next/host/app-router-client.cjs +72 -23
- package/dist/internal/next/host/app-router-client.cjs.map +1 -1
- package/dist/internal/next/host/app-router-client.d.ts +2 -2
- package/dist/internal/next/host/app-router-client.js +73 -24
- package/dist/internal/next/host/app-router-client.js.map +1 -1
- package/dist/internal/shared/client/remote-component.cjs +43 -16
- package/dist/internal/shared/client/remote-component.cjs.map +1 -1
- package/dist/internal/shared/client/remote-component.d.ts +2 -0
- package/dist/internal/shared/client/remote-component.js +43 -16
- package/dist/internal/shared/client/remote-component.js.map +1 -1
- package/dist/internal/shared/ssr/dom-flight.cjs +9 -17
- package/dist/internal/shared/ssr/dom-flight.cjs.map +1 -1
- package/dist/internal/shared/ssr/dom-flight.js +9 -17
- package/dist/internal/shared/ssr/dom-flight.js.map +1 -1
- package/dist/internal/shared/ssr/fetch-remote-component.cjs +3 -4
- package/dist/internal/shared/ssr/fetch-remote-component.cjs.map +1 -1
- package/dist/internal/shared/ssr/fetch-remote-component.js +3 -4
- package/dist/internal/shared/ssr/fetch-remote-component.js.map +1 -1
- package/dist/internal/webpack/next-client-pages-loader.cjs +43 -16
- package/dist/internal/webpack/next-client-pages-loader.cjs.map +1 -1
- package/dist/internal/webpack/next-client-pages-loader.js +43 -16
- package/dist/internal/webpack/next-client-pages-loader.js.map +1 -1
- package/dist/next/host/app-router-server.cjs +4 -0
- package/dist/next/host/app-router-server.cjs.map +1 -1
- package/dist/next/host/app-router-server.d.ts +5 -1
- package/dist/next/host/app-router-server.js +4 -0
- package/dist/next/host/app-router-server.js.map +1 -1
- package/dist/next/host/client/index.d.ts +1 -1
- package/dist/next/host/pages-router-server.cjs +11 -4
- package/dist/next/host/pages-router-server.cjs.map +1 -1
- package/dist/next/host/pages-router-server.d.ts +3 -0
- package/dist/next/host/pages-router-server.js +11 -4
- package/dist/next/host/pages-router-server.js.map +1 -1
- package/dist/next/middleware.cjs +1 -1
- package/dist/next/middleware.cjs.map +1 -1
- package/dist/next/middleware.js +1 -1
- package/dist/next/middleware.js.map +1 -1
- package/dist/react/index.cjs +56 -19
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.ts +6 -2
- package/dist/react/index.js +56 -19
- package/dist/react/index.js.map +1 -1
- package/dist/{types-7425dfe1.d.ts → types-b8210fd3.d.ts} +2 -0
- package/package.json +1 -1
|
@@ -101,8 +101,11 @@ function RemoteComponent(props) {
|
|
|
101
101
|
RemoteComponentReact,
|
|
102
102
|
{
|
|
103
103
|
isolate: props.isolate,
|
|
104
|
+
mode: props.mode,
|
|
105
|
+
name: props.name,
|
|
106
|
+
reset: props.reset,
|
|
104
107
|
shared: shared(props.bundle ?? "default"),
|
|
105
|
-
src: props.src,
|
|
108
|
+
src: props.url ?? props.src,
|
|
106
109
|
children: props.children
|
|
107
110
|
}
|
|
108
111
|
);
|
|
@@ -111,9 +114,11 @@ function RemoteComponent(props) {
|
|
|
111
114
|
RemoteComponentReact,
|
|
112
115
|
{
|
|
113
116
|
isolate: props.isolate,
|
|
117
|
+
mode: props.mode,
|
|
114
118
|
name: props.name,
|
|
119
|
+
reset: props.reset,
|
|
115
120
|
shared: shared(props.bundle ?? "default"),
|
|
116
|
-
src: props.src,
|
|
121
|
+
src: props.url ?? props.src,
|
|
117
122
|
children: remoteComponent
|
|
118
123
|
}
|
|
119
124
|
);
|
|
@@ -129,7 +134,8 @@ async function getRemoteComponentProps(src, headers) {
|
|
|
129
134
|
name,
|
|
130
135
|
links,
|
|
131
136
|
component,
|
|
132
|
-
nextData
|
|
137
|
+
nextData,
|
|
138
|
+
url
|
|
133
139
|
} = await fetchRemoteComponent(
|
|
134
140
|
src,
|
|
135
141
|
headers instanceof Headers ? headers : (
|
|
@@ -155,7 +161,8 @@ async function getRemoteComponentProps(src, headers) {
|
|
|
155
161
|
name,
|
|
156
162
|
route,
|
|
157
163
|
runtime,
|
|
158
|
-
buildId: nextData?.buildId ?? null
|
|
164
|
+
buildId: nextData?.buildId ?? null,
|
|
165
|
+
url: url.href
|
|
159
166
|
};
|
|
160
167
|
const key = getKey(props);
|
|
161
168
|
if (nextData?.buildId !== "development") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/next/host/pages-router-server.tsx"],"sourcesContent":["import type { IncomingHttpHeaders } from 'node:http';\nimport { useEffect } from 'react';\nimport { shared as _shared } from '@remote-components/shared/host/pages';\nimport * as Form from 'next/form';\nimport * as Image from 'next/image';\nimport * as Link from 'next/link';\nimport * as Script from 'next/script';\nimport { useRouter } from 'next/router';\nimport { RemoteComponent as RemoteComponentReact } from '#remote-components/react/index';\nimport { fetchRemoteComponent } from '#internal/shared/ssr/fetch-remote-component';\n\nconst navigationImpl = {\n useRouter,\n useSearchParams: () => {\n const router = useRouter();\n return {\n get: (key: string) => router.query[key],\n has: (key: string) => key in router.query,\n };\n },\n};\n\nconst sharedCache = new Map<string, Record<string, () => Promise<unknown>>>();\nconst shared = (bundle: string) => {\n if (sharedCache.has(bundle)) {\n return sharedCache.get(bundle);\n }\n\n const remoteLoader = ({ src, width, quality }: Image.ImageLoaderProps) => {\n const self = globalThis as typeof globalThis & {\n __remote_bundle_url__?: Record<string, URL>;\n };\n const { assetPrefix } =\n /^(?<assetPrefix>.*?)\\/_next\\//.exec(src)?.groups ?? {};\n return `${self.__remote_bundle_url__?.[bundle]?.origin ?? ''}${assetPrefix}/_next/image?url=${encodeURIComponent(src)}&w=${width}&q=${quality || 75}`;\n };\n\n const imageImpl = (ImageComponent: typeof Image.default) => {\n return function RemoteImage(props: Image.ImageProps) {\n return <ImageComponent loader={remoteLoader} {...props} />;\n };\n };\n\n return {\n // polyfill Next.js App Router client API (minimal)\n // some API methods are not available when using a Next.js Pages Router application as host\n 'next/navigation': () =>\n Promise.resolve(navigationImpl) as Promise<unknown>,\n 'next/dist/client/components/navigation': () =>\n Promise.resolve(navigationImpl) as Promise<unknown>,\n 'next/dist/client/app-dir/link': () =>\n Promise.resolve(Link.default) as Promise<unknown>,\n 'next/link': () => Promise.resolve(Link.default) as Promise<unknown>,\n 'next/dist/client/app-dir/form': () =>\n Promise.resolve(Form.default) as Promise<unknown>,\n 'next/form': () => Promise.resolve(Form.default) as Promise<unknown>,\n 'next/dist/client/script': () =>\n Promise.resolve(Script.default) as Promise<unknown>,\n 'next/script': () => Promise.resolve(Script.default) as Promise<unknown>,\n 'next/image': () =>\n Promise.resolve({\n // @ts-expect-error default.default\n // eslint-disable-next-line\n default: imageImpl(Image.default.default ?? Image.default),\n getImageProps: Image.getImageProps,\n }) as Promise<unknown>,\n 'next/dist/client/image-component': () =>\n Promise.resolve({\n // @ts-expect-error default.default\n // eslint-disable-next-line\n Image: imageImpl(Image.default.default ?? Image.default),\n }) as Promise<unknown>,\n 'next/dist/api/image': () =>\n Promise.resolve({\n // @ts-expect-error default.default\n // eslint-disable-next-line\n default: imageImpl(Image.default.default ?? Image.default),\n getImageProps: Image.getImageProps,\n }) as Promise<unknown>,\n ..._shared,\n };\n};\n\n// internal symbols to access global store\nconst REMOTE_COMPONENT_STORE = Symbol('REMOTE_COMPONENT_STORE');\nconst REMOTE_COMPONENT_KEY = '__REMOTE_COMPONENT_KEY__';\n\n// temporary global store for remote component HTML\n// the store is used to save the HTML of remote components for SSR without sending the content to the client\nconst self = globalThis as typeof globalThis & {\n [REMOTE_COMPONENT_STORE]?: Map<string, React.ReactNode>;\n};\n\nfunction getKey({\n bundle,\n route,\n name,\n}: {\n bundle?: string;\n route?: string;\n name?: string;\n}): string {\n return `${bundle ?? '__next'}:${route ?? '/'}:${name ?? '__vercel_remote_component'}__${crypto.randomUUID()}`;\n}\n\nfunction setComponent(key: string, component: React.ReactNode): void {\n if (!self[REMOTE_COMPONENT_STORE]) {\n self[REMOTE_COMPONENT_STORE] = new Map();\n }\n self[REMOTE_COMPONENT_STORE].set(key, component);\n}\n\nfunction getComponent(key: string): React.ReactNode | undefined {\n const component = self[REMOTE_COMPONENT_STORE]?.get(key);\n // remove the component from the store after retrieving it to prevent memory leaks\n // storing the HTML in the global store is only needed for SSR and it's temporary only used for a single render\n self[REMOTE_COMPONENT_STORE]?.delete(key);\n return component;\n}\n\nexport interface RemoteComponentProps {\n src: string;\n bundle?: string;\n route?: string;\n name?: string;\n isolate?: boolean;\n [REMOTE_COMPONENT_KEY]?: string;\n children?: React.ReactNode;\n}\n\n/**\n * This component handles the rendering of remote microfrontends.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n */\nexport function RemoteComponent(props: RemoteComponentProps) {\n const remoteComponent =\n typeof document !== 'undefined'\n ? null\n : // retrieve the HTML from the global store\n getComponent(\n props[REMOTE_COMPONENT_KEY] ?? '__vercel_remote_component',\n );\n\n useEffect(() => {\n const clientSelf = globalThis as typeof globalThis & {\n __remote_component_shared__?: Record<string, () => Promise<unknown>>;\n };\n // eslint-disable-next-line camelcase\n clientSelf.__remote_component_shared__ = shared(props.bundle ?? 'default');\n }, [props.bundle]);\n\n if (!props[REMOTE_COMPONENT_KEY]) {\n return (\n <RemoteComponentReact\n isolate={props.isolate}\n shared={shared(props.bundle ?? 'default')}\n src={props.src}\n >\n {props.children}\n </RemoteComponentReact>\n );\n }\n\n return (\n <RemoteComponentReact\n isolate={props.isolate}\n name={props.name}\n shared={shared(props.bundle ?? 'default')}\n src={props.src}\n >\n {remoteComponent}\n </RemoteComponentReact>\n );\n}\n\n/**\n * Fetches the remote component properties from the server. You need to pass these properties to the `<RemoteComponent>` component to render the fetched remote component.\n *\n * @param src - The source URL of the remote component. When using the Vercel Microfrontends solution, you can use relative paths, e.g. `/nextjs-app-remote/components/header`. Absolute URLs are also supported.\n * @param headers - The HTTP headers used for supporting the Vercel Microfrontends proxy.\n * @returns The properties of the remote component.\n *\n * @example\n *\n * ```tsx\n * import { getRemoteComponentProps } from 'remote-components/next/host/pages';\n * import type { GetServerSideProps } from 'next';\n *\n * export const getServerSideProps: GetServerSideProps<PageProps> = async function getServerSideProps({ req }) {\n * const myRemoteComponent = await getRemoteComponentProps(\n * '/nextjs-app-remote/components/header',\n * req.headers,\n * );\n * return {\n * props: {\n * remoteComponents: {\n * myRemoteComponent,\n * },\n * },\n * };\n * }\n * ```\n */\nexport async function getRemoteComponentProps(\n src: string,\n headers: IncomingHttpHeaders,\n): Promise<RemoteComponentProps> {\n if (typeof document !== 'undefined') {\n throw new Error(\n 'getRemoteComponentProps can only be used on the server side.',\n );\n }\n\n const {\n metadata: { bundle, route, runtime },\n name,\n links,\n component,\n nextData,\n } = await fetchRemoteComponent(\n src,\n headers instanceof Headers\n ? headers\n : // convert IncomingHttpHeaders to web standard Headers\n Object.entries(headers).reduce((acc, [key, value]) => {\n if (value) {\n if (Array.isArray(value)) {\n value.forEach((v) => acc.append(key, v));\n } else {\n acc.append(key, value);\n }\n }\n return acc;\n }, new Headers()),\n {\n rsc: true,\n },\n );\n\n const props = {\n src,\n bundle,\n name,\n route,\n runtime,\n buildId: nextData?.buildId ?? null,\n };\n\n const key = getKey(props);\n\n // do not render the HTML in development mode when remote is using Next.js Pages Router\n // this behavior is emulating the Next.js Pages Router FOUC as the styles are only applied on the client when running in development mode\n if (nextData?.buildId !== 'development') {\n // store the HTML in a global store\n setComponent(\n key,\n <>\n {links.map((link) => (\n <link\n key={`${link.as}_${link.href}`}\n {...link}\n precedence={undefined}\n />\n ))}\n {component}\n </>,\n );\n }\n\n return {\n ...props,\n // add remote component key to the props\n [REMOTE_COMPONENT_KEY]: key,\n };\n}\n"],"mappings":"AAuCa,SA2NP,UA3NO,KA2NP,YA3NO;AAtCb,SAAS,iBAAiB;AAC1B,SAAS,UAAU,eAAe;AAClC,YAAY,UAAU;AACtB,YAAY,WAAW;AACvB,YAAY,UAAU;AACtB,YAAY,YAAY;AACxB,SAAS,iBAAiB;AAC1B,SA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AAA,MACA,iCACG;AAAA,cAAM,IAAI,CAAC,SACV;AAAA,UAAC;AAAA;AAAA,YAEE,GAAG;AAAA,YACJ,YAAY;AAAA;AAAA,UAFP,GAAG,KAAK,MAAM,KAAK;AAAA,QAG1B,CACD;AAAA,QACA;AAAA,SACH;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,GAAG;AAAA;AAAA,IAEH,CAAC,oBAAoB,GAAG;AAAA,EAC1B;AACF;","names":["self","key"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/next/host/pages-router-server.tsx"],"sourcesContent":["import type { IncomingHttpHeaders } from 'node:http';\nimport { useEffect } from 'react';\nimport { shared as _shared } from '@remote-components/shared/host/pages';\nimport * as Form from 'next/form';\nimport * as Image from 'next/image';\nimport * as Link from 'next/link';\nimport * as Script from 'next/script';\nimport { useRouter } from 'next/router';\nimport { RemoteComponent as RemoteComponentReact } from '#remote-components/react/index';\nimport { fetchRemoteComponent } from '#internal/shared/ssr/fetch-remote-component';\n\nconst navigationImpl = {\n useRouter,\n useSearchParams: () => {\n const router = useRouter();\n return {\n get: (key: string) => router.query[key],\n has: (key: string) => key in router.query,\n };\n },\n};\n\nconst sharedCache = new Map<string, Record<string, () => Promise<unknown>>>();\nconst shared = (bundle: string) => {\n if (sharedCache.has(bundle)) {\n return sharedCache.get(bundle);\n }\n\n const remoteLoader = ({ src, width, quality }: Image.ImageLoaderProps) => {\n const self = globalThis as typeof globalThis & {\n __remote_bundle_url__?: Record<string, URL>;\n };\n const { assetPrefix } =\n /^(?<assetPrefix>.*?)\\/_next\\//.exec(src)?.groups ?? {};\n return `${self.__remote_bundle_url__?.[bundle]?.origin ?? ''}${assetPrefix}/_next/image?url=${encodeURIComponent(src)}&w=${width}&q=${quality || 75}`;\n };\n\n const imageImpl = (ImageComponent: typeof Image.default) => {\n return function RemoteImage(props: Image.ImageProps) {\n return <ImageComponent loader={remoteLoader} {...props} />;\n };\n };\n\n return {\n // polyfill Next.js App Router client API (minimal)\n // some API methods are not available when using a Next.js Pages Router application as host\n 'next/navigation': () =>\n Promise.resolve(navigationImpl) as Promise<unknown>,\n 'next/dist/client/components/navigation': () =>\n Promise.resolve(navigationImpl) as Promise<unknown>,\n 'next/dist/client/app-dir/link': () =>\n Promise.resolve(Link.default) as Promise<unknown>,\n 'next/link': () => Promise.resolve(Link.default) as Promise<unknown>,\n 'next/dist/client/app-dir/form': () =>\n Promise.resolve(Form.default) as Promise<unknown>,\n 'next/form': () => Promise.resolve(Form.default) as Promise<unknown>,\n 'next/dist/client/script': () =>\n Promise.resolve(Script.default) as Promise<unknown>,\n 'next/script': () => Promise.resolve(Script.default) as Promise<unknown>,\n 'next/image': () =>\n Promise.resolve({\n // @ts-expect-error default.default\n // eslint-disable-next-line\n default: imageImpl(Image.default.default ?? Image.default),\n getImageProps: Image.getImageProps,\n }) as Promise<unknown>,\n 'next/dist/client/image-component': () =>\n Promise.resolve({\n // @ts-expect-error default.default\n // eslint-disable-next-line\n Image: imageImpl(Image.default.default ?? Image.default),\n }) as Promise<unknown>,\n 'next/dist/api/image': () =>\n Promise.resolve({\n // @ts-expect-error default.default\n // eslint-disable-next-line\n default: imageImpl(Image.default.default ?? Image.default),\n getImageProps: Image.getImageProps,\n }) as Promise<unknown>,\n ..._shared,\n };\n};\n\n// internal symbols to access global store\nconst REMOTE_COMPONENT_STORE = Symbol('REMOTE_COMPONENT_STORE');\nconst REMOTE_COMPONENT_KEY = '__REMOTE_COMPONENT_KEY__';\n\n// temporary global store for remote component HTML\n// the store is used to save the HTML of remote components for SSR without sending the content to the client\nconst self = globalThis as typeof globalThis & {\n [REMOTE_COMPONENT_STORE]?: Map<string, React.ReactNode>;\n};\n\nfunction getKey({\n bundle,\n route,\n name,\n}: {\n bundle?: string;\n route?: string;\n name?: string;\n}): string {\n return `${bundle ?? '__next'}:${route ?? '/'}:${name ?? '__vercel_remote_component'}__${crypto.randomUUID()}`;\n}\n\nfunction setComponent(key: string, component: React.ReactNode): void {\n if (!self[REMOTE_COMPONENT_STORE]) {\n self[REMOTE_COMPONENT_STORE] = new Map();\n }\n self[REMOTE_COMPONENT_STORE].set(key, component);\n}\n\nfunction getComponent(key: string): React.ReactNode | undefined {\n const component = self[REMOTE_COMPONENT_STORE]?.get(key);\n // remove the component from the store after retrieving it to prevent memory leaks\n // storing the HTML in the global store is only needed for SSR and it's temporary only used for a single render\n self[REMOTE_COMPONENT_STORE]?.delete(key);\n return component;\n}\n\nexport interface RemoteComponentProps {\n src: string;\n url?: string | URL;\n bundle?: string;\n route?: string;\n name?: string;\n isolate?: boolean;\n mode?: 'open' | 'closed';\n reset?: boolean;\n [REMOTE_COMPONENT_KEY]?: string;\n children?: React.ReactNode;\n}\n\n/**\n * This component handles the rendering of remote microfrontends.\n *\n * @param props - The properties for the remote component.\n * @returns A React component that renders the remote component.\n */\nexport function RemoteComponent(props: RemoteComponentProps) {\n const remoteComponent =\n typeof document !== 'undefined'\n ? null\n : // retrieve the HTML from the global store\n getComponent(\n props[REMOTE_COMPONENT_KEY] ?? '__vercel_remote_component',\n );\n\n useEffect(() => {\n const clientSelf = globalThis as typeof globalThis & {\n __remote_component_shared__?: Record<string, () => Promise<unknown>>;\n };\n // eslint-disable-next-line camelcase\n clientSelf.__remote_component_shared__ = shared(props.bundle ?? 'default');\n }, [props.bundle]);\n\n if (!props[REMOTE_COMPONENT_KEY]) {\n return (\n <RemoteComponentReact\n isolate={props.isolate}\n mode={props.mode}\n name={props.name}\n reset={props.reset}\n shared={shared(props.bundle ?? 'default')}\n src={props.url ?? props.src}\n >\n {props.children}\n </RemoteComponentReact>\n );\n }\n\n return (\n <RemoteComponentReact\n isolate={props.isolate}\n mode={props.mode}\n name={props.name}\n reset={props.reset}\n shared={shared(props.bundle ?? 'default')}\n src={props.url ?? props.src}\n >\n {remoteComponent}\n </RemoteComponentReact>\n );\n}\n\n/**\n * Fetches the remote component properties from the server. You need to pass these properties to the `<RemoteComponent>` component to render the fetched remote component.\n *\n * @param src - The source URL of the remote component. When using the Vercel Microfrontends solution, you can use relative paths, e.g. `/nextjs-app-remote/components/header`. Absolute URLs are also supported.\n * @param headers - The HTTP headers used for supporting the Vercel Microfrontends proxy.\n * @returns The properties of the remote component.\n *\n * @example\n *\n * ```tsx\n * import { getRemoteComponentProps } from 'remote-components/next/host/pages';\n * import type { GetServerSideProps } from 'next';\n *\n * export const getServerSideProps: GetServerSideProps<PageProps> = async function getServerSideProps({ req }) {\n * const myRemoteComponent = await getRemoteComponentProps(\n * '/nextjs-app-remote/components/header',\n * req.headers,\n * );\n * return {\n * props: {\n * remoteComponents: {\n * myRemoteComponent,\n * },\n * },\n * };\n * }\n * ```\n */\nexport async function getRemoteComponentProps(\n src: string,\n headers: IncomingHttpHeaders,\n): Promise<RemoteComponentProps> {\n if (typeof document !== 'undefined') {\n throw new Error(\n 'getRemoteComponentProps can only be used on the server side.',\n );\n }\n\n const {\n metadata: { bundle, route, runtime },\n name,\n links,\n component,\n nextData,\n url,\n } = await fetchRemoteComponent(\n src,\n headers instanceof Headers\n ? headers\n : // convert IncomingHttpHeaders to web standard Headers\n Object.entries(headers).reduce((acc, [key, value]) => {\n if (value) {\n if (Array.isArray(value)) {\n value.forEach((v) => acc.append(key, v));\n } else {\n acc.append(key, value);\n }\n }\n return acc;\n }, new Headers()),\n {\n rsc: true,\n },\n );\n\n const props = {\n src,\n bundle,\n name,\n route,\n runtime,\n buildId: nextData?.buildId ?? null,\n url: url.href,\n };\n\n const key = getKey(props);\n\n // do not render the HTML in development mode when remote is using Next.js Pages Router\n // this behavior is emulating the Next.js Pages Router FOUC as the styles are only applied on the client when running in development mode\n if (nextData?.buildId !== 'development') {\n // store the HTML in a global store\n setComponent(\n key,\n <>\n {links.map((link) => (\n <link\n key={`${link.as}_${link.href}`}\n {...link}\n precedence={undefined}\n />\n ))}\n {component}\n </>,\n );\n }\n\n return {\n ...props,\n // add remote component key to the props\n [REMOTE_COMPONENT_KEY]: key,\n };\n}\n"],"mappings":"AAuCa,SAqOP,UArOO,KAq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vB;AAAA,QACF;AACA,eAAO;AAAA,MACT,GAAG,IAAI,QAAQ,CAAC;AAAA;AAAA,IACpB;AAAA,MACE,KAAK;AAAA,IACP;AAAA,EACF;AAEA,QAAM,QAAQ;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS,UAAU,WAAW;AAAA,IAC9B,KAAK,IAAI;AAAA,EACX;AAEA,QAAM,MAAM,OAAO,KAAK;AAIxB,MAAI,UAAU,YAAY,eAAe;AAEvC;AAAA,MACE;AAAA,MACA,iCACG;AAAA,cAAM,IAAI,CAAC,SACV;AAAA,UAAC;AAAA;AAAA,YAEE,GAAG;AAAA,YACJ,YAAY;AAAA;AAAA,UAFP,GAAG,KAAK,MAAM,KAAK;AAAA,QAG1B,CACD;AAAA,QACA;AAAA,SACH;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,GAAG;AAAA;AAAA,IAEH,CAAC,oBAAoB,GAAG;AAAA,EAC1B;AACF;","names":["self","key"]}
|
package/dist/next/middleware.cjs
CHANGED
|
@@ -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":
|
|
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'
|
|
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;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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":[]}
|
package/dist/next/middleware.js
CHANGED
|
@@ -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":
|
|
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'
|
|
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":[]}
|
package/dist/react/index.cjs
CHANGED
|
@@ -47,6 +47,8 @@ function getRemoteComponentHtml(html) {
|
|
|
47
47
|
function RemoteComponent({
|
|
48
48
|
src,
|
|
49
49
|
isolate,
|
|
50
|
+
mode = "open",
|
|
51
|
+
reset,
|
|
50
52
|
credentials = "same-origin",
|
|
51
53
|
name: nameProp = "__vercel_remote_component",
|
|
52
54
|
shared = {},
|
|
@@ -69,12 +71,21 @@ function RemoteComponent({
|
|
|
69
71
|
const [data, setData] = (0, import_react.useState)(null);
|
|
70
72
|
const [remoteComponent, setRemoteComponent] = (0, import_react.useState)(null);
|
|
71
73
|
const shadowRootContainerRef = (0, import_react.useRef)(null);
|
|
72
|
-
const [shadowRoot, setShadowRoot] = (0, import_react.useState)(
|
|
73
|
-
|
|
74
|
-
|
|
74
|
+
const [shadowRoot, setShadowRoot] = (0, import_react.useState)(() => {
|
|
75
|
+
const self = globalThis;
|
|
76
|
+
const shadowRootKey = `__remote_components_shadowroot_${src ? new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href.replace(/[^a-z0-9]/g, "_") : ""}_${(data?.name ?? name).replace(/[^a-z0-9]/g, "_")}`;
|
|
77
|
+
const ssrShadowRoot = typeof document !== "undefined" ? document.getElementById(
|
|
78
|
+
`shadowroot_${src ? new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href.replace(/[^a-z0-9]/g, "_") : ""}_${(data?.name ?? name).replace(/[^a-z0-9]/g, "_")}`
|
|
79
|
+
)?.shadowRoot ?? self[shadowRootKey] ?? null : null;
|
|
80
|
+
self[shadowRootKey] = null;
|
|
81
|
+
return ssrShadowRoot;
|
|
82
|
+
});
|
|
75
83
|
const htmlRef = (0, import_react.useRef)(
|
|
76
|
-
typeof document !== "undefined" ? document.getElementById(
|
|
84
|
+
typeof document !== "undefined" ? document.getElementById(
|
|
85
|
+
`shadowroot_${src ? new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href.replace(/[^a-z0-9]/g, "_") : ""}_${(data?.name ?? name).replace(/[^a-z0-9]/g, "_")}`
|
|
86
|
+
)?.shadowRoot?.innerHTML ?? document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ?? document.querySelector(`div[data-bundle][data-route][id^="${name}"]`)?.innerHTML ?? document.querySelector("div[data-bundle][data-route]")?.innerHTML : null
|
|
77
87
|
);
|
|
88
|
+
const ssrHtmlRef = (0, import_react.useRef)(htmlRef.current);
|
|
78
89
|
const endTemplateRef = (0, import_react.useRef)(null);
|
|
79
90
|
const childrenRef = (0, import_react.useRef)(
|
|
80
91
|
typeof document !== "undefined" ? (() => {
|
|
@@ -98,11 +109,15 @@ function RemoteComponent({
|
|
|
98
109
|
}
|
|
99
110
|
if (isolate !== false && typeof document !== "undefined" && !shadowRoot) {
|
|
100
111
|
let shadowRootElement = null;
|
|
101
|
-
const element = document.getElementById(
|
|
112
|
+
const element = document.getElementById(
|
|
113
|
+
`shadowroot_${src ? new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href.replace(/[^a-z0-9]/g, "_") : ""}_${(data?.name ?? name).replace(/[^a-z0-9]/g, "_")}`
|
|
114
|
+
);
|
|
102
115
|
shadowRootElement = element?.shadowRoot ?? null;
|
|
103
116
|
if (!shadowRootElement && element) {
|
|
104
|
-
|
|
105
|
-
|
|
117
|
+
try {
|
|
118
|
+
shadowRootElement = element.attachShadow({ mode });
|
|
119
|
+
} catch {
|
|
120
|
+
}
|
|
106
121
|
}
|
|
107
122
|
if (shadowRootElement) {
|
|
108
123
|
shadowRootElement.querySelectorAll("*:not(link)").forEach((node) => {
|
|
@@ -111,7 +126,7 @@ function RemoteComponent({
|
|
|
111
126
|
setShadowRoot(shadowRootElement);
|
|
112
127
|
}
|
|
113
128
|
}
|
|
114
|
-
}, [name, isolate, shadowRoot, remoteComponent]);
|
|
129
|
+
}, [name, isolate, shadowRoot, remoteComponent, mode]);
|
|
115
130
|
const url = (0, import_react.useMemo)(() => {
|
|
116
131
|
if (typeof src !== "string")
|
|
117
132
|
return new URL(
|
|
@@ -134,9 +149,7 @@ function RemoteComponent({
|
|
|
134
149
|
const fetchInit = {
|
|
135
150
|
method: "GET",
|
|
136
151
|
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
|
|
152
|
+
Accept: "text/html"
|
|
140
153
|
},
|
|
141
154
|
credentials
|
|
142
155
|
};
|
|
@@ -184,7 +197,7 @@ function RemoteComponent({
|
|
|
184
197
|
"script[src],script[data-src]"
|
|
185
198
|
);
|
|
186
199
|
const inlineScripts = doc.querySelectorAll(
|
|
187
|
-
"script:not([src]):not([data-src]):not([id*='_rsc'])"
|
|
200
|
+
"script:not([src]):not([data-src]):not([id*='_rsc']):not([id='__NEXT_DATA__']):not([id='__REMOTE_NEXT_DATA__'])"
|
|
188
201
|
);
|
|
189
202
|
const self = globalThis;
|
|
190
203
|
const prevNextScripts = self.__next_s;
|
|
@@ -317,15 +330,16 @@ function RemoteComponent({
|
|
|
317
330
|
remoteComponent ?? children
|
|
318
331
|
] });
|
|
319
332
|
if (isolate !== false) {
|
|
320
|
-
const shadowRemoteComponentHtml = shadowRoot?.querySelector(
|
|
321
|
-
`#__REMOTE_COMPONENT${name}`
|
|
322
|
-
);
|
|
333
|
+
const shadowRemoteComponentHtml = shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ?? shadowRoot?.querySelector("div[data-bundle][data-route]");
|
|
323
334
|
if (shadowRemoteComponentHtml) {
|
|
324
335
|
shadowRemoteComponentHtml.remove();
|
|
325
336
|
}
|
|
326
337
|
if (shadowRoot && remoteComponent && htmlRef.current) {
|
|
327
|
-
|
|
328
|
-
|
|
338
|
+
if (ssrHtmlRef.current) {
|
|
339
|
+
const content = shadowRoot.querySelectorAll(":not(link,style)");
|
|
340
|
+
content.forEach((node) => node.remove());
|
|
341
|
+
ssrHtmlRef.current = null;
|
|
342
|
+
}
|
|
329
343
|
htmlRef.current = null;
|
|
330
344
|
}
|
|
331
345
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
|
|
@@ -333,12 +347,35 @@ function RemoteComponent({
|
|
|
333
347
|
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
|
|
334
348
|
"div",
|
|
335
349
|
{
|
|
336
|
-
id: `shadowroot_${data?.name ?? name}`,
|
|
350
|
+
id: `shadowroot_${src ? new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href.replace(/[^a-z0-9]/g, "_") : ""}_${(data?.name ?? name).replace(/[^a-z0-9]/g, "_")}`,
|
|
337
351
|
ref: shadowRootContainerRef,
|
|
338
352
|
children: [
|
|
339
353
|
typeof document === "undefined" ? (
|
|
340
354
|
// eslint-disable-next-line react/no-unknown-property
|
|
341
|
-
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("template", { shadowrootmode:
|
|
355
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("template", { shadowrootmode: mode, children: [
|
|
356
|
+
typeof document === "undefined" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
357
|
+
"div",
|
|
358
|
+
{
|
|
359
|
+
dangerouslySetInnerHTML: {
|
|
360
|
+
__html: `<img
|
|
361
|
+
alt="" decoding="async" style="display:none"
|
|
362
|
+
src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
|
|
363
|
+
onload="(function(el){
|
|
364
|
+
const root = el.getRootNode();
|
|
365
|
+
globalThis.__remote_components_shadowroot_${src ? new URL(src, typeof location !== "undefined" ? location.origin : "http://localhost").href.replace(/[^a-z0-9]/g, "_") : ""}_${(data?.name ?? name).replace(/[^a-z0-9]/g, "_")} = root;
|
|
366
|
+
el.parentElement.remove();
|
|
367
|
+
})(this)"
|
|
368
|
+
/>`
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
) : null,
|
|
372
|
+
reset ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
373
|
+
"style",
|
|
374
|
+
{
|
|
375
|
+
"data-remote-components-reset": true,
|
|
376
|
+
children: `:host { all: initial; }`
|
|
377
|
+
}
|
|
378
|
+
) : null,
|
|
342
379
|
linksToRender,
|
|
343
380
|
children
|
|
344
381
|
] })
|
package/dist/react/index.cjs.map
CHANGED
|
@@ -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,8B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5B,CAAC,GACH;AAEF,QAAM,gBACJ,MAAM,OAAO,IAAI,CAAC,SAChB;AAAA,IAAC;AAAA;AAAA,MACC,IAAI,KAAK;AAAA,MACT,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,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 shadow DOM mode to use when isolating the remote component. */\n mode?: 'open' | 'closed';\n /** Whether to include a CSS reset style in the shadow DOM. Defaults to `false`. */\n reset?: 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 mode = 'open',\n reset,\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 const self = globalThis as Record<\n `__remote_components_shadowroot_${string}`,\n ShadowRoot | null\n >;\n const shadowRootKey =\n `__remote_components_shadowroot_${src ? new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href.replace(/[^a-z0-9]/g, '_') : ''}_${(data?.name ?? name).replace(/[^a-z0-9]/g, '_')}` as const;\n const ssrShadowRoot =\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, '_') : ''}_${(data?.name ?? name).replace(/[^a-z0-9]/g, '_')}`,\n )?.shadowRoot ??\n self[shadowRootKey] ??\n null)\n : null;\n self[shadowRootKey] = null;\n return ssrShadowRoot;\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, '_') : ''}_${(data?.name ?? name).replace(/[^a-z0-9]/g, '_')}`,\n )?.shadowRoot?.innerHTML ??\n document.getElementById(`__REMOTE_COMPONENT${name}`)?.innerHTML ??\n document.querySelector(`div[data-bundle][data-route][id^=\"${name}\"]`)\n ?.innerHTML ??\n document.querySelector('div[data-bundle][data-route]')?.innerHTML)\n : null,\n );\n const ssrHtmlRef = useRef<string | null>(htmlRef.current);\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(\n `shadowroot_${src ? new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href.replace(/[^a-z0-9]/g, '_') : ''}_${(data?.name ?? name).replace(/[^a-z0-9]/g, '_')}`,\n );\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 try {\n shadowRootElement = element.attachShadow({ mode });\n } catch {\n // do nothing if attachShadow fails because of existing shadow root\n }\n }\n\n if (shadowRootElement) {\n // remove all nodes from the shadow root except links\n shadowRootElement.querySelectorAll('*:not(link)').forEach((node) => {\n node.remove();\n });\n setShadowRoot(shadowRootElement);\n }\n }\n }, [name, isolate, shadowRoot, remoteComponent, mode]);\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 =\n shadowRoot?.querySelector(`#__REMOTE_COMPONENT${name}`) ??\n shadowRoot?.querySelector('div[data-bundle][data-route]');\n if (shadowRemoteComponentHtml) {\n shadowRemoteComponentHtml.remove();\n }\n\n if (shadowRoot && remoteComponent && htmlRef.current) {\n if (ssrHtmlRef.current) {\n const content = shadowRoot.querySelectorAll(':not(link,style)');\n content.forEach((node) => node.remove());\n ssrHtmlRef.current = null;\n }\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).replace(/[^a-z0-9]/g, '_')}`}\n ref={shadowRootContainerRef}\n >\n {typeof document === 'undefined' ? (\n // eslint-disable-next-line react/no-unknown-property\n <template shadowrootmode={mode}>\n {typeof document === 'undefined' ? (\n <div\n dangerouslySetInnerHTML={{\n __html: `<img\n alt=\"\" decoding=\"async\" style=\"display:none\"\n src=\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==\"\n onload=\"(function(el){\n const root = el.getRootNode();\n globalThis.__remote_components_shadowroot_${src ? new URL(src, typeof location !== 'undefined' ? location.origin : 'http://localhost').href.replace(/[^a-z0-9]/g, '_') : ''}_${(data?.name ?? name).replace(/[^a-z0-9]/g, '_')} = root;\n el.parentElement.remove();\n })(this)\"\n />`,\n }}\n />\n ) : null}\n {reset ? (\n <style\n data-remote-components-reset\n >{`:host { all: initial; }`}</style>\n ) : null}\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;AAwgBI;AAxgBJ,mBAOO;AACP,uBAA6B;AAC7B,8BAOO;AAuCP,SAAS,u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AAc,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"]}
|
package/dist/react/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
-
import { R as RemoteComponentProps$1 } from '../types-
|
|
2
|
+
import { R as RemoteComponentProps$1 } from '../types-b8210fd3.js';
|
|
3
3
|
import 'react';
|
|
4
4
|
import '../types-280a3640.js';
|
|
5
5
|
|
|
@@ -30,6 +30,10 @@ interface RemoteComponentProps {
|
|
|
30
30
|
src?: string | URL;
|
|
31
31
|
/** Whether to isolate the remote component using a Shadow DOM wrapper. */
|
|
32
32
|
isolate?: boolean;
|
|
33
|
+
/** The shadow DOM mode to use when isolating the remote component. */
|
|
34
|
+
mode?: 'open' | 'closed';
|
|
35
|
+
/** Whether to include a CSS reset style in the shadow DOM. Defaults to `false`. */
|
|
36
|
+
reset?: boolean;
|
|
33
37
|
/** The credentials to use for the fetch request. Defaults to `same-origin`. */
|
|
34
38
|
credentials?: RequestCredentials;
|
|
35
39
|
name?: string;
|
|
@@ -74,6 +78,6 @@ interface RemoteComponentProps {
|
|
|
74
78
|
* />
|
|
75
79
|
* ```
|
|
76
80
|
*/
|
|
77
|
-
declare function RemoteComponent({ src, isolate, credentials, name: nameProp, shared, children, }: RemoteComponentProps): react_jsx_runtime.JSX.Element;
|
|
81
|
+
declare function RemoteComponent({ src, isolate, mode, reset, credentials, name: nameProp, shared, children, }: RemoteComponentProps): react_jsx_runtime.JSX.Element;
|
|
78
82
|
|
|
79
83
|
export { RemoteComponent, RemoteComponentProps };
|