import {z} from 'zod' export type QueryProp = unknown | {contains?: string | undefined, endsWith?: string | undefined, eq?: (string | number | boolean | null) | undefined, gt?: (string | number) | undefined, gte?: (string | number) | undefined, in?: (Array) | undefined, lt?: (string | number) | undefined, lte?: (string | number) | undefined, neq?: (string | number | boolean | null) | undefined, startsWith?: string | undefined}; export type Query = {[key: string]: QueryProp}; export type Bboxfilter = Array; export type DatetimeQuery = string; export type GeoJsonPoint = {type: 'Point', coordinates: Array}; export type GeoJsonLineString = {type: 'LineString', coordinates: Array>}; export type GeoJsonPolygon = {type: 'Polygon', coordinates: Array>>}; export type GeoJsonMultiPoint = {type: 'MultiPoint', coordinates: Array>}; export type GeoJsonMultiLineString = {type: 'MultiLineString', coordinates: Array>>}; export type GeoJsonMultiPolygon = {type: 'MultiPolygon', coordinates: Array>>>}; export type CollectionsArray = Array; export type Ids = Array; export type Limit = number; export type SearchBody = {query?: Query | undefined, bbox?: Bboxfilter | undefined, datetime?: DatetimeQuery | undefined, intersects?: (GeoJsonPoint | GeoJsonLineString | GeoJsonPolygon | GeoJsonMultiPoint | GeoJsonMultiLineString | GeoJsonMultiPolygon) | undefined, collections?: CollectionsArray | undefined, ids?: Ids | undefined, limit?: Limit | undefined}; export type CreateApiSearchArgs = {body: SearchBody}; export type CreateApiSearchOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const itemId = z.string(); export const link = z.object({href: z.string(), rel: z.string(), title: z.string().optional(), type: z.string().optional(), method: z.enum(["GET", "POST"]).optional()}); export const assetType = z.string(); export const title = z.string().min(1).max(255).nullable(); export const description = z.string(); export const href = z.string(); export const checksumMultihashReadOnly = z.string(); export const geoadminVariant = z.string(); export const geoadminLang = z.enum(["de", "it", "fr", "rm", "en"]); export const projEpsg = z.number().int(); export const eoGsd = z.number(); export const created = z.string(); export const updated = z.string(); export const itemAssets = z.record(z.string(), z.object({type: assetType, title: title.optional(), description: description.optional(), href: href.optional(), "checksum:multihash": checksumMultihashReadOnly.optional(), "geoadmin:variant": geoadminVariant.optional(), "geoadmin:lang": geoadminLang.optional(), "proj:epsg": projEpsg.optional(), "eo:gsd": eoGsd.optional(), created: created, updated: updated})); export const bbox = z.array(z.number()); export const itemGeometry = z.object({type: z.literal("Polygon"), coordinates: z.array(z.array(z.array(z.number())))}); export const datetime = z.string(); export const itemProperties = z.object({created: created, datetime: datetime.optional(), start_datetime: datetime.optional(), end_datetime: datetime.optional(), updated: updated, title: z.string().min(1).max(255).nullable().optional()}); export const stacVersion = z.string(); export const itemType = z.literal("Feature"); export const item = z.object({id: itemId, links: z.array(link), assets: itemAssets, bbox: bbox, geometry: itemGeometry, properties: itemProperties, stac_version: stacVersion, type: itemType}); export const linkPostSearch = z.object({href: z.string(), rel: z.string(), title: z.string().optional(), type: z.string().optional(), method: z.enum(["GET", "POST"]).optional(), body: z.object({}).optional(), merge: z.boolean().optional()}); export const itemsSearchPostLinks = z.array(linkPostSearch); export const itemsSearchPost = z.object({features: z.array(item), type: z.literal("FeatureCollection"), links: itemsSearchPostLinks.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 STAC items with full-featured filtering. * * POST /search */ export const createApiSearch = async (args: CreateApiSearchArgs, options?: CreateApiSearchOptions) => { const {baseUrl = "http://data.geo.admin.ch/api/stac/v0.9", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/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(itemsSearchPost, await res.json()) };