@ralphralphai/playwright 0.1.0 → 1.1.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 +201 -0
- package/README.md +222 -268
- package/dist/index.cjs +23 -585
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +91 -52
- package/dist/index.mjs +17 -555
- package/dist/index.mjs.map +1 -1
- package/dist/reporter.cjs +169 -0
- package/dist/reporter.cjs.map +1 -0
- package/dist/reporter.d.cts +1 -0
- package/dist/reporter.d.mts +54 -0
- package/dist/reporter.mjs +167 -0
- package/dist/reporter.mjs.map +1 -0
- package/dist/upload-QZreR5i6.cjs +694 -0
- package/dist/upload-QZreR5i6.cjs.map +1 -0
- package/dist/upload-giSVxpun.mjs +592 -0
- package/dist/upload-giSVxpun.mjs.map +1 -0
- package/package.json +26 -16
package/dist/index.mjs
CHANGED
|
@@ -1,554 +1,6 @@
|
|
|
1
|
+
import { a as uploadRawGraph, c as Recorder, d as loadConfigSync, f as resolveMode, o as MANIFEST_ATTACHMENT, r as createRawGraphBundle, u as loadConfig } from "./upload-giSVxpun.mjs";
|
|
1
2
|
import path from "node:path";
|
|
2
3
|
import { expect, mergeTests, test as test$1 } from "@playwright/test";
|
|
3
|
-
import { readFileSync } from "node:fs";
|
|
4
|
-
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
5
|
-
import configPackage from "@ralphralphai/config/package.json" with { type: "json" };
|
|
6
|
-
import { WebRalphConfigSchema } from "@ralphralphai/config/zod";
|
|
7
|
-
import { parse, printParseErrorCode } from "jsonc-parser";
|
|
8
|
-
import { randomUUID } from "node:crypto";
|
|
9
|
-
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
10
|
-
import playwrightPackage from "@playwright/test/package.json" with { type: "json" };
|
|
11
|
-
import { promisify } from "node:util";
|
|
12
|
-
import { gzip } from "node:zlib";
|
|
13
|
-
import { pack } from "tar-stream";
|
|
14
|
-
//#region src/config.ts
|
|
15
|
-
function resolveMode(options) {
|
|
16
|
-
const mode = options.mode ?? process.env["RALPH_MODE"] ?? (process.env["RALPH_UPLOAD_KEY"] ? "upload" : "off");
|
|
17
|
-
if (mode === "off" || mode === "local" || mode === "upload") return mode;
|
|
18
|
-
throw new Error("RALPH_MODE must be off, local, or upload.");
|
|
19
|
-
}
|
|
20
|
-
async function loadConfig(options, root) {
|
|
21
|
-
const file = configFile(options, root);
|
|
22
|
-
return snapshot(options.config ?? parseConfig(await readFile(file, "utf8")));
|
|
23
|
-
}
|
|
24
|
-
function loadConfigSync(options, root) {
|
|
25
|
-
const file = configFile(options, root);
|
|
26
|
-
return snapshot(options.config ?? parseConfig(readFileSync(file, "utf8")));
|
|
27
|
-
}
|
|
28
|
-
function configFile(options, root) {
|
|
29
|
-
if (options.config && options.configPath) throw new Error("Provide either ralphOptions.config or configPath, not both.");
|
|
30
|
-
return path.resolve(root, options.configPath ?? "ralph.jsonc");
|
|
31
|
-
}
|
|
32
|
-
function parseConfig(text) {
|
|
33
|
-
const errors = [];
|
|
34
|
-
const value = parse(text, errors, { allowTrailingComma: true });
|
|
35
|
-
if (errors.length) throw new Error("Invalid Ralph config: " + errors.map((error) => printParseErrorCode(error.error) + " at " + error.offset).join(", "));
|
|
36
|
-
return value;
|
|
37
|
-
}
|
|
38
|
-
function snapshot(value) {
|
|
39
|
-
WebRalphConfigSchema.parse(value);
|
|
40
|
-
return {
|
|
41
|
-
config: JSON.parse(JSON.stringify(value)),
|
|
42
|
-
packageVersion: configPackage.version
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
//#endregion
|
|
46
|
-
//#region package.json
|
|
47
|
-
var version = "0.1.0";
|
|
48
|
-
//#endregion
|
|
49
|
-
//#region src/image.ts
|
|
50
|
-
/**
|
|
51
|
-
* Matches the crawler's full-page captures: lossless measured larger than this
|
|
52
|
-
* on real sites, which are mostly photographic content.
|
|
53
|
-
*/
|
|
54
|
-
const WEBP_QUALITY = 80;
|
|
55
|
-
async function takeScreenshot(page, deadline) {
|
|
56
|
-
const options = {
|
|
57
|
-
fullPage: true,
|
|
58
|
-
scale: "css"
|
|
59
|
-
};
|
|
60
|
-
const webp = await page.screenshot({
|
|
61
|
-
...options,
|
|
62
|
-
type: "webp",
|
|
63
|
-
quality: WEBP_QUALITY,
|
|
64
|
-
timeout: Math.max(1, deadline - Date.now())
|
|
65
|
-
});
|
|
66
|
-
if (webp.length > 0) return {
|
|
67
|
-
bytes: webp,
|
|
68
|
-
contentType: "image/webp",
|
|
69
|
-
...webpSize(webp)
|
|
70
|
-
};
|
|
71
|
-
const png = await page.screenshot({
|
|
72
|
-
...options,
|
|
73
|
-
type: "png",
|
|
74
|
-
timeout: Math.max(1, deadline - Date.now())
|
|
75
|
-
});
|
|
76
|
-
return {
|
|
77
|
-
bytes: png,
|
|
78
|
-
contentType: "image/png",
|
|
79
|
-
width: png.readUInt32BE(16),
|
|
80
|
-
height: png.readUInt32BE(20)
|
|
81
|
-
};
|
|
82
|
-
}
|
|
83
|
-
function imageExtension(contentType) {
|
|
84
|
-
return contentType === "image/png" ? ".png" : ".webp";
|
|
85
|
-
}
|
|
86
|
-
function webpSize(bytes) {
|
|
87
|
-
if (bytes.toString("ascii", 0, 4) !== "RIFF" || bytes.toString("ascii", 8, 12) !== "WEBP") throw new Error("The screenshot is not a WebP image.");
|
|
88
|
-
const chunk = bytes.toString("ascii", 12, 16);
|
|
89
|
-
if (chunk === "VP8X") return {
|
|
90
|
-
width: 1 + bytes.readUIntLE(24, 3),
|
|
91
|
-
height: 1 + bytes.readUIntLE(27, 3)
|
|
92
|
-
};
|
|
93
|
-
if (chunk === "VP8 ") return {
|
|
94
|
-
width: bytes.readUInt16LE(26) & 16383,
|
|
95
|
-
height: bytes.readUInt16LE(28) & 16383
|
|
96
|
-
};
|
|
97
|
-
if (chunk === "VP8L") {
|
|
98
|
-
const bits = bytes.readUInt32LE(21);
|
|
99
|
-
return {
|
|
100
|
-
width: 1 + (bits & 16383),
|
|
101
|
-
height: 1 + (bits >> 14 & 16383)
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
throw new Error("Unsupported WebP chunk: " + chunk);
|
|
105
|
-
}
|
|
106
|
-
//#endregion
|
|
107
|
-
//#region src/layout.ts
|
|
108
|
-
function readLayout(page) {
|
|
109
|
-
return page.locator("[data-track-id]").filter({ visible: true }).evaluateAll((elements) => ({
|
|
110
|
-
viewport: {
|
|
111
|
-
width: window.innerWidth,
|
|
112
|
-
height: window.innerHeight
|
|
113
|
-
},
|
|
114
|
-
document: {
|
|
115
|
-
width: Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth, document.body?.scrollWidth ?? 0),
|
|
116
|
-
height: Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight, document.body?.scrollHeight ?? 0)
|
|
117
|
-
},
|
|
118
|
-
scroll: {
|
|
119
|
-
x: window.scrollX,
|
|
120
|
-
y: window.scrollY
|
|
121
|
-
},
|
|
122
|
-
devicePixelRatio: window.devicePixelRatio,
|
|
123
|
-
trackedElements: elements.flatMap((element) => {
|
|
124
|
-
const trackId = element.getAttribute("data-track-id");
|
|
125
|
-
const rect = element.getBoundingClientRect();
|
|
126
|
-
if (!trackId || rect.width <= 0 || rect.height <= 0 || rect.right <= 0 || rect.left >= window.innerWidth) return [];
|
|
127
|
-
return [{
|
|
128
|
-
trackId,
|
|
129
|
-
x: rect.x + window.scrollX,
|
|
130
|
-
y: rect.y + window.scrollY,
|
|
131
|
-
width: rect.width,
|
|
132
|
-
height: rect.height
|
|
133
|
-
}];
|
|
134
|
-
})
|
|
135
|
-
}));
|
|
136
|
-
}
|
|
137
|
-
//#endregion
|
|
138
|
-
//#region src/upload.ts
|
|
139
|
-
function resolveUploadOptions(options) {
|
|
140
|
-
const uploadKey = process.env["RALPH_UPLOAD_KEY"];
|
|
141
|
-
const apiUrl = options.apiUrl ?? process.env["RALPH_API_URL"];
|
|
142
|
-
const appId = options.appId ?? process.env["RALPH_APP_ID"];
|
|
143
|
-
if (!uploadKey || !apiUrl || !appId) throw new Error("Ralph upload requires RALPH_UPLOAD_KEY, RALPH_API_URL (or ralphOptions.apiUrl), and RALPH_APP_ID (or ralphOptions.appId).");
|
|
144
|
-
return {
|
|
145
|
-
uploadKey,
|
|
146
|
-
apiUrl,
|
|
147
|
-
appId,
|
|
148
|
-
timeoutMs: options.uploadTimeoutMs
|
|
149
|
-
};
|
|
150
|
-
}
|
|
151
|
-
const CAPTURE_BUNDLE_INDEX = "capture.json";
|
|
152
|
-
const CAPTURE_BUNDLE_IMAGE_DIR = "assets/images";
|
|
153
|
-
/**
|
|
154
|
-
* Packs the manifest and screenshots into a gzipped tar archive:
|
|
155
|
-
*
|
|
156
|
-
* capture.json { manifest, screenshots: [{ nodeId, path }] }
|
|
157
|
-
* assets/images/<id>.webp raw screenshot bytes (.png when too large for WebP)
|
|
158
|
-
*/
|
|
159
|
-
async function createCaptureBundle(manifest, screenshots) {
|
|
160
|
-
if (Buffer.byteLength(JSON.stringify(manifest)) > 2097152 || screenshots.length > 500 || screenshots.reduce((total, screenshot) => total + screenshot.bytes.byteLength, 0) > 67108864) throw new Error("Ralph capture attempt exceeds upload limits.");
|
|
161
|
-
const images = screenshots.map(({ nodeId, contentType, bytes }) => {
|
|
162
|
-
if (!/^[A-Za-z0-9-]{1,64}$/.test(nodeId)) throw new Error(`Ralph node id is not path-safe: ${nodeId}`);
|
|
163
|
-
return {
|
|
164
|
-
nodeId,
|
|
165
|
-
path: `${CAPTURE_BUNDLE_IMAGE_DIR}/${nodeId}${imageExtension(contentType)}`,
|
|
166
|
-
bytes
|
|
167
|
-
};
|
|
168
|
-
});
|
|
169
|
-
const index = {
|
|
170
|
-
manifest,
|
|
171
|
-
screenshots: images.map(({ nodeId, path }) => ({
|
|
172
|
-
nodeId,
|
|
173
|
-
path
|
|
174
|
-
}))
|
|
175
|
-
};
|
|
176
|
-
const attrs = {
|
|
177
|
-
mtime: /* @__PURE__ */ new Date(0),
|
|
178
|
-
uid: 0,
|
|
179
|
-
gid: 0
|
|
180
|
-
};
|
|
181
|
-
const tar = pack();
|
|
182
|
-
tar.entry({
|
|
183
|
-
name: CAPTURE_BUNDLE_INDEX,
|
|
184
|
-
...attrs
|
|
185
|
-
}, JSON.stringify(index));
|
|
186
|
-
for (const { path, bytes } of images) tar.entry({
|
|
187
|
-
name: path,
|
|
188
|
-
...attrs
|
|
189
|
-
}, Buffer.from(bytes));
|
|
190
|
-
tar.finalize();
|
|
191
|
-
const chunks = [];
|
|
192
|
-
for await (const chunk of tar) chunks.push(chunk);
|
|
193
|
-
const compressed = await promisify(gzip)(Buffer.concat(chunks));
|
|
194
|
-
if (compressed.byteLength > 67108864) throw new Error("Ralph compressed capture bundle exceeds upload limits.");
|
|
195
|
-
return compressed;
|
|
196
|
-
}
|
|
197
|
-
function isLoopback(url) {
|
|
198
|
-
return url.hostname === "localhost" || url.hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(url.hostname);
|
|
199
|
-
}
|
|
200
|
-
async function uploadCapture(manifest, screenshots, options) {
|
|
201
|
-
if (!/^[A-Za-z0-9_-]{1,64}$/.test(options.appId)) throw new Error(`Ralph app id is not valid: ${options.appId}`);
|
|
202
|
-
const url = new URL(`/api/upload/playwright/apps/${options.appId}/attempts`, options.apiUrl);
|
|
203
|
-
if (!(url.protocol === "https:" || url.protocol === "http:" && isLoopback(url)) || !options.uploadKey) throw new Error("Ralph upload requires an HTTPS API URL (HTTP only for loopback hosts) and an upload key.");
|
|
204
|
-
const timeoutMs = options.timeoutMs ?? 3e4;
|
|
205
|
-
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("Ralph uploadTimeoutMs must be positive and finite.");
|
|
206
|
-
const blob = new Blob([new Uint8Array(await createCaptureBundle(manifest, screenshots))], { type: "application/gzip" });
|
|
207
|
-
const response = await fetch(url, {
|
|
208
|
-
method: "POST",
|
|
209
|
-
headers: { Authorization: `Bearer ${options.uploadKey}` },
|
|
210
|
-
body: blob,
|
|
211
|
-
redirect: "error",
|
|
212
|
-
signal: AbortSignal.timeout(timeoutMs)
|
|
213
|
-
});
|
|
214
|
-
if (!response.ok) throw new Error(`Ralph upload failed (HTTP ${response.status}). Local capture artifacts are retained for retry.`);
|
|
215
|
-
const receipt = await response.json();
|
|
216
|
-
if (receipt.result !== "ok" || receipt.status !== "received" || receipt.attemptId !== manifest.attemptId || typeof receipt.replayed !== "boolean") throw new Error("Ralph server returned an invalid upload receipt.");
|
|
217
|
-
return receipt;
|
|
218
|
-
}
|
|
219
|
-
//#endregion
|
|
220
|
-
//#region src/recorder.ts
|
|
221
|
-
const MANIFEST_ATTACHMENT = "ralph-captures";
|
|
222
|
-
const DEFAULT_SETTLE_MS = 150;
|
|
223
|
-
const DEFAULT_CAPTURE_TIMEOUT_MS = 5e3;
|
|
224
|
-
/** Where captures are written, inside Playwright's per-test output directory. */
|
|
225
|
-
const OUTPUT_DIR = "ralph";
|
|
226
|
-
var Recorder = class {
|
|
227
|
-
options;
|
|
228
|
-
config;
|
|
229
|
-
testInfo;
|
|
230
|
-
upload;
|
|
231
|
-
/**
|
|
232
|
-
* Identifies this run of the test. A retry gets a new recorder, and so a new
|
|
233
|
-
* id, which is what lets the server tell retries apart and dedupe re-uploads.
|
|
234
|
-
*/
|
|
235
|
-
attemptId = randomUUID();
|
|
236
|
-
startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
237
|
-
/** How long to wait after a navigation's DOM loads before capturing. */
|
|
238
|
-
settleMs;
|
|
239
|
-
/**
|
|
240
|
-
* The budget for one capture, from settling through the screenshot. Past it,
|
|
241
|
-
* the capture is recorded as failed.
|
|
242
|
-
*/
|
|
243
|
-
captureTimeoutMs;
|
|
244
|
-
/**
|
|
245
|
-
* Every context being watched. `onPage` is kept so `stopContext` can remove
|
|
246
|
-
* the exact listener `observe` added. The id is stored in the manifest's
|
|
247
|
-
* `pages[].contextId`.
|
|
248
|
-
*/
|
|
249
|
-
contexts = /* @__PURE__ */ new Map();
|
|
250
|
-
/**
|
|
251
|
-
* Every tab seen in a watched context, including closed ones, so their
|
|
252
|
-
* captures and opener links still reach the manifest.
|
|
253
|
-
*/
|
|
254
|
-
pages = /* @__PURE__ */ new Map();
|
|
255
|
-
/**
|
|
256
|
-
* Each capture's outcome, in completion order. Captures in one tab complete
|
|
257
|
-
* in sequence, but tabs interleave; `finish` sorts them.
|
|
258
|
-
*/
|
|
259
|
-
nodes = [];
|
|
260
|
-
/**
|
|
261
|
-
* When each capture was requested, keyed by capture id, for linking a
|
|
262
|
-
* popup's first capture to its opener's latest. Numbers, so they compare
|
|
263
|
-
* without parsing each node's `requestedAt` string.
|
|
264
|
-
*/
|
|
265
|
-
requestedAtMs = /* @__PURE__ */ new Map();
|
|
266
|
-
/** Set by `finish`, after which `observe` throws. */
|
|
267
|
-
closed = false;
|
|
268
|
-
constructor(options, config, testInfo, upload) {
|
|
269
|
-
this.options = options;
|
|
270
|
-
this.config = config;
|
|
271
|
-
this.testInfo = testInfo;
|
|
272
|
-
this.upload = upload;
|
|
273
|
-
this.settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
|
|
274
|
-
this.captureTimeoutMs = options.captureTimeoutMs ?? DEFAULT_CAPTURE_TIMEOUT_MS;
|
|
275
|
-
if (!(Number.isFinite(this.settleMs) && this.settleMs >= 0 && Number.isFinite(this.captureTimeoutMs) && this.captureTimeoutMs > this.settleMs)) throw new Error("Ralph captureTimeoutMs must be finite and greater than settleMs, which must be non-negative.");
|
|
276
|
-
}
|
|
277
|
-
/** Starts capturing URL changes in every current and future tab of `context`. */
|
|
278
|
-
observe(context) {
|
|
279
|
-
if (this.closed) throw new Error("The Ralph recorder has finished.");
|
|
280
|
-
if (this.contexts.has(context)) return;
|
|
281
|
-
const id = "context-" + this.contexts.size;
|
|
282
|
-
const onPage = (page) => this.watchPage(page, id);
|
|
283
|
-
this.contexts.set(context, {
|
|
284
|
-
id,
|
|
285
|
-
onPage
|
|
286
|
-
});
|
|
287
|
-
context.on("page", onPage);
|
|
288
|
-
for (const page of context.pages()) onPage(page);
|
|
289
|
-
}
|
|
290
|
-
/** Captures the page as it is now, e.g. an open dialog at the same URL. */
|
|
291
|
-
async captureNode(page, options = {}) {
|
|
292
|
-
this.observe(page.context());
|
|
293
|
-
const state = this.pages.get(page);
|
|
294
|
-
if (!state) throw new Error("Cannot capture a closed browser page.");
|
|
295
|
-
await this.enqueue(state, "explicit", options);
|
|
296
|
-
}
|
|
297
|
-
/** Waits for every queued capture to finish. */
|
|
298
|
-
async flush() {
|
|
299
|
-
await Promise.all([...this.pages.values()].map((state) => state.tail));
|
|
300
|
-
}
|
|
301
|
-
/** Stops watching `context` and waits for its queued captures. */
|
|
302
|
-
async stopContext(context) {
|
|
303
|
-
const entry = this.contexts.get(context);
|
|
304
|
-
if (entry) context.off("page", entry.onPage);
|
|
305
|
-
const states = [...this.pages.values()].filter((state) => state.page.context() === context);
|
|
306
|
-
for (const state of states) state.page.off("framenavigated", state.onNavigation);
|
|
307
|
-
await Promise.all(states.map((state) => state.tail));
|
|
308
|
-
}
|
|
309
|
-
/**
|
|
310
|
-
* Stops recording, then writes the manifest, uploads it if configured, and
|
|
311
|
-
* fails a passing test whose captures failed.
|
|
312
|
-
*/
|
|
313
|
-
async finish() {
|
|
314
|
-
this.closed = true;
|
|
315
|
-
await Promise.all([...this.contexts.keys()].map((context) => this.stopContext(context)));
|
|
316
|
-
await Promise.all([...this.pages.values()].map((state) => state.opener));
|
|
317
|
-
const nodes = this.nodes.sort((a, b) => a.pageId.localeCompare(b.pageId) || a.sequence - b.sequence);
|
|
318
|
-
linkPreviousNodes(nodes, (pageId) => this.pageInfo(pageId)?.openerPageId, (nodeId) => this.requestedAtMs.get(nodeId) ?? 0);
|
|
319
|
-
const failures = nodes.filter((item) => item.status === "failed");
|
|
320
|
-
const manifest = this.buildManifest(nodes, failures.length);
|
|
321
|
-
await this.writeManifest(manifest);
|
|
322
|
-
if (this.upload) await this.uploadManifest(manifest, this.upload);
|
|
323
|
-
if (failures.length && this.testInfo.status === "passed") throw new Error("Ralph could not capture " + failures.length + " page state(s). See the ralph-captures attachment.");
|
|
324
|
-
}
|
|
325
|
-
watchPage(page, contextId) {
|
|
326
|
-
if (this.pages.has(page)) return;
|
|
327
|
-
const state = {
|
|
328
|
-
page,
|
|
329
|
-
info: {
|
|
330
|
-
pageId: "page-" + this.pages.size,
|
|
331
|
-
contextId,
|
|
332
|
-
browserName: page.context().browser()?.browserType().name()
|
|
333
|
-
},
|
|
334
|
-
lastUrl: "",
|
|
335
|
-
generation: 0,
|
|
336
|
-
sequence: 0,
|
|
337
|
-
tail: Promise.resolve(),
|
|
338
|
-
opener: Promise.resolve(),
|
|
339
|
-
onNavigation: (frame) => {
|
|
340
|
-
if (frame === page.mainFrame()) this.urlChanged(state);
|
|
341
|
-
}
|
|
342
|
-
};
|
|
343
|
-
this.pages.set(page, state);
|
|
344
|
-
state.opener = page.opener().then((opener) => {
|
|
345
|
-
if (opener) state.info.openerPageId = this.pages.get(opener)?.info.pageId;
|
|
346
|
-
}).catch(() => void 0);
|
|
347
|
-
page.on("framenavigated", state.onNavigation);
|
|
348
|
-
this.urlChanged(state);
|
|
349
|
-
}
|
|
350
|
-
urlChanged(state) {
|
|
351
|
-
state.generation++;
|
|
352
|
-
const url = state.page.url();
|
|
353
|
-
if (url === state.lastUrl) return;
|
|
354
|
-
state.lastUrl = url;
|
|
355
|
-
if (isHttpUrl(url)) this.enqueue(state, "url-change", {}).catch(() => void 0);
|
|
356
|
-
}
|
|
357
|
-
/** Queues a capture behind the tab's earlier ones. */
|
|
358
|
-
enqueue(state, trigger, options) {
|
|
359
|
-
const actualUrl = state.page.url();
|
|
360
|
-
const url = options.url === void 0 ? actualUrl : new URL(options.url, actualUrl).href;
|
|
361
|
-
if (!isHttpUrl(actualUrl) || !isHttpUrl(url)) throw new Error("Ralph captures require HTTP or HTTPS page and recorded URLs.");
|
|
362
|
-
const request = {
|
|
363
|
-
nodeId: randomUUID(),
|
|
364
|
-
pageId: state.info.pageId,
|
|
365
|
-
sequence: state.sequence++,
|
|
366
|
-
requestedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
367
|
-
actualUrl,
|
|
368
|
-
url,
|
|
369
|
-
trigger,
|
|
370
|
-
...options.state === void 0 ? {} : { state: options.state }
|
|
371
|
-
};
|
|
372
|
-
this.requestedAtMs.set(request.nodeId, Date.now());
|
|
373
|
-
const generation = state.generation;
|
|
374
|
-
const task = state.tail.then(() => this.record(state, generation, request));
|
|
375
|
-
state.tail = task.catch(() => void 0);
|
|
376
|
-
return task;
|
|
377
|
-
}
|
|
378
|
-
/**
|
|
379
|
-
* Takes one capture and records its outcome. Fails if the tab navigates or
|
|
380
|
-
* closes before it finishes, or if it runs past the capture timeout.
|
|
381
|
-
*/
|
|
382
|
-
async record(state, generation, request) {
|
|
383
|
-
const { page } = state;
|
|
384
|
-
const deadline = startDeadline(this.captureTimeoutMs, "Ralph capture timed out.");
|
|
385
|
-
const { wait } = deadline;
|
|
386
|
-
const navigatedAway = () => state.generation !== generation || page.url() !== request.actualUrl;
|
|
387
|
-
const check = () => {
|
|
388
|
-
deadline.signal.throwIfAborted();
|
|
389
|
-
if (navigatedAway()) throw new Error("The page navigated before its capture completed.");
|
|
390
|
-
if (page.isClosed()) throw new Error("The page closed before its capture completed.");
|
|
391
|
-
};
|
|
392
|
-
try {
|
|
393
|
-
check();
|
|
394
|
-
if (request.trigger === "url-change") await this.waitForPageToSettle(page, deadline, check);
|
|
395
|
-
check();
|
|
396
|
-
const before = await wait(readLayout(page));
|
|
397
|
-
check();
|
|
398
|
-
const image = await wait(takeScreenshot(page, deadline.endsAt));
|
|
399
|
-
check();
|
|
400
|
-
const after = await wait(readLayout(page));
|
|
401
|
-
check();
|
|
402
|
-
this.nodes.push({
|
|
403
|
-
...request,
|
|
404
|
-
status: "captured",
|
|
405
|
-
capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
406
|
-
layout: before,
|
|
407
|
-
geometryStable: JSON.stringify(before) === JSON.stringify(after),
|
|
408
|
-
screenshot: await this.saveScreenshot(request.nodeId, image)
|
|
409
|
-
});
|
|
410
|
-
} catch (error) {
|
|
411
|
-
this.nodes.push({
|
|
412
|
-
...request,
|
|
413
|
-
status: navigatedAway() ? "superseded" : "failed",
|
|
414
|
-
reason: error instanceof Error ? error.message : String(error)
|
|
415
|
-
});
|
|
416
|
-
if (request.trigger === "explicit") throw error;
|
|
417
|
-
} finally {
|
|
418
|
-
deadline.cancel();
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
/** After a navigation: the DOM, the settle delay, then the `ready` hook. */
|
|
422
|
-
async waitForPageToSettle(page, { wait, signal }, check) {
|
|
423
|
-
await wait(page.waitForLoadState("domcontentloaded", { timeout: this.captureTimeoutMs }));
|
|
424
|
-
await wait(setTimeout$1(this.settleMs, void 0, { signal }));
|
|
425
|
-
check();
|
|
426
|
-
if (this.options.ready) await wait(this.options.ready(page, signal));
|
|
427
|
-
}
|
|
428
|
-
/** Writes the image to the test output and attaches it to the report. */
|
|
429
|
-
async saveScreenshot(nodeId, image) {
|
|
430
|
-
const path = "ralph/" + nodeId + imageExtension(image.contentType);
|
|
431
|
-
const attachmentName = "ralph-screenshot-" + nodeId;
|
|
432
|
-
await mkdir(this.testInfo.outputPath(OUTPUT_DIR), { recursive: true });
|
|
433
|
-
await writeFile(this.testInfo.outputPath(path), image.bytes);
|
|
434
|
-
await this.testInfo.attach(attachmentName, {
|
|
435
|
-
path: this.testInfo.outputPath(path),
|
|
436
|
-
contentType: image.contentType
|
|
437
|
-
});
|
|
438
|
-
return {
|
|
439
|
-
path,
|
|
440
|
-
attachmentName,
|
|
441
|
-
width: image.width,
|
|
442
|
-
height: image.height,
|
|
443
|
-
scale: "css",
|
|
444
|
-
contentType: image.contentType
|
|
445
|
-
};
|
|
446
|
-
}
|
|
447
|
-
pageInfo(pageId) {
|
|
448
|
-
return [...this.pages.values()].find((state) => state.info.pageId === pageId)?.info;
|
|
449
|
-
}
|
|
450
|
-
buildManifest(nodes, failureCount) {
|
|
451
|
-
const { testInfo } = this;
|
|
452
|
-
const testPassed = testInfo.status === "passed";
|
|
453
|
-
return {
|
|
454
|
-
formatVersion: 1,
|
|
455
|
-
producer: {
|
|
456
|
-
name: "@ralphralphai/playwright",
|
|
457
|
-
version,
|
|
458
|
-
playwrightVersion: playwrightPackage.version
|
|
459
|
-
},
|
|
460
|
-
runId: this.options.runId ?? process.env["RALPH_RUN_ID"],
|
|
461
|
-
buildId: this.options.buildId ?? process.env["RALPH_BUILD_ID"],
|
|
462
|
-
attemptId: this.attemptId,
|
|
463
|
-
test: {
|
|
464
|
-
id: testInfo.testId,
|
|
465
|
-
titlePath: testInfo.titlePath,
|
|
466
|
-
project: testInfo.project.name,
|
|
467
|
-
retry: testInfo.retry,
|
|
468
|
-
repeatEachIndex: testInfo.repeatEachIndex,
|
|
469
|
-
workerIndex: testInfo.workerIndex,
|
|
470
|
-
parallelIndex: testInfo.parallelIndex,
|
|
471
|
-
shard: testInfo.config.shard,
|
|
472
|
-
status: failureCount && testPassed ? "failed" : testInfo.status ?? "unknown",
|
|
473
|
-
expectedStatus: testInfo.expectedStatus
|
|
474
|
-
},
|
|
475
|
-
startedAt: this.startedAt,
|
|
476
|
-
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
477
|
-
config: this.config,
|
|
478
|
-
pages: [...this.pages.values()].map((state) => state.info),
|
|
479
|
-
nodes,
|
|
480
|
-
complete: testPassed && nodes.length > 0 && nodes.every((item) => item.status === "captured" && item.geometryStable)
|
|
481
|
-
};
|
|
482
|
-
}
|
|
483
|
-
async writeManifest(manifest) {
|
|
484
|
-
const file = this.testInfo.outputPath(OUTPUT_DIR, "captures.json");
|
|
485
|
-
await mkdir(this.testInfo.outputPath(OUTPUT_DIR), { recursive: true });
|
|
486
|
-
await writeFile(file, JSON.stringify(manifest, null, 2) + "\n");
|
|
487
|
-
await this.testInfo.attach(MANIFEST_ATTACHMENT, {
|
|
488
|
-
path: file,
|
|
489
|
-
contentType: "application/json"
|
|
490
|
-
});
|
|
491
|
-
}
|
|
492
|
-
async uploadManifest(manifest, upload) {
|
|
493
|
-
const captured = manifest.nodes.filter((item) => item.status === "captured");
|
|
494
|
-
const screenshots = [];
|
|
495
|
-
for (const { nodeId, screenshot } of captured) screenshots.push({
|
|
496
|
-
nodeId,
|
|
497
|
-
contentType: screenshot.contentType,
|
|
498
|
-
bytes: await readFile(this.testInfo.outputPath(screenshot.path))
|
|
499
|
-
});
|
|
500
|
-
const receipt = await uploadCapture(manifest, screenshots, upload);
|
|
501
|
-
await this.testInfo.attach("ralph-upload-receipt", {
|
|
502
|
-
body: JSON.stringify(receipt),
|
|
503
|
-
contentType: "application/json"
|
|
504
|
-
});
|
|
505
|
-
}
|
|
506
|
-
};
|
|
507
|
-
function isHttpUrl(url) {
|
|
508
|
-
return /^https?:/.test(url);
|
|
509
|
-
}
|
|
510
|
-
function startDeadline(timeoutMs, message) {
|
|
511
|
-
const controller = new AbortController();
|
|
512
|
-
const { signal } = controller;
|
|
513
|
-
const timer = setTimeout(() => controller.abort(new Error(message)), timeoutMs);
|
|
514
|
-
const aborted = new Promise((_, reject) => {
|
|
515
|
-
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
|
|
516
|
-
});
|
|
517
|
-
aborted.catch(() => void 0);
|
|
518
|
-
return {
|
|
519
|
-
signal,
|
|
520
|
-
endsAt: Date.now() + timeoutMs,
|
|
521
|
-
wait: (promise) => Promise.race([promise, aborted]),
|
|
522
|
-
cancel: () => clearTimeout(timer)
|
|
523
|
-
};
|
|
524
|
-
}
|
|
525
|
-
/**
|
|
526
|
-
* Sets `previousNodeId` on each node: the one before it in the same
|
|
527
|
-
* tab, or for a popup's first capture, its opener's latest. Superseded captures
|
|
528
|
-
* are skipped, since their page state was never shown.
|
|
529
|
-
*
|
|
530
|
-
* `nodes` must be sorted by page, then sequence.
|
|
531
|
-
*/
|
|
532
|
-
function linkPreviousNodes(nodes, openerOf, requestedAtMs) {
|
|
533
|
-
const byPage = /* @__PURE__ */ new Map();
|
|
534
|
-
for (const item of nodes) byPage.set(item.pageId, [...byPage.get(item.pageId) ?? [], item]);
|
|
535
|
-
const openerNodeBefore = (item) => {
|
|
536
|
-
const openerPageId = openerOf(item.pageId);
|
|
537
|
-
const requestedAt = requestedAtMs(item.nodeId);
|
|
538
|
-
return byPage.get(openerPageId ?? "")?.filter((candidate) => requestedAtMs(candidate.nodeId) <= requestedAt).at(-1);
|
|
539
|
-
};
|
|
540
|
-
const previous = /* @__PURE__ */ new Map();
|
|
541
|
-
for (const items of byPage.values()) items.forEach((item, index) => {
|
|
542
|
-
const from = index > 0 ? items[index - 1] : openerNodeBefore(item);
|
|
543
|
-
if (from) previous.set(item, from);
|
|
544
|
-
});
|
|
545
|
-
for (const item of nodes) {
|
|
546
|
-
let from = previous.get(item);
|
|
547
|
-
while (from?.status === "superseded") from = previous.get(from);
|
|
548
|
-
if (from) item.previousNodeId = from.nodeId;
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
//#endregion
|
|
552
4
|
//#region src/screens.ts
|
|
553
5
|
const SCREEN_TAG_PREFIX = "@ralph-screen:";
|
|
554
6
|
function screenLabel(size) {
|
|
@@ -610,11 +62,13 @@ const test = test$1.extend({
|
|
|
610
62
|
await use();
|
|
611
63
|
}, { auto: true }],
|
|
612
64
|
_ralphRecorder: [async ({ ralphOptions, _ralphConfigs, _ralphScreen }, use, testInfo) => {
|
|
613
|
-
|
|
65
|
+
const mode = resolveMode(ralphOptions);
|
|
66
|
+
if (!testInfo.tags.includes("@ralph") || mode === "off") {
|
|
614
67
|
await use(null);
|
|
615
68
|
return;
|
|
616
69
|
}
|
|
617
|
-
const
|
|
70
|
+
const reported = process.env["RALPH_PLAYWRIGHT_REPORTER"] || testInfo.config.reporter.some(([name]) => name === "blob");
|
|
71
|
+
if (mode === "upload" && !reported) throw new Error("Ralph uploads one merged graph per run from its reporter. Add ['@ralphralphai/playwright/reporter'] to `reporter` in playwright.config, or use the blob reporter and merge-reports when sharding.");
|
|
618
72
|
const root = testInfo.config.configFile ? path.dirname(testInfo.config.configFile) : process.cwd();
|
|
619
73
|
const key = JSON.stringify({
|
|
620
74
|
root,
|
|
@@ -626,7 +80,7 @@ const test = test$1.extend({
|
|
|
626
80
|
pending = loadConfig(ralphOptions, root);
|
|
627
81
|
_ralphConfigs.set(key, pending);
|
|
628
82
|
}
|
|
629
|
-
const recorder = new Recorder(ralphOptions, await pending, testInfo,
|
|
83
|
+
const recorder = new Recorder(ralphOptions, await pending, testInfo, mode);
|
|
630
84
|
try {
|
|
631
85
|
await use(recorder);
|
|
632
86
|
} finally {
|
|
@@ -641,15 +95,23 @@ const test = test$1.extend({
|
|
|
641
95
|
if (resolveMode(ralphOptions) !== "off") throw new Error("Opt this test into Ralph with the @ralph tag.");
|
|
642
96
|
};
|
|
643
97
|
await use(_ralphRecorder ?? {
|
|
644
|
-
|
|
98
|
+
recordNode: async () => {
|
|
645
99
|
checkOptIn();
|
|
646
100
|
},
|
|
647
|
-
|
|
101
|
+
waitForCapture: async () => {},
|
|
102
|
+
pause: () => {},
|
|
103
|
+
resume: () => {},
|
|
648
104
|
observe: () => {
|
|
649
105
|
checkOptIn();
|
|
650
106
|
}
|
|
651
107
|
});
|
|
652
108
|
},
|
|
109
|
+
contextOptions: async ({ contextOptions, ralphOptions }, use, testInfo) => {
|
|
110
|
+
await use(testInfo.tags.includes("@ralph") && resolveMode(ralphOptions) !== "off" && ralphOptions.reduceMotion ? {
|
|
111
|
+
...contextOptions,
|
|
112
|
+
reducedMotion: "reduce"
|
|
113
|
+
} : contextOptions);
|
|
114
|
+
},
|
|
653
115
|
context: async ({ context, _ralphRecorder }, use) => {
|
|
654
116
|
_ralphRecorder?.observe(context);
|
|
655
117
|
try {
|
|
@@ -660,6 +122,6 @@ const test = test$1.extend({
|
|
|
660
122
|
}
|
|
661
123
|
});
|
|
662
124
|
//#endregion
|
|
663
|
-
export { MANIFEST_ATTACHMENT, SCREEN_TAG_PREFIX,
|
|
125
|
+
export { MANIFEST_ATTACHMENT, SCREEN_TAG_PREFIX, createRawGraphBundle, expect, mergeTests, ralphProjects, test, uploadRawGraph };
|
|
664
126
|
|
|
665
127
|
//# sourceMappingURL=index.mjs.map
|