@plune-ai/playwright 0.2.8 → 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
  }
@@ -253,6 +256,37 @@ var EXPECTED_MAX = 1e4;
253
256
  var KEY_MAX = 1024;
254
257
  var TITLE_MAX = 300;
255
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
+ };
256
290
  function boundKey(key) {
257
291
  if (key.value.length <= KEY_MAX) return key;
258
292
  const digest = (0, import_crypto.createHash)("sha256").update(key.value).digest("hex").slice(0, 16);
@@ -320,7 +354,8 @@ async function startRun(passed, declared2) {
320
354
  offered: 0,
321
355
  created: 0,
322
356
  unoffered: 0,
323
- deferred: 0
357
+ deferred: 0,
358
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 }
324
359
  };
325
360
  const resolved = /* @__PURE__ */ new Map();
326
361
  let buffer = [];
@@ -330,6 +365,7 @@ async function startRun(passed, declared2) {
330
365
  let offline = token === "";
331
366
  let done = false;
332
367
  const shortened = /* @__PURE__ */ new Set();
368
+ const skipsSaid = /* @__PURE__ */ new Set();
333
369
  function bound(keys) {
334
370
  return keys.map((key) => {
335
371
  const fit = boundKey(key);
@@ -458,6 +494,60 @@ async function startRun(passed, declared2) {
458
494
  stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
459
495
  }
460
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
+ }
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
+ );
550
+ }
461
551
  async function flush() {
462
552
  if (buffer.length === 0) return;
463
553
  const pending = buffer;
@@ -469,11 +559,13 @@ async function startRun(passed, declared2) {
469
559
  await resolveKeys(pending.flatMap((p) => p.keys));
470
560
  const submissions = [];
471
561
  const unanswered = [];
562
+ const filesByKey = /* @__PURE__ */ new Map();
472
563
  for (const result of pending) {
473
564
  const match = matchFor(result);
474
565
  if (match.kind === "found") {
475
- const { keys: _keys, ...rest } = result;
566
+ const { keys: _keys, files, ...rest } = result;
476
567
  submissions.push({ ...rest, testCaseId: match.testCaseId });
568
+ if (files !== void 0) filesByKey.set(result.resultKey, files);
477
569
  } else if (match.kind === "unmatched") {
478
570
  stats.unresolved += 1;
479
571
  remember(result);
@@ -491,14 +583,16 @@ async function startRun(passed, declared2) {
491
583
  defer(part);
492
584
  continue;
493
585
  }
494
- const out = await client.post(`/v1/runs/${runId}/results`, {
495
- results: part
496
- });
586
+ const out = await client.post(
587
+ `/v1/runs/${runId}/results`,
588
+ { results: part }
589
+ );
497
590
  const counts = out.ok ? out.body?.counts : void 0;
498
591
  const told = COUNTED.filter((k) => typeof counts?.[k] === "number");
499
592
  if (told.length > 0) {
500
593
  for (const k of told) stats[k] += counts[k];
501
594
  progress();
595
+ await upload(out.ok ? out.body?.items : void 0, filesByKey);
502
596
  continue;
503
597
  }
504
598
  if (out.ok) {
@@ -528,6 +622,12 @@ async function startRun(passed, declared2) {
528
622
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
529
623
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
530
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
+ }
531
631
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
532
632
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
533
633
  log(`plune: ${parts.join(" \xB7 ")}`);
@@ -606,15 +706,18 @@ function failureOf(attempt, home = (0, import_os2.homedir)()) {
606
706
  return Object.keys(failure).length === 0 ? void 0 : failure;
607
707
  }
608
708
  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;
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;
612
712
  }
613
713
  }
614
714
  function errorContextOf(attempt, home = (0, import_os2.homedir)()) {
615
715
  const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
616
716
  return cut(machineless(text, attempt.repoRoot, home));
617
717
  }
718
+ function filesOf(attempt) {
719
+ return attempt.attachments.filter((a) => a.path !== void 0);
720
+ }
618
721
  function machineless(raw, repoRoot, home) {
619
722
  let text = (0, import_util.stripVTControlCharacters)(raw).replaceAll("\x1B", "");
620
723
  const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
@@ -693,7 +796,7 @@ function fileOf(raw) {
693
796
  }
694
797
  return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
695
798
  }
696
- 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()}:`);
697
800
  function fromRoot(place, root) {
698
801
  if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
699
802
  const base = normal(root).replace(/\/+$/, "");
@@ -785,6 +888,7 @@ function pendingFrom(test, result, ctx) {
785
888
  const attempt = attemptOf(test, result, ctx);
786
889
  const errorContext = errorContextOf(attempt);
787
890
  const failure = NOT_FAILED.has(result.status) ? void 0 : failureOf(attempt);
891
+ const files = filesOf(attempt);
788
892
  const startedAt = result.startTime;
789
893
  return {
790
894
  resultKey: resultKey(test.id, result.retry),
@@ -813,7 +917,9 @@ function pendingFrom(test, result, ctx) {
813
917
  worker: String(result.workerIndex)
814
918
  },
815
919
  ...errorContext !== "" ? { errorContext } : {},
816
- ...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 } : {}
817
923
  };
818
924
  }
819
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
  }
@@ -219,6 +222,37 @@ var EXPECTED_MAX = 1e4;
219
222
  var KEY_MAX = 1024;
220
223
  var TITLE_MAX = 300;
221
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
+ };
222
256
  function boundKey(key) {
223
257
  if (key.value.length <= KEY_MAX) return key;
224
258
  const digest = createHash("sha256").update(key.value).digest("hex").slice(0, 16);
@@ -286,7 +320,8 @@ async function startRun(passed, declared2) {
286
320
  offered: 0,
287
321
  created: 0,
288
322
  unoffered: 0,
289
- deferred: 0
323
+ deferred: 0,
324
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 }
290
325
  };
291
326
  const resolved = /* @__PURE__ */ new Map();
292
327
  let buffer = [];
@@ -296,6 +331,7 @@ async function startRun(passed, declared2) {
296
331
  let offline = token === "";
297
332
  let done = false;
298
333
  const shortened = /* @__PURE__ */ new Set();
334
+ const skipsSaid = /* @__PURE__ */ new Set();
299
335
  function bound(keys) {
300
336
  return keys.map((key) => {
301
337
  const fit = boundKey(key);
@@ -424,6 +460,60 @@ async function startRun(passed, declared2) {
424
460
  stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
425
461
  }
426
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
+ }
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
+ );
516
+ }
427
517
  async function flush() {
428
518
  if (buffer.length === 0) return;
429
519
  const pending = buffer;
@@ -435,11 +525,13 @@ async function startRun(passed, declared2) {
435
525
  await resolveKeys(pending.flatMap((p) => p.keys));
436
526
  const submissions = [];
437
527
  const unanswered = [];
528
+ const filesByKey = /* @__PURE__ */ new Map();
438
529
  for (const result of pending) {
439
530
  const match = matchFor(result);
440
531
  if (match.kind === "found") {
441
- const { keys: _keys, ...rest } = result;
532
+ const { keys: _keys, files, ...rest } = result;
442
533
  submissions.push({ ...rest, testCaseId: match.testCaseId });
534
+ if (files !== void 0) filesByKey.set(result.resultKey, files);
443
535
  } else if (match.kind === "unmatched") {
444
536
  stats.unresolved += 1;
445
537
  remember(result);
@@ -457,14 +549,16 @@ async function startRun(passed, declared2) {
457
549
  defer(part);
458
550
  continue;
459
551
  }
460
- const out = await client.post(`/v1/runs/${runId}/results`, {
461
- results: part
462
- });
552
+ const out = await client.post(
553
+ `/v1/runs/${runId}/results`,
554
+ { results: part }
555
+ );
463
556
  const counts = out.ok ? out.body?.counts : void 0;
464
557
  const told = COUNTED.filter((k) => typeof counts?.[k] === "number");
465
558
  if (told.length > 0) {
466
559
  for (const k of told) stats[k] += counts[k];
467
560
  progress();
561
+ await upload(out.ok ? out.body?.items : void 0, filesByKey);
468
562
  continue;
469
563
  }
470
564
  if (out.ok) {
@@ -494,6 +588,12 @@ async function startRun(passed, declared2) {
494
588
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
495
589
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
496
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
+ }
497
597
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
498
598
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
499
599
  log(`plune: ${parts.join(" \xB7 ")}`);
@@ -581,6 +681,9 @@ function errorContextOf(attempt, home = homedir2()) {
581
681
  const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
582
682
  return cut(machineless(text, attempt.repoRoot, home));
583
683
  }
684
+ function filesOf(attempt) {
685
+ return attempt.attachments.filter((a) => a.path !== void 0);
686
+ }
584
687
  function machineless(raw, repoRoot, home) {
585
688
  let text = stripVTControlCharacters(raw).replaceAll("\x1B", "");
586
689
  const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
@@ -751,6 +854,7 @@ function pendingFrom(test, result, ctx) {
751
854
  const attempt = attemptOf(test, result, ctx);
752
855
  const errorContext = errorContextOf(attempt);
753
856
  const failure = NOT_FAILED.has(result.status) ? void 0 : failureOf(attempt);
857
+ const files = filesOf(attempt);
754
858
  const startedAt = result.startTime;
755
859
  return {
756
860
  resultKey: resultKey(test.id, result.retry),
@@ -779,7 +883,9 @@ function pendingFrom(test, result, ctx) {
779
883
  worker: String(result.workerIndex)
780
884
  },
781
885
  ...errorContext !== "" ? { errorContext } : {},
782
- ...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 } : {}
783
889
  };
784
890
  }
785
891
  var PluneReporter = class {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plune-ai/playwright",
3
- "version": "0.2.8",
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.2"
41
+ "@plune-ai/cli": "0.15.0"
42
42
  },
43
43
  "repository": {
44
44
  "type": "git",