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 CreateApiV2ListsArgs = {body: {dynamic?: boolean | undefined, imported?: boolean | undefined, mailFrequency?: ('disabled' | 'daily' | 'weekly' | 'monthly') | undefined, maxCompanies?: number | undefined, name: string, processInitialized?: boolean | undefined, query?: Array | undefined, similarDomains?: Array | undefined}}; export type CreateApiV2ListsOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const listAnalytics = z.object({companiesCount: z.number().nullable().optional(), id: z.number().optional(), listId: z.number().nullable().optional()}); 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 team = z.object({admin: z.boolean().nullable(), country: z.string().nullable(), createdAt: z.string().nullable(), credits: z.number(), creditsPack: z.number(), id: z.number(), name: z.string().nullable(), role: z.string().nullable().optional(), stripeCustomerId: z.string().nullable(), stripeProductId: z.string().nullable(), stripeSubscribed: z.boolean(), stripeSubscriptionId: z.string().nullable(), stripeSubscriptionStatus: z.string().nullable(), websiteUrl: z.string().nullable()}); export const user = z.object({colorMode: z.enum(["dark", "light", "system"]).optional(), createdAt: z.string().nullable().optional(), currentTeamId: z.number().nullable(), email: z.string(), emailFree: z.boolean().nullable(), emailVerified: z.boolean().nullable(), emailVerifiedResentAt: z.string().nullable(), fullName: z.string().nullable(), hasPassword: z.boolean().nullable(), id: z.number(), locale: z.unknown(), pictureUrl: z.string().nullable(), referral: z.string().nullable().optional(), role: z.enum(["owner", "user"]).nullable().optional()}); export const lLMAnswer = z.object({companyId: z.number(), explanation: z.string().optional(), fields: z.array(z.object({description: z.string().optional(), key: z.string(), type: z.enum(["array|boolean", "array|number", "array|string", "boolean", "number", "string"]), values: z.array(z.string()).optional()})).optional(), grounded: z.boolean().optional(), output: z.record(z.string(), z.unknown()), question: z.string(), score: z.number()}); export const action = z.object({attempts: z.number().optional(), cost: z.number().nullable().optional(), createdAt: z.string().nullable().optional(), data: z.object({cleanedUp: z.number().optional(), completed: z.array(z.string()).optional(), completedDomains: z.number().optional(), completedDomainsSample: z.array(z.string()).optional(), count: z.number().optional(), domain: z.string().optional(), domains: z.array(z.string()).optional(), domainsSample: z.array(z.string()).optional(), elasticQuery: z.unknown(), failed: z.array(z.string()).optional(), failedDomains: z.number().optional(), failedDomainsSample: z.array(z.string()).optional(), fields: z.array(z.object({description: z.string().optional(), key: z.string(), type: z.enum(["array|boolean", "array|number", "array|string", "boolean", "number", "string"]), values: z.array(z.string()).optional()})).optional(), grounded: z.boolean().optional(), job: z.enum(["ask-domain", "ask-list", "enrich-companies", "enrich-list", "cleanup-list"]).optional(), model: z.enum(["claude", "claude-mini", "cousteau", "cousteau2", "cousteau2-thinking", "gpt", "gpt-mini", "groq", "groq-mini", "llama4"]).optional(), query: z.array(segmentationCondition).optional(), question: z.string().optional(), team: team.optional(), totalDomains: z.number().optional(), user: user.optional()}).optional(), id: z.number(), listId: z.number().optional(), promptId: z.number().optional(), result: z.object({answers: z.array(lLMAnswer).optional(), cleanedUp: z.number().optional(), domains: z.array(z.string()).optional()}).optional(), status: z.enum(["active", "completed", "failed", "pending"]), teamId: z.number().optional(), type: z.enum(["companies:added", "jobs:request"]).optional(), updatedAt: z.string().nullable().optional()}); export const list = z.object({analytics: listAnalytics.optional(), companyListId: z.number().nullable().optional(), createdAt: z.string().nullable(), dynamic: z.boolean().nullable(), exporting: z.boolean(), exportingAt: z.string().nullable(), id: z.number(), imported: z.boolean(), mailFrequencies: z.record(z.string(), z.enum(["daily", "disabled", "monthly", "weekly"])).nullable().optional(), maxCompanies: z.number().nullable(), name: z.string(), processActive: z.boolean(), processDisabled: z.boolean().nullable().optional(), processingAt: z.string().nullable(), processInitialized: z.boolean(), processMessage: z.string().nullable(), query: z.array(segmentationCondition).optional(), querySimilar: z.array(z.string()), teamId: z.string().nullable().optional(), unseenActions: z.array(action).optional(), userId: z.number().nullable().optional(), vectors: z.array(z.array(z.number())).optional()}); 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 }; /** * Create a new list. * * POST /v2/lists */ export const createApiV2Lists = async (args: CreateApiV2ListsArgs, options?: CreateApiV2ListsOptions) => { 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/lists${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(list, await res.json()) };