import {z} from 'zod' export type SegmentationCondition = {attribute: 'about.businessType' | 'about.industries' | 'about.industry' | 'about.name' | 'about.totalEmployees' | 'about.yearFounded' | 'ai.search' | 'analytics.monthlyVisitors' | 'apps' | 'codes.naics' | 'codes.sic' | 'contacts' | 'domain.domain' | 'domain.tld' | 'finances.revenue' | 'finances.stockExchange' | 'locations.headquarters.city.code' | 'locations.headquarters.continent.code' | 'locations.headquarters.country.code' | 'locations.headquarters.county.code' | 'locations.headquarters.state.code' | 'meta.listIds' | 'meta.score' | 'meta.syncedAt' | 'socials' | 'socials.linkedin.id' | 'technologies.active' | 'technologies.categories' | 'urls', blockedOperator?: boolean | undefined, operator: 'and' | 'or', sign: 'equals' | 'exactEquals' | 'greater' | 'lower' | 'notEquals', values: Array}; export type CreateApiV2CompaniesAnalyticsExportArgs = {body: {actionId?: number | undefined, attributes?: (Array<'about.businessType' | 'about.industries' | 'about.industry' | 'about.totalEmployees' | 'about.yearFounded' | 'analytics.monthlyVisitors' | 'apps' | 'codes.naics' | 'codes.sic' | 'contacts' | 'domain.tld' | 'finances.revenue' | 'finances.stockExchange' | 'locations.headquarters.city.code' | 'locations.headquarters.continent.code' | 'locations.headquarters.country.code' | 'locations.headquarters.county.code' | 'locations.headquarters.state.code' | 'meta.score' | 'meta.syncedAt' | 'socials' | 'technologies.active' | 'technologies.categories'>) | undefined, format?: ('csv' | 'json' | 'txt' | 'xls' | 'xml') | undefined, full?: boolean | undefined, listId?: number | undefined, query?: Array | undefined, size?: number | undefined, sort?: ('asc' | 'desc') | undefined}}; export type CreateApiV2CompaniesAnalyticsExportOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const segmentationCondition = z.object({attribute: z.enum(["about.businessType", "about.industries", "about.industry", "about.name", "about.totalEmployees", "about.yearFounded", "ai.search", "analytics.monthlyVisitors", "apps", "codes.naics", "codes.sic", "contacts", "domain.domain", "domain.tld", "finances.revenue", "finances.stockExchange", "locations.headquarters.city.code", "locations.headquarters.continent.code", "locations.headquarters.country.code", "locations.headquarters.county.code", "locations.headquarters.state.code", "meta.listIds", "meta.score", "meta.syncedAt", "socials", "socials.linkedin.id", "technologies.active", "technologies.categories", "urls"]), blockedOperator: z.boolean().optional(), operator: z.enum(["and", "or"]), sign: z.enum(["equals", "exactEquals", "greater", "lower", "notEquals"]), values: z.array(z.union([z.string(), z.number()]))}); export const createApiV2CompaniesAnalyticsExportResponse = z.object({data: z.array(z.object({count: z.number(), name: z.string(), percentageOfAll: z.number(), percentageOfTotal: z.number()})), meta: z.object({listId: z.number().optional(), query: z.array(segmentationCondition), totalDatapoints: z.number(), totalDocuments: z.number(), totalValues: z.number()})}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Export analytics data for search segmentations and lists. * * POST /v2/companies/analytics/export */ export const createApiV2CompaniesAnalyticsExport = async (args: CreateApiV2CompaniesAnalyticsExportArgs, options?: CreateApiV2CompaniesAnalyticsExportOptions) => { const {baseUrl = "https://api.thecompaniesapi.com", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (apiKey !== undefined) headers.set("Authorization", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v2/companies/analytics/export${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApiV2CompaniesAnalyticsExportResponse, await res.json()) };