import {z} from 'zod' export type NoisePort = {portCode: string}; export type NoiseVessel = {imo?: number | undefined, mmsi?: number | undefined}; export type ComputeNoiseRequest = {departure: NoisePort, vessel: NoiseVessel, arrival: NoisePort}; export type CreateApiComputeNoiseArgs = {body: ComputeNoiseRequest}; export type CreateApiComputeNoiseOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const noisePort = z.object({portCode: z.string()}); export const noiseVessel = z.object({imo: z.number().int().optional(), mmsi: z.number().int().optional()}); export const computeNoiseRequest = z.object({departure: noisePort, vessel: noiseVessel, arrival: noisePort}); export const computeNoiseResponse = z.object({input: computeNoiseRequest.optional(), sel: z.number().optional(), duration: z.number().int().optional(), isAboveRecommendedThresholds: z.object({LloydsTransit: z.boolean().optional(), BureauVeritasStandard: z.boolean().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 }; /** * Retrieve Noise emitted for a trip from one port to another. * * POST /compute-noise */ export const createApiComputeNoise = async (args: CreateApiComputeNoiseArgs, options?: CreateApiComputeNoiseOptions) => { const {baseUrl = "https://api.sinay.ai/noise/api/v1", 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) headers.set("API_KEY", ApiKey) const url = `${baseUrl.replace(/\/+$/, '')}/compute-noise${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(computeNoiseResponse, await res.json()) };