import { CryptoOnrampConstructor, CryptoOnrampInitOptions, OnrampCoordinator, } from '../types/crypto-js/embedded-components-onramp'; export type LoadCryptoOnrampAndInitialize = ( publishableKey: string, options?: CryptoOnrampInitOptions ) => Promise; const EMBEDDED_COMPONENTS_ONRAMP_URL = 'https://js.stripe.com/crypto-onramp/v1/crypto-onramp.js'; export const findScript = (): HTMLScriptElement | null => { const scripts = document.querySelectorAll( `script[src^="${EMBEDDED_COMPONENTS_ONRAMP_URL}"]` ); for (let i = 0; i < scripts.length; i++) { const script = scripts[i]; if (EMBEDDED_COMPONENTS_ONRAMP_URL !== script.src) { continue; } return script; } return null; }; const injectScript = (): HTMLScriptElement => { const script = document.createElement('script'); script.src = EMBEDDED_COMPONENTS_ONRAMP_URL; script.async = true; script.type = 'module'; const headOrBody = document.head || document.body; if (!headOrBody) { throw new Error( 'Expected document.body not to be null. loadCryptoOnrampAndInitialize requires a element.' ); } headOrBody.appendChild(script); return script; }; let cryptoOnrampPromise: Promise | null = null; export const loadScript = (): Promise => { if (cryptoOnrampPromise !== null) { return cryptoOnrampPromise; } cryptoOnrampPromise = new Promise((resolve, reject) => { if (typeof window === 'undefined') { resolve(null); return; } if (window.loadCryptoOnrampAndInitialize) { resolve(window.loadCryptoOnrampAndInitialize); return; } try { let script = findScript(); if (!script) { script = injectScript(); } script.addEventListener('load', () => { if (window.loadCryptoOnrampAndInitialize) { resolve(window.loadCryptoOnrampAndInitialize); } else { reject(new Error('loadCryptoOnrampAndInitialize not available')); } }); script.addEventListener('error', () => { reject(new Error('Failed to load loadCryptoOnrampAndInitialize')); }); } catch (error) { reject(error); return; } }); return cryptoOnrampPromise; }; export const loadCryptoOnrampAndInitialize: LoadCryptoOnrampAndInitialize = ( publishableKey: string, options?: CryptoOnrampInitOptions ) => { return loadScript().then( (maybeCryptoOnramp: CryptoOnrampConstructor | null) => { if (maybeCryptoOnramp === null) { return null; } return maybeCryptoOnramp(publishableKey, options); } ); };