@devitek/mailsink-vitest 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Devitek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # @devitek/mailsink-vitest
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Vitest and Jest helpers for [Mailsink](https://github.com/Devitek/mailsink), the email sink
4
+ for staging and CI: an ephemeral workspace per test file, worker or run, and matchers for
5
+ the emails your code sends.
6
+
7
+ ```sh
8
+ npm install --save-dev @devitek/mailsink-vitest
9
+ ```
10
+
11
+ ```ts
12
+ // vitest.config.ts: test.setupFiles = ['@devitek/mailsink-vitest/setup']
13
+ import { test } from '@devitek/mailsink-vitest'
14
+ import { expect } from 'vitest'
15
+
16
+ test('sends the welcome email', async ({ mailsink }) => {
17
+ await signUp('ada@example.test', mailsink.credentials('resend'))
18
+
19
+ await expect(mailsink).toHaveReceivedEmail({ to: 'ada@example.test', subject: 'Welcome' })
20
+ const message = await mailsink.client.messages.waitFor(
21
+ { to: 'ada@example.test' },
22
+ { since: new Date(0) },
23
+ )
24
+ expect(message).toHaveLink('/welcome')
25
+ expect(message).toHaveStatus(['queued', 'delivered'])
26
+ })
27
+ ```
28
+
29
+ Set `MAILSINK_URL` and `MAILSINK_ADMIN_KEY` (or pass `url` and `adminKey`). Jest, the
30
+ worker scope, the global setup and every option: the
31
+ [guide](https://mailsink.devitek.fr/guides/vitest-jest/) of the
32
+ [Mailsink documentation](https://mailsink.devitek.fr).
33
+
34
+ Versioned with the Mailsink server. MIT license.
@@ -0,0 +1,12 @@
1
+ import { TestProject } from "vitest/node";
2
+ import "./vitest-types-DjRjVdmN.js";
3
+ import { i as EphemeralWorkspaceOptions } from "./workspace-ax6D_yPR.js";
4
+ type Provider = Pick<TestProject, 'provide'>;
5
+ /**
6
+ * A global setup function creating the workspace with `options`, for a custom
7
+ * `globalSetup` file: `export default mailsinkGlobalSetup({ workspace: { name: 'CI' } })`.
8
+ */
9
+ export declare function mailsinkGlobalSetup(options?: EphemeralWorkspaceOptions): (project: Provider) => Promise<() => Promise<void>>;
10
+ /** The default: `MAILSINK_URL`, `MAILSINK_ADMIN_KEY` and the default workspace. */
11
+ declare const _default: (project: Provider) => Promise<() => Promise<void>>;
12
+ export { _default as default };
@@ -0,0 +1,21 @@
1
+ import { r as createEphemeralWorkspace } from "./workspace-DEMV9evu.js";
2
+ // src/global-setup.ts
3
+ /**
4
+ * A global setup function creating the workspace with `options`, for a custom
5
+ * `globalSetup` file: `export default mailsinkGlobalSetup({ workspace: { name: 'CI' } })`.
6
+ */
7
+ function mailsinkGlobalSetup(options = {}) {
8
+ return async (project) => {
9
+ const workspace = await createEphemeralWorkspace(options);
10
+ project.provide("mailsink", {
11
+ url: workspace.url,
12
+ workspace: workspace.workspace,
13
+ workspaceKey: workspace.workspaceKey,
14
+ connections: workspace.connections
15
+ });
16
+ return () => workspace.dispose();
17
+ };
18
+ }
19
+ /** The default: `MAILSINK_URL`, `MAILSINK_ADMIN_KEY` and the default workspace. */
20
+ var global_setup_default = mailsinkGlobalSetup();
21
+ export { global_setup_default as default, mailsinkGlobalSetup };
@@ -0,0 +1,71 @@
1
+ import { DeliveryStatus, LinkMatcher, ListMessagesParams, Mailsink } from "@devitek/mailsink";
2
+ interface MatcherContext {
3
+ isNot: boolean;
4
+ }
5
+ interface MatcherResult {
6
+ pass: boolean;
7
+ message: () => string;
8
+ }
9
+ /** A message as `messages.get`, `messages.waitFor` or `messages.list` answer it. */
10
+ interface MessageWithStatus {
11
+ subject?: string;
12
+ status: DeliveryStatus;
13
+ recipients?: readonly {
14
+ email: string;
15
+ status: DeliveryStatus;
16
+ }[];
17
+ }
18
+ interface StatusOptions {
19
+ /** Checks the status of this recipient (a `MessageDetail`) instead of the aggregate. */
20
+ recipient?: string;
21
+ }
22
+ /**
23
+ * `expect(message).toHaveStatus('delivered')`: the aggregate status of a message, or the
24
+ * status of one recipient with `{ recipient }`; several statuses mean any of them.
25
+ */
26
+ declare function toHaveStatus(this: MatcherContext, received: unknown, expected: DeliveryStatus | readonly DeliveryStatus[], options?: StatusOptions): MatcherResult;
27
+ /**
28
+ * `expect(message).toHaveLink('/verify')`: the message has a link (server links, HTML
29
+ * `href`s, text URLs) matching a substring, a RegExp or a predicate on the URL; any link
30
+ * when no matcher is given.
31
+ */
32
+ declare function toHaveLink(this: MatcherContext, received: unknown, matcher?: LinkMatcher): MatcherResult;
33
+ interface ReceivedEmailOptions {
34
+ /** How long to wait for a matching message, default 5 000 ms. Ignored with `.not`. */
35
+ timeout?: number;
36
+ /**
37
+ * Oldest `createdAt` that counts. Default: every message of the workspace, so a message
38
+ * that arrived before the assertion matches too.
39
+ */
40
+ since?: Date | string;
41
+ }
42
+ declare const DEFAULT_RECEIVED_TIMEOUT_MS = 5000;
43
+ /** What `toHaveReceivedEmail` accepts: an SDK client, or a handle with a `client`. */
44
+ type MailsinkLike = Pick<Mailsink, 'messages'> | {
45
+ client: Pick<Mailsink, 'messages'>;
46
+ };
47
+ /**
48
+ * `await expect(client).toHaveReceivedEmail(filters?, options?)`: passes when a message of
49
+ * the workspace matches `filters` (the `messages.list` filters: `to`, `subject`, `status`,
50
+ * `tag`, `q`...), waiting up to `timeout`. With `.not`, checks once without waiting.
51
+ */
52
+ declare function toHaveReceivedEmail(this: MatcherContext, received: unknown, filters?: ListMessagesParams, options?: ReceivedEmailOptions): Promise<MatcherResult>;
53
+ declare const mailsinkMatchers: {
54
+ toHaveReceivedEmail: typeof toHaveReceivedEmail;
55
+ toHaveStatus: typeof toHaveStatus;
56
+ toHaveLink: typeof toHaveLink;
57
+ };
58
+ /**
59
+ * Signatures of the matchers, `R` being the return type of a synchronous assertion. Augment
60
+ * your runner's `Matchers` interface with it (Vitest: done by this package; Jest: see
61
+ * `docs/guides/vitest-jest.md`).
62
+ */
63
+ interface MailsinkMatchers<R> {
64
+ /** A message of the workspace matches `filters`; always `await` it. */
65
+ toHaveReceivedEmail(filters?: ListMessagesParams, options?: ReceivedEmailOptions): Promise<void>;
66
+ /** The aggregate status of the message (or of `recipient`) is one of `expected`. */
67
+ toHaveStatus(expected: DeliveryStatus | readonly DeliveryStatus[], options?: StatusOptions): R;
68
+ /** The message has a link matching `matcher` (any link when omitted). */
69
+ toHaveLink(matcher?: LinkMatcher): R;
70
+ }
71
+ export { ReceivedEmailOptions as a, StatusOptions as c, MatcherContext as d, MatcherResult as f, MailsinkLike as i, toHaveLink as l, mailsinkMatchers as n, toHaveReceivedEmail as o, DEFAULT_RECEIVED_TIMEOUT_MS as r, MessageWithStatus as s, MailsinkMatchers as t, toHaveStatus as u };
@@ -0,0 +1,35 @@
1
+ import "./vitest-types-DjRjVdmN.js";
2
+ import { a as MailsinkConnectOptions, c as connectWorkspace, i as EphemeralWorkspaceOptions, l as createEphemeralWorkspace, n as Credentials, o as MailsinkWorkspace, r as DEFAULT_WORKSPACE, s as MailsinkWorkspaceData, t as ConnectionKind, u as resolveConnect } from "./workspace-ax6D_yPR.js";
3
+ import { mailsinkGlobalSetup } from "./global-setup.js";
4
+ import { a as ReceivedEmailOptions, c as StatusOptions, d as MatcherContext, f as MatcherResult, i as MailsinkLike, l as toHaveLink, n as mailsinkMatchers, o as toHaveReceivedEmail, r as DEFAULT_RECEIVED_TIMEOUT_MS, s as MessageWithStatus, t as MailsinkMatchers, u as toHaveStatus } from "./index-CcOgfADP.js";
5
+ /** Options, or a function read when the fixture starts (after `beforeAll` hooks). */
6
+ type MailsinkTestOptions = EphemeralWorkspaceOptions | (() => EphemeralWorkspaceOptions);
7
+ /** A `test` whose `mailsink` fixture is one ephemeral workspace per test file. */
8
+ export declare function fileScopedTest(options?: MailsinkTestOptions): import("vitest").TestAPI<{
9
+ mailsink: MailsinkWorkspace;
10
+ } & object>;
11
+ /**
12
+ * A `test` whose `mailsink` fixture is one ephemeral workspace per worker. Vitest isolates
13
+ * each test file in its own worker by default: set `isolate: false` to share it.
14
+ */
15
+ export declare function workerScopedTest(options?: MailsinkTestOptions): import("vitest").TestAPI<{
16
+ mailsink: MailsinkWorkspace;
17
+ } & object>;
18
+ type MailsinkFileTest = ReturnType<typeof fileScopedTest>;
19
+ type MailsinkWorkerTest = ReturnType<typeof workerScopedTest>;
20
+ /**
21
+ * A `test` with a `mailsink` fixture: an ephemeral workspace (`MailsinkWorkspace`) created
22
+ * the first time a test of the file (or worker) uses it and deleted after the last one.
23
+ */
24
+ export declare function createMailsinkTest(options?: MailsinkTestOptions, scope?: 'file'): MailsinkFileTest;
25
+ export declare function createMailsinkTest(options: MailsinkTestOptions, scope: 'worker'): MailsinkWorkerTest;
26
+ /** `test` with a per-file `mailsink` workspace, configured by `MAILSINK_URL` and `MAILSINK_ADMIN_KEY`. */
27
+ export declare const test: import("vitest").TestAPI<{
28
+ mailsink: MailsinkWorkspace;
29
+ } & object>;
30
+ /**
31
+ * The workspace of `@devitek/mailsink-vitest/global-setup`, as a handle. Its `dispose()`
32
+ * does nothing: the global teardown deletes the workspace.
33
+ */
34
+ export declare function injectMailsink(): MailsinkWorkspace;
35
+ export { ConnectionKind, Credentials, DEFAULT_RECEIVED_TIMEOUT_MS, DEFAULT_WORKSPACE, EphemeralWorkspaceOptions, MailsinkConnectOptions, type MailsinkFileTest, type MailsinkLike, MailsinkMatchers, type MailsinkTestOptions, type MailsinkWorkerTest, MailsinkWorkspace, MailsinkWorkspaceData, type MatcherContext, type MatcherResult, type MessageWithStatus, type ReceivedEmailOptions, type StatusOptions, connectWorkspace, createEphemeralWorkspace, mailsinkGlobalSetup, mailsinkMatchers, resolveConnect, toHaveLink, toHaveReceivedEmail, toHaveStatus };
package/dist/index.js ADDED
@@ -0,0 +1,41 @@
1
+ import { inject, test as test$1 } from "vitest";
2
+ import { i as resolveConnect, n as connectWorkspace, r as createEphemeralWorkspace, t as DEFAULT_WORKSPACE } from "./workspace-DEMV9evu.js";
3
+ import { mailsinkGlobalSetup } from "./global-setup.js";
4
+ import { a as toHaveStatus, i as toHaveLink, n as DEFAULT_RECEIVED_TIMEOUT_MS, r as toHaveReceivedEmail, t as mailsinkMatchers } from "./matchers-OtUxqZu_.js";
5
+ // src/fixtures.ts
6
+ const read = (options) => typeof options === "function" ? options() : options;
7
+ async function setUp(options, use) {
8
+ const workspace = await createEphemeralWorkspace(read(options));
9
+ try {
10
+ await use(workspace);
11
+ } finally {
12
+ await workspace.dispose();
13
+ }
14
+ }
15
+ /** A `test` whose `mailsink` fixture is one ephemeral workspace per test file. */
16
+ function fileScopedTest(options = {}) {
17
+ return test$1.extend({ mailsink: [async ({}, use) => setUp(options, use), { scope: "file" }] });
18
+ }
19
+ /**
20
+ * A `test` whose `mailsink` fixture is one ephemeral workspace per worker. Vitest isolates
21
+ * each test file in its own worker by default: set `isolate: false` to share it.
22
+ */
23
+ function workerScopedTest(options = {}) {
24
+ return test$1.extend({ mailsink: [async ({}, use) => setUp(options, use), { scope: "worker" }] });
25
+ }
26
+ function createMailsinkTest(options = {}, scope = "file") {
27
+ return scope === "worker" ? workerScopedTest(options) : fileScopedTest(options);
28
+ }
29
+ /** `test` with a per-file `mailsink` workspace, configured by `MAILSINK_URL` and `MAILSINK_ADMIN_KEY`. */
30
+ const test = fileScopedTest();
31
+ // src/index.ts
32
+ /**
33
+ * The workspace of `@devitek/mailsink-vitest/global-setup`, as a handle. Its `dispose()`
34
+ * does nothing: the global teardown deletes the workspace.
35
+ */
36
+ function injectMailsink() {
37
+ const data = inject("mailsink");
38
+ if (!data) throw new Error("Mailsink: no workspace provided, add @devitek/mailsink-vitest/global-setup to globalSetup");
39
+ return connectWorkspace(data);
40
+ }
41
+ export { DEFAULT_RECEIVED_TIMEOUT_MS, DEFAULT_WORKSPACE, connectWorkspace, createEphemeralWorkspace, createMailsinkTest, fileScopedTest, injectMailsink, mailsinkGlobalSetup, mailsinkMatchers, resolveConnect, test, toHaveLink, toHaveReceivedEmail, toHaveStatus, workerScopedTest };
package/dist/jest.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ import { a as MailsinkConnectOptions, c as connectWorkspace, i as EphemeralWorkspaceOptions, l as createEphemeralWorkspace, n as Credentials, o as MailsinkWorkspace, r as DEFAULT_WORKSPACE, s as MailsinkWorkspaceData, t as ConnectionKind, u as resolveConnect } from "./workspace-ax6D_yPR.js";
2
+ import { a as ReceivedEmailOptions, c as StatusOptions, d as MatcherContext, f as MatcherResult, i as MailsinkLike, l as toHaveLink, n as mailsinkMatchers, o as toHaveReceivedEmail, r as DEFAULT_RECEIVED_TIMEOUT_MS, s as MessageWithStatus, t as MailsinkMatchers, u as toHaveStatus } from "./index-CcOgfADP.js";
3
+ type Hook = (fn: () => Promise<void>, timeout?: number) => void;
4
+ export interface Hooks {
5
+ beforeAll: Hook;
6
+ afterAll: Hook;
7
+ }
8
+ interface Expect {
9
+ extend(matchers: Record<string, unknown>): void;
10
+ }
11
+ /** Registers the matchers on `expect` (the global one by default). */
12
+ export declare function installMailsinkMatchers(expect?: Expect): void;
13
+ /**
14
+ * Creates an ephemeral workspace before the tests of the file and deletes it after them.
15
+ * Call it at the top of a test file, or in a `setupFilesAfterEnv` module (it then runs for
16
+ * every test file). Answers the handle; `mailsinkWorkspace()` answers it too.
17
+ */
18
+ export declare function useMailsinkWorkspace(options?: EphemeralWorkspaceOptions, hooks?: Hooks, timeout?: number): MailsinkWorkspace;
19
+ /** The workspace of `useMailsinkWorkspace`, once its `beforeAll` ran. */
20
+ export declare function mailsinkWorkspace(): MailsinkWorkspace;
21
+ export { ConnectionKind, Credentials, DEFAULT_RECEIVED_TIMEOUT_MS, DEFAULT_WORKSPACE, EphemeralWorkspaceOptions, MailsinkConnectOptions, type MailsinkLike, MailsinkMatchers, MailsinkWorkspace, MailsinkWorkspaceData, type MatcherContext, type MatcherResult, type MessageWithStatus, type ReceivedEmailOptions, type StatusOptions, connectWorkspace, createEphemeralWorkspace, mailsinkMatchers, resolveConnect, toHaveLink, toHaveReceivedEmail, toHaveStatus };
package/dist/jest.js ADDED
@@ -0,0 +1,42 @@
1
+ import { a as toHaveStatus, i as toHaveLink, n as DEFAULT_RECEIVED_TIMEOUT_MS, r as toHaveReceivedEmail, t as mailsinkMatchers } from "./matchers-OtUxqZu_.js";
2
+ import { i as resolveConnect, n as connectWorkspace, r as createEphemeralWorkspace, t as DEFAULT_WORKSPACE } from "./workspace-DEMV9evu.js";
3
+ // src/jest.ts
4
+ const CURRENT = Symbol.for("@devitek/mailsink-vitest/current-workspace");
5
+ const globalHooks = () => {
6
+ const g = globalThis;
7
+ if (!g.beforeAll || !g.afterAll) throw new Error("Mailsink: no global beforeAll/afterAll, pass them as the `hooks` argument");
8
+ return {
9
+ beforeAll: g.beforeAll,
10
+ afterAll: g.afterAll
11
+ };
12
+ };
13
+ /** Registers the matchers on `expect` (the global one by default). */
14
+ function installMailsinkMatchers(expect) {
15
+ const target = expect ?? globalThis.expect;
16
+ if (!target) throw new Error("Mailsink: no global expect, pass it to installMailsinkMatchers");
17
+ target.extend(mailsinkMatchers);
18
+ }
19
+ /**
20
+ * Creates an ephemeral workspace before the tests of the file and deletes it after them.
21
+ * Call it at the top of a test file, or in a `setupFilesAfterEnv` module (it then runs for
22
+ * every test file). Answers the handle; `mailsinkWorkspace()` answers it too.
23
+ */
24
+ function useMailsinkWorkspace(options = {}, hooks = globalHooks(), timeout = 3e4) {
25
+ const slot = globalThis;
26
+ hooks.beforeAll(async () => {
27
+ slot[CURRENT] = await createEphemeralWorkspace(options);
28
+ }, timeout);
29
+ hooks.afterAll(async () => {
30
+ const workspace = slot[CURRENT];
31
+ slot[CURRENT] = void 0;
32
+ await workspace?.dispose();
33
+ }, timeout);
34
+ return new Proxy({}, { get: (_, key) => key === "then" ? void 0 : Reflect.get(mailsinkWorkspace(), key) });
35
+ }
36
+ /** The workspace of `useMailsinkWorkspace`, once its `beforeAll` ran. */
37
+ function mailsinkWorkspace() {
38
+ const workspace = globalThis[CURRENT];
39
+ if (!workspace) throw new Error("Mailsink: no workspace yet, call useMailsinkWorkspace() and read it in tests");
40
+ return workspace;
41
+ }
42
+ export { DEFAULT_RECEIVED_TIMEOUT_MS, DEFAULT_WORKSPACE, connectWorkspace, createEphemeralWorkspace, installMailsinkMatchers, mailsinkMatchers, mailsinkWorkspace, resolveConnect, toHaveLink, toHaveReceivedEmail, toHaveStatus, useMailsinkWorkspace };
@@ -0,0 +1,113 @@
1
+ import { extractLinks, findLink } from "@devitek/mailsink";
2
+ // src/matchers/message.ts
3
+ const subjectOf = (m) => m.subject ? ` "${m.subject}"` : "";
4
+ function assertMessage(received, matcher) {
5
+ if (!received || typeof received !== "object") throw new TypeError(`${matcher} expects a message, got ${String(received)}`);
6
+ }
7
+ /**
8
+ * `expect(message).toHaveStatus('delivered')`: the aggregate status of a message, or the
9
+ * status of one recipient with `{ recipient }`; several statuses mean any of them.
10
+ */
11
+ function toHaveStatus(received, expected, options = {}) {
12
+ assertMessage(received, "toHaveStatus");
13
+ const message = received;
14
+ const allowed = typeof expected === "string" ? [expected] : expected;
15
+ const wanted = allowed.join(" or ");
16
+ let actual = message.status;
17
+ let who = `message${subjectOf(message)}`;
18
+ if (options.recipient) {
19
+ const email = options.recipient.toLowerCase();
20
+ actual = message.recipients?.find((r) => r.email.toLowerCase() === email)?.status;
21
+ who = `recipient ${options.recipient} of message${subjectOf(message)}`;
22
+ if (!actual) return {
23
+ pass: false,
24
+ message: () => `expected ${who} to exist (status ${wanted})`
25
+ };
26
+ }
27
+ const pass = actual !== void 0 && allowed.includes(actual);
28
+ return {
29
+ pass,
30
+ message: () => pass ? `expected ${who} not to have status ${wanted}` : `expected ${who} to have status ${wanted}, got ${actual}`
31
+ };
32
+ }
33
+ const describeMatcher = (matcher) => matcher === void 0 ? "a link" : typeof matcher === "function" ? "a link matching the predicate" : `a link matching ${String(matcher)}`;
34
+ /**
35
+ * `expect(message).toHaveLink('/verify')`: the message has a link (server links, HTML
36
+ * `href`s, text URLs) matching a substring, a RegExp or a predicate on the URL; any link
37
+ * when no matcher is given.
38
+ */
39
+ function toHaveLink(received, matcher) {
40
+ assertMessage(received, "toHaveLink");
41
+ const message = received;
42
+ const links = extractLinks(message);
43
+ const found = matcher === void 0 ? links[0] ?? null : findLink(message, matcher);
44
+ const wanted = describeMatcher(matcher);
45
+ const list = links.length ? `\nLinks:\n${links.map((l) => ` - ${l}`).join("\n")}` : "";
46
+ return {
47
+ pass: found !== null,
48
+ message: () => found !== null ? `expected the message${subjectOf(message)} not to have ${wanted}, found ${found}` : `expected the message${subjectOf(message)} to have ${wanted}${list || ", it has none"}`
49
+ };
50
+ }
51
+ // src/matchers/received.ts
52
+ const DEFAULT_RECEIVED_TIMEOUT_MS = 5e3;
53
+ function messagesOf(received) {
54
+ const value = received;
55
+ const messages = value?.messages ?? value?.client?.messages;
56
+ if (!messages || typeof messages.waitFor !== "function") throw new TypeError("toHaveReceivedEmail expects a Mailsink client or a workspace handle with a `client`");
57
+ return messages;
58
+ }
59
+ const describeFilters = (filters) => {
60
+ const entries = Object.entries(filters).filter(([, v]) => v !== void 0);
61
+ return entries.length ? JSON.stringify(Object.fromEntries(entries)) : "any filter";
62
+ };
63
+ const line = (m) => ` - "${m.subject}" to ${m.to.map((a) => a.email).join(", ")} (${m.status})`;
64
+ /**
65
+ * `await expect(client).toHaveReceivedEmail(filters?, options?)`: passes when a message of
66
+ * the workspace matches `filters` (the `messages.list` filters: `to`, `subject`, `status`,
67
+ * `tag`, `q`...), waiting up to `timeout`. With `.not`, checks once without waiting.
68
+ */
69
+ async function toHaveReceivedEmail(received, filters = {}, options = {}) {
70
+ const messages = messagesOf(received);
71
+ const since = options.since ?? /* @__PURE__ */ new Date(0);
72
+ const wanted = describeFilters(filters);
73
+ let found;
74
+ if (this.isNot) found = (await messages.list({
75
+ ...filters,
76
+ since,
77
+ limit: 1
78
+ })).data[0];
79
+ else {
80
+ const timeout = options.timeout ?? 5e3;
81
+ try {
82
+ found = await messages.waitFor(filters, {
83
+ since,
84
+ timeout
85
+ });
86
+ } catch (error) {
87
+ if (error?.code !== "wait_timeout") throw error;
88
+ const recent = (await messages.list({
89
+ since,
90
+ limit: 5
91
+ })).data;
92
+ const seen = recent.length ? `Latest messages of the workspace:\n${recent.map(line).join("\n")}` : "The workspace has no message.";
93
+ return {
94
+ pass: false,
95
+ message: () => `expected an email matching ${wanted} within ${timeout} ms\n${seen}`
96
+ };
97
+ }
98
+ }
99
+ return found ? {
100
+ pass: true,
101
+ message: () => `expected no email matching ${wanted}, found:\n${line(found)}`
102
+ } : {
103
+ pass: false,
104
+ message: () => `expected an email matching ${wanted}, found none`
105
+ };
106
+ }
107
+ // src/matchers/index.ts
108
+ const mailsinkMatchers = {
109
+ toHaveReceivedEmail,
110
+ toHaveStatus,
111
+ toHaveLink
112
+ };
113
+ export { toHaveStatus as a, toHaveLink as i, DEFAULT_RECEIVED_TIMEOUT_MS as n, toHaveReceivedEmail as r, mailsinkMatchers as t };
@@ -0,0 +1,2 @@
1
+ import { a as ReceivedEmailOptions, c as StatusOptions, d as MatcherContext, f as MatcherResult, i as MailsinkLike, l as toHaveLink, n as mailsinkMatchers, o as toHaveReceivedEmail, r as DEFAULT_RECEIVED_TIMEOUT_MS, s as MessageWithStatus, t as MailsinkMatchers, u as toHaveStatus } from "./index-CcOgfADP.js";
2
+ export { DEFAULT_RECEIVED_TIMEOUT_MS, type MailsinkLike, MailsinkMatchers, type MatcherContext, type MatcherResult, type MessageWithStatus, type ReceivedEmailOptions, type StatusOptions, mailsinkMatchers, toHaveLink, toHaveReceivedEmail, toHaveStatus };
@@ -0,0 +1 @@
1
+ export { n as DEFAULT_RECEIVED_TIMEOUT_MS, t as mailsinkMatchers, i as toHaveLink, r as toHaveReceivedEmail, a as toHaveStatus } from "./matchers-OtUxqZu_.js";
@@ -0,0 +1 @@
1
+ import "./vitest-types-DjRjVdmN.js";
package/dist/setup.js ADDED
@@ -0,0 +1,5 @@
1
+ import { expect } from "vitest";
2
+ import { t as mailsinkMatchers } from "./matchers-OtUxqZu_.js";
3
+ // src/setup.ts
4
+ expect.extend(mailsinkMatchers);
5
+ export {};
@@ -0,0 +1,10 @@
1
+ import "vitest";
2
+ import { t as MailsinkMatchers } from "./index-CcOgfADP.js";
3
+ import { s as MailsinkWorkspaceData } from "./workspace-ax6D_yPR.js";
4
+ declare module 'vitest' {
5
+ interface Matchers<R, T> extends MailsinkMatchers<R> {}
6
+ interface ProvidedContext {
7
+ /** The workspace created by `@devitek/mailsink-vitest/global-setup`. */
8
+ mailsink: MailsinkWorkspaceData;
9
+ }
10
+ }
@@ -0,0 +1,78 @@
1
+ import { createMailsink, isMailsinkError } from "@devitek/mailsink";
2
+ // src/workspace.ts
3
+ const DEFAULT_WORKSPACE = {
4
+ name: "Tests",
5
+ connections: [{
6
+ kind: "resend",
7
+ name: "Test"
8
+ }]
9
+ };
10
+ /** Connection options with the `MAILSINK_URL` and `MAILSINK_ADMIN_KEY` fallbacks. */
11
+ function resolveConnect(options = {}) {
12
+ const env = typeof process === "undefined" ? {} : process.env;
13
+ const url = options.url ?? env.MAILSINK_URL;
14
+ const adminKey = options.adminKey ?? env.MAILSINK_ADMIN_KEY;
15
+ if (!url) throw new Error("Mailsink: set MAILSINK_URL or pass the `url` option");
16
+ if (!adminKey) throw new Error("Mailsink: set MAILSINK_ADMIN_KEY or pass the `adminKey` option");
17
+ return {
18
+ url,
19
+ adminKey,
20
+ fetch: options.fetch
21
+ };
22
+ }
23
+ /** Creates an ephemeral workspace; `dispose()` deletes it. */
24
+ async function createEphemeralWorkspace(options = {}) {
25
+ const { url, adminKey, fetch } = resolveConnect(options);
26
+ const admin = createMailsink({
27
+ url,
28
+ adminKey,
29
+ fetch
30
+ });
31
+ const created = await admin.admin.workspaces.create({
32
+ ...DEFAULT_WORKSPACE,
33
+ ...options.workspace,
34
+ name: options.workspace?.name ?? DEFAULT_WORKSPACE.name ?? "Tests",
35
+ ephemeral: true,
36
+ metadata: {
37
+ createdBy: "@devitek/mailsink-vitest",
38
+ ...options.workspace?.metadata
39
+ }
40
+ });
41
+ return connectWorkspace({
42
+ url,
43
+ workspace: created.workspace,
44
+ workspaceKey: created.workspaceKey,
45
+ connections: created.connections
46
+ }, {
47
+ fetch,
48
+ dispose: async () => {
49
+ try {
50
+ await admin.admin.workspaces.delete(created.workspace.id);
51
+ } catch (error) {
52
+ if (!isMailsinkError(error, "not_found")) throw error;
53
+ }
54
+ }
55
+ });
56
+ }
57
+ /** A handle on an existing workspace, e.g. the one a global setup created. */
58
+ function connectWorkspace(data, options = {}) {
59
+ let disposed;
60
+ return {
61
+ ...data,
62
+ client: createMailsink({
63
+ url: data.url,
64
+ key: data.workspaceKey,
65
+ fetch: options.fetch
66
+ }),
67
+ credentials(kind) {
68
+ const found = data.connections.find((c) => !kind || c.kind === kind);
69
+ if (!found) throw new Error(`Mailsink: the workspace has no ${kind ?? ""} connection`);
70
+ return found.credentials;
71
+ },
72
+ dispose() {
73
+ disposed ??= options.dispose?.() ?? Promise.resolve();
74
+ return disposed;
75
+ }
76
+ };
77
+ }
78
+ export { resolveConnect as i, connectWorkspace as n, createEphemeralWorkspace as r, DEFAULT_WORKSPACE as t };
@@ -0,0 +1,53 @@
1
+ import { CreateWorkspaceInput, CreatedConnection, Mailsink, Workspace } from "@devitek/mailsink";
2
+ /** Where the Mailsink instance is and how to administrate it. */
3
+ interface MailsinkConnectOptions {
4
+ /** Base URL of the instance, default `MAILSINK_URL`. */
5
+ url?: string;
6
+ /** Admin key, default `MAILSINK_ADMIN_KEY`. */
7
+ adminKey?: string;
8
+ /** `fetch` implementation, the global one by default. */
9
+ fetch?: typeof fetch;
10
+ }
11
+ interface EphemeralWorkspaceOptions extends MailsinkConnectOptions {
12
+ /**
13
+ * Fields of the created workspace. `ephemeral` is always true; default name `Tests`,
14
+ * default connections one Resend connection named `Test`.
15
+ */
16
+ workspace?: Partial<CreateWorkspaceInput>;
17
+ }
18
+ /** Serializable part of a workspace handle: what a global setup hands to the tests. */
19
+ interface MailsinkWorkspaceData {
20
+ url: string;
21
+ workspace: Workspace;
22
+ /** `mskw_` key of the workspace: capture, overrides, stream. */
23
+ workspaceKey: string;
24
+ /** Connections with their secrets (API key or SMTP credentials), shown once. */
25
+ connections: CreatedConnection[];
26
+ }
27
+ type ConnectionKind = CreatedConnection['kind'];
28
+ type Credentials<K extends ConnectionKind = ConnectionKind> = Extract<CreatedConnection['credentials'], {
29
+ kind: K;
30
+ }>;
31
+ interface MailsinkWorkspace extends MailsinkWorkspaceData {
32
+ /** SDK client scoped to the workspace (its `mskw_` key). */
33
+ client: Mailsink;
34
+ /** Credentials of the first connection of `kind` (any kind when omitted). */
35
+ credentials<K extends ConnectionKind>(kind?: K): Credentials<K>;
36
+ /** Deletes the workspace (no-op when it is already gone or was not created here). */
37
+ dispose(): Promise<void>;
38
+ }
39
+ declare const DEFAULT_WORKSPACE: Partial<CreateWorkspaceInput>;
40
+ /** Connection options with the `MAILSINK_URL` and `MAILSINK_ADMIN_KEY` fallbacks. */
41
+ declare function resolveConnect(options?: MailsinkConnectOptions): {
42
+ url: string;
43
+ adminKey: string;
44
+ fetch: typeof fetch | undefined;
45
+ };
46
+ /** Creates an ephemeral workspace; `dispose()` deletes it. */
47
+ declare function createEphemeralWorkspace(options?: EphemeralWorkspaceOptions): Promise<MailsinkWorkspace>;
48
+ /** A handle on an existing workspace, e.g. the one a global setup created. */
49
+ declare function connectWorkspace(data: MailsinkWorkspaceData, options?: {
50
+ fetch?: typeof fetch;
51
+ dispose?: () => Promise<void>;
52
+ }): MailsinkWorkspace;
53
+ export { MailsinkConnectOptions as a, connectWorkspace as c, EphemeralWorkspaceOptions as i, createEphemeralWorkspace as l, Credentials as n, MailsinkWorkspace as o, DEFAULT_WORKSPACE as r, MailsinkWorkspaceData as s, ConnectionKind as t, resolveConnect as u };
package/package.json CHANGED
@@ -1,6 +1,83 @@
1
1
  {
2
2
  "name": "@devitek/mailsink-vitest",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "Vitest and Jest helpers for Mailsink: an ephemeral workspace per test file or worker, and matchers for received emails, statuses and links",
5
+ "keywords": [
6
+ "mailsink",
7
+ "email",
8
+ "testing",
9
+ "vitest",
10
+ "jest",
11
+ "matchers"
12
+ ],
13
+ "license": "MIT",
14
+ "author": "Devitek",
15
+ "homepage": "https://github.com/Devitek/mailsink/tree/main/packages/vitest#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/Devitek/mailsink.git",
19
+ "directory": "packages/vitest"
20
+ },
21
+ "bugs": "https://github.com/Devitek/mailsink/issues",
22
+ "type": "module",
23
+ "sideEffects": [
24
+ "./src/setup.ts",
25
+ "./dist/setup.js"
26
+ ],
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "import": "./dist/index.js"
31
+ },
32
+ "./setup": {
33
+ "types": "./dist/setup.d.ts",
34
+ "import": "./dist/setup.js"
35
+ },
36
+ "./global-setup": {
37
+ "types": "./dist/global-setup.d.ts",
38
+ "import": "./dist/global-setup.js"
39
+ },
40
+ "./jest": {
41
+ "types": "./dist/jest.d.ts",
42
+ "import": "./dist/jest.js"
43
+ },
44
+ "./matchers": {
45
+ "types": "./dist/matchers.d.ts",
46
+ "import": "./dist/matchers.js"
47
+ },
48
+ "./package.json": "./package.json"
49
+ },
50
+ "files": [
51
+ "dist"
52
+ ],
53
+ "engines": {
54
+ "node": ">=20"
55
+ },
56
+ "publishConfig": {
57
+ "access": "public"
58
+ },
59
+ "dependencies": {
60
+ "@devitek/mailsink": "0.3.0"
61
+ },
62
+ "peerDependencies": {
63
+ "vitest": ">=5.0.0"
64
+ },
65
+ "peerDependenciesMeta": {
66
+ "vitest": {
67
+ "optional": true
68
+ }
69
+ },
70
+ "devDependencies": {
71
+ "@mailsink/contracts": "0.0.0",
72
+ "@mailsink/core": "0.0.0",
73
+ "@mailsink/db": "0.0.0",
74
+ "jest": "^30.5.2",
75
+ "tsdown": "^0.23.7",
76
+ "vitest": "^5.1.1"
77
+ },
78
+ "scripts": {
79
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
80
+ "build": "tsdown"
81
+ },
82
+ "types": "./dist/index.d.ts"
6
83
  }