import {z} from 'zod' export type Latlng = string; export type PipedCoordinates = string; export type RequestDirections = {origin: Latlng, destination: Latlng, option?: ('fast' | 'flexible') | undefined, waypoints?: PipedCoordinates | undefined, mode?: ('car' | 'truck') | undefined, steps?: boolean | undefined, alternatives?: boolean | undefined, altcount?: number | undefined, avoid?: ('toll' | 'ferry' | 'highway' | 'none' | 'sharp_turn' | 'uturn' | 'service_road' | 'left_turn' | 'right_turn' | 'bbox' | 'geofence_id' | 'tunnel') | undefined, overview?: ('full' | 'simplified' | 'false') | undefined, approaches?: string | undefined, bearings?: string | undefined, geometry?: ('polyline' | 'polyline6' | 'geojson') | undefined, exclude?: ('toll' | 'ferry' | 'highway' | 'service_road' | 'uturn' | 'sharp_turn' | 'left_turn' | 'right_turn' | 'none') | undefined, departure_time?: number | undefined, truck_size?: unknown | undefined, truck_weight?: number | undefined, route_type?: ('fastest' | 'shortest') | undefined, road_info?: ('max_speed' | 'toll_distance' | 'toll_cost') | undefined, cross_border?: boolean | undefined, truck_axle_load?: number | undefined, hazmat_type?: ('general' | 'circumstantial' | 'explosive' | 'harmful_to_water') | undefined, turn_angle_range?: number | undefined, drive_time_limits?: string | undefined, rest_times?: string | undefined, emission_class?: ('euro0' | 'euro1' | 'euro2' | 'euro3' | 'euro4' | 'euro5' | 'euro6' | 'euro7' | 'euro8' | 'euro9') | undefined}; export type CreateApiDirectionsJsonArgs = {body: RequestDirections}; export type CreateApiDirectionsJsonOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiDirectionsJsonResponse = z.object({status: z.string().optional(), msg: z.string().optional(), route: z.object({geometry: z.string().optional(), distance: z.number().optional(), duration: z.number().optional(), start_location: z.object({latitude: z.number().optional(), longitude: z.number().optional()}).optional(), end_location: z.object({latitude: z.number().optional(), longitude: z.number().optional()}).optional(), geojson: z.object({type: z.string().optional(), geometry: z.object({type: z.string().optional(), coordinates: z.array(z.number()).optional()}).optional(), properties: z.string().optional()}).optional(), legs: z.array(z.object({distance: z.object({value: z.number().optional()}).optional(), duration: z.object({value: z.number().optional()}).optional(), start_location: z.object({latitude: z.number().optional(), longitude: z.number().optional()}).optional(), end_location: z.object({latitude: z.number().optional(), longitude: z.number().optional()}).optional(), steps: z.array(z.object({geometry: z.string().optional(), start_location: z.object({latitude: z.number().optional(), longitude: z.number().optional()}).optional(), end_location: z.object({latitude: z.number().optional(), longitude: z.number().optional()}).optional(), distance: z.object({value: z.number().optional()}).optional(), duration: z.object({value: z.number().optional()}).optional(), maneuver: z.object({bearing_before: z.number().int().optional(), bearing_after: z.number().int().optional(), coordinate: z.object({latitude: z.number().optional(), longitude: z.number().optional()}).optional(), maneuver_type: z.string().optional(), modifier: z.string().optional()}).optional(), geojson: z.object({type: z.string().optional(), geometry: z.object({type: z.string().optional(), coordinates: z.array(z.number()).optional()}).optional(), properties: z.string().optional()}).optional()})).optional()})).optional()}).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 }; /** * Directions API * * POST /directions/json */ export const createApiDirectionsJson = async (args: CreateApiDirectionsJsonArgs, options?: CreateApiDirectionsJsonOptions) => { const {baseUrl = "https://api.nextbillion.io", 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) query.set("key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/directions/json${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(createApiDirectionsJsonResponse, await res.json()) };