import {z} from 'zod' export type V2SpendType = 'SPEND_TYPE_DAILY' | 'SPEND_TYPE_HOURLY' | 'SPEND_TYPE_TOTAL'; export type V2CampaignSpends = {id: string, spendType: V2SpendType}; export type V2CampaignSpendRequest = {campaignSpendRequest?: Array | undefined}; export type CreateApiV2SpendCampaignArgs = {body: V2CampaignSpendRequest}; export type CreateApiV2SpendCampaignOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const v2SpendType = z.enum(["SPEND_TYPE_DAILY", "SPEND_TYPE_HOURLY", "SPEND_TYPE_TOTAL"]); export const campaignSpendSuccess = z.object({amount: z.number().optional()}); export const campaignSpendFailure = z.object({message: z.string().optional()}); export const v2CampaignSpend = z.object({id: z.string().optional(), spendType: v2SpendType.optional(), success: campaignSpendSuccess.optional(), failure: campaignSpendFailure.optional()}); export const v2CampaignSpendResponse = z.object({campaignSpends: z.array(v2CampaignSpend).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 }; /** * Retrieve campaign spend details * * POST /v2/spend/campaign */ export const createApiV2SpendCampaign = async (args: CreateApiV2SpendCampaignArgs, options?: CreateApiV2SpendCampaignOptions) => { const {baseUrl = "https://auth..citrusad.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/v2/spend/campaign${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(v2CampaignSpendResponse, await res.json()) };