@plune-ai/playwright 0.7.5 → 0.8.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/README.md CHANGED
@@ -162,6 +162,136 @@ test('rejects a negative quantity', { annotation: { type: 'PluneId', description
162
162
  A result whose test matches no case is **not** sent and **not** invented — a made-up id would
163
163
  write into somebody else's history. The run summary says how many there were.
164
164
 
165
+ ## What the browser reported: console errors, page errors, failed and slow requests
166
+
167
+ Import `test` from the fixture entry instead of `@playwright/test`, and each test that opens a browser
168
+ collects what its browser context reported:
169
+
170
+ ```ts
171
+ import { test, expect } from '@plune-ai/playwright/fixture';
172
+ ```
173
+
174
+ A project that already has its own `test` merges the fixtures in, either way:
175
+
176
+ ```ts
177
+ import { mergeTests } from '@playwright/test';
178
+ import { test as findings } from '@plune-ai/playwright/fixture';
179
+ export const test = mergeTests(myTest, findings); // Playwright 1.39 and later
180
+
181
+ import { findingsFixtures } from '@plune-ai/playwright/fixture';
182
+ export const test = myTest.extend(findingsFixtures);
183
+ ```
184
+
185
+ What is collected:
186
+
187
+ | Kind | When | What is kept |
188
+ | --- | --- | --- |
189
+ | `console` | a `console.error` in a page | the text |
190
+ | `page_error` | an uncaught error in a page | the error's message |
191
+ | `request_failed` | an answer with status 400 or above, or no answer at all | method, path, the status and the duration when there was an answer |
192
+ | `request_slow` | an answer under 400 that took the threshold or longer | method, path, status, duration |
193
+
194
+ Three options, set as any Playwright option (`use` in the config, or `test.use` in a file):
195
+
196
+ | Option | Default | Meaning |
197
+ | --- | --- | --- |
198
+ | `pluneFindings` | `true` | `false` turns the collection off |
199
+ | `pluneSlowRequestMs` | `3000` | how long a request takes, in milliseconds, before it is slow |
200
+ | `pluneSecretEnv` | `[]` | names of environment variables whose values are masked in every text and path; see below |
201
+
202
+ What is never read from a request or a response: headers, bodies, cookies, post data. A request's own
203
+ address is cut to its path before it leaves the test process (`https://shop.example/api/cart?token=…`
204
+ is kept as `/api/cart`). Only `http:` and `https:` requests count. A test keeps its first 20 findings by time
205
+ and counts the rest.
206
+
207
+ **An address written into a text** (a console line, an error message) is cut too, by its shape. The text is
208
+ read word by word, a word being a run of characters with no space, quote (`"`, `'`, `` ` ``) or angle bracket
209
+ in it, and in each word:
210
+
211
+ 1. a `?` followed by a name and `=` cuts the word there; a name is letters, digits, `_`, `-`, `.`, `[`, `]`
212
+ and `%` (`?id=`, `?user-id=`, `?ids[]=`) (`api.example/y?id=5` is kept as `api.example/y`,
213
+ `localhost:3000/a?x=1` as `localhost:3000/a`, `./api?x=1` as `./api`);
214
+ 2. after `http://`, `https://`, `ws://` or `wss://` the word is cut at the first `?` or `#`, and a user and
215
+ password before the host are removed (`GET https://api.example/y?email=… failed` is kept as
216
+ `GET https://api.example/y failed`);
217
+ 3. after a `/`, `./` or `../` that starts the word (or follows `(`, `[`, `{`, `=`, `:`, `,` or `;`) the word is
218
+ cut at the first `?` or `#` (`/cb#access_token=…` is kept as `/cb`).
219
+
220
+ What is cut is removed, not masked. Two limits of a rule by shape: a value that holds a raw space, quote or
221
+ angle bracket ends the word there, and what follows it is kept (`/search?q=anna smith` is kept as
222
+ `/search smith`); and on an address with no scheme and no leading slash, a query with no `name=`
223
+ (`api.example/y?abc`) or a fragment (`api.example/y#token`) is not recognised and is kept. The cut runs to the
224
+ end of the word, so punctuation right after an address goes with it. Only the first 4000 characters of a text
225
+ are read, without the word that limit falls inside (a text of one word longer than that is not sent, only
226
+ counted), and the result is cut to 300.
227
+
228
+ Two things are told by Chromium's wording, and hold for Chromium only. A request the page itself aborted (a
229
+ navigation away) is not reported as failed when its error is `net::ERR_ABORTED`; another browser words a
230
+ cancelled request differently, and there it may be reported as failed. And the console line Chromium prints for
231
+ every failed request, «Failed to load resource: …», is dropped because the request is already there; another
232
+ browser's line of the same kind is kept as a console finding.
233
+
234
+ The fixture needs Playwright 1.38 or later for the events it listens to (`weberror` is the newest); this
235
+ package asks for 1.44 or later anyway.
236
+
237
+ **What is masked, and what is not.** A console text, an error message and a path go through the masking the
238
+ code snapshot uses, before they leave the test process; a text is masked with its line breaks still in it,
239
+ then its addresses are cut, then its lines are joined. It replaces with a `‹…›` marker:
240
+
241
+ - a value with a well-known form: a GitHub token (`ghp_…`, `github_pat_…`), a key starting `sk-`,
242
+ `sk_live_…` or `rk_test_…`, an npm token (`npm_…`), a Google key (`AIza…`), a Plune token (`plune_…`), an AWS
243
+ access key id (`AKIA…`), a Slack token (`xox…`), a JWT, a private key block;
244
+ - the value after `Bearer`, and after `Basic` or `Token` when it looks encoded;
245
+ - a quoted value given to a name that says credential (`password = '…'`, `apiKey: "…"`, `setToken('…')`);
246
+ - the value of a parameter whose name says credential (`?token=…`, `&api_key=…`, `&session=…`), where the
247
+ address around it was not recognised and cut as above;
248
+ - the value of an `Authorization`, `Cookie` or `…session…` header written at the start of a line
249
+ (`Cookie: sid=…` on a line of its own; not one in the middle of a sentence);
250
+ - the user and password of an address (`https://user:pass@host`), and the value of a `PLUNE_…=` variable.
251
+
252
+ Nothing else is by its form. A password, a key of a form not listed, a personal detail or a customer's data
253
+ that a page writes to its console as plain words (`login failed for anna@example.com with hunter2`) is sent as
254
+ written, and so is an identifier in a path (`/reset/8f3a9c…`). A page that logs such things needs
255
+ `pluneFindings: false` for those tests, a fix in the page, or, for a secret your tests hold in an environment
256
+ variable, its name in `pluneSecretEnv`.
257
+
258
+ **Secrets you name: `pluneSecretEnv`.** The option takes the names of environment variables, never their
259
+ values: an option can be read by any reporter and end up in a report, and a name gives nothing away.
260
+
261
+ ```ts
262
+ // playwright.config.ts
263
+ use: { pluneSecretEnv: ['SHOP_PASSWORD', 'SHOP_API_KEY'] },
264
+ ```
265
+
266
+ When a test's browser opens, the fixture reads each variable in the test process, and from then on every
267
+ occurrence of its value in a console text, an error message or a request's path is replaced by `‹env-secret›`,
268
+ before anything else is done to the text (so before it is cut to 300 characters) and before the attachment is
269
+ written. What is recognised is the exact value, and the value as an address carries it (the results of
270
+ `encodeURIComponent` and of `encodeURI`). Its limits:
271
+
272
+ - a value under 4 characters is not masked: replacing every `123` would shred a text and hide nothing;
273
+ - a variable that is not set, or is empty, is skipped without a word;
274
+ - a value the page changed in any other way is another string and is not recognised: base64, a hash, another
275
+ letter case, percent escapes written in lower case, a value split over two lines;
276
+ - a path that a marker makes longer than 300 characters is not sent, only counted.
277
+
278
+ A test that opens no browser context collects nothing, and no browser is opened for it. A context a test
279
+ makes itself with `browser.newContext()` is not listened to. The fixture never fails a test and does not wait
280
+ at its end for an answer still arriving: a response that had not finished when the test ended is not reported.
281
+
282
+ The findings travel as one attachment of the test, `plune-findings` (`application/plune.findings+json`).
283
+ It is an attachment like any other, so it is also in Playwright's own HTML, JSON and blob reports and in a
284
+ trace, **for a passing test too**. It holds what is described above and nothing more: for each finding its
285
+ kind, the cleaned text or the method, path, status and duration, and the time it happened; and the count of
286
+ what was left out.
287
+
288
+ The reporter reads it and sends the findings with the result of that attempt, each with the top-level
289
+ `test.step` it happened in, **only when the attempt did not pass**: Plune shows them under a failure. The
290
+ attachment itself is not uploaded as a file of the result and is not listed among the failure's artifacts.
291
+ A Plune that does not know the field yet (an older self-hosted one) refuses the batch once; the reporter
292
+ sends it again without the findings, says so in one line, and sends none for the rest of the run. No result
293
+ is lost to it.
294
+
165
295
  ## Screenshots
166
296
 
167
297
  Every screenshot a test keeps as a file — Playwright's `screenshot` option, `testInfo.attach` with a
@@ -0,0 +1,371 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/fixture.ts
31
+ var fixture_exports = {};
32
+ __export(fixture_exports, {
33
+ expect: () => import_test.expect,
34
+ findingsFixtures: () => findingsFixtures,
35
+ test: () => test
36
+ });
37
+ module.exports = __toCommonJS(fixture_exports);
38
+ var import_test = require("@playwright/test");
39
+
40
+ // src/findings.ts
41
+ var import_node_util = require("util");
42
+
43
+ // ../../dist/reporter-core.js
44
+ var import_util = require("util");
45
+ var import_http = require("http");
46
+ var import_https = require("https");
47
+ var path2 = __toESM(require("path"), 1);
48
+ var POOLS = { "http:": new import_http.Agent({ keepAlive: true }), "https:": new import_https.Agent({ keepAlive: true }) };
49
+ var HEADLINE_LIMIT = 8 * 1024;
50
+ var DIRECT_BATCH_BYTES = 6 * 1024 * 1024;
51
+ var DEFAULT_FALLBACK_PATH = path2.join(".plune", "pending-results.jsonl");
52
+ var BEFORE_REGEX = /* @__PURE__ */ new Set([..."(,=:[!&|?{};+-*%<>~^"]);
53
+ var CREDENTIAL = "password|passphrase|passwd|pass|pwd|token|secret|api[-_]?key|private[-_]?key|credential|auth|session|cookie";
54
+ var LITERAL = String.raw`(?<q>['"\x60])(?:\\.|(?!\k<q>)[^\\\n])*\k<q>`;
55
+ var TYPING = "(?:fill|type|pressSequentially)";
56
+ var SHAPES = [
57
+ { kind: "github-token", re: /\b(?:ghp|gho|ghs|ghu)_[A-Za-z0-9]{36}\b|\bgithub_pat_\w{20,}/g },
58
+ { kind: "api-key", re: /\bsk-[\w-]{20,}/g },
59
+ { kind: "api-key", re: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{10,}/g },
60
+ { kind: "npm-token", re: /\bnpm_[A-Za-z0-9]{20,}/g },
61
+ { kind: "google-key", re: /\bAIza[\w-]{30,}/g },
62
+ { kind: "plune-token", re: /\bplune_[A-Za-z0-9_]{16,}/g },
63
+ { kind: "aws-key", re: /\bAKIA[0-9A-Z]{16}\b/g },
64
+ { kind: "slack-token", re: /\bxox[abprs]-[A-Za-z0-9-]{10,}/g },
65
+ {
66
+ kind: "private-key",
67
+ re: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g
68
+ },
69
+ { kind: "jwt", re: /\beyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,}/g }
70
+ ];
71
+ var PLACES = [
72
+ // `password = '…'`, `apiKey: "…"`, `'x-api-key': '…'`
73
+ new RegExp(
74
+ String.raw`(?<lead>\b(?<role>[\w$-]*(?:${CREDENTIAL})[\w$-]*)['"]?\s*[:=]\s*)${LITERAL}`,
75
+ "gi"
76
+ ),
77
+ // `setToken('…')`: the call is named for a credential
78
+ new RegExp(String.raw`(?<lead>\b(?<role>[\w$]*(?:${CREDENTIAL})[\w$]*)\s*\(\s*)${LITERAL}`, "gi"),
79
+ // `.fill('#password', '…')`, `.type('#pwd', '…')`: the field is named in the same call
80
+ new RegExp(
81
+ String.raw`(?<lead>\.${TYPING}\(\s*['"][^'"\n]*?(?<role>${CREDENTIAL})[^'"\n]*['"]\s*,\s*)${LITERAL}`,
82
+ "gi"
83
+ ),
84
+ // `getByLabel('Password').fill('…')`, `getByRole('textbox', { name: 'Password' }).type('…')`: … or
85
+ // anywhere in the call the typing is chained off
86
+ new RegExp(
87
+ String.raw`(?<lead>\([^()\n]*?(?<role>${CREDENTIAL})[^()\n]*\)\s*\.${TYPING}\(\s*)${LITERAL}`,
88
+ "gi"
89
+ ),
90
+ // `{ name: 'session', value: '…' }`: a cookie (or any name/value pair) named for a credential
91
+ new RegExp(
92
+ String.raw`(?<lead>\bname\s*:\s*['"][^'"\n]*?(?<role>${CREDENTIAL})[^'"\n]*['"]\s*,\s*value\s*:\s*)${LITERAL}`,
93
+ "gi"
94
+ )
95
+ ];
96
+ var HEADER_LINE = /((?:^|\\[nr]|\x60)[ \t>*<+-]*['"]?)((?:proxy-)?authorization|(?:set-)?cookie|[\w-]*session[\w-]*)(['"]?[ \t]*:[ \t]*)(?![\w$.]+(?:\([^()\n]*\))?[ \t]*[,;)}\]])[^\s'"\x60\\][^\r\n'"\x60\\]*/gim;
97
+ var QUERY_PARAM = /([?&][\w.-]*(?:token|key|secret|password|passwd|pass|pwd|auth|signature|sig|credential|session)[\w.-]*=)(?!‹)[^&#\s'"\x60]+/gi;
98
+ function maskCredentials(text) {
99
+ let out = text;
100
+ for (const { kind, re } of SHAPES) out = out.replace(re, `\u2039${kind}\u203A`);
101
+ for (const re of PLACES) {
102
+ out = out.replace(re, (...args) => {
103
+ const groups = args.at(-1);
104
+ return `${groups.lead}${groups.q}\u2039${groups.role.toLowerCase().replace(/^[^a-z]+/, "")}\u203A${groups.q}`;
105
+ });
106
+ }
107
+ return out.replace(HEADER_LINE, "$1$2$3\u2039header\u203A").replace(/\b(Bearer)([ \t]+)(?!‹)[\w.~+/=-]{8,}/g, "$1$2\u2039credential\u203A").replace(
108
+ /\b(Basic|Token)([ \t]+)(?!‹)(?=[\w.~+/=-]*[\d=+/]|[\w.~+/=-]*[a-z][\w.~+/=-]*[A-Z])[\w.~+/=-]{8,}/g,
109
+ "$1$2\u2039credential\u203A"
110
+ ).replace(/\b(PLUNE_[A-Z0-9_]*=)(?!‹)[^\s'"\x60;,)]+/g, "$1\u2039env-secret\u203A").replace(QUERY_PARAM, "$1\u2039credential\u203A").replace(/\b([a-z][\w+.-]*:\/\/)[^\s/@'"\x60]+@/gi, "$1\u2039credential\u203A@");
111
+ }
112
+ var SCREENSHOT_BYTES = 2 * 1024 * 1024;
113
+ var SCREENSHOTS_PER_RESULT = 20;
114
+ var TEXT_BYTES = 512 * 1024;
115
+ var TEXTS_PER_RESULT = 10;
116
+ var UTF8 = new import_util.TextDecoder("utf-8", { fatal: true });
117
+ var SKIPPED = {
118
+ hidden: "its name starts with an underscore, which hides an attachment in Playwright's own reports too",
119
+ type: "Plune takes PNG, JPEG and WebP",
120
+ limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
121
+ missing: "the file cannot be read on this machine",
122
+ size: "Plune takes a file of at most 2 MB",
123
+ textLimit: `a result holds at most ${TEXTS_PER_RESULT} text files`,
124
+ textSize: "Plune takes a text file of at most 512 KiB",
125
+ empty: "the file is empty",
126
+ binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
127
+ encoding: "Plune takes UTF-8 text only",
128
+ noStorage: "no storage bucket is connected to this project"
129
+ };
130
+ var BATCH_BYTES = 8 * 1024 * 1024;
131
+ var ENVELOPE_BYTES = Buffer.byteLength(JSON.stringify({ results: [] }));
132
+
133
+ // src/findings.ts
134
+ var FINDINGS_TYPE = "application/plune.findings+json";
135
+ var FINDINGS_MAX = 20;
136
+ var OMITTED_MAX = 1e5;
137
+ var TEXT_MAX = 300;
138
+ var METHOD = /^[A-Z]{1,16}$/;
139
+ var PATH = /^\/(?!\/)[^?#]*$/;
140
+ function clip(text, max = TEXT_MAX) {
141
+ const cut = text.slice(0, max);
142
+ return /[\ud800-\udbff]$/.test(cut) ? cut.slice(0, -1) : cut;
143
+ }
144
+ var WORK_MAX = 4e3;
145
+ var SEPARATORS = String.raw`\s"'\x60<>`;
146
+ var SEPARATOR = new RegExp(`[${SEPARATORS}]`);
147
+ var TOKEN = new RegExp(`[^${SEPARATORS}]+`, "g");
148
+ var SCHEME = /(?:https?|wss?):\/\//i;
149
+ var PATH_START = /(?:^|[(\[{=:,;])\.{0,2}\//;
150
+ var NAMED_QUERY = /\?[\w\-.[\]%]+=/;
151
+ function markIn(token, from) {
152
+ const at = token.slice(from).search(/[?#]/);
153
+ return at === -1 ? token.length : from + at;
154
+ }
155
+ function withoutQuery(token) {
156
+ const named = token.search(NAMED_QUERY);
157
+ let out = named === -1 ? token : token.slice(0, named);
158
+ const scheme = SCHEME.exec(out);
159
+ if (scheme !== null) {
160
+ const from = scheme.index + scheme[0].length;
161
+ const rest = out.slice(from, markIn(out, from));
162
+ const slash = rest.indexOf("/");
163
+ const user = rest.lastIndexOf("@", slash === -1 ? rest.length : slash);
164
+ return out.slice(0, from) + rest.slice(user + 1);
165
+ }
166
+ const path = PATH_START.exec(out);
167
+ if (path !== null) out = out.slice(0, markIn(out, path.index));
168
+ return out;
169
+ }
170
+ var SECRET_MARK = "\u2039env-secret\u203A";
171
+ var SECRET_MIN = 4;
172
+ function secretValues(names, env = process.env) {
173
+ const forms = /* @__PURE__ */ new Set();
174
+ for (const name of Array.isArray(names) ? names : []) {
175
+ const value = typeof name === "string" ? env[name] : void 0;
176
+ if (value === void 0 || value.length < SECRET_MIN) continue;
177
+ forms.add(value);
178
+ for (const encode of [encodeURIComponent, encodeURI]) {
179
+ try {
180
+ forms.add(encode(value));
181
+ } catch {
182
+ }
183
+ }
184
+ }
185
+ return [...forms].sort((a, b) => b.length - a.length);
186
+ }
187
+ function withoutSecrets(text, secrets) {
188
+ let out = text;
189
+ for (const secret of secrets) out = out.split(secret).join(SECRET_MARK);
190
+ return out;
191
+ }
192
+ function cleaned(raw, secrets) {
193
+ const window = raw.slice(0, WORK_MAX + (secrets[0]?.length ?? 0));
194
+ const text = withoutSecrets(window, secrets);
195
+ let head = clip(text, WORK_MAX);
196
+ const next = text.length > head.length ? text[head.length] : raw[window.length];
197
+ if (next !== void 0 && !SEPARATOR.test(next)) {
198
+ let end = head.length;
199
+ while (end > 0 && !SEPARATOR.test(head[end - 1])) end -= 1;
200
+ head = head.slice(0, end);
201
+ }
202
+ const masked = maskCredentials((0, import_node_util.stripVTControlCharacters)(head));
203
+ const flat = masked.replace(TOKEN, withoutQuery).replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ");
204
+ return clip(flat.trim());
205
+ }
206
+ function createCollector(slowMs, secrets = []) {
207
+ let items = [];
208
+ let omitted = 0;
209
+ const drop = () => {
210
+ omitted = Math.min(OMITTED_MAX, omitted + 1);
211
+ };
212
+ const keep = (finding) => {
213
+ items.push(finding);
214
+ items.sort((a, b) => a.at - b.at);
215
+ if (items.length > FINDINGS_MAX) {
216
+ items = items.slice(0, FINDINGS_MAX);
217
+ drop();
218
+ }
219
+ };
220
+ const text = (kind, raw, at) => {
221
+ const clean = cleaned(String(raw), secrets);
222
+ if (clean === "") drop();
223
+ else keep({ kind, text: clean, at });
224
+ };
225
+ const place = (url, rawMethod) => {
226
+ let parsed;
227
+ try {
228
+ parsed = new URL(url);
229
+ } catch {
230
+ return null;
231
+ }
232
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
233
+ const method = String(rawMethod).toUpperCase();
234
+ const path = maskCredentials(withoutSecrets(parsed.pathname, secrets));
235
+ return METHOD.test(method) && PATH.test(path) && path.length <= TEXT_MAX ? { method, path } : void 0;
236
+ };
237
+ const request = (kind, seen, extra) => {
238
+ const where = place(seen.url, seen.method);
239
+ if (where === null) return;
240
+ if (where === void 0) drop();
241
+ else keep({ kind, ...where, ...extra, at: seen.at });
242
+ };
243
+ return {
244
+ console(raw, at) {
245
+ if (String(raw).startsWith("Failed to load resource:")) return;
246
+ text("console", raw, at);
247
+ },
248
+ pageError(message, at) {
249
+ text("page_error", message, at);
250
+ },
251
+ response({ status, durationMs, ...seen }) {
252
+ const ms = Number.isFinite(durationMs) ? Math.max(0, Math.round(durationMs)) : void 0;
253
+ const extra = {
254
+ ...Number.isInteger(status) && status >= 100 && status <= 599 ? { status } : {},
255
+ ...ms !== void 0 ? { durationMs: ms } : {}
256
+ };
257
+ if (status >= 400) request("request_failed", seen, extra);
258
+ else if (ms !== void 0 && ms >= slowMs) request("request_slow", seen, extra);
259
+ },
260
+ failed({ errorText, ...seen }) {
261
+ if (errorText?.includes("net::ERR_ABORTED") === true) return;
262
+ request("request_failed", seen, {});
263
+ },
264
+ result() {
265
+ return { items: [...items], omitted };
266
+ }
267
+ };
268
+ }
269
+ function watch(context, slowMs, secrets = []) {
270
+ const collector = createCollector(slowMs, secrets);
271
+ const started = /* @__PURE__ */ new WeakMap();
272
+ const settled = /* @__PURE__ */ new WeakSet();
273
+ const startOf = (request) => {
274
+ const own = request.timing().startTime;
275
+ return own > 0 ? own : started.get(request) ?? Date.now();
276
+ };
277
+ const once = (request) => {
278
+ if (settled.has(request)) return false;
279
+ settled.add(request);
280
+ return true;
281
+ };
282
+ const quiet = (listener) => (arg) => {
283
+ try {
284
+ void Promise.resolve(listener(arg)).catch(() => void 0);
285
+ } catch {
286
+ }
287
+ };
288
+ try {
289
+ context.on(
290
+ "console",
291
+ quiet((message) => {
292
+ if (message.type() === "error") collector.console(message.text(), Date.now());
293
+ })
294
+ );
295
+ context.on(
296
+ "weberror",
297
+ quiet(
298
+ (webError) => collector.pageError(webError.error().message, Date.now())
299
+ )
300
+ );
301
+ context.on(
302
+ "request",
303
+ quiet((request) => {
304
+ started.set(request, Date.now());
305
+ })
306
+ );
307
+ context.on(
308
+ "requestfailed",
309
+ quiet((request) => {
310
+ if (!once(request)) return;
311
+ const errorText = request.failure()?.errorText;
312
+ collector.failed({
313
+ url: request.url(),
314
+ method: request.method(),
315
+ at: startOf(request),
316
+ ...errorText !== void 0 ? { errorText } : {}
317
+ });
318
+ })
319
+ );
320
+ context.on(
321
+ "response",
322
+ quiet(async (response) => {
323
+ const request = response.request();
324
+ await response.finished();
325
+ if (!once(request)) return;
326
+ const end = request.timing().responseEnd;
327
+ collector.response({
328
+ url: request.url(),
329
+ method: request.method(),
330
+ status: response.status(),
331
+ at: startOf(request),
332
+ durationMs: end >= 0 ? end : Date.now() - (started.get(request) ?? Date.now())
333
+ });
334
+ })
335
+ );
336
+ } catch {
337
+ }
338
+ return collector;
339
+ }
340
+
341
+ // src/fixture.ts
342
+ var SLOW_MS = 3e3;
343
+ var findingsFixtures = {
344
+ pluneFindings: [true, { option: true }],
345
+ pluneSlowRequestMs: [SLOW_MS, { option: true }],
346
+ pluneSecretEnv: [[], { option: true }],
347
+ context: async ({ context, pluneFindings, pluneSlowRequestMs, pluneSecretEnv }, use, testInfo) => {
348
+ const collector = pluneFindings ? watch(
349
+ context,
350
+ Number.isFinite(pluneSlowRequestMs) && pluneSlowRequestMs >= 0 ? pluneSlowRequestMs : SLOW_MS,
351
+ // Read when the test's browser opens: the values this worker has now.
352
+ secretValues(pluneSecretEnv)
353
+ ) : void 0;
354
+ await use(context);
355
+ if (collector === void 0) return;
356
+ try {
357
+ await testInfo.attach("plune-findings", {
358
+ body: JSON.stringify(collector.result()),
359
+ contentType: FINDINGS_TYPE
360
+ });
361
+ } catch {
362
+ }
363
+ }
364
+ };
365
+ var test = import_test.test.extend(findingsFixtures);
366
+ // Annotate the CommonJS export names for ESM import in node:
367
+ 0 && (module.exports = {
368
+ expect,
369
+ findingsFixtures,
370
+ test
371
+ });
@@ -0,0 +1,35 @@
1
+ import * as _playwright_test from '@playwright/test';
2
+ import { Fixtures, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions } from '@playwright/test';
3
+ export { expect } from '@playwright/test';
4
+
5
+ /**
6
+ * `@plune-ai/playwright/fixture` — collects what the browser reported during a test (console errors, page
7
+ * errors, failed and slow requests) and attaches it for the reporter.
8
+ *
9
+ * The one file of this package that imports `@playwright/test` at runtime, which is why it is an entry of
10
+ * its own: the reporter entry imports only its types.
11
+ */
12
+ interface PluneFindingsOptions {
13
+ /** Collect what the browser reports. On by default; `test.use({ pluneFindings: false })` turns it off. */
14
+ pluneFindings: boolean;
15
+ /** A request that took this long, in milliseconds, is reported as slow. Default 3000. */
16
+ pluneSlowRequestMs: number;
17
+ /**
18
+ * NAMES of environment variables whose values must never leave the test process: each value is replaced by
19
+ * `‹env-secret›` in every text and path. Names and not values on purpose: an option can be read by any
20
+ * reporter and written into a report; a name is safe there. Default none.
21
+ */
22
+ pluneSecretEnv: string[];
23
+ }
24
+ /**
25
+ * The fixture definitions, for a project that already has its own `test`: `base.extend(findingsFixtures)`,
26
+ * or `mergeTests` with the `test` below.
27
+ *
28
+ * `context` is overridden, not `page` wrapped in an automatic fixture: a test that asks for no browser gets
29
+ * none opened for it, and then attaches nothing — which reads as «not collected».
30
+ * A context a test opens itself with `browser.newContext()` is not this fixture and is not listened to.
31
+ */
32
+ declare const findingsFixtures: Fixtures<PluneFindingsOptions, object, PlaywrightTestArgs & PlaywrightTestOptions, PlaywrightWorkerArgs & PlaywrightWorkerOptions>;
33
+ declare const test: _playwright_test.TestType<PlaywrightTestArgs & PlaywrightTestOptions & PluneFindingsOptions, PlaywrightWorkerArgs & PlaywrightWorkerOptions>;
34
+
35
+ export { type PluneFindingsOptions, findingsFixtures, test };
@@ -0,0 +1,35 @@
1
+ import * as _playwright_test from '@playwright/test';
2
+ import { Fixtures, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions } from '@playwright/test';
3
+ export { expect } from '@playwright/test';
4
+
5
+ /**
6
+ * `@plune-ai/playwright/fixture` — collects what the browser reported during a test (console errors, page
7
+ * errors, failed and slow requests) and attaches it for the reporter.
8
+ *
9
+ * The one file of this package that imports `@playwright/test` at runtime, which is why it is an entry of
10
+ * its own: the reporter entry imports only its types.
11
+ */
12
+ interface PluneFindingsOptions {
13
+ /** Collect what the browser reports. On by default; `test.use({ pluneFindings: false })` turns it off. */
14
+ pluneFindings: boolean;
15
+ /** A request that took this long, in milliseconds, is reported as slow. Default 3000. */
16
+ pluneSlowRequestMs: number;
17
+ /**
18
+ * NAMES of environment variables whose values must never leave the test process: each value is replaced by
19
+ * `‹env-secret›` in every text and path. Names and not values on purpose: an option can be read by any
20
+ * reporter and written into a report; a name is safe there. Default none.
21
+ */
22
+ pluneSecretEnv: string[];
23
+ }
24
+ /**
25
+ * The fixture definitions, for a project that already has its own `test`: `base.extend(findingsFixtures)`,
26
+ * or `mergeTests` with the `test` below.
27
+ *
28
+ * `context` is overridden, not `page` wrapped in an automatic fixture: a test that asks for no browser gets
29
+ * none opened for it, and then attaches nothing — which reads as «not collected».
30
+ * A context a test opens itself with `browser.newContext()` is not this fixture and is not listened to.
31
+ */
32
+ declare const findingsFixtures: Fixtures<PluneFindingsOptions, object, PlaywrightTestArgs & PlaywrightTestOptions, PlaywrightWorkerArgs & PlaywrightWorkerOptions>;
33
+ declare const test: _playwright_test.TestType<PlaywrightTestArgs & PlaywrightTestOptions & PluneFindingsOptions, PlaywrightWorkerArgs & PlaywrightWorkerOptions>;
34
+
35
+ export { type PluneFindingsOptions, findingsFixtures, test };