import {z} from 'zod' export type AudienceTarget = {operator?: ('AND' | 'OR') | undefined, audience_segment_ids?: Array | undefined}; export type TargetDimensionInclude = {code: string, operator: 'AND' | 'OR', target_value_ids: Array}; export type TargetDimensionExclude = {code?: string | undefined, operator?: ('AND' | 'OR') | undefined, target_value_ids: Array}; export type DayPart = {user_time?: boolean | undefined, start_hour: number, end_hour: number, days: Array<'M' | 'T' | 'W' | 'R' | 'F' | 'S' | 'U'>}; export type TargetingBase = {audience?: ({include?: Array | undefined, exclude?: Array | undefined}) | undefined, contextual?: ({include?: Array | undefined, exclude?: Array | undefined}) | undefined, my_data?: ({include?: ({pixel_bundle_ids?: Array | undefined, operator?: ('AND' | 'OR') | undefined}) | undefined, exclude?: ({pixel_bundle_ids?: Array | undefined}) | undefined}) | undefined, location?: ({include?: Array | undefined, exclude?: Array | undefined}) | undefined, technology?: ({include?: Array | undefined, exclude?: Array | undefined}) | undefined, day_parts?: Array | undefined}; export type CreateApiTargetingArgs = {body: {strategy_id: Array, targeting?: TargetingBase | undefined}}; export type CreateApiTargetingOptions = {baseUrl?: string | undefined, Auth0?: string | undefined, fetch?: typeof fetch | undefined}; export const locationResponse = z.object({strategy_id: z.number(), strategy_target_id: z.number(), strategy_target_exclude: z.boolean(), strategy_target_active: z.boolean(), strategy_target_operator: z.string().min(1), strategy_target_value_id: z.number(), target_dimension_code: z.string().min(1), target_dimension_name: z.string().min(1), target_value_id: z.number(), target_value_name: z.string().min(1), target_value_value: z.number(), target_value_code: z.string().min(1), strategy_count: z.number()}); export const createApiTargetingResponse = z.object({data: z.object({location: z.array(locationResponse).nullable().optional()}).optional(), meta: z.object({status: z.string().min(1), count: z.number()}), errors: z.array(z.unknown()).nullable().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 }; /** * Add and View Targeting * * POST /targeting */ export const createApiTargeting = async (args: CreateApiTargetingArgs, options?: CreateApiTargetingOptions) => { const {baseUrl = "https://api.mediamath.com/api/v3.0", fetch: fetchFn = fetch, Auth0} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (Auth0 !== undefined) headers.set('authorization', `Bearer ${Auth0}`) const url = `${baseUrl.replace(/\/+$/, '')}/targeting${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(createApiTargetingResponse, await res.json()) };