diff --git a/tools/tools.tsx b/tools/tools.tsx index 777171d..e862bf2 100644 --- a/tools/tools.tsx +++ b/tools/tools.tsx @@ -9,11 +9,28 @@ export type SuperJSONProps

= P & { _superjson?: ReturnType["meta"]; }; +let alreadyPatched = '__alreadyPatchedBySuperJSONPlugin'; + +function isAlreadyPatched(gssp: any) { + return gssp && gssp[alreadyPatched]; +} + +function markAsPatched(gssp: any) { + if (!gssp) { + return gssp; + } + gssp[alreadyPatched] = true; +} + export function withSuperJSONProps

( gssp: GetServerSideProps

, exclude: string[] = [] ): GetServerSideProps> { - return async function withSuperJSON(...args) { + if (isAlreadyPatched(gssp)) { + return gssp; + } + + return markAsPatched(async function withSuperJSON(...args) { const result = await gssp(...args); if (!("props" in result)) { @@ -48,11 +65,15 @@ export function withSuperJSONProps

( ...result, props, }; - }; + }); } export function withSuperJSONInitProps(gip: any, exclude: string[] = []): any { - return async function withSuperJSON(...args: any[]) { + if (isAlreadyPatched(gip)) { + return gip; + } + + return markAsPatched(async function withSuperJSON(...args: any[]) { const result = await gip(...args); const excludedPropValues = exclude.map((propKey) => { @@ -79,7 +100,7 @@ export function withSuperJSONInitProps(gip: any, exclude: string[] = []): any { ...result, ...props, }; - }; + }); } export function deserializeProps

(serializedProps: SuperJSONProps

): P { @@ -90,13 +111,16 @@ export function deserializeProps

(serializedProps: SuperJSONProps

): P { export function withSuperJSONPage

( Page: React.ComponentType

): React.ComponentType> { + if (isAlreadyPatched(Page)) { + return Page; + } function WithSuperJSON(serializedProps: SuperJSONProps

) { return (serializedProps)} />; } hoistNonReactStatics(WithSuperJSON, Page); - return WithSuperJSON; + return markAsPatched(WithSuperJSON); } export function serialize

(props: P): SuperJSONProps

{