From 8c2b8f157e86dfc9b72cb10de9485decd83f4744 Mon Sep 17 00:00:00 2001 From: renyuanz Date: Sat, 7 Nov 2026 02:42:05 +0800 Subject: [PATCH 1/2] SDK 0.6.0: receive email, attachments, thread headers - emails.send / sendBatch take `headers` and `attachments` (bytes or base64; the SDK base64-encodes Buffers and Uint8Arrays). - threadHeaders() builds In-Reply-To / References from a received email or an email.sent event's message_id. - emails.inbound.list / get / getAttachment read mail received at the workspace's mailboxes. - Webhook types: email.failed, email.received, and message_id on email.sent. Needs app.zalify.com#2617 (the endpoints) and reach#326 (message_id). Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 52 +++++++++++- package.json | 2 +- src/client.ts | 2 +- src/emails.ts | 185 ++++++++++++++++++++++++++++++++++++++++++- src/http.ts | 14 ++++ src/index.ts | 11 +++ src/webhooks.ts | 37 ++++++++- test/inbound.test.ts | 102 ++++++++++++++++++++++++ 8 files changed, 394 insertions(+), 11 deletions(-) create mode 100644 test/inbound.test.ts diff --git a/README.md b/README.md index 60b6013..dda562c 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,52 @@ for (const [i, result] of data.entries()) { } ``` +## Attachments and threads + +Attach up to 10 files (10 MB together) as bytes or base64. `threadHeaders()` keeps a follow-up in the same thread as an earlier email: + +```ts +import { readFile } from "node:fs/promises"; +import { threadHeaders } from "@zalify/sdk"; + +await zalify.emails.send({ + from: "Emma ", + to: "creator@example.com", + subject: "Re: Spring collab", + html: "

Following up with the brief.

", + // message_id from your first email's email.sent webhook event + headers: threadHeaders({ messageId: sentMessageId }), + attachments: [{ filename: "brief.pdf", content: await readFile("brief.pdf") }], +}); +``` + +`headers` takes up to 10 other headers too. Ones Zalify or the mail provider set (From, To, Cc, Subject, Reply-To, Message-ID, Date, Content-Type, List-Unsubscribe…) are refused. + +## Receive email + +Mail that arrives at your mailboxes (senders forwarded to Zalify, or a reply domain, in **Settings → Email → Receiving**) can be read with the same key. Each new email is also an `email.received` webhook event. + +```ts +const { data, nextCursor } = await zalify.emails.inbound.list({ mailbox: "emma@acme.com" }); + +const email = await zalify.emails.inbound.get(data[0].id); +// { from, subject, text, html, messageId, references, inReplyToEmailId, attachments, … } +// inReplyToEmailId: the id of your email it answers, when it answers one + +for (const file of email.attachments) { + const { content, contentType } = await zalify.emails.inbound.getAttachment(email.id, file.id); +} + +// Reply in its thread +await zalify.emails.send({ + from: "Emma ", + to: email.replyTo ?? email.from, + subject: `Re: ${email.subject}`, + html: "

Sounds good!

", + headers: threadHeaders(email), +}); +``` + ## Contacts Create or update a contact by email, e.g. when someone signs up. The key needs the **Manage contacts** permission. @@ -188,15 +234,17 @@ new Zalify({ ## Webhooks -Add an endpoint in **Settings → Developer → Webhooks** to get events for email sent through the API: +Add an endpoint in **Settings → Developer → Webhooks** to get events for email sent through the API, and for email you receive: -- `email.sent` +- `email.sent`, with `message_id`: the Message-ID the recipient sees, for `threadHeaders()` +- `email.failed`, with `reason` - `email.delivered` - `email.bounced`, with `bounce_type` `hard` or `soft` - `email.complained` - `email.opened` - `email.clicked`, with `url` - `contact.unsubscribed` +- `email.received`: `{ inbound_id, in_reply_to_email_id, mailbox, from, subject, preview }`; fetch the whole email with `emails.inbound.get(inbound_id)` The signing secret (`whsec_…`) is shown once, when you create the endpoint. diff --git a/package.json b/package.json index 62fe6c2..171d108 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@zalify/sdk", - "version": "0.5.0", + "version": "0.6.0", "description": "Official Node.js / TypeScript SDK for the Zalify API", "keywords": ["zalify", "email", "transactional email", "contacts", "events", "sdk"], "homepage": "https://github.com/zalify/zalify-node#readme", diff --git a/src/client.ts b/src/client.ts index 2520c6e..2ce4691 100644 --- a/src/client.ts +++ b/src/client.ts @@ -4,7 +4,7 @@ import { Events } from "./events"; import { Webhooks } from "./webhooks"; import type { HttpConfig } from "./http"; -export const VERSION = "0.5.0"; +export const VERSION = "0.6.0"; export type ZalifyOptions = { /** A Zalify Public API key (`zalify_api_…`). Defaults to `ZALIFY_API_KEY`. */ diff --git a/src/emails.ts b/src/emails.ts index 17abe5c..a9dbbe9 100644 --- a/src/emails.ts +++ b/src/emails.ts @@ -1,6 +1,6 @@ import { randomUUID } from "node:crypto"; import { ZalifyError } from "./errors"; -import { type HttpConfig, request } from "./http"; +import { type HttpConfig, type RawBody, request } from "./http"; /** * `transactional` (sign-in, password reset, receipts, notifications) goes out @@ -42,6 +42,24 @@ export type EmailMessage = EmailSender & { * `automation_`, `broadcast_` or `message_`. */ tags?: Record; + /** + * Up to 10 extra headers, e.g. from `threadHeaders()` to keep a follow-up + * or a reply in the same thread. From, To, Cc, Subject, Reply-To, + * Message-ID, Date, Content-Type, List-Unsubscribe and the like are set by + * Zalify and refused. + */ + headers?: Record; + /** Up to 10 files, 10 MB together. */ + attachments?: EmailAttachment[]; +}; + +export type EmailAttachment = { + filename: string; + /** The file: bytes (Buffer, Uint8Array) or a base64 string. */ + content: Uint8Array | string; + contentType?: string; + /** Shows the file inline, referenced from the HTML as `cid:`. */ + contentId?: string; }; export type SendEmailParams = EmailMessage & { type?: EmailType }; @@ -98,9 +116,167 @@ export type RequestOptions = { const MAX_BATCH = 100; -export class Emails { +const toBase64 = (content: Uint8Array | string) => + typeof content === "string" + ? content + : Buffer.from(content.buffer, content.byteOffset, content.byteLength).toString( + "base64" + ); + +/** The message as the API takes it: attachments base64-encoded. */ +const toWire = (message: T): T => + message.attachments + ? { + ...message, + attachments: message.attachments.map((file) => ({ + ...file, + content: toBase64(file.content), + })), + } + : message; + +const MESSAGE_ID = /<[^<>\s]+>/g; +/** References only needs the thread's root and its latest ids. */ +const MAX_REFERENCES = 10; + +/** + * Headers that put an email in the same thread as an earlier one: + * `In-Reply-To` is the earlier email's Message-ID, `References` its + * References plus that id (RFC 5322). Pass the `messageId` and `references` + * of a received email (`emails.inbound.get`), or the `message_id` of your own + * email's `email.sent` webhook event to follow up before they reply. + */ +export function threadHeaders(earlier: { + /** Null for a received email that had none: it can't be threaded. */ + messageId: string | null; + references?: string | null; +}): { "In-Reply-To": string; References: string } { + const [messageId] = earlier.messageId?.match(MESSAGE_ID) ?? []; + if (!messageId) { + throw new ZalifyError({ + message: `Not a Message-ID: ${earlier.messageId ?? "none"}`, + code: "invalid_request", + status: 0, + }); + } + const references = (earlier.references?.match(MESSAGE_ID) ?? []).filter( + (id) => id !== messageId + ); + const kept = + references.length < MAX_REFERENCES + ? references + : [references[0] as string, ...references.slice(-(MAX_REFERENCES - 2))]; + return { + "In-Reply-To": messageId, + References: [...kept, messageId].join(" "), + }; +} + +/** A received email in a list. */ +export type InboundEmailSummary = { + id: string; + /** The mailbox it came in on, e.g. support@brand.com. */ + mailbox: string; + from: string; + subject: string; + /** The start of the text body. */ + preview: string; + /** The `id` of your email it replies to, when it answers one you sent. */ + inReplyToEmailId: string | null; + receivedAt: string; +}; + +export type InboundEmailAttachment = { + id: string; + filename: string; + contentType: string; + /** Bytes. */ + size: number; + contentId: string | null; + /** Shown in the HTML (`cid:`) rather than attached. */ + inline: boolean; +}; + +/** A received email, whole. */ +export type InboundEmail = InboundEmailSummary & { + /** The address it was delivered to (the forwarding address for forwarded mail). */ + to: string; + cc: string[]; + replyTo: string | null; + /** Its Message-ID; pass the email to `threadHeaders()` to reply in its thread. */ + messageId: string | null; + references: string | null; + text: string | null; + html: string | null; + /** Every header, names lowercased; a repeated header is an array. */ + headers: Record; + attachments: InboundEmailAttachment[]; +}; + +export type ListInboundParams = { + /** 1–100, default 25. */ + limit?: number; + /** `nextCursor` from the previous page. */ + cursor?: string; + /** Only email that came in on this mailbox (a sender address). */ + mailbox?: string; + /** Only email from this address. */ + from?: string; +}; + +export type ListInboundResult = { + data: InboundEmailSummary[]; + /** Pass as `cursor` for the next page; null on the last. */ + nextCursor: string | null; +}; + +/** + * Email received at your mailboxes: senders forwarded to Zalify and reply + * domains (Settings → Email → Receiving). Each new one is also an + * `email.received` webhook event. Uses the same Send email key. + */ +export class Inbound { constructor(private readonly http: HttpConfig) {} + /** Newest first. */ + async list(params: ListInboundParams = {}): Promise { + const query = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value !== undefined && value !== null) query.set(key, String(value)); + } + const qs = query.toString(); + return request(this.http, { + method: "GET", + path: `/email/inbound${qs ? `?${qs}` : ""}`, + }); + } + + /** The whole email. Throws ZalifyError `not_found` for an unknown id. */ + async get(id: string): Promise { + return request(this.http, { + method: "GET", + path: `/email/inbound/${encodeURIComponent(id)}`, + }); + } + + /** An attachment's bytes and type. */ + async getAttachment(id: string, attachmentId: string): Promise { + return request(this.http, { + method: "GET", + path: `/email/inbound/${encodeURIComponent(id)}/attachments/${encodeURIComponent(attachmentId)}`, + raw: true, + }); + } +} + +export class Emails { + /** Email received at your mailboxes. */ + readonly inbound: Inbound; + + constructor(private readonly http: HttpConfig) { + this.inbound = new Inbound(http); + } + /** Send one email. Throws ZalifyError when it isn't accepted. */ async send( params: SendEmailParams, @@ -109,7 +285,7 @@ export class Emails { return request(this.http, { method: "POST", path: "/email/send", - body: params, + body: toWire(params), idempotencyKey: options.idempotencyKey ?? randomUUID(), }); } @@ -130,7 +306,8 @@ export class Emails { params: SendBatchParams | EmailMessage[], options: RequestOptions = {} ): Promise { - const body = Array.isArray(params) ? { messages: params } : params; + const given = Array.isArray(params) ? { messages: params } : params; + const body = { ...given, messages: given.messages.map(toWire) }; if (body.messages.length === 0 || body.messages.length > MAX_BATCH) { throw new ZalifyError({ message: `A batch holds 1 to ${MAX_BATCH} messages, got ${body.messages.length}`, diff --git a/src/http.ts b/src/http.ts index c86c57e..0888d3a 100644 --- a/src/http.ts +++ b/src/http.ts @@ -16,8 +16,13 @@ type RequestInit = { path: string; body?: unknown; idempotencyKey?: string; + /** Return the body's bytes and type instead of parsing JSON. */ + raw?: boolean; }; +/** A file the API returned as is. */ +export type RawBody = { content: Uint8Array; contentType: string }; + const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); /** Exponential backoff with full jitter: 0.5s, 1s, 2s… capped. */ @@ -97,6 +102,15 @@ async function once(config: HttpConfig, init: RequestInit): Promise { clearTimeout(timer); } + if (init.raw && response.ok) { + const raw: RawBody = { + content: new Uint8Array(await response.arrayBuffer()), + contentType: + response.headers.get("content-type") ?? "application/octet-stream", + }; + return raw as T; + } + const text = await response.text(); let body: unknown; try { diff --git a/src/index.ts b/src/index.ts index ee39893..a882924 100644 --- a/src/index.ts +++ b/src/index.ts @@ -17,7 +17,9 @@ export type { TrackEventResult, TrackOptions, } from "./events"; +export { threadHeaders } from "./emails"; export type { + EmailAttachment, EmailMessage, EmailSender, EmailSendError, @@ -28,11 +30,20 @@ export type { SendEmailResult, SenderEmail, RequestOptions, + Inbound, + InboundEmail, + InboundEmailAttachment, + InboundEmailSummary, + ListInboundParams, + ListInboundResult, } from "./emails"; +export type { RawBody } from "./http"; export { verifyWebhook, Webhooks, WebhookVerificationError, + type EmailWebhookEvent, + type ReceivedWebhookEvent, type VerifyOptions, type WebhookEvent, type WebhookEventType, diff --git a/src/webhooks.ts b/src/webhooks.ts index 75207b9..11e9b7b 100644 --- a/src/webhooks.ts +++ b/src/webhooks.ts @@ -3,17 +3,20 @@ import { createHmac, timingSafeEqual } from "node:crypto"; /** Event types a Zalify webhook endpoint can receive. */ export type WebhookEventType = | "email.sent" + | "email.failed" | "email.delivered" | "email.bounced" | "email.complained" | "email.opened" | "email.clicked" - | "contact.unsubscribed"; + | "contact.unsubscribed" + | "email.received"; -export type WebhookEvent = { +/** What happened to an email you sent through the Email API. */ +export type EmailWebhookEvent = { /** Stable across retries: use it to drop duplicates. */ id: string; - type: WebhookEventType; + type: Exclude; created_at: string; data: { /** The `id` returned when the email was sent. */ @@ -21,6 +24,13 @@ export type WebhookEvent = { to: string; /** The tags sent with the email. */ tags: Record; + /** + * email.sent: the Message-ID the recipient sees. Keep it to follow up in + * the same thread: `threadHeaders({ messageId })`. + */ + message_id?: string; + /** email.failed: why it wasn't sent. */ + reason?: string; /** email.bounced: `hard` (permanent — stop sending) or `soft`. */ bounce_type?: "hard" | "soft" | (string & {}); /** email.clicked: the link that was clicked. */ @@ -28,6 +38,27 @@ export type WebhookEvent = { }; }; +/** An email arrived at one of your mailboxes. */ +export type ReceivedWebhookEvent = { + id: string; + type: "email.received"; + created_at: string; + data: { + /** Fetch the whole email with `emails.inbound.get(inbound_id)`. */ + inbound_id: string; + /** The `email_id` of your email it replies to, when it answers one. */ + in_reply_to_email_id: string | null; + /** The mailbox it came in on, e.g. support@brand.com. */ + mailbox: string; + from: string; + subject: string; + /** The start of the text body. */ + preview: string; + }; +}; + +export type WebhookEvent = EmailWebhookEvent | ReceivedWebhookEvent; + export class WebhookVerificationError extends Error { constructor(message: string) { super(message); diff --git a/test/inbound.test.ts b/test/inbound.test.ts new file mode 100644 index 0000000..df6c6b0 --- /dev/null +++ b/test/inbound.test.ts @@ -0,0 +1,102 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { threadHeaders, Zalify, ZalifyError } from "../src/index"; + +type Call = { url: string; init: RequestInit }; + +const scripted = (responses: Response[]) => { + const calls: Call[] = []; + const fetchImpl = (async (url: string, init: RequestInit) => { + calls.push({ url, init }); + const next = responses.shift(); + if (!next) throw new Error("no more scripted responses"); + return next; + }) as unknown as typeof fetch; + return { calls, fetchImpl }; +}; + +const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); + +const client = (fetchImpl: typeof fetch) => + new Zalify({ apiKey: "zalify_api_test", fetch: fetchImpl, maxRetryDelayMs: 5 }); + +test("attachments go out base64-encoded, with thread headers", async () => { + const { calls, fetchImpl } = scripted([json({ id: "msg_1" })]); + await client(fetchImpl).emails.send({ + from: "Emma ", + to: "creator@gmail.com", + subject: "Re: Collab", + html: "

Brief attached

", + headers: threadHeaders({ messageId: "" }), + attachments: [ + { filename: "brief.pdf", content: Buffer.from("%PDF"), contentType: "application/pdf" }, + { filename: "note.txt", content: "aGk=" }, + ], + }); + const body = JSON.parse(String(calls[0]?.init.body)); + assert.deepEqual(body.headers, { + "In-Reply-To": "", + References: "", + }); + assert.deepEqual(body.attachments, [ + { filename: "brief.pdf", content: "JVBERg==", contentType: "application/pdf" }, + { filename: "note.txt", content: "aGk=" }, + ]); +}); + +test("threadHeaders extends References and keeps root plus newest", () => { + assert.deepEqual( + threadHeaders({ messageId: "", references: " " }), + { "In-Reply-To": "", References: " " } + ); + const ids = Array.from({ length: 20 }, (_, i) => ``).join(" "); + const refs = threadHeaders({ messageId: "", references: ids }).References.split(" "); + assert.equal(refs.length, 10); + assert.equal(refs[0], ""); + assert.equal(refs.at(-2), ""); + assert.throws(() => threadHeaders({ messageId: "nope" }), ZalifyError); +}); + +test("inbound.list sends filters as a query; get and attachments read back", async () => { + const { calls, fetchImpl } = scripted([ + json({ data: [], nextCursor: null }), + json({ id: "in_1", messageId: "", references: null }), + new Response(new Uint8Array([1, 2, 3]), { + headers: { "content-type": "application/pdf" }, + }), + ]); + const zalify = client(fetchImpl); + await zalify.emails.inbound.list({ mailbox: "emma@zalify.com", limit: 10 }); + const email = await zalify.emails.inbound.get("in_1"); + const file = await zalify.emails.inbound.getAttachment("in_1", "att_1"); + + assert.equal( + calls[0]?.url, + "https://app.zalify.com/api/v1/email/inbound?mailbox=emma%40zalify.com&limit=10" + ); + assert.equal(calls[0]?.init.method, "GET"); + assert.equal(email.messageId, ""); + assert.equal(calls[2]?.url, "https://app.zalify.com/api/v1/email/inbound/in_1/attachments/att_1"); + assert.deepEqual([...file.content], [1, 2, 3]); + assert.equal(file.contentType, "application/pdf"); +}); + +test("an unknown inbound id is a ZalifyError not_found", async () => { + const { fetchImpl } = scripted([json({ error: "No received email", code: "not_found" }, 404)]); + await assert.rejects(client(fetchImpl).emails.inbound.get("x"), (error: unknown) => + error instanceof ZalifyError && error.code === "not_found" && error.status === 404 + ); +}); + +test("a received email threads straight from inbound.get", () => { + const email = { messageId: "", references: "" }; + assert.deepEqual(threadHeaders(email), { + "In-Reply-To": "", + References: " ", + }); + assert.throws(() => threadHeaders({ messageId: null }), ZalifyError); +}); From 00401602bb0b008d1a90147661220494b63f26b5 Mon Sep 17 00:00:00 2001 From: renyuanz Date: Sat, 7 Nov 2026 11:32:57 +0800 Subject: [PATCH 2/2] feat: conversations and inboxes; drop threadHeaders() zalify.conversations.create / reply / list / get / update / import and messages.list / getAttachment, zalify.inboxes.list, and the conversation.* webhook event types (app#2624, ZAL-174). Threading is done server side now, so threadHeaders() is gone before it ever shipped; headers stay for other custom headers. Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 85 +++++++--- src/client.ts | 6 + src/conversations.ts | 308 +++++++++++++++++++++++++++++++++++++ src/emails.ts | 47 +----- src/errors.ts | 6 + src/http.ts | 2 +- src/index.ts | 22 ++- src/webhooks.ts | 41 ++++- test/conversations.test.ts | 117 ++++++++++++++ test/inbound.test.ts | 33 +--- 10 files changed, 565 insertions(+), 102 deletions(-) create mode 100644 src/conversations.ts create mode 100644 test/conversations.test.ts diff --git a/README.md b/README.md index dda562c..730ea43 100644 --- a/README.md +++ b/README.md @@ -67,50 +67,86 @@ for (const [i, result] of data.entries()) { } ``` -## Attachments and threads +## Attachments -Attach up to 10 files (10 MB together) as bytes or base64. `threadHeaders()` keeps a follow-up in the same thread as an earlier email: +Attach up to 10 files (10 MB together) as bytes or base64: ```ts import { readFile } from "node:fs/promises"; -import { threadHeaders } from "@zalify/sdk"; await zalify.emails.send({ from: "Emma ", to: "creator@example.com", - subject: "Re: Spring collab", - html: "

Following up with the brief.

", - // message_id from your first email's email.sent webhook event - headers: threadHeaders({ messageId: sentMessageId }), + subject: "Spring collab brief", + html: "

Brief attached.

", attachments: [{ filename: "brief.pdf", content: await readFile("brief.pdf") }], }); ``` -`headers` takes up to 10 other headers too. Ones Zalify or the mail provider set (From, To, Cc, Subject, Reply-To, Message-ID, Date, Content-Type, List-Unsubscribe…) are refused. +`headers` takes up to 10 extra headers. Ones Zalify or the mail provider set (From, To, Cc, Subject, Reply-To, Message-ID, Date, Content-Type, List-Unsubscribe…) are refused. + +## Conversations + +For back-and-forth with a person: start a conversation, reply in it, and replies that come back land in it. Zalify fills in the sender, recipient, `Re:` subject and thread headers, so follow-ups and answers stay in one thread in their mail client. Email today; every conversation and message carries `channel`, so SMS and WhatsApp won't change the API. The key needs the **Conversations** permission. + +```ts +// Start one: the first email +const { conversation } = await zalify.conversations.create( + { + inbox: "emma@acme.com", // an inbox id or address: see zalify.inboxes.list() + contact: { email: "creator@example.com" }, + subject: "Spring collab", + html: "

Hi…

", + externalId: campaignCreator.id, // your own id, unique in the workspace + metadata: { campaignId: "c_9" }, + }, + { idempotencyKey: `outreach:${campaignCreator.id}` } +); + +// Follow up before they answer, or reply after: content only +await zalify.conversations.reply(conversation.id, { text: "Just checking in!" }); + +// What came back: conversation.message.received +const event = zalify.webhooks.verify(rawBody, req.headers); +if (event.type === "conversation.message.received") { + const { conversation, message } = event.data; + // message.textWithoutQuote: what they wrote this time, without the quoted thread + await zalify.conversations.reply(conversation.id, { text: "Thanks, sending the contract." }); +} + +// Read +await zalify.conversations.list({ externalId: campaignCreator.id }); +await zalify.conversations.list({ contact: "creator@example.com", status: "open" }); +const { data: messages } = await zalify.conversations.messages.list(conversation.id); +await zalify.conversations.update(conversation.id, { status: "closed" }); +``` + +Every received email lands in a conversation: the one it replies to, else a new one (replies to broadcasts and flows, mail out of the blue), so `conversation.message.received` covers everything that comes in. + +Moving threads over from another mailbox provider? Register each one by its Message-IDs and keep replying in it: + +```ts +await zalify.conversations.import({ + inbox: "emma@acme.com", + contact: { email: "creator@example.com" }, + subject: "Spring collab", + messageIds: gmailThread.messages.map((m) => m.messageIdHeader), // oldest first + externalId: campaignCreator.id, +}); +``` ## Receive email -Mail that arrives at your mailboxes (senders forwarded to Zalify, or a reply domain, in **Settings → Email → Receiving**) can be read with the same key. Each new email is also an `email.received` webhook event. +The raw received mail is also readable on its own, with a Send email key. Each new email is an `email.received` webhook event too. ```ts const { data, nextCursor } = await zalify.emails.inbound.list({ mailbox: "emma@acme.com" }); - const email = await zalify.emails.inbound.get(data[0].id); // { from, subject, text, html, messageId, references, inReplyToEmailId, attachments, … } -// inReplyToEmailId: the id of your email it answers, when it answers one for (const file of email.attachments) { const { content, contentType } = await zalify.emails.inbound.getAttachment(email.id, file.id); } - -// Reply in its thread -await zalify.emails.send({ - from: "Emma ", - to: email.replyTo ?? email.from, - subject: `Re: ${email.subject}`, - html: "

Sounds good!

", - headers: threadHeaders(email), -}); ``` ## Contacts @@ -196,7 +232,7 @@ try { | code | status | meaning | | --- | --- | --- | | `unauthorized` | 401 | missing or invalid API key | -| `missing_scope` | 403 | the key lacks the permission: **Send email**, **Manage contacts** or **Track events** | +| `missing_scope` | 403 | the key lacks the permission: **Send email**, **Conversations**, **Manage contacts** or **Track events** | | `email_not_enabled` | 403 | the workspace has no sending set up yet | | `contacts_not_enabled` | 403 | the workspace has no contacts set up yet | | `list_not_found` | 404 | a list in `lists` isn't in your workspace (nothing was written) | @@ -205,6 +241,10 @@ try { | `unverified_sender` | 422 | the from address isn't on a verified domain | | `not_subscribed` | 422 | a marketing recipient isn't a subscribed contact | | `idempotency_conflict` | 409 | the idempotency key was used for a different request | +| `conversation_exists` | 409 | a conversation already has this `externalId` (`details.conversationId`); reply to it | +| `inbox_not_found` | 404 | no inbox with that id or address; see `zalify.inboxes.list()` | +| `inbox_cannot_send` | 422 | the inbox only receives (a catch-all reply domain) | +| `suppressed` | 422 | the recipient bounced hard or complained before | | `rate_limited` | 429 | over 120 requests a minute for this key (a batch counts once) | | `new_recipient_limit` | 429 | the recipient is new to your workspace and today's allowance of new recipients is used; it resets at 00:00 UTC (`retryAfter`) | | `invalid_event` | 422 | an event was refused, e.g. properties over 64 KB or `time` out of range (see `field`) | @@ -236,7 +276,7 @@ new Zalify({ Add an endpoint in **Settings → Developer → Webhooks** to get events for email sent through the API, and for email you receive: -- `email.sent`, with `message_id`: the Message-ID the recipient sees, for `threadHeaders()` +- `email.sent`, with `message_id`: the Message-ID the recipient sees - `email.failed`, with `reason` - `email.delivered` - `email.bounced`, with `bounce_type` `hard` or `soft` @@ -245,6 +285,7 @@ Add an endpoint in **Settings → Developer → Webhooks** to get events for ema - `email.clicked`, with `url` - `contact.unsubscribed` - `email.received`: `{ inbound_id, in_reply_to_email_id, mailbox, from, subject, preview }`; fetch the whole email with `emails.inbound.get(inbound_id)` +- `conversation.created`, `conversation.message.received`, `conversation.message.updated`, `conversation.updated`: `{ conversation, message? }` (`message.html` left out; read it with `conversations.messages.list`) The signing secret (`whsec_…`) is shown once, when you create the endpoint. diff --git a/src/client.ts b/src/client.ts index 2ce4691..6397c1f 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,4 +1,5 @@ import { Contacts } from "./contacts"; +import { Conversations, Inboxes } from "./conversations"; import { Emails } from "./emails"; import { Events } from "./events"; import { Webhooks } from "./webhooks"; @@ -25,6 +26,9 @@ export type ZalifyOptions = { export class Zalify { readonly emails: Emails; + /** Two-way exchanges with one person: start, reply, read. */ + readonly conversations: Conversations; + readonly inboxes: Inboxes; readonly contacts: Contacts; readonly events: Events; readonly webhooks: Webhooks; @@ -59,6 +63,8 @@ export class Zalify { userAgent: `zalify-node/${VERSION}`, }; this.emails = new Emails(http); + this.conversations = new Conversations(http); + this.inboxes = new Inboxes(http); this.contacts = new Contacts(http); this.events = new Events(http); this.webhooks = new Webhooks(options.webhookSecret); diff --git a/src/conversations.ts b/src/conversations.ts new file mode 100644 index 0000000..d9c4576 --- /dev/null +++ b/src/conversations.ts @@ -0,0 +1,308 @@ +import { randomUUID } from "node:crypto"; +import type { EmailAttachment, EmailType, RequestOptions } from "./emails"; +import { type HttpConfig, type RawBody, request } from "./http"; + +/** Channels a conversation can use. Email today; SMS and WhatsApp next. */ +export type Channel = "email"; + +/** Your side of conversations: one per sender email, plus receive-only reply domains. */ +export type Inbox = { + id: string; + name: string; + email: string; + /** False for a receive-only address. */ + canSend: boolean; +}; + +export type ConversationChannel = { + channel: Channel; + /** The inbox's address on this channel. */ + address: string; + /** The other party's address: where replies go. */ + contact: string; + sendable: boolean; + /** Why it can't send, when it can't. */ + reason: string | null; +}; + +export type Conversation = { + id: string; + inboxId: string; + inbox: Inbox; + status: "open" | "closed"; + subject: string; + contact: { email: string | null }; + /** Your own id for what it's about; unique in the workspace. */ + externalId: string | null; + metadata: Record | null; + /** The channel the contact last wrote on; replies default to it. */ + lastChannel: Channel | (string & {}); + channels: ConversationChannel[]; + lastMessageAt: string; + lastInboundAt: string | null; + createdAt: string; +}; + +export type ConversationAttachment = { + id: string; + filename: string; + contentType: string; + size: number; + contentId: string | null; + inline: boolean; +}; + +export type MessageStatus = + | "queued" + | "sent" + | "delayed" + | "delivered" + | "opened" + | "bounced" + | "complained" + | "failed" + | "received"; + +export type ConversationMessage = { + id: string; + conversationId: string; + direction: "inbound" | "outbound"; + channel: Channel | (string & {}); + from: string; + to: string; + text: string | null; + /** Null in webhook events; read it with `messages.list`. */ + html: string | null; + /** Inbound email: what they wrote this time, without the quoted thread. */ + textWithoutQuote: string | null; + attachments: ConversationAttachment[]; + status: MessageStatus | (string & {}); + statusAt: string | null; + /** The bounce type, or why it failed. */ + statusDetail: string | null; + email?: { subject: string; messageId: string | null }; + createdAt: string; +}; + +/** Give `text` or `html` (or both); text alone is sent as simple HTML too. */ +export type MessageContent = { + text?: string; + html?: string; + /** Up to 10 files, 10 MB together. */ + attachments?: EmailAttachment[]; +}; + +export type CreateConversationParams = MessageContent & { + /** An inbox id, or its email address (e.g. `emma@brand.com`). */ + inbox: string; + contact: { email: string }; + channel?: Channel; + subject: string; + /** Your own id for what it's about, e.g. a campaign-creator id. */ + externalId?: string; + /** Your JSON, up to 8 KB. */ + metadata?: Record; + /** Default `transactional`. */ + type?: EmailType; +}; + +export type ReplyParams = MessageContent & { + /** Defaults to the channel the contact last wrote on. */ + channel?: Channel; +}; + +export type ListConversationsParams = { + /** An inbox id or address. */ + inbox?: string; + status?: "open" | "closed"; + /** The contact's email address. */ + contact?: string; + externalId?: string; + /** 1–100, default 25. */ + limit?: number; + cursor?: string; +}; + +export type UpdateConversationParams = { + status?: "open" | "closed"; + /** Null clears it. */ + externalId?: string | null; + /** Replaces it; null clears it. */ + metadata?: Record | null; +}; + +export type ImportConversationParams = { + inbox: string; + contact: { email: string }; + subject: string; + /** The thread's Message-IDs, oldest first, with angle brackets (up to 50). */ + messageIds: string[]; + lastMessageAt?: string; + externalId?: string; + metadata?: Record; +}; + +export type Page = { + data: T[]; + /** Pass as `cursor` for the next page; null on the last. */ + nextCursor: string | null; +}; + +export type ConversationWithMessage = { + conversation: Conversation; + message: ConversationMessage; +}; + +const toBase64 = (content: Uint8Array | string) => + typeof content === "string" + ? content + : Buffer.from(content.buffer, content.byteOffset, content.byteLength).toString( + "base64" + ); + +const toWire = (params: T): T => + params.attachments + ? { + ...params, + attachments: params.attachments.map((file) => ({ + ...file, + content: toBase64(file.content), + })), + } + : params; + +const query = (params: Record) => { + const search = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value !== undefined && value !== null) search.set(key, String(value)); + } + const qs = search.toString(); + return qs ? `?${qs}` : ""; +}; + +const path = (id: string) => `/conversations/${encodeURIComponent(id)}`; + +/** A conversation's messages. */ +export class Messages { + constructor(private readonly http: HttpConfig) {} + + /** Oldest first, every channel together. */ + async list( + conversationId: string, + params: { limit?: number; cursor?: string } = {} + ): Promise> { + return request>(this.http, { + method: "GET", + path: `${path(conversationId)}/messages${query(params)}`, + }); + } + + /** A received attachment's bytes and type. */ + async getAttachment( + conversationId: string, + messageId: string, + attachmentId: string + ): Promise { + return request(this.http, { + method: "GET", + path: `${path(conversationId)}/messages/${encodeURIComponent(messageId)}/attachments/${encodeURIComponent(attachmentId)}`, + raw: true, + }); + } +} + +/** + * Two-way exchanges with one person. Start one, reply in it; what comes back + * arrives as `conversation.message.received` webhook events. Zalify fills in + * the sender, recipient, subject and thread headers. Needs a key with the + * Conversations permission. + */ +export class Conversations { + readonly messages: Messages; + + constructor(private readonly http: HttpConfig) { + this.messages = new Messages(http); + } + + /** Start a conversation with its first message. */ + async create( + params: CreateConversationParams, + options: RequestOptions = {} + ): Promise { + return request(this.http, { + method: "POST", + path: "/conversations", + body: toWire(params), + idempotencyKey: options.idempotencyKey ?? randomUUID(), + }); + } + + /** + * Reply, or follow up before they answer. Goes to the contact, from the + * conversation's inbox, threaded under its newest message. + */ + async reply( + conversationId: string, + params: ReplyParams, + options: RequestOptions = {} + ): Promise { + return request(this.http, { + method: "POST", + path: `${path(conversationId)}/messages`, + body: toWire(params), + idempotencyKey: options.idempotencyKey ?? randomUUID(), + }); + } + + /** Newest activity first. */ + async list(params: ListConversationsParams = {}): Promise> { + return request>(this.http, { + method: "GET", + path: `/conversations${query(params)}`, + }); + } + + /** Throws ZalifyError `not_found` for an unknown id. */ + async get(conversationId: string): Promise { + return request(this.http, { + method: "GET", + path: path(conversationId), + }); + } + + /** Close or reopen it, or change its externalId or metadata. */ + async update( + conversationId: string, + params: UpdateConversationParams + ): Promise { + return request(this.http, { + method: "PATCH", + path: path(conversationId), + body: params, + }); + } + + /** + * Bring over a thread that started with another mailbox provider, so your + * next reply continues it and its replies come back here. + */ + async import(params: ImportConversationParams): Promise { + return request(this.http, { + method: "POST", + path: "/conversations/import", + body: params, + }); + } +} + +/** Where conversations happen. */ +export class Inboxes { + constructor(private readonly http: HttpConfig) {} + + async list(): Promise<{ data: Inbox[] }> { + return request<{ data: Inbox[] }>(this.http, { + method: "GET", + path: "/inboxes", + }); + } +} diff --git a/src/emails.ts b/src/emails.ts index a9dbbe9..7382861 100644 --- a/src/emails.ts +++ b/src/emails.ts @@ -43,10 +43,10 @@ export type EmailMessage = EmailSender & { */ tags?: Record; /** - * Up to 10 extra headers, e.g. from `threadHeaders()` to keep a follow-up - * or a reply in the same thread. From, To, Cc, Subject, Reply-To, - * Message-ID, Date, Content-Type, List-Unsubscribe and the like are set by - * Zalify and refused. + * Up to 10 extra headers. For back-and-forth with a person, use + * `zalify.conversations`, which threads replies for you. From, To, Cc, + * Subject, Reply-To, Message-ID, Date, Content-Type, List-Unsubscribe and + * the like are set by Zalify and refused. */ headers?: Record; /** Up to 10 files, 10 MB together. */ @@ -135,43 +135,6 @@ const toWire = (message: T): T => } : message; -const MESSAGE_ID = /<[^<>\s]+>/g; -/** References only needs the thread's root and its latest ids. */ -const MAX_REFERENCES = 10; - -/** - * Headers that put an email in the same thread as an earlier one: - * `In-Reply-To` is the earlier email's Message-ID, `References` its - * References plus that id (RFC 5322). Pass the `messageId` and `references` - * of a received email (`emails.inbound.get`), or the `message_id` of your own - * email's `email.sent` webhook event to follow up before they reply. - */ -export function threadHeaders(earlier: { - /** Null for a received email that had none: it can't be threaded. */ - messageId: string | null; - references?: string | null; -}): { "In-Reply-To": string; References: string } { - const [messageId] = earlier.messageId?.match(MESSAGE_ID) ?? []; - if (!messageId) { - throw new ZalifyError({ - message: `Not a Message-ID: ${earlier.messageId ?? "none"}`, - code: "invalid_request", - status: 0, - }); - } - const references = (earlier.references?.match(MESSAGE_ID) ?? []).filter( - (id) => id !== messageId - ); - const kept = - references.length < MAX_REFERENCES - ? references - : [references[0] as string, ...references.slice(-(MAX_REFERENCES - 2))]; - return { - "In-Reply-To": messageId, - References: [...kept, messageId].join(" "), - }; -} - /** A received email in a list. */ export type InboundEmailSummary = { id: string; @@ -203,7 +166,7 @@ export type InboundEmail = InboundEmailSummary & { to: string; cc: string[]; replyTo: string | null; - /** Its Message-ID; pass the email to `threadHeaders()` to reply in its thread. */ + /** Its Message-ID. To answer it, reply in its conversation. */ messageId: string | null; references: string | null; text: string | null; diff --git a/src/errors.ts b/src/errors.ts index 9ed8048..e673eb7 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -26,6 +26,12 @@ export type ZalifyErrorCode = | "daily_limit" | "suppressed" | "rejected" + | "not_found" + | "conversation_exists" + | "inbox_not_found" + | "inbox_cannot_send" + | "channel_unavailable" + | "email_api_not_enabled" | "network_error" | "timeout" | (string & {}); diff --git a/src/http.ts b/src/http.ts index 0888d3a..da6c6e1 100644 --- a/src/http.ts +++ b/src/http.ts @@ -12,7 +12,7 @@ export type HttpConfig = { }; type RequestInit = { - method: "GET" | "POST"; + method: "GET" | "POST" | "PATCH"; path: string; body?: unknown; idempotencyKey?: string; diff --git a/src/index.ts b/src/index.ts index a882924..2de877e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -17,7 +17,26 @@ export type { TrackEventResult, TrackOptions, } from "./events"; -export { threadHeaders } from "./emails"; +export type { + Channel, + Conversation, + ConversationAttachment, + ConversationChannel, + ConversationMessage, + Conversations, + ConversationWithMessage, + CreateConversationParams, + ImportConversationParams, + Inbox, + Inboxes, + ListConversationsParams, + MessageContent, + Messages, + MessageStatus, + Page, + ReplyParams, + UpdateConversationParams, +} from "./conversations"; export type { EmailAttachment, EmailMessage, @@ -42,6 +61,7 @@ export { verifyWebhook, Webhooks, WebhookVerificationError, + type ConversationWebhookEvent, type EmailWebhookEvent, type ReceivedWebhookEvent, type VerifyOptions, diff --git a/src/webhooks.ts b/src/webhooks.ts index 11e9b7b..9f5622c 100644 --- a/src/webhooks.ts +++ b/src/webhooks.ts @@ -1,4 +1,5 @@ import { createHmac, timingSafeEqual } from "node:crypto"; +import type { Conversation, ConversationMessage } from "./conversations"; /** Event types a Zalify webhook endpoint can receive. */ export type WebhookEventType = @@ -10,13 +11,20 @@ export type WebhookEventType = | "email.opened" | "email.clicked" | "contact.unsubscribed" - | "email.received"; + | "email.received" + | "conversation.created" + | "conversation.message.received" + | "conversation.message.updated" + | "conversation.updated"; /** What happened to an email you sent through the Email API. */ export type EmailWebhookEvent = { /** Stable across retries: use it to drop duplicates. */ id: string; - type: Exclude; + type: Exclude< + WebhookEventType, + "email.received" | ConversationWebhookEvent["type"] + >; created_at: string; data: { /** The `id` returned when the email was sent. */ @@ -24,10 +32,7 @@ export type EmailWebhookEvent = { to: string; /** The tags sent with the email. */ tags: Record; - /** - * email.sent: the Message-ID the recipient sees. Keep it to follow up in - * the same thread: `threadHeaders({ messageId })`. - */ + /** email.sent: the Message-ID the recipient sees. */ message_id?: string; /** email.failed: why it wasn't sent. */ reason?: string; @@ -57,7 +62,29 @@ export type ReceivedWebhookEvent = { }; }; -export type WebhookEvent = EmailWebhookEvent | ReceivedWebhookEvent; +/** + * A conversation started, a message came in (any channel), a sent message's + * delivery moved on, or a conversation's status or metadata changed. + * `message.html` is left out; read it with `conversations.messages.list`. + */ +export type ConversationWebhookEvent = { + id: string; + type: + | "conversation.created" + | "conversation.message.received" + | "conversation.message.updated" + | "conversation.updated"; + created_at: string; + data: { + conversation: Conversation; + message?: ConversationMessage; + }; +}; + +export type WebhookEvent = + | EmailWebhookEvent + | ReceivedWebhookEvent + | ConversationWebhookEvent; export class WebhookVerificationError extends Error { constructor(message: string) { diff --git a/test/conversations.test.ts b/test/conversations.test.ts new file mode 100644 index 0000000..93a7ab7 --- /dev/null +++ b/test/conversations.test.ts @@ -0,0 +1,117 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { Zalify, ZalifyError } from "../src/index"; + +type Call = { url: string; init: RequestInit }; + +const scripted = (responses: Response[]) => { + const calls: Call[] = []; + const fetchImpl = (async (url: string, init: RequestInit) => { + calls.push({ url, init }); + const next = responses.shift(); + if (!next) throw new Error("no more scripted responses"); + return next; + }) as unknown as typeof fetch; + return { calls, fetchImpl }; +}; + +const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); + +const client = (fetchImpl: typeof fetch) => + new Zalify({ apiKey: "zalify_api_test", fetch: fetchImpl, maxRetryDelayMs: 5 }); + +const BASE = "https://app.zalify.com/api/v1"; +const body = (call: Call | undefined) => JSON.parse(String(call?.init.body)); +const header = (call: Call | undefined, name: string) => + new Headers(call?.init.headers).get(name); + +test("create and reply send content only; idempotency keys go along", async () => { + const { calls, fetchImpl } = scripted([ + json({ conversation: { id: "conv_1" }, message: { id: "m1" } }, 201), + json({ conversation: { id: "conv_1" }, message: { id: "m2" } }, 201), + ]); + const zalify = client(fetchImpl); + const { conversation } = await zalify.conversations.create( + { + inbox: "emma@zalify.com", + contact: { email: "creator@example.com" }, + subject: "Collab", + html: "

Hi

", + externalId: "cc_1", + attachments: [{ filename: "brief.pdf", content: Buffer.from("%PDF") }], + }, + { idempotencyKey: "outreach:cc_1" } + ); + await zalify.conversations.reply(conversation.id, { text: "Following up" }); + + assert.equal(calls[0]?.url, `${BASE}/conversations`); + assert.equal(calls[0]?.init.method, "POST"); + assert.equal(header(calls[0], "idempotency-key"), "outreach:cc_1"); + assert.equal(body(calls[0]).attachments[0].content, "JVBERg=="); + assert.equal(calls[1]?.url, `${BASE}/conversations/conv_1/messages`); + assert.deepEqual(body(calls[1]), { text: "Following up" }); + assert.ok(header(calls[1], "idempotency-key"), "a key is made per call"); +}); + +test("list, get, update, messages, import and inboxes hit their routes", async () => { + const { calls, fetchImpl } = scripted([ + json({ data: [], nextCursor: null }), + json({ id: "c 1" }), + json({ id: "c 1", status: "closed" }), + json({ data: [], nextCursor: null }), + json({ id: "c2" }, 201), + json({ data: [] }), + new Response(new Uint8Array([7]), { headers: { "content-type": "image/png" } }), + ]); + const zalify = client(fetchImpl); + await zalify.conversations.list({ externalId: "cc_1", status: "open" }); + await zalify.conversations.get("c 1"); + await zalify.conversations.update("c 1", { status: "closed", metadata: null }); + await zalify.conversations.messages.list("c 1", { limit: 50 }); + await zalify.conversations.import({ + inbox: "emma@zalify.com", + contact: { email: "creator@example.com" }, + subject: "Re: Collab", + messageIds: [""], + }); + await zalify.inboxes.list(); + const file = await zalify.conversations.messages.getAttachment("c 1", "m1", "a1"); + + assert.equal(calls[0]?.url, `${BASE}/conversations?externalId=cc_1&status=open`); + assert.equal(calls[1]?.url, `${BASE}/conversations/c%201`); + assert.equal(calls[2]?.init.method, "PATCH"); + assert.deepEqual(body(calls[2]), { status: "closed", metadata: null }); + assert.equal(calls[3]?.url, `${BASE}/conversations/c%201/messages?limit=50`); + assert.equal(calls[4]?.url, `${BASE}/conversations/import`); + assert.equal(calls[5]?.url, `${BASE}/inboxes`); + assert.equal(calls[6]?.url, `${BASE}/conversations/c%201/messages/m1/attachments/a1`); + assert.equal(file.contentType, "image/png"); +}); + +test("a taken externalId surfaces as conversation_exists", async () => { + const { fetchImpl } = scripted([ + json( + { + error: "A conversation with this externalId already exists.", + code: "conversation_exists", + details: { conversationId: "conv_9" }, + }, + 409 + ), + ]); + await assert.rejects( + client(fetchImpl).conversations.create({ + inbox: "emma@zalify.com", + contact: { email: "a@example.com" }, + subject: "Hi", + text: "Hi", + externalId: "dup", + }), + (error: unknown) => + error instanceof ZalifyError && error.code === "conversation_exists" && error.status === 409 + ); +}); diff --git a/test/inbound.test.ts b/test/inbound.test.ts index df6c6b0..59df7ad 100644 --- a/test/inbound.test.ts +++ b/test/inbound.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { threadHeaders, Zalify, ZalifyError } from "../src/index"; +import { Zalify, ZalifyError } from "../src/index"; type Call = { url: string; init: RequestInit }; @@ -24,43 +24,27 @@ const json = (body: unknown, status = 200) => const client = (fetchImpl: typeof fetch) => new Zalify({ apiKey: "zalify_api_test", fetch: fetchImpl, maxRetryDelayMs: 5 }); -test("attachments go out base64-encoded, with thread headers", async () => { +test("attachments go out base64-encoded, with extra headers", async () => { const { calls, fetchImpl } = scripted([json({ id: "msg_1" })]); await client(fetchImpl).emails.send({ from: "Emma ", to: "creator@gmail.com", subject: "Re: Collab", html: "

Brief attached

", - headers: threadHeaders({ messageId: "" }), + headers: { "X-Campaign": "c9" }, attachments: [ { filename: "brief.pdf", content: Buffer.from("%PDF"), contentType: "application/pdf" }, { filename: "note.txt", content: "aGk=" }, ], }); const body = JSON.parse(String(calls[0]?.init.body)); - assert.deepEqual(body.headers, { - "In-Reply-To": "", - References: "", - }); + assert.deepEqual(body.headers, { "X-Campaign": "c9" }); assert.deepEqual(body.attachments, [ { filename: "brief.pdf", content: "JVBERg==", contentType: "application/pdf" }, { filename: "note.txt", content: "aGk=" }, ]); }); -test("threadHeaders extends References and keeps root plus newest", () => { - assert.deepEqual( - threadHeaders({ messageId: "", references: " " }), - { "In-Reply-To": "", References: " " } - ); - const ids = Array.from({ length: 20 }, (_, i) => ``).join(" "); - const refs = threadHeaders({ messageId: "", references: ids }).References.split(" "); - assert.equal(refs.length, 10); - assert.equal(refs[0], ""); - assert.equal(refs.at(-2), ""); - assert.throws(() => threadHeaders({ messageId: "nope" }), ZalifyError); -}); - test("inbound.list sends filters as a query; get and attachments read back", async () => { const { calls, fetchImpl } = scripted([ json({ data: [], nextCursor: null }), @@ -91,12 +75,3 @@ test("an unknown inbound id is a ZalifyError not_found", async () => { error instanceof ZalifyError && error.code === "not_found" && error.status === 404 ); }); - -test("a received email threads straight from inbound.get", () => { - const email = { messageId: "", references: "" }; - assert.deepEqual(threadHeaders(email), { - "In-Reply-To": "", - References: " ", - }); - assert.throws(() => threadHeaders({ messageId: null }), ZalifyError); -});