SPB Git

Repository Public

client.ts 8.1 KB 173 lines typescript

1// Client JMAP d'une boîte SP Mail : session, requêtes groupées avec références de résultat, téléversement, téléchargement.2import { HttpError, JmapMethodError, JmapSetError, NetworkError } from "./errors"3import { api, request, sessionLost, setUnauthorizedHandler } from "./http"4import { CAP, type Id, type Invocation, type MethodArgs, type MethodName, type MethodResponse, type ResultReference, type Session, type SetError } from "./types"56export { setUnauthorizedHandler }78const DEFAULT_USING = [CAP.core, CAP.mail, CAP.submission]9const MAX_CALLS = 16 // limite de la passerelle1011/** Résultat différé d'un appel dans un lot : lisible après `Batch.send()`. */12export class Call<M extends MethodName> {13  private settled?: { ok: true; value: MethodResponse<M> } | { ok: false; error: JmapMethodError }14  /** réponses implicites supplémentaires portant le même identifiant d'appel (ex. Email/set après EmailSubmission/set) */15  extra: Invocation[] = []16  constructor(17    public readonly name: M,18    public readonly id: string,19  ) {}20  /** Référence vers un chemin du résultat de cet appel, utilisable dans un appel suivant du même lot. */21  ref(path: string): ResultReference {22    return { resultOf: this.id, name: this.name, path }23  }24  /** @internal */25  settle(inv: Invocation | undefined) {26    if (!inv) this.settled = { ok: false, error: new JmapMethodError(this.name, "noResponse") }27    else if (inv[0] === "error") {28      const e = inv[1] as { type?: string; description?: string }29      this.settled = { ok: false, error: new JmapMethodError(this.name, String(e.type ?? "serverFail"), e.description) }30    } else this.settled = { ok: true, value: inv[1] as unknown as MethodResponse<M> }31  }32  get error(): JmapMethodError | null {33    return this.settled && !this.settled.ok ? this.settled.error : null34  }35  /** La réponse, ou lève l'erreur de méthode. */36  get result(): MethodResponse<M> {37    if (!this.settled) throw new Error(`${this.name}: batch not sent`)38    if (!this.settled.ok) throw this.settled.error39    return this.settled.value40  }41}4243export class Batch {44  private calls: { call: Call<MethodName>; args: Record<string, unknown> }[] = []45  private using = new Set<string>(DEFAULT_USING)46  constructor(private client: JmapClient) {}47  /** Ajoute un appel ; `accountId` est renseigné automatiquement. */48  add<M extends MethodName>(name: M, args: MethodArgs<M>, capability?: string): Call<M> {49    if (this.calls.length >= MAX_CALLS) throw new Error("too many calls in one JMAP request")50    const call = new Call(name, `c${this.calls.length}`)51    this.calls.push({ call: call as unknown as Call<MethodName>, args: { accountId: this.client.accountId, ...(args as Record<string, unknown>) } })52    if (capability) this.using.add(capability)53    return call54  }55  get size() {56    return this.calls.length57  }58  async send(signal?: AbortSignal): Promise<void> {59    if (!this.calls.length) return60    const methodCalls: Invocation[] = this.calls.map(({ call, args }) => [call.name, args, call.id])61    const responses = await this.client.raw([...this.using], methodCalls, signal)62    for (const { call } of this.calls) {63      const mine = responses.filter((r) => r[2] === call.id)64      call.settle(mine.find((r) => r[0] === call.name || r[0] === "error"))65      call.extra = mine.filter((r) => r[0] !== call.name && r[0] !== "error")66    }67  }68}6970export interface UploadResult {71  accountId: Id72  blobId: Id73  type: string74  size: number75}7677export class JmapClient {78  session!: Session79  accountId: Id = ""80  constructor(public readonly mailboxId: string) {}81  private get base() {82    return `/api/jmap/${this.mailboxId}`83  }8485  async connect(signal?: AbortSignal): Promise<Session> {86    this.session = await api<Session>(`${this.base}/session`, { signal })87    const acct = this.session.primaryAccounts[CAP.mail]88    if (!acct) throw new HttpError(502, "mail_server_error", "no mail account in session")89    this.accountId = acct90    return this.session91  }9293  batch(): Batch {94    return new Batch(this)95  }9697  /** Un seul appel ; lève JmapMethodError si la méthode échoue. */98  async call<M extends MethodName>(name: M, args: MethodArgs<M>, capability?: string, signal?: AbortSignal): Promise<MethodResponse<M>> {99    const b = this.batch()100    const c = b.add(name, args, capability)101    await b.send(signal)102    return c.result103  }104105  /** @internal Envoi brut d'une requête JMAP. */106  async raw(using: string[], methodCalls: Invocation[], signal?: AbortSignal): Promise<Invocation[]> {107    const r = await api<{ methodResponses?: Invocation[]; type?: string; detail?: string }>(`${this.base}/api`, { method: "POST", json: { using, methodCalls }, signal })108    if (!Array.isArray(r.methodResponses)) throw new HttpError(502, "mail_server_error", r.detail ?? r.type ?? "malformed JMAP response")109    return r.methodResponses110  }111112  /** URL de téléchargement par la passerelle. Toujours servie en pièce jointe, sauf `inline` pour png/jpeg/gif/webp. */113  downloadUrl(blobId: Id, name: string, type: string, inline = false): string {114    const safe = name.replace(/[/\\?#%]/g, "_").slice(0, 150) || "fichier"115    return `${this.base}/download/${encodeURIComponent(this.accountId)}/${encodeURIComponent(blobId)}/${encodeURIComponent(safe)}?accept=${encodeURIComponent(type || "application/octet-stream")}${inline ? "&inline=1" : ""}`116  }117118  async downloadBytes(blobId: Id, type = "application/octet-stream", signal?: AbortSignal): Promise<Uint8Array> {119    const r = await request(this.downloadUrl(blobId, "blob", type), { signal, headers: { accept: "*/*" } })120    return new Uint8Array(await r.arrayBuffer())121  }122  async downloadText(blobId: Id, type = "text/plain", signal?: AbortSignal): Promise<string> {123    return new TextDecoder().decode(await this.downloadBytes(blobId, type, signal))124  }125126  /** Téléversement avec progression (XMLHttpRequest : fetch n'expose pas l'avancement de l'envoi). */127  upload(data: Blob, type: string, onProgress?: (loaded: number, total: number) => void, signal?: AbortSignal): Promise<UploadResult> {128    return new Promise((resolve, reject) => {129      const xhr = new XMLHttpRequest()130      xhr.open("POST", `${this.base}/upload/${encodeURIComponent(this.accountId)}/`)131      // Toujours « application/octet-stream » : la passerelle ne relaie en flux que les types qu'elle n'interprète pas132      // (text/plain et application/json y sont analysés par Fastify → 500). Le vrai type voyage dans Email/set.133      void type134      xhr.setRequestHeader("content-type", "application/octet-stream")135      xhr.setRequestHeader("x-spmail", "1")136      xhr.responseType = "json"137      xhr.upload.onprogress = (e) => {138        if (e.lengthComputable) onProgress?.(e.loaded, e.total)139      }140      xhr.onerror = () => reject(new NetworkError())141      xhr.onabort = () => reject(new DOMException("aborted", "AbortError"))142      xhr.onload = () => {143        const body = xhr.response as (UploadResult & { error?: string; message?: string }) | null144        if (xhr.status >= 200 && xhr.status < 300 && body?.blobId) resolve(body)145        else {146          if (xhr.status === 401) sessionLost(body?.error ?? "")147          reject(new HttpError(xhr.status, body?.error ?? `http_${xhr.status}`, body?.message))148        }149      }150      signal?.addEventListener("abort", () => xhr.abort(), { once: true })151      xhr.send(data)152    })153  }154155  eventSourceUrl(): string {156    return `${this.base}/eventsource?types=*&closeafter=no&ping=30`157  }158}159160/** @internal relié par l'état de l'application (même gestionnaire pour fetch et pour le téléversement). */161export function bindUnauthorized(fn: () => void) {162  setUnauthorizedHandler(fn)163}164165/** Lève JmapSetError si l'objet `key` figure dans notCreated / notUpdated / notDestroyed. */166export function assertSet(method: string, res: { notCreated?: Record<string, SetError> | null; notUpdated?: Record<string, SetError> | null; notDestroyed?: Record<string, SetError> | null }, key?: string): void {167  for (const bucket of [res.notCreated, res.notUpdated, res.notDestroyed]) {168    if (!bucket) continue169    const k = key !== undefined ? (key in bucket ? key : undefined) : Object.keys(bucket)[0]170    if (k !== undefined) throw new JmapSetError(method, bucket[k])171  }172}173
Files main
Menu

Theme