SPB Git

Repository Public

client.ts 20.6 KB 398 lines typescript

1// The resource-style surface. Every method maps to one operation of docs/OPENAPI.yaml.2import { TimeoutError } from "./errors.js"3import { HttpClient, type InternalRequest, type RequestOptions, type SPMailOptions } from "./http.js"4import { constructWebhookEvent, signWebhookPayload, verifyWebhookSignature, type VerifySignatureParams } from "./signature.js"5import {6  FINAL_STATUSES,7  type Address, type AddressCreateParams, type AddressListParams, type AddressUpdateParams, type Attachment, type Automation, type AutomationUpdateParams,8  type BatchResult, type Changes, type ChangesParams, type DownloadedAttachment, type DraftCreateParams, type DraftListParams, type DraftUpdateParams, type Event,9  type EventListParams, type Folder, type FolderCreateParams, type FolderRole, type ForwardParams, type Health, type Me, type Message, type MessageListParams,10  type MessageSummary, type MessageUpdateParams, type OutboundListParams, type OutboundMessage, type Page, type RenderedTemplate, type ReplyParams,11  type ScheduledListParams, type SendParams, type Template, type TemplateRenderParams, type TemplateSendParams, type TemplateSummary, type Thread, type ThreadListParams,12  type ThreadSummary, type UploadParams, type UploadedFile, type Webhook, type WebhookCreateParams, type WebhookDelivery, type WebhookDeliveryListParams,13  type WebhookEvent, type WebhookTestResult, type WebhookUpdateParams,14} from "./types.js"1516const enc = encodeURIComponent17type Opts = RequestOptions1819/** Walks a cursor-paginated list page by page. */20async function* paginate<T, P extends { cursor?: string }>(fetchPage: (params: P) => Promise<Page<T>>, params: P): AsyncGenerator<T, void, undefined> {21  let cursor = params.cursor22  for (;;) {23    const page = await fetchPage({ ...params, cursor })24    for (const item of page.data) yield item25    if (!page.has_more || !page.next_cursor) return26    cursor = page.next_cursor27  }28}2930abstract class Resource {31  constructor(protected readonly http: HttpClient) {}32  protected req<T>(r: InternalRequest, o?: Opts): Promise<T> {33    return this.http.request<T>({ ...r, ...(o ?? {}) })34  }35}3637export interface WaitForDeliveryOptions {38  /** Give up after this long (default 60 000 ms) with a TimeoutError carrying the last observed status in `details`. */39  timeoutMs?: number40  /** Delay between two polls (default 1 500 ms). */41  intervalMs?: number42  signal?: AbortSignal43}4445class Outbound extends Resource {46  /** Sends created by this key, or made from an address it can act as; newest first. */47  list(params: OutboundListParams = {}, o?: Opts): Promise<Page<OutboundMessage>> {48    return this.req({ method: "GET", path: "/messages/outbound", query: params }, o)49  }50  iterate(params: OutboundListParams = {}, o?: Opts): AsyncGenerator<OutboundMessage, void, undefined> {51    return paginate((p) => this.list(p, o), params)52  }53  /** One send, with per-recipient status and SMTP reply. */54  get(id: string, o?: Opts): Promise<OutboundMessage> {55    return this.req({ method: "GET", path: `/messages/outbound/${enc(id)}` }, o)56  }57}58class Scheduled extends Resource {59  list(params: ScheduledListParams = {}, o?: Opts): Promise<Page<OutboundMessage>> {60    return this.req({ method: "GET", path: "/messages/scheduled", query: params }, o)61  }62  iterate(params: ScheduledListParams = {}, o?: Opts): AsyncGenerator<OutboundMessage, void, undefined> {63    return paginate((p) => this.list(p, o), params)64  }65  /** Cancels a scheduled send (→ `cancelled`); `409 not_cancellable` once it is no longer scheduled. */66  cancel(id: string, o?: Opts): Promise<OutboundMessage> {67    return this.req({ method: "DELETE", path: `/messages/scheduled/${enc(id)}` }, o)68  }69}70class Attachments extends Resource {71  list(messageId: string, o?: Opts): Promise<Attachment[]> {72    return this.req<{ data: Attachment[] }>({ method: "GET", path: `/messages/${enc(messageId)}/attachments` }, o).then((r) => r.data)73  }74  /** Downloads one attachment into memory. The bytes are untrusted third-party content: never execute or render them blindly. */75  async download(messageId: string, attachmentId: string, o?: Opts): Promise<DownloadedAttachment> {76    const r = await this.req<{ data: Uint8Array; headers: Headers }>({ method: "GET", path: `/messages/${enc(messageId)}/attachments/${enc(attachmentId)}`, binary: true }, o)77    const m = /filename\*=UTF-8''([^;]+)/i.exec(r.headers.get("content-disposition") ?? "")78    let filename: string | null = null79    if (m) { try { filename = decodeURIComponent(m[1]!) } catch { filename = m[1]! } }80    return { data: r.data, filename, size: r.data.byteLength }81  }82}8384class Messages extends Resource {85  readonly outbound = new Outbound(this.http)86  readonly scheduled = new Scheduled(this.http)87  readonly attachments = new Attachments(this.http)8889  /**90   * Sends a message (or, with `template_id` + `variables`, a rendered template). Look at `status` in the answer:91   * `sent`/`failed` (200), `scheduled`/`pending_approval`/`queued` (202), `draft` (201). `pending_approval` means NOTHING was sent yet.92   */93  send(params: SendParams | TemplateSendParams, o?: Opts): Promise<OutboundMessage> {94    return this.req({ method: "POST", path: "/messages/send", body: params, idempotent: true }, o)95  }96  /** Up to 50 messages; each one is validated, authorised and limited independently (`results[i].ok`). */97  sendBatch(messages: (SendParams | TemplateSendParams)[], o?: Opts): Promise<BatchResult> {98    return this.req({ method: "POST", path: "/messages/send-batch", body: { messages }, idempotent: true }, o)99  }100  /** Newest first. Search filters (`from`, `to`, `subject`, `text`, `label`) need the scope `mail.search`. */101  list(params: MessageListParams = {}, o?: Opts): Promise<Page<MessageSummary>> {102    return this.req({ method: "GET", path: "/messages", query: params }, o)103  }104  /** `for await (const m of client.messages.iterate({ folder: "inbox", unread: true }))` — follows `next_cursor` for you. */105  iterate(params: MessageListParams = {}, o?: Opts): AsyncGenerator<MessageSummary, void, undefined> {106    return paginate((p) => this.list(p, o), params)107  }108  /** Full message: headers, text, sanitised HTML, attachments, authentication results. */109  get(id: string, o?: Opts): Promise<Message> {110    return this.req({ method: "GET", path: `/messages/${enc(id)}` }, o)111  }112  /** Incremental sync of one mailbox. Without `since`: the current state. `409 resync_required` → list again. */113  changes(params: ChangesParams = {}, o?: Opts): Promise<Changes> {114    return this.req({ method: "GET", path: "/messages/changes", query: params }, o)115  }116  reply(id: string, params: ReplyParams, o?: Opts): Promise<OutboundMessage> {117    return this.req({ method: "POST", path: `/messages/${enc(id)}/reply`, body: params, idempotent: true }, o)118  }119  forward(id: string, params: ForwardParams, o?: Opts): Promise<OutboundMessage> {120    return this.req({ method: "POST", path: `/messages/${enc(id)}/forward`, body: params, idempotent: true }, o)121  }122  /** Read/unread, star, labels. */123  update(id: string, params: MessageUpdateParams, o?: Opts): Promise<MessageSummary> {124    return this.req({ method: "PATCH", path: `/messages/${enc(id)}`, body: params, repeatable: true }, o)125  }126  markRead(id: string, o?: Opts): Promise<MessageSummary> {127    return this.update(id, { unread: false }, o)128  }129  markUnread(id: string, o?: Opts): Promise<MessageSummary> {130    return this.update(id, { unread: true }, o)131  }132  /** Moves to a role (`inbox`, `archive`, `trash`, `junk`, `sent`, `drafts`) or to a folder id of the same mailbox. */133  move(id: string, folder: FolderRole | (string & {}), o?: Opts): Promise<MessageSummary> {134    return this.req({ method: "POST", path: `/messages/${enc(id)}/move`, body: { folder }, repeatable: true }, o)135  }136  archive(id: string, o?: Opts): Promise<MessageSummary> {137    return this.move(id, "archive", o)138  }139  /** Moves to Trash. With `{ permanent: true }` the message is destroyed (scope `mail.delete`; the SDK sends the required confirmation). */140  delete(id: string, params: { permanent?: boolean } = {}, o?: Opts): Promise<{ ok: boolean; permanent: boolean }> {141    return params.permanent142      ? this.req({ method: "DELETE", path: `/messages/${enc(id)}`, query: { permanent: true }, body: { confirm: "permanently-delete" } }, o)143      : this.req({ method: "DELETE", path: `/messages/${enc(id)}` }, o)144  }145  /**146   * Polls the status of a send until it is final (`delivered`, `bounced`, `failed`, `cancelled`) and returns it.147   * `delivered` = accepted by the recipient's server, not inbox placement. A send that is `pending_approval` or `scheduled`148   * stays so until someone acts: expect a TimeoutError (its `details.last` holds the last status seen).149   */150  async waitForDelivery(outboundId: string, opts: WaitForDeliveryOptions = {}): Promise<OutboundMessage> {151    const timeoutMs = opts.timeoutMs ?? 60_000152    const intervalMs = Math.max(100, opts.intervalMs ?? 1500)153    const deadline = Date.now() + timeoutMs154    for (;;) {155      const o = await this.outbound.get(outboundId, { signal: opts.signal })156      if ((FINAL_STATUSES as readonly string[]).includes(o.status)) return o157      if (Date.now() + intervalMs > deadline) {158        throw new TimeoutError({ status: 0, code: "timeout", message: `Send ${outboundId} is still "${o.status}" after ${timeoutMs} ms`, details: { last: o } })159      }160      await new Promise<void>((resolve, reject) => {161        const t = setTimeout(resolve, intervalMs)162        opts.signal?.addEventListener("abort", () => { clearTimeout(t); reject(opts.signal!.reason) }, { once: true })163      })164    }165  }166}167168class Threads extends Resource {169  /** One entry per conversation (`latest` = its newest message). Same filters as `messages.list`. */170  list(params: ThreadListParams = {}, o?: Opts): Promise<Page<ThreadSummary>> {171    return this.req({ method: "GET", path: "/threads", query: params }, o)172  }173  iterate(params: ThreadListParams = {}, o?: Opts): AsyncGenerator<ThreadSummary, void, undefined> {174    return paginate((p) => this.list(p, o), params)175  }176  /** Messages of a conversation, oldest first, limited to what the key may see. */177  get(id: string, o?: Opts): Promise<Thread> {178    return this.req({ method: "GET", path: `/threads/${enc(id)}` }, o)179  }180}181182class Drafts extends Resource {183  /** Saves a draft; only `from` is required. The answer's `id` is the draft's `msg_…` id. */184  create(params: DraftCreateParams, o?: Opts): Promise<OutboundMessage> {185    return this.req({ method: "POST", path: "/drafts", body: params, idempotent: true }, o)186  }187  list(params: DraftListParams = {}, o?: Opts): Promise<Page<MessageSummary>> {188    return this.req({ method: "GET", path: "/drafts", query: params }, o)189  }190  iterate(params: DraftListParams = {}, o?: Opts): AsyncGenerator<MessageSummary, void, undefined> {191    return paginate((p) => this.list(p, o), params)192  }193  get(id: string, o?: Opts): Promise<Message> {194    return this.req({ method: "GET", path: `/drafts/${enc(id)}` }, o)195  }196  /** Replaces the given fields. **The answer carries a NEW `id`**: the old one is gone. */197  update(id: string, params: DraftUpdateParams, o?: Opts): Promise<OutboundMessage> {198    return this.req({ method: "PATCH", path: `/drafts/${enc(id)}`, body: params }, o)199  }200  delete(id: string, o?: Opts): Promise<{ ok: boolean }> {201    return this.req({ method: "DELETE", path: `/drafts/${enc(id)}` }, o)202  }203  /** Sends a draft; same checks and outcomes as `messages.send`. */204  send(id: string, params: { send_at?: string } = {}, o?: Opts): Promise<OutboundMessage> {205    return this.req({ method: "POST", path: `/drafts/${enc(id)}/send`, body: params, idempotent: true }, o)206  }207}208209class Folders extends Resource {210  list(params: { address?: string } = {}, o?: Opts): Promise<Folder[]> {211    return this.req<{ data: Folder[] }>({ method: "GET", path: "/folders", query: params }, o).then((r) => r.data)212  }213  create(params: FolderCreateParams, o?: Opts): Promise<Folder> {214    return this.req({ method: "POST", path: "/folders", body: params, idempotent: true }, o)215  }216}217218class Files extends Resource {219  /** Uploads raw bytes (max 50 MB) and returns a `file_…` id to reference in `attachments`. Not idempotent: never retried on failure. */220  upload(params: UploadParams, o?: Opts): Promise<UploadedFile> {221    const type = params.contentType ?? (params.data instanceof Blob && params.data.type ? params.data.type : "application/octet-stream")222    const data = (typeof params.data === "string" ? new TextEncoder().encode(params.data) : params.data) as BodyInit223    return this.req({ method: "POST", path: "/files", query: { filename: params.filename, address: params.address }, raw: { data, contentType: type } }, o)224  }225}226227class AddressBase extends Resource {228  constructor(http: HttpClient, private readonly base: "/addresses" | "/aliases") { super(http) }229  list(params: AddressListParams = {}, o?: Opts): Promise<Address[]> {230    return this.req<{ data: Address[] }>({ method: "GET", path: this.base, query: params }, o).then((r) => r.data)231  }232  create(params: AddressCreateParams, o?: Opts): Promise<Address> {233    return this.req({ method: "POST", path: this.base, body: params, idempotent: true }, o)234  }235  /** `id` is the UUID or the address itself. */236  update(id: string, params: AddressUpdateParams, o?: Opts): Promise<Address> {237    return this.req({ method: "PATCH", path: `${this.base}/${enc(id)}`, body: params, repeatable: true }, o)238  }239}240class Addresses extends AddressBase {241  constructor(http: HttpClient) { super(http, "/addresses") }242  get(id: string, o?: Opts): Promise<Address> {243    return this.req({ method: "GET", path: `/addresses/${enc(id)}` }, o)244  }245  /** Alias kinds are removed. A mailbox (scope `mail.admin`) is detached unless `purgeAllMail` is true, which destroys the account and all its mail. */246  delete(id: string, params: { purgeAllMail?: boolean } = {}, o?: Opts): Promise<{ ok: boolean; purged: boolean }> {247    return params.purgeAllMail248      ? this.req({ method: "DELETE", path: `/addresses/${enc(id)}`, query: { purge: "delete-all-mail" }, body: { confirm: "delete-all-mail" } }, o)249      : this.req({ method: "DELETE", path: `/addresses/${enc(id)}` }, o)250  }251  /** Filters, auto-reply and forwarding of a physical mailbox (`id` = its primary address). */252  getAutomation(id: string, o?: Opts): Promise<Automation> {253    return this.req({ method: "GET", path: `/addresses/${enc(id)}/automation` }, o)254  }255  updateAutomation(id: string, params: AutomationUpdateParams, o?: Opts): Promise<Automation> {256    return this.req({ method: "PUT", path: `/addresses/${enc(id)}/automation`, body: params }, o)257  }258}259class Aliases extends AddressBase {260  constructor(http: HttpClient) { super(http, "/aliases") }261  delete(id: string, o?: Opts): Promise<{ ok: boolean; purged: boolean }> {262    return this.req({ method: "DELETE", path: `/aliases/${enc(id)}` }, o)263  }264}265266class WebhookDeliveries extends Resource {267  /** Delivery attempts of one webhook, newest first. */268  list(webhookId: string, params: WebhookDeliveryListParams = {}, o?: Opts): Promise<Page<WebhookDelivery>> {269    return this.req({ method: "GET", path: `/webhooks/${enc(webhookId)}/deliveries`, query: params }, o)270  }271  iterate(webhookId: string, params: WebhookDeliveryListParams = {}, o?: Opts): AsyncGenerator<WebhookDelivery, void, undefined> {272    return paginate((p) => this.list(webhookId, p, o), params)273  }274  /** Queues a delivery again (same event id, new timestamp and signature). */275  replay(deliveryId: string, o?: Opts): Promise<WebhookDelivery> {276    return this.req({ method: "POST", path: `/webhook-deliveries/${enc(deliveryId)}/replay` }, o)277  }278}279class Webhooks extends Resource {280  readonly deliveries = new WebhookDeliveries(this.http)281  /** The answer carries `secret` (`whsec_…`) — shown ONCE: store it now. */282  create(params: WebhookCreateParams, o?: Opts): Promise<Webhook> {283    return this.req({ method: "POST", path: "/webhooks", body: params, idempotent: true }, o)284  }285  list(o?: Opts): Promise<Webhook[]> {286    return this.req<{ data: Webhook[] }>({ method: "GET", path: "/webhooks" }, o).then((r) => r.data)287  }288  get(id: string, o?: Opts): Promise<Webhook> {289    return this.req({ method: "GET", path: `/webhooks/${enc(id)}` }, o)290  }291  /** `rotate_secret: true` returns the new secret once. */292  update(id: string, params: WebhookUpdateParams, o?: Opts): Promise<Webhook> {293    return this.req({ method: "PATCH", path: `/webhooks/${enc(id)}`, body: params }, o)294  }295  delete(id: string, o?: Opts): Promise<{ ok: boolean }> {296    return this.req({ method: "DELETE", path: `/webhooks/${enc(id)}` }, o)297  }298  /** Sends a signed `webhook.test` event now. */299  test(id: string, o?: Opts): Promise<WebhookTestResult> {300    return this.req({ method: "POST", path: `/webhooks/${enc(id)}/test` }, o)301  }302  /** Shortcut for `deliveries.replay`. */303  replay(deliveryId: string, o?: Opts): Promise<WebhookDelivery> {304    return this.deliveries.replay(deliveryId, o)305  }306  /** Verifies `SPMail-Signature` over the RAW body (WebCrypto; constant-time; replay window). Resolves to a boolean. */307  verifySignature(params: VerifySignatureParams): Promise<boolean> {308    return verifyWebhookSignature(params)309  }310  /** Verifies the signature and returns the parsed event; throws SignatureVerificationError otherwise. */311  constructEvent(params: VerifySignatureParams): Promise<WebhookEvent> {312    return constructWebhookEvent(params)313  }314  /** Builds a valid header for tests of your own receiver. */315  sign(params: { payload: string | Uint8Array | ArrayBuffer; secret: string; timestamp?: number }): Promise<string> {316    return signWebhookPayload(params)317  }318}319320class Events extends Resource {321  /** Recent events visible to the key, newest first, metadata only, kept 30 days. */322  list(params: EventListParams = {}, o?: Opts): Promise<Page<Event>> {323    return this.req({ method: "GET", path: "/events", query: params }, o)324  }325  iterate(params: EventListParams = {}, o?: Opts): AsyncGenerator<Event, void, undefined> {326    return paginate((p) => this.list(p, o), params)327  }328}329330class Templates extends Resource {331  /** Templates of the library of the user who owns the key (without HTML). */332  list(o?: Opts): Promise<TemplateSummary[]> {333    return this.req<{ templates: TemplateSummary[] }>({ method: "GET", path: "/templates" }, o).then((r) => r.templates)334  }335  get(id: string, o?: Opts): Promise<Template> {336    return this.req({ method: "GET", path: `/templates/${enc(id)}` }, o)337  }338  /** Renders without sending; `missing` lists the required variables that were not supplied. */339  render(id: string, params: TemplateRenderParams = {}, o?: Opts): Promise<RenderedTemplate> {340    return this.req({ method: "POST", path: `/templates/${enc(id)}/render`, body: params, repeatable: true }, o)341  }342}343344/** Client of the SP Mail REST API. */345export class SPMail {346  readonly #http: HttpClient347  readonly messages: Messages348  readonly threads: Threads349  readonly drafts: Drafts350  readonly folders: Folders351  readonly files: Files352  readonly addresses: Addresses353  readonly aliases: Aliases354  readonly webhooks: Webhooks355  readonly events: Events356  readonly templates: Templates357358  constructor(options: SPMailOptions) {359    const http = new HttpClient(options)360    this.#http = http361    this.messages = new Messages(http)362    this.threads = new Threads(http)363    this.drafts = new Drafts(http)364    this.folders = new Folders(http)365    this.files = new Files(http)366    this.addresses = new Addresses(http)367    this.aliases = new Aliases(http)368    this.webhooks = new Webhooks(http)369    this.events = new Events(http)370    this.templates = new Templates(http)371  }372  /** Base URL in use, ending with `/api/v1`. */373  get baseUrl(): string {374    return this.#http.baseUrl375  }376  /** Who am I: scopes, usable addresses (with `read: full|restricted|none`), limits, today's usage. */377  me(o?: Opts): Promise<Me> {378    return this.#http.request({ method: "GET", path: "/me", ...(o ?? {}) })379  }380  /** Public health probe. Throws a ServerError (503) when the instance is not healthy. */381  health(o?: Opts): Promise<Health> {382    return this.#http.request({ method: "GET", path: "/health", anonymous: true, ...(o ?? {}) })383  }384  /** Shortcut for `messages.waitForDelivery`. */385  waitForDelivery(outboundId: string, opts?: WaitForDeliveryOptions): Promise<OutboundMessage> {386    return this.messages.waitForDelivery(outboundId, opts)387  }388  /** Escape hatch for an endpoint the SDK does not wrap yet. `path` is relative to `/api/v1`. */389  request<T = unknown>(method: InternalRequest["method"], path: string, init: { query?: Record<string, unknown>; body?: unknown; idempotent?: boolean } & Opts = {}): Promise<T> {390    return this.#http.request<T>({ method, path: path.startsWith("/") ? path : `/${path}`, ...init })391  }392  toJSON(): { baseUrl: string } {393    return { baseUrl: this.baseUrl }394  }395}396397export type { Messages, Threads, Drafts, Folders, Files, Addresses, Aliases, Webhooks, Events, Templates, Outbound, Scheduled, Attachments, WebhookDeliveries }398
Files main
Menu

Theme