import { z } from "zod"; export const organizationSchema = z.string().uuid().toLowerCase(); const productSummarySchema = z.object({ id: z.string().uuid(), name: z.string(), slug: z.string(), }); export const productSchema = productSummarySchema.extend({ description: z.string(), variants: z.array( z.object({ id: z.string().uuid(), sku: z.string(), name: z.string(), price: z.string().regex(/^\d+(?:\.\d{1,2})?$/), currency: z.string(), attributes: z.record(z.string(), z.string()), }), ), groups: z.array( z.object({ group: z.object({ id: z.string().uuid(), name: z.string(), slug: z.string(), kind: z.enum(["CATEGORY", "COLLECTION"]), }), }), ), }); export type ProductSummary = z.infer; export type Product = z.infer; const sessionSchema = z.object({ accessToken: z.string().min(1), tokenType: z.literal("Bearer"), expiresAt: z.string().datetime(), }); export type Session = z.infer; const principalSchema = z.object({ userId: z.string().uuid(), organizationId: z.string().uuid(), sessionId: z.string().uuid(), permissions: z.array(z.string()), }); export type Principal = z.infer; export class ApiError extends Error { status: number; code?: string; requestId?: string; constructor( message: string, status: number, code?: string, requestId?: string, ) { super(message); this.name = "ApiError"; this.status = status; this.code = code; this.requestId = requestId; } } export function isUnknownOutcome(error: unknown) { return ( (error instanceof Error && error.name === "AbortError") || (error instanceof ApiError && (error.status === 0 || error.status >= 500 || error.code === "INVALID_RESPONSE" || error.code === "SESSION_CHANGED")) ); } type ApiOptions = { token?: string; body?: unknown; method?: string; signal?: AbortSignal; }; async function fetchApiResponse( path: string, { token, body, method = "GET", signal, attachmentMime, }: ApiOptions & { attachmentMime?: string }, ) { let response: Response; const multipart = body instanceof FormData; try { const timeout = AbortSignal.timeout(15000); response = await fetch(`/api/v1${path}`, { method, signal: signal ? AbortSignal.any([signal, timeout]) : timeout, ...(attachmentMime || multipart ? { cache: "no-store", redirect: "error" } : {}), headers: { ...(body === undefined || multipart ? {} : { "Content-Type": "application/json" }), ...(attachmentMime ? { Accept: attachmentMime } : {}), ...(token ? { Authorization: `Bearer ${token}` } : {}), }, ...(body === undefined ? {} : { body: multipart ? body : JSON.stringify(body) }), }); } catch (error) { if (error instanceof Error && error.name === "AbortError") throw error; throw new ApiError( "The service could not be reached. Check your connection and try again.", 0, "NETWORK_ERROR", ); } if (!response.ok) { const data = await response.json().catch(() => null); throw new ApiError( typeof data?.message === "string" ? data.message : "The service could not complete this request.", response.status, typeof data?.code === "string" ? data.code : undefined, typeof data?.requestId === "string" ? data.requestId : (response.headers.get("x-request-id") ?? undefined), ); } return response; } export async function apiRequest(path: string, options: ApiOptions = {}): Promise { const response = await fetchApiResponse(path, options); if (response.status === 204) return null; const data = await response.json().catch(() => null); if (data === null) throw new ApiError( "The service returned an unexpected response.", response.status, "INVALID_RESPONSE", ); return data; } async function apiAttachment( path: string, size: number, attachmentMime: string, token: string, signal: AbortSignal, errorMessage: string, ) { const response = await fetchApiResponse(path, { token, signal, attachmentMime }); const invalidAttachment = () => new ApiError(errorMessage, response.status, "INVALID_RESPONSE"); if (response.headers.get("content-type")?.split(";")[0].trim().toLowerCase() !== attachmentMime) throw invalidAttachment(); const file = await response.blob(); if (file.size !== size) throw invalidAttachment(); return file; } export function apiPdf(path: string, size: number, token: string, signal: AbortSignal) { return apiAttachment(path, size, "application/pdf", token, signal, "The service returned an unexpected PDF."); } const artworkAttachment = z.object({ versionId: z.string().uuid(), size: z.number().int().min(1).max(2 * 1024 * 1024), mimeType: z.enum(["application/pdf", "image/png", "image/jpeg"]), }); export async function apiArtwork(versionId: string, size: number, mimeType: string, token: string, signal: AbortSignal) { const file = artworkAttachment.parse({ versionId, size, mimeType }); return apiAttachment( `/b2b/artwork-versions/${file.versionId}/download`, file.size, file.mimeType, token, signal, "The service returned an unexpected artwork attachment.", ); } export function parse(schema: z.ZodType, data: unknown): T { const result = schema.safeParse(data); if (!result.success) throw new ApiError( "The service returned an unexpected response.", 200, "INVALID_RESPONSE", ); return result.data; } export async function listProducts( organization: string, search = "", offset = 0, limit = 12, signal?: AbortSignal, ) { organizationSchema.parse(organization); const params = new URLSearchParams({ limit: String(limit), offset: String(offset), ...(search ? { search } : {}), }); return parse( z.array(productSummarySchema), await apiRequest(`/storefront/${organization}/products?${params}`, { signal, }), ); } export async function getProduct( organization: string, id: string, signal?: AbortSignal, ) { organizationSchema.parse(organization); z.string().uuid().parse(id); return parse( productSchema, await apiRequest(`/storefront/${organization}/products/${id}`, { signal }), ); } export async function login( organizationId: string, email: string, password: string, ) { const organization = organizationSchema.parse(organizationId); return parse( sessionSchema, await apiRequest("/auth/login", { method: "POST", body: { organizationId: organization, email, password }, }), ); } export async function getPrincipal(token: string) { return parse(principalSchema, await apiRequest("/auth/me", { token })); } export async function healthCheck(kind: "live" | "ready") { return parse( z.object({ status: z.literal("ok") }), await apiRequest(`/health/${kind}`), ); }