@mailpier/inbox 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (unreleased)
4
+ - First version: `MailPierInbox` (newAddress, waitForMessage, waitForNextMessage, listMessages, getMessage, getRaw,
5
+ getAttachment, deleteMessage, deleteAll, me), `message.code` / `message.firstLink()`, retries on 429 (Retry-After) and
6
+ 502/503/504/network errors, ESM + CJS builds with types.
7
+ - `@mailpier/inbox/playwright`: `test`/`expect` with the `inbox` fixture (newAddress, waitForMessage, waitForCode, waitForLink).
8
+ - `@mailpier/inbox/cypress` (`mailpierTasks`) and `@mailpier/inbox/cypress/commands` (`cy.mailpier*`).
9
+ - `@mailpier/inbox/testing`: in-process fake MailPier Inbox API.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Solutions Group Unlimited
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,100 @@
1
- # Temporary Holding Version
1
+ # @mailpier/inbox
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node.js client for [MailPier Inbox](https://mailpier.io): give each test its own email address, wait for the mail your app
4
+ sends, and read its one-time code and links. TypeScript types, ESM and CommonJS, Node 18+, no runtime dependencies.
5
+ Includes a **Playwright fixture**, **Cypress commands** and a **fake MailPier API** for offline tests.
6
+
7
+ ## Quick start
8
+
9
+ ```ts
10
+ import { MailPierInbox } from "@mailpier/inbox";
11
+ const inbox = new MailPierInbox({ apiKey: process.env.MAILPIER_API_KEY });
12
+ const address = await inbox.newAddress({ prefix: "signup" }); // signup-k3v9q2mz7a@qa.acme.mailpier.io
13
+ await signUp(address); // your app sends the mail
14
+ const mail = await inbox.waitForMessage({ to: address, subjectContains: "Confirm", timeoutMs: 60_000 });
15
+ console.log(mail.code, mail.firstLink("verify")); // "482913", "https://app.example.com/verify?t=..."
16
+ ```
17
+
18
+ Create the API key on your environment's **API keys** page and keep it in a secret (`MAILPIER_API_KEY`).
19
+
20
+ ## API
21
+
22
+ | Call | What it does |
23
+ |---|---|
24
+ | `new MailPierInbox({ apiKey?, baseUrl?, maxRetries?, maxRetryDelayMs?, fetch? })` | `apiKey` defaults to `MAILPIER_API_KEY`, `baseUrl` to `MAILPIER_BASE_URL` or `https://api.mailpier.io`. |
25
+ | `newAddress({ prefix?, domain? })` | A fresh random address of the key's environment. |
26
+ | `waitForMessage({ to, subjectContains?, timeoutMs?, since?, afterId?, signal? })` | The **oldest** matching mail received at or after `since`; long-polls (120 s per poll); throws `MailPierTimeoutError`. |
27
+ | `waitForNextMessage(previous, { to, ... })` | The mail after `previous` (never `previous` again, even in the same millisecond). |
28
+ | `listMessages({ to?, subjectContains?, since?, take?, skip? })` | Newest first, at most 100 per call. |
29
+ | `getMessage(id)` / `getRaw(id)` / `getAttachment(id, index)` | Full mail / `.eml` bytes / attachment bytes; `null` when gone. |
30
+ | `deleteMessage(id)` / `deleteAll(to)` | Clean up after a test. |
31
+ | `message.code` / `message.firstLink(contains?)` | The first one-time code; the first link whose URL or text contains `contains`. |
32
+
33
+ Errors throw `MailPierInboxError` with `status` (400, 401 bad key, 403 suspended, 404, 409, 429, 503; 0 = unreachable) and the
34
+ server's message. **429** is retried after `Retry-After`, **502/503/504** and network errors with backoff (0.5, 1, 2 ... s),
35
+ up to `maxRetries` (5) times; other errors are not retried.
36
+
37
+ ## Playwright
38
+
39
+ ```ts
40
+ import { test, expect } from "@mailpier/inbox/playwright"; // Playwright's test + an `inbox` fixture
41
+
42
+ test("sign up", async ({ page, inbox }) => {
43
+ const email = await inbox.newAddress();
44
+ await page.getByLabel("Email").fill(email);
45
+ await page.getByRole("button", { name: "Create account" }).click();
46
+ await page.getByLabel("Code").fill(await inbox.waitForCode(email));
47
+ // or: await page.goto(await inbox.waitForLink(email, "verify"));
48
+ });
49
+ ```
50
+
51
+ The key comes from `MAILPIER_API_KEY` (or `test.use({ mailpierOptions: { apiKey } })`). Each wait returns the **next** mail to that
52
+ address since `newAddress()`. `test.use({ mailpierCleanup: true })` deletes the test's mail afterwards. To merge into your own
53
+ fixtures: `base.extend<MailPierFixtures>(mailpierFixtures)`. Example: `playwright/signup.spec.ts` (runs against a local demo app
54
+ and the fake API: `npm run build && npm run test:e2e`).
55
+
56
+ ## Cypress
57
+
58
+ ```ts
59
+ // cypress.config.ts
60
+ import { mailpierTasks } from "@mailpier/inbox/cypress";
61
+ export default defineConfig({ e2e: { setupNodeEvents(on) { on("task", mailpierTasks()); } } });
62
+
63
+ // cypress/support/e2e.ts
64
+ import "@mailpier/inbox/cypress/commands";
65
+
66
+ // a spec
67
+ cy.mailpierNewAddress().then((email) => {
68
+ cy.get("input[name=email]").type(email);
69
+ cy.contains("button", "Create account").click();
70
+ cy.mailpierWaitForCode(email).then((code) => cy.get("input[name=code]").type(code));
71
+ });
72
+ ```
73
+
74
+ Commands: `cy.mailpierNewAddress({prefix?, domain?})`, `cy.mailpierWaitForMessage(to, {subjectContains?, timeoutMs?})` (yields
75
+ the message JSON plus `code` and `firstLink`), `cy.mailpierWaitForCode(to)`, `cy.mailpierWaitForLink(to, contains?)`,
76
+ `cy.mailpierDeleteAll(to)`. The API key stays in the Cypress Node process (`MAILPIER_API_KEY`); it never reaches the browser.
77
+ Example: `cypress/`.
78
+
79
+ ## Offline tests: the fake API
80
+
81
+ ```ts
82
+ import { startFakeMailPier } from "@mailpier/inbox/testing";
83
+ const fake = await startFakeMailPier(); // 127.0.0.1, key "mpi_test_key", zone qa.demo.mailpier.io
84
+ const inbox = new MailPierInbox({ apiKey: fake.apiKey, baseUrl: fake.url });
85
+ fake.deliver({ to: address, subject: "Confirm", text: "Your code is 482913" }); // what MailPier would have received
86
+ await fake.close();
87
+ ```
88
+
89
+ It implements every public endpoint with the real JSON shapes and errors, extracts links and 4-8 digit codes like the service,
90
+ and can simulate failures (`fake.failNext({ status: 429, retryAfter: 1 })`). `POST /_fake/deliver` lets another process add mail.
91
+
92
+ ## Develop
93
+
94
+ `npm install`, `npm run typecheck`, `npm run build`, `npm test` (vitest), `npm run test:e2e` (Playwright; `PW_CHANNEL=msedge`
95
+ uses an installed Edge). `..\test-all.ps1` runs everything.
96
+
97
+ Mail is kept for the environment's retention period (15 minutes to 24 hours) and permanently deleted when the retention period ends. The message `html` is as received and NOT
98
+ sanitised: never render it in a page of your own origin.
99
+
100
+ License: MIT.
@@ -0,0 +1,317 @@
1
+ // src/errors.ts
2
+ var MailPierInboxError = class extends Error {
3
+ status;
4
+ /** Set on 429: seconds to wait before the next call. */
5
+ retryAfterSeconds;
6
+ constructor(status, message, retryAfterSeconds) {
7
+ super(message);
8
+ this.name = "MailPierInboxError";
9
+ this.status = status;
10
+ this.retryAfterSeconds = retryAfterSeconds;
11
+ }
12
+ };
13
+ var MailPierTimeoutError = class extends Error {
14
+ address;
15
+ timeoutMs;
16
+ constructor(address, timeoutMs, subjectContains) {
17
+ super(`No mail to ${address}${subjectContains ? ` with "${subjectContains}" in the subject` : ""} arrived within ${Math.round(timeoutMs / 1e3)} seconds.`);
18
+ this.name = "MailPierTimeoutError";
19
+ this.address = address;
20
+ this.timeoutMs = timeoutMs;
21
+ }
22
+ };
23
+
24
+ // src/message.ts
25
+ var InboxMessage = class {
26
+ id;
27
+ receivedUtc;
28
+ from;
29
+ to = [];
30
+ subject;
31
+ sizeBytes = 0;
32
+ hasAttachments = false;
33
+ text;
34
+ html;
35
+ headers;
36
+ links = [];
37
+ codes = [];
38
+ attachments = [];
39
+ auth;
40
+ spam;
41
+ constructor(data) {
42
+ Object.assign(this, data);
43
+ this.to = Array.isArray(data.to) ? data.to : [];
44
+ this.links = Array.isArray(data.links) ? data.links.filter((l) => l && typeof l.href === "string") : [];
45
+ this.codes = normaliseCodes(data.codes);
46
+ this.attachments = Array.isArray(data.attachments) ? data.attachments : [];
47
+ }
48
+ /** The first one-time code in the mail (best guess first), or undefined when it has none. */
49
+ get code() {
50
+ return this.codes[0];
51
+ }
52
+ /**
53
+ * The first link whose address (or text) contains `contains` (case-insensitive), or the first link when it is omitted;
54
+ * undefined when none matches.
55
+ */
56
+ firstLink(contains) {
57
+ if (contains === void 0 || contains === null || contains === "") return this.links[0]?.href;
58
+ const needle = contains.toLowerCase();
59
+ return this.links.find((l) => l.href.toLowerCase().includes(needle) || (l.text ?? "").toLowerCase().includes(needle))?.href;
60
+ }
61
+ /** The plain JSON (what the API returned), e.g. to pass through a Cypress task. */
62
+ toJSON() {
63
+ const { ...plain } = this;
64
+ return { ...plain, code: this.code };
65
+ }
66
+ };
67
+ function normaliseCodes(codes) {
68
+ if (!Array.isArray(codes)) return [];
69
+ const out = [];
70
+ for (const c of codes) {
71
+ if (typeof c === "string" && c.length > 0) out.push(c);
72
+ else if (c && typeof c === "object") {
73
+ for (const k of ["value", "code", "Value", "Code"]) {
74
+ const v = c[k];
75
+ if (typeof v === "string" && v.length > 0) {
76
+ out.push(v);
77
+ break;
78
+ }
79
+ }
80
+ }
81
+ }
82
+ return out;
83
+ }
84
+
85
+ // src/client.ts
86
+ var DEFAULT_BASE_URL = "https://api.mailpier.io";
87
+ var MAX_POLL_SECONDS = 120;
88
+ var VERSION = "0.1.0";
89
+ var sleep = (ms, signal) => new Promise((resolve, reject) => {
90
+ if (signal?.aborted) return reject(signal.reason);
91
+ const t = setTimeout(() => {
92
+ signal?.removeEventListener("abort", onAbort);
93
+ resolve();
94
+ }, ms);
95
+ const onAbort = () => {
96
+ clearTimeout(t);
97
+ reject(signal.reason);
98
+ };
99
+ signal?.addEventListener("abort", onAbort, { once: true });
100
+ });
101
+ function iso(t) {
102
+ if (t === void 0) return void 0;
103
+ return typeof t === "string" ? t : t.toISOString();
104
+ }
105
+ function env(name) {
106
+ const p = globalThis.process;
107
+ const v = p?.env?.[name];
108
+ return v && v.trim() ? v.trim() : void 0;
109
+ }
110
+ var MailPierInbox = class {
111
+ baseUrl;
112
+ apiKey;
113
+ maxRetries;
114
+ maxRetryDelayMs;
115
+ fetchImpl;
116
+ constructor(options = {}) {
117
+ const key = (options.apiKey ?? env("MAILPIER_API_KEY") ?? "").trim();
118
+ if (!key) throw new Error("An API key (mpi_...) is required: pass { apiKey } or set MAILPIER_API_KEY.");
119
+ this.apiKey = key;
120
+ this.baseUrl = (options.baseUrl ?? env("MAILPIER_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
121
+ this.maxRetries = Math.max(0, options.maxRetries ?? 5);
122
+ this.maxRetryDelayMs = Math.max(0, options.maxRetryDelayMs ?? 6e4);
123
+ const f = options.fetch ?? globalThis.fetch;
124
+ if (!f) throw new Error("No fetch available: use Node 18 or later, or pass { fetch }.");
125
+ this.fetchImpl = f;
126
+ }
127
+ /** A fresh random address of the key's environment, e.g. `signup-k3v9q2mz7a@qa.acme.mailpier.io`. */
128
+ async newAddress(options = {}) {
129
+ const body = {};
130
+ if (options.domain) body.domain = options.domain;
131
+ if (options.prefix) body.prefix = options.prefix;
132
+ const resp = await this.request("POST", "/v1/addresses", {}, { body: JSON.stringify(body) });
133
+ const json = await resp.json();
134
+ if (!json?.address) throw new MailPierInboxError(resp.status, "The server returned no address.");
135
+ return json.address;
136
+ }
137
+ /**
138
+ * Waits until a mail to `to` arrives and returns it (the OLDEST match received at or after `since`).
139
+ * Throws MailPierTimeoutError when nothing arrives within `timeoutMs`.
140
+ */
141
+ async waitForMessage(options) {
142
+ const to = options.to?.trim();
143
+ if (!to) throw new Error("waitForMessage needs { to: address }.");
144
+ const timeoutMs = options.timeoutMs ?? 6e4;
145
+ if (!(timeoutMs > 0)) throw new Error("timeoutMs must be greater than 0.");
146
+ const deadline = Date.now() + timeoutMs;
147
+ const since = iso(options.since);
148
+ for (; ; ) {
149
+ const left = deadline - Date.now();
150
+ const seconds = Math.min(Math.max(Math.ceil(left / 1e3), 1), MAX_POLL_SECONDS);
151
+ const resp = await this.request("GET", "/v1/messages/wait", {
152
+ to,
153
+ subject: options.subjectContains,
154
+ since,
155
+ afterId: since ? options.afterId : void 0,
156
+ timeoutSeconds: seconds
157
+ }, { signal: options.signal, timeoutMs: (seconds + 30) * 1e3 });
158
+ if (resp.status !== 204) return new InboxMessage(await resp.json());
159
+ if (Date.now() >= deadline) throw new MailPierTimeoutError(to, timeoutMs, options.subjectContains);
160
+ }
161
+ }
162
+ /**
163
+ * Waits for the next mail to `to` after `previous` (one you already received): passes its receivedUtc as `since` and its id as
164
+ * `afterId`, so a mail stored in the same millisecond is not missed and `previous` itself is never returned again.
165
+ */
166
+ waitForNextMessage(previous, options) {
167
+ return this.waitForMessage({ ...options, since: previous.receivedUtc, afterId: previous.id });
168
+ }
169
+ /** Mail of the environment, newest first (at most 100 per call). */
170
+ async listMessages(options = {}) {
171
+ const since = iso(options.since);
172
+ const resp = await this.request("GET", "/v1/messages", {
173
+ to: options.to,
174
+ subject: options.subjectContains,
175
+ since,
176
+ afterId: since ? options.afterId : void 0,
177
+ take: options.take ?? 50,
178
+ skip: options.skip ?? 0
179
+ }, { signal: options.signal });
180
+ const json = await resp.json();
181
+ return json?.items ?? [];
182
+ }
183
+ /** One mail with its text, HTML, headers, links, codes and attachment list; null when it does not exist (or expired). */
184
+ async getMessage(id) {
185
+ const resp = await this.request("GET", `/v1/messages/${encodeURIComponent(id)}`, {}, { allow404: true });
186
+ if (resp.status === 404) return null;
187
+ return new InboxMessage(await resp.json());
188
+ }
189
+ /** The original message (.eml bytes); null when it does not exist. */
190
+ getRaw(id) {
191
+ return this.download(`/v1/messages/${encodeURIComponent(id)}/raw`);
192
+ }
193
+ /** One attachment's bytes; null when it does not exist. */
194
+ getAttachment(id, index) {
195
+ return this.download(`/v1/messages/${encodeURIComponent(id)}/attachments/${index}`);
196
+ }
197
+ /** Deletes one mail. False when it did not exist. Throws (409) when the mail was also sent outside this environment. */
198
+ async deleteMessage(id) {
199
+ const resp = await this.request("DELETE", `/v1/messages/${encodeURIComponent(id)}`, {}, { allow404: true });
200
+ return resp.status !== 404;
201
+ }
202
+ /** Deletes every mail to one address; returns how many were deleted. */
203
+ async deleteAll(to) {
204
+ return (await this.deleteAllDetailed(to)).deleted;
205
+ }
206
+ /** Like deleteAll, but also says how many shared mails were skipped. */
207
+ async deleteAllDetailed(to) {
208
+ if (!to?.trim()) throw new Error("deleteAll needs the address.");
209
+ const resp = await this.request("DELETE", "/v1/messages", { to: to.trim() });
210
+ const json = await resp.json();
211
+ return { deleted: json?.deleted ?? 0, skippedShared: json?.skippedShared ?? 0 };
212
+ }
213
+ /** The key's account, environment, domains, plan and usage (GET /v1/me). */
214
+ async me() {
215
+ const resp = await this.request("GET", "/v1/me", {});
216
+ return await resp.json();
217
+ }
218
+ // ------------------------------------------------------------------ plumbing
219
+ async download(path) {
220
+ const resp = await this.request("GET", path, {}, { allow404: true, accept: "*/*" });
221
+ if (resp.status === 404) return null;
222
+ return new Uint8Array(await resp.arrayBuffer());
223
+ }
224
+ url(path, query) {
225
+ const q = new URLSearchParams();
226
+ for (const [k, v] of Object.entries(query)) if (v !== void 0 && v !== null && v !== "") q.set(k, String(v));
227
+ const s = q.toString();
228
+ return `${this.baseUrl}${path}${s ? `?${s}` : ""}`;
229
+ }
230
+ /**
231
+ * One call with retries: 429 waits Retry-After (default 1 s), 502/503/504 and network errors back off 0.5, 1, 2, 4 ... s
232
+ * (both capped at maxRetryDelayMs). Other errors throw MailPierInboxError with the server's {"error": "..."} text.
233
+ */
234
+ async request(method, path, query, o = {}) {
235
+ const url = this.url(path, query);
236
+ const headers = {
237
+ Authorization: `Bearer ${this.apiKey}`,
238
+ Accept: o.accept ?? "application/json",
239
+ "User-Agent": `mailpier-inbox-node/${VERSION}`
240
+ };
241
+ if (o.body !== void 0) headers["Content-Type"] = "application/json";
242
+ for (let attempt = 0; ; attempt++) {
243
+ const ctl = new AbortController();
244
+ const timer = setTimeout(
245
+ () => ctl.abort(new Error(`No answer within ${Math.round((o.timeoutMs ?? 6e4) / 1e3)} s.`)),
246
+ o.timeoutMs ?? 6e4
247
+ );
248
+ const onAbort = () => ctl.abort(o.signal.reason);
249
+ if (o.signal?.aborted) onAbort();
250
+ else o.signal?.addEventListener("abort", onAbort, { once: true });
251
+ let resp;
252
+ try {
253
+ resp = await this.fetchImpl(url, { method, headers, body: o.body, signal: ctl.signal });
254
+ } catch (err) {
255
+ clearTimeout(timer);
256
+ o.signal?.removeEventListener("abort", onAbort);
257
+ if (o.signal?.aborted) throw err;
258
+ if (attempt >= this.maxRetries) {
259
+ throw new MailPierInboxError(0, `Could not reach MailPier Inbox at ${this.baseUrl}: ${err instanceof Error ? err.message : String(err)}`);
260
+ }
261
+ await sleep(this.backoff(attempt), o.signal);
262
+ continue;
263
+ }
264
+ clearTimeout(timer);
265
+ o.signal?.removeEventListener("abort", onAbort);
266
+ if (resp.ok || o.allow404 && resp.status === 404) return resp;
267
+ const message = await errorText(resp);
268
+ if (resp.status === 429) {
269
+ const retryAfter = parseRetryAfter(resp.headers.get("Retry-After"));
270
+ if (attempt < this.maxRetries) {
271
+ await sleep(Math.min((retryAfter ?? 1) * 1e3, this.maxRetryDelayMs), o.signal);
272
+ continue;
273
+ }
274
+ throw new MailPierInboxError(429, message ?? "Too many requests.", retryAfter);
275
+ }
276
+ if ((resp.status === 502 || resp.status === 503 || resp.status === 504) && attempt < this.maxRetries) {
277
+ await sleep(this.backoff(attempt), o.signal);
278
+ continue;
279
+ }
280
+ throw new MailPierInboxError(resp.status, message ?? `MailPier Inbox answered ${resp.status}.`);
281
+ }
282
+ }
283
+ backoff(attempt) {
284
+ return Math.min(500 * 2 ** attempt, this.maxRetryDelayMs);
285
+ }
286
+ };
287
+ async function errorText(resp) {
288
+ try {
289
+ const text = await resp.text();
290
+ if (!text) return void 0;
291
+ try {
292
+ const e = JSON.parse(text).error;
293
+ return typeof e === "string" && e ? `${e} (HTTP ${resp.status})` : void 0;
294
+ } catch {
295
+ return void 0;
296
+ }
297
+ } catch {
298
+ return void 0;
299
+ }
300
+ }
301
+ function parseRetryAfter(v) {
302
+ if (!v) return void 0;
303
+ const n = Number.parseInt(v, 10);
304
+ if (Number.isFinite(n) && n >= 0) return n;
305
+ const t = Date.parse(v);
306
+ return Number.isFinite(t) ? Math.max(0, Math.ceil((t - Date.now()) / 1e3)) : void 0;
307
+ }
308
+
309
+ export {
310
+ MailPierInboxError,
311
+ MailPierTimeoutError,
312
+ InboxMessage,
313
+ DEFAULT_BASE_URL,
314
+ MAX_POLL_SECONDS,
315
+ VERSION,
316
+ MailPierInbox
317
+ };
@@ -0,0 +1,194 @@
1
+ /** A mailbox from a header: display name (may be null) and address. */
2
+ interface InboxAddress {
3
+ name?: string | null;
4
+ address: string;
5
+ }
6
+ /** The parsed headers (what the sender wrote). */
7
+ interface InboxHeaders {
8
+ from?: InboxAddress | null;
9
+ to?: InboxAddress[];
10
+ cc?: InboxAddress[];
11
+ replyTo?: InboxAddress | null;
12
+ subject?: string | null;
13
+ /** The Date header (ISO 8601); null when missing or unreadable. */
14
+ date?: string | null;
15
+ messageId?: string | null;
16
+ }
17
+ interface InboxLink {
18
+ href: string;
19
+ text?: string | null;
20
+ }
21
+ interface InboxAttachment {
22
+ index: number;
23
+ fileName?: string | null;
24
+ contentType?: string | null;
25
+ size: number;
26
+ }
27
+ /** A mail as the list call returns it. `to` holds the environment's own (envelope) recipients. */
28
+ interface InboxMessageSummary {
29
+ id: string;
30
+ /** ISO 8601, UTC. */
31
+ receivedUtc: string;
32
+ from?: string | null;
33
+ to: string[];
34
+ subject?: string | null;
35
+ sizeBytes: number;
36
+ /** Exact up to 16 KiB, a best guess above; getMessage is exact. */
37
+ hasAttachments: boolean;
38
+ }
39
+ /** The full JSON of GET /v1/messages/{id} and GET /v1/messages/wait. */
40
+ interface InboxMessageData extends InboxMessageSummary {
41
+ text?: string | null;
42
+ /** The HTML part as received, NOT sanitised: never render it in a page of your own origin. */
43
+ html?: string | null;
44
+ headers?: InboxHeaders | null;
45
+ links?: InboxLink[];
46
+ /** One-time codes found in the mail (verification codes, OTPs, PINs), best guess first. */
47
+ codes?: string[];
48
+ attachments?: InboxAttachment[];
49
+ /** Sender authentication verdicts (SPF/DKIM/DMARC) as the server reports them. */
50
+ auth?: unknown;
51
+ /** Spam check result as the server reports it. */
52
+ spam?: unknown;
53
+ }
54
+ /** A full mail with helpers: `message.code` and `message.firstLink("verify")`. */
55
+ declare class InboxMessage implements InboxMessageData {
56
+ id: string;
57
+ receivedUtc: string;
58
+ from?: string | null;
59
+ to: string[];
60
+ subject?: string | null;
61
+ sizeBytes: number;
62
+ hasAttachments: boolean;
63
+ text?: string | null;
64
+ html?: string | null;
65
+ headers?: InboxHeaders | null;
66
+ links: InboxLink[];
67
+ codes: string[];
68
+ attachments: InboxAttachment[];
69
+ auth?: unknown;
70
+ spam?: unknown;
71
+ constructor(data: InboxMessageData);
72
+ /** The first one-time code in the mail (best guess first), or undefined when it has none. */
73
+ get code(): string | undefined;
74
+ /**
75
+ * The first link whose address (or text) contains `contains` (case-insensitive), or the first link when it is omitted;
76
+ * undefined when none matches.
77
+ */
78
+ firstLink(contains?: string): string | undefined;
79
+ /** The plain JSON (what the API returned), e.g. to pass through a Cypress task. */
80
+ toJSON(): InboxMessageData & {
81
+ code?: string;
82
+ };
83
+ }
84
+
85
+ /** The public API. */
86
+ declare const DEFAULT_BASE_URL = "https://api.mailpier.io";
87
+ /** The server caps one long-poll at 120 seconds; longer waits are made of several polls. */
88
+ declare const MAX_POLL_SECONDS = 120;
89
+ declare const VERSION = "0.1.0";
90
+ interface MailPierInboxOptions {
91
+ /** An API key from the environment's API keys page (`mpi_...`). Defaults to the MAILPIER_API_KEY environment variable. */
92
+ apiKey?: string;
93
+ /** API root; defaults to MAILPIER_BASE_URL or https://api.mailpier.io. */
94
+ baseUrl?: string;
95
+ /** How often one call is retried on 429 (after Retry-After), 502/503/504 and network errors. Default 5. */
96
+ maxRetries?: number;
97
+ /** The longest single pause between retries, in ms (Retry-After is honoured up to this). Default 60000. */
98
+ maxRetryDelayMs?: number;
99
+ /** A fetch implementation (default: the global fetch of Node 18+). */
100
+ fetch?: typeof fetch;
101
+ }
102
+ interface NewAddressOptions {
103
+ /** One of the environment's base domains; omitted for its default. */
104
+ domain?: string;
105
+ /** A readable start of the address (a-z, 0-9, '-', at most 30). */
106
+ prefix?: string;
107
+ }
108
+ interface WaitForMessageOptions {
109
+ /** The full address the mail was sent to. */
110
+ to: string;
111
+ /** Only a mail whose subject contains this (case-insensitive). */
112
+ subjectContains?: string;
113
+ /** How long to wait in total, in ms. Default 60000. */
114
+ timeoutMs?: number;
115
+ /** Only a mail received at or after this time. Pass the time your test started to ignore older mail to the same address. */
116
+ since?: Date | string;
117
+ /** Together with `since`: skip this mail id (and the ones stored before it in the same millisecond). */
118
+ afterId?: string;
119
+ signal?: AbortSignal;
120
+ }
121
+ interface ListMessagesOptions {
122
+ to?: string;
123
+ subjectContains?: string;
124
+ since?: Date | string;
125
+ afterId?: string;
126
+ /** 1..100, default 50. */
127
+ take?: number;
128
+ skip?: number;
129
+ signal?: AbortSignal;
130
+ }
131
+ interface DeleteAllResult {
132
+ deleted: number;
133
+ /** Mails that were also sent outside this environment; they expire with the retention period instead. */
134
+ skippedShared: number;
135
+ }
136
+ /**
137
+ * Client for the MailPier Inbox API. Create one per API key and reuse it.
138
+ *
139
+ * ```ts
140
+ * const inbox = new MailPierInbox({ apiKey: process.env.MAILPIER_API_KEY });
141
+ * const address = await inbox.newAddress({ prefix: "signup" });
142
+ * // ... make your app send a mail to address ...
143
+ * const mail = await inbox.waitForMessage({ to: address, subjectContains: "Confirm", timeoutMs: 60_000 });
144
+ * mail.code; // "482913"
145
+ * mail.firstLink("verify"); // "https://app.example.com/verify?t=..."
146
+ * ```
147
+ */
148
+ declare class MailPierInbox {
149
+ readonly baseUrl: string;
150
+ private readonly apiKey;
151
+ private readonly maxRetries;
152
+ private readonly maxRetryDelayMs;
153
+ private readonly fetchImpl;
154
+ constructor(options?: MailPierInboxOptions);
155
+ /** A fresh random address of the key's environment, e.g. `signup-k3v9q2mz7a@qa.acme.mailpier.io`. */
156
+ newAddress(options?: NewAddressOptions): Promise<string>;
157
+ /**
158
+ * Waits until a mail to `to` arrives and returns it (the OLDEST match received at or after `since`).
159
+ * Throws MailPierTimeoutError when nothing arrives within `timeoutMs`.
160
+ */
161
+ waitForMessage(options: WaitForMessageOptions): Promise<InboxMessage>;
162
+ /**
163
+ * Waits for the next mail to `to` after `previous` (one you already received): passes its receivedUtc as `since` and its id as
164
+ * `afterId`, so a mail stored in the same millisecond is not missed and `previous` itself is never returned again.
165
+ */
166
+ waitForNextMessage(previous: Pick<InboxMessageSummary, "id" | "receivedUtc">, options: Omit<WaitForMessageOptions, "since" | "afterId">): Promise<InboxMessage>;
167
+ /** Mail of the environment, newest first (at most 100 per call). */
168
+ listMessages(options?: ListMessagesOptions): Promise<InboxMessageSummary[]>;
169
+ /** One mail with its text, HTML, headers, links, codes and attachment list; null when it does not exist (or expired). */
170
+ getMessage(id: string): Promise<InboxMessage | null>;
171
+ /** The original message (.eml bytes); null when it does not exist. */
172
+ getRaw(id: string): Promise<Uint8Array | null>;
173
+ /** One attachment's bytes; null when it does not exist. */
174
+ getAttachment(id: string, index: number): Promise<Uint8Array | null>;
175
+ /** Deletes one mail. False when it did not exist. Throws (409) when the mail was also sent outside this environment. */
176
+ deleteMessage(id: string): Promise<boolean>;
177
+ /** Deletes every mail to one address; returns how many were deleted. */
178
+ deleteAll(to: string): Promise<number>;
179
+ /** Like deleteAll, but also says how many shared mails were skipped. */
180
+ deleteAllDetailed(to: string): Promise<DeleteAllResult>;
181
+ /** The key's account, environment, domains, plan and usage (GET /v1/me). */
182
+ me(): Promise<Record<string, unknown>>;
183
+ private download;
184
+ private url;
185
+ /**
186
+ * One call with retries: 429 waits Retry-After (default 1 s), 502/503/504 and network errors back off 0.5, 1, 2, 4 ... s
187
+ * (both capped at maxRetryDelayMs). Other errors throw MailPierInboxError with the server's {"error": "..."} text.
188
+ */
189
+ private request;
190
+ private backoff;
191
+ }
192
+
193
+ export { DEFAULT_BASE_URL as D, MAX_POLL_SECONDS as M, VERSION as V, InboxMessage as e, MailPierInbox as h };
194
+ export type { InboxAddress as I, ListMessagesOptions as L, NewAddressOptions as N, WaitForMessageOptions as W, DeleteAllResult as a, InboxAttachment as b, InboxHeaders as c, InboxLink as d, InboxMessageData as f, InboxMessageSummary as g, MailPierInboxOptions as i };