import {z} from 'zod' export type ReferenceGeneration = {generation_request_id?: (string | null) | undefined, index?: number | undefined}; export type MediaType = 'photography' | 'illustration'; export type ReplaceBackgroundRequest = {prompt?: (string | null) | undefined, reference_asset_id?: (string | null) | undefined, reference_generation?: ReferenceGeneration | undefined, product_id?: (number | null) | undefined, media_type?: MediaType | undefined, negative_prompt?: (string | null) | undefined, background_color?: (string | null) | undefined, project_code?: (string | null) | undefined, notes?: (string | null) | undefined}; export type CreateApiV3AiImageGenerationsBackgroundReplacementArgs = {body: ReplaceBackgroundRequest}; export type CreateApiV3AiImageGenerationsBackgroundReplacementOptions = {baseUrl: string, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const pendingImageGenerationResponse = z.object({generation_request_id: z.string().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 }; /** * Replace the background of an existing image * * POST /v3/ai/image-generations/background-replacement * * Also accepts auth: OAuth2 */ export const createApiV3AiImageGenerationsBackgroundReplacement = async (args: CreateApiV3AiImageGenerationsBackgroundReplacementArgs, options: CreateApiV3AiImageGenerationsBackgroundReplacementOptions) => { const {baseUrl, fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKey !== undefined) headers.set("Api-Key", ApiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v3/ai/image-generations/background-replacement${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(pendingImageGenerationResponse, await res.json()) };