@ralphralphai/playwright 0.2.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.
@@ -0,0 +1,592 @@
1
+ import path from "node:path";
2
+ import { errors } 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 = "1.1.0";
48
+ //#endregion
49
+ //#region src/animations.ts
50
+ /**
51
+ * Waits until no finite CSS animation, CSS transition, or Web Animation is
52
+ * running. Infinite ones (spinners, shimmers) never finish, so they are
53
+ * ignored. Animations driven by `requestAnimationFrame` are invisible here.
54
+ *
55
+ * Stops waiting after `timeoutMs` without failing; the screenshot then jumps
56
+ * whatever is left to its end state.
57
+ */
58
+ async function waitForAnimations(page, timeoutMs) {
59
+ try {
60
+ await page.waitForFunction(() => document.getAnimations().every((animation) => animation.playState !== "running" || animation.playbackRate === 0 || !Number.isFinite(animation.effect?.getComputedTiming().endTime)), void 0, {
61
+ polling: "raf",
62
+ timeout: Math.max(1, timeoutMs)
63
+ });
64
+ } catch (error) {
65
+ if (!(error instanceof errors.TimeoutError)) throw error;
66
+ }
67
+ }
68
+ //#endregion
69
+ //#region src/image.ts
70
+ /**
71
+ * Matches the crawler's full-page screenshots: lossless measured larger than this
72
+ * on real sites, which are mostly photographic content.
73
+ */
74
+ const WEBP_QUALITY = 80;
75
+ async function takeScreenshot(page, deadline) {
76
+ const options = {
77
+ fullPage: true,
78
+ scale: "css",
79
+ animations: "disabled"
80
+ };
81
+ const webp = await page.screenshot({
82
+ ...options,
83
+ type: "webp",
84
+ quality: WEBP_QUALITY,
85
+ timeout: Math.max(1, deadline - Date.now())
86
+ });
87
+ if (webp.length > 0) return {
88
+ bytes: webp,
89
+ contentType: "image/webp",
90
+ ...webpSize(webp)
91
+ };
92
+ const png = await page.screenshot({
93
+ ...options,
94
+ type: "png",
95
+ timeout: Math.max(1, deadline - Date.now())
96
+ });
97
+ return {
98
+ bytes: png,
99
+ contentType: "image/png",
100
+ width: png.readUInt32BE(16),
101
+ height: png.readUInt32BE(20)
102
+ };
103
+ }
104
+ function imageExtension(contentType) {
105
+ return contentType === "image/png" ? ".png" : ".webp";
106
+ }
107
+ function webpSize(bytes) {
108
+ if (bytes.toString("ascii", 0, 4) !== "RIFF" || bytes.toString("ascii", 8, 12) !== "WEBP") throw new Error("The screenshot is not a WebP image.");
109
+ const chunk = bytes.toString("ascii", 12, 16);
110
+ if (chunk === "VP8X") return {
111
+ width: 1 + bytes.readUIntLE(24, 3),
112
+ height: 1 + bytes.readUIntLE(27, 3)
113
+ };
114
+ if (chunk === "VP8 ") return {
115
+ width: bytes.readUInt16LE(26) & 16383,
116
+ height: bytes.readUInt16LE(28) & 16383
117
+ };
118
+ if (chunk === "VP8L") {
119
+ const bits = bytes.readUInt32LE(21);
120
+ return {
121
+ width: 1 + (bits & 16383),
122
+ height: 1 + (bits >> 14 & 16383)
123
+ };
124
+ }
125
+ throw new Error("Unsupported WebP chunk: " + chunk);
126
+ }
127
+ //#endregion
128
+ //#region src/layout.ts
129
+ function readLayout(page) {
130
+ return page.locator("[data-track-id]").filter({ visible: true }).evaluateAll((elements) => ({
131
+ viewport: {
132
+ width: window.innerWidth,
133
+ height: window.innerHeight
134
+ },
135
+ document: {
136
+ width: Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth, document.body?.scrollWidth ?? 0),
137
+ height: Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight, document.body?.scrollHeight ?? 0)
138
+ },
139
+ scroll: {
140
+ x: window.scrollX,
141
+ y: window.scrollY
142
+ },
143
+ devicePixelRatio: window.devicePixelRatio,
144
+ trackedElements: elements.flatMap((element) => {
145
+ const trackId = element.getAttribute("data-track-id");
146
+ const rect = element.getBoundingClientRect();
147
+ if (!trackId || rect.width <= 0 || rect.height <= 0 || rect.right <= 0 || rect.left >= window.innerWidth) return [];
148
+ return [{
149
+ trackId,
150
+ x: rect.x + window.scrollX,
151
+ y: rect.y + window.scrollY,
152
+ width: rect.width,
153
+ height: rect.height
154
+ }];
155
+ })
156
+ }));
157
+ }
158
+ //#endregion
159
+ //#region src/recorder.ts
160
+ /** The attachment holding a test's `RawGraphFile`, which the reporter merges. */
161
+ const MANIFEST_ATTACHMENT = "ralph-raw-graph";
162
+ /**
163
+ * Set by the reporter in the main process before any worker starts, so the
164
+ * fixtures can refuse to upload without it.
165
+ */
166
+ const REPORTER_ENV = "RALPH_PLAYWRIGHT_REPORTER";
167
+ /** Prefix of the attachment holding each recorded node's screenshot; the node id follows. */
168
+ const SCREENSHOT_ATTACHMENT_PREFIX = "ralph-screenshot-";
169
+ const DEFAULT_SETTLE_MS = 150;
170
+ const DEFAULT_RECORD_TIMEOUT_MS = 5e3;
171
+ /** Where the raw graph and screenshots are written, inside Playwright's per-test output directory. */
172
+ const OUTPUT_DIR = "ralph";
173
+ var Recorder = class {
174
+ options;
175
+ config;
176
+ testInfo;
177
+ mode;
178
+ startedAt = (/* @__PURE__ */ new Date()).toISOString();
179
+ /** How long to wait after a navigation's DOM loads before recording. */
180
+ settleMs;
181
+ /**
182
+ * The budget for recording one node, from settling through the screenshot.
183
+ * Past it, the node is recorded as failed.
184
+ */
185
+ recordTimeoutMs;
186
+ /**
187
+ * Every context being watched, with its page listener, kept so
188
+ * `stopContext` can remove the exact listener `observe` added.
189
+ */
190
+ contexts = /* @__PURE__ */ new Map();
191
+ /**
192
+ * Every tab seen in a watched context, including closed ones, so their
193
+ * nodes and opener links still reach the manifest.
194
+ */
195
+ pages = /* @__PURE__ */ new Map();
196
+ /**
197
+ * Each node's outcome, in completion order. Nodes in one tab complete
198
+ * in sequence, but tabs interleave; `finish` sorts them.
199
+ */
200
+ nodes = [];
201
+ /**
202
+ * When each node was requested, keyed by node id, for linking a
203
+ * popup's first node to its opener's latest. Numbers, so they compare
204
+ * without parsing each node's `requestedAt` string.
205
+ */
206
+ requestedAtMs = /* @__PURE__ */ new Map();
207
+ /** Set by `finish`, after which `observe` throws. */
208
+ closed = false;
209
+ /** Set by `pause`; while set, no new nodes are requested. */
210
+ paused = false;
211
+ /** The most recently requested node, the anchor for tabs used while paused. */
212
+ lastRequestedNodeId;
213
+ constructor(options, config, testInfo, mode) {
214
+ this.options = options;
215
+ this.config = config;
216
+ this.testInfo = testInfo;
217
+ this.mode = mode;
218
+ this.settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
219
+ this.recordTimeoutMs = options.recordTimeoutMs ?? DEFAULT_RECORD_TIMEOUT_MS;
220
+ if (!(Number.isFinite(this.settleMs) && this.settleMs >= 0 && Number.isFinite(this.recordTimeoutMs) && this.recordTimeoutMs > this.settleMs)) throw new Error("Ralph recordTimeoutMs must be finite and greater than settleMs, which must be non-negative.");
221
+ }
222
+ /** Starts recording URL changes in every current and future tab of `context`. */
223
+ observe(context) {
224
+ if (this.closed) throw new Error("The Ralph recorder has finished.");
225
+ if (this.contexts.has(context)) return;
226
+ const onPage = (page) => this.watchPage(page);
227
+ this.contexts.set(context, onPage);
228
+ context.on("page", onPage);
229
+ for (const page of context.pages()) onPage(page);
230
+ }
231
+ /** Records the page as it is now, e.g. an open dialog at the same URL. */
232
+ async recordNode(page, options = {}) {
233
+ this.observe(page.context());
234
+ const state = this.pages.get(page);
235
+ if (!state) throw new Error("Cannot record a closed browser page.");
236
+ if (this.paused) return;
237
+ await this.enqueueCreateNodeRequest(state, "explicit", options);
238
+ }
239
+ /**
240
+ * Stops requesting nodes, automatic or explicit, until `resume`. Recordings
241
+ * already requested still complete. The next node after `resume` links to
242
+ * the last one before `pause`, so the skipped steps drop out of the graph.
243
+ */
244
+ pause() {
245
+ this.paused = true;
246
+ }
247
+ /** Undoes `pause`. The current page is not recorded until its URL changes. */
248
+ resume() {
249
+ this.paused = false;
250
+ }
251
+ /** Waits until every page recording requested so far has finished. */
252
+ async waitForCapture() {
253
+ await Promise.all([...this.pages.values()].map((state) => state.tail));
254
+ }
255
+ /** Stops watching `context` and waits for its queued recordings. */
256
+ async stopContext(context) {
257
+ const onPage = this.contexts.get(context);
258
+ if (onPage) context.off("page", onPage);
259
+ const states = [...this.pages.values()].filter((state) => state.page.context() === context);
260
+ for (const state of states) state.page.off("framenavigated", state.onNavigation);
261
+ await Promise.all(states.map((state) => state.tail));
262
+ }
263
+ /**
264
+ * Stops recording, then writes the test's raw graph for the reporter, and
265
+ * fails a passing test whose nodes failed to record.
266
+ */
267
+ async finish() {
268
+ this.closed = true;
269
+ await Promise.all([...this.contexts.keys()].map((context) => this.stopContext(context)));
270
+ await Promise.all([...this.pages.values()].map((state) => state.opener));
271
+ const nodes = this.nodes.sort((a, b) => a.pageId.localeCompare(b.pageId) || a.sequence - b.sequence);
272
+ linkPreviousNodes(nodes, (pageId) => this.pageInfo(pageId)?.openerPageId, (nodeId) => this.requestedAtMs.get(nodeId) ?? 0, (pageId) => this.pageState(pageId)?.pauseAnchor);
273
+ const failures = nodes.filter((item) => item.status === "uncaptured" && item.reason === "error");
274
+ await this.writeRawGraph(this.buildRawGraph(nodes, failures.length));
275
+ if (failures.length && this.testInfo.status === "passed") throw new Error("Ralph could not record " + failures.length + " page state(s). See the ralph-raw-graph attachment.");
276
+ }
277
+ watchPage(page) {
278
+ if (this.pages.has(page)) return;
279
+ const state = {
280
+ page,
281
+ info: {
282
+ pageId: "page-" + this.pages.size,
283
+ browserName: page.context().browser()?.browserType().name()
284
+ },
285
+ lastUrl: "",
286
+ generation: 0,
287
+ sequence: 0,
288
+ tail: Promise.resolve(),
289
+ opener: Promise.resolve(),
290
+ onNavigation: (frame) => {
291
+ if (frame === page.mainFrame()) this.urlChanged(state);
292
+ }
293
+ };
294
+ this.pages.set(page, state);
295
+ state.opener = page.opener().then((opener) => {
296
+ if (opener) {
297
+ const openerState = this.pages.get(opener);
298
+ state.info.openerPageId = openerState?.info.pageId;
299
+ state.pauseAnchor ??= openerState?.pauseAnchor;
300
+ }
301
+ }).catch(() => void 0);
302
+ page.on("framenavigated", state.onNavigation);
303
+ this.urlChanged(state);
304
+ }
305
+ urlChanged(state) {
306
+ if (this.paused && state.sequence === 0) state.pauseAnchor ??= this.lastRequestedNodeId;
307
+ const url = state.page.url();
308
+ if (url === state.lastUrl) return;
309
+ state.generation++;
310
+ state.lastUrl = url;
311
+ if (!this.paused && isHttpUrl(url)) this.enqueueCreateNodeRequest(state, "url-change", {}).catch(() => void 0);
312
+ }
313
+ /** Queues a recording behind the tab's earlier ones. */
314
+ enqueueCreateNodeRequest(state, trigger, options) {
315
+ const actualUrl = state.page.url();
316
+ const url = options.url === void 0 ? actualUrl : new URL(options.url, actualUrl).href;
317
+ if (!isHttpUrl(actualUrl) || !isHttpUrl(url)) throw new Error("Ralph recordings require HTTP or HTTPS page and recorded URLs.");
318
+ const request = {
319
+ nodeId: randomUUID(),
320
+ pageId: state.info.pageId,
321
+ sequence: state.sequence++,
322
+ requestedAt: (/* @__PURE__ */ new Date()).toISOString(),
323
+ actualUrl,
324
+ url,
325
+ trigger,
326
+ ...options.state === void 0 ? {} : { state: options.state }
327
+ };
328
+ this.requestedAtMs.set(request.nodeId, Date.now());
329
+ this.lastRequestedNodeId = request.nodeId;
330
+ const generation = state.generation;
331
+ const task = state.tail.then(() => this.createNode(state, generation, request));
332
+ state.tail = task.catch(() => void 0);
333
+ return task;
334
+ }
335
+ /**
336
+ * Creates the requested node: `recorded`, or `uncaptured` if the tab
337
+ * navigates or closes first, or the record timeout passes.
338
+ */
339
+ async createNode(state, generation, request) {
340
+ const { page } = state;
341
+ const deadline = startDeadline(this.recordTimeoutMs, "Ralph recording timed out.");
342
+ const { wait } = deadline;
343
+ const navigatedAway = () => state.generation !== generation || page.url() !== request.actualUrl;
344
+ const check = () => {
345
+ deadline.signal.throwIfAborted();
346
+ if (navigatedAway()) throw new Error("The page navigated before its recording completed.");
347
+ if (page.isClosed()) throw new Error("The page closed before its recording completed.");
348
+ };
349
+ try {
350
+ check();
351
+ if (request.trigger === "url-change") await this.waitForPageToSettle(page, deadline, check);
352
+ if (this.options.reduceMotion) {
353
+ check();
354
+ await wait(waitForAnimations(page, (deadline.endsAt - Date.now()) / 2));
355
+ }
356
+ check();
357
+ const before = await wait(readLayout(page));
358
+ check();
359
+ const image = await wait(takeScreenshot(page, deadline.endsAt));
360
+ check();
361
+ const after = await wait(readLayout(page));
362
+ check();
363
+ this.nodes.push({
364
+ ...request,
365
+ status: "recorded",
366
+ recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
367
+ layout: before,
368
+ geometryStable: JSON.stringify(before) === JSON.stringify(after),
369
+ screenshot: await this.saveScreenshot(request.nodeId, image)
370
+ });
371
+ } catch (error) {
372
+ this.nodes.push({
373
+ ...request,
374
+ status: "uncaptured",
375
+ reason: navigatedAway() ? "navigated-away" : "error",
376
+ message: error instanceof Error ? error.message : String(error)
377
+ });
378
+ if (request.trigger === "explicit") throw error;
379
+ } finally {
380
+ deadline.cancel();
381
+ }
382
+ }
383
+ /** After a navigation: the DOM, the settle delay, then the `ready` hook. */
384
+ async waitForPageToSettle(page, { wait, signal }, check) {
385
+ await wait(page.waitForLoadState("domcontentloaded", { timeout: this.recordTimeoutMs }));
386
+ await wait(setTimeout$1(this.settleMs, void 0, { signal }));
387
+ check();
388
+ if (this.options.ready) await wait(this.options.ready(page, signal));
389
+ }
390
+ /** Writes the image to the test output and attaches it to the report. */
391
+ async saveScreenshot(nodeId, image) {
392
+ const path = "ralph/" + nodeId + imageExtension(image.contentType);
393
+ const attachmentName = SCREENSHOT_ATTACHMENT_PREFIX + nodeId;
394
+ await mkdir(this.testInfo.outputPath(OUTPUT_DIR), { recursive: true });
395
+ await writeFile(this.testInfo.outputPath(path), image.bytes);
396
+ await this.testInfo.attach(attachmentName, {
397
+ ...this.testInfo.config.preserveOutput === "always" ? { path: this.testInfo.outputPath(path) } : { body: image.bytes },
398
+ contentType: image.contentType
399
+ });
400
+ return {
401
+ path,
402
+ attachmentName,
403
+ width: image.width,
404
+ height: image.height,
405
+ scale: "css",
406
+ contentType: image.contentType
407
+ };
408
+ }
409
+ pageState(pageId) {
410
+ return [...this.pages.values()].find((state) => state.info.pageId === pageId);
411
+ }
412
+ pageInfo(pageId) {
413
+ return this.pageState(pageId)?.info;
414
+ }
415
+ buildRawGraph(nodes, failureCount) {
416
+ const { testInfo } = this;
417
+ const testPassed = testInfo.status === "passed";
418
+ return {
419
+ formatVersion: 1,
420
+ producer: {
421
+ name: "@ralphralphai/playwright",
422
+ version,
423
+ playwrightVersion: playwrightPackage.version
424
+ },
425
+ runId: this.options.runId ?? process.env["RALPH_RUN_ID"],
426
+ buildId: this.options.buildId ?? process.env["RALPH_BUILD_ID"],
427
+ config: this.config,
428
+ mode: this.mode,
429
+ rawGraph: {
430
+ id: testInfo.testId,
431
+ titlePath: testInfo.titlePath,
432
+ project: testInfo.project.name,
433
+ retry: testInfo.retry,
434
+ repeatEachIndex: testInfo.repeatEachIndex,
435
+ workerIndex: testInfo.workerIndex,
436
+ parallelIndex: testInfo.parallelIndex,
437
+ status: failureCount && testPassed ? "failed" : testInfo.status ?? "unknown",
438
+ expectedStatus: testInfo.expectedStatus,
439
+ startedAt: this.startedAt,
440
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
441
+ pages: [...this.pages.values()].map((state) => state.info),
442
+ nodes,
443
+ complete: testPassed && nodes.length > 0 && nodes.every((item) => item.status === "recorded" && item.geometryStable)
444
+ }
445
+ };
446
+ }
447
+ async writeRawGraph(file) {
448
+ const path = this.testInfo.outputPath(OUTPUT_DIR, "raw_graph.json");
449
+ const body = JSON.stringify(file, null, 2) + "\n";
450
+ await mkdir(this.testInfo.outputPath(OUTPUT_DIR), { recursive: true });
451
+ await writeFile(path, body);
452
+ await this.testInfo.attach(MANIFEST_ATTACHMENT, {
453
+ ...this.testInfo.config.preserveOutput === "always" ? { path } : { body },
454
+ contentType: "application/json"
455
+ });
456
+ }
457
+ };
458
+ function isHttpUrl(url) {
459
+ return /^https?:/.test(url);
460
+ }
461
+ function startDeadline(timeoutMs, message) {
462
+ const controller = new AbortController();
463
+ const { signal } = controller;
464
+ const timer = setTimeout(() => controller.abort(new Error(message)), timeoutMs);
465
+ const aborted = new Promise((_, reject) => {
466
+ signal.addEventListener("abort", () => reject(signal.reason), { once: true });
467
+ });
468
+ aborted.catch(() => void 0);
469
+ return {
470
+ signal,
471
+ endsAt: Date.now() + timeoutMs,
472
+ wait: (promise) => Promise.race([promise, aborted]),
473
+ cancel: () => clearTimeout(timer)
474
+ };
475
+ }
476
+ /**
477
+ * Sets `previousNodeId` on each node: the one before it in the same
478
+ * tab, or for a popup's first node, its opener's latest. Failing both, a tab
479
+ * first used while paused links to the last node before the pause.
480
+ * Uncaptured nodes stay in the chain, as regular nodes in the server's graph.
481
+ *
482
+ * `nodes` must be sorted by page, then sequence.
483
+ */
484
+ function linkPreviousNodes(nodes, openerOf, requestedAtMs, pauseAnchorOf) {
485
+ const byPage = /* @__PURE__ */ new Map();
486
+ const byId = /* @__PURE__ */ new Map();
487
+ for (const item of nodes) {
488
+ byPage.set(item.pageId, [...byPage.get(item.pageId) ?? [], item]);
489
+ byId.set(item.nodeId, item);
490
+ }
491
+ const openerNodeBefore = (item) => {
492
+ const openerPageId = openerOf(item.pageId);
493
+ const requestedAt = requestedAtMs(item.nodeId);
494
+ return byPage.get(openerPageId ?? "")?.filter((candidate) => requestedAtMs(candidate.nodeId) <= requestedAt).at(-1);
495
+ };
496
+ for (const items of byPage.values()) items.forEach((item, index) => {
497
+ const from = index > 0 ? items[index - 1] : openerNodeBefore(item) ?? byId.get(pauseAnchorOf(item.pageId) ?? "");
498
+ if (from) item.previousNodeId = from.nodeId;
499
+ });
500
+ }
501
+ //#endregion
502
+ //#region src/upload.ts
503
+ /** Where the reporter uploads: its options, else the environment. */
504
+ function resolveUploadOptions(options) {
505
+ const uploadKey = process.env["RALPH_UPLOAD_KEY"];
506
+ const apiUrl = options.apiUrl ?? process.env["RALPH_API_URL"];
507
+ const appId = options.appId ?? process.env["RALPH_APP_ID"];
508
+ if (!uploadKey || !apiUrl || !appId) throw new Error("Ralph upload requires RALPH_UPLOAD_KEY, RALPH_API_URL (or the reporter option apiUrl), and RALPH_APP_ID (or appId).");
509
+ return {
510
+ uploadKey,
511
+ apiUrl,
512
+ appId,
513
+ timeoutMs: options.uploadTimeoutMs
514
+ };
515
+ }
516
+ const RAW_GRAPH_BUNDLE_INDEX = "raw_graph.json";
517
+ const RAW_GRAPH_BUNDLE_IMAGE_DIR = "assets/images";
518
+ /** Where a node's screenshot sits inside the bundle. */
519
+ function bundleImagePath(nodeId, contentType) {
520
+ if (!/^[A-Za-z0-9-]{1,64}$/.test(nodeId)) throw new Error(`Ralph node id is not path-safe: ${nodeId}`);
521
+ return `${RAW_GRAPH_BUNDLE_IMAGE_DIR}/${nodeId}${imageExtension(contentType)}`;
522
+ }
523
+ /**
524
+ * Packs the manifest and screenshots into a gzipped tar archive:
525
+ *
526
+ * raw_graph.json { manifest, screenshots: [{ nodeId, path }] }
527
+ * assets/images/<id>.webp raw screenshot bytes (.png when too large for WebP)
528
+ */
529
+ async function createRawGraphBundle(manifest, screenshots) {
530
+ if (Buffer.byteLength(JSON.stringify(manifest)) > 16777216 || screenshots.length > 5e3 || screenshots.reduce((total, screenshot) => total + screenshot.bytes.byteLength, 0) > 268435456) throw new Error("Ralph raw graph exceeds upload limits.");
531
+ const images = screenshots.map(({ nodeId, contentType, bytes }) => ({
532
+ nodeId,
533
+ path: bundleImagePath(nodeId, contentType),
534
+ bytes
535
+ }));
536
+ const index = {
537
+ manifest,
538
+ screenshots: images.map(({ nodeId, path }) => ({
539
+ nodeId,
540
+ path
541
+ }))
542
+ };
543
+ const attrs = {
544
+ mtime: /* @__PURE__ */ new Date(0),
545
+ uid: 0,
546
+ gid: 0
547
+ };
548
+ const tar = pack();
549
+ tar.entry({
550
+ name: RAW_GRAPH_BUNDLE_INDEX,
551
+ ...attrs
552
+ }, JSON.stringify(index));
553
+ for (const { path, bytes } of images) tar.entry({
554
+ name: path,
555
+ ...attrs
556
+ }, Buffer.from(bytes));
557
+ tar.finalize();
558
+ const chunks = [];
559
+ for await (const chunk of tar) chunks.push(chunk);
560
+ const compressed = await promisify(gzip)(Buffer.concat(chunks));
561
+ if (compressed.byteLength > 268435456) throw new Error("Ralph compressed raw graph bundle exceeds upload limits.");
562
+ return compressed;
563
+ }
564
+ function isLoopback(url) {
565
+ return url.hostname === "localhost" || url.hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(url.hostname);
566
+ }
567
+ async function uploadRawGraph(manifest, screenshots, options) {
568
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(options.appId)) throw new Error(`Ralph app id is not valid: ${options.appId}`);
569
+ const url = new URL(`/api/upload/playwright/apps/${options.appId}/artifact`, options.apiUrl);
570
+ const storage = process.env["RALPH_UPLOAD_STORAGE"] || "gcs";
571
+ if (storage !== "gcs" && storage !== "local") throw new Error(`RALPH_UPLOAD_STORAGE must be gcs or local, not ${storage}.`);
572
+ if (storage === "local") url.searchParams.set("storage", "local");
573
+ 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.");
574
+ const timeoutMs = options.timeoutMs ?? 12e4;
575
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("Ralph uploadTimeoutMs must be positive and finite.");
576
+ const blob = new Blob([new Uint8Array(await createRawGraphBundle(manifest, screenshots))], { type: "application/gzip" });
577
+ const response = await fetch(url, {
578
+ method: "POST",
579
+ headers: { Authorization: `Bearer ${options.uploadKey}` },
580
+ body: blob,
581
+ redirect: "error",
582
+ signal: AbortSignal.timeout(timeoutMs)
583
+ });
584
+ if (!response.ok) throw new Error(`Ralph upload failed (HTTP ${response.status}). Local Ralph artifacts are retained for retry.`);
585
+ const receipt = await response.json();
586
+ if (receipt.result !== "ok" || receipt.status !== "received" || receipt.artifactId !== manifest.artifactId || typeof receipt.resultId !== "string" || receipt.resultUrl !== void 0 && typeof receipt.resultUrl !== "string" || typeof receipt.replayed !== "boolean") throw new Error("Ralph server returned an invalid upload receipt.");
587
+ return receipt;
588
+ }
589
+ //#endregion
590
+ export { uploadRawGraph as a, Recorder as c, loadConfigSync as d, resolveMode as f, resolveUploadOptions as i, version as l, bundleImagePath as n, MANIFEST_ATTACHMENT as o, createRawGraphBundle as r, REPORTER_ENV as s, RAW_GRAPH_BUNDLE_INDEX as t, loadConfig as u };
591
+
592
+ //# sourceMappingURL=upload-giSVxpun.mjs.map