@plune-ai/playwright 0.2.8 → 0.4.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
@@ -120,6 +120,19 @@ test('rejects a negative quantity', { annotation: { type: 'PluneId', description
120
120
  A result whose test matches no case is **not** sent and **not** invented — a made-up id would
121
121
  write into somebody else's history. The run summary says how many there were.
122
122
 
123
+ ## Screenshots
124
+
125
+ Every screenshot a test keeps as a file — Playwright's `screenshot` option, `testInfo.attach` with a
126
+ `path`, the images of a failed `toHaveScreenshot` — is uploaded to its result in Plune, for a test
127
+ that passed as well as one that failed. So a run in Plune shows each test with what it looked at,
128
+ under the name it was attached with: `testInfo.attach('checkout', { path })` arrives as
129
+ `checkout.png`.
130
+
131
+ Plune takes PNG, JPEG and WebP, up to 2 MB a file and 20 a result. An image outside those limits is
132
+ skipped: the run summary counts it and says why, once per reason. Traces, videos and other files are
133
+ not uploaded, and neither is an image attached as a `body` rather than a file — attach it with `path`.
134
+ A screenshot that does not arrive never costs its result or your run's exit code.
135
+
123
136
  ## When Plune is unreachable
124
137
 
125
138
  Nothing is lost and nothing fails. An unreachable platform, a refused token or an already-closed
package/dist/index.cjs CHANGED
@@ -39,17 +39,19 @@ var import_node_util = require("util");
39
39
  // ../../dist/reporter-core.js
40
40
  var import_crypto = require("crypto");
41
41
  var import_fs = require("fs");
42
- var import_os = require("os");
43
42
  var import_path = require("path");
43
+ var import_fs2 = require("fs");
44
+ var import_os = require("os");
45
+ var import_path2 = require("path");
44
46
  var import_http = require("http");
45
47
  var import_https = require("https");
46
48
  var path = __toESM(require("path"), 1);
47
49
  var fs = __toESM(require("fs"), 1);
48
50
  var path2 = __toESM(require("path"), 1);
49
51
  var import_crypto2 = require("crypto");
50
- var import_fs2 = require("fs");
52
+ var import_fs3 = require("fs");
51
53
  var import_os2 = require("os");
52
- var import_path2 = require("path");
54
+ var import_path3 = require("path");
53
55
  var import_util = require("util");
54
56
  var DEFAULT_API_URL = "https://beta-api.plune.ai";
55
57
  function resolveApiUrl(explicit) {
@@ -57,14 +59,14 @@ function resolveApiUrl(explicit) {
57
59
  return raw.replace(/\/+$/, "");
58
60
  }
59
61
  function credentialsFile() {
60
- const base = process.env["XDG_CONFIG_HOME"]?.trim() || (0, import_path.join)((0, import_os.homedir)(), ".config");
61
- return (0, import_path.join)(base, "plune", "credentials.json");
62
+ const base = process.env["XDG_CONFIG_HOME"]?.trim() || (0, import_path2.join)((0, import_os.homedir)(), ".config");
63
+ return (0, import_path2.join)(base, "plune", "credentials.json");
62
64
  }
63
65
  function loadToken() {
64
66
  const fromEnv = process.env["PLUNE_TOKEN"]?.trim();
65
67
  if (fromEnv !== void 0 && fromEnv !== "") return fromEnv;
66
68
  try {
67
- const parsed = JSON.parse((0, import_fs.readFileSync)(credentialsFile(), "utf-8"));
69
+ const parsed = JSON.parse((0, import_fs2.readFileSync)(credentialsFile(), "utf-8"));
68
70
  return typeof parsed.token === "string" && parsed.token.length > 0 ? parsed.token : null;
69
71
  } catch {
70
72
  return null;
@@ -128,7 +130,7 @@ function createClient(opts) {
128
130
  const wait = opts.wait ?? sleep;
129
131
  const base = opts.apiUrl.replace(/\/+$/, "");
130
132
  const scrub = (text) => opts.token === "" ? text : text.split(opts.token).join("***");
131
- async function send(method, path3, body) {
133
+ async function send(method, path3, payload) {
132
134
  let last = {
133
135
  kind: "unavailable",
134
136
  status: null,
@@ -139,11 +141,11 @@ function createClient(opts) {
139
141
  try {
140
142
  res = await doFetch(`${base}${path3}`, {
141
143
  method,
142
- headers: { "content-type": "application/json", authorization: `Bearer ${opts.token}` },
144
+ headers: { "content-type": payload?.type ?? "application/json", authorization: `Bearer ${opts.token}` },
143
145
  // A DELETE carries none. Sending `"undefined"` as a body is what a naive
144
146
  // `JSON.stringify(body)` would do, and some proxies answer that with a 400 nobody can
145
147
  // explain.
146
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
148
+ ...payload === void 0 ? {} : { body: payload.body }
147
149
  });
148
150
  } catch (err) {
149
151
  last = { kind: "unavailable", status: null, detail: scrub(String(err)) };
@@ -169,7 +171,8 @@ function createClient(opts) {
169
171
  return { ok: false, ...last };
170
172
  }
171
173
  return {
172
- post: (path3, body) => send("POST", path3, body),
174
+ post: (path3, body) => send("POST", path3, { body: JSON.stringify(body), type: "application/json" }),
175
+ upload: (path3, bytes, contentType) => send("POST", path3, { body: bytes, type: contentType }),
173
176
  del: (path3) => send("DELETE", path3)
174
177
  };
175
178
  }
@@ -233,6 +236,28 @@ function defaultRunTitle(env = process.env, now = /* @__PURE__ */ new Date(), cw
233
236
  const where = flag(env, "CI") || flag(env, "GITHUB_ACTIONS") ? "ci" : "local";
234
237
  return `${path.basename(cwd)} \xB7 ${stamp} \xB7 ${where}`;
235
238
  }
239
+ var PROVIDERS = [
240
+ { is: "GITHUB_ACTIONS", sha: "GITHUB_SHA", branch: ["GITHUB_HEAD_REF", "GITHUB_REF_NAME"] },
241
+ { is: "GITLAB_CI", sha: "CI_COMMIT_SHA", branch: ["CI_COMMIT_REF_NAME"] },
242
+ { is: "JENKINS_URL", sha: "GIT_COMMIT", branch: ["GIT_BRANCH"] }
243
+ ];
244
+ function ciCommit(reported, env = process.env) {
245
+ const said = typeof reported === "object" && reported !== null ? reported : {};
246
+ const text = (raw) => typeof raw === "string" && raw.trim() !== "" ? raw.trim() : void 0;
247
+ const provider = PROVIDERS.find((p) => value(env, p.is) !== void 0);
248
+ const job = {
249
+ sha: provider === void 0 ? void 0 : value(env, provider.sha),
250
+ branch: provider?.branch.map((name) => value(env, name)).find((v) => v !== void 0)
251
+ };
252
+ const sha = text(said["commitHash"]);
253
+ const sameCommit = sha === void 0 || sha === job.sha;
254
+ const commit = sha ?? job.sha;
255
+ const branch = text(said["branch"]) ?? (sameCommit ? job.branch : void 0);
256
+ return {
257
+ ...commit !== void 0 ? { sha: commit } : {},
258
+ ...branch !== void 0 ? { branch } : {}
259
+ };
260
+ }
236
261
  var DEFAULT_FALLBACK_PATH = path2.join(".plune", "pending-results.jsonl");
237
262
  function appendBatch(file, batch) {
238
263
  fs.mkdirSync(path2.dirname(file), { recursive: true });
@@ -240,6 +265,8 @@ function appendBatch(file, batch) {
240
265
  ts: (/* @__PURE__ */ new Date()).toISOString(),
241
266
  runId: batch.runId,
242
267
  externalKey: batch.externalKey,
268
+ ...batch.session !== void 0 ? { session: batch.session } : {},
269
+ ...batch.meta !== void 0 ? { meta: batch.meta } : {},
243
270
  results: batch.results
244
271
  };
245
272
  fs.appendFileSync(file, `${JSON.stringify(line)}
@@ -253,6 +280,37 @@ var EXPECTED_MAX = 1e4;
253
280
  var KEY_MAX = 1024;
254
281
  var TITLE_MAX = 300;
255
282
  var COUNTED = ["accepted", "duplicate", "conflict", "rejected"];
283
+ var SCREENSHOT_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp"]);
284
+ var SCREENSHOT_BYTES = 2 * 1024 * 1024;
285
+ var SCREENSHOTS_PER_RESULT = 20;
286
+ var TYPE_BY_EXTENSION = {
287
+ ".png": "image/png",
288
+ ".jpg": "image/jpeg",
289
+ ".jpeg": "image/jpeg",
290
+ ".webp": "image/webp"
291
+ };
292
+ var UPLOADS_AT_ONCE = 4;
293
+ var NAME_MAX = 200;
294
+ function nameOf(file) {
295
+ const own = file.name.split(/[\\/]/).pop()?.trim() || (0, import_path.basename)(file.path);
296
+ const fileExt = (0, import_path.extname)(file.path);
297
+ const ownExt = (0, import_path.extname)(own);
298
+ const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
299
+ const ext = typed ? ownExt : fileExt;
300
+ let stem = typed ? own.slice(0, -ownExt.length) : own;
301
+ if (stem.length + ext.length > NAME_MAX) {
302
+ stem = stem.slice(0, Math.max(0, NAME_MAX - ext.length));
303
+ if (/[\uD800-\uDBFF]$/.test(stem)) stem = stem.slice(0, -1);
304
+ }
305
+ return `${stem}${ext}`;
306
+ }
307
+ var SKIPPED = {
308
+ hidden: "its name starts with an underscore, which hides an attachment in Playwright's own reports too",
309
+ type: "Plune takes PNG, JPEG and WebP",
310
+ limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
311
+ missing: "the file cannot be read on this machine",
312
+ size: "Plune takes a file of at most 2 MB"
313
+ };
256
314
  function boundKey(key) {
257
315
  if (key.value.length <= KEY_MAX) return key;
258
316
  const digest = (0, import_crypto.createHash)("sha256").update(key.value).digest("hex").slice(0, 16);
@@ -260,6 +318,12 @@ function boundKey(key) {
260
318
  if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
261
319
  return { ...key, value: `${head}#${digest}` };
262
320
  }
321
+ function whyUnoffered(out) {
322
+ if (out.ok || out.status !== 429) return "other";
323
+ if (/review queue quota reached/i.test(out.detail)) return "queue";
324
+ if (/test case quota reached/i.test(out.detail)) return "cases";
325
+ return "other";
326
+ }
263
327
  function boundTitle(title) {
264
328
  return title.length <= TITLE_MAX ? title : `${title.slice(0, TITLE_MAX - 1)}\u2026`;
265
329
  }
@@ -303,6 +367,7 @@ async function startRun(passed, declared2) {
303
367
  `));
304
368
  const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
305
369
  const externalKey = cfg.externalKey ?? null;
370
+ const sessionMarker = (0, import_crypto.randomUUID)();
306
371
  const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
307
372
  const offerDiscovered = cfg.offerDiscovered ?? false;
308
373
  const token = cfg.token ?? loadToken() ?? "";
@@ -320,7 +385,8 @@ async function startRun(passed, declared2) {
320
385
  offered: 0,
321
386
  created: 0,
322
387
  unoffered: 0,
323
- deferred: 0
388
+ deferred: 0,
389
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 }
324
390
  };
325
391
  const resolved = /* @__PURE__ */ new Map();
326
392
  let buffer = [];
@@ -330,6 +396,7 @@ async function startRun(passed, declared2) {
330
396
  let offline = token === "";
331
397
  let done = false;
332
398
  const shortened = /* @__PURE__ */ new Set();
399
+ const skipsSaid = /* @__PURE__ */ new Set();
333
400
  function bound(keys) {
334
401
  return keys.map((key) => {
335
402
  const fit = boundKey(key);
@@ -352,7 +419,13 @@ async function startRun(passed, declared2) {
352
419
  log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
353
420
  }
354
421
  function defer(results) {
355
- appendBatch(fallbackPath, { runId, externalKey, results });
422
+ appendBatch(fallbackPath, {
423
+ runId,
424
+ externalKey,
425
+ session: sessionMarker,
426
+ ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
427
+ results
428
+ });
356
429
  stats.deferred += results.length;
357
430
  }
358
431
  async function resolveKeys(values) {
@@ -449,6 +522,7 @@ async function startRun(passed, declared2) {
449
522
  });
450
523
  if (!out.ok || !Array.isArray(out.body?.results)) {
451
524
  stats.unoffered = batches.slice(index).reduce((n, rest) => n + rest.length, 0);
525
+ stats.unofferedWhy = whyUnoffered(out);
452
526
  log(
453
527
  `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.ok ? "the answer had no results" : out.detail || out.kind}).`
454
528
  );
@@ -458,6 +532,60 @@ async function startRun(passed, declared2) {
458
532
  stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
459
533
  }
460
534
  }
535
+ function skip(name, why) {
536
+ stats.screenshots.skipped += 1;
537
+ if (skipsSaid.has(why)) return;
538
+ skipsSaid.add(why);
539
+ log(`plune: screenshot "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
540
+ }
541
+ async function uploadOne(shot) {
542
+ let bytes;
543
+ try {
544
+ if ((await import_fs.promises.stat(shot.path)).size > SCREENSHOT_BYTES) return skip(shot.name, "size");
545
+ bytes = await import_fs.promises.readFile(shot.path);
546
+ } catch {
547
+ return skip(shot.name, "missing");
548
+ }
549
+ const out = await client.upload(
550
+ `/v1/results/${encodeURIComponent(shot.id)}/files?name=${encodeURIComponent(shot.name)}`,
551
+ bytes,
552
+ shot.type
553
+ );
554
+ if (out.ok) {
555
+ stats.screenshots.uploaded += 1;
556
+ return;
557
+ }
558
+ stats.screenshots.failed += 1;
559
+ if (stats.screenshots.failed === 1) {
560
+ log(`plune: could not upload a screenshot (${out.detail || out.kind}) \u2014 its result is reported without it.`);
561
+ }
562
+ }
563
+ async function upload(items, filesByKey) {
564
+ if (filesByKey.size === 0 || !Array.isArray(items)) return;
565
+ const shots = [];
566
+ for (const item of items) {
567
+ if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
568
+ let room = SCREENSHOTS_PER_RESULT;
569
+ for (const file of filesByKey.get(item.resultKey) ?? []) {
570
+ const type = file.contentType?.split(";")[0]?.trim().toLowerCase() || TYPE_BY_EXTENSION[(0, import_path.extname)(file.path).toLowerCase()];
571
+ if (!type?.startsWith("image/")) continue;
572
+ const name = nameOf(file);
573
+ if (file.name.startsWith("_")) skip(name, "hidden");
574
+ else if (!SCREENSHOT_TYPES.has(type)) skip(name, "type");
575
+ else if (room === 0) skip(name, "limit");
576
+ else {
577
+ room -= 1;
578
+ shots.push({ id: item.id, name, type, path: file.path });
579
+ }
580
+ }
581
+ }
582
+ let next = 0;
583
+ await Promise.all(
584
+ Array.from({ length: Math.min(UPLOADS_AT_ONCE, shots.length) }, async () => {
585
+ while (next < shots.length) await uploadOne(shots[next++]);
586
+ })
587
+ );
588
+ }
461
589
  async function flush() {
462
590
  if (buffer.length === 0) return;
463
591
  const pending = buffer;
@@ -469,11 +597,13 @@ async function startRun(passed, declared2) {
469
597
  await resolveKeys(pending.flatMap((p) => p.keys));
470
598
  const submissions = [];
471
599
  const unanswered = [];
600
+ const filesByKey = /* @__PURE__ */ new Map();
472
601
  for (const result of pending) {
473
602
  const match = matchFor(result);
474
603
  if (match.kind === "found") {
475
- const { keys: _keys, ...rest } = result;
604
+ const { keys: _keys, files, ...rest } = result;
476
605
  submissions.push({ ...rest, testCaseId: match.testCaseId });
606
+ if (files !== void 0) filesByKey.set(result.resultKey, files);
477
607
  } else if (match.kind === "unmatched") {
478
608
  stats.unresolved += 1;
479
609
  remember(result);
@@ -491,14 +621,16 @@ async function startRun(passed, declared2) {
491
621
  defer(part);
492
622
  continue;
493
623
  }
494
- const out = await client.post(`/v1/runs/${runId}/results`, {
495
- results: part
496
- });
624
+ const out = await client.post(
625
+ `/v1/runs/${runId}/results`,
626
+ { results: part }
627
+ );
497
628
  const counts = out.ok ? out.body?.counts : void 0;
498
629
  const told = COUNTED.filter((k) => typeof counts?.[k] === "number");
499
630
  if (told.length > 0) {
500
631
  for (const k of told) stats[k] += counts[k];
501
632
  progress();
633
+ await upload(out.ok ? out.body?.items : void 0, filesByKey);
502
634
  continue;
503
635
  }
504
636
  if (out.ok) {
@@ -528,6 +660,12 @@ async function startRun(passed, declared2) {
528
660
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
529
661
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
530
662
  if (stats.created > 0) parts.push(`${stats.created} added as cases (trusted source)`);
663
+ const shots = stats.screenshots;
664
+ if (shots.uploaded + shots.skipped + shots.failed > 0) {
665
+ parts.push(
666
+ `${shots.uploaded} screenshot(s) uploaded` + (shots.skipped > 0 ? `, ${shots.skipped} skipped` : "") + (shots.failed > 0 ? `, ${shots.failed} failed to upload` : "")
667
+ );
668
+ }
531
669
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
532
670
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
533
671
  log(`plune: ${parts.join(" \xB7 ")}`);
@@ -606,15 +744,18 @@ function failureOf(attempt, home = (0, import_os2.homedir)()) {
606
744
  return Object.keys(failure).length === 0 ? void 0 : failure;
607
745
  }
608
746
  function repoRootOf(dir, stopAt) {
609
- for (let here = (0, import_path2.resolve)(dir); ; here = (0, import_path2.dirname)(here)) {
610
- if ((0, import_fs2.existsSync)((0, import_path2.join)(here, ".git"))) return here;
611
- if (here === stopAt || (0, import_path2.dirname)(here) === here) return void 0;
747
+ for (let here = (0, import_path3.resolve)(dir); ; here = (0, import_path3.dirname)(here)) {
748
+ if ((0, import_fs3.existsSync)((0, import_path3.join)(here, ".git"))) return here;
749
+ if (here === stopAt || (0, import_path3.dirname)(here) === here) return void 0;
612
750
  }
613
751
  }
614
752
  function errorContextOf(attempt, home = (0, import_os2.homedir)()) {
615
753
  const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
616
754
  return cut(machineless(text, attempt.repoRoot, home));
617
755
  }
756
+ function filesOf(attempt) {
757
+ return attempt.attachments.filter((a) => a.path !== void 0);
758
+ }
618
759
  function machineless(raw, repoRoot, home) {
619
760
  let text = (0, import_util.stripVTControlCharacters)(raw).replaceAll("\x1B", "");
620
761
  const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
@@ -693,7 +834,7 @@ function fileOf(raw) {
693
834
  }
694
835
  return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
695
836
  }
696
- var normal = (path3) => import_path2.posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
837
+ var normal = (path3) => import_path3.posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
697
838
  function fromRoot(place, root) {
698
839
  if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
699
840
  const base = normal(root).replace(/\/+$/, "");
@@ -785,6 +926,7 @@ function pendingFrom(test, result, ctx) {
785
926
  const attempt = attemptOf(test, result, ctx);
786
927
  const errorContext = errorContextOf(attempt);
787
928
  const failure = NOT_FAILED.has(result.status) ? void 0 : failureOf(attempt);
929
+ const files = filesOf(attempt);
788
930
  const startedAt = result.startTime;
789
931
  return {
790
932
  resultKey: resultKey(test.id, result.retry),
@@ -813,7 +955,9 @@ function pendingFrom(test, result, ctx) {
813
955
  worker: String(result.workerIndex)
814
956
  },
815
957
  ...errorContext !== "" ? { errorContext } : {},
816
- ...failure !== void 0 ? { failure } : {}
958
+ ...failure !== void 0 ? { failure } : {},
959
+ // Every attempt's, a passed one's too; the core uploads the screenshots once the result is stored.
960
+ ...files.length > 0 ? { files } : {}
817
961
  };
818
962
  }
819
963
  var PluneReporter = class {
@@ -868,7 +1012,9 @@ var PluneReporter = class {
868
1012
  ...this.options.externalKey !== void 0 ? { externalKey: this.options.externalKey } : {},
869
1013
  ...this.options.batchSize !== void 0 ? { batchSize: this.options.batchSize } : {},
870
1014
  ...this.options.fallbackPath !== void 0 ? { fallbackPath: this.options.fallbackPath } : {},
871
- meta: { runner: SOURCE, ...ciUrl !== void 0 ? { ciUrl } : {} }
1015
+ // Where it ran (plune#927): the commit Playwright wrote into `metadata.ci`, and its branch —
1016
+ // which Playwright gives on GitLab and Jenkins, and the core reads from the job on GitHub.
1017
+ meta: { runner: SOURCE, ...ciUrl !== void 0 ? { ciUrl } : {}, ...ciCommit(ci) }
872
1018
  },
873
1019
  this.declared
874
1020
  );
package/dist/index.js CHANGED
@@ -3,7 +3,9 @@ import { readFileSync as readFileSync2 } from "fs";
3
3
  import { stripVTControlCharacters as stripVTControlCharacters2 } from "util";
4
4
 
5
5
  // ../../dist/reporter-core.js
6
- import { createHash } from "crypto";
6
+ import { createHash, randomUUID } from "crypto";
7
+ import { promises as disk } from "fs";
8
+ import { basename as basename2, extname } from "path";
7
9
  import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
8
10
  import { homedir } from "os";
9
11
  import { dirname, join } from "path";
@@ -94,7 +96,7 @@ function createClient(opts) {
94
96
  const wait = opts.wait ?? sleep;
95
97
  const base = opts.apiUrl.replace(/\/+$/, "");
96
98
  const scrub = (text) => opts.token === "" ? text : text.split(opts.token).join("***");
97
- async function send(method, path3, body) {
99
+ async function send(method, path3, payload) {
98
100
  let last = {
99
101
  kind: "unavailable",
100
102
  status: null,
@@ -105,11 +107,11 @@ function createClient(opts) {
105
107
  try {
106
108
  res = await doFetch(`${base}${path3}`, {
107
109
  method,
108
- headers: { "content-type": "application/json", authorization: `Bearer ${opts.token}` },
110
+ headers: { "content-type": payload?.type ?? "application/json", authorization: `Bearer ${opts.token}` },
109
111
  // A DELETE carries none. Sending `"undefined"` as a body is what a naive
110
112
  // `JSON.stringify(body)` would do, and some proxies answer that with a 400 nobody can
111
113
  // explain.
112
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
114
+ ...payload === void 0 ? {} : { body: payload.body }
113
115
  });
114
116
  } catch (err) {
115
117
  last = { kind: "unavailable", status: null, detail: scrub(String(err)) };
@@ -135,7 +137,8 @@ function createClient(opts) {
135
137
  return { ok: false, ...last };
136
138
  }
137
139
  return {
138
- post: (path3, body) => send("POST", path3, body),
140
+ post: (path3, body) => send("POST", path3, { body: JSON.stringify(body), type: "application/json" }),
141
+ upload: (path3, bytes, contentType) => send("POST", path3, { body: bytes, type: contentType }),
139
142
  del: (path3) => send("DELETE", path3)
140
143
  };
141
144
  }
@@ -199,6 +202,28 @@ function defaultRunTitle(env = process.env, now = /* @__PURE__ */ new Date(), cw
199
202
  const where = flag(env, "CI") || flag(env, "GITHUB_ACTIONS") ? "ci" : "local";
200
203
  return `${path.basename(cwd)} \xB7 ${stamp} \xB7 ${where}`;
201
204
  }
205
+ var PROVIDERS = [
206
+ { is: "GITHUB_ACTIONS", sha: "GITHUB_SHA", branch: ["GITHUB_HEAD_REF", "GITHUB_REF_NAME"] },
207
+ { is: "GITLAB_CI", sha: "CI_COMMIT_SHA", branch: ["CI_COMMIT_REF_NAME"] },
208
+ { is: "JENKINS_URL", sha: "GIT_COMMIT", branch: ["GIT_BRANCH"] }
209
+ ];
210
+ function ciCommit(reported, env = process.env) {
211
+ const said = typeof reported === "object" && reported !== null ? reported : {};
212
+ const text = (raw) => typeof raw === "string" && raw.trim() !== "" ? raw.trim() : void 0;
213
+ const provider = PROVIDERS.find((p) => value(env, p.is) !== void 0);
214
+ const job = {
215
+ sha: provider === void 0 ? void 0 : value(env, provider.sha),
216
+ branch: provider?.branch.map((name) => value(env, name)).find((v) => v !== void 0)
217
+ };
218
+ const sha = text(said["commitHash"]);
219
+ const sameCommit = sha === void 0 || sha === job.sha;
220
+ const commit = sha ?? job.sha;
221
+ const branch = text(said["branch"]) ?? (sameCommit ? job.branch : void 0);
222
+ return {
223
+ ...commit !== void 0 ? { sha: commit } : {},
224
+ ...branch !== void 0 ? { branch } : {}
225
+ };
226
+ }
202
227
  var DEFAULT_FALLBACK_PATH = path2.join(".plune", "pending-results.jsonl");
203
228
  function appendBatch(file, batch) {
204
229
  fs.mkdirSync(path2.dirname(file), { recursive: true });
@@ -206,6 +231,8 @@ function appendBatch(file, batch) {
206
231
  ts: (/* @__PURE__ */ new Date()).toISOString(),
207
232
  runId: batch.runId,
208
233
  externalKey: batch.externalKey,
234
+ ...batch.session !== void 0 ? { session: batch.session } : {},
235
+ ...batch.meta !== void 0 ? { meta: batch.meta } : {},
209
236
  results: batch.results
210
237
  };
211
238
  fs.appendFileSync(file, `${JSON.stringify(line)}
@@ -219,6 +246,37 @@ var EXPECTED_MAX = 1e4;
219
246
  var KEY_MAX = 1024;
220
247
  var TITLE_MAX = 300;
221
248
  var COUNTED = ["accepted", "duplicate", "conflict", "rejected"];
249
+ var SCREENSHOT_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp"]);
250
+ var SCREENSHOT_BYTES = 2 * 1024 * 1024;
251
+ var SCREENSHOTS_PER_RESULT = 20;
252
+ var TYPE_BY_EXTENSION = {
253
+ ".png": "image/png",
254
+ ".jpg": "image/jpeg",
255
+ ".jpeg": "image/jpeg",
256
+ ".webp": "image/webp"
257
+ };
258
+ var UPLOADS_AT_ONCE = 4;
259
+ var NAME_MAX = 200;
260
+ function nameOf(file) {
261
+ const own = file.name.split(/[\\/]/).pop()?.trim() || basename2(file.path);
262
+ const fileExt = extname(file.path);
263
+ const ownExt = extname(own);
264
+ const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
265
+ const ext = typed ? ownExt : fileExt;
266
+ let stem = typed ? own.slice(0, -ownExt.length) : own;
267
+ if (stem.length + ext.length > NAME_MAX) {
268
+ stem = stem.slice(0, Math.max(0, NAME_MAX - ext.length));
269
+ if (/[\uD800-\uDBFF]$/.test(stem)) stem = stem.slice(0, -1);
270
+ }
271
+ return `${stem}${ext}`;
272
+ }
273
+ var SKIPPED = {
274
+ hidden: "its name starts with an underscore, which hides an attachment in Playwright's own reports too",
275
+ type: "Plune takes PNG, JPEG and WebP",
276
+ limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
277
+ missing: "the file cannot be read on this machine",
278
+ size: "Plune takes a file of at most 2 MB"
279
+ };
222
280
  function boundKey(key) {
223
281
  if (key.value.length <= KEY_MAX) return key;
224
282
  const digest = createHash("sha256").update(key.value).digest("hex").slice(0, 16);
@@ -226,6 +284,12 @@ function boundKey(key) {
226
284
  if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
227
285
  return { ...key, value: `${head}#${digest}` };
228
286
  }
287
+ function whyUnoffered(out) {
288
+ if (out.ok || out.status !== 429) return "other";
289
+ if (/review queue quota reached/i.test(out.detail)) return "queue";
290
+ if (/test case quota reached/i.test(out.detail)) return "cases";
291
+ return "other";
292
+ }
229
293
  function boundTitle(title) {
230
294
  return title.length <= TITLE_MAX ? title : `${title.slice(0, TITLE_MAX - 1)}\u2026`;
231
295
  }
@@ -269,6 +333,7 @@ async function startRun(passed, declared2) {
269
333
  `));
270
334
  const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
271
335
  const externalKey = cfg.externalKey ?? null;
336
+ const sessionMarker = randomUUID();
272
337
  const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
273
338
  const offerDiscovered = cfg.offerDiscovered ?? false;
274
339
  const token = cfg.token ?? loadToken() ?? "";
@@ -286,7 +351,8 @@ async function startRun(passed, declared2) {
286
351
  offered: 0,
287
352
  created: 0,
288
353
  unoffered: 0,
289
- deferred: 0
354
+ deferred: 0,
355
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 }
290
356
  };
291
357
  const resolved = /* @__PURE__ */ new Map();
292
358
  let buffer = [];
@@ -296,6 +362,7 @@ async function startRun(passed, declared2) {
296
362
  let offline = token === "";
297
363
  let done = false;
298
364
  const shortened = /* @__PURE__ */ new Set();
365
+ const skipsSaid = /* @__PURE__ */ new Set();
299
366
  function bound(keys) {
300
367
  return keys.map((key) => {
301
368
  const fit = boundKey(key);
@@ -318,7 +385,13 @@ async function startRun(passed, declared2) {
318
385
  log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
319
386
  }
320
387
  function defer(results) {
321
- appendBatch(fallbackPath, { runId, externalKey, results });
388
+ appendBatch(fallbackPath, {
389
+ runId,
390
+ externalKey,
391
+ session: sessionMarker,
392
+ ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
393
+ results
394
+ });
322
395
  stats.deferred += results.length;
323
396
  }
324
397
  async function resolveKeys(values) {
@@ -415,6 +488,7 @@ async function startRun(passed, declared2) {
415
488
  });
416
489
  if (!out.ok || !Array.isArray(out.body?.results)) {
417
490
  stats.unoffered = batches.slice(index).reduce((n, rest) => n + rest.length, 0);
491
+ stats.unofferedWhy = whyUnoffered(out);
418
492
  log(
419
493
  `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.ok ? "the answer had no results" : out.detail || out.kind}).`
420
494
  );
@@ -424,6 +498,60 @@ async function startRun(passed, declared2) {
424
498
  stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
425
499
  }
426
500
  }
501
+ function skip(name, why) {
502
+ stats.screenshots.skipped += 1;
503
+ if (skipsSaid.has(why)) return;
504
+ skipsSaid.add(why);
505
+ log(`plune: screenshot "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
506
+ }
507
+ async function uploadOne(shot) {
508
+ let bytes;
509
+ try {
510
+ if ((await disk.stat(shot.path)).size > SCREENSHOT_BYTES) return skip(shot.name, "size");
511
+ bytes = await disk.readFile(shot.path);
512
+ } catch {
513
+ return skip(shot.name, "missing");
514
+ }
515
+ const out = await client.upload(
516
+ `/v1/results/${encodeURIComponent(shot.id)}/files?name=${encodeURIComponent(shot.name)}`,
517
+ bytes,
518
+ shot.type
519
+ );
520
+ if (out.ok) {
521
+ stats.screenshots.uploaded += 1;
522
+ return;
523
+ }
524
+ stats.screenshots.failed += 1;
525
+ if (stats.screenshots.failed === 1) {
526
+ log(`plune: could not upload a screenshot (${out.detail || out.kind}) \u2014 its result is reported without it.`);
527
+ }
528
+ }
529
+ async function upload(items, filesByKey) {
530
+ if (filesByKey.size === 0 || !Array.isArray(items)) return;
531
+ const shots = [];
532
+ for (const item of items) {
533
+ if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
534
+ let room = SCREENSHOTS_PER_RESULT;
535
+ for (const file of filesByKey.get(item.resultKey) ?? []) {
536
+ const type = file.contentType?.split(";")[0]?.trim().toLowerCase() || TYPE_BY_EXTENSION[extname(file.path).toLowerCase()];
537
+ if (!type?.startsWith("image/")) continue;
538
+ const name = nameOf(file);
539
+ if (file.name.startsWith("_")) skip(name, "hidden");
540
+ else if (!SCREENSHOT_TYPES.has(type)) skip(name, "type");
541
+ else if (room === 0) skip(name, "limit");
542
+ else {
543
+ room -= 1;
544
+ shots.push({ id: item.id, name, type, path: file.path });
545
+ }
546
+ }
547
+ }
548
+ let next = 0;
549
+ await Promise.all(
550
+ Array.from({ length: Math.min(UPLOADS_AT_ONCE, shots.length) }, async () => {
551
+ while (next < shots.length) await uploadOne(shots[next++]);
552
+ })
553
+ );
554
+ }
427
555
  async function flush() {
428
556
  if (buffer.length === 0) return;
429
557
  const pending = buffer;
@@ -435,11 +563,13 @@ async function startRun(passed, declared2) {
435
563
  await resolveKeys(pending.flatMap((p) => p.keys));
436
564
  const submissions = [];
437
565
  const unanswered = [];
566
+ const filesByKey = /* @__PURE__ */ new Map();
438
567
  for (const result of pending) {
439
568
  const match = matchFor(result);
440
569
  if (match.kind === "found") {
441
- const { keys: _keys, ...rest } = result;
570
+ const { keys: _keys, files, ...rest } = result;
442
571
  submissions.push({ ...rest, testCaseId: match.testCaseId });
572
+ if (files !== void 0) filesByKey.set(result.resultKey, files);
443
573
  } else if (match.kind === "unmatched") {
444
574
  stats.unresolved += 1;
445
575
  remember(result);
@@ -457,14 +587,16 @@ async function startRun(passed, declared2) {
457
587
  defer(part);
458
588
  continue;
459
589
  }
460
- const out = await client.post(`/v1/runs/${runId}/results`, {
461
- results: part
462
- });
590
+ const out = await client.post(
591
+ `/v1/runs/${runId}/results`,
592
+ { results: part }
593
+ );
463
594
  const counts = out.ok ? out.body?.counts : void 0;
464
595
  const told = COUNTED.filter((k) => typeof counts?.[k] === "number");
465
596
  if (told.length > 0) {
466
597
  for (const k of told) stats[k] += counts[k];
467
598
  progress();
599
+ await upload(out.ok ? out.body?.items : void 0, filesByKey);
468
600
  continue;
469
601
  }
470
602
  if (out.ok) {
@@ -494,6 +626,12 @@ async function startRun(passed, declared2) {
494
626
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
495
627
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
496
628
  if (stats.created > 0) parts.push(`${stats.created} added as cases (trusted source)`);
629
+ const shots = stats.screenshots;
630
+ if (shots.uploaded + shots.skipped + shots.failed > 0) {
631
+ parts.push(
632
+ `${shots.uploaded} screenshot(s) uploaded` + (shots.skipped > 0 ? `, ${shots.skipped} skipped` : "") + (shots.failed > 0 ? `, ${shots.failed} failed to upload` : "")
633
+ );
634
+ }
497
635
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
498
636
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
499
637
  log(`plune: ${parts.join(" \xB7 ")}`);
@@ -581,6 +719,9 @@ function errorContextOf(attempt, home = homedir2()) {
581
719
  const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
582
720
  return cut(machineless(text, attempt.repoRoot, home));
583
721
  }
722
+ function filesOf(attempt) {
723
+ return attempt.attachments.filter((a) => a.path !== void 0);
724
+ }
584
725
  function machineless(raw, repoRoot, home) {
585
726
  let text = stripVTControlCharacters(raw).replaceAll("\x1B", "");
586
727
  const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
@@ -751,6 +892,7 @@ function pendingFrom(test, result, ctx) {
751
892
  const attempt = attemptOf(test, result, ctx);
752
893
  const errorContext = errorContextOf(attempt);
753
894
  const failure = NOT_FAILED.has(result.status) ? void 0 : failureOf(attempt);
895
+ const files = filesOf(attempt);
754
896
  const startedAt = result.startTime;
755
897
  return {
756
898
  resultKey: resultKey(test.id, result.retry),
@@ -779,7 +921,9 @@ function pendingFrom(test, result, ctx) {
779
921
  worker: String(result.workerIndex)
780
922
  },
781
923
  ...errorContext !== "" ? { errorContext } : {},
782
- ...failure !== void 0 ? { failure } : {}
924
+ ...failure !== void 0 ? { failure } : {},
925
+ // Every attempt's, a passed one's too; the core uploads the screenshots once the result is stored.
926
+ ...files.length > 0 ? { files } : {}
783
927
  };
784
928
  }
785
929
  var PluneReporter = class {
@@ -834,7 +978,9 @@ var PluneReporter = class {
834
978
  ...this.options.externalKey !== void 0 ? { externalKey: this.options.externalKey } : {},
835
979
  ...this.options.batchSize !== void 0 ? { batchSize: this.options.batchSize } : {},
836
980
  ...this.options.fallbackPath !== void 0 ? { fallbackPath: this.options.fallbackPath } : {},
837
- meta: { runner: SOURCE, ...ciUrl !== void 0 ? { ciUrl } : {} }
981
+ // Where it ran (plune#927): the commit Playwright wrote into `metadata.ci`, and its branch —
982
+ // which Playwright gives on GitLab and Jenkins, and the core reads from the job on GitHub.
983
+ meta: { runner: SOURCE, ...ciUrl !== void 0 ? { ciUrl } : {}, ...ciCommit(ci) }
838
984
  },
839
985
  this.declared
840
986
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plune-ai/playwright",
3
- "version": "0.2.8",
3
+ "version": "0.4.0",
4
4
  "description": "Report Playwright results to Plune — a reporter and, later, a test importer.",
5
5
  "keywords": [
6
6
  "playwright",
@@ -38,7 +38,7 @@
38
38
  "tsup": "^8.0.0",
39
39
  "typescript": "^5.4.0",
40
40
  "vitest": "^1.6.0",
41
- "@plune-ai/cli": "0.14.2"
41
+ "@plune-ai/cli": "0.16.0"
42
42
  },
43
43
  "repository": {
44
44
  "type": "git",