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 RelationshipsFolderJsonApiResource = {data?: {id: string, type: 'folder-segment'} | undefined}; export type EntitiesPredictiveSegmentUpdateRepresentation = {id?: string | undefined, type?: 'predictive-segment' | undefined, attributes?: ({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}) | undefined, relationships?: ({parentFolder?: RelationshipsFolderJsonApiResource | undefined}) | undefined}; export type CreateApiEntitiesPredictiveSegmentsArgs = {body: EntitiesPredictiveSegmentUpdateRepresentation}; export type CreateApiEntitiesPredictiveSegmentsOptions = {baseUrl?: 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 predictiveSegmentJsonApiResourceAttr = z.object({audienceId: 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(), modelUpdatedAt: z.string().optional()}); export const userJsonApiResource = z.object({id: z.string(), type: z.literal("user"), attributes: z.object({tdUserId: z.string(), name: z.string()})}); export const entitiesGetPredictiveSegmentJsonApiResponse = z.object({data: predictiveSegmentJsonApiResourceAttr, included: z.array(userJsonApiResource)}); 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 * * POST /entities/predictive_segments */ export const createApiEntitiesPredictiveSegments = async (args: CreateApiEntitiesPredictiveSegmentsArgs, options?: CreateApiEntitiesPredictiveSegmentsOptions) => { const {baseUrl = "https://api-cdp.treasuredata.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/vnd.treasuredata.v1+json") headers.set('accept', "application/vnd.treasuredata.v1+json") const url = `${baseUrl.replace(/\/+$/, '')}/entities/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(entitiesGetPredictiveSegmentJsonApiResponse, await res.json()) };