import {z} from 'zod' export type ExecutionPolicy = 'local_only' | 'prefer_local' | 'cloud_allowed' | 'cloud_required'; export type CreateUploadRequest = {filename: string, media_type: string, byte_size: number, execution_policy: ExecutionPolicy}; export type CreateApiV1UploadsArgs = {'Idempotency-Key': string, body: CreateUploadRequest}; export type CreateApiV1UploadsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const requestId = z.string(); export const runtimeLocation = z.enum(["local", "cloud"]); export const execution = z.object({location: runtimeLocation, capability_id: z.string().nullable().optional(), capability_version: z.string().nullable().optional()}); export const usage = z.object({billable: z.boolean(), quantity: z.number().gte(0), unit: z.string(), credits: z.number().gte(0).optional()}); export const assetId = z.string(); export const uploadSession = z.object({id: z.string(), asset_id: assetId, method: z.enum(["PUT", "POST"]), upload_url: z.string(), expires_at: z.string()}); export const uploadResponse = z.object({request_id: requestId, execution: execution, usage: usage, warnings: z.array(z.string()), data: uploadSession}); 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 an isomorphic local or cloud upload session * * POST /v1/uploads * * Also accepts auth: apiKeyAuth */ export const createApiV1Uploads = async (args: CreateApiV1UploadsArgs, options?: CreateApiV1UploadsOptions) => { const {baseUrl = "https://api.cerul.ai", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/uploads${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(uploadResponse, await res.json()) };