import { Analytics } from '../../../core/analytics' import { logger } from '../../logger' import { IClearbitDataV1, IIntentSourcesSourceOptions } from '../types' declare global { interface Window { clearbitCallback?: (data: IClearbitDataV1) => Promise } } export function loadClearbitV1( analytics: Analytics, options: IIntentSourcesSourceOptions ): void { if (!options.token) { logger.error( 'Token is missing for the Clearbit intent source. Make sure it is included in your script setup.' ) return } const response = sessionStorage.getItem('cb_reveal') if (response || analytics.group().traits()?.website) { return } const handleClearbitResponse = async (response: IClearbitDataV1) => { if ( !response?.company || response.type !== 'company' || !response.company.domain ) { return } const { domain, name, geo, category, metrics } = response.company const traits = { website: domain, intentSource: 'clearbit', name: name, country: geo.country, industry: category.industryGroup, number_of_employees: metrics.employeesRange, annual_revenue: metrics.estimatedAnnualRevenue, } await analytics.group(null, traits) sessionStorage.setItem('cb_reveal', JSON.stringify(traits)) } window.clearbitCallback = handleClearbitResponse const script = document.createElement('script') script.src = `https://reveal.clearbit.com/v1/companies/reveal?authorization=${options.token}&callback=clearbitCallback` script.onerror = () => logger.error('Failed to load Clearbit script') document.body.appendChild(script) }