import {z} from 'zod' export type PutWorkflowGraphInput = {nodes: Array<{public_id: string, type: 'trigger' | 'send_email' | 'wait' | 'condition' | 'webhook', config: {[key: string]: unknown}, canvas_x: number, canvas_y: number}>, edges: Array<{from_public_id: string, to_public_id: string, branch?: ('match' | 'no_match' | null) | undefined}>}; export type UpdateApiWorkflowsIdGraphArgs = {id: string, body: PutWorkflowGraphInput}; export type UpdateApiWorkflowsIdGraphOptions = {baseUrl?: string | undefined, bearerApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const workflowGraph = z.object({nodes: z.array(z.object({public_id: z.string(), type: z.enum(["trigger", "send_email", "wait", "condition", "webhook"]), config: z.object({}), canvas_x: z.number().optional(), canvas_y: z.number().optional()})), edges: z.array(z.object({from_public_id: z.string(), to_public_id: z.string(), branch: z.enum(["match", "no_match"]).nullable().optional()}))}); export const updateApiWorkflowsIdGraphResponse = z.object({graph: workflowGraph}); 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 }; /** * Replace the graph * * PUT /workflows/{id}/graph * * Also accepts auth: bearerOAuth */ export const updateApiWorkflowsIdGraph = async (args: UpdateApiWorkflowsIdGraphArgs, options?: UpdateApiWorkflowsIdGraphOptions) => { const {baseUrl = "https://api.poststack.dev", fetch: fetchFn = fetch, bearerApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerApiKey !== undefined) headers.set('authorization', `Bearer ${bearerApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/workflows/${encodeURIComponent(String(args.id))}/graph${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "PUT", 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(updateApiWorkflowsIdGraphResponse, await res.json()) };