import {z} from 'zod' export type Polygon = {type: 'Polygon', coordinates: Array>>, bbox?: Array | undefined}; export type SearchResource = {location?: (Polygon | {ref: {uri: string}}) | undefined, start_date?: string | undefined, end_date?: string | undefined, resolution?: (Array<'low' | 'medium' | 'high' | 'very_high'> | 'low' | 'medium' | 'high' | 'very_high') | undefined, coverage?: number | undefined, interval_length?: number | undefined, order_by?: (Array<'resolution' | 'cost' | 'coverage' | 'date' | '-resolution' | '-cost' | '-coverage' | '-date'> | 'resolution' | 'cost' | 'coverage' | 'date' | '-resolution' | '-cost' | '-coverage' | '-date') | undefined, off_nadir_angle?: Array | undefined}; export type CreateApiDataSearchArgs = {body: SearchResource}; export type CreateApiDataSearchOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const supportedGeojsonGeometry = z.object({type: z.literal("Polygon"), coordinates: z.array(z.array(z.array(z.unknown()))), bbox: z.array(z.number().gte(-180).lte(180)).optional()}); export const searchResponse = z.object({data: z.array(z.object({id: z.string().optional(), location: supportedGeojsonGeometry.optional(), intersection: supportedGeojsonGeometry.optional(), start_time: z.string().optional(), end_time: z.string().optional(), preview_uri: z.string().optional(), thumbnail_uri: z.string().optional(), resolution: z.number().gte(0).optional(), source: z.string().optional(), product_name: z.string().optional(), location_coverage_percentage: z.number().gte(0).lte(100).optional(), area_sq_km: z.number().gte(0).optional(), minimum_area_sq_km: z.number().gte(0).optional(), price_per_sq_km: z.number().gte(0).optional(), cost: z.union([z.string(), z.number().gte(0)]).optional(), result_cloud_cover_percentage: z.number().gte(0).lte(100).optional(), off_nadir_angle: z.number().gte(-90).lte(90).optional()})), pagination: z.object({per_page: z.number().int(), cursor: z.object({next: z.number().int().optional(), self: z.number().int().gte(0).optional()}), total: z.number().int().gte(0), count: z.number().int().gte(0)}).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 }; /** * Search Archive * * POST /data/search */ export const createApiDataSearch = async (args: CreateApiDataSearchArgs, options?: CreateApiDataSearchOptions) => { const {baseUrl = "https://api.skywatch.co/earthcache", 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(/\/+$/, '')}/data/search${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(searchResponse, await res.json()) };