import {z} from 'zod' export type GetApiOperationsOperationIdArgs = {operationId: string}; export type GetApiOperationsOperationIdOptions = {baseUrl?: string | undefined, BasicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const operationIdSchema = z.string(); export const planIdSchema = z.string(); export const stopIdSchema = z.string(); export const operationSchema = z.object({id: operationIdSchema, type: z.literal("plan_optimization"), done: z.boolean(), metadata: z.object({canceled: z.boolean(), startedAt: z.number(), finishedAt: z.number().nullable(), startedBy: z.union([z.literal("dispatcher"), z.literal("api"), z.string()]), targetPlanId: planIdSchema}), result: z.union([z.object({numOptimizedStops: z.number(), skippedStops: z.array(z.object({id: stopIdSchema, reason: z.union([z.literal("impossible_time_window"), z.literal("impossible_navigation"), z.literal("impossible_number_of_stops"), z.literal("impossible_order_of_stops"), z.string()])}))}), z.object({code: z.string(), message: z.string()})]).nullable()}); 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 an operation * * GET /operations/{operationId} */ export const getApiOperationsOperationId = async (args: GetApiOperationsOperationIdArgs, options?: GetApiOperationsOperationIdOptions) => { const {baseUrl = "https://api.spoke.com/public/v1", fetch: fetchFn = fetch, BasicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (BasicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${BasicAuth.username}:${BasicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/operations/${encodeURIComponent(String(args.operationId))}${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(operationSchema, await res.json()) };