import {z} from 'zod' export type BoundariesQuery = {ids: Array}; export type CreateApiV4BoundariesQueryArgs = {body: BoundariesQuery}; export type CreateApiV4BoundariesQueryOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const geometry = z.object({type: z.enum(["Point", "Polygon", "MultiPolygon"]), coordinates: z.array(z.string())}); export const area = z.object({q: z.number(), u: z.string()}); export const point = z.object({coordinates: z.array(z.number()), type: z.string()}); export const boundaryProperties = z.object({area: area, centroid: point}); export const boundary = z.object({id: z.string(), type: z.literal("Feature"), geometry: geometry, properties: boundaryProperties}); export const boundaries = z.object({type: z.literal("FeatureCollection"), features: z.array(boundary)}); 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 Boundaries in batch * * POST /v4/boundaries/query * * Also accepts auth: oauth2_authorization_code */ export const createApiV4BoundariesQuery = async (args: CreateApiV4BoundariesQueryArgs, options?: CreateApiV4BoundariesQueryOptions) => { const {baseUrl = "https://platform.climate.com", 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("X-Api-Key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v4/boundaries/query${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(boundaries, await res.json()) };