@mailpier/inbox 0.0.0-stage → 0.1.1
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 +24 -0
- package/LICENSE +21 -0
- package/README.md +159 -2
- package/dist/chunk-2NMZ2IWD.js +524 -0
- package/dist/cli.cjs +751 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +244 -0
- package/dist/client-DD8Tr4-3.d.cts +415 -0
- package/dist/client-DD8Tr4-3.d.ts +415 -0
- package/dist/cypress/commands.cjs +94 -0
- package/dist/cypress/commands.d.cts +58 -0
- package/dist/cypress/commands.d.ts +58 -0
- package/dist/cypress/commands.js +68 -0
- package/dist/cypress/index.cjs +575 -0
- package/dist/cypress/index.d.cts +47 -0
- package/dist/cypress/index.d.ts +47 -0
- package/dist/cypress/index.js +40 -0
- package/dist/index.cjs +557 -0
- package/dist/index.d.cts +26 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +22 -0
- package/dist/playwright.cjs +639 -0
- package/dist/playwright.d.cts +65 -0
- package/dist/playwright.d.ts +65 -0
- package/dist/playwright.js +104 -0
- package/dist/testing/index.cjs +683 -0
- package/dist/testing/index.d.cts +106 -0
- package/dist/testing/index.d.ts +106 -0
- package/dist/testing/index.js +654 -0
- package/package.json +112 -4
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// src/cypress/commands.ts
|
|
2
|
+
function pickLink(message, contains) {
|
|
3
|
+
const links = message.links ?? [];
|
|
4
|
+
if (!contains) return links[0]?.href;
|
|
5
|
+
const n = contains.toLowerCase();
|
|
6
|
+
return links.find((l) => l.href.toLowerCase().includes(n) || (l.text ?? "").toLowerCase().includes(n))?.href;
|
|
7
|
+
}
|
|
8
|
+
function registerMailPierCommands(cypress, cyRef) {
|
|
9
|
+
const created = /* @__PURE__ */ new Map();
|
|
10
|
+
const lastSeen = /* @__PURE__ */ new Map();
|
|
11
|
+
const waitArgs = (to, o = {}) => {
|
|
12
|
+
const key = to.toLowerCase();
|
|
13
|
+
const prev = lastSeen.get(key);
|
|
14
|
+
return {
|
|
15
|
+
to,
|
|
16
|
+
subjectContains: o.subjectContains,
|
|
17
|
+
timeoutMs: o.timeoutMs ?? 6e4,
|
|
18
|
+
since: prev?.receivedUtc ?? created.get(key),
|
|
19
|
+
afterId: prev?.id
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
const wait = (to, o = {}) => {
|
|
23
|
+
const args = waitArgs(to, o);
|
|
24
|
+
return cyRef().task("mailpier:waitForMessage", args, { timeout: (args.timeoutMs ?? 6e4) + 15e3 }).then((m) => {
|
|
25
|
+
lastSeen.set(to.toLowerCase(), { receivedUtc: m.receivedUtc, id: m.id });
|
|
26
|
+
return m;
|
|
27
|
+
});
|
|
28
|
+
};
|
|
29
|
+
cypress.Commands.add("mailpierNewAddress", (options) => {
|
|
30
|
+
const started2 = new Date(Date.now() - 1e3).toISOString();
|
|
31
|
+
return cyRef().task("mailpier:newAddress", options ?? null).then((address) => {
|
|
32
|
+
created.set(address.toLowerCase(), started2);
|
|
33
|
+
return address;
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
cypress.Commands.add("mailpierWaitForMessage", (to, options) => wait(to, options));
|
|
37
|
+
cypress.Commands.add("mailpierWaitForCode", (to, options) => wait(to, options).then((m) => {
|
|
38
|
+
if (!m.code) throw new Error(`The mail "${m.subject ?? ""}" to ${to} holds no one-time code.`);
|
|
39
|
+
return m.code;
|
|
40
|
+
}));
|
|
41
|
+
cypress.Commands.add("mailpierWaitForLink", (to, contains, options) => wait(to, options).then((m) => {
|
|
42
|
+
const link = pickLink(m, contains);
|
|
43
|
+
if (!link) throw new Error(`The mail "${m.subject ?? ""}" to ${to} holds no link${contains ? ` containing "${contains}"` : ""}.`);
|
|
44
|
+
return link;
|
|
45
|
+
}));
|
|
46
|
+
cypress.Commands.add("mailpierDeleteAll", (to) => cyRef().task("mailpier:deleteAll", { to }));
|
|
47
|
+
const started = new Date(Date.now() - 1e3).toISOString();
|
|
48
|
+
const lastWebhook = /* @__PURE__ */ new Map();
|
|
49
|
+
cypress.Commands.add("mailpierCreateWebhookUrl", () => cyRef().task("mailpier:createWebhookUrl", null));
|
|
50
|
+
cypress.Commands.add("mailpierWaitForWebhook", (path, options) => {
|
|
51
|
+
const p = path?.trim() ? path.trim().startsWith("/") ? path.trim() : `/${path.trim()}` : "/";
|
|
52
|
+
const method = options?.method?.trim().toUpperCase() || void 0;
|
|
53
|
+
const key = `${method ?? "*"} ${p}`;
|
|
54
|
+
const afterId = lastWebhook.get(key);
|
|
55
|
+
const timeoutSeconds = options?.timeoutSeconds ?? 60;
|
|
56
|
+
const args = afterId !== void 0 ? { path: p, method, timeoutSeconds, afterId } : { path: p, method, timeoutSeconds, since: started };
|
|
57
|
+
return cyRef().task("mailpier:waitForWebhook", args, { timeout: timeoutSeconds * 1e3 + 15e3 }).then((r) => {
|
|
58
|
+
lastWebhook.set(key, r.id);
|
|
59
|
+
return r;
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
var g = globalThis;
|
|
64
|
+
if (g.Cypress?.Commands) registerMailPierCommands(g.Cypress, () => g.cy);
|
|
65
|
+
export {
|
|
66
|
+
pickLink,
|
|
67
|
+
registerMailPierCommands
|
|
68
|
+
};
|
|
@@ -0,0 +1,575 @@
|
|
|
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/cypress/index.ts
|
|
21
|
+
var cypress_exports = {};
|
|
22
|
+
__export(cypress_exports, {
|
|
23
|
+
mailpierTasks: () => mailpierTasks
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(cypress_exports);
|
|
26
|
+
|
|
27
|
+
// src/errors.ts
|
|
28
|
+
var MailPierInboxError = class extends Error {
|
|
29
|
+
status;
|
|
30
|
+
/** Set on 429: seconds to wait before the next call. */
|
|
31
|
+
retryAfterSeconds;
|
|
32
|
+
constructor(status, message, retryAfterSeconds) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.name = "MailPierInboxError";
|
|
35
|
+
this.status = status;
|
|
36
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
var MailPierTimeoutError = class extends Error {
|
|
40
|
+
address;
|
|
41
|
+
timeoutMs;
|
|
42
|
+
constructor(address, timeoutMs, subjectContains) {
|
|
43
|
+
super(`No mail to ${address}${subjectContains ? ` with "${subjectContains}" in the subject` : ""} arrived within ${Math.round(timeoutMs / 1e3)} seconds.`);
|
|
44
|
+
this.name = "MailPierTimeoutError";
|
|
45
|
+
this.address = address;
|
|
46
|
+
this.timeoutMs = timeoutMs;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
var MailPierWebhookTimeoutError = class extends MailPierTimeoutError {
|
|
50
|
+
path;
|
|
51
|
+
method;
|
|
52
|
+
constructor(path, timeoutMs, method) {
|
|
53
|
+
super(path, timeoutMs);
|
|
54
|
+
this.message = `No ${method ? `${method.toUpperCase()} ` : ""}webhook request to ${path} arrived within ${Math.round(timeoutMs / 1e3)} seconds.`;
|
|
55
|
+
this.name = "MailPierWebhookTimeoutError";
|
|
56
|
+
this.path = path;
|
|
57
|
+
this.method = method;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// src/message.ts
|
|
62
|
+
var InboxMessage = class {
|
|
63
|
+
id;
|
|
64
|
+
receivedUtc;
|
|
65
|
+
from;
|
|
66
|
+
to = [];
|
|
67
|
+
subject;
|
|
68
|
+
sizeBytes = 0;
|
|
69
|
+
hasAttachments = false;
|
|
70
|
+
text;
|
|
71
|
+
html;
|
|
72
|
+
headers;
|
|
73
|
+
links = [];
|
|
74
|
+
codes = [];
|
|
75
|
+
attachments = [];
|
|
76
|
+
auth;
|
|
77
|
+
spam;
|
|
78
|
+
constructor(data) {
|
|
79
|
+
Object.assign(this, data);
|
|
80
|
+
this.to = Array.isArray(data.to) ? data.to : [];
|
|
81
|
+
this.links = Array.isArray(data.links) ? data.links.filter((l) => l && typeof l.href === "string") : [];
|
|
82
|
+
this.codes = normaliseCodes(data.codes);
|
|
83
|
+
this.attachments = Array.isArray(data.attachments) ? data.attachments : [];
|
|
84
|
+
}
|
|
85
|
+
/** The first one-time code in the mail (best guess first), or undefined when it has none. */
|
|
86
|
+
get code() {
|
|
87
|
+
return this.codes[0];
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* The first link whose address (or text) contains `contains` (case-insensitive), or the first link when it is omitted;
|
|
91
|
+
* undefined when none matches.
|
|
92
|
+
*/
|
|
93
|
+
firstLink(contains) {
|
|
94
|
+
if (contains === void 0 || contains === null || contains === "") return this.links[0]?.href;
|
|
95
|
+
const needle = contains.toLowerCase();
|
|
96
|
+
return this.links.find((l) => l.href.toLowerCase().includes(needle) || (l.text ?? "").toLowerCase().includes(needle))?.href;
|
|
97
|
+
}
|
|
98
|
+
/** The plain JSON (what the API returned), e.g. to pass through a Cypress task. */
|
|
99
|
+
toJSON() {
|
|
100
|
+
const { ...plain } = this;
|
|
101
|
+
return { ...plain, code: this.code };
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
function normaliseCodes(codes) {
|
|
105
|
+
if (!Array.isArray(codes)) return [];
|
|
106
|
+
const out = [];
|
|
107
|
+
for (const c of codes) {
|
|
108
|
+
if (typeof c === "string" && c.length > 0) out.push(c);
|
|
109
|
+
else if (c && typeof c === "object") {
|
|
110
|
+
for (const k of ["value", "code", "Value", "Code"]) {
|
|
111
|
+
const v = c[k];
|
|
112
|
+
if (typeof v === "string" && v.length > 0) {
|
|
113
|
+
out.push(v);
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// src/webhook.ts
|
|
123
|
+
var WebhookRequest = class {
|
|
124
|
+
id;
|
|
125
|
+
receivedUtc;
|
|
126
|
+
method = "";
|
|
127
|
+
path = "/";
|
|
128
|
+
query;
|
|
129
|
+
contentType;
|
|
130
|
+
size = 0;
|
|
131
|
+
environment;
|
|
132
|
+
status = 0;
|
|
133
|
+
url;
|
|
134
|
+
headers = [];
|
|
135
|
+
body;
|
|
136
|
+
bodyBase64;
|
|
137
|
+
json;
|
|
138
|
+
form;
|
|
139
|
+
sourceIp;
|
|
140
|
+
headersTruncated = false;
|
|
141
|
+
ruleId;
|
|
142
|
+
forwardStatus;
|
|
143
|
+
constructor(data) {
|
|
144
|
+
Object.assign(this, data);
|
|
145
|
+
this.headers = Array.isArray(data.headers) ? data.headers.filter((h) => h && typeof h.name === "string").map((h) => ({ name: h.name, value: String(h.value ?? "") })) : [];
|
|
146
|
+
this.headersTruncated = data.headersTruncated === true;
|
|
147
|
+
}
|
|
148
|
+
/** The first value of a header (name case-insensitive), or undefined when the request has none. */
|
|
149
|
+
header(name) {
|
|
150
|
+
const n = name.toLowerCase();
|
|
151
|
+
return this.headers.find((h) => h.name.toLowerCase() === n)?.value;
|
|
152
|
+
}
|
|
153
|
+
/** The body bytes (from `body` or `bodyBase64`); empty when the request had no body. */
|
|
154
|
+
bytes() {
|
|
155
|
+
if (typeof this.bodyBase64 === "string" && this.bodyBase64) {
|
|
156
|
+
const bin = atob(this.bodyBase64);
|
|
157
|
+
const out = new Uint8Array(bin.length);
|
|
158
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
161
|
+
return new TextEncoder().encode(this.body ?? "");
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* The body as JSON: the server's parsed `json`, or the text body parsed here (a JSON body sent with another content type).
|
|
165
|
+
* Throws when the body is not JSON.
|
|
166
|
+
*/
|
|
167
|
+
jsonBody() {
|
|
168
|
+
if (this.json !== void 0 && this.json !== null) return this.json;
|
|
169
|
+
if (typeof this.body === "string" && this.body.trim()) {
|
|
170
|
+
try {
|
|
171
|
+
return JSON.parse(this.body);
|
|
172
|
+
} catch {
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
throw new Error(`The body of ${this.method} ${this.path} (request ${this.id}, ${this.contentType ?? "no content type"}) is not JSON.`);
|
|
176
|
+
}
|
|
177
|
+
/** The plain JSON (what the API returned), e.g. to pass through a Cypress task. */
|
|
178
|
+
toJSON() {
|
|
179
|
+
const { ...plain } = this;
|
|
180
|
+
return plain;
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
// src/client.ts
|
|
185
|
+
var DEFAULT_BASE_URL = "https://api.mailpier.io";
|
|
186
|
+
var MAX_POLL_SECONDS = 120;
|
|
187
|
+
var VERSION = "0.1.1";
|
|
188
|
+
var sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
189
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
190
|
+
const t = setTimeout(() => {
|
|
191
|
+
signal?.removeEventListener("abort", onAbort);
|
|
192
|
+
resolve();
|
|
193
|
+
}, ms);
|
|
194
|
+
const onAbort = () => {
|
|
195
|
+
clearTimeout(t);
|
|
196
|
+
reject(signal.reason);
|
|
197
|
+
};
|
|
198
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
199
|
+
});
|
|
200
|
+
function iso(t) {
|
|
201
|
+
if (t === void 0) return void 0;
|
|
202
|
+
return typeof t === "string" ? t : t.toISOString();
|
|
203
|
+
}
|
|
204
|
+
function env(name) {
|
|
205
|
+
const p = globalThis.process;
|
|
206
|
+
const v = p?.env?.[name];
|
|
207
|
+
return v && v.trim() ? v.trim() : void 0;
|
|
208
|
+
}
|
|
209
|
+
function webhookPath(path) {
|
|
210
|
+
const p = path?.trim();
|
|
211
|
+
if (!p) return void 0;
|
|
212
|
+
return p.startsWith("/") ? p : `/${p}`;
|
|
213
|
+
}
|
|
214
|
+
var MailPierInbox = class {
|
|
215
|
+
baseUrl;
|
|
216
|
+
apiKey;
|
|
217
|
+
maxRetries;
|
|
218
|
+
maxRetryDelayMs;
|
|
219
|
+
fetchImpl;
|
|
220
|
+
constructor(options = {}) {
|
|
221
|
+
const key = (options.apiKey ?? env("MAILPIER_API_KEY") ?? "").trim();
|
|
222
|
+
if (!key) throw new Error("An API key (mpi_...) is required: pass { apiKey } or set MAILPIER_API_KEY.");
|
|
223
|
+
this.apiKey = key;
|
|
224
|
+
this.baseUrl = (options.baseUrl ?? env("MAILPIER_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
225
|
+
this.maxRetries = Math.max(0, options.maxRetries ?? 5);
|
|
226
|
+
this.maxRetryDelayMs = Math.max(0, options.maxRetryDelayMs ?? 6e4);
|
|
227
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
228
|
+
if (!f) throw new Error("No fetch available: use Node 18 or later, or pass { fetch }.");
|
|
229
|
+
this.fetchImpl = f;
|
|
230
|
+
}
|
|
231
|
+
/** A fresh random address of the key's environment, e.g. `signup-k3v9q2mz7a@qa.acme.mailpier.io`. */
|
|
232
|
+
async newAddress(options = {}) {
|
|
233
|
+
const body = {};
|
|
234
|
+
if (options.domain) body.domain = options.domain;
|
|
235
|
+
if (options.prefix) body.prefix = options.prefix;
|
|
236
|
+
const resp = await this.request("POST", "/v1/addresses", {}, { body: JSON.stringify(body) });
|
|
237
|
+
const json = await resp.json();
|
|
238
|
+
if (!json?.address) throw new MailPierInboxError(resp.status, "The server returned no address.");
|
|
239
|
+
return json.address;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Waits until a mail to `to` arrives and returns it (the OLDEST match received at or after `since`).
|
|
243
|
+
* Throws MailPierTimeoutError when nothing arrives within `timeoutMs`.
|
|
244
|
+
*/
|
|
245
|
+
async waitForMessage(options) {
|
|
246
|
+
const to = options.to?.trim();
|
|
247
|
+
if (!to) throw new Error("waitForMessage needs { to: address }.");
|
|
248
|
+
const timeoutMs = options.timeoutMs ?? 6e4;
|
|
249
|
+
if (!(timeoutMs > 0)) throw new Error("timeoutMs must be greater than 0.");
|
|
250
|
+
const deadline = Date.now() + timeoutMs;
|
|
251
|
+
const since = iso(options.since);
|
|
252
|
+
for (; ; ) {
|
|
253
|
+
const left = deadline - Date.now();
|
|
254
|
+
const seconds = Math.min(Math.max(Math.ceil(left / 1e3), 1), MAX_POLL_SECONDS);
|
|
255
|
+
const resp = await this.request("GET", "/v1/messages/wait", {
|
|
256
|
+
to,
|
|
257
|
+
subject: options.subjectContains,
|
|
258
|
+
since,
|
|
259
|
+
afterId: since ? options.afterId : void 0,
|
|
260
|
+
timeoutSeconds: seconds
|
|
261
|
+
}, { signal: options.signal, timeoutMs: (seconds + 30) * 1e3 });
|
|
262
|
+
if (resp.status !== 204) return new InboxMessage(await resp.json());
|
|
263
|
+
if (Date.now() >= deadline) throw new MailPierTimeoutError(to, timeoutMs, options.subjectContains);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Waits for the next mail to `to` after `previous` (one you already received): passes its receivedUtc as `since` and its id as
|
|
268
|
+
* `afterId`, so a mail stored in the same millisecond is not missed and `previous` itself is never returned again.
|
|
269
|
+
*/
|
|
270
|
+
waitForNextMessage(previous, options) {
|
|
271
|
+
return this.waitForMessage({ ...options, since: previous.receivedUtc, afterId: previous.id });
|
|
272
|
+
}
|
|
273
|
+
/** Mail of the environment, newest first (at most 100 per call). */
|
|
274
|
+
async listMessages(options = {}) {
|
|
275
|
+
const since = iso(options.since);
|
|
276
|
+
const resp = await this.request("GET", "/v1/messages", {
|
|
277
|
+
to: options.to,
|
|
278
|
+
subject: options.subjectContains,
|
|
279
|
+
since,
|
|
280
|
+
afterId: since ? options.afterId : void 0,
|
|
281
|
+
take: options.take ?? 50,
|
|
282
|
+
skip: options.skip ?? 0
|
|
283
|
+
}, { signal: options.signal });
|
|
284
|
+
const json = await resp.json();
|
|
285
|
+
return json?.items ?? [];
|
|
286
|
+
}
|
|
287
|
+
/** One mail with its text, HTML, headers, links, codes and attachment list; null when it does not exist (or expired). */
|
|
288
|
+
async getMessage(id) {
|
|
289
|
+
const resp = await this.request("GET", `/v1/messages/${encodeURIComponent(id)}`, {}, { allow404: true });
|
|
290
|
+
if (resp.status === 404) return null;
|
|
291
|
+
return new InboxMessage(await resp.json());
|
|
292
|
+
}
|
|
293
|
+
/** The original message (.eml bytes); null when it does not exist. */
|
|
294
|
+
getRaw(id) {
|
|
295
|
+
return this.download(`/v1/messages/${encodeURIComponent(id)}/raw`);
|
|
296
|
+
}
|
|
297
|
+
/** One attachment's bytes; null when it does not exist. */
|
|
298
|
+
getAttachment(id, index) {
|
|
299
|
+
return this.download(`/v1/messages/${encodeURIComponent(id)}/attachments/${index}`);
|
|
300
|
+
}
|
|
301
|
+
/** Deletes one mail. False when it did not exist. Throws (409) when the mail was also sent outside this environment. */
|
|
302
|
+
async deleteMessage(id) {
|
|
303
|
+
const resp = await this.request("DELETE", `/v1/messages/${encodeURIComponent(id)}`, {}, { allow404: true });
|
|
304
|
+
return resp.status !== 404;
|
|
305
|
+
}
|
|
306
|
+
/** Deletes every mail to one address; returns how many were deleted. */
|
|
307
|
+
async deleteAll(to) {
|
|
308
|
+
return (await this.deleteAllDetailed(to)).deleted;
|
|
309
|
+
}
|
|
310
|
+
/** Like deleteAll, but also says how many shared mails were skipped. */
|
|
311
|
+
async deleteAllDetailed(to) {
|
|
312
|
+
if (!to?.trim()) throw new Error("deleteAll needs the address.");
|
|
313
|
+
const resp = await this.request("DELETE", "/v1/messages", { to: to.trim() });
|
|
314
|
+
const json = await resp.json();
|
|
315
|
+
return { deleted: json?.deleted ?? 0, skippedShared: json?.skippedShared ?? 0 };
|
|
316
|
+
}
|
|
317
|
+
/** The key's account, environment, domains, plan and usage (GET /v1/me). */
|
|
318
|
+
async me() {
|
|
319
|
+
const resp = await this.request("GET", "/v1/me", {});
|
|
320
|
+
return await resp.json();
|
|
321
|
+
}
|
|
322
|
+
// ------------------------------------------------------------------ Webhook inspector (/v1/hooks; 404 while the feature is off)
|
|
323
|
+
/** The environment's catch URL (made on first use), its switches and the plan's webhook limits. */
|
|
324
|
+
async getWebhookEndpoint() {
|
|
325
|
+
const resp = await this.request("GET", "/v1/hooks", {});
|
|
326
|
+
const json = await resp.json();
|
|
327
|
+
if (!json?.url) throw new MailPierInboxError(resp.status, "The server returned no webhook URL.");
|
|
328
|
+
return json;
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* The catch URL with a fresh random path, e.g. `{ url: "https://hook.gather-io.com/<token>/t-8f2k1x", path: "/t-8f2k1x" }`.
|
|
332
|
+
* Give `url` to the app under test and wait with `waitForWebhook({ path })`. Nothing is stored: any path works without this call.
|
|
333
|
+
*/
|
|
334
|
+
async createWebhookUrl() {
|
|
335
|
+
const resp = await this.request("POST", "/v1/hooks/urls", {});
|
|
336
|
+
const json = await resp.json();
|
|
337
|
+
if (!json?.url || !json.path) throw new MailPierInboxError(resp.status, "The server returned no webhook URL.");
|
|
338
|
+
return { url: json.url, path: json.path };
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Waits until a request to the catch URL arrives and returns it: the OLDEST match newer than `afterId` / `since`.
|
|
342
|
+
* Throws MailPierWebhookTimeoutError (a MailPierTimeoutError) when nothing arrives within `timeoutSeconds`.
|
|
343
|
+
*/
|
|
344
|
+
async waitForWebhook(options = {}) {
|
|
345
|
+
const path = webhookPath(options.path);
|
|
346
|
+
const method = options.method?.trim() || void 0;
|
|
347
|
+
const timeoutSeconds = options.timeoutSeconds ?? 60;
|
|
348
|
+
if (!(timeoutSeconds > 0)) throw new Error("timeoutSeconds must be greater than 0.");
|
|
349
|
+
const timeoutMs = timeoutSeconds * 1e3;
|
|
350
|
+
const deadline = Date.now() + timeoutMs;
|
|
351
|
+
const since = iso(options.since);
|
|
352
|
+
for (; ; ) {
|
|
353
|
+
const left = deadline - Date.now();
|
|
354
|
+
const seconds = Math.min(Math.max(Math.ceil(left / 1e3), 1), MAX_POLL_SECONDS);
|
|
355
|
+
const resp = await this.request("GET", "/v1/hooks/requests/wait", {
|
|
356
|
+
path,
|
|
357
|
+
method,
|
|
358
|
+
afterId: options.afterId,
|
|
359
|
+
since,
|
|
360
|
+
timeoutSeconds: seconds
|
|
361
|
+
}, { signal: options.signal, timeoutMs: (seconds + 30) * 1e3 });
|
|
362
|
+
if (resp.status !== 204) return new WebhookRequest(await resp.json());
|
|
363
|
+
if (Date.now() >= deadline) throw new MailPierWebhookTimeoutError(path ?? "/", timeoutMs, method);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
/** Caught requests of the environment, newest first (at most 100 per call). */
|
|
367
|
+
async listWebhooks(options = {}) {
|
|
368
|
+
const resp = await this.request("GET", "/v1/hooks/requests", {
|
|
369
|
+
path: webhookPath(options.path),
|
|
370
|
+
method: options.method?.trim() || void 0,
|
|
371
|
+
afterId: options.afterId,
|
|
372
|
+
since: iso(options.since),
|
|
373
|
+
take: options.take ?? 50,
|
|
374
|
+
skip: options.skip ?? 0
|
|
375
|
+
}, { signal: options.signal });
|
|
376
|
+
const json = await resp.json();
|
|
377
|
+
return json?.items ?? [];
|
|
378
|
+
}
|
|
379
|
+
/** One caught request with headers and body; null when it does not exist (or expired). */
|
|
380
|
+
async getWebhook(id) {
|
|
381
|
+
const resp = await this.request("GET", `/v1/hooks/requests/${encodeURIComponent(String(id))}`, {}, { allow404: true });
|
|
382
|
+
if (resp.status === 404) return null;
|
|
383
|
+
return new WebhookRequest(await resp.json());
|
|
384
|
+
}
|
|
385
|
+
/** The raw body bytes of a caught request; null when it does not exist. */
|
|
386
|
+
getWebhookBody(id) {
|
|
387
|
+
return this.download(`/v1/hooks/requests/${encodeURIComponent(String(id))}/body`);
|
|
388
|
+
}
|
|
389
|
+
/** Deletes one caught request. False when it did not exist. */
|
|
390
|
+
async deleteWebhook(id) {
|
|
391
|
+
const resp = await this.request("DELETE", `/v1/hooks/requests/${encodeURIComponent(String(id))}`, {}, { allow404: true });
|
|
392
|
+
return resp.status !== 404;
|
|
393
|
+
}
|
|
394
|
+
/** Deletes the caught requests whose path starts with `path` (every request of the environment when omitted); returns how many. */
|
|
395
|
+
async deleteWebhooks(options = {}) {
|
|
396
|
+
const resp = await this.request("DELETE", "/v1/hooks/requests", { path: webhookPath(options.path) });
|
|
397
|
+
const json = await resp.json();
|
|
398
|
+
return json?.deleted ?? 0;
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Sends a caught request again (method, path, query, headers, body) to `url`, a PUBLIC http(s) address (MailPier never calls
|
|
402
|
+
* private or loopback addresses: 400). Not retried on 502/504 or network errors, so the target never gets it twice.
|
|
403
|
+
*/
|
|
404
|
+
async replayWebhook(id, url) {
|
|
405
|
+
if (!url?.trim()) throw new Error("replayWebhook needs the URL to send the request to.");
|
|
406
|
+
const resp = await this.request(
|
|
407
|
+
"POST",
|
|
408
|
+
`/v1/hooks/requests/${encodeURIComponent(String(id))}/replay`,
|
|
409
|
+
{},
|
|
410
|
+
{ body: JSON.stringify({ url: url.trim() }), once: true }
|
|
411
|
+
);
|
|
412
|
+
const json = await resp.json();
|
|
413
|
+
return { status: json?.status ?? null, durationMs: json?.durationMs ?? null, error: json?.error ?? null };
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Adds a custom response: requests whose path starts with `rule.path` (and of `rule.method`, when given) get this status,
|
|
417
|
+
* content type, body and delay instead of 200 OK. Throws MailPierInboxError (400) when it is invalid or over the plan's count.
|
|
418
|
+
*/
|
|
419
|
+
async addWebhookResponse(rule) {
|
|
420
|
+
const path = webhookPath(rule?.path);
|
|
421
|
+
if (!path) throw new Error('addWebhookResponse needs a path (e.g. "/stripe"; "/" for every request).');
|
|
422
|
+
const isObject = rule.body !== void 0 && rule.body !== null && typeof rule.body === "object";
|
|
423
|
+
const payload = {
|
|
424
|
+
method: rule.method?.trim() ? rule.method.trim().toUpperCase() : null,
|
|
425
|
+
path,
|
|
426
|
+
status: rule.status ?? 200,
|
|
427
|
+
contentType: rule.contentType ?? (isObject ? "application/json" : "text/plain"),
|
|
428
|
+
body: isObject ? JSON.stringify(rule.body) : rule.body ?? "",
|
|
429
|
+
delayMs: rule.delayMs ?? 0
|
|
430
|
+
};
|
|
431
|
+
const resp = await this.request("POST", "/v1/hooks/responses", {}, { body: JSON.stringify(payload), once: true });
|
|
432
|
+
return await resp.json();
|
|
433
|
+
}
|
|
434
|
+
/** The environment's custom responses. */
|
|
435
|
+
async listWebhookResponses() {
|
|
436
|
+
const resp = await this.request("GET", "/v1/hooks/responses", {});
|
|
437
|
+
const json = await resp.json();
|
|
438
|
+
return json?.items ?? [];
|
|
439
|
+
}
|
|
440
|
+
/** Deletes a custom response. False when it did not exist. */
|
|
441
|
+
async deleteWebhookResponse(id) {
|
|
442
|
+
const resp = await this.request("DELETE", `/v1/hooks/responses/${encodeURIComponent(String(id))}`, {}, { allow404: true });
|
|
443
|
+
return resp.status !== 404;
|
|
444
|
+
}
|
|
445
|
+
// ------------------------------------------------------------------ plumbing
|
|
446
|
+
async download(path) {
|
|
447
|
+
const resp = await this.request("GET", path, {}, { allow404: true, accept: "*/*" });
|
|
448
|
+
if (resp.status === 404) return null;
|
|
449
|
+
return new Uint8Array(await resp.arrayBuffer());
|
|
450
|
+
}
|
|
451
|
+
url(path, query) {
|
|
452
|
+
const q = new URLSearchParams();
|
|
453
|
+
for (const [k, v] of Object.entries(query)) if (v !== void 0 && v !== null && v !== "") q.set(k, String(v));
|
|
454
|
+
const s = q.toString();
|
|
455
|
+
return `${this.baseUrl}${path}${s ? `?${s}` : ""}`;
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* 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
|
|
459
|
+
* (both capped at maxRetryDelayMs). Other errors throw MailPierInboxError with the server's {"error": "..."} text.
|
|
460
|
+
* `once`: a call that must not run twice (replay, add a rule) is retried only on 429 and 503 (refused before any work), never
|
|
461
|
+
* on 502/504 or network errors (it may have been done).
|
|
462
|
+
*/
|
|
463
|
+
async request(method, path, query, o = {}) {
|
|
464
|
+
const url = this.url(path, query);
|
|
465
|
+
const headers = {
|
|
466
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
467
|
+
Accept: o.accept ?? "application/json",
|
|
468
|
+
"User-Agent": `mailpier-inbox-node/${VERSION}`
|
|
469
|
+
};
|
|
470
|
+
if (o.body !== void 0) headers["Content-Type"] = "application/json";
|
|
471
|
+
for (let attempt = 0; ; attempt++) {
|
|
472
|
+
const ctl = new AbortController();
|
|
473
|
+
const timer = setTimeout(
|
|
474
|
+
() => ctl.abort(new Error(`No answer within ${Math.round((o.timeoutMs ?? 6e4) / 1e3)} s.`)),
|
|
475
|
+
o.timeoutMs ?? 6e4
|
|
476
|
+
);
|
|
477
|
+
const onAbort = () => ctl.abort(o.signal.reason);
|
|
478
|
+
if (o.signal?.aborted) onAbort();
|
|
479
|
+
else o.signal?.addEventListener("abort", onAbort, { once: true });
|
|
480
|
+
let resp;
|
|
481
|
+
try {
|
|
482
|
+
resp = await this.fetchImpl(url, { method, headers, body: o.body, signal: ctl.signal });
|
|
483
|
+
} catch (err) {
|
|
484
|
+
clearTimeout(timer);
|
|
485
|
+
o.signal?.removeEventListener("abort", onAbort);
|
|
486
|
+
if (o.signal?.aborted) throw err;
|
|
487
|
+
if (attempt >= this.maxRetries || o.once) {
|
|
488
|
+
throw new MailPierInboxError(0, `Could not reach MailPier Inbox at ${this.baseUrl}: ${err instanceof Error ? err.message : String(err)}`);
|
|
489
|
+
}
|
|
490
|
+
await sleep(this.backoff(attempt), o.signal);
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
clearTimeout(timer);
|
|
494
|
+
o.signal?.removeEventListener("abort", onAbort);
|
|
495
|
+
if (resp.ok || o.allow404 && resp.status === 404) return resp;
|
|
496
|
+
const message = await errorText(resp);
|
|
497
|
+
if (resp.status === 429) {
|
|
498
|
+
const retryAfter = parseRetryAfter(resp.headers.get("Retry-After"));
|
|
499
|
+
if (attempt < this.maxRetries) {
|
|
500
|
+
await sleep(Math.min((retryAfter ?? 1) * 1e3, this.maxRetryDelayMs), o.signal);
|
|
501
|
+
continue;
|
|
502
|
+
}
|
|
503
|
+
throw new MailPierInboxError(429, message ?? "Too many requests.", retryAfter);
|
|
504
|
+
}
|
|
505
|
+
const retryable = resp.status === 503 || !o.once && (resp.status === 502 || resp.status === 504);
|
|
506
|
+
if (retryable && attempt < this.maxRetries) {
|
|
507
|
+
await sleep(this.backoff(attempt), o.signal);
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
throw new MailPierInboxError(resp.status, message ?? `MailPier Inbox answered ${resp.status}.`);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
backoff(attempt) {
|
|
514
|
+
return Math.min(500 * 2 ** attempt, this.maxRetryDelayMs);
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
async function errorText(resp) {
|
|
518
|
+
try {
|
|
519
|
+
const text = await resp.text();
|
|
520
|
+
if (!text) return void 0;
|
|
521
|
+
try {
|
|
522
|
+
const e = JSON.parse(text).error;
|
|
523
|
+
return typeof e === "string" && e ? `${e} (HTTP ${resp.status})` : void 0;
|
|
524
|
+
} catch {
|
|
525
|
+
return void 0;
|
|
526
|
+
}
|
|
527
|
+
} catch {
|
|
528
|
+
return void 0;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
function parseRetryAfter(v) {
|
|
532
|
+
if (!v) return void 0;
|
|
533
|
+
const n = Number.parseInt(v, 10);
|
|
534
|
+
if (Number.isFinite(n) && n >= 0) return n;
|
|
535
|
+
const t = Date.parse(v);
|
|
536
|
+
return Number.isFinite(t) ? Math.max(0, Math.ceil((t - Date.now()) / 1e3)) : void 0;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// src/cypress/tasks.ts
|
|
540
|
+
function mailpierTasks(options = {}) {
|
|
541
|
+
let client;
|
|
542
|
+
const inbox = () => client ??= new MailPierInbox(options);
|
|
543
|
+
return {
|
|
544
|
+
"mailpier:newAddress": async (args) => inbox().newAddress({ prefix: args?.prefix, domain: args?.domain }),
|
|
545
|
+
"mailpier:waitForMessage": async (args) => {
|
|
546
|
+
if (!args?.to) throw new Error("mailpier:waitForMessage needs { to }.");
|
|
547
|
+
const m = await inbox().waitForMessage({
|
|
548
|
+
to: args.to,
|
|
549
|
+
subjectContains: args.subjectContains,
|
|
550
|
+
timeoutMs: args.timeoutMs,
|
|
551
|
+
since: args.since,
|
|
552
|
+
afterId: args.afterId
|
|
553
|
+
});
|
|
554
|
+
return { ...m.toJSON(), code: m.code ?? null, firstLink: m.firstLink() ?? null };
|
|
555
|
+
},
|
|
556
|
+
"mailpier:deleteAll": async (args) => inbox().deleteAll(args.to),
|
|
557
|
+
"mailpier:createWebhookUrl": async () => inbox().createWebhookUrl(),
|
|
558
|
+
"mailpier:waitForWebhook": async (args) => {
|
|
559
|
+
if (!args?.path) throw new Error("mailpier:waitForWebhook needs { path }.");
|
|
560
|
+
const r = await inbox().waitForWebhook({
|
|
561
|
+
path: args.path,
|
|
562
|
+
method: args.method,
|
|
563
|
+
timeoutSeconds: args.timeoutSeconds,
|
|
564
|
+
since: args.since,
|
|
565
|
+
afterId: args.afterId
|
|
566
|
+
});
|
|
567
|
+
const plain = r.toJSON();
|
|
568
|
+
return { ...plain, body: plain.body ?? null, bodyBase64: plain.bodyBase64 ?? null, json: plain.json ?? null, form: plain.form ?? null };
|
|
569
|
+
}
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
573
|
+
0 && (module.exports = {
|
|
574
|
+
mailpierTasks
|
|
575
|
+
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { InboxMessageData, WebhookRequestData, WebhookUrl, MailPierInboxOptions } from '../index.cjs';
|
|
2
|
+
|
|
3
|
+
interface MailPierWaitTaskArgs {
|
|
4
|
+
to: string;
|
|
5
|
+
subjectContains?: string;
|
|
6
|
+
timeoutMs?: number;
|
|
7
|
+
/** ISO time; only mail received at or after it. */
|
|
8
|
+
since?: string;
|
|
9
|
+
/** With since: skip this message id (use the previous message's receivedUtc + id to get the next one). */
|
|
10
|
+
afterId?: string;
|
|
11
|
+
}
|
|
12
|
+
/** What cy.mailpierWaitForMessage yields: the message JSON plus `code` and `firstLink` (any link). */
|
|
13
|
+
type MailPierTaskMessage = InboxMessageData & {
|
|
14
|
+
code: string | null;
|
|
15
|
+
firstLink: string | null;
|
|
16
|
+
};
|
|
17
|
+
interface MailPierWebhookWaitTaskArgs {
|
|
18
|
+
/** Path prefix after the token (e.g. the path of mailpier:createWebhookUrl). */
|
|
19
|
+
path: string;
|
|
20
|
+
method?: string;
|
|
21
|
+
/** Default 60. */
|
|
22
|
+
timeoutSeconds?: number;
|
|
23
|
+
/** ISO time; only requests received at or after it. */
|
|
24
|
+
since?: string;
|
|
25
|
+
/** Only a request with a larger id. */
|
|
26
|
+
afterId?: number;
|
|
27
|
+
}
|
|
28
|
+
/** What cy.mailpierWaitForWebhook yields: the request JSON (method, path, query, headers, body, json, form ...). */
|
|
29
|
+
type MailPierTaskWebhook = WebhookRequestData;
|
|
30
|
+
interface MailPierTasks {
|
|
31
|
+
"mailpier:newAddress"(args?: {
|
|
32
|
+
prefix?: string;
|
|
33
|
+
domain?: string;
|
|
34
|
+
} | null): Promise<string>;
|
|
35
|
+
"mailpier:waitForMessage"(args: MailPierWaitTaskArgs): Promise<MailPierTaskMessage>;
|
|
36
|
+
"mailpier:deleteAll"(args: {
|
|
37
|
+
to: string;
|
|
38
|
+
}): Promise<number>;
|
|
39
|
+
"mailpier:createWebhookUrl"(args?: null): Promise<WebhookUrl>;
|
|
40
|
+
"mailpier:waitForWebhook"(args: MailPierWebhookWaitTaskArgs): Promise<MailPierTaskWebhook>;
|
|
41
|
+
[name: string]: (args: never) => unknown;
|
|
42
|
+
}
|
|
43
|
+
/** The cy.task handlers. Options default to MAILPIER_API_KEY / MAILPIER_BASE_URL in the Cypress Node process. */
|
|
44
|
+
declare function mailpierTasks(options?: MailPierInboxOptions): MailPierTasks;
|
|
45
|
+
|
|
46
|
+
export { mailpierTasks };
|
|
47
|
+
export type { MailPierTaskMessage, MailPierTaskWebhook, MailPierTasks, MailPierWaitTaskArgs, MailPierWebhookWaitTaskArgs };
|