// AssertInbox Cypress tasks. MIT License. Node 18+ (global fetch). Use in cypress.config.js: registerAssertInboxTasks(on) const BASE = "https://assertinbox.com"; function clean(value, max) { return String(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, max); } // Task arguments are one value: a tag string or an options object. function asOptions(arg) { if (arg === undefined || arg === null) return {}; return typeof arg === "string" ? { tag: arg } : { ...arg }; } // Cypress needs serialisable results: undefined becomes null. function plain(value) { return value === undefined ? null : JSON.parse(JSON.stringify(value)); } function registerAssertInboxTasks(on, { baseUrl = BASE, fetch: fetchFn } = {}) { const doFetch = fetchFn || ((...a) => globalThis.fetch(...a)); const settings = () => { const key = process.env.ASSERTINBOX_KEY; const namespace = process.env.ASSERTINBOX_NAMESPACE; if (!key || !namespace) throw new Error("Set ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE. Create a key at https://assertinbox.com/start"); return { key, namespace }; }; async function wait(arg) { const { key } = settings(); const { tag, timeout = 25, from, subject, after, since, retries = 2 } = asOptions(arg); if (!tag) throw new Error("tag is required"); const q = new URLSearchParams(); for (const [k, v] of Object.entries({ tag, timeout, from, subject, after, since })) if (v !== undefined && v !== null && v !== "") q.set(k, String(v)); for (let attempt = 0; ; attempt++) { const res = await doFetch(baseUrl.replace(/\/+$/, "") + "/v1/wait?" + q, { headers: { Authorization: "Bearer " + key } }); const body = await res.json().catch(() => ({})); if (res.ok) return body; if (res.status === 408 && attempt < retries) continue; throw new Error("AssertInbox " + (body.error || "http_" + res.status) + (body.message ? ": " + body.message : "")); } } on("task", { "assertinbox:address"(arg) { const { namespace } = settings(); const { name = "user" } = asOptions(typeof arg === "string" ? { name: arg } : arg); const tag = clean(name, 16) + "-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 8); return { tag, address: namespace + "." + tag + "@" + new URL(baseUrl).hostname.replace(/^www\./, "") }; }, async "assertinbox:wait"(arg) { return plain(await wait(arg)); }, async "assertinbox:waitForOtp"(arg) { const message = await wait(arg); if (!message.otp) throw new Error('No code found in the email with subject "' + message.subject + '"'); return message.otp; }, async "assertinbox:waitForLink"(arg) { const message = await wait(arg); if (!message.magic_link) throw new Error('No link found in the email with subject "' + message.subject + '"'); return message.magic_link; }, }); } module.exports = { registerAssertInboxTasks };