import {z} from 'zod' export type Entity = {text?: string | undefined, type?: string | undefined, role?: (string | null) | undefined, value?: Record | undefined, display_text?: string | undefined, confidence?: number | undefined, is_system_entity?: boolean | undefined}; export type Params = {target_dialogue_state?: (string | null) | undefined, dynamic_resource?: (Record | null) | undefined, allowed_intents?: (Array | null) | undefined, time_zone?: (string | null) | undefined, language?: (string | null) | undefined, locale?: (string | null) | undefined, timestamp?: (number | null) | undefined}; export type Request = {text?: string | undefined, domain?: string | undefined, intent?: string | undefined, entities?: Array | undefined, context?: Record | undefined, params?: Params | undefined}; export type Directive = {name?: string | undefined, type?: ('view' | 'action') | undefined, payload?: Record | undefined}; export type Responder = {directives?: Array | undefined, frame?: Record | undefined, params?: Params | undefined, slots?: Record | undefined}; export type Data = {request?: Request | undefined, responder?: Responder | undefined, action?: string | undefined}; export type CreateApiActionArgs = {body: Data}; export type CreateApiActionOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const directive = z.object({name: z.string().optional(), type: z.enum(["view", "action"]).optional(), payload: z.object({}).optional()}); export const params = z.object({target_dialogue_state: z.string().nullable().optional(), dynamic_resource: z.object({}).nullable().optional(), allowed_intents: z.array(z.string()).nullable().optional(), time_zone: z.string().nullable().optional(), language: z.string().nullable().optional(), locale: z.string().nullable().optional(), timestamp: z.number().int().nullable().optional()}); export const responder = z.object({directives: z.array(directive).optional(), frame: z.object({}).optional(), params: params.optional(), slots: z.object({}).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 }; /** * Invoke an action * * POST /action */ export const createApiAction = async (args: CreateApiActionArgs, options: CreateApiActionOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/action${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(responder, await res.json()) };