@plune-ai/playwright 0.3.0 → 0.5.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
@@ -130,8 +130,33 @@ under the name it was attached with: `testInfo.attach('checkout', { path })` arr
130
130
 
131
131
  Plune takes PNG, JPEG and WebP, up to 2 MB a file and 20 a result. An image outside those limits is
132
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.
133
+ not uploaded (a JSON or a text is: see below), and neither is an image attached as a `body` rather
134
+ than a file — attach it with `path`. A screenshot that does not arrive never costs its result or your
135
+ run's exit code.
136
+
137
+ ## JSON and text files
138
+
139
+ What a test attaches as JSON or plain text — the answer of an API, a log — is uploaded to its result
140
+ as well, beside the screenshots and for a test that passed as much as one that failed. Attach it with
141
+ a `body` or with a `path`; both are read:
142
+
143
+ ```ts
144
+ await testInfo.attach('api-response', { body: JSON.stringify(data), contentType: 'application/json' });
145
+ await testInfo.attach('server.log', { path: 'logs/server.log', contentType: 'text/plain' });
146
+ ```
147
+
148
+ Name the type: `application/json` or `text/plain` (a log is `text/plain`, whatever its file is
149
+ called). An attachment that names none is not uploaded, and its extension is not guessed at;
150
+ Markdown, HTML, CSV, traces and videos are not uploaded either. Plune takes UTF-8 text without NUL
151
+ bytes, up to 512 KiB a file and 10 a result — apart from the screenshots' 20. A text outside those
152
+ limits, an empty one, or one whose name starts with an underscore is skipped: the run summary counts
153
+ it and says why, once per reason. The reporter sends a file as it is; Plune cleans the credentials it
154
+ recognises out of a text before it keeps it. A file that does not arrive never costs its result or
155
+ your run's exit code.
156
+
157
+ A text attached as a `body` exists only in memory: it is uploaded once Plune has stored the result,
158
+ and is never written to `.plune/pending-results.jsonl`, so a result sent again with `plune run report`
159
+ goes without it.
135
160
 
136
161
  ## When Plune is unreachable
137
162
 
package/dist/index.cjs CHANGED
@@ -40,19 +40,20 @@ var import_node_util = require("util");
40
40
  var import_crypto = require("crypto");
41
41
  var import_fs = require("fs");
42
42
  var import_path = require("path");
43
+ var import_util = require("util");
43
44
  var import_fs2 = require("fs");
44
45
  var import_os = require("os");
45
46
  var import_path2 = require("path");
46
47
  var import_http = require("http");
47
48
  var import_https = require("https");
48
49
  var path = __toESM(require("path"), 1);
49
- var fs = __toESM(require("fs"), 1);
50
- var path2 = __toESM(require("path"), 1);
51
- var import_crypto2 = require("crypto");
52
50
  var import_fs3 = require("fs");
53
51
  var import_os2 = require("os");
54
52
  var import_path3 = require("path");
55
- var import_util = require("util");
53
+ var import_util2 = require("util");
54
+ var fs = __toESM(require("fs"), 1);
55
+ var path2 = __toESM(require("path"), 1);
56
+ var import_crypto2 = require("crypto");
56
57
  var DEFAULT_API_URL = "https://beta-api.plune.ai";
57
58
  function resolveApiUrl(explicit) {
58
59
  const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
@@ -236,6 +237,153 @@ function defaultRunTitle(env = process.env, now = /* @__PURE__ */ new Date(), cw
236
237
  const where = flag(env, "CI") || flag(env, "GITHUB_ACTIONS") ? "ci" : "local";
237
238
  return `${path.basename(cwd)} \xB7 ${stamp} \xB7 ${where}`;
238
239
  }
240
+ var PROVIDERS = [
241
+ { is: "GITHUB_ACTIONS", sha: "GITHUB_SHA", branch: ["GITHUB_HEAD_REF", "GITHUB_REF_NAME"] },
242
+ { is: "GITLAB_CI", sha: "CI_COMMIT_SHA", branch: ["CI_COMMIT_REF_NAME"] },
243
+ { is: "JENKINS_URL", sha: "GIT_COMMIT", branch: ["GIT_BRANCH"] }
244
+ ];
245
+ function ciCommit(reported, env = process.env) {
246
+ const said = typeof reported === "object" && reported !== null ? reported : {};
247
+ const text = (raw) => typeof raw === "string" && raw.trim() !== "" ? raw.trim() : void 0;
248
+ const provider = PROVIDERS.find((p) => value(env, p.is) !== void 0);
249
+ const job = {
250
+ sha: provider === void 0 ? void 0 : value(env, provider.sha),
251
+ branch: provider?.branch.map((name) => value(env, name)).find((v) => v !== void 0)
252
+ };
253
+ const sha = text(said["commitHash"]);
254
+ const sameCommit = sha === void 0 || sha === job.sha;
255
+ const commit = sha ?? job.sha;
256
+ const branch = text(said["branch"]) ?? (sameCommit ? job.branch : void 0);
257
+ return {
258
+ ...commit !== void 0 ? { sha: commit } : {},
259
+ ...branch !== void 0 ? { branch } : {}
260
+ };
261
+ }
262
+ function failureOf(attempt, home = (0, import_os2.homedir)()) {
263
+ const error = chosen(attempt);
264
+ const line = error === void 0 ? void 0 : firstLine(machineless(error.text, attempt.repoRoot, home));
265
+ const headline = line !== void 0 && jsonBytes(line) <= HEADLINE_LIMIT ? line : void 0;
266
+ const steps = chainOf(attempt.steps);
267
+ const location = error === void 0 ? void 0 : fromRoot(placeOf(error, attempt.testFile), attempt.repoRoot);
268
+ const artifacts = attempt.attachments.filter((a) => a.path !== void 0 && !a.name.startsWith("_") && a.contentType !== METADATA_TYPE).map(({ name, contentType }) => ({ name: fileNameOf(name), ...contentType ? { contentType } : {} })).filter((a) => a.name !== "");
269
+ const ciUrl = webLink(attempt.buildHref);
270
+ const failure = {
271
+ ...headline !== void 0 ? { headline } : {},
272
+ ...steps.length > 0 ? { steps } : {},
273
+ ...location !== void 0 ? { location } : {},
274
+ ...artifacts.length > 0 ? { artifacts } : {},
275
+ ...ciUrl !== void 0 ? { ciUrl } : {}
276
+ };
277
+ return Object.keys(failure).length === 0 ? void 0 : failure;
278
+ }
279
+ function repoRootOf(dir, stopAt) {
280
+ for (let here = (0, import_path3.resolve)(dir); ; here = (0, import_path3.dirname)(here)) {
281
+ if ((0, import_fs3.existsSync)((0, import_path3.join)(here, ".git"))) return here;
282
+ if (here === stopAt || (0, import_path3.dirname)(here) === here) return void 0;
283
+ }
284
+ }
285
+ function errorContextOf(attempt, home = (0, import_os2.homedir)()) {
286
+ const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
287
+ return cut(machineless(text, attempt.repoRoot, home));
288
+ }
289
+ var mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
290
+ var TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
291
+ var isTextType = (contentType) => TEXT_TYPES.has(mediaTypeOf(contentType) ?? "");
292
+ function filesOf(attempt) {
293
+ return attempt.attachments.filter((a) => a.path !== void 0 || a.body !== void 0 && isTextType(a.contentType));
294
+ }
295
+ function machineless(raw, repoRoot, home) {
296
+ let text = (0, import_util2.stripVTControlCharacters)(raw).replaceAll("\x1B", "");
297
+ const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
298
+ if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
299
+ const own = pathIn(home);
300
+ if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
301
+ if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
302
+ return text;
303
+ }
304
+ var PATH_START = "(?<![\\w.~%/\\\\-])";
305
+ var TEXT_LIMIT = 524288;
306
+ var HEADLINE_LIMIT = 8 * 1024;
307
+ var jsonBytes = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
308
+ var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
309
+ function pathIn(path3) {
310
+ const parts = path3.split(/[\\/]+/);
311
+ while (parts.length > 1 && parts.at(-1) === "") parts.pop();
312
+ if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
313
+ const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
314
+ const escaped = /^\/(?!\/)/.test(path3) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
315
+ const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
316
+ return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
317
+ }
318
+ var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
319
+ function cut(text) {
320
+ if (jsonBytes(text) <= TEXT_LIMIT) return text;
321
+ const lines = text.split("\n");
322
+ const size = lines.map((line) => jsonBytes(line) + 2);
323
+ const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
324
+ let used = 0;
325
+ let head = 0;
326
+ let tail = lines.length;
327
+ while (head < tail && used + size[head] <= budget / 2) used += size[head++];
328
+ while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
329
+ return [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n");
330
+ }
331
+ var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
332
+ var METADATA_TYPE = "application/plune.metadata+json";
333
+ var REPO_RELATIVE = /^(?![A-Za-z][A-Za-z0-9+.-]*:)(?![\\/~])(?!(?:.*[\\/])?\.\.(?:[\\/]|$)).+$/;
334
+ var FRAME = /^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/;
335
+ var FRAME_MAX = 8192;
336
+ var firstLine = (text) => (0, import_util2.stripVTControlCharacters)(text).split("\n").map((line) => line.trim()).find((line) => line !== "");
337
+ function chosen({ status, errors }) {
338
+ if (status === "timedOut") {
339
+ const timeout = errors.findIndex((e) => firstLine(e.text)?.startsWith("Test timeout of ") === true);
340
+ if (timeout !== -1 && timeout + 1 < errors.length) return errors[timeout + 1];
341
+ }
342
+ return errors[0];
343
+ }
344
+ function chainOf(steps) {
345
+ const chain = [];
346
+ for (let failed = steps.find((s) => s.failed); failed !== void 0; failed = failed.steps.find((s) => s.failed)) {
347
+ chain.push(failed.title);
348
+ }
349
+ return chain;
350
+ }
351
+ function placeOf(error, testFile) {
352
+ const own = normal(testFile);
353
+ let first;
354
+ for (const line of (0, import_util2.stripVTControlCharacters)(error.text).split("\n")) {
355
+ if (line.length > FRAME_MAX) continue;
356
+ const frame = FRAME.exec(line);
357
+ if (frame === null) continue;
358
+ const place = { file: fileOf(frame[1]), line: Number(frame[2]), column: Number(frame[3]) };
359
+ if (normal(place.file) === own) return place;
360
+ if (first === void 0 && !normal(place.file).includes("/node_modules/")) first = place;
361
+ }
362
+ return error.location ?? first;
363
+ }
364
+ function fileOf(raw) {
365
+ if (!raw.startsWith("file://")) return raw;
366
+ let path3 = raw.slice("file://".length);
367
+ try {
368
+ path3 = decodeURIComponent(path3);
369
+ } catch {
370
+ }
371
+ return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
372
+ }
373
+ var normal = (path3) => import_path3.posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
374
+ function fromRoot(place, root) {
375
+ if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
376
+ const base = normal(root).replace(/\/+$/, "");
377
+ const file = normal(place.file);
378
+ if (!file.startsWith(`${base}/`)) return void 0;
379
+ const relative = file.slice(base.length + 1);
380
+ if (!REPO_RELATIVE.test(relative)) return void 0;
381
+ const column = place.column !== void 0 && Number.isInteger(place.column) && place.column >= 1 ? place.column : void 0;
382
+ return column === void 0 ? { file: relative, line: place.line } : { file: relative, line: place.line, column };
383
+ }
384
+ function webLink(href) {
385
+ return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
386
+ }
239
387
  var DEFAULT_FALLBACK_PATH = path2.join(".plune", "pending-results.jsonl");
240
388
  function appendBatch(file, batch) {
241
389
  fs.mkdirSync(path2.dirname(file), { recursive: true });
@@ -243,6 +391,8 @@ function appendBatch(file, batch) {
243
391
  ts: (/* @__PURE__ */ new Date()).toISOString(),
244
392
  runId: batch.runId,
245
393
  externalKey: batch.externalKey,
394
+ ...batch.session !== void 0 ? { session: batch.session } : {},
395
+ ...batch.meta !== void 0 ? { meta: batch.meta } : {},
246
396
  results: batch.results
247
397
  };
248
398
  fs.appendFileSync(file, `${JSON.stringify(line)}
@@ -259,6 +409,9 @@ var COUNTED = ["accepted", "duplicate", "conflict", "rejected"];
259
409
  var SCREENSHOT_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp"]);
260
410
  var SCREENSHOT_BYTES = 2 * 1024 * 1024;
261
411
  var SCREENSHOTS_PER_RESULT = 20;
412
+ var TEXT_BYTES = 512 * 1024;
413
+ var TEXTS_PER_RESULT = 10;
414
+ var UTF8 = new import_util.TextDecoder("utf-8", { fatal: true });
262
415
  var TYPE_BY_EXTENSION = {
263
416
  ".png": "image/png",
264
417
  ".jpg": "image/jpeg",
@@ -268,8 +421,8 @@ var TYPE_BY_EXTENSION = {
268
421
  var UPLOADS_AT_ONCE = 4;
269
422
  var NAME_MAX = 200;
270
423
  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);
424
+ const own = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : (0, import_path.basename)(file.path));
425
+ const fileExt = file.path === void 0 ? "" : (0, import_path.extname)(file.path);
273
426
  const ownExt = (0, import_path.extname)(own);
274
427
  const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
275
428
  const ext = typed ? ownExt : fileExt;
@@ -285,8 +438,46 @@ var SKIPPED = {
285
438
  type: "Plune takes PNG, JPEG and WebP",
286
439
  limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
287
440
  missing: "the file cannot be read on this machine",
288
- size: "Plune takes a file of at most 2 MB"
441
+ size: "Plune takes a file of at most 2 MB",
442
+ textLimit: `a result holds at most ${TEXTS_PER_RESULT} text files`,
443
+ textSize: "Plune takes a text file of at most 512 KiB",
444
+ empty: "the file is empty",
445
+ binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
446
+ encoding: "Plune takes UTF-8 text only"
447
+ };
448
+ var KINDS = {
449
+ screenshot: { label: "screenshot", bytes: SCREENSHOT_BYTES, room: SCREENSHOTS_PER_RESULT, limit: "limit", size: "size" },
450
+ text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" }
289
451
  };
452
+ function kindOf(type) {
453
+ if (type.startsWith("image/")) return "screenshot";
454
+ return TEXT_TYPES.has(type) ? "text" : void 0;
455
+ }
456
+ function textTypeOf(contentType, type) {
457
+ const charset = /;\s*charset\s*=\s*"?([^\s";]+)"?/i.exec(contentType)?.[1];
458
+ return charset?.toLowerCase() === "utf-8" ? `${type}; charset=utf-8` : type;
459
+ }
460
+ function textRefusal(bytes) {
461
+ if (bytes.length > TEXT_BYTES) return "textSize";
462
+ if (bytes.length === 0) return "empty";
463
+ if (bytes.includes(0)) return "binary";
464
+ try {
465
+ UTF8.decode(bytes);
466
+ } catch {
467
+ return "encoding";
468
+ }
469
+ return void 0;
470
+ }
471
+ function onDisk(result) {
472
+ if (!("files" in result) || result.files === void 0) return result;
473
+ const { files, ...rest } = result;
474
+ const kept = files.filter((f) => f.path !== void 0).map(({ body: _body, ...file }) => file);
475
+ return kept.length === 0 ? rest : { ...rest, files: kept };
476
+ }
477
+ function tally(counts, noun) {
478
+ if (counts.uploaded + counts.skipped + counts.failed === 0) return void 0;
479
+ return `${counts.uploaded} ${noun}(s) uploaded` + (counts.skipped > 0 ? `, ${counts.skipped} skipped` : "") + (counts.failed > 0 ? `, ${counts.failed} failed to upload` : "");
480
+ }
290
481
  function boundKey(key) {
291
482
  if (key.value.length <= KEY_MAX) return key;
292
483
  const digest = (0, import_crypto.createHash)("sha256").update(key.value).digest("hex").slice(0, 16);
@@ -294,6 +485,12 @@ function boundKey(key) {
294
485
  if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
295
486
  return { ...key, value: `${head}#${digest}` };
296
487
  }
488
+ function whyUnoffered(out) {
489
+ if (out.ok || out.status !== 429) return "other";
490
+ if (/review queue quota reached/i.test(out.detail)) return "queue";
491
+ if (/test case quota reached/i.test(out.detail)) return "cases";
492
+ return "other";
493
+ }
297
494
  function boundTitle(title) {
298
495
  return title.length <= TITLE_MAX ? title : `${title.slice(0, TITLE_MAX - 1)}\u2026`;
299
496
  }
@@ -337,6 +534,7 @@ async function startRun(passed, declared2) {
337
534
  `));
338
535
  const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
339
536
  const externalKey = cfg.externalKey ?? null;
537
+ const sessionMarker = (0, import_crypto.randomUUID)();
340
538
  const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
341
539
  const offerDiscovered = cfg.offerDiscovered ?? false;
342
540
  const token = cfg.token ?? loadToken() ?? "";
@@ -355,7 +553,8 @@ async function startRun(passed, declared2) {
355
553
  created: 0,
356
554
  unoffered: 0,
357
555
  deferred: 0,
358
- screenshots: { uploaded: 0, skipped: 0, failed: 0 }
556
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 },
557
+ textFiles: { uploaded: 0, skipped: 0, failed: 0 }
359
558
  };
360
559
  const resolved = /* @__PURE__ */ new Map();
361
560
  let buffer = [];
@@ -366,6 +565,7 @@ async function startRun(passed, declared2) {
366
565
  let done = false;
367
566
  const shortened = /* @__PURE__ */ new Set();
368
567
  const skipsSaid = /* @__PURE__ */ new Set();
568
+ const countsOf = (kind) => kind === "text" ? stats.textFiles : stats.screenshots;
369
569
  function bound(keys) {
370
570
  return keys.map((key) => {
371
571
  const fit = boundKey(key);
@@ -388,7 +588,13 @@ async function startRun(passed, declared2) {
388
588
  log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
389
589
  }
390
590
  function defer(results) {
391
- appendBatch(fallbackPath, { runId, externalKey, results });
591
+ appendBatch(fallbackPath, {
592
+ runId,
593
+ externalKey,
594
+ session: sessionMarker,
595
+ ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
596
+ results: results.map(onDisk)
597
+ });
392
598
  stats.deferred += results.length;
393
599
  }
394
600
  async function resolveKeys(values) {
@@ -485,6 +691,7 @@ async function startRun(passed, declared2) {
485
691
  });
486
692
  if (!out.ok || !Array.isArray(out.body?.results)) {
487
693
  stats.unoffered = batches.slice(index).reduce((n, rest) => n + rest.length, 0);
694
+ stats.unofferedWhy = whyUnoffered(out);
488
695
  log(
489
696
  `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.ok ? "the answer had no results" : out.detail || out.kind}).`
490
697
  );
@@ -494,57 +701,74 @@ async function startRun(passed, declared2) {
494
701
  stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
495
702
  }
496
703
  }
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]}.`);
704
+ function skip(kind, name, why) {
705
+ countsOf(kind).skipped += 1;
706
+ if (skipsSaid.has(`${kind}/${why}`)) return;
707
+ skipsSaid.add(`${kind}/${why}`);
708
+ log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
502
709
  }
503
- async function uploadOne(shot) {
710
+ async function uploadOne(job) {
711
+ const { kind } = job;
712
+ const { label, bytes: ceiling, size } = KINDS[kind];
504
713
  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");
714
+ if (job.body !== void 0) bytes = job.body;
715
+ else if (job.path === void 0) return skip(kind, job.name, "missing");
716
+ else {
717
+ try {
718
+ if ((await import_fs.promises.stat(job.path)).size > ceiling) return skip(kind, job.name, size);
719
+ bytes = await import_fs.promises.readFile(job.path);
720
+ } catch {
721
+ return skip(kind, job.name, "missing");
722
+ }
510
723
  }
724
+ const refusal = kind === "text" ? textRefusal(bytes) : void 0;
725
+ if (refusal !== void 0) return skip(kind, job.name, refusal);
511
726
  const out = await client.upload(
512
- `/v1/results/${encodeURIComponent(shot.id)}/files?name=${encodeURIComponent(shot.name)}`,
727
+ `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
513
728
  bytes,
514
- shot.type
729
+ job.type
515
730
  );
731
+ const counts = countsOf(kind);
516
732
  if (out.ok) {
517
- stats.screenshots.uploaded += 1;
733
+ counts.uploaded += 1;
518
734
  return;
519
735
  }
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.`);
736
+ counts.failed += 1;
737
+ if (counts.failed === 1) {
738
+ log(`plune: could not upload a ${label} (${out.detail || out.kind}) \u2014 its result is reported without it.`);
523
739
  }
524
740
  }
525
741
  async function upload(items, filesByKey) {
526
742
  if (filesByKey.size === 0 || !Array.isArray(items)) return;
527
- const shots = [];
743
+ const jobs = [];
528
744
  for (const item of items) {
529
745
  if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
530
- let room = SCREENSHOTS_PER_RESULT;
746
+ const room = { screenshot: KINDS.screenshot.room, text: KINDS.text.room };
531
747
  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;
748
+ const type = mediaTypeOf(file.contentType) ?? (file.path === void 0 ? void 0 : TYPE_BY_EXTENSION[(0, import_path.extname)(file.path).toLowerCase()]);
749
+ const kind = type === void 0 ? void 0 : kindOf(type);
750
+ if (type === void 0 || kind === void 0 || kind === "screenshot" && file.path === void 0) continue;
534
751
  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");
752
+ if (file.name.startsWith("_")) skip(kind, name, "hidden");
753
+ else if (kind === "screenshot" && !SCREENSHOT_TYPES.has(type)) skip(kind, name, "type");
754
+ else if (room[kind] === 0) skip(kind, name, KINDS[kind].limit);
538
755
  else {
539
- room -= 1;
540
- shots.push({ id: item.id, name, type, path: file.path });
756
+ room[kind] -= 1;
757
+ jobs.push({
758
+ id: item.id,
759
+ kind,
760
+ name,
761
+ type: kind === "text" ? textTypeOf(file.contentType ?? "", type) : type,
762
+ ...file.body !== void 0 ? { body: file.body } : {},
763
+ ...file.path !== void 0 ? { path: file.path } : {}
764
+ });
541
765
  }
542
766
  }
543
767
  }
544
768
  let next = 0;
545
769
  await Promise.all(
546
- Array.from({ length: Math.min(UPLOADS_AT_ONCE, shots.length) }, async () => {
547
- while (next < shots.length) await uploadOne(shots[next++]);
770
+ Array.from({ length: Math.min(UPLOADS_AT_ONCE, jobs.length) }, async () => {
771
+ while (next < jobs.length) await uploadOne(jobs[next++]);
548
772
  })
549
773
  );
550
774
  }
@@ -622,11 +846,8 @@ async function startRun(passed, declared2) {
622
846
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
623
847
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
624
848
  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
- );
849
+ for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
850
+ if (said !== void 0) parts.push(said);
630
851
  }
631
852
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
632
853
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
@@ -688,128 +909,6 @@ function resultKey(testId, retry) {
688
909
  const plain = `${testId}#${retry}`;
689
910
  return plain.length <= RESULT_KEY_MAX ? plain : `${sha256(testId).slice(0, HASH_CHARS)}#${retry}`;
690
911
  }
691
- function failureOf(attempt, home = (0, import_os2.homedir)()) {
692
- const error = chosen(attempt);
693
- const line = error === void 0 ? void 0 : firstLine(machineless(error.text, attempt.repoRoot, home));
694
- const headline = line !== void 0 && jsonBytes(line) <= HEADLINE_LIMIT ? line : void 0;
695
- const steps = chainOf(attempt.steps);
696
- const location = error === void 0 ? void 0 : fromRoot(placeOf(error, attempt.testFile), attempt.repoRoot);
697
- const artifacts = attempt.attachments.filter((a) => a.path !== void 0 && !a.name.startsWith("_") && a.contentType !== METADATA_TYPE).map(({ name, contentType }) => ({ name: fileNameOf(name), ...contentType ? { contentType } : {} })).filter((a) => a.name !== "");
698
- const ciUrl = webLink(attempt.buildHref);
699
- const failure = {
700
- ...headline !== void 0 ? { headline } : {},
701
- ...steps.length > 0 ? { steps } : {},
702
- ...location !== void 0 ? { location } : {},
703
- ...artifacts.length > 0 ? { artifacts } : {},
704
- ...ciUrl !== void 0 ? { ciUrl } : {}
705
- };
706
- return Object.keys(failure).length === 0 ? void 0 : failure;
707
- }
708
- function repoRootOf(dir, stopAt) {
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;
712
- }
713
- }
714
- function errorContextOf(attempt, home = (0, import_os2.homedir)()) {
715
- const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
716
- return cut(machineless(text, attempt.repoRoot, home));
717
- }
718
- function filesOf(attempt) {
719
- return attempt.attachments.filter((a) => a.path !== void 0);
720
- }
721
- function machineless(raw, repoRoot, home) {
722
- let text = (0, import_util.stripVTControlCharacters)(raw).replaceAll("\x1B", "");
723
- const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
724
- if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
725
- const own = pathIn(home);
726
- if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
727
- if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
728
- return text;
729
- }
730
- var PATH_START = "(?<![\\w.~%/\\\\-])";
731
- var TEXT_LIMIT = 524288;
732
- var HEADLINE_LIMIT = 8 * 1024;
733
- var jsonBytes = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
734
- var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
735
- function pathIn(path3) {
736
- const parts = path3.split(/[\\/]+/);
737
- while (parts.length > 1 && parts.at(-1) === "") parts.pop();
738
- if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
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");
743
- }
744
- var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
745
- function cut(text) {
746
- if (jsonBytes(text) <= TEXT_LIMIT) return text;
747
- const lines = text.split("\n");
748
- const size = lines.map((line) => jsonBytes(line) + 2);
749
- const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
750
- let used = 0;
751
- let head = 0;
752
- let tail = lines.length;
753
- while (head < tail && used + size[head] <= budget / 2) used += size[head++];
754
- while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
755
- return [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n");
756
- }
757
- var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
758
- var METADATA_TYPE = "application/plune.metadata+json";
759
- var REPO_RELATIVE = /^(?![A-Za-z][A-Za-z0-9+.-]*:)(?![\\/~])(?!(?:.*[\\/])?\.\.(?:[\\/]|$)).+$/;
760
- var FRAME = /^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/;
761
- var FRAME_MAX = 8192;
762
- var firstLine = (text) => (0, import_util.stripVTControlCharacters)(text).split("\n").map((line) => line.trim()).find((line) => line !== "");
763
- function chosen({ status, errors }) {
764
- if (status === "timedOut") {
765
- const timeout = errors.findIndex((e) => firstLine(e.text)?.startsWith("Test timeout of ") === true);
766
- if (timeout !== -1 && timeout + 1 < errors.length) return errors[timeout + 1];
767
- }
768
- return errors[0];
769
- }
770
- function chainOf(steps) {
771
- const chain = [];
772
- for (let failed = steps.find((s) => s.failed); failed !== void 0; failed = failed.steps.find((s) => s.failed)) {
773
- chain.push(failed.title);
774
- }
775
- return chain;
776
- }
777
- function placeOf(error, testFile) {
778
- const own = normal(testFile);
779
- let first;
780
- for (const line of (0, import_util.stripVTControlCharacters)(error.text).split("\n")) {
781
- if (line.length > FRAME_MAX) continue;
782
- const frame = FRAME.exec(line);
783
- if (frame === null) continue;
784
- const place = { file: fileOf(frame[1]), line: Number(frame[2]), column: Number(frame[3]) };
785
- if (normal(place.file) === own) return place;
786
- if (first === void 0 && !normal(place.file).includes("/node_modules/")) first = place;
787
- }
788
- return error.location ?? first;
789
- }
790
- function fileOf(raw) {
791
- if (!raw.startsWith("file://")) return raw;
792
- let path3 = raw.slice("file://".length);
793
- try {
794
- path3 = decodeURIComponent(path3);
795
- } catch {
796
- }
797
- return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
798
- }
799
- var normal = (path3) => import_path3.posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
800
- function fromRoot(place, root) {
801
- if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
802
- const base = normal(root).replace(/\/+$/, "");
803
- const file = normal(place.file);
804
- if (!file.startsWith(`${base}/`)) return void 0;
805
- const relative = file.slice(base.length + 1);
806
- if (!REPO_RELATIVE.test(relative)) return void 0;
807
- const column = place.column !== void 0 && Number.isInteger(place.column) && place.column >= 1 ? place.column : void 0;
808
- return column === void 0 ? { file: relative, line: place.line } : { file: relative, line: place.line, column };
809
- }
810
- function webLink(href) {
811
- return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
812
- }
813
912
 
814
913
  // src/index.ts
815
914
  var SOURCE = "playwright";
@@ -871,10 +970,12 @@ function attemptOf(test, result, ctx) {
871
970
  status: result.status,
872
971
  errors: result.errors.map((e) => ({ text: textOf(e), ...e.location !== void 0 ? { location: e.location } : {} })),
873
972
  steps: declared(result.steps ?? []),
874
- attachments: result.attachments.map(({ name, contentType, path: path3 }) => ({
973
+ attachments: result.attachments.map(({ name, contentType, path: path3, body }) => ({
875
974
  name,
876
975
  contentType,
877
- ...path3 !== void 0 ? { path: path3 } : {}
976
+ ...path3 !== void 0 ? { path: path3 } : {},
977
+ // What a test attached from memory has no file: the bytes are the reporter's only copy (plune#928).
978
+ ...body !== void 0 ? { body } : {}
878
979
  })),
879
980
  ...ctx.buildHref !== void 0 ? { buildHref: ctx.buildHref } : {},
880
981
  testFile: test.location.file,
@@ -918,7 +1019,7 @@ function pendingFrom(test, result, ctx) {
918
1019
  },
919
1020
  ...errorContext !== "" ? { errorContext } : {},
920
1021
  ...failure !== void 0 ? { failure } : {},
921
- // Every attempt's, a passed one's too; the core uploads the screenshots once the result is stored.
1022
+ // Every attempt's, a passed one's too; the core uploads the screenshots and the text files once the result is stored.
922
1023
  ...files.length > 0 ? { files } : {}
923
1024
  };
924
1025
  }
@@ -974,7 +1075,9 @@ var PluneReporter = class {
974
1075
  ...this.options.externalKey !== void 0 ? { externalKey: this.options.externalKey } : {},
975
1076
  ...this.options.batchSize !== void 0 ? { batchSize: this.options.batchSize } : {},
976
1077
  ...this.options.fallbackPath !== void 0 ? { fallbackPath: this.options.fallbackPath } : {},
977
- meta: { runner: SOURCE, ...ciUrl !== void 0 ? { ciUrl } : {} }
1078
+ // Where it ran (plune#927): the commit Playwright wrote into `metadata.ci`, and its branch —
1079
+ // which Playwright gives on GitLab and Jenkins, and the core reads from the job on GitHub.
1080
+ meta: { runner: SOURCE, ...ciUrl !== void 0 ? { ciUrl } : {}, ...ciCommit(ci) }
978
1081
  },
979
1082
  this.declared
980
1083
  );
package/dist/index.js CHANGED
@@ -3,22 +3,23 @@ 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
7
  import { promises as disk } from "fs";
8
8
  import { basename as basename2, extname } from "path";
9
+ import { TextDecoder } from "util";
9
10
  import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
10
11
  import { homedir } from "os";
11
12
  import { dirname, join } from "path";
12
13
  import { request as httpRequest } from "http";
13
14
  import { request as httpsRequest } from "https";
14
15
  import * as path from "path";
15
- import * as fs from "fs";
16
- import * as path2 from "path";
17
- import { createHash as createHash2 } from "crypto";
18
16
  import { existsSync as existsSync2 } from "fs";
19
17
  import { homedir as homedir2 } from "os";
20
- import { dirname as dirname3, join as join3, posix, resolve } from "path";
18
+ import { dirname as dirname2, join as join2, posix, resolve } from "path";
21
19
  import { stripVTControlCharacters } from "util";
20
+ import * as fs from "fs";
21
+ import * as path2 from "path";
22
+ import { createHash as createHash2 } from "crypto";
22
23
  var DEFAULT_API_URL = "https://beta-api.plune.ai";
23
24
  function resolveApiUrl(explicit) {
24
25
  const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
@@ -202,6 +203,153 @@ function defaultRunTitle(env = process.env, now = /* @__PURE__ */ new Date(), cw
202
203
  const where = flag(env, "CI") || flag(env, "GITHUB_ACTIONS") ? "ci" : "local";
203
204
  return `${path.basename(cwd)} \xB7 ${stamp} \xB7 ${where}`;
204
205
  }
206
+ var PROVIDERS = [
207
+ { is: "GITHUB_ACTIONS", sha: "GITHUB_SHA", branch: ["GITHUB_HEAD_REF", "GITHUB_REF_NAME"] },
208
+ { is: "GITLAB_CI", sha: "CI_COMMIT_SHA", branch: ["CI_COMMIT_REF_NAME"] },
209
+ { is: "JENKINS_URL", sha: "GIT_COMMIT", branch: ["GIT_BRANCH"] }
210
+ ];
211
+ function ciCommit(reported, env = process.env) {
212
+ const said = typeof reported === "object" && reported !== null ? reported : {};
213
+ const text = (raw) => typeof raw === "string" && raw.trim() !== "" ? raw.trim() : void 0;
214
+ const provider = PROVIDERS.find((p) => value(env, p.is) !== void 0);
215
+ const job = {
216
+ sha: provider === void 0 ? void 0 : value(env, provider.sha),
217
+ branch: provider?.branch.map((name) => value(env, name)).find((v) => v !== void 0)
218
+ };
219
+ const sha = text(said["commitHash"]);
220
+ const sameCommit = sha === void 0 || sha === job.sha;
221
+ const commit = sha ?? job.sha;
222
+ const branch = text(said["branch"]) ?? (sameCommit ? job.branch : void 0);
223
+ return {
224
+ ...commit !== void 0 ? { sha: commit } : {},
225
+ ...branch !== void 0 ? { branch } : {}
226
+ };
227
+ }
228
+ function failureOf(attempt, home = homedir2()) {
229
+ const error = chosen(attempt);
230
+ const line = error === void 0 ? void 0 : firstLine(machineless(error.text, attempt.repoRoot, home));
231
+ const headline = line !== void 0 && jsonBytes(line) <= HEADLINE_LIMIT ? line : void 0;
232
+ const steps = chainOf(attempt.steps);
233
+ const location = error === void 0 ? void 0 : fromRoot(placeOf(error, attempt.testFile), attempt.repoRoot);
234
+ const artifacts = attempt.attachments.filter((a) => a.path !== void 0 && !a.name.startsWith("_") && a.contentType !== METADATA_TYPE).map(({ name, contentType }) => ({ name: fileNameOf(name), ...contentType ? { contentType } : {} })).filter((a) => a.name !== "");
235
+ const ciUrl = webLink(attempt.buildHref);
236
+ const failure = {
237
+ ...headline !== void 0 ? { headline } : {},
238
+ ...steps.length > 0 ? { steps } : {},
239
+ ...location !== void 0 ? { location } : {},
240
+ ...artifacts.length > 0 ? { artifacts } : {},
241
+ ...ciUrl !== void 0 ? { ciUrl } : {}
242
+ };
243
+ return Object.keys(failure).length === 0 ? void 0 : failure;
244
+ }
245
+ function repoRootOf(dir, stopAt) {
246
+ for (let here = resolve(dir); ; here = dirname2(here)) {
247
+ if (existsSync2(join2(here, ".git"))) return here;
248
+ if (here === stopAt || dirname2(here) === here) return void 0;
249
+ }
250
+ }
251
+ function errorContextOf(attempt, home = homedir2()) {
252
+ const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
253
+ return cut(machineless(text, attempt.repoRoot, home));
254
+ }
255
+ var mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
256
+ var TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
257
+ var isTextType = (contentType) => TEXT_TYPES.has(mediaTypeOf(contentType) ?? "");
258
+ function filesOf(attempt) {
259
+ return attempt.attachments.filter((a) => a.path !== void 0 || a.body !== void 0 && isTextType(a.contentType));
260
+ }
261
+ function machineless(raw, repoRoot, home) {
262
+ let text = stripVTControlCharacters(raw).replaceAll("\x1B", "");
263
+ const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
264
+ if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
265
+ const own = pathIn(home);
266
+ if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
267
+ if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
268
+ return text;
269
+ }
270
+ var PATH_START = "(?<![\\w.~%/\\\\-])";
271
+ var TEXT_LIMIT = 524288;
272
+ var HEADLINE_LIMIT = 8 * 1024;
273
+ var jsonBytes = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
274
+ var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
275
+ function pathIn(path3) {
276
+ const parts = path3.split(/[\\/]+/);
277
+ while (parts.length > 1 && parts.at(-1) === "") parts.pop();
278
+ if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
279
+ const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
280
+ const escaped = /^\/(?!\/)/.test(path3) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
281
+ const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
282
+ return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
283
+ }
284
+ var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
285
+ function cut(text) {
286
+ if (jsonBytes(text) <= TEXT_LIMIT) return text;
287
+ const lines = text.split("\n");
288
+ const size = lines.map((line) => jsonBytes(line) + 2);
289
+ const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
290
+ let used = 0;
291
+ let head = 0;
292
+ let tail = lines.length;
293
+ while (head < tail && used + size[head] <= budget / 2) used += size[head++];
294
+ while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
295
+ return [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n");
296
+ }
297
+ var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
298
+ var METADATA_TYPE = "application/plune.metadata+json";
299
+ var REPO_RELATIVE = /^(?![A-Za-z][A-Za-z0-9+.-]*:)(?![\\/~])(?!(?:.*[\\/])?\.\.(?:[\\/]|$)).+$/;
300
+ var FRAME = /^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/;
301
+ var FRAME_MAX = 8192;
302
+ var firstLine = (text) => stripVTControlCharacters(text).split("\n").map((line) => line.trim()).find((line) => line !== "");
303
+ function chosen({ status, errors }) {
304
+ if (status === "timedOut") {
305
+ const timeout = errors.findIndex((e) => firstLine(e.text)?.startsWith("Test timeout of ") === true);
306
+ if (timeout !== -1 && timeout + 1 < errors.length) return errors[timeout + 1];
307
+ }
308
+ return errors[0];
309
+ }
310
+ function chainOf(steps) {
311
+ const chain = [];
312
+ for (let failed = steps.find((s) => s.failed); failed !== void 0; failed = failed.steps.find((s) => s.failed)) {
313
+ chain.push(failed.title);
314
+ }
315
+ return chain;
316
+ }
317
+ function placeOf(error, testFile) {
318
+ const own = normal(testFile);
319
+ let first;
320
+ for (const line of stripVTControlCharacters(error.text).split("\n")) {
321
+ if (line.length > FRAME_MAX) continue;
322
+ const frame = FRAME.exec(line);
323
+ if (frame === null) continue;
324
+ const place = { file: fileOf(frame[1]), line: Number(frame[2]), column: Number(frame[3]) };
325
+ if (normal(place.file) === own) return place;
326
+ if (first === void 0 && !normal(place.file).includes("/node_modules/")) first = place;
327
+ }
328
+ return error.location ?? first;
329
+ }
330
+ function fileOf(raw) {
331
+ if (!raw.startsWith("file://")) return raw;
332
+ let path3 = raw.slice("file://".length);
333
+ try {
334
+ path3 = decodeURIComponent(path3);
335
+ } catch {
336
+ }
337
+ return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
338
+ }
339
+ var normal = (path3) => posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
340
+ function fromRoot(place, root) {
341
+ if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
342
+ const base = normal(root).replace(/\/+$/, "");
343
+ const file = normal(place.file);
344
+ if (!file.startsWith(`${base}/`)) return void 0;
345
+ const relative = file.slice(base.length + 1);
346
+ if (!REPO_RELATIVE.test(relative)) return void 0;
347
+ const column = place.column !== void 0 && Number.isInteger(place.column) && place.column >= 1 ? place.column : void 0;
348
+ return column === void 0 ? { file: relative, line: place.line } : { file: relative, line: place.line, column };
349
+ }
350
+ function webLink(href) {
351
+ return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
352
+ }
205
353
  var DEFAULT_FALLBACK_PATH = path2.join(".plune", "pending-results.jsonl");
206
354
  function appendBatch(file, batch) {
207
355
  fs.mkdirSync(path2.dirname(file), { recursive: true });
@@ -209,6 +357,8 @@ function appendBatch(file, batch) {
209
357
  ts: (/* @__PURE__ */ new Date()).toISOString(),
210
358
  runId: batch.runId,
211
359
  externalKey: batch.externalKey,
360
+ ...batch.session !== void 0 ? { session: batch.session } : {},
361
+ ...batch.meta !== void 0 ? { meta: batch.meta } : {},
212
362
  results: batch.results
213
363
  };
214
364
  fs.appendFileSync(file, `${JSON.stringify(line)}
@@ -225,6 +375,9 @@ var COUNTED = ["accepted", "duplicate", "conflict", "rejected"];
225
375
  var SCREENSHOT_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp"]);
226
376
  var SCREENSHOT_BYTES = 2 * 1024 * 1024;
227
377
  var SCREENSHOTS_PER_RESULT = 20;
378
+ var TEXT_BYTES = 512 * 1024;
379
+ var TEXTS_PER_RESULT = 10;
380
+ var UTF8 = new TextDecoder("utf-8", { fatal: true });
228
381
  var TYPE_BY_EXTENSION = {
229
382
  ".png": "image/png",
230
383
  ".jpg": "image/jpeg",
@@ -234,8 +387,8 @@ var TYPE_BY_EXTENSION = {
234
387
  var UPLOADS_AT_ONCE = 4;
235
388
  var NAME_MAX = 200;
236
389
  function nameOf(file) {
237
- const own = file.name.split(/[\\/]/).pop()?.trim() || basename2(file.path);
238
- const fileExt = extname(file.path);
390
+ const own = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : basename2(file.path));
391
+ const fileExt = file.path === void 0 ? "" : extname(file.path);
239
392
  const ownExt = extname(own);
240
393
  const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
241
394
  const ext = typed ? ownExt : fileExt;
@@ -251,8 +404,46 @@ var SKIPPED = {
251
404
  type: "Plune takes PNG, JPEG and WebP",
252
405
  limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
253
406
  missing: "the file cannot be read on this machine",
254
- size: "Plune takes a file of at most 2 MB"
407
+ size: "Plune takes a file of at most 2 MB",
408
+ textLimit: `a result holds at most ${TEXTS_PER_RESULT} text files`,
409
+ textSize: "Plune takes a text file of at most 512 KiB",
410
+ empty: "the file is empty",
411
+ binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
412
+ encoding: "Plune takes UTF-8 text only"
255
413
  };
414
+ var KINDS = {
415
+ screenshot: { label: "screenshot", bytes: SCREENSHOT_BYTES, room: SCREENSHOTS_PER_RESULT, limit: "limit", size: "size" },
416
+ text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" }
417
+ };
418
+ function kindOf(type) {
419
+ if (type.startsWith("image/")) return "screenshot";
420
+ return TEXT_TYPES.has(type) ? "text" : void 0;
421
+ }
422
+ function textTypeOf(contentType, type) {
423
+ const charset = /;\s*charset\s*=\s*"?([^\s";]+)"?/i.exec(contentType)?.[1];
424
+ return charset?.toLowerCase() === "utf-8" ? `${type}; charset=utf-8` : type;
425
+ }
426
+ function textRefusal(bytes) {
427
+ if (bytes.length > TEXT_BYTES) return "textSize";
428
+ if (bytes.length === 0) return "empty";
429
+ if (bytes.includes(0)) return "binary";
430
+ try {
431
+ UTF8.decode(bytes);
432
+ } catch {
433
+ return "encoding";
434
+ }
435
+ return void 0;
436
+ }
437
+ function onDisk(result) {
438
+ if (!("files" in result) || result.files === void 0) return result;
439
+ const { files, ...rest } = result;
440
+ const kept = files.filter((f) => f.path !== void 0).map(({ body: _body, ...file }) => file);
441
+ return kept.length === 0 ? rest : { ...rest, files: kept };
442
+ }
443
+ function tally(counts, noun) {
444
+ if (counts.uploaded + counts.skipped + counts.failed === 0) return void 0;
445
+ return `${counts.uploaded} ${noun}(s) uploaded` + (counts.skipped > 0 ? `, ${counts.skipped} skipped` : "") + (counts.failed > 0 ? `, ${counts.failed} failed to upload` : "");
446
+ }
256
447
  function boundKey(key) {
257
448
  if (key.value.length <= KEY_MAX) return key;
258
449
  const digest = createHash("sha256").update(key.value).digest("hex").slice(0, 16);
@@ -260,6 +451,12 @@ function boundKey(key) {
260
451
  if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
261
452
  return { ...key, value: `${head}#${digest}` };
262
453
  }
454
+ function whyUnoffered(out) {
455
+ if (out.ok || out.status !== 429) return "other";
456
+ if (/review queue quota reached/i.test(out.detail)) return "queue";
457
+ if (/test case quota reached/i.test(out.detail)) return "cases";
458
+ return "other";
459
+ }
263
460
  function boundTitle(title) {
264
461
  return title.length <= TITLE_MAX ? title : `${title.slice(0, TITLE_MAX - 1)}\u2026`;
265
462
  }
@@ -303,6 +500,7 @@ async function startRun(passed, declared2) {
303
500
  `));
304
501
  const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
305
502
  const externalKey = cfg.externalKey ?? null;
503
+ const sessionMarker = randomUUID();
306
504
  const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
307
505
  const offerDiscovered = cfg.offerDiscovered ?? false;
308
506
  const token = cfg.token ?? loadToken() ?? "";
@@ -321,7 +519,8 @@ async function startRun(passed, declared2) {
321
519
  created: 0,
322
520
  unoffered: 0,
323
521
  deferred: 0,
324
- screenshots: { uploaded: 0, skipped: 0, failed: 0 }
522
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 },
523
+ textFiles: { uploaded: 0, skipped: 0, failed: 0 }
325
524
  };
326
525
  const resolved = /* @__PURE__ */ new Map();
327
526
  let buffer = [];
@@ -332,6 +531,7 @@ async function startRun(passed, declared2) {
332
531
  let done = false;
333
532
  const shortened = /* @__PURE__ */ new Set();
334
533
  const skipsSaid = /* @__PURE__ */ new Set();
534
+ const countsOf = (kind) => kind === "text" ? stats.textFiles : stats.screenshots;
335
535
  function bound(keys) {
336
536
  return keys.map((key) => {
337
537
  const fit = boundKey(key);
@@ -354,7 +554,13 @@ async function startRun(passed, declared2) {
354
554
  log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
355
555
  }
356
556
  function defer(results) {
357
- appendBatch(fallbackPath, { runId, externalKey, results });
557
+ appendBatch(fallbackPath, {
558
+ runId,
559
+ externalKey,
560
+ session: sessionMarker,
561
+ ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
562
+ results: results.map(onDisk)
563
+ });
358
564
  stats.deferred += results.length;
359
565
  }
360
566
  async function resolveKeys(values) {
@@ -451,6 +657,7 @@ async function startRun(passed, declared2) {
451
657
  });
452
658
  if (!out.ok || !Array.isArray(out.body?.results)) {
453
659
  stats.unoffered = batches.slice(index).reduce((n, rest) => n + rest.length, 0);
660
+ stats.unofferedWhy = whyUnoffered(out);
454
661
  log(
455
662
  `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.ok ? "the answer had no results" : out.detail || out.kind}).`
456
663
  );
@@ -460,57 +667,74 @@ async function startRun(passed, declared2) {
460
667
  stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
461
668
  }
462
669
  }
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]}.`);
670
+ function skip(kind, name, why) {
671
+ countsOf(kind).skipped += 1;
672
+ if (skipsSaid.has(`${kind}/${why}`)) return;
673
+ skipsSaid.add(`${kind}/${why}`);
674
+ log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
468
675
  }
469
- async function uploadOne(shot) {
676
+ async function uploadOne(job) {
677
+ const { kind } = job;
678
+ const { label, bytes: ceiling, size } = KINDS[kind];
470
679
  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");
680
+ if (job.body !== void 0) bytes = job.body;
681
+ else if (job.path === void 0) return skip(kind, job.name, "missing");
682
+ else {
683
+ try {
684
+ if ((await disk.stat(job.path)).size > ceiling) return skip(kind, job.name, size);
685
+ bytes = await disk.readFile(job.path);
686
+ } catch {
687
+ return skip(kind, job.name, "missing");
688
+ }
476
689
  }
690
+ const refusal = kind === "text" ? textRefusal(bytes) : void 0;
691
+ if (refusal !== void 0) return skip(kind, job.name, refusal);
477
692
  const out = await client.upload(
478
- `/v1/results/${encodeURIComponent(shot.id)}/files?name=${encodeURIComponent(shot.name)}`,
693
+ `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
479
694
  bytes,
480
- shot.type
695
+ job.type
481
696
  );
697
+ const counts = countsOf(kind);
482
698
  if (out.ok) {
483
- stats.screenshots.uploaded += 1;
699
+ counts.uploaded += 1;
484
700
  return;
485
701
  }
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.`);
702
+ counts.failed += 1;
703
+ if (counts.failed === 1) {
704
+ log(`plune: could not upload a ${label} (${out.detail || out.kind}) \u2014 its result is reported without it.`);
489
705
  }
490
706
  }
491
707
  async function upload(items, filesByKey) {
492
708
  if (filesByKey.size === 0 || !Array.isArray(items)) return;
493
- const shots = [];
709
+ const jobs = [];
494
710
  for (const item of items) {
495
711
  if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
496
- let room = SCREENSHOTS_PER_RESULT;
712
+ const room = { screenshot: KINDS.screenshot.room, text: KINDS.text.room };
497
713
  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;
714
+ const type = mediaTypeOf(file.contentType) ?? (file.path === void 0 ? void 0 : TYPE_BY_EXTENSION[extname(file.path).toLowerCase()]);
715
+ const kind = type === void 0 ? void 0 : kindOf(type);
716
+ if (type === void 0 || kind === void 0 || kind === "screenshot" && file.path === void 0) continue;
500
717
  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");
718
+ if (file.name.startsWith("_")) skip(kind, name, "hidden");
719
+ else if (kind === "screenshot" && !SCREENSHOT_TYPES.has(type)) skip(kind, name, "type");
720
+ else if (room[kind] === 0) skip(kind, name, KINDS[kind].limit);
504
721
  else {
505
- room -= 1;
506
- shots.push({ id: item.id, name, type, path: file.path });
722
+ room[kind] -= 1;
723
+ jobs.push({
724
+ id: item.id,
725
+ kind,
726
+ name,
727
+ type: kind === "text" ? textTypeOf(file.contentType ?? "", type) : type,
728
+ ...file.body !== void 0 ? { body: file.body } : {},
729
+ ...file.path !== void 0 ? { path: file.path } : {}
730
+ });
507
731
  }
508
732
  }
509
733
  }
510
734
  let next = 0;
511
735
  await Promise.all(
512
- Array.from({ length: Math.min(UPLOADS_AT_ONCE, shots.length) }, async () => {
513
- while (next < shots.length) await uploadOne(shots[next++]);
736
+ Array.from({ length: Math.min(UPLOADS_AT_ONCE, jobs.length) }, async () => {
737
+ while (next < jobs.length) await uploadOne(jobs[next++]);
514
738
  })
515
739
  );
516
740
  }
@@ -588,11 +812,8 @@ async function startRun(passed, declared2) {
588
812
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
589
813
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
590
814
  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
- );
815
+ for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
816
+ if (said !== void 0) parts.push(said);
596
817
  }
597
818
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
598
819
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
@@ -654,128 +875,6 @@ function resultKey(testId, retry) {
654
875
  const plain = `${testId}#${retry}`;
655
876
  return plain.length <= RESULT_KEY_MAX ? plain : `${sha256(testId).slice(0, HASH_CHARS)}#${retry}`;
656
877
  }
657
- function failureOf(attempt, home = homedir2()) {
658
- const error = chosen(attempt);
659
- const line = error === void 0 ? void 0 : firstLine(machineless(error.text, attempt.repoRoot, home));
660
- const headline = line !== void 0 && jsonBytes(line) <= HEADLINE_LIMIT ? line : void 0;
661
- const steps = chainOf(attempt.steps);
662
- const location = error === void 0 ? void 0 : fromRoot(placeOf(error, attempt.testFile), attempt.repoRoot);
663
- const artifacts = attempt.attachments.filter((a) => a.path !== void 0 && !a.name.startsWith("_") && a.contentType !== METADATA_TYPE).map(({ name, contentType }) => ({ name: fileNameOf(name), ...contentType ? { contentType } : {} })).filter((a) => a.name !== "");
664
- const ciUrl = webLink(attempt.buildHref);
665
- const failure = {
666
- ...headline !== void 0 ? { headline } : {},
667
- ...steps.length > 0 ? { steps } : {},
668
- ...location !== void 0 ? { location } : {},
669
- ...artifacts.length > 0 ? { artifacts } : {},
670
- ...ciUrl !== void 0 ? { ciUrl } : {}
671
- };
672
- return Object.keys(failure).length === 0 ? void 0 : failure;
673
- }
674
- function repoRootOf(dir, stopAt) {
675
- for (let here = resolve(dir); ; here = dirname3(here)) {
676
- if (existsSync2(join3(here, ".git"))) return here;
677
- if (here === stopAt || dirname3(here) === here) return void 0;
678
- }
679
- }
680
- function errorContextOf(attempt, home = homedir2()) {
681
- const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
682
- return cut(machineless(text, attempt.repoRoot, home));
683
- }
684
- function filesOf(attempt) {
685
- return attempt.attachments.filter((a) => a.path !== void 0);
686
- }
687
- function machineless(raw, repoRoot, home) {
688
- let text = stripVTControlCharacters(raw).replaceAll("\x1B", "");
689
- const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
690
- if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
691
- const own = pathIn(home);
692
- if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
693
- if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
694
- return text;
695
- }
696
- var PATH_START = "(?<![\\w.~%/\\\\-])";
697
- var TEXT_LIMIT = 524288;
698
- var HEADLINE_LIMIT = 8 * 1024;
699
- var jsonBytes = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
700
- var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
701
- function pathIn(path3) {
702
- const parts = path3.split(/[\\/]+/);
703
- while (parts.length > 1 && parts.at(-1) === "") parts.pop();
704
- if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
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");
709
- }
710
- var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
711
- function cut(text) {
712
- if (jsonBytes(text) <= TEXT_LIMIT) return text;
713
- const lines = text.split("\n");
714
- const size = lines.map((line) => jsonBytes(line) + 2);
715
- const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
716
- let used = 0;
717
- let head = 0;
718
- let tail = lines.length;
719
- while (head < tail && used + size[head] <= budget / 2) used += size[head++];
720
- while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
721
- return [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n");
722
- }
723
- var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
724
- var METADATA_TYPE = "application/plune.metadata+json";
725
- var REPO_RELATIVE = /^(?![A-Za-z][A-Za-z0-9+.-]*:)(?![\\/~])(?!(?:.*[\\/])?\.\.(?:[\\/]|$)).+$/;
726
- var FRAME = /^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/;
727
- var FRAME_MAX = 8192;
728
- var firstLine = (text) => stripVTControlCharacters(text).split("\n").map((line) => line.trim()).find((line) => line !== "");
729
- function chosen({ status, errors }) {
730
- if (status === "timedOut") {
731
- const timeout = errors.findIndex((e) => firstLine(e.text)?.startsWith("Test timeout of ") === true);
732
- if (timeout !== -1 && timeout + 1 < errors.length) return errors[timeout + 1];
733
- }
734
- return errors[0];
735
- }
736
- function chainOf(steps) {
737
- const chain = [];
738
- for (let failed = steps.find((s) => s.failed); failed !== void 0; failed = failed.steps.find((s) => s.failed)) {
739
- chain.push(failed.title);
740
- }
741
- return chain;
742
- }
743
- function placeOf(error, testFile) {
744
- const own = normal(testFile);
745
- let first;
746
- for (const line of stripVTControlCharacters(error.text).split("\n")) {
747
- if (line.length > FRAME_MAX) continue;
748
- const frame = FRAME.exec(line);
749
- if (frame === null) continue;
750
- const place = { file: fileOf(frame[1]), line: Number(frame[2]), column: Number(frame[3]) };
751
- if (normal(place.file) === own) return place;
752
- if (first === void 0 && !normal(place.file).includes("/node_modules/")) first = place;
753
- }
754
- return error.location ?? first;
755
- }
756
- function fileOf(raw) {
757
- if (!raw.startsWith("file://")) return raw;
758
- let path3 = raw.slice("file://".length);
759
- try {
760
- path3 = decodeURIComponent(path3);
761
- } catch {
762
- }
763
- return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
764
- }
765
- var normal = (path3) => posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
766
- function fromRoot(place, root) {
767
- if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
768
- const base = normal(root).replace(/\/+$/, "");
769
- const file = normal(place.file);
770
- if (!file.startsWith(`${base}/`)) return void 0;
771
- const relative = file.slice(base.length + 1);
772
- if (!REPO_RELATIVE.test(relative)) return void 0;
773
- const column = place.column !== void 0 && Number.isInteger(place.column) && place.column >= 1 ? place.column : void 0;
774
- return column === void 0 ? { file: relative, line: place.line } : { file: relative, line: place.line, column };
775
- }
776
- function webLink(href) {
777
- return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
778
- }
779
878
 
780
879
  // src/index.ts
781
880
  var SOURCE = "playwright";
@@ -837,10 +936,12 @@ function attemptOf(test, result, ctx) {
837
936
  status: result.status,
838
937
  errors: result.errors.map((e) => ({ text: textOf(e), ...e.location !== void 0 ? { location: e.location } : {} })),
839
938
  steps: declared(result.steps ?? []),
840
- attachments: result.attachments.map(({ name, contentType, path: path3 }) => ({
939
+ attachments: result.attachments.map(({ name, contentType, path: path3, body }) => ({
841
940
  name,
842
941
  contentType,
843
- ...path3 !== void 0 ? { path: path3 } : {}
942
+ ...path3 !== void 0 ? { path: path3 } : {},
943
+ // What a test attached from memory has no file: the bytes are the reporter's only copy (plune#928).
944
+ ...body !== void 0 ? { body } : {}
844
945
  })),
845
946
  ...ctx.buildHref !== void 0 ? { buildHref: ctx.buildHref } : {},
846
947
  testFile: test.location.file,
@@ -884,7 +985,7 @@ function pendingFrom(test, result, ctx) {
884
985
  },
885
986
  ...errorContext !== "" ? { errorContext } : {},
886
987
  ...failure !== void 0 ? { failure } : {},
887
- // Every attempt's, a passed one's too; the core uploads the screenshots once the result is stored.
988
+ // Every attempt's, a passed one's too; the core uploads the screenshots and the text files once the result is stored.
888
989
  ...files.length > 0 ? { files } : {}
889
990
  };
890
991
  }
@@ -940,7 +1041,9 @@ var PluneReporter = class {
940
1041
  ...this.options.externalKey !== void 0 ? { externalKey: this.options.externalKey } : {},
941
1042
  ...this.options.batchSize !== void 0 ? { batchSize: this.options.batchSize } : {},
942
1043
  ...this.options.fallbackPath !== void 0 ? { fallbackPath: this.options.fallbackPath } : {},
943
- meta: { runner: SOURCE, ...ciUrl !== void 0 ? { ciUrl } : {} }
1044
+ // Where it ran (plune#927): the commit Playwright wrote into `metadata.ci`, and its branch —
1045
+ // which Playwright gives on GitLab and Jenkins, and the core reads from the job on GitHub.
1046
+ meta: { runner: SOURCE, ...ciUrl !== void 0 ? { ciUrl } : {}, ...ciCommit(ci) }
944
1047
  },
945
1048
  this.declared
946
1049
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plune-ai/playwright",
3
- "version": "0.3.0",
3
+ "version": "0.5.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.15.0"
41
+ "@plune-ai/cli": "0.17.0"
42
42
  },
43
43
  "repository": {
44
44
  "type": "git",