import {z} from 'zod' export type PluginCallRequest = {params: unknown}; export type CreateApiApiV1PluginsPluginIdCallArgs = {plugin_id: string, route?: string | undefined, body: PluginCallRequest}; export type CreateApiApiV1PluginsPluginIdCallOptions = {baseUrl: string, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const logLevel = z.enum(["log", "info", "error", "warn", "debug", "result"]); export const logEntry = z.object({level: logLevel, message: z.string()}); export const pluginMetadata = z.object({logs: z.array(logEntry).nullable().optional(), traces: z.array(z.unknown()).nullable().optional()}); export const paginationMeta = z.object({current_page: z.number().int().gte(0), per_page: z.number().int().gte(0), total_items: z.number().int().gte(0)}); export const apiResponseValue = z.object({data: z.unknown(), error: z.string().optional(), metadata: pluginMetadata.optional(), pagination: paginationMeta.optional(), success: z.boolean()}); 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 }; /** * Execute a plugin with optional wildcard route routing * * POST /api/v1/plugins/{plugin_id}/call */ export const createApiApiV1PluginsPluginIdCall = async (args: CreateApiApiV1PluginsPluginIdCallArgs, options: CreateApiApiV1PluginsPluginIdCallOptions) => { const {baseUrl, fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.route != null) query.append("route", String(args.route)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/plugins/${encodeURIComponent(String(args.plugin_id))}/call${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(apiResponseValue, await res.json()) };