import {z} from 'zod' export type CreateApiLettersArgs = {'Idempotency-Key': string, body: BodyInit}; export type CreateApiLettersOptions = {baseUrl: string, ApiKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const letter = z.object({deliveredAt: z.string().nullable().optional(), dispatchedAt: z.string().nullable().optional(), documentType: z.string().min(1).max(100).optional(), environment: z.enum(["production", "staging"]).optional(), error: z.object({}).nullable().optional(), failedAt: z.string().nullable().optional(), id: z.string().optional(), invoiceId: z.string().nullable().optional(), invoiceSnapshot: z.object({}).optional(), invoiceStatus: z.string().nullable().optional(), recipientAddress: z.string().nullable().optional(), recipientCountry: z.string().nullable().optional(), requestedAt: z.string().nullable().optional(), status: z.enum(["sending", "processing", "dispatched", "delivered", "failed", "undeliverable", "needs_review"]).optional(), undeliverableAt: z.string().nullable().optional(), updatedAt: z.string().nullable().optional()}); export const createApiLettersResponse = z.object({data: letter.optional(), success: z.boolean().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 }; /** * Send any PDF by post * * POST /letters * * Also accepts auth: FirebaseIdToken */ export const createApiLetters = async (args: CreateApiLettersArgs, options: CreateApiLettersOptions) => { const {baseUrl, fetch: fetchFn = fetch, ApiKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (ApiKeyHeader !== undefined) headers.set("X-API-Key", ApiKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/letters${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: args.body}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApiLettersResponse, await res.json()) };