import {z} from 'zod' export type CreateApiPlansArgs = {body: {title: string, starts: {day: number, month: number, year: number}, drivers?: Array | undefined, depot?: (string | null) | undefined, routeOverrides?: ({startAddress?: ({addressName?: (string | null) | undefined, addressLineOne?: (string | null) | undefined, addressLineTwo?: (string | null) | undefined, city?: (string | null) | undefined, state?: (string | null) | undefined, zip?: (string | null) | undefined, country?: (string | null) | undefined, latitude?: (number | null) | undefined, longitude?: (number | null) | undefined} | null) | undefined, endAddress?: ({addressName?: (string | null) | undefined, addressLineOne?: (string | null) | undefined, addressLineTwo?: (string | null) | undefined, city?: (string | null) | undefined, state?: (string | null) | undefined, zip?: (string | null) | undefined, country?: (string | null) | undefined, latitude?: (number | null) | undefined, longitude?: (number | null) | undefined} | null) | undefined, startTime?: ({hour: number, minute: number} | null) | undefined, endTime?: ({hour: number, minute: number} | null) | undefined, maxStops?: (number | null) | undefined, drivingSpeed?: ('slower' | 'average' | 'faster' | null) | undefined, deliverySpeed?: ('slower' | 'average' | 'faster' | null) | undefined, vehicleType?: ('bike' | 'scooter' | 'car' | 'small_truck' | 'truck' | 'electric_cargo_bike' | null) | undefined, optimizationSettings?: ({objective?: ('distribute_services' | null) | undefined, subObjective?: ('equalize_workload' | 'equalize_time' | 'maximize_efficiency' | null) | undefined} | null) | undefined} | null) | undefined}}; export type CreateApiPlansOptions = {baseUrl?: string | undefined, BasicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const planIdSchema = z.string(); export const dateSchema = z.object({day: z.number().int().gte(1).lte(31), month: z.number().int().gte(1).lte(12), year: z.number().int().gte(2000).lte(2100)}); export const depotIdSchema = z.string(); export const driverIdSchema = z.string(); export const routeIdSchema = z.string(); export const planSchema = z.object({id: planIdSchema, title: z.string(), starts: dateSchema, depot: depotIdSchema.nullable(), distributed: z.boolean(), writable: z.boolean(), optimization: z.enum(["creating", "editing", "preview", "optimized", "optimizing"]).nullable(), drivers: z.array(driverIdSchema), routes: z.array(routeIdSchema), routeOverrides: z.object({startTime: z.object({hour: z.number().int().gte(0).lte(23), minute: z.number().int().gte(0).lte(59)}).nullable(), endTime: z.object({hour: z.number().int().gte(0).lte(23), minute: z.number().int().gte(0).lte(59)}).nullable(), startAddress: z.object({address: z.string(), addressLineOne: z.string(), addressLineTwo: z.string(), latitude: z.number().gte(-90).lte(90).nullable(), longitude: z.number().gte(-180).lte(180).nullable(), placeId: z.string().nullable(), placeTypes: z.array(z.string())}).nullable(), endAddress: z.object({address: z.string(), addressLineOne: z.string(), addressLineTwo: z.string(), latitude: z.number().gte(-90).lte(90).nullable(), longitude: z.number().gte(-180).lte(180).nullable(), placeId: z.string().nullable(), placeTypes: z.array(z.string())}).nullable(), maxStops: z.number().int().gte(-9007199254740991).lte(9007199254740991).nullable(), drivingSpeed: z.enum(["slower", "average", "faster"]).nullable(), deliverySpeed: z.enum(["slower", "average", "faster"]).nullable(), vehicleType: z.enum(["bike", "scooter", "car", "small_truck", "truck", "electric_cargo_bike"]).nullable(), optimizationSettings: z.object({objective: z.enum(["minimize_drivers", "distribute_services"]), subObjective: z.enum(["equalize_workload", "equalize_time", "maximize_efficiency"]).nullable().optional()})}).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 }; /** * Create a new plan * * POST /plans */ export const createApiPlans = async (args: CreateApiPlansArgs, options?: CreateApiPlansOptions) => { const {baseUrl = "https://api.spoke.com/public/v1", fetch: fetchFn = fetch, BasicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (BasicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${BasicAuth.username}:${BasicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/plans${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(planSchema, await res.json()) };