import {z} from 'zod' export type PredictiveSegmentGradeThresholds = Array; export type FunctionExpression = {function: '+' | '-' | '*' | '/', arg?: number | undefined} | {function: 'replace', search?: string | undefined, replacement?: (string | null) | undefined} | {function: 'substr', start?: number | undefined, length?: number | undefined} | {function: 'regexp_extract', pattern?: string | undefined, group?: number | undefined} | {function: 'day_of_week' | 'from_iso8601_timestamp' | 'ln' | 'elapsed_days' | 'td_ip_to_least_specific_subdivision_name' | 'td_ip_to_country_name' | 'td_ip_to_city_name' | 'td_ip_to_connection_type' | 'td_ip_to_domain'} | {function: 'cast_as_quantitative', default: number} | {function: 'cast_as_categorical', default: string} | {function: 'cast_as_categorical_array'} | {function: 'if', op?: ('>' | '<' | '<=' | '>=' | '=' | '!=' | 'is' | 'is\' | 'not') | undefined, right_value?: (number | null) | undefined, then?: number | undefined, else?: number | undefined}; export type PredictiveSegmentPreprocessItem = {column: string, source: {column?: string | undefined, table?: string | undefined, functions?: Array | undefined}}; export type PredictiveSegmentParameters = {name?: string | undefined, description?: (string | null) | undefined, baseSegmentId?: (number | null) | undefined, segmentId?: number | undefined, scoredSegmentId?: (number | null) | undefined, gradeThresholds?: PredictiveSegmentGradeThresholds | undefined, categoricalAsColumnNames?: Array | undefined, categoricalArrayAsColumnNames?: Array | undefined, quantitativeAsColumnNames?: Array | undefined, preprocess?: Array | undefined}; export type CreateApiAudiencesAudienceIdPredictiveSegmentsArgs = {audienceId: number, body: PredictiveSegmentParameters}; export type CreateApiAudiencesAudienceIdPredictiveSegmentsOptions = {baseUrl?: string | undefined, TdApikeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const predictiveSegmentAccuracy = z.number().gte(0).lte(100).nullable(); export const predictiveSegmentAreaUnderRocCurve = z.number().gte(0).lte(1).nullable(); export const predictiveSegmentGradeThresholds = z.array(z.number().gte(0).lte(100)); export const predictiveSegment = z.object({audienceId: z.string().optional(), id: z.string().optional(), baseSegmentId: z.string().nullable().optional(), segmentId: z.string().optional(), scoredSegmentId: z.string().nullable().optional(), name: z.string().optional(), description: z.string().nullable().optional(), categoricalAsColumnNames: z.array(z.string()).optional(), categoricalArrayAsColumnNames: z.array(z.string()).optional(), quantitativeAsColumnNames: z.array(z.string()).optional(), accuracy: predictiveSegmentAccuracy.optional(), areaUnderRocCurve: predictiveSegmentAreaUnderRocCurve.optional(), gradeThresholds: predictiveSegmentGradeThresholds.optional(), createdAt: z.string().optional(), updatedAt: z.string().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 predictive scoring model (legacy) * * POST /audiences/{audienceId}/predictive_segments */ export const createApiAudiencesAudienceIdPredictiveSegments = async (args: CreateApiAudiencesAudienceIdPredictiveSegmentsArgs, options?: CreateApiAudiencesAudienceIdPredictiveSegmentsOptions) => { const {baseUrl = "https://api-cdp.treasuredata.com", fetch: fetchFn = fetch, TdApikeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (TdApikeyAuth !== undefined) headers.set("Authorization", TdApikeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/audiences/${encodeURIComponent(String(args.audienceId))}/predictive_segments${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(predictiveSegment, await res.json()) };