@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.
@@ -0,0 +1,410 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/playwright.ts
21
+ var playwright_exports = {};
22
+ __export(playwright_exports, {
23
+ PlaywrightInbox: () => PlaywrightInbox,
24
+ expect: () => import_test2.expect,
25
+ mailpierFixtures: () => mailpierFixtures,
26
+ test: () => test
27
+ });
28
+ module.exports = __toCommonJS(playwright_exports);
29
+ var import_test = require("@playwright/test");
30
+
31
+ // src/errors.ts
32
+ var MailPierInboxError = class extends Error {
33
+ status;
34
+ /** Set on 429: seconds to wait before the next call. */
35
+ retryAfterSeconds;
36
+ constructor(status, message, retryAfterSeconds) {
37
+ super(message);
38
+ this.name = "MailPierInboxError";
39
+ this.status = status;
40
+ this.retryAfterSeconds = retryAfterSeconds;
41
+ }
42
+ };
43
+ var MailPierTimeoutError = class extends Error {
44
+ address;
45
+ timeoutMs;
46
+ constructor(address, timeoutMs, subjectContains) {
47
+ super(`No mail to ${address}${subjectContains ? ` with "${subjectContains}" in the subject` : ""} arrived within ${Math.round(timeoutMs / 1e3)} seconds.`);
48
+ this.name = "MailPierTimeoutError";
49
+ this.address = address;
50
+ this.timeoutMs = timeoutMs;
51
+ }
52
+ };
53
+
54
+ // src/message.ts
55
+ var InboxMessage = class {
56
+ id;
57
+ receivedUtc;
58
+ from;
59
+ to = [];
60
+ subject;
61
+ sizeBytes = 0;
62
+ hasAttachments = false;
63
+ text;
64
+ html;
65
+ headers;
66
+ links = [];
67
+ codes = [];
68
+ attachments = [];
69
+ auth;
70
+ spam;
71
+ constructor(data) {
72
+ Object.assign(this, data);
73
+ this.to = Array.isArray(data.to) ? data.to : [];
74
+ this.links = Array.isArray(data.links) ? data.links.filter((l) => l && typeof l.href === "string") : [];
75
+ this.codes = normaliseCodes(data.codes);
76
+ this.attachments = Array.isArray(data.attachments) ? data.attachments : [];
77
+ }
78
+ /** The first one-time code in the mail (best guess first), or undefined when it has none. */
79
+ get code() {
80
+ return this.codes[0];
81
+ }
82
+ /**
83
+ * The first link whose address (or text) contains `contains` (case-insensitive), or the first link when it is omitted;
84
+ * undefined when none matches.
85
+ */
86
+ firstLink(contains) {
87
+ if (contains === void 0 || contains === null || contains === "") return this.links[0]?.href;
88
+ const needle = contains.toLowerCase();
89
+ return this.links.find((l) => l.href.toLowerCase().includes(needle) || (l.text ?? "").toLowerCase().includes(needle))?.href;
90
+ }
91
+ /** The plain JSON (what the API returned), e.g. to pass through a Cypress task. */
92
+ toJSON() {
93
+ const { ...plain } = this;
94
+ return { ...plain, code: this.code };
95
+ }
96
+ };
97
+ function normaliseCodes(codes) {
98
+ if (!Array.isArray(codes)) return [];
99
+ const out = [];
100
+ for (const c of codes) {
101
+ if (typeof c === "string" && c.length > 0) out.push(c);
102
+ else if (c && typeof c === "object") {
103
+ for (const k of ["value", "code", "Value", "Code"]) {
104
+ const v = c[k];
105
+ if (typeof v === "string" && v.length > 0) {
106
+ out.push(v);
107
+ break;
108
+ }
109
+ }
110
+ }
111
+ }
112
+ return out;
113
+ }
114
+
115
+ // src/client.ts
116
+ var DEFAULT_BASE_URL = "https://api.mailpier.io";
117
+ var MAX_POLL_SECONDS = 120;
118
+ var VERSION = "0.1.0";
119
+ var sleep = (ms, signal) => new Promise((resolve, reject) => {
120
+ if (signal?.aborted) return reject(signal.reason);
121
+ const t = setTimeout(() => {
122
+ signal?.removeEventListener("abort", onAbort);
123
+ resolve();
124
+ }, ms);
125
+ const onAbort = () => {
126
+ clearTimeout(t);
127
+ reject(signal.reason);
128
+ };
129
+ signal?.addEventListener("abort", onAbort, { once: true });
130
+ });
131
+ function iso(t) {
132
+ if (t === void 0) return void 0;
133
+ return typeof t === "string" ? t : t.toISOString();
134
+ }
135
+ function env(name) {
136
+ const p = globalThis.process;
137
+ const v = p?.env?.[name];
138
+ return v && v.trim() ? v.trim() : void 0;
139
+ }
140
+ var MailPierInbox = class {
141
+ baseUrl;
142
+ apiKey;
143
+ maxRetries;
144
+ maxRetryDelayMs;
145
+ fetchImpl;
146
+ constructor(options = {}) {
147
+ const key = (options.apiKey ?? env("MAILPIER_API_KEY") ?? "").trim();
148
+ if (!key) throw new Error("An API key (mpi_...) is required: pass { apiKey } or set MAILPIER_API_KEY.");
149
+ this.apiKey = key;
150
+ this.baseUrl = (options.baseUrl ?? env("MAILPIER_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
151
+ this.maxRetries = Math.max(0, options.maxRetries ?? 5);
152
+ this.maxRetryDelayMs = Math.max(0, options.maxRetryDelayMs ?? 6e4);
153
+ const f = options.fetch ?? globalThis.fetch;
154
+ if (!f) throw new Error("No fetch available: use Node 18 or later, or pass { fetch }.");
155
+ this.fetchImpl = f;
156
+ }
157
+ /** A fresh random address of the key's environment, e.g. `signup-k3v9q2mz7a@qa.acme.mailpier.io`. */
158
+ async newAddress(options = {}) {
159
+ const body = {};
160
+ if (options.domain) body.domain = options.domain;
161
+ if (options.prefix) body.prefix = options.prefix;
162
+ const resp = await this.request("POST", "/v1/addresses", {}, { body: JSON.stringify(body) });
163
+ const json = await resp.json();
164
+ if (!json?.address) throw new MailPierInboxError(resp.status, "The server returned no address.");
165
+ return json.address;
166
+ }
167
+ /**
168
+ * Waits until a mail to `to` arrives and returns it (the OLDEST match received at or after `since`).
169
+ * Throws MailPierTimeoutError when nothing arrives within `timeoutMs`.
170
+ */
171
+ async waitForMessage(options) {
172
+ const to = options.to?.trim();
173
+ if (!to) throw new Error("waitForMessage needs { to: address }.");
174
+ const timeoutMs = options.timeoutMs ?? 6e4;
175
+ if (!(timeoutMs > 0)) throw new Error("timeoutMs must be greater than 0.");
176
+ const deadline = Date.now() + timeoutMs;
177
+ const since = iso(options.since);
178
+ for (; ; ) {
179
+ const left = deadline - Date.now();
180
+ const seconds = Math.min(Math.max(Math.ceil(left / 1e3), 1), MAX_POLL_SECONDS);
181
+ const resp = await this.request("GET", "/v1/messages/wait", {
182
+ to,
183
+ subject: options.subjectContains,
184
+ since,
185
+ afterId: since ? options.afterId : void 0,
186
+ timeoutSeconds: seconds
187
+ }, { signal: options.signal, timeoutMs: (seconds + 30) * 1e3 });
188
+ if (resp.status !== 204) return new InboxMessage(await resp.json());
189
+ if (Date.now() >= deadline) throw new MailPierTimeoutError(to, timeoutMs, options.subjectContains);
190
+ }
191
+ }
192
+ /**
193
+ * Waits for the next mail to `to` after `previous` (one you already received): passes its receivedUtc as `since` and its id as
194
+ * `afterId`, so a mail stored in the same millisecond is not missed and `previous` itself is never returned again.
195
+ */
196
+ waitForNextMessage(previous, options) {
197
+ return this.waitForMessage({ ...options, since: previous.receivedUtc, afterId: previous.id });
198
+ }
199
+ /** Mail of the environment, newest first (at most 100 per call). */
200
+ async listMessages(options = {}) {
201
+ const since = iso(options.since);
202
+ const resp = await this.request("GET", "/v1/messages", {
203
+ to: options.to,
204
+ subject: options.subjectContains,
205
+ since,
206
+ afterId: since ? options.afterId : void 0,
207
+ take: options.take ?? 50,
208
+ skip: options.skip ?? 0
209
+ }, { signal: options.signal });
210
+ const json = await resp.json();
211
+ return json?.items ?? [];
212
+ }
213
+ /** One mail with its text, HTML, headers, links, codes and attachment list; null when it does not exist (or expired). */
214
+ async getMessage(id) {
215
+ const resp = await this.request("GET", `/v1/messages/${encodeURIComponent(id)}`, {}, { allow404: true });
216
+ if (resp.status === 404) return null;
217
+ return new InboxMessage(await resp.json());
218
+ }
219
+ /** The original message (.eml bytes); null when it does not exist. */
220
+ getRaw(id) {
221
+ return this.download(`/v1/messages/${encodeURIComponent(id)}/raw`);
222
+ }
223
+ /** One attachment's bytes; null when it does not exist. */
224
+ getAttachment(id, index) {
225
+ return this.download(`/v1/messages/${encodeURIComponent(id)}/attachments/${index}`);
226
+ }
227
+ /** Deletes one mail. False when it did not exist. Throws (409) when the mail was also sent outside this environment. */
228
+ async deleteMessage(id) {
229
+ const resp = await this.request("DELETE", `/v1/messages/${encodeURIComponent(id)}`, {}, { allow404: true });
230
+ return resp.status !== 404;
231
+ }
232
+ /** Deletes every mail to one address; returns how many were deleted. */
233
+ async deleteAll(to) {
234
+ return (await this.deleteAllDetailed(to)).deleted;
235
+ }
236
+ /** Like deleteAll, but also says how many shared mails were skipped. */
237
+ async deleteAllDetailed(to) {
238
+ if (!to?.trim()) throw new Error("deleteAll needs the address.");
239
+ const resp = await this.request("DELETE", "/v1/messages", { to: to.trim() });
240
+ const json = await resp.json();
241
+ return { deleted: json?.deleted ?? 0, skippedShared: json?.skippedShared ?? 0 };
242
+ }
243
+ /** The key's account, environment, domains, plan and usage (GET /v1/me). */
244
+ async me() {
245
+ const resp = await this.request("GET", "/v1/me", {});
246
+ return await resp.json();
247
+ }
248
+ // ------------------------------------------------------------------ plumbing
249
+ async download(path) {
250
+ const resp = await this.request("GET", path, {}, { allow404: true, accept: "*/*" });
251
+ if (resp.status === 404) return null;
252
+ return new Uint8Array(await resp.arrayBuffer());
253
+ }
254
+ url(path, query) {
255
+ const q = new URLSearchParams();
256
+ for (const [k, v] of Object.entries(query)) if (v !== void 0 && v !== null && v !== "") q.set(k, String(v));
257
+ const s = q.toString();
258
+ return `${this.baseUrl}${path}${s ? `?${s}` : ""}`;
259
+ }
260
+ /**
261
+ * 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
262
+ * (both capped at maxRetryDelayMs). Other errors throw MailPierInboxError with the server's {"error": "..."} text.
263
+ */
264
+ async request(method, path, query, o = {}) {
265
+ const url = this.url(path, query);
266
+ const headers = {
267
+ Authorization: `Bearer ${this.apiKey}`,
268
+ Accept: o.accept ?? "application/json",
269
+ "User-Agent": `mailpier-inbox-node/${VERSION}`
270
+ };
271
+ if (o.body !== void 0) headers["Content-Type"] = "application/json";
272
+ for (let attempt = 0; ; attempt++) {
273
+ const ctl = new AbortController();
274
+ const timer = setTimeout(
275
+ () => ctl.abort(new Error(`No answer within ${Math.round((o.timeoutMs ?? 6e4) / 1e3)} s.`)),
276
+ o.timeoutMs ?? 6e4
277
+ );
278
+ const onAbort = () => ctl.abort(o.signal.reason);
279
+ if (o.signal?.aborted) onAbort();
280
+ else o.signal?.addEventListener("abort", onAbort, { once: true });
281
+ let resp;
282
+ try {
283
+ resp = await this.fetchImpl(url, { method, headers, body: o.body, signal: ctl.signal });
284
+ } catch (err) {
285
+ clearTimeout(timer);
286
+ o.signal?.removeEventListener("abort", onAbort);
287
+ if (o.signal?.aborted) throw err;
288
+ if (attempt >= this.maxRetries) {
289
+ throw new MailPierInboxError(0, `Could not reach MailPier Inbox at ${this.baseUrl}: ${err instanceof Error ? err.message : String(err)}`);
290
+ }
291
+ await sleep(this.backoff(attempt), o.signal);
292
+ continue;
293
+ }
294
+ clearTimeout(timer);
295
+ o.signal?.removeEventListener("abort", onAbort);
296
+ if (resp.ok || o.allow404 && resp.status === 404) return resp;
297
+ const message = await errorText(resp);
298
+ if (resp.status === 429) {
299
+ const retryAfter = parseRetryAfter(resp.headers.get("Retry-After"));
300
+ if (attempt < this.maxRetries) {
301
+ await sleep(Math.min((retryAfter ?? 1) * 1e3, this.maxRetryDelayMs), o.signal);
302
+ continue;
303
+ }
304
+ throw new MailPierInboxError(429, message ?? "Too many requests.", retryAfter);
305
+ }
306
+ if ((resp.status === 502 || resp.status === 503 || resp.status === 504) && attempt < this.maxRetries) {
307
+ await sleep(this.backoff(attempt), o.signal);
308
+ continue;
309
+ }
310
+ throw new MailPierInboxError(resp.status, message ?? `MailPier Inbox answered ${resp.status}.`);
311
+ }
312
+ }
313
+ backoff(attempt) {
314
+ return Math.min(500 * 2 ** attempt, this.maxRetryDelayMs);
315
+ }
316
+ };
317
+ async function errorText(resp) {
318
+ try {
319
+ const text = await resp.text();
320
+ if (!text) return void 0;
321
+ try {
322
+ const e = JSON.parse(text).error;
323
+ return typeof e === "string" && e ? `${e} (HTTP ${resp.status})` : void 0;
324
+ } catch {
325
+ return void 0;
326
+ }
327
+ } catch {
328
+ return void 0;
329
+ }
330
+ }
331
+ function parseRetryAfter(v) {
332
+ if (!v) return void 0;
333
+ const n = Number.parseInt(v, 10);
334
+ if (Number.isFinite(n) && n >= 0) return n;
335
+ const t = Date.parse(v);
336
+ return Number.isFinite(t) ? Math.max(0, Math.ceil((t - Date.now()) / 1e3)) : void 0;
337
+ }
338
+
339
+ // src/inboxSession.ts
340
+ var PlaywrightInbox = class {
341
+ /** The underlying client, for anything else (listMessages, getRaw, getAttachment ...). */
342
+ client;
343
+ created = /* @__PURE__ */ new Map();
344
+ lastSeen = /* @__PURE__ */ new Map();
345
+ constructor(client) {
346
+ this.client = client;
347
+ }
348
+ /** A fresh address of the key's environment. */
349
+ async newAddress(options = {}) {
350
+ const started = new Date(Date.now() - 1e3);
351
+ const address = await this.client.newAddress(options);
352
+ this.created.set(address.toLowerCase(), started);
353
+ return address;
354
+ }
355
+ /**
356
+ * Waits for the next mail to `address`: the first call returns the first mail since newAddress(), each later call the mail
357
+ * after the one returned before.
358
+ */
359
+ async waitForMessage(address, options = {}) {
360
+ const key = address.toLowerCase();
361
+ const previous = this.lastSeen.get(key);
362
+ const message = previous ? await this.client.waitForNextMessage(previous, { to: address, ...options }) : await this.client.waitForMessage({ to: address, since: this.created.get(key), ...options });
363
+ this.lastSeen.set(key, message);
364
+ return message;
365
+ }
366
+ /** Waits for the next mail to `address` and returns its one-time code; throws when the mail has none. */
367
+ async waitForCode(address, options = {}) {
368
+ const m = await this.waitForMessage(address, options);
369
+ if (!m.code) throw new Error(`The mail "${m.subject ?? ""}" to ${address} holds no one-time code.`);
370
+ return m.code;
371
+ }
372
+ /** Waits for the next mail to `address` and returns its first link containing `contains` (any link when omitted). */
373
+ async waitForLink(address, contains, options = {}) {
374
+ const m = await this.waitForMessage(address, options);
375
+ const link = m.firstLink(contains);
376
+ if (!link) throw new Error(`The mail "${m.subject ?? ""}" to ${address} holds no link${contains ? ` containing "${contains}"` : ""}.`);
377
+ return link;
378
+ }
379
+ /** Addresses handed out by this fixture instance. */
380
+ get addresses() {
381
+ return [...this.created.keys()];
382
+ }
383
+ };
384
+
385
+ // src/playwright.ts
386
+ var import_test2 = require("@playwright/test");
387
+ var mailpierFixtures = {
388
+ mailpierOptions: [{}, { option: true }],
389
+ mailpierCleanup: [false, { option: true }],
390
+ inbox: async ({ mailpierOptions, mailpierCleanup }, use) => {
391
+ const inbox = new PlaywrightInbox(new MailPierInbox(mailpierOptions));
392
+ await use(inbox);
393
+ if (mailpierCleanup) {
394
+ for (const a of inbox.addresses) {
395
+ try {
396
+ await inbox.client.deleteAll(a);
397
+ } catch {
398
+ }
399
+ }
400
+ }
401
+ }
402
+ };
403
+ var test = import_test.test.extend(mailpierFixtures);
404
+ // Annotate the CommonJS export names for ESM import in node:
405
+ 0 && (module.exports = {
406
+ PlaywrightInbox,
407
+ expect,
408
+ mailpierFixtures,
409
+ test
410
+ });
@@ -0,0 +1,50 @@
1
+ import * as _playwright_test from '@playwright/test';
2
+ import { Fixtures, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions } from '@playwright/test';
3
+ export { expect } from '@playwright/test';
4
+ import { MailPierInbox, NewAddressOptions, InboxMessage, MailPierInboxOptions } from './index.cjs';
5
+
6
+ interface InboxWaitOptions {
7
+ /** Only a mail whose subject contains this (case-insensitive). */
8
+ subjectContains?: string;
9
+ /** Default 60000. */
10
+ timeoutMs?: number;
11
+ }
12
+ /**
13
+ * The `inbox` fixture. Every address it hands out remembers when it was made, so a wait only returns mail sent after that
14
+ * (an old mail to a reused address is never picked up by mistake).
15
+ */
16
+ declare class PlaywrightInbox {
17
+ /** The underlying client, for anything else (listMessages, getRaw, getAttachment ...). */
18
+ readonly client: MailPierInbox;
19
+ private readonly created;
20
+ private readonly lastSeen;
21
+ constructor(client: MailPierInbox);
22
+ /** A fresh address of the key's environment. */
23
+ newAddress(options?: NewAddressOptions): Promise<string>;
24
+ /**
25
+ * Waits for the next mail to `address`: the first call returns the first mail since newAddress(), each later call the mail
26
+ * after the one returned before.
27
+ */
28
+ waitForMessage(address: string, options?: InboxWaitOptions): Promise<InboxMessage>;
29
+ /** Waits for the next mail to `address` and returns its one-time code; throws when the mail has none. */
30
+ waitForCode(address: string, options?: InboxWaitOptions): Promise<string>;
31
+ /** Waits for the next mail to `address` and returns its first link containing `contains` (any link when omitted). */
32
+ waitForLink(address: string, contains?: string, options?: InboxWaitOptions): Promise<string>;
33
+ /** Addresses handed out by this fixture instance. */
34
+ get addresses(): string[];
35
+ }
36
+
37
+ interface MailPierFixtures {
38
+ inbox: PlaywrightInbox;
39
+ /** Client options (apiKey, baseUrl ...); default from MAILPIER_API_KEY / MAILPIER_BASE_URL. Set with test.use(). */
40
+ mailpierOptions: MailPierInboxOptions;
41
+ /** Delete the mail of every address the test created when it ends. Default false. */
42
+ mailpierCleanup: boolean;
43
+ }
44
+ /** The fixtures, to merge into your own test: `base.extend<MailPierFixtures>(mailpierFixtures)`. */
45
+ declare const mailpierFixtures: Fixtures<MailPierFixtures, object, PlaywrightTestArgs & PlaywrightTestOptions, PlaywrightWorkerArgs & PlaywrightWorkerOptions>;
46
+ /** Playwright's `test` with the `inbox` fixture. */
47
+ declare const test: _playwright_test.TestType<PlaywrightTestArgs & PlaywrightTestOptions & MailPierFixtures, PlaywrightWorkerArgs & PlaywrightWorkerOptions>;
48
+
49
+ export { PlaywrightInbox, mailpierFixtures, test };
50
+ export type { InboxWaitOptions, MailPierFixtures };
@@ -0,0 +1,50 @@
1
+ import * as _playwright_test from '@playwright/test';
2
+ import { Fixtures, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions } from '@playwright/test';
3
+ export { expect } from '@playwright/test';
4
+ import { MailPierInbox, NewAddressOptions, InboxMessage, MailPierInboxOptions } from './index.js';
5
+
6
+ interface InboxWaitOptions {
7
+ /** Only a mail whose subject contains this (case-insensitive). */
8
+ subjectContains?: string;
9
+ /** Default 60000. */
10
+ timeoutMs?: number;
11
+ }
12
+ /**
13
+ * The `inbox` fixture. Every address it hands out remembers when it was made, so a wait only returns mail sent after that
14
+ * (an old mail to a reused address is never picked up by mistake).
15
+ */
16
+ declare class PlaywrightInbox {
17
+ /** The underlying client, for anything else (listMessages, getRaw, getAttachment ...). */
18
+ readonly client: MailPierInbox;
19
+ private readonly created;
20
+ private readonly lastSeen;
21
+ constructor(client: MailPierInbox);
22
+ /** A fresh address of the key's environment. */
23
+ newAddress(options?: NewAddressOptions): Promise<string>;
24
+ /**
25
+ * Waits for the next mail to `address`: the first call returns the first mail since newAddress(), each later call the mail
26
+ * after the one returned before.
27
+ */
28
+ waitForMessage(address: string, options?: InboxWaitOptions): Promise<InboxMessage>;
29
+ /** Waits for the next mail to `address` and returns its one-time code; throws when the mail has none. */
30
+ waitForCode(address: string, options?: InboxWaitOptions): Promise<string>;
31
+ /** Waits for the next mail to `address` and returns its first link containing `contains` (any link when omitted). */
32
+ waitForLink(address: string, contains?: string, options?: InboxWaitOptions): Promise<string>;
33
+ /** Addresses handed out by this fixture instance. */
34
+ get addresses(): string[];
35
+ }
36
+
37
+ interface MailPierFixtures {
38
+ inbox: PlaywrightInbox;
39
+ /** Client options (apiKey, baseUrl ...); default from MAILPIER_API_KEY / MAILPIER_BASE_URL. Set with test.use(). */
40
+ mailpierOptions: MailPierInboxOptions;
41
+ /** Delete the mail of every address the test created when it ends. Default false. */
42
+ mailpierCleanup: boolean;
43
+ }
44
+ /** The fixtures, to merge into your own test: `base.extend<MailPierFixtures>(mailpierFixtures)`. */
45
+ declare const mailpierFixtures: Fixtures<MailPierFixtures, object, PlaywrightTestArgs & PlaywrightTestOptions, PlaywrightWorkerArgs & PlaywrightWorkerOptions>;
46
+ /** Playwright's `test` with the `inbox` fixture. */
47
+ declare const test: _playwright_test.TestType<PlaywrightTestArgs & PlaywrightTestOptions & MailPierFixtures, PlaywrightWorkerArgs & PlaywrightWorkerOptions>;
48
+
49
+ export { PlaywrightInbox, mailpierFixtures, test };
50
+ export type { InboxWaitOptions, MailPierFixtures };
@@ -0,0 +1,78 @@
1
+ import {
2
+ MailPierInbox
3
+ } from "./chunk-FR6JEAV7.js";
4
+
5
+ // src/playwright.ts
6
+ import { test as base } from "@playwright/test";
7
+
8
+ // src/inboxSession.ts
9
+ var PlaywrightInbox = class {
10
+ /** The underlying client, for anything else (listMessages, getRaw, getAttachment ...). */
11
+ client;
12
+ created = /* @__PURE__ */ new Map();
13
+ lastSeen = /* @__PURE__ */ new Map();
14
+ constructor(client) {
15
+ this.client = client;
16
+ }
17
+ /** A fresh address of the key's environment. */
18
+ async newAddress(options = {}) {
19
+ const started = new Date(Date.now() - 1e3);
20
+ const address = await this.client.newAddress(options);
21
+ this.created.set(address.toLowerCase(), started);
22
+ return address;
23
+ }
24
+ /**
25
+ * Waits for the next mail to `address`: the first call returns the first mail since newAddress(), each later call the mail
26
+ * after the one returned before.
27
+ */
28
+ async waitForMessage(address, options = {}) {
29
+ const key = address.toLowerCase();
30
+ const previous = this.lastSeen.get(key);
31
+ const message = previous ? await this.client.waitForNextMessage(previous, { to: address, ...options }) : await this.client.waitForMessage({ to: address, since: this.created.get(key), ...options });
32
+ this.lastSeen.set(key, message);
33
+ return message;
34
+ }
35
+ /** Waits for the next mail to `address` and returns its one-time code; throws when the mail has none. */
36
+ async waitForCode(address, options = {}) {
37
+ const m = await this.waitForMessage(address, options);
38
+ if (!m.code) throw new Error(`The mail "${m.subject ?? ""}" to ${address} holds no one-time code.`);
39
+ return m.code;
40
+ }
41
+ /** Waits for the next mail to `address` and returns its first link containing `contains` (any link when omitted). */
42
+ async waitForLink(address, contains, options = {}) {
43
+ const m = await this.waitForMessage(address, options);
44
+ const link = m.firstLink(contains);
45
+ if (!link) throw new Error(`The mail "${m.subject ?? ""}" to ${address} holds no link${contains ? ` containing "${contains}"` : ""}.`);
46
+ return link;
47
+ }
48
+ /** Addresses handed out by this fixture instance. */
49
+ get addresses() {
50
+ return [...this.created.keys()];
51
+ }
52
+ };
53
+
54
+ // src/playwright.ts
55
+ import { expect } from "@playwright/test";
56
+ var mailpierFixtures = {
57
+ mailpierOptions: [{}, { option: true }],
58
+ mailpierCleanup: [false, { option: true }],
59
+ inbox: async ({ mailpierOptions, mailpierCleanup }, use) => {
60
+ const inbox = new PlaywrightInbox(new MailPierInbox(mailpierOptions));
61
+ await use(inbox);
62
+ if (mailpierCleanup) {
63
+ for (const a of inbox.addresses) {
64
+ try {
65
+ await inbox.client.deleteAll(a);
66
+ } catch {
67
+ }
68
+ }
69
+ }
70
+ }
71
+ };
72
+ var test = base.extend(mailpierFixtures);
73
+ export {
74
+ PlaywrightInbox,
75
+ expect,
76
+ mailpierFixtures,
77
+ test
78
+ };