|
| 1 | +import { removeEdgesAndNodes } from '@bigcommerce/catalyst-client'; |
| 2 | +import Script from 'next/script'; |
| 3 | +import { ComponentProps } from 'react'; |
| 4 | + |
| 5 | +import { FragmentOf } from '~/client/graphql'; |
| 6 | + |
| 7 | +import { ScriptsFragment } from './fragment'; |
| 8 | + |
| 9 | +type ScriptsData = FragmentOf<typeof ScriptsFragment>; |
| 10 | + |
| 11 | +interface ScriptRendererProps { |
| 12 | + scripts: ScriptsData['headerScripts'] | null; |
| 13 | + strategy: ComponentProps<typeof Script>['strategy']; |
| 14 | +} |
| 15 | + |
| 16 | +export const ScriptManagerScripts = ({ scripts, strategy }: ScriptRendererProps) => { |
| 17 | + if (!scripts?.edges) return null; |
| 18 | + |
| 19 | + const scriptNodes = removeEdgesAndNodes(scripts); |
| 20 | + |
| 21 | + return ( |
| 22 | + <> |
| 23 | + {scriptNodes |
| 24 | + .map((script) => { |
| 25 | + const scriptProps: ComponentProps<typeof Script> = { |
| 26 | + strategy, |
| 27 | + }; |
| 28 | + |
| 29 | + // Handle external scripts (SrcScript) |
| 30 | + if (script.__typename === 'SrcScript' && script.src) { |
| 31 | + scriptProps.src = script.src; |
| 32 | + |
| 33 | + // Add integrity hashes if provided |
| 34 | + if (script.integrityHashes.length > 0) { |
| 35 | + scriptProps.integrity = script.integrityHashes |
| 36 | + .map((hashObj) => hashObj.hash) |
| 37 | + .join(' '); |
| 38 | + scriptProps.crossOrigin = 'anonymous'; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // Handle inline scripts (InlineScript) |
| 43 | + if (script.__typename === 'InlineScript' && script.scriptTag) { |
| 44 | + const scriptMatch = /<script[^>]*>([\s\S]*?)<\/script>/i.exec(script.scriptTag); |
| 45 | + |
| 46 | + if (scriptMatch?.[1]) { |
| 47 | + scriptProps.dangerouslySetInnerHTML = { |
| 48 | + __html: scriptMatch[1], |
| 49 | + }; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + scriptProps.id = `bc-script-${script.entityId}`; |
| 54 | + |
| 55 | + // Return null for invalid scripts (will be filtered out) |
| 56 | + if (!scriptProps.src && !scriptProps.dangerouslySetInnerHTML) { |
| 57 | + return null; |
| 58 | + } |
| 59 | + |
| 60 | + return scriptProps; |
| 61 | + }) |
| 62 | + .filter((scriptProps): scriptProps is ComponentProps<typeof Script> => scriptProps !== null) |
| 63 | + .map((scriptProps) => { |
| 64 | + return <Script key={scriptProps.id} {...scriptProps} />; |
| 65 | + })} |
| 66 | + </> |
| 67 | + ); |
| 68 | +}; |
0 commit comments