@plune-ai/playwright 0.2.7 → 0.3.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
  }
@@ -252,6 +255,38 @@ var BATCH_DEFAULT = 100;
252
255
  var EXPECTED_MAX = 1e4;
253
256
  var KEY_MAX = 1024;
254
257
  var TITLE_MAX = 300;
258
+ var COUNTED = ["accepted", "duplicate", "conflict", "rejected"];
259
+ var SCREENSHOT_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp"]);
260
+ var SCREENSHOT_BYTES = 2 * 1024 * 1024;
261
+ var SCREENSHOTS_PER_RESULT = 20;
262
+ var TYPE_BY_EXTENSION = {
263
+ ".png": "image/png",
264
+ ".jpg": "image/jpeg",
265
+ ".jpeg": "image/jpeg",
266
+ ".webp": "image/webp"
267
+ };
268
+ var UPLOADS_AT_ONCE = 4;
269
+ var NAME_MAX = 200;
270
+ function nameOf(file) {
271
+ const own = file.name.split(/[\\/]/).pop()?.trim() || (0, import_path.basename)(file.path);
272
+ const fileExt = (0, import_path.extname)(file.path);
273
+ const ownExt = (0, import_path.extname)(own);
274
+ const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
275
+ const ext = typed ? ownExt : fileExt;
276
+ let stem = typed ? own.slice(0, -ownExt.length) : own;
277
+ if (stem.length + ext.length > NAME_MAX) {
278
+ stem = stem.slice(0, Math.max(0, NAME_MAX - ext.length));
279
+ if (/[\uD800-\uDBFF]$/.test(stem)) stem = stem.slice(0, -1);
280
+ }
281
+ return `${stem}${ext}`;
282
+ }
283
+ var SKIPPED = {
284
+ hidden: "its name starts with an underscore, which hides an attachment in Playwright's own reports too",
285
+ type: "Plune takes PNG, JPEG and WebP",
286
+ limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
287
+ missing: "the file cannot be read on this machine",
288
+ size: "Plune takes a file of at most 2 MB"
289
+ };
255
290
  function boundKey(key) {
256
291
  if (key.value.length <= KEY_MAX) return key;
257
292
  const digest = (0, import_crypto.createHash)("sha256").update(key.value).digest("hex").slice(0, 16);
@@ -319,7 +354,8 @@ async function startRun(passed, declared2) {
319
354
  offered: 0,
320
355
  created: 0,
321
356
  unoffered: 0,
322
- deferred: 0
357
+ deferred: 0,
358
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 }
323
359
  };
324
360
  const resolved = /* @__PURE__ */ new Map();
325
361
  let buffer = [];
@@ -329,6 +365,7 @@ async function startRun(passed, declared2) {
329
365
  let offline = token === "";
330
366
  let done = false;
331
367
  const shortened = /* @__PURE__ */ new Set();
368
+ const skipsSaid = /* @__PURE__ */ new Set();
332
369
  function bound(keys) {
333
370
  return keys.map((key) => {
334
371
  const fit = boundKey(key);
@@ -362,11 +399,13 @@ async function startRun(passed, declared2) {
362
399
  "/v1/test-cases/resolve",
363
400
  { keys: part }
364
401
  );
365
- if (!out.ok) {
366
- log(`plune: could not look up test cases (${out.detail || out.kind}).`);
402
+ if (!out.ok || !Array.isArray(out.body?.results)) {
403
+ log(`plune: could not look up test cases (${out.ok ? "the answer had no results" : out.detail || out.kind}).`);
367
404
  return;
368
405
  }
369
- for (const row of out.body.results) resolved.set(row.key.value, row.testCaseId);
406
+ for (const row of out.body.results) {
407
+ if (typeof row?.key?.value === "string") resolved.set(row.key.value, row.testCaseId);
408
+ }
370
409
  }
371
410
  }
372
411
  if (!offline) {
@@ -403,12 +442,13 @@ async function startRun(passed, declared2) {
403
442
  title: defaultRunTitle(),
404
443
  ...described
405
444
  });
406
- if (start.ok) {
445
+ if (start.ok && typeof start.body?.run?.id === "string") {
407
446
  runId = start.body.run.id;
408
447
  joined = start.status === 200;
409
448
  warnIfDropped(described, start.body.run, log);
410
449
  } else {
411
- log(`plune: could not start the run (${start.detail || start.kind}). Results will be written to ${fallbackPath}.`);
450
+ const why = start.ok ? "the answer had no run" : start.detail || start.kind;
451
+ log(`plune: could not start the run (${why}). Results will be written to ${fallbackPath}.`);
412
452
  }
413
453
  }
414
454
  function matchFor(result) {
@@ -443,16 +483,70 @@ async function startRun(passed, declared2) {
443
483
  discovered: batch,
444
484
  runId
445
485
  });
446
- if (!out.ok) {
486
+ if (!out.ok || !Array.isArray(out.body?.results)) {
447
487
  stats.unoffered = batches.slice(index).reduce((n, rest) => n + rest.length, 0);
448
488
  log(
449
- `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.detail || out.kind}).`
489
+ `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.ok ? "the answer had no results" : out.detail || out.kind}).`
450
490
  );
451
491
  return;
452
492
  }
453
- stats.offered += out.body.results.filter((r) => r.outcome === "queued").length;
454
- stats.created += out.body.results.filter((r) => r.outcome === "created").length;
493
+ stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
494
+ stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
495
+ }
496
+ }
497
+ function skip(name, why) {
498
+ stats.screenshots.skipped += 1;
499
+ if (skipsSaid.has(why)) return;
500
+ skipsSaid.add(why);
501
+ log(`plune: screenshot "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
502
+ }
503
+ async function uploadOne(shot) {
504
+ let bytes;
505
+ try {
506
+ if ((await import_fs.promises.stat(shot.path)).size > SCREENSHOT_BYTES) return skip(shot.name, "size");
507
+ bytes = await import_fs.promises.readFile(shot.path);
508
+ } catch {
509
+ return skip(shot.name, "missing");
510
+ }
511
+ const out = await client.upload(
512
+ `/v1/results/${encodeURIComponent(shot.id)}/files?name=${encodeURIComponent(shot.name)}`,
513
+ bytes,
514
+ shot.type
515
+ );
516
+ if (out.ok) {
517
+ stats.screenshots.uploaded += 1;
518
+ return;
519
+ }
520
+ stats.screenshots.failed += 1;
521
+ if (stats.screenshots.failed === 1) {
522
+ log(`plune: could not upload a screenshot (${out.detail || out.kind}) \u2014 its result is reported without it.`);
523
+ }
524
+ }
525
+ async function upload(items, filesByKey) {
526
+ if (filesByKey.size === 0 || !Array.isArray(items)) return;
527
+ const shots = [];
528
+ for (const item of items) {
529
+ if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
530
+ let room = SCREENSHOTS_PER_RESULT;
531
+ for (const file of filesByKey.get(item.resultKey) ?? []) {
532
+ const type = file.contentType?.split(";")[0]?.trim().toLowerCase() || TYPE_BY_EXTENSION[(0, import_path.extname)(file.path).toLowerCase()];
533
+ if (!type?.startsWith("image/")) continue;
534
+ const name = nameOf(file);
535
+ if (file.name.startsWith("_")) skip(name, "hidden");
536
+ else if (!SCREENSHOT_TYPES.has(type)) skip(name, "type");
537
+ else if (room === 0) skip(name, "limit");
538
+ else {
539
+ room -= 1;
540
+ shots.push({ id: item.id, name, type, path: file.path });
541
+ }
542
+ }
455
543
  }
544
+ let next = 0;
545
+ await Promise.all(
546
+ Array.from({ length: Math.min(UPLOADS_AT_ONCE, shots.length) }, async () => {
547
+ while (next < shots.length) await uploadOne(shots[next++]);
548
+ })
549
+ );
456
550
  }
457
551
  async function flush() {
458
552
  if (buffer.length === 0) return;
@@ -465,11 +559,13 @@ async function startRun(passed, declared2) {
465
559
  await resolveKeys(pending.flatMap((p) => p.keys));
466
560
  const submissions = [];
467
561
  const unanswered = [];
562
+ const filesByKey = /* @__PURE__ */ new Map();
468
563
  for (const result of pending) {
469
564
  const match = matchFor(result);
470
565
  if (match.kind === "found") {
471
- const { keys: _keys, ...rest } = result;
566
+ const { keys: _keys, files, ...rest } = result;
472
567
  submissions.push({ ...rest, testCaseId: match.testCaseId });
568
+ if (files !== void 0) filesByKey.set(result.resultKey, files);
473
569
  } else if (match.kind === "unmatched") {
474
570
  stats.unresolved += 1;
475
571
  remember(result);
@@ -487,16 +583,16 @@ async function startRun(passed, declared2) {
487
583
  defer(part);
488
584
  continue;
489
585
  }
490
- const out = await client.post(`/v1/runs/${runId}/results`, {
491
- results: part
492
- });
586
+ const out = await client.post(
587
+ `/v1/runs/${runId}/results`,
588
+ { results: part }
589
+ );
493
590
  const counts = out.ok ? out.body?.counts : void 0;
494
- if (counts !== void 0) {
495
- stats.accepted += counts.accepted ?? 0;
496
- stats.duplicate += counts.duplicate ?? 0;
497
- stats.conflict += counts.conflict ?? 0;
498
- stats.rejected += counts.rejected ?? 0;
591
+ const told = COUNTED.filter((k) => typeof counts?.[k] === "number");
592
+ if (told.length > 0) {
593
+ for (const k of told) stats[k] += counts[k];
499
594
  progress();
595
+ await upload(out.ok ? out.body?.items : void 0, filesByKey);
500
596
  continue;
501
597
  }
502
598
  if (out.ok) {
@@ -526,6 +622,12 @@ async function startRun(passed, declared2) {
526
622
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
527
623
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
528
624
  if (stats.created > 0) parts.push(`${stats.created} added as cases (trusted source)`);
625
+ const shots = stats.screenshots;
626
+ if (shots.uploaded + shots.skipped + shots.failed > 0) {
627
+ parts.push(
628
+ `${shots.uploaded} screenshot(s) uploaded` + (shots.skipped > 0 ? `, ${shots.skipped} skipped` : "") + (shots.failed > 0 ? `, ${shots.failed} failed to upload` : "")
629
+ );
630
+ }
529
631
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
530
632
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
531
633
  log(`plune: ${parts.join(" \xB7 ")}`);
@@ -559,7 +661,7 @@ async function startRun(passed, declared2) {
559
661
  ...reason !== void 0 ? { reason } : {}
560
662
  });
561
663
  if (!out.ok) log(`plune: could not close run ${runId} (${out.detail || out.kind}).`);
562
- else if (typeof out.body.detached === "number" && out.body.detached > 0) {
664
+ else if (typeof out.body?.detached === "number" && out.body.detached > 0) {
563
665
  log(`plune: ${out.body.detached} test case(s) marked detached \u2014 this full run no longer reports them.`);
564
666
  }
565
667
  }
@@ -604,15 +706,18 @@ function failureOf(attempt, home = (0, import_os2.homedir)()) {
604
706
  return Object.keys(failure).length === 0 ? void 0 : failure;
605
707
  }
606
708
  function repoRootOf(dir, stopAt) {
607
- for (let here = (0, import_path2.resolve)(dir); ; here = (0, import_path2.dirname)(here)) {
608
- if ((0, import_fs2.existsSync)((0, import_path2.join)(here, ".git"))) return here;
609
- if (here === stopAt || (0, import_path2.dirname)(here) === here) return void 0;
709
+ for (let here = (0, import_path3.resolve)(dir); ; here = (0, import_path3.dirname)(here)) {
710
+ if ((0, import_fs3.existsSync)((0, import_path3.join)(here, ".git"))) return here;
711
+ if (here === stopAt || (0, import_path3.dirname)(here) === here) return void 0;
610
712
  }
611
713
  }
612
714
  function errorContextOf(attempt, home = (0, import_os2.homedir)()) {
613
715
  const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
614
716
  return cut(machineless(text, attempt.repoRoot, home));
615
717
  }
718
+ function filesOf(attempt) {
719
+ return attempt.attachments.filter((a) => a.path !== void 0);
720
+ }
616
721
  function machineless(raw, repoRoot, home) {
617
722
  let text = (0, import_util.stripVTControlCharacters)(raw).replaceAll("\x1B", "");
618
723
  const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
@@ -626,13 +731,15 @@ var PATH_START = "(?<![\\w.~%/\\\\-])";
626
731
  var TEXT_LIMIT = 524288;
627
732
  var HEADLINE_LIMIT = 8 * 1024;
628
733
  var jsonBytes = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
629
- var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:file:\/\/\/?)?(?:\/home\/|\/Users\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
734
+ var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
630
735
  function pathIn(path3) {
631
736
  const parts = path3.split(/[\\/]+/);
632
737
  while (parts.length > 1 && parts.at(-1) === "") parts.pop();
633
738
  if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
634
- const escaped = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
635
- return new RegExp(`(?:file:\\/\\/\\/?)?${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
739
+ const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
740
+ const escaped = /^\/(?!\/)/.test(path3) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
741
+ const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
742
+ return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
636
743
  }
637
744
  var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
638
745
  function cut(text) {
@@ -689,7 +796,7 @@ function fileOf(raw) {
689
796
  }
690
797
  return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
691
798
  }
692
- var normal = (path3) => import_path2.posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
799
+ var normal = (path3) => import_path3.posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
693
800
  function fromRoot(place, root) {
694
801
  if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
695
802
  const base = normal(root).replace(/\/+$/, "");
@@ -781,6 +888,7 @@ function pendingFrom(test, result, ctx) {
781
888
  const attempt = attemptOf(test, result, ctx);
782
889
  const errorContext = errorContextOf(attempt);
783
890
  const failure = NOT_FAILED.has(result.status) ? void 0 : failureOf(attempt);
891
+ const files = filesOf(attempt);
784
892
  const startedAt = result.startTime;
785
893
  return {
786
894
  resultKey: resultKey(test.id, result.retry),
@@ -809,7 +917,9 @@ function pendingFrom(test, result, ctx) {
809
917
  worker: String(result.workerIndex)
810
918
  },
811
919
  ...errorContext !== "" ? { errorContext } : {},
812
- ...failure !== void 0 ? { failure } : {}
920
+ ...failure !== void 0 ? { failure } : {},
921
+ // Every attempt's, a passed one's too; the core uploads the screenshots once the result is stored.
922
+ ...files.length > 0 ? { files } : {}
813
923
  };
814
924
  }
815
925
  var PluneReporter = class {
package/dist/index.js CHANGED
@@ -4,6 +4,8 @@ import { stripVTControlCharacters as stripVTControlCharacters2 } from "util";
4
4
 
5
5
  // ../../dist/reporter-core.js
6
6
  import { createHash } 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
  }
@@ -218,6 +221,38 @@ var BATCH_DEFAULT = 100;
218
221
  var EXPECTED_MAX = 1e4;
219
222
  var KEY_MAX = 1024;
220
223
  var TITLE_MAX = 300;
224
+ var COUNTED = ["accepted", "duplicate", "conflict", "rejected"];
225
+ var SCREENSHOT_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp"]);
226
+ var SCREENSHOT_BYTES = 2 * 1024 * 1024;
227
+ var SCREENSHOTS_PER_RESULT = 20;
228
+ var TYPE_BY_EXTENSION = {
229
+ ".png": "image/png",
230
+ ".jpg": "image/jpeg",
231
+ ".jpeg": "image/jpeg",
232
+ ".webp": "image/webp"
233
+ };
234
+ var UPLOADS_AT_ONCE = 4;
235
+ var NAME_MAX = 200;
236
+ function nameOf(file) {
237
+ const own = file.name.split(/[\\/]/).pop()?.trim() || basename2(file.path);
238
+ const fileExt = extname(file.path);
239
+ const ownExt = extname(own);
240
+ const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
241
+ const ext = typed ? ownExt : fileExt;
242
+ let stem = typed ? own.slice(0, -ownExt.length) : own;
243
+ if (stem.length + ext.length > NAME_MAX) {
244
+ stem = stem.slice(0, Math.max(0, NAME_MAX - ext.length));
245
+ if (/[\uD800-\uDBFF]$/.test(stem)) stem = stem.slice(0, -1);
246
+ }
247
+ return `${stem}${ext}`;
248
+ }
249
+ var SKIPPED = {
250
+ hidden: "its name starts with an underscore, which hides an attachment in Playwright's own reports too",
251
+ type: "Plune takes PNG, JPEG and WebP",
252
+ limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
253
+ missing: "the file cannot be read on this machine",
254
+ size: "Plune takes a file of at most 2 MB"
255
+ };
221
256
  function boundKey(key) {
222
257
  if (key.value.length <= KEY_MAX) return key;
223
258
  const digest = createHash("sha256").update(key.value).digest("hex").slice(0, 16);
@@ -285,7 +320,8 @@ async function startRun(passed, declared2) {
285
320
  offered: 0,
286
321
  created: 0,
287
322
  unoffered: 0,
288
- deferred: 0
323
+ deferred: 0,
324
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 }
289
325
  };
290
326
  const resolved = /* @__PURE__ */ new Map();
291
327
  let buffer = [];
@@ -295,6 +331,7 @@ async function startRun(passed, declared2) {
295
331
  let offline = token === "";
296
332
  let done = false;
297
333
  const shortened = /* @__PURE__ */ new Set();
334
+ const skipsSaid = /* @__PURE__ */ new Set();
298
335
  function bound(keys) {
299
336
  return keys.map((key) => {
300
337
  const fit = boundKey(key);
@@ -328,11 +365,13 @@ async function startRun(passed, declared2) {
328
365
  "/v1/test-cases/resolve",
329
366
  { keys: part }
330
367
  );
331
- if (!out.ok) {
332
- log(`plune: could not look up test cases (${out.detail || out.kind}).`);
368
+ if (!out.ok || !Array.isArray(out.body?.results)) {
369
+ log(`plune: could not look up test cases (${out.ok ? "the answer had no results" : out.detail || out.kind}).`);
333
370
  return;
334
371
  }
335
- for (const row of out.body.results) resolved.set(row.key.value, row.testCaseId);
372
+ for (const row of out.body.results) {
373
+ if (typeof row?.key?.value === "string") resolved.set(row.key.value, row.testCaseId);
374
+ }
336
375
  }
337
376
  }
338
377
  if (!offline) {
@@ -369,12 +408,13 @@ async function startRun(passed, declared2) {
369
408
  title: defaultRunTitle(),
370
409
  ...described
371
410
  });
372
- if (start.ok) {
411
+ if (start.ok && typeof start.body?.run?.id === "string") {
373
412
  runId = start.body.run.id;
374
413
  joined = start.status === 200;
375
414
  warnIfDropped(described, start.body.run, log);
376
415
  } else {
377
- log(`plune: could not start the run (${start.detail || start.kind}). Results will be written to ${fallbackPath}.`);
416
+ const why = start.ok ? "the answer had no run" : start.detail || start.kind;
417
+ log(`plune: could not start the run (${why}). Results will be written to ${fallbackPath}.`);
378
418
  }
379
419
  }
380
420
  function matchFor(result) {
@@ -409,16 +449,70 @@ async function startRun(passed, declared2) {
409
449
  discovered: batch,
410
450
  runId
411
451
  });
412
- if (!out.ok) {
452
+ if (!out.ok || !Array.isArray(out.body?.results)) {
413
453
  stats.unoffered = batches.slice(index).reduce((n, rest) => n + rest.length, 0);
414
454
  log(
415
- `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.detail || out.kind}).`
455
+ `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.ok ? "the answer had no results" : out.detail || out.kind}).`
416
456
  );
417
457
  return;
418
458
  }
419
- stats.offered += out.body.results.filter((r) => r.outcome === "queued").length;
420
- stats.created += out.body.results.filter((r) => r.outcome === "created").length;
459
+ stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
460
+ stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
461
+ }
462
+ }
463
+ function skip(name, why) {
464
+ stats.screenshots.skipped += 1;
465
+ if (skipsSaid.has(why)) return;
466
+ skipsSaid.add(why);
467
+ log(`plune: screenshot "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
468
+ }
469
+ async function uploadOne(shot) {
470
+ let bytes;
471
+ try {
472
+ if ((await disk.stat(shot.path)).size > SCREENSHOT_BYTES) return skip(shot.name, "size");
473
+ bytes = await disk.readFile(shot.path);
474
+ } catch {
475
+ return skip(shot.name, "missing");
476
+ }
477
+ const out = await client.upload(
478
+ `/v1/results/${encodeURIComponent(shot.id)}/files?name=${encodeURIComponent(shot.name)}`,
479
+ bytes,
480
+ shot.type
481
+ );
482
+ if (out.ok) {
483
+ stats.screenshots.uploaded += 1;
484
+ return;
485
+ }
486
+ stats.screenshots.failed += 1;
487
+ if (stats.screenshots.failed === 1) {
488
+ log(`plune: could not upload a screenshot (${out.detail || out.kind}) \u2014 its result is reported without it.`);
489
+ }
490
+ }
491
+ async function upload(items, filesByKey) {
492
+ if (filesByKey.size === 0 || !Array.isArray(items)) return;
493
+ const shots = [];
494
+ for (const item of items) {
495
+ if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
496
+ let room = SCREENSHOTS_PER_RESULT;
497
+ for (const file of filesByKey.get(item.resultKey) ?? []) {
498
+ const type = file.contentType?.split(";")[0]?.trim().toLowerCase() || TYPE_BY_EXTENSION[extname(file.path).toLowerCase()];
499
+ if (!type?.startsWith("image/")) continue;
500
+ const name = nameOf(file);
501
+ if (file.name.startsWith("_")) skip(name, "hidden");
502
+ else if (!SCREENSHOT_TYPES.has(type)) skip(name, "type");
503
+ else if (room === 0) skip(name, "limit");
504
+ else {
505
+ room -= 1;
506
+ shots.push({ id: item.id, name, type, path: file.path });
507
+ }
508
+ }
421
509
  }
510
+ let next = 0;
511
+ await Promise.all(
512
+ Array.from({ length: Math.min(UPLOADS_AT_ONCE, shots.length) }, async () => {
513
+ while (next < shots.length) await uploadOne(shots[next++]);
514
+ })
515
+ );
422
516
  }
423
517
  async function flush() {
424
518
  if (buffer.length === 0) return;
@@ -431,11 +525,13 @@ async function startRun(passed, declared2) {
431
525
  await resolveKeys(pending.flatMap((p) => p.keys));
432
526
  const submissions = [];
433
527
  const unanswered = [];
528
+ const filesByKey = /* @__PURE__ */ new Map();
434
529
  for (const result of pending) {
435
530
  const match = matchFor(result);
436
531
  if (match.kind === "found") {
437
- const { keys: _keys, ...rest } = result;
532
+ const { keys: _keys, files, ...rest } = result;
438
533
  submissions.push({ ...rest, testCaseId: match.testCaseId });
534
+ if (files !== void 0) filesByKey.set(result.resultKey, files);
439
535
  } else if (match.kind === "unmatched") {
440
536
  stats.unresolved += 1;
441
537
  remember(result);
@@ -453,16 +549,16 @@ async function startRun(passed, declared2) {
453
549
  defer(part);
454
550
  continue;
455
551
  }
456
- const out = await client.post(`/v1/runs/${runId}/results`, {
457
- results: part
458
- });
552
+ const out = await client.post(
553
+ `/v1/runs/${runId}/results`,
554
+ { results: part }
555
+ );
459
556
  const counts = out.ok ? out.body?.counts : void 0;
460
- if (counts !== void 0) {
461
- stats.accepted += counts.accepted ?? 0;
462
- stats.duplicate += counts.duplicate ?? 0;
463
- stats.conflict += counts.conflict ?? 0;
464
- stats.rejected += counts.rejected ?? 0;
557
+ const told = COUNTED.filter((k) => typeof counts?.[k] === "number");
558
+ if (told.length > 0) {
559
+ for (const k of told) stats[k] += counts[k];
465
560
  progress();
561
+ await upload(out.ok ? out.body?.items : void 0, filesByKey);
466
562
  continue;
467
563
  }
468
564
  if (out.ok) {
@@ -492,6 +588,12 @@ async function startRun(passed, declared2) {
492
588
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
493
589
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
494
590
  if (stats.created > 0) parts.push(`${stats.created} added as cases (trusted source)`);
591
+ const shots = stats.screenshots;
592
+ if (shots.uploaded + shots.skipped + shots.failed > 0) {
593
+ parts.push(
594
+ `${shots.uploaded} screenshot(s) uploaded` + (shots.skipped > 0 ? `, ${shots.skipped} skipped` : "") + (shots.failed > 0 ? `, ${shots.failed} failed to upload` : "")
595
+ );
596
+ }
495
597
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
496
598
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
497
599
  log(`plune: ${parts.join(" \xB7 ")}`);
@@ -525,7 +627,7 @@ async function startRun(passed, declared2) {
525
627
  ...reason !== void 0 ? { reason } : {}
526
628
  });
527
629
  if (!out.ok) log(`plune: could not close run ${runId} (${out.detail || out.kind}).`);
528
- else if (typeof out.body.detached === "number" && out.body.detached > 0) {
630
+ else if (typeof out.body?.detached === "number" && out.body.detached > 0) {
529
631
  log(`plune: ${out.body.detached} test case(s) marked detached \u2014 this full run no longer reports them.`);
530
632
  }
531
633
  }
@@ -579,6 +681,9 @@ function errorContextOf(attempt, home = homedir2()) {
579
681
  const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
580
682
  return cut(machineless(text, attempt.repoRoot, home));
581
683
  }
684
+ function filesOf(attempt) {
685
+ return attempt.attachments.filter((a) => a.path !== void 0);
686
+ }
582
687
  function machineless(raw, repoRoot, home) {
583
688
  let text = stripVTControlCharacters(raw).replaceAll("\x1B", "");
584
689
  const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
@@ -592,13 +697,15 @@ var PATH_START = "(?<![\\w.~%/\\\\-])";
592
697
  var TEXT_LIMIT = 524288;
593
698
  var HEADLINE_LIMIT = 8 * 1024;
594
699
  var jsonBytes = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
595
- var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:file:\/\/\/?)?(?:\/home\/|\/Users\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
700
+ var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
596
701
  function pathIn(path3) {
597
702
  const parts = path3.split(/[\\/]+/);
598
703
  while (parts.length > 1 && parts.at(-1) === "") parts.pop();
599
704
  if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
600
- const escaped = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
601
- return new RegExp(`(?:file:\\/\\/\\/?)?${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
705
+ const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
706
+ const escaped = /^\/(?!\/)/.test(path3) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
707
+ const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
708
+ return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
602
709
  }
603
710
  var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
604
711
  function cut(text) {
@@ -747,6 +854,7 @@ function pendingFrom(test, result, ctx) {
747
854
  const attempt = attemptOf(test, result, ctx);
748
855
  const errorContext = errorContextOf(attempt);
749
856
  const failure = NOT_FAILED.has(result.status) ? void 0 : failureOf(attempt);
857
+ const files = filesOf(attempt);
750
858
  const startedAt = result.startTime;
751
859
  return {
752
860
  resultKey: resultKey(test.id, result.retry),
@@ -775,7 +883,9 @@ function pendingFrom(test, result, ctx) {
775
883
  worker: String(result.workerIndex)
776
884
  },
777
885
  ...errorContext !== "" ? { errorContext } : {},
778
- ...failure !== void 0 ? { failure } : {}
886
+ ...failure !== void 0 ? { failure } : {},
887
+ // Every attempt's, a passed one's too; the core uploads the screenshots once the result is stored.
888
+ ...files.length > 0 ? { files } : {}
779
889
  };
780
890
  }
781
891
  var PluneReporter = class {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plune-ai/playwright",
3
- "version": "0.2.7",
3
+ "version": "0.3.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.1"
41
+ "@plune-ai/cli": "0.15.0"
42
42
  },
43
43
  "repository": {
44
44
  "type": "git",