@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/dist/cli.cjs ADDED
@@ -0,0 +1,751 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ // src/errors.ts
5
+ var MailPierInboxError = class extends Error {
6
+ status;
7
+ /** Set on 429: seconds to wait before the next call. */
8
+ retryAfterSeconds;
9
+ constructor(status, message, retryAfterSeconds) {
10
+ super(message);
11
+ this.name = "MailPierInboxError";
12
+ this.status = status;
13
+ this.retryAfterSeconds = retryAfterSeconds;
14
+ }
15
+ };
16
+ var MailPierTimeoutError = class extends Error {
17
+ address;
18
+ timeoutMs;
19
+ constructor(address, timeoutMs, subjectContains) {
20
+ super(`No mail to ${address}${subjectContains ? ` with "${subjectContains}" in the subject` : ""} arrived within ${Math.round(timeoutMs / 1e3)} seconds.`);
21
+ this.name = "MailPierTimeoutError";
22
+ this.address = address;
23
+ this.timeoutMs = timeoutMs;
24
+ }
25
+ };
26
+ var MailPierWebhookTimeoutError = class extends MailPierTimeoutError {
27
+ path;
28
+ method;
29
+ constructor(path, timeoutMs, method) {
30
+ super(path, timeoutMs);
31
+ this.message = `No ${method ? `${method.toUpperCase()} ` : ""}webhook request to ${path} arrived within ${Math.round(timeoutMs / 1e3)} seconds.`;
32
+ this.name = "MailPierWebhookTimeoutError";
33
+ this.path = path;
34
+ this.method = method;
35
+ }
36
+ };
37
+
38
+ // src/message.ts
39
+ var InboxMessage = class {
40
+ id;
41
+ receivedUtc;
42
+ from;
43
+ to = [];
44
+ subject;
45
+ sizeBytes = 0;
46
+ hasAttachments = false;
47
+ text;
48
+ html;
49
+ headers;
50
+ links = [];
51
+ codes = [];
52
+ attachments = [];
53
+ auth;
54
+ spam;
55
+ constructor(data) {
56
+ Object.assign(this, data);
57
+ this.to = Array.isArray(data.to) ? data.to : [];
58
+ this.links = Array.isArray(data.links) ? data.links.filter((l) => l && typeof l.href === "string") : [];
59
+ this.codes = normaliseCodes(data.codes);
60
+ this.attachments = Array.isArray(data.attachments) ? data.attachments : [];
61
+ }
62
+ /** The first one-time code in the mail (best guess first), or undefined when it has none. */
63
+ get code() {
64
+ return this.codes[0];
65
+ }
66
+ /**
67
+ * The first link whose address (or text) contains `contains` (case-insensitive), or the first link when it is omitted;
68
+ * undefined when none matches.
69
+ */
70
+ firstLink(contains) {
71
+ if (contains === void 0 || contains === null || contains === "") return this.links[0]?.href;
72
+ const needle = contains.toLowerCase();
73
+ return this.links.find((l) => l.href.toLowerCase().includes(needle) || (l.text ?? "").toLowerCase().includes(needle))?.href;
74
+ }
75
+ /** The plain JSON (what the API returned), e.g. to pass through a Cypress task. */
76
+ toJSON() {
77
+ const { ...plain } = this;
78
+ return { ...plain, code: this.code };
79
+ }
80
+ };
81
+ function normaliseCodes(codes) {
82
+ if (!Array.isArray(codes)) return [];
83
+ const out = [];
84
+ for (const c of codes) {
85
+ if (typeof c === "string" && c.length > 0) out.push(c);
86
+ else if (c && typeof c === "object") {
87
+ for (const k of ["value", "code", "Value", "Code"]) {
88
+ const v = c[k];
89
+ if (typeof v === "string" && v.length > 0) {
90
+ out.push(v);
91
+ break;
92
+ }
93
+ }
94
+ }
95
+ }
96
+ return out;
97
+ }
98
+
99
+ // src/webhook.ts
100
+ var WebhookRequest = class {
101
+ id;
102
+ receivedUtc;
103
+ method = "";
104
+ path = "/";
105
+ query;
106
+ contentType;
107
+ size = 0;
108
+ environment;
109
+ status = 0;
110
+ url;
111
+ headers = [];
112
+ body;
113
+ bodyBase64;
114
+ json;
115
+ form;
116
+ sourceIp;
117
+ headersTruncated = false;
118
+ ruleId;
119
+ forwardStatus;
120
+ constructor(data) {
121
+ Object.assign(this, data);
122
+ this.headers = Array.isArray(data.headers) ? data.headers.filter((h) => h && typeof h.name === "string").map((h) => ({ name: h.name, value: String(h.value ?? "") })) : [];
123
+ this.headersTruncated = data.headersTruncated === true;
124
+ }
125
+ /** The first value of a header (name case-insensitive), or undefined when the request has none. */
126
+ header(name) {
127
+ const n = name.toLowerCase();
128
+ return this.headers.find((h) => h.name.toLowerCase() === n)?.value;
129
+ }
130
+ /** The body bytes (from `body` or `bodyBase64`); empty when the request had no body. */
131
+ bytes() {
132
+ if (typeof this.bodyBase64 === "string" && this.bodyBase64) {
133
+ const bin = atob(this.bodyBase64);
134
+ const out = new Uint8Array(bin.length);
135
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
136
+ return out;
137
+ }
138
+ return new TextEncoder().encode(this.body ?? "");
139
+ }
140
+ /**
141
+ * The body as JSON: the server's parsed `json`, or the text body parsed here (a JSON body sent with another content type).
142
+ * Throws when the body is not JSON.
143
+ */
144
+ jsonBody() {
145
+ if (this.json !== void 0 && this.json !== null) return this.json;
146
+ if (typeof this.body === "string" && this.body.trim()) {
147
+ try {
148
+ return JSON.parse(this.body);
149
+ } catch {
150
+ }
151
+ }
152
+ throw new Error(`The body of ${this.method} ${this.path} (request ${this.id}, ${this.contentType ?? "no content type"}) is not JSON.`);
153
+ }
154
+ /** The plain JSON (what the API returned), e.g. to pass through a Cypress task. */
155
+ toJSON() {
156
+ const { ...plain } = this;
157
+ return plain;
158
+ }
159
+ };
160
+
161
+ // src/client.ts
162
+ var DEFAULT_BASE_URL = "https://api.mailpier.io";
163
+ var MAX_POLL_SECONDS = 120;
164
+ var VERSION = "0.1.1";
165
+ var sleep = (ms, signal) => new Promise((resolve, reject) => {
166
+ if (signal?.aborted) return reject(signal.reason);
167
+ const t = setTimeout(() => {
168
+ signal?.removeEventListener("abort", onAbort);
169
+ resolve();
170
+ }, ms);
171
+ const onAbort = () => {
172
+ clearTimeout(t);
173
+ reject(signal.reason);
174
+ };
175
+ signal?.addEventListener("abort", onAbort, { once: true });
176
+ });
177
+ function iso(t) {
178
+ if (t === void 0) return void 0;
179
+ return typeof t === "string" ? t : t.toISOString();
180
+ }
181
+ function env(name) {
182
+ const p = globalThis.process;
183
+ const v = p?.env?.[name];
184
+ return v && v.trim() ? v.trim() : void 0;
185
+ }
186
+ function webhookPath(path) {
187
+ const p = path?.trim();
188
+ if (!p) return void 0;
189
+ return p.startsWith("/") ? p : `/${p}`;
190
+ }
191
+ var MailPierInbox = class {
192
+ baseUrl;
193
+ apiKey;
194
+ maxRetries;
195
+ maxRetryDelayMs;
196
+ fetchImpl;
197
+ constructor(options = {}) {
198
+ const key = (options.apiKey ?? env("MAILPIER_API_KEY") ?? "").trim();
199
+ if (!key) throw new Error("An API key (mpi_...) is required: pass { apiKey } or set MAILPIER_API_KEY.");
200
+ this.apiKey = key;
201
+ this.baseUrl = (options.baseUrl ?? env("MAILPIER_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
202
+ this.maxRetries = Math.max(0, options.maxRetries ?? 5);
203
+ this.maxRetryDelayMs = Math.max(0, options.maxRetryDelayMs ?? 6e4);
204
+ const f = options.fetch ?? globalThis.fetch;
205
+ if (!f) throw new Error("No fetch available: use Node 18 or later, or pass { fetch }.");
206
+ this.fetchImpl = f;
207
+ }
208
+ /** A fresh random address of the key's environment, e.g. `signup-k3v9q2mz7a@qa.acme.mailpier.io`. */
209
+ async newAddress(options = {}) {
210
+ const body = {};
211
+ if (options.domain) body.domain = options.domain;
212
+ if (options.prefix) body.prefix = options.prefix;
213
+ const resp = await this.request("POST", "/v1/addresses", {}, { body: JSON.stringify(body) });
214
+ const json = await resp.json();
215
+ if (!json?.address) throw new MailPierInboxError(resp.status, "The server returned no address.");
216
+ return json.address;
217
+ }
218
+ /**
219
+ * Waits until a mail to `to` arrives and returns it (the OLDEST match received at or after `since`).
220
+ * Throws MailPierTimeoutError when nothing arrives within `timeoutMs`.
221
+ */
222
+ async waitForMessage(options) {
223
+ const to = options.to?.trim();
224
+ if (!to) throw new Error("waitForMessage needs { to: address }.");
225
+ const timeoutMs = options.timeoutMs ?? 6e4;
226
+ if (!(timeoutMs > 0)) throw new Error("timeoutMs must be greater than 0.");
227
+ const deadline = Date.now() + timeoutMs;
228
+ const since = iso(options.since);
229
+ for (; ; ) {
230
+ const left = deadline - Date.now();
231
+ const seconds = Math.min(Math.max(Math.ceil(left / 1e3), 1), MAX_POLL_SECONDS);
232
+ const resp = await this.request("GET", "/v1/messages/wait", {
233
+ to,
234
+ subject: options.subjectContains,
235
+ since,
236
+ afterId: since ? options.afterId : void 0,
237
+ timeoutSeconds: seconds
238
+ }, { signal: options.signal, timeoutMs: (seconds + 30) * 1e3 });
239
+ if (resp.status !== 204) return new InboxMessage(await resp.json());
240
+ if (Date.now() >= deadline) throw new MailPierTimeoutError(to, timeoutMs, options.subjectContains);
241
+ }
242
+ }
243
+ /**
244
+ * Waits for the next mail to `to` after `previous` (one you already received): passes its receivedUtc as `since` and its id as
245
+ * `afterId`, so a mail stored in the same millisecond is not missed and `previous` itself is never returned again.
246
+ */
247
+ waitForNextMessage(previous, options) {
248
+ return this.waitForMessage({ ...options, since: previous.receivedUtc, afterId: previous.id });
249
+ }
250
+ /** Mail of the environment, newest first (at most 100 per call). */
251
+ async listMessages(options = {}) {
252
+ const since = iso(options.since);
253
+ const resp = await this.request("GET", "/v1/messages", {
254
+ to: options.to,
255
+ subject: options.subjectContains,
256
+ since,
257
+ afterId: since ? options.afterId : void 0,
258
+ take: options.take ?? 50,
259
+ skip: options.skip ?? 0
260
+ }, { signal: options.signal });
261
+ const json = await resp.json();
262
+ return json?.items ?? [];
263
+ }
264
+ /** One mail with its text, HTML, headers, links, codes and attachment list; null when it does not exist (or expired). */
265
+ async getMessage(id) {
266
+ const resp = await this.request("GET", `/v1/messages/${encodeURIComponent(id)}`, {}, { allow404: true });
267
+ if (resp.status === 404) return null;
268
+ return new InboxMessage(await resp.json());
269
+ }
270
+ /** The original message (.eml bytes); null when it does not exist. */
271
+ getRaw(id) {
272
+ return this.download(`/v1/messages/${encodeURIComponent(id)}/raw`);
273
+ }
274
+ /** One attachment's bytes; null when it does not exist. */
275
+ getAttachment(id, index) {
276
+ return this.download(`/v1/messages/${encodeURIComponent(id)}/attachments/${index}`);
277
+ }
278
+ /** Deletes one mail. False when it did not exist. Throws (409) when the mail was also sent outside this environment. */
279
+ async deleteMessage(id) {
280
+ const resp = await this.request("DELETE", `/v1/messages/${encodeURIComponent(id)}`, {}, { allow404: true });
281
+ return resp.status !== 404;
282
+ }
283
+ /** Deletes every mail to one address; returns how many were deleted. */
284
+ async deleteAll(to) {
285
+ return (await this.deleteAllDetailed(to)).deleted;
286
+ }
287
+ /** Like deleteAll, but also says how many shared mails were skipped. */
288
+ async deleteAllDetailed(to) {
289
+ if (!to?.trim()) throw new Error("deleteAll needs the address.");
290
+ const resp = await this.request("DELETE", "/v1/messages", { to: to.trim() });
291
+ const json = await resp.json();
292
+ return { deleted: json?.deleted ?? 0, skippedShared: json?.skippedShared ?? 0 };
293
+ }
294
+ /** The key's account, environment, domains, plan and usage (GET /v1/me). */
295
+ async me() {
296
+ const resp = await this.request("GET", "/v1/me", {});
297
+ return await resp.json();
298
+ }
299
+ // ------------------------------------------------------------------ Webhook inspector (/v1/hooks; 404 while the feature is off)
300
+ /** The environment's catch URL (made on first use), its switches and the plan's webhook limits. */
301
+ async getWebhookEndpoint() {
302
+ const resp = await this.request("GET", "/v1/hooks", {});
303
+ const json = await resp.json();
304
+ if (!json?.url) throw new MailPierInboxError(resp.status, "The server returned no webhook URL.");
305
+ return json;
306
+ }
307
+ /**
308
+ * The catch URL with a fresh random path, e.g. `{ url: "https://hook.gather-io.com/<token>/t-8f2k1x", path: "/t-8f2k1x" }`.
309
+ * Give `url` to the app under test and wait with `waitForWebhook({ path })`. Nothing is stored: any path works without this call.
310
+ */
311
+ async createWebhookUrl() {
312
+ const resp = await this.request("POST", "/v1/hooks/urls", {});
313
+ const json = await resp.json();
314
+ if (!json?.url || !json.path) throw new MailPierInboxError(resp.status, "The server returned no webhook URL.");
315
+ return { url: json.url, path: json.path };
316
+ }
317
+ /**
318
+ * Waits until a request to the catch URL arrives and returns it: the OLDEST match newer than `afterId` / `since`.
319
+ * Throws MailPierWebhookTimeoutError (a MailPierTimeoutError) when nothing arrives within `timeoutSeconds`.
320
+ */
321
+ async waitForWebhook(options = {}) {
322
+ const path = webhookPath(options.path);
323
+ const method = options.method?.trim() || void 0;
324
+ const timeoutSeconds = options.timeoutSeconds ?? 60;
325
+ if (!(timeoutSeconds > 0)) throw new Error("timeoutSeconds must be greater than 0.");
326
+ const timeoutMs = timeoutSeconds * 1e3;
327
+ const deadline = Date.now() + timeoutMs;
328
+ const since = iso(options.since);
329
+ for (; ; ) {
330
+ const left = deadline - Date.now();
331
+ const seconds = Math.min(Math.max(Math.ceil(left / 1e3), 1), MAX_POLL_SECONDS);
332
+ const resp = await this.request("GET", "/v1/hooks/requests/wait", {
333
+ path,
334
+ method,
335
+ afterId: options.afterId,
336
+ since,
337
+ timeoutSeconds: seconds
338
+ }, { signal: options.signal, timeoutMs: (seconds + 30) * 1e3 });
339
+ if (resp.status !== 204) return new WebhookRequest(await resp.json());
340
+ if (Date.now() >= deadline) throw new MailPierWebhookTimeoutError(path ?? "/", timeoutMs, method);
341
+ }
342
+ }
343
+ /** Caught requests of the environment, newest first (at most 100 per call). */
344
+ async listWebhooks(options = {}) {
345
+ const resp = await this.request("GET", "/v1/hooks/requests", {
346
+ path: webhookPath(options.path),
347
+ method: options.method?.trim() || void 0,
348
+ afterId: options.afterId,
349
+ since: iso(options.since),
350
+ take: options.take ?? 50,
351
+ skip: options.skip ?? 0
352
+ }, { signal: options.signal });
353
+ const json = await resp.json();
354
+ return json?.items ?? [];
355
+ }
356
+ /** One caught request with headers and body; null when it does not exist (or expired). */
357
+ async getWebhook(id) {
358
+ const resp = await this.request("GET", `/v1/hooks/requests/${encodeURIComponent(String(id))}`, {}, { allow404: true });
359
+ if (resp.status === 404) return null;
360
+ return new WebhookRequest(await resp.json());
361
+ }
362
+ /** The raw body bytes of a caught request; null when it does not exist. */
363
+ getWebhookBody(id) {
364
+ return this.download(`/v1/hooks/requests/${encodeURIComponent(String(id))}/body`);
365
+ }
366
+ /** Deletes one caught request. False when it did not exist. */
367
+ async deleteWebhook(id) {
368
+ const resp = await this.request("DELETE", `/v1/hooks/requests/${encodeURIComponent(String(id))}`, {}, { allow404: true });
369
+ return resp.status !== 404;
370
+ }
371
+ /** Deletes the caught requests whose path starts with `path` (every request of the environment when omitted); returns how many. */
372
+ async deleteWebhooks(options = {}) {
373
+ const resp = await this.request("DELETE", "/v1/hooks/requests", { path: webhookPath(options.path) });
374
+ const json = await resp.json();
375
+ return json?.deleted ?? 0;
376
+ }
377
+ /**
378
+ * Sends a caught request again (method, path, query, headers, body) to `url`, a PUBLIC http(s) address (MailPier never calls
379
+ * private or loopback addresses: 400). Not retried on 502/504 or network errors, so the target never gets it twice.
380
+ */
381
+ async replayWebhook(id, url) {
382
+ if (!url?.trim()) throw new Error("replayWebhook needs the URL to send the request to.");
383
+ const resp = await this.request(
384
+ "POST",
385
+ `/v1/hooks/requests/${encodeURIComponent(String(id))}/replay`,
386
+ {},
387
+ { body: JSON.stringify({ url: url.trim() }), once: true }
388
+ );
389
+ const json = await resp.json();
390
+ return { status: json?.status ?? null, durationMs: json?.durationMs ?? null, error: json?.error ?? null };
391
+ }
392
+ /**
393
+ * Adds a custom response: requests whose path starts with `rule.path` (and of `rule.method`, when given) get this status,
394
+ * content type, body and delay instead of 200 OK. Throws MailPierInboxError (400) when it is invalid or over the plan's count.
395
+ */
396
+ async addWebhookResponse(rule) {
397
+ const path = webhookPath(rule?.path);
398
+ if (!path) throw new Error('addWebhookResponse needs a path (e.g. "/stripe"; "/" for every request).');
399
+ const isObject = rule.body !== void 0 && rule.body !== null && typeof rule.body === "object";
400
+ const payload = {
401
+ method: rule.method?.trim() ? rule.method.trim().toUpperCase() : null,
402
+ path,
403
+ status: rule.status ?? 200,
404
+ contentType: rule.contentType ?? (isObject ? "application/json" : "text/plain"),
405
+ body: isObject ? JSON.stringify(rule.body) : rule.body ?? "",
406
+ delayMs: rule.delayMs ?? 0
407
+ };
408
+ const resp = await this.request("POST", "/v1/hooks/responses", {}, { body: JSON.stringify(payload), once: true });
409
+ return await resp.json();
410
+ }
411
+ /** The environment's custom responses. */
412
+ async listWebhookResponses() {
413
+ const resp = await this.request("GET", "/v1/hooks/responses", {});
414
+ const json = await resp.json();
415
+ return json?.items ?? [];
416
+ }
417
+ /** Deletes a custom response. False when it did not exist. */
418
+ async deleteWebhookResponse(id) {
419
+ const resp = await this.request("DELETE", `/v1/hooks/responses/${encodeURIComponent(String(id))}`, {}, { allow404: true });
420
+ return resp.status !== 404;
421
+ }
422
+ // ------------------------------------------------------------------ plumbing
423
+ async download(path) {
424
+ const resp = await this.request("GET", path, {}, { allow404: true, accept: "*/*" });
425
+ if (resp.status === 404) return null;
426
+ return new Uint8Array(await resp.arrayBuffer());
427
+ }
428
+ url(path, query) {
429
+ const q = new URLSearchParams();
430
+ for (const [k, v] of Object.entries(query)) if (v !== void 0 && v !== null && v !== "") q.set(k, String(v));
431
+ const s = q.toString();
432
+ return `${this.baseUrl}${path}${s ? `?${s}` : ""}`;
433
+ }
434
+ /**
435
+ * 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
436
+ * (both capped at maxRetryDelayMs). Other errors throw MailPierInboxError with the server's {"error": "..."} text.
437
+ * `once`: a call that must not run twice (replay, add a rule) is retried only on 429 and 503 (refused before any work), never
438
+ * on 502/504 or network errors (it may have been done).
439
+ */
440
+ async request(method, path, query, o = {}) {
441
+ const url = this.url(path, query);
442
+ const headers = {
443
+ Authorization: `Bearer ${this.apiKey}`,
444
+ Accept: o.accept ?? "application/json",
445
+ "User-Agent": `mailpier-inbox-node/${VERSION}`
446
+ };
447
+ if (o.body !== void 0) headers["Content-Type"] = "application/json";
448
+ for (let attempt = 0; ; attempt++) {
449
+ const ctl2 = new AbortController();
450
+ const timer = setTimeout(
451
+ () => ctl2.abort(new Error(`No answer within ${Math.round((o.timeoutMs ?? 6e4) / 1e3)} s.`)),
452
+ o.timeoutMs ?? 6e4
453
+ );
454
+ const onAbort = () => ctl2.abort(o.signal.reason);
455
+ if (o.signal?.aborted) onAbort();
456
+ else o.signal?.addEventListener("abort", onAbort, { once: true });
457
+ let resp;
458
+ try {
459
+ resp = await this.fetchImpl(url, { method, headers, body: o.body, signal: ctl2.signal });
460
+ } catch (err) {
461
+ clearTimeout(timer);
462
+ o.signal?.removeEventListener("abort", onAbort);
463
+ if (o.signal?.aborted) throw err;
464
+ if (attempt >= this.maxRetries || o.once) {
465
+ throw new MailPierInboxError(0, `Could not reach MailPier Inbox at ${this.baseUrl}: ${err instanceof Error ? err.message : String(err)}`);
466
+ }
467
+ await sleep(this.backoff(attempt), o.signal);
468
+ continue;
469
+ }
470
+ clearTimeout(timer);
471
+ o.signal?.removeEventListener("abort", onAbort);
472
+ if (resp.ok || o.allow404 && resp.status === 404) return resp;
473
+ const message = await errorText(resp);
474
+ if (resp.status === 429) {
475
+ const retryAfter = parseRetryAfter(resp.headers.get("Retry-After"));
476
+ if (attempt < this.maxRetries) {
477
+ await sleep(Math.min((retryAfter ?? 1) * 1e3, this.maxRetryDelayMs), o.signal);
478
+ continue;
479
+ }
480
+ throw new MailPierInboxError(429, message ?? "Too many requests.", retryAfter);
481
+ }
482
+ const retryable = resp.status === 503 || !o.once && (resp.status === 502 || resp.status === 504);
483
+ if (retryable && attempt < this.maxRetries) {
484
+ await sleep(this.backoff(attempt), o.signal);
485
+ continue;
486
+ }
487
+ throw new MailPierInboxError(resp.status, message ?? `MailPier Inbox answered ${resp.status}.`);
488
+ }
489
+ }
490
+ backoff(attempt) {
491
+ return Math.min(500 * 2 ** attempt, this.maxRetryDelayMs);
492
+ }
493
+ };
494
+ async function errorText(resp) {
495
+ try {
496
+ const text = await resp.text();
497
+ if (!text) return void 0;
498
+ try {
499
+ const e = JSON.parse(text).error;
500
+ return typeof e === "string" && e ? `${e} (HTTP ${resp.status})` : void 0;
501
+ } catch {
502
+ return void 0;
503
+ }
504
+ } catch {
505
+ return void 0;
506
+ }
507
+ }
508
+ function parseRetryAfter(v) {
509
+ if (!v) return void 0;
510
+ const n = Number.parseInt(v, 10);
511
+ if (Number.isFinite(n) && n >= 0) return n;
512
+ const t = Date.parse(v);
513
+ return Number.isFinite(t) ? Math.max(0, Math.ceil((t - Date.now()) / 1e3)) : void 0;
514
+ }
515
+
516
+ // src/listen.ts
517
+ var USAGE = `Usage: mailpier listen <port|http://localhost:5000> [--path /prefix] [--key mpi_...] [--api https://api.mailpier.io]
518
+
519
+ Forwards every request caught by your MailPier Inbox environment's webhook URL to a local server (same method, path after
520
+ the token, query, headers and body) and prints one line per request, e.g. "POST /stripe -> 200 (34 ms)". Ctrl+C stops.
521
+
522
+ <port|url> a port on localhost (5000 = http://localhost:5000) or a URL; the request path is added to the URL's path
523
+ --path only requests whose path starts with this
524
+ --key the environment's API key (default: MAILPIER_API_KEY)
525
+ --api API root (default: MAILPIER_BASE_URL or https://api.mailpier.io)`;
526
+ var POLL_SECONDS = 60;
527
+ var DROPPED_HEADERS = /* @__PURE__ */ new Set([
528
+ "connection",
529
+ "keep-alive",
530
+ "proxy-authenticate",
531
+ "proxy-authorization",
532
+ "proxy-connection",
533
+ "te",
534
+ "trailer",
535
+ "transfer-encoding",
536
+ "upgrade",
537
+ "host",
538
+ "content-length",
539
+ "expect"
540
+ ]);
541
+ var MASKED_HEADERS = /* @__PURE__ */ new Set([
542
+ "authorization",
543
+ "proxy-authorization",
544
+ "cookie",
545
+ "x-api-key",
546
+ "api-key",
547
+ "x-auth-token",
548
+ "x-access-token",
549
+ "x-amz-security-token"
550
+ ]);
551
+ function parseListenArgs(argv) {
552
+ const args = [...argv];
553
+ if (args[0] === "listen") args.shift();
554
+ const out = {};
555
+ for (let i = 0; i < args.length; i++) {
556
+ const a = args[i];
557
+ const eq = a.startsWith("--") ? a.indexOf("=") : -1;
558
+ const name = eq > 0 ? a.slice(0, eq) : a;
559
+ const value = () => eq > 0 ? a.slice(eq + 1) : args[++i];
560
+ if (name === "--path" || name === "--key" || name === "--api") {
561
+ const v = value();
562
+ if (v === void 0 || v === "") return { error: `${name} needs a value.` };
563
+ if (name === "--path") out.path = v;
564
+ else if (name === "--key") out.apiKey = v;
565
+ else out.baseUrl = v;
566
+ } else if (a.startsWith("-")) {
567
+ return { error: `Unknown option ${a}.` };
568
+ } else if (out.target === void 0) {
569
+ out.target = a;
570
+ } else {
571
+ return { error: `Unexpected argument ${a}.` };
572
+ }
573
+ }
574
+ if (!out.target) return { error: "Give the local port or URL to forward to, e.g. `mailpier listen 5000`." };
575
+ try {
576
+ targetUrl(out.target);
577
+ } catch (err) {
578
+ return { error: err instanceof Error ? err.message : String(err) };
579
+ }
580
+ return out;
581
+ }
582
+ function targetUrl(target) {
583
+ const t = target.trim();
584
+ if (/^\d+$/.test(t)) {
585
+ const port = Number(t);
586
+ if (port < 1 || port > 65535) throw new Error(`${t} is not a port (1-65535).`);
587
+ return new URL(`http://localhost:${port}`);
588
+ }
589
+ let u;
590
+ try {
591
+ u = new URL(t);
592
+ } catch {
593
+ throw new Error(`${t} is neither a port nor a URL (e.g. 5000 or http://localhost:5000).`);
594
+ }
595
+ if (u.protocol !== "http:" && u.protocol !== "https:") throw new Error(`${t}: only http and https URLs can be forwarded to.`);
596
+ return u;
597
+ }
598
+ var PATH_SAFE = "-._~!$&'()*+,;=:@/";
599
+ function escapePath(path) {
600
+ let out = "";
601
+ const chars = Array.from(path);
602
+ for (let i = 0; i < chars.length; i++) {
603
+ const c = chars[i];
604
+ if (c === "%" && chars[i + 1] === "2" && (chars[i + 2] === "F" || chars[i + 2] === "f")) out += c;
605
+ else if (/^[A-Za-z0-9]$/.test(c) || PATH_SAFE.includes(c)) out += c;
606
+ else out += Array.from(new TextEncoder().encode(c), (b) => `%${b.toString(16).toUpperCase().padStart(2, "0")}`).join("");
607
+ }
608
+ return out;
609
+ }
610
+ var PathEscapeError = class extends Error {
611
+ constructor(base) {
612
+ super(`skipped: its path would leave ${base}/ on the target`);
613
+ this.name = "PathEscapeError";
614
+ }
615
+ };
616
+ function forwardUrl(target, path, query) {
617
+ const u = new URL(target.href);
618
+ const base = u.pathname.replace(/\/+$/, "");
619
+ u.pathname = base + escapePath(path.startsWith("/") ? path : `/${path}`);
620
+ u.search = query ? `?${query.replace(/^\?/, "")}` : "";
621
+ u.hash = "";
622
+ if (base && u.pathname !== base && !u.pathname.startsWith(`${base}/`)) throw new PathEscapeError(base);
623
+ return u.href;
624
+ }
625
+ function printable(text) {
626
+ return text.replace(/[\u0000-\u001f\u007f-\u009f]/g, (c) => `\\x${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`);
627
+ }
628
+ async function forwardRequest(request, target, fetchImpl = fetch, timeoutMs = 3e4) {
629
+ const headers = new Headers();
630
+ for (const h of request.headers) {
631
+ const n = h.name.toLowerCase();
632
+ if (DROPPED_HEADERS.has(n) || MASKED_HEADERS.has(n) && h.value === "***") continue;
633
+ try {
634
+ headers.append(h.name, h.value);
635
+ } catch {
636
+ }
637
+ }
638
+ const method = (request.method || "GET").toUpperCase();
639
+ const bytes = request.bytes();
640
+ const body = method === "GET" || method === "HEAD" || bytes.length === 0 ? void 0 : bytes;
641
+ const t0 = Date.now();
642
+ let url;
643
+ try {
644
+ url = forwardUrl(target, request.path, request.query);
645
+ } catch (err) {
646
+ return { error: err instanceof Error ? err.message : String(err), ms: Date.now() - t0 };
647
+ }
648
+ try {
649
+ const resp = await fetchImpl(url, {
650
+ method,
651
+ headers,
652
+ body,
653
+ redirect: "manual",
654
+ signal: AbortSignal.timeout(timeoutMs)
655
+ });
656
+ await resp.arrayBuffer().catch(() => void 0);
657
+ return { status: resp.status, ms: Date.now() - t0 };
658
+ } catch (err) {
659
+ const cause = err?.cause?.message;
660
+ return { error: cause ?? (err instanceof Error ? err.message : String(err)), ms: Date.now() - t0 };
661
+ }
662
+ }
663
+ var pause = (ms, signal) => new Promise((resolve) => {
664
+ if (signal?.aborted) return resolve();
665
+ const t = setTimeout(() => {
666
+ signal?.removeEventListener("abort", stop);
667
+ resolve();
668
+ }, ms);
669
+ const stop = () => {
670
+ clearTimeout(t);
671
+ resolve();
672
+ };
673
+ signal?.addEventListener("abort", stop, { once: true });
674
+ });
675
+ async function listen(o) {
676
+ const log = o.log ?? ((l) => console.log(l));
677
+ const target = targetUrl(o.target);
678
+ const path = webhookPath(o.path);
679
+ const fetchImpl = o.clientOptions?.fetch ?? fetch;
680
+ const inbox = new MailPierInbox({ apiKey: o.apiKey, baseUrl: o.baseUrl, ...o.clientOptions });
681
+ const maxBackoff = o.maxBackoffMs ?? 3e4;
682
+ const endpoint = await inbox.getWebhookEndpoint();
683
+ log(`Catch URL: ${endpoint.url}${path ?? ""}`);
684
+ if (endpoint.paused) log("Note: this webhook URL is paused (it answers 503 and stores nothing until it is resumed).");
685
+ let last = (await inbox.listWebhooks({ path, take: 1, signal: o.signal }))[0]?.id;
686
+ log(`Forwarding ${path ? `requests to ${path}* ` : "every request "}to ${target.href.replace(/\/$/, "")}. Ctrl+C stops.`);
687
+ let backoff = 0;
688
+ while (!o.signal?.aborted) {
689
+ let request;
690
+ try {
691
+ request = await inbox.waitForWebhook({ path, afterId: last, timeoutSeconds: o.pollSeconds ?? POLL_SECONDS, signal: o.signal });
692
+ backoff = 0;
693
+ } catch (err) {
694
+ if (o.signal?.aborted) break;
695
+ if (err instanceof MailPierTimeoutError) continue;
696
+ if (err instanceof MailPierInboxError && [400, 401, 403, 404].includes(err.status)) throw err;
697
+ backoff = Math.min(backoff ? backoff * 2 : 1e3, maxBackoff);
698
+ log(`Lost the connection to MailPier Inbox (${err instanceof Error ? err.message : String(err)}); retrying in ${Math.round(backoff / 1e3)} s.`);
699
+ await pause(backoff, o.signal);
700
+ continue;
701
+ }
702
+ last = request.id;
703
+ const r = await forwardRequest(request, target, fetchImpl);
704
+ const what = printable(`${request.method} ${request.path}${request.query ? `?${request.query}` : ""}`);
705
+ log(r.status !== void 0 ? `${what} -> ${r.status} (${r.ms} ms)` : `${what} -> failed: ${printable(r.error ?? "")} (${r.ms} ms)`);
706
+ }
707
+ }
708
+ async function main(argv, io) {
709
+ if (argv.length === 0 || ["-h", "--help", "help"].includes(argv[0]) || argv[0] === "listen" && argv.includes("--help")) {
710
+ io.log(USAGE);
711
+ return argv.length === 0 ? 2 : 0;
712
+ }
713
+ if (argv[0] !== "listen") {
714
+ io.error(`Unknown command ${argv[0]}.
715
+
716
+ ${USAGE}`);
717
+ return 2;
718
+ }
719
+ const args = parseListenArgs(argv);
720
+ if ("error" in args) {
721
+ io.error(`${args.error}
722
+
723
+ ${USAGE}`);
724
+ return 2;
725
+ }
726
+ try {
727
+ await listen({ ...args, signal: io.signal, log: io.log, clientOptions: io.clientOptions });
728
+ io.log("Stopped.");
729
+ return 0;
730
+ } catch (err) {
731
+ if (io.signal?.aborted) {
732
+ io.log("Stopped.");
733
+ return 0;
734
+ }
735
+ io.error(err instanceof Error ? err.message : String(err));
736
+ return 1;
737
+ }
738
+ }
739
+
740
+ // src/cli.ts
741
+ var ctl = new AbortController();
742
+ process.on("SIGINT", () => {
743
+ if (ctl.signal.aborted) process.exit(130);
744
+ ctl.abort();
745
+ });
746
+ main(process.argv.slice(2), { log: (l) => console.log(l), error: (l) => console.error(l), signal: ctl.signal }).then((code) => {
747
+ process.exitCode = code;
748
+ }).catch((err) => {
749
+ console.error(String(err));
750
+ process.exitCode = 1;
751
+ });