import {z} from 'zod' export type GetApiCmV1LogsArgs = {ad_account_id: string, 'date_range.start': string, 'date_range.end': string}; export type GetApiCmV1LogsOptions = {baseUrl?: string | undefined, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const dspLogType = z.enum(["UNKNOWN_LOG_TYPE", "IMP", "CLICK", "CONVERSION", "SKAN_CONVERSION", "ENGAGED_VIEW"]); export const dspLogFormat = z.enum(["UNKNOWN_LOG_FORMAT", "CSV", "AVRO", "PARQUET"]); export const dspLogStatus = z.enum(["UNKNOWN_LOG_STATUS", "ACCEPTED", "READY", "FAILED"]); export const dspLog = z.object({id: z.string().optional(), type: dspLogType, format: dspLogFormat.optional(), date: z.string(), ad_account_id: z.string(), status: dspLogStatus.optional(), skip_compression: z.boolean().optional(), expire_at: z.string().optional(), created_at: z.string().optional(), updated_at: z.string().optional()}); export const messagesListLogsResponse = z.object({logs: z.array(dspLog).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 }; /** * List up logs. * * GET /cm/v1/logs */ export const getApiCmV1Logs = async (args: GetApiCmV1LogsArgs, options?: GetApiCmV1LogsOptions) => { const {baseUrl = "https://api.moloco.cloud", fetch: fetchFn = fetch, Bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.ad_account_id != null) query.append("ad_account_id", String(args.ad_account_id)) if (args['date_range.start'] != null) query.append("date_range.start", String(args['date_range.start'])) if (args['date_range.end'] != null) query.append("date_range.end", String(args['date_range.end'])) if (Bearer !== undefined) headers.set("Authorization", Bearer) const url = `${baseUrl.replace(/\/+$/, '')}/cm/v1/logs${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(messagesListLogsResponse, await res.json()) };