import {z} from 'zod' export type GetApiUnassignedStopsArgs = {pageToken?: string | undefined, maxPageSize?: number | undefined, filter?: ({externalId?: string | undefined}) | undefined}; export type GetApiUnassignedStopsOptions = {baseUrl?: string | undefined, BasicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const unassignedStopIdSchema = z.string(); export const timeOfDaySchema = z.object({hour: z.number().int().gte(0).lte(23), minute: z.number().int().gte(0).lte(59)}); export const unassignedStopSchema = z.object({id: unassignedStopIdSchema, depot: z.string(), address: 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())}), barcodes: z.array(z.string()), allowedDrivers: z.array(z.string()), notes: z.string().nullable(), packageCount: z.number().nullable(), weight: z.object({amount: z.number().gte(0), unit: z.enum(["kilogram", "pound", "metric-ton"])}).nullable(), orderInfo: z.object({products: z.array(z.string()), invoiceNumber: z.string().nullable(), sellerName: z.string().nullable(), sellerOrderId: z.string().nullable(), sellerWebsite: z.string().nullable()}), recipient: z.object({name: z.string().nullable(), email: z.string().nullable(), phone: z.string().nullable(), externalId: z.string().nullable()}), activity: z.enum(["delivery", "pickup"]).optional(), trackingLink: z.string().nullable(), timing: z.object({timeWindows: z.array(z.object({earliestAttemptTime: timeOfDaySchema.nullable(), latestAttemptTime: timeOfDaySchema.nullable()})), estimatedAttemptDuration: z.number().nullable(), earliestAttemptTime: timeOfDaySchema.nullable(), latestAttemptTime: timeOfDaySchema.nullable()}), optimizationOrder: z.enum(["first", "last", "default"]).optional(), paymentOnDelivery: z.object({amount: z.number().int().gte(0).lte(9007199254740991).nullable(), currency: z.string()}).nullable(), proofOfAttemptRequirements: z.object({enabled: z.boolean().nullable()}), customProperties: z.record(z.string(), z.string().nullable()).nullable(), clientId: z.string().nullable()}); export const getApiUnassignedStopsResponse = z.object({unassignedStops: z.array(unassignedStopSchema), nextPageToken: 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 }; /** * List unassigned stops * * GET /unassignedStops */ export const getApiUnassignedStops = async (args: GetApiUnassignedStopsArgs, options?: GetApiUnassignedStopsOptions) => { 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 (args.pageToken != null) query.append("pageToken", String(args.pageToken)) if (args.maxPageSize != null) query.append("maxPageSize", String(args.maxPageSize)) if (args.filter != null) query.append("filter", JSON.stringify(args.filter)) if (BasicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${BasicAuth.username}:${BasicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/unassignedStops${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(getApiUnassignedStopsResponse, await res.json()) };