playwright-facteur 0.0.0 → 1.0.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 Facteur
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,5 +1,90 @@
1
1
  # playwright-facteur
2
2
 
3
- Name reserved. The first release is coming shortly.
3
+ Receive email in your Playwright tests, and assert on what arrived.
4
4
 
5
- Facteur receives email and SMS for test suites: https://facteur.eu
5
+ ```ts
6
+ import { test, expect } from 'playwright-facteur';
7
+
8
+ test('the verification link activates the account', async ({ page, inbox }) => {
9
+ await page.goto('/signup');
10
+ await page.getByLabel('Email').fill(inbox.address('signup'));
11
+ await page.getByRole('button', { name: 'Create my account' }).click();
12
+
13
+ const message = await inbox.waitFor();
14
+ expect(message).toHaveOtp();
15
+
16
+ await page.goto(message.links[0].href);
17
+ await expect(page.getByText('Account verified')).toBeVisible();
18
+ });
19
+ ```
20
+
21
+ No `sleep`, no retry loop, no regular expression pulling a six-digit code out of an HTML
22
+ body. The wait happens on the server; the extraction happens when the mail is received.
23
+
24
+ ## Install
25
+
26
+ ```sh
27
+ npm i -D playwright-facteur
28
+ export FACTEUR_API_KEY=fk_...
29
+ ```
30
+
31
+ Node 20 or later, and Playwright 1.40 or later. Mint the key in the application under
32
+ **Settings → API keys**.
33
+
34
+ ## What you get
35
+
36
+ **`inbox`** is a fixture, one address per test. The tag carries the worker index, the
37
+ retry number and the test title, so `--workers=16` collides with nothing. The retry
38
+ matters: without it, a retried test reads the mail its own first attempt received, and
39
+ passes for the wrong reason exactly when something is already flaky.
40
+
41
+ ```ts
42
+ inbox.address() // test+the-title-w3r0-lz9k@j3k9x2mq.inbox.facteur.eu
43
+ inbox.address('billing') // billing+the-title-w3r0-lz9k@…
44
+ await inbox.waitFor({ subject: /invoice/ })
45
+ ```
46
+
47
+ **Matchers**, retried by Playwright's own engine and inheriting the test's timeout:
48
+
49
+ ```ts
50
+ await expect(inbox).toReceiveEmail({ subject: /verification/ });
51
+ expect(message).toHaveOtp('882314');
52
+ expect(message).toHaveLinkTo('app.example.com');
53
+ expect(message).toHaveAttachment('invoice.pdf');
54
+ ```
55
+
56
+ `toHaveOtp` fails with a different sentence when the message is not parsed yet, because
57
+ "there is no code in this mail" and "the code is not extracted yet" are different
58
+ problems and an `undefined` cannot tell them apart.
59
+
60
+ **The message in the report.** Every awaited message is attached to the test: the JSON
61
+ for the extracted fields, the HTML body to open. When a test fails, the mail that
62
+ actually arrived is next to the failure.
63
+
64
+ ## One inbox per worker, one address per test
65
+
66
+ Every address ending in the inbox's domain arrives, with nothing to create first, so a
67
+ sub-address isolates a test as well as a whole inbox would.
68
+
69
+ It also survives your plan. Creating an inbox per test walks into the inbox ceiling (one
70
+ on the free plan, three on Solo), so that arrangement works on a laptop and fails the
71
+ first time the suite runs on the plan you pay for.
72
+
73
+ Name an existing inbox to skip creation entirely, which is what most suites end up doing:
74
+
75
+ ```sh
76
+ export FACTEUR_INBOX=j3k9x2mq
77
+ ```
78
+
79
+ Without it, the plugin opens one per worker and destroys it at the end. That costs
80
+ nothing: an operation is a message received, never a call.
81
+
82
+ ## Parallel runs
83
+
84
+ The API refuses past twenty open waits per organization. The client keeps its own queue,
85
+ sized from your worker count, so the surplus waits its turn instead of coming back as a
86
+ `429`.
87
+
88
+ ## Licence
89
+
90
+ MIT.
package/index.d.mts ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Types for `index.mjs`, hand-written beside it — see `@facteur-eu/sdk` for why nothing
3
+ * here is compiled.
4
+ *
5
+ * The matcher declarations are the part that earns its keep: without them
6
+ * `expect(inbox).toReceiveEmail(...)` is a type error in the suites this package exists
7
+ * for, which are written in TypeScript.
8
+ */
9
+
10
+ import type { Inbox, Message, SearchCriteria, Facteur } from '@facteur-eu/sdk';
11
+ import type { TestType, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions } from '@playwright/test';
12
+
13
+ /** The inbox as a test holds it: shared with its worker, addressed to this test alone. */
14
+ export interface TestInbox {
15
+ id: string;
16
+ domain?: string;
17
+ /** The sub-address tag for this test: worker, retry and title. */
18
+ tag: string;
19
+ /** `test+<tag>@<inbox>.inbox.facteur.eu`, with `local` replacing `test`. */
20
+ address(local?: string): string;
21
+ /** Wait for a message addressed to this test. Attaches it to the report. */
22
+ waitFor(criteria?: Omit<SearchCriteria, 'inbox'>): Promise<Message>;
23
+ /** Everything currently in the shared inbox, this test's mail and its neighbours'. */
24
+ messages(): Promise<Message[]>;
25
+ }
26
+
27
+ export interface FacteurFixtures {
28
+ /** The client, one per worker. */
29
+ facteur: Facteur;
30
+ /** The inbox, opened once per worker or named by `FACTEUR_INBOX`. */
31
+ facteurInbox: Inbox;
32
+ /** This test's view onto it. */
33
+ inbox: TestInbox;
34
+ }
35
+
36
+ export declare const test: TestType<
37
+ PlaywrightTestArgs & PlaywrightTestOptions & FacteurFixtures,
38
+ PlaywrightWorkerArgs & PlaywrightWorkerOptions & FacteurFixtures
39
+ >;
40
+
41
+ declare global {
42
+ namespace PlaywrightTest {
43
+ interface Matchers<R, T> {
44
+ /** Wait for a message matching the criteria, and attach it to the report. */
45
+ toReceiveEmail(criteria?: Omit<SearchCriteria, 'inbox'>): Promise<R>;
46
+ /** A one-time code was extracted; optionally, this exact one. */
47
+ toHaveOtp(expected?: string): R;
48
+ /** A link whose URL contains this fragment. */
49
+ toHaveLinkTo(fragment: string): R;
50
+ /** A real attachment; an inline signature image is never counted. */
51
+ toHaveAttachment(fileName?: string): R;
52
+ }
53
+ }
54
+ }
55
+
56
+ export { expect } from '@playwright/test';
57
+ export { FacteurTimeout } from '@facteur-eu/sdk';
package/index.mjs ADDED
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Facteur inside Playwright: a fixture that waits, matchers that assert, and the message
3
+ * that arrived attached to the report.
4
+ *
5
+ * **Why this exists when a ten-line fixture would do.** The objection is a fair one:
6
+ * Playwright's fixtures make a plugin less indispensable than Cypress's command registry.
7
+ * Four things answer it, and none of them is a wrapper around a call:
8
+ *
9
+ * 1. **The address is derived from the test, not written by hand.** Worker index, test
10
+ * title and retry number make a sub-address no other test can collide with, which is
11
+ * what lets a suite run at `--workers=16` against one inbox.
12
+ * 2. **The matchers are retried by Playwright's own engine** and rewrite their failure.
13
+ * `await expect(inbox).toReceiveEmail({ subject: /code/ })` inherits the test's
14
+ * timeout and prints what did arrive. An `await` on a promise does neither.
15
+ * 3. **The message lands in the report.** `testInfo.attach` puts the subject, the
16
+ * headers, the extracted fields and the HTML body next to the failure — the
17
+ * difference between "the test failed" and "here is the mail that arrived instead".
18
+ * 4. **The wait ceiling follows the worker count.** The API refuses past twenty open
19
+ * waits per organization; the plugin knows `workerInfo`, a hand-written fixture does
20
+ * not.
21
+ *
22
+ * **One inbox per worker, not one per test — and that is a product decision, not a
23
+ * shortcut.** Every address ending in an inbox's domain arrives without being created
24
+ * first, so a sub-address per test isolates just as well as an inbox per test would, at
25
+ * no cost. Creating one per test would also walk straight into the inbox ceiling, which
26
+ * is one on the free plan and three on Solo: the isolation would work on a laptop and
27
+ * fail the first time somebody ran the suite on the plan they actually pay for.
28
+ */
29
+
30
+ import { test as base, expect } from '@playwright/test';
31
+ import { Facteur, FacteurTimeout, addressFor } from '@facteur-eu/sdk';
32
+
33
+ /** Characters that survive in the local part of an address, and read back on a screen. */
34
+ const slug = (text) =>
35
+ text
36
+ .toLowerCase()
37
+ .replace(/[^a-z0-9]+/g, '-')
38
+ .replace(/^-|-$/g, '')
39
+ .slice(0, 40);
40
+
41
+ /**
42
+ * The Playwright fixtures, and the object a test actually holds.
43
+ *
44
+ * `inbox` is per test even though the inbox itself is per worker: what the test gets is a
45
+ * view onto the shared inbox carrying *its* address, which is the thing that must not be
46
+ * shared.
47
+ */
48
+ export const test = base.extend({
49
+ /** The client, one per worker: it holds the wait queue, which is per process. */
50
+ facteur: [
51
+ async ({}, use, workerInfo) => {
52
+ const client = new Facteur({
53
+ /*
54
+ * Half the workers' ceiling, floored at one. Twenty waits is per *organization*,
55
+ * so every worker of every suite in that organization shares it — a client that
56
+ * spent it alone would push the refusal onto whoever started second.
57
+ */
58
+ maxConcurrentWaits: Math.max(1, Math.floor(16 / Math.max(1, workerInfo.config.workers))),
59
+ });
60
+ await use(client);
61
+ },
62
+ { scope: 'worker' },
63
+ ],
64
+
65
+ /**
66
+ * The inbox, opened once per worker and destroyed with it.
67
+ *
68
+ * `FACTEUR_INBOX` names an existing one, which is what a suite on a plan with a single
69
+ * inbox does — and what most suites end up doing, since an inbox is a stable address
70
+ * worth putting in a CI secret rather than a thing to create four times a minute.
71
+ */
72
+ facteurInbox: [
73
+ async ({ facteur }, use, workerInfo) => {
74
+ const existing = process.env.FACTEUR_INBOX;
75
+ if (existing) {
76
+ const inboxes = await facteur.inboxes.list();
77
+ const found = inboxes.find((one) => one.id === existing);
78
+ if (!found) {
79
+ throw new Error(
80
+ `FACTEUR_INBOX names ${existing}, which this key does not reach. Check the id on the inbox screen, or widen the key's workspaces.`,
81
+ );
82
+ }
83
+ await use(found);
84
+ return;
85
+ }
86
+
87
+ const opened = await facteur.inboxes.create({
88
+ name: `playwright w${workerInfo.workerIndex}`,
89
+ workspace: process.env.FACTEUR_WORKSPACE,
90
+ });
91
+
92
+ try {
93
+ await use(opened);
94
+ } finally {
95
+ /*
96
+ * Destroying is how an inbox is purged — there is no route that empties one. It
97
+ * is also free: an operation is the message received, never the call.
98
+ */
99
+ await facteur.inboxes.delete(opened.id).catch(() => {});
100
+ }
101
+ },
102
+ { scope: 'worker' },
103
+ ],
104
+
105
+ /**
106
+ * What a test holds: the inbox, plus an address that belongs to this test alone.
107
+ *
108
+ * The tag carries the worker, the retry and the title. The retry matters more than it
109
+ * looks: without it a retried test reads the mail its own first attempt received, and
110
+ * passes for the wrong reason exactly when something is already flaky.
111
+ */
112
+ inbox: async ({ facteur, facteurInbox }, use, testInfo) => {
113
+ const tag = `${slug(testInfo.title)}-w${testInfo.workerIndex}r${testInfo.retry}-${Date.now().toString(36)}`;
114
+ const startedAt = Date.now();
115
+
116
+ /**
117
+ * How long to hold, when the caller does not say: whatever is left of the test's own
118
+ * timeout, less two seconds to fail inside it.
119
+ *
120
+ * This is the difference between two failures. Held for a fixed thirty seconds inside
121
+ * a ninety-second test, a missing mail reads as a passing wait followed by a failed
122
+ * assertion; held past the test's timeout, Playwright kills the test and prints its
123
+ * own message about a slow test. Neither says the mail never came. Ending two seconds
124
+ * early means the plugin's diagnostic — what did arrive instead — is the last thing
125
+ * written, which is the only one worth reading.
126
+ *
127
+ * `testInfo.timeout` is `0` when timeouts are disabled, and the SDK's own default
128
+ * applies then: an unbounded wait would hang a suite on a mail that is never sent.
129
+ */
130
+ const remainingWait = () => {
131
+ if (!testInfo.timeout) return undefined;
132
+ const left = testInfo.timeout - (Date.now() - startedAt) - 2_000;
133
+ return Math.max(1_000, Math.min(left, 300_000));
134
+ };
135
+
136
+ await use({
137
+ id: facteurInbox.id,
138
+ domain: facteurInbox.domain,
139
+ tag,
140
+ address: (local = 'test') => addressFor(facteurInbox, tag, { local }),
141
+
142
+ async waitFor(criteria = {}) {
143
+ const message = await facteur.messages.waitFor({
144
+ inbox: facteurInbox.id,
145
+ sentTo: tag,
146
+ wait: remainingWait(),
147
+ ...criteria,
148
+ });
149
+ await attach(testInfo, message);
150
+ return message;
151
+ },
152
+
153
+ async messages() {
154
+ return facteur.inboxes.messages(facteurInbox.id);
155
+ },
156
+ });
157
+ },
158
+ });
159
+
160
+ /**
161
+ * The message, in the HTML report.
162
+ *
163
+ * Two attachments rather than one: the JSON is what a developer reads for the extracted
164
+ * fields, and the HTML body is what they open to see what the customer would have seen.
165
+ * Both are named after the test, so a failure with three mails in it stays readable.
166
+ */
167
+ async function attach(testInfo, message) {
168
+ await testInfo.attach(`facteur-${message.id}.json`, {
169
+ contentType: 'application/json',
170
+ body: Buffer.from(JSON.stringify(message, null, 2)),
171
+ });
172
+
173
+ if (message.html?.body) {
174
+ await testInfo.attach(`facteur-${message.id}.html`, {
175
+ contentType: 'text/html',
176
+ body: Buffer.from(message.html.body),
177
+ });
178
+ }
179
+ }
180
+
181
+ /** What a failed match should say, given what the inbox actually holds. */
182
+ function describe(messages) {
183
+ if (!messages.length) return 'nothing arrived in that inbox during the wait';
184
+ return messages
185
+ .slice(0, 5)
186
+ .map((one) => `${one.to} · ${one.subject ?? 'no subject'} (${one.status})`)
187
+ .join('; ');
188
+ }
189
+
190
+ expect.extend({
191
+ /**
192
+ * `await expect(inbox).toReceiveEmail({ subject: /code/ })`.
193
+ *
194
+ * The wait is the server's, so this does not poll: it hands the criteria over and the
195
+ * connection answers the moment a message matches. What Playwright adds is the failure
196
+ * message and the timeout the test already carries.
197
+ */
198
+ async toReceiveEmail(inbox, criteria = {}) {
199
+ try {
200
+ const message = await inbox.waitFor(criteria);
201
+ this.received = message;
202
+ return {
203
+ pass: true,
204
+ message: () => `expected no message matching ${JSON.stringify(criteria)}, one arrived`,
205
+ name: 'toReceiveEmail',
206
+ };
207
+ } catch (error) {
208
+ if (!(error instanceof FacteurTimeout)) throw error;
209
+ const arrived = describe(error.arrived ?? []);
210
+ return {
211
+ pass: false,
212
+ name: 'toReceiveEmail',
213
+ message: () =>
214
+ [
215
+ `No message matched ${JSON.stringify(criteria)} at ${inbox.address()}.`,
216
+ `Waited ${Math.round((error.waitedMs ?? 0) / 1000)}s. What did arrive: ${arrived}.`,
217
+ ].join('\n'),
218
+ };
219
+ }
220
+ },
221
+
222
+ /**
223
+ * `expect(message).toHaveOtp()` — and the reason it is a matcher rather than a field
224
+ * read: an unparsed message has no `otp`, and asserting on `undefined` cannot tell
225
+ * "there is no code in this mail" from "the code is not extracted yet".
226
+ */
227
+ toHaveOtp(message, expected) {
228
+ if (message.status !== 'parsed') {
229
+ return {
230
+ pass: false,
231
+ name: 'toHaveOtp',
232
+ message: () =>
233
+ `the message is ${message.status}, so nothing derived from its body is populated yet — read status before any extracted field`,
234
+ };
235
+ }
236
+
237
+ const pass = expected === undefined ? Boolean(message.otp) : message.otp === expected;
238
+ return {
239
+ pass,
240
+ name: 'toHaveOtp',
241
+ message: () =>
242
+ expected === undefined
243
+ ? `expected a one-time code, the message carries ${message.otp ?? 'none'}`
244
+ : `expected the code ${expected}, the message carries ${message.otp ?? 'none'}`,
245
+ };
246
+ },
247
+
248
+ /** `expect(message).toHaveLinkTo('app.example.com')` — host, or any part of the URL. */
249
+ toHaveLinkTo(message, fragment) {
250
+ const links = (message.links ?? []).map((link) => link.href ?? link.url ?? '');
251
+ const pass = links.some((href) => String(href).includes(fragment));
252
+ return {
253
+ pass,
254
+ name: 'toHaveLinkTo',
255
+ message: () =>
256
+ `expected a link containing ${fragment}, the message carries ${links.length ? links.join(', ') : 'no link'}`,
257
+ };
258
+ },
259
+
260
+ /** `expect(message).toHaveAttachment('invoice.pdf')` — a real one; a signature image is not. */
261
+ toHaveAttachment(message, fileName) {
262
+ const names = (message.attachments ?? []).map((one) => one.fileName);
263
+ const pass = fileName === undefined ? names.length > 0 : names.includes(fileName);
264
+ return {
265
+ pass,
266
+ name: 'toHaveAttachment',
267
+ message: () =>
268
+ `expected ${fileName ?? 'an attachment'}, the message carries ${names.length ? names.join(', ') : 'none'} (inline images are never counted)`,
269
+ };
270
+ },
271
+ });
272
+
273
+ export { expect };
274
+ export { FacteurTimeout } from '@facteur-eu/sdk';
package/package.json CHANGED
@@ -1,7 +1,51 @@
1
1
  {
2
2
  "name": "playwright-facteur",
3
- "version": "0.0.0",
4
- "description": "Reserved. The first release is coming shortly.",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "Receive email in your Playwright tests: a fixture that waits, matchers that assert, and the message attached to the report",
5
6
  "license": "MIT",
6
- "files": ["README.md"]
7
+ "keywords": [
8
+ "playwright",
9
+ "email testing",
10
+ "e2e",
11
+ "otp",
12
+ "2fa",
13
+ "qa",
14
+ "test automation",
15
+ "fixture"
16
+ ],
17
+ "engines": {
18
+ "node": ">=20"
19
+ },
20
+ "exports": {
21
+ ".": {
22
+ "types": "./index.d.mts",
23
+ "default": "./index.mjs"
24
+ }
25
+ },
26
+ "files": [
27
+ "index.mjs",
28
+ "index.d.mts",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
32
+ "dependencies": {
33
+ "@facteur-eu/sdk": "^1.0.0"
34
+ },
35
+ "peerDependencies": {
36
+ "@playwright/test": ">=1.40.0"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/facteur-eu/facteur.git",
41
+ "directory": "packages/playwright-facteur"
42
+ },
43
+ "homepage": "https://facteur.eu",
44
+ "bugs": {
45
+ "url": "https://github.com/facteur-eu/facteur/issues"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public",
49
+ "provenance": true
50
+ }
7
51
  }