import {z} from 'zod' export type TriggerServiceCreateTriggerSubscriptionBody = {config?: {[key: string]: string} | undefined, connected_account_id?: string | undefined, interval_seconds?: number | undefined, trigger_name: string}; export type CreateApiApiV1ConnectionsConnectionIdTriggerSubscriptionsArgs = {connection_id: string, body: TriggerServiceCreateTriggerSubscriptionBody}; export type CreateApiApiV1ConnectionsConnectionIdTriggerSubscriptionsOptions = {baseUrl?: string | undefined, oauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const triggersAccountHealthState = z.enum(["READY", "AWAITING_CONFIRMATION", "WRONG_APP", "DISCONNECTED", "NEEDS_REAUTHENTICATION"]); export const triggersTriggerDeliveryScope = z.enum(["ACCOUNT", "CONNECTION"]); export const triggersTriggerPollErrorCode = z.enum(["RATE_LIMITED", "CREDENTIAL_REVOKED", "INVALID_CONFIGURATION", "PROVIDER_ERROR", "DELIVERY_FAILED", "TIMED_OUT", "POLL_FAILED"]); export const triggersTriggerPollState = z.object({backoff_until: z.string().optional(), consecutive_failures: z.number().int().optional(), last_error: z.string().optional(), last_error_code: triggersTriggerPollErrorCode.optional(), last_run_at: z.string().optional(), watermark_updated_at: z.string().optional()}); export const triggersTriggerSubscriptionStatus = z.enum(["ACTIVE", "THROTTLED", "PAUSED", "PAUSED_CREDENTIAL"]); export const triggersTriggerSubscription = z.object({account_health: triggersAccountHealthState.optional(), config: z.record(z.string(), z.string()).optional(), connected_account_id: z.string().optional(), connected_account_identifier: z.string().optional(), connection_id: z.string().optional(), created_at: z.string().optional(), delivery_scope: triggersTriggerDeliveryScope.optional(), effective_interval_seconds: z.number().int().optional(), id: z.string().optional(), poll_state: triggersTriggerPollState.optional(), provider: z.string().optional(), requested_interval_seconds: z.number().int().optional(), status: triggersTriggerSubscriptionStatus.optional(), trigger_name: z.string().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 }; /** * Subscribe to a trigger * * POST /api/v1/connections/{connection_id}/trigger-subscriptions */ export const createApiApiV1ConnectionsConnectionIdTriggerSubscriptions = async (args: CreateApiApiV1ConnectionsConnectionIdTriggerSubscriptionsArgs, options?: CreateApiApiV1ConnectionsConnectionIdTriggerSubscriptionsOptions) => { const {baseUrl = "https://$SCALEKIT_ENVIRONMENT_URL", fetch: fetchFn = fetch, oauth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (oauth2 !== undefined) headers.set('authorization', `Bearer ${oauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/connections/${encodeURIComponent(String(args.connection_id))}/trigger-subscriptions${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(triggersTriggerSubscription, await res.json()) };