import {z} from 'zod' export type V3Signals = 'co2_moer' | 'health_damage'; export type V3HistoricalSignals = 'co2_aoer'; export type GetApiV3MapsArgs = {signal_type: V3Signals | V3HistoricalSignals | unknown}; export type GetApiV3MapsOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const properties = z.object({region: z.string(), region_full_name: z.string()}); export const geometry = z.object({type: z.literal("MultiPolygon"), coordinates: z.array(z.array(z.array(z.array(z.number()))))}); export const feature = z.object({type: z.literal("Feature"), properties: properties, geometry: geometry}); export const v3Signals = z.enum(["co2_moer", "health_damage"]); export const v3HistoricalSignals = z.literal("co2_aoer"); export const meta = z.object({last_updated: z.string(), signal_type: z.union([v3Signals, v3HistoricalSignals, z.unknown()])}); export const map = z.object({type: z.literal("FeatureCollection"), features: z.array(feature), meta: meta}); 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 }; /** * Grid Region Map Geometry * * GET /v3/maps */ export const getApiV3Maps = async (args: GetApiV3MapsArgs, options?: GetApiV3MapsOptions) => { const {baseUrl = "https://api.watttime.org", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.signal_type != null) query.append("signal_type", String(args.signal_type)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v3/maps${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(map, await res.json()) };