import {z} from 'zod' export type GetApiV2UpdatesArgs = {'X-Signature'?: string | undefined, 'X-Timestamp'?: number | undefined, offset?: string | undefined, limit?: number | undefined, timeout?: number | undefined}; export type GetApiV2UpdatesOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, hmacSignature?: string | undefined, fetch?: typeof fetch | undefined}; export const webhookTranscription = z.object({status: z.enum(["Pending", "Started", "Done", "Failed"]).optional(), text: z.string().optional()}); export const webhookAttachment = z.object({id: z.string().optional(), type: z.enum(["image", "file", "video", "audio"]).optional(), name: z.string().optional(), mimeType: z.string().optional(), searchQuery: z.string().max(100).optional(), url: z.string().optional(), transcription: webhookTranscription.optional()}); export const messageMention = z.object({id: z.string().optional(), name: z.string().optional()}); export const webhookLocation = z.object({latitude: z.string().optional(), longitude: z.string().optional(), name: z.string().optional(), address: z.string().optional()}); export const webhookTask = z.object({id: z.string().optional(), action: z.enum(["Added", "Updated", "Deleted", "MarkedAsDone", "MarkedAsOpened", "Replied"]).optional(), title: z.string().optional(), text: z.string().optional(), status: z.enum(["Open", "Done"]).optional(), assignee: z.string().optional(), dueDate: z.number().int().optional(), isDueDateTimeSelected: z.boolean().optional(), parentId: z.string().optional(), subItemsCount: z.number().int().optional()}); export const webhookContact = z.object({name: z.string().optional(), phoneNumbers: z.array(z.string()).optional(), emails: z.array(z.string()).optional(), role: z.string().optional(), location: z.string().optional(), linkedIn: z.string().optional(), profileId: z.string().optional()}); export const webhookPoll = z.object({id: z.string().optional(), title: z.string().optional(), subtitle: z.string().optional(), selectionType: z.enum(["single", "multiple"]).optional(), anonymous: z.boolean().optional(), status: z.enum(["active", "closed"]).optional(), expiresAt: z.number().int().optional(), options: z.array(z.object({id: z.string().optional(), text: z.string().optional()})).optional()}); export const webhookCall = z.object({id: z.string().optional(), initiatorId: z.string().optional(), callType: z.enum(["audio", "video"]).optional(), status: z.enum(["initiating", "calling", "active", "ended", "cancelled"]).optional(), startedAt: z.number().int().optional(), endedAt: z.number().int().optional(), endReason: z.enum(["caller_not_joined", "caller_cancelled", "no_one_answered", "finished", "max_duration", "last_participant"]).optional(), duration: z.number().int().optional(), participantCount: z.number().int().optional()}); export const webhookMessage = z.object({id: z.string(), topicId: z.string(), senderId: z.string(), senderName: z.string(), senderType: z.enum(["user", "bot", "system"]), type: z.enum(["text", "image", "file", "video", "audio", "location", "task", "contact", "poll", "call", "admin"]), text: z.string().optional(), previousText: z.string().optional(), createdAt: z.number().int(), updatedAt: z.number().int().optional(), parentId: z.string().optional(), mentionedProfiles: z.array(z.string()).optional(), attachments: z.array(webhookAttachment).optional(), mentions: z.array(messageMention).optional(), location: webhookLocation.optional(), task: webhookTask.optional(), contact: webhookContact.optional(), poll: webhookPoll.optional(), call: webhookCall.optional()}); export const webhookMessageCreatedData = z.object({message: webhookMessage, truncated: z.boolean().optional()}); export const webhookMessageUpdatedData = z.object({message: webhookMessage, updatedFields: z.array(z.string()).optional(), truncated: z.boolean().optional()}); export const webhookMessageDeletedData = z.object({messageId: z.string(), topicId: z.string(), deletedAt: z.number().int().optional(), deletedBy: z.string().optional(), message: z.object({id: z.string().optional(), topicId: z.string().optional(), senderId: z.string().optional()}).optional()}); export const webhookReactionObject = z.object({id: z.string().optional(), messageId: z.string().optional(), topicId: z.string().optional(), userId: z.string().optional(), emoji: z.string().optional()}); export const webhookReactionData = z.object({messageId: z.string(), topicId: z.string(), emoji: z.string(), userId: z.string(), reactionId: z.string().optional(), createdAt: z.number().int().optional(), reaction: webhookReactionObject.optional()}); export const webhookMemberData = z.object({topicId: z.string(), memberIds: z.array(z.string()), memberId: z.string().optional(), memberType: z.enum(["user", "bot"]).optional(), actorId: z.string().optional(), createdAt: z.number().int().optional()}); export const webhookTopicUpdatedData = z.object({topicId: z.string(), name: z.string().optional(), description: z.string().optional(), actorId: z.string().optional(), changes: z.record(z.string(), z.unknown()).optional()}); export const pollingUpdate = z.object({updateId: z.string(), eventType: z.enum(["message.created", "message.updated", "message.deleted", "reaction.added", "reaction.removed", "member.added", "member.removed", "topic.updated"]), createdAt: z.number().int(), data: z.union([webhookMessageCreatedData, webhookMessageUpdatedData, webhookMessageDeletedData, webhookReactionData, webhookMemberData, webhookTopicUpdatedData])}); export const updatesResponse = z.object({updates: z.array(pollingUpdate), nextOffset: z.string()}); 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 }; /** * Get updates (long polling) * * GET /v2/updates * * Also accepts auth: oauth2ClientCredentials */ export const getApiV2Updates = async (args: GetApiV2UpdatesArgs, options?: GetApiV2UpdatesOptions) => { const {baseUrl = "https://api.zenzap.co", fetch: fetchFn = fetch, bearerAuth, hmacSignature} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['X-Signature'] != null) headers.set("X-Signature", String(args['X-Signature'])) if (args['X-Timestamp'] != null) headers.set("X-Timestamp", String(args['X-Timestamp'])) if (args.offset != null) query.append("offset", String(args.offset)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.timeout != null) query.append("timeout", String(args.timeout)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) if (hmacSignature !== undefined) headers.set("X-Signature", hmacSignature) const url = `${baseUrl.replace(/\/+$/, '')}/v2/updates${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(updatesResponse, await res.json()) };