@plune-ai/playwright 0.7.0 → 0.7.2

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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/index.ts
2
- import { readFileSync as readFileSync2 } from "fs";
2
+ import { readFileSync as readFileSync3 } from "fs";
3
3
  import { resolve as resolve2 } from "path";
4
4
  import { stripVTControlCharacters as stripVTControlCharacters2 } from "util";
5
5
 
@@ -24,6 +24,7 @@ import { createHash } from "crypto";
24
24
  import { createReadStream as createReadStream2 } from "fs";
25
25
  import * as fs from "fs";
26
26
  import * as path2 from "path";
27
+ import { readFileSync as readFileSync2 } from "fs";
27
28
  import { createHash as createHash3 } from "crypto";
28
29
  var DEFAULT_API_URL = "https://beta-api.plune.ai";
29
30
  function resolveApiUrl(explicit) {
@@ -225,6 +226,7 @@ function createClient(opts) {
225
226
  upload: (path3, bytes, contentType) => send("POST", path3, { body: bytes, type: contentType }, uploadRetries ?? DEFAULT_RETRIES),
226
227
  del: (path3) => send("DELETE", path3),
227
228
  get: (path3) => send("GET", path3),
229
+ patch: (path3, body) => send("PATCH", path3, { body: JSON.stringify(body), type: "application/json" }),
228
230
  async put(url, headers, source) {
229
231
  const putRetries = uploadRetries ?? 3;
230
232
  let last = { ok: false, status: null, code: "network" };
@@ -432,7 +434,7 @@ function cutErrorContext(attempt, home) {
432
434
  const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
433
435
  return cut(machineless(text, attempt.repoRoot, home));
434
436
  }
435
- var printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
437
+ var printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "?");
436
438
  var mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
437
439
  var TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
438
440
  var isTextType = (contentType) => TEXT_TYPES.has(mediaTypeOf(contentType) ?? "");
@@ -564,10 +566,175 @@ function appendBatch(file, batch) {
564
566
  fs.appendFileSync(file, `${JSON.stringify(line)}
565
567
  `, "utf8");
566
568
  }
569
+ var SNAPSHOT_MAX_BYTES = 16384;
570
+ var CALL = /\b(?:test|it)(?:\.(?:skip|fixme|only|fail|slow))?\s*\(/g;
571
+ var BEFORE_REGEX = /* @__PURE__ */ new Set([..."(,=:[!&|?{};+-*%<>~^"]);
572
+ function skipString(src, i, quote) {
573
+ for (let j = i + 1; j < src.length; j += 1) {
574
+ const c = src[j];
575
+ if (c === "\\") j += 1;
576
+ else if (c === quote) return j + 1;
577
+ else if (c === "\n") return -1;
578
+ }
579
+ return -1;
580
+ }
581
+ function skipTemplate(src, i) {
582
+ for (let j = i + 1; j < src.length; j += 1) {
583
+ const c = src[j];
584
+ if (c === "\\") j += 1;
585
+ else if (c === "`") return j + 1;
586
+ else if (c === "$" && src[j + 1] === "{") {
587
+ const end = matching(src, j + 2, "}");
588
+ if (end < 0) return -1;
589
+ j = end;
590
+ }
591
+ }
592
+ return -1;
593
+ }
594
+ function skipRegex(src, i) {
595
+ let inClass = false;
596
+ for (let j = i + 1; j < src.length; j += 1) {
597
+ const c = src[j];
598
+ if (c === "\\") j += 1;
599
+ else if (c === "\n") return -1;
600
+ else if (c === "[") inClass = true;
601
+ else if (c === "]") inClass = false;
602
+ else if (c === "/" && !inClass) {
603
+ let k = j + 1;
604
+ while (k < src.length && /[a-z]/i.test(src[k])) k += 1;
605
+ return k;
606
+ }
607
+ }
608
+ return -1;
609
+ }
610
+ function matching(src, i, close) {
611
+ const stack = [close];
612
+ let prev = "(";
613
+ while (i < src.length) {
614
+ const c = src[i];
615
+ const next = src[i + 1];
616
+ let to = -2;
617
+ if (c === "/" && next === "/") to = src.indexOf("\n", i);
618
+ else if (c === "/" && next === "*")
619
+ to = src.indexOf("*/", i + 2) < 0 ? -1 : src.indexOf("*/", i + 2) + 2;
620
+ else if (c === "'" || c === '"') to = skipString(src, i, c);
621
+ else if (c === "`") to = skipTemplate(src, i);
622
+ else if (c === "/" && BEFORE_REGEX.has(prev)) to = skipRegex(src, i);
623
+ if (to === -1) return -1;
624
+ if (to !== -2) {
625
+ if (c !== "/" || next !== "/" && next !== "*") prev = "a";
626
+ i = to;
627
+ continue;
628
+ }
629
+ if (c === "(") stack.push(")");
630
+ else if (c === "[") stack.push("]");
631
+ else if (c === "{") stack.push("}");
632
+ else if (c === ")" || c === "]" || c === "}") {
633
+ if (stack.pop() !== c) return -1;
634
+ if (stack.length === 0) return i;
635
+ }
636
+ if (!/\s/.test(c)) prev = c;
637
+ i += 1;
638
+ }
639
+ return -1;
640
+ }
641
+ function callTextAt(source, line, column) {
642
+ const lines = source.split("\n");
643
+ if (line < 1 || line > lines.length) return void 0;
644
+ const lineStart = lines.slice(0, line - 1).reduce((n, l) => n + l.length + 1, 0);
645
+ const lineEnd = lineStart + lines[line - 1].length;
646
+ const heads = [];
647
+ CALL.lastIndex = lineStart;
648
+ for (let h = CALL.exec(source); h !== null && h.index < lineEnd; h = CALL.exec(source))
649
+ heads.push(h);
650
+ const at = column === void 0 ? -1 : lineStart + column - 1;
651
+ const head = heads.find((h) => h.index <= at && at < h.index + h[0].length) ?? (heads.length === 1 ? heads[0] : void 0);
652
+ if (head === void 0) return void 0;
653
+ const end = matching(source, head.index + head[0].length, ")");
654
+ if (end < 0) return void 0;
655
+ const text = source.slice(head.index, end + 1).replace(/\r\n/g, "\n");
656
+ return Buffer.byteLength(text, "utf8") <= SNAPSHOT_MAX_BYTES ? text : void 0;
657
+ }
658
+ var CREDENTIAL = "password|passphrase|passwd|pass|pwd|token|secret|api[-_]?key|private[-_]?key|credential|auth|session|cookie";
659
+ var LITERAL = String.raw`(?<q>['"\x60])(?:\\.|(?!\k<q>)[^\\\n])*\k<q>`;
660
+ var TYPING = "(?:fill|type|pressSequentially)";
661
+ var SHAPES = [
662
+ { kind: "github-token", re: /\b(?:ghp|gho|ghs|ghu)_[A-Za-z0-9]{36}\b|\bgithub_pat_\w{20,}/g },
663
+ { kind: "api-key", re: /\bsk-[\w-]{20,}/g },
664
+ { kind: "api-key", re: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{10,}/g },
665
+ { kind: "npm-token", re: /\bnpm_[A-Za-z0-9]{20,}/g },
666
+ { kind: "google-key", re: /\bAIza[\w-]{30,}/g },
667
+ { kind: "plune-token", re: /\bplune_[A-Za-z0-9_]{16,}/g },
668
+ { kind: "aws-key", re: /\bAKIA[0-9A-Z]{16}\b/g },
669
+ { kind: "slack-token", re: /\bxox[abprs]-[A-Za-z0-9-]{10,}/g },
670
+ {
671
+ kind: "private-key",
672
+ re: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g
673
+ },
674
+ { kind: "jwt", re: /\beyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,}/g }
675
+ ];
676
+ var PLACES = [
677
+ // `password = '…'`, `apiKey: "…"`, `'x-api-key': '…'`
678
+ new RegExp(
679
+ String.raw`(?<lead>\b(?<role>[\w$-]*(?:${CREDENTIAL})[\w$-]*)['"]?\s*[:=]\s*)${LITERAL}`,
680
+ "gi"
681
+ ),
682
+ // `setToken('…')`: the call is named for a credential
683
+ new RegExp(String.raw`(?<lead>\b(?<role>[\w$]*(?:${CREDENTIAL})[\w$]*)\s*\(\s*)${LITERAL}`, "gi"),
684
+ // `.fill('#password', '…')`, `.type('#pwd', '…')`: the field is named in the same call
685
+ new RegExp(
686
+ String.raw`(?<lead>\.${TYPING}\(\s*['"][^'"\n]*?(?<role>${CREDENTIAL})[^'"\n]*['"]\s*,\s*)${LITERAL}`,
687
+ "gi"
688
+ ),
689
+ // `getByLabel('Password').fill('…')`, `getByRole('textbox', { name: 'Password' }).type('…')`: … or
690
+ // anywhere in the call the typing is chained off
691
+ new RegExp(
692
+ String.raw`(?<lead>\([^()\n]*?(?<role>${CREDENTIAL})[^()\n]*\)\s*\.${TYPING}\(\s*)${LITERAL}`,
693
+ "gi"
694
+ ),
695
+ // `{ name: 'session', value: '…' }`: a cookie (or any name/value pair) named for a credential
696
+ new RegExp(
697
+ String.raw`(?<lead>\bname\s*:\s*['"][^'"\n]*?(?<role>${CREDENTIAL})[^'"\n]*['"]\s*,\s*value\s*:\s*)${LITERAL}`,
698
+ "gi"
699
+ )
700
+ ];
701
+ var HEADER_LINE = /((?:^|\\[nr]|\x60)[ \t>*<+-]*['"]?)((?:proxy-)?authorization|(?:set-)?cookie|[\w-]*session[\w-]*)(['"]?[ \t]*:[ \t]*)(?![\w$.]+(?:\([^()\n]*\))?[ \t]*[,;)}\]])[^\s'"\x60\\][^\r\n'"\x60\\]*/gim;
702
+ var QUERY_PARAM = /([?&][\w.-]*(?:token|key|secret|password|passwd|pass|pwd|auth|signature|sig|credential|session)[\w.-]*=)(?!‹)[^&#\s'"\x60]+/gi;
703
+ function maskCredentials(text) {
704
+ let out = text;
705
+ for (const { kind, re } of SHAPES) out = out.replace(re, `\u2039${kind}\u203A`);
706
+ for (const re of PLACES) {
707
+ out = out.replace(re, (...args) => {
708
+ const groups = args.at(-1);
709
+ return `${groups.lead}${groups.q}\u2039${groups.role.toLowerCase().replace(/^[^a-z]+/, "")}\u203A${groups.q}`;
710
+ });
711
+ }
712
+ return out.replace(HEADER_LINE, "$1$2$3\u2039header\u203A").replace(/\b(Bearer)([ \t]+)(?!‹)[\w.~+/=-]{8,}/g, "$1$2\u2039credential\u203A").replace(
713
+ /\b(Basic|Token)([ \t]+)(?!‹)(?=[\w.~+/=-]*[\d=+/]|[\w.~+/=-]*[a-z][\w.~+/=-]*[A-Z])[\w.~+/=-]{8,}/g,
714
+ "$1$2\u2039credential\u203A"
715
+ ).replace(/\b(PLUNE_[A-Z0-9_]*=)(?!‹)[^\s'"\x60;,)]+/g, "$1\u2039env-secret\u203A").replace(QUERY_PARAM, "$1\u2039credential\u203A").replace(/\b([a-z][\w+.-]*:\/\/)[^\s/@'"\x60]+@/gi, "$1\u2039credential\u203A@");
716
+ }
717
+ function snapshotAt(at, files) {
718
+ let source = files.get(at.file);
719
+ if (source === void 0) {
720
+ try {
721
+ source = readFileSync2(at.file, "utf8");
722
+ } catch {
723
+ source = null;
724
+ }
725
+ files.set(at.file, source);
726
+ }
727
+ if (source === null) return void 0;
728
+ const text = callTextAt(source, at.line, at.column);
729
+ if (text === void 0) return void 0;
730
+ const masked = maskCredentials(text);
731
+ return Buffer.byteLength(masked, "utf8") <= SNAPSHOT_MAX_BYTES ? masked : void 0;
732
+ }
567
733
  var RESOLVE_CHUNK = 500;
568
734
  var BATCH_MAX = 500;
569
735
  var DISCOVER_MAX = 500;
570
736
  var BATCH_DEFAULT = 500;
737
+ var SNAPSHOT_UPDATES_MAX = 100;
571
738
  var SEND_CONCURRENCY = 4;
572
739
  var EXPECTED_MAX = 1e4;
573
740
  var KEY_MAX = 1024;
@@ -663,6 +830,7 @@ function boundKey(key) {
663
830
  if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
664
831
  return { ...key, value: `${head}#${digest}` };
665
832
  }
833
+ var keyId = (key) => `${key.kind ?? ""}\0${key.value}`;
666
834
  function whyUnoffered(out) {
667
835
  if (out.ok || out.status !== 429) return "other";
668
836
  if (/review queue quota reached/i.test(out.detail)) return "queue";
@@ -696,68 +864,14 @@ function chunk(items, size) {
696
864
  for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
697
865
  return out;
698
866
  }
699
- function warnIfDropped(sent, run, log) {
700
- const names = Object.keys(sent);
701
- if (names.length === 0) return;
702
- if (names.some((name) => run[name] != null)) return;
703
- log(
704
- `plune: this deployment stored none of ${names.join(", ")} \u2014 it is older than the fields. The run is otherwise reported in full.`
705
- );
706
- }
707
- async function startRun(passed, declared2) {
708
- const env = readEnv();
709
- if (env.shardError !== void 0) throw new Error(env.shardError);
710
- if (env.configurationError !== void 0 && passed.configuration === void 0) throw new Error(env.configurationError);
711
- const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
712
- const cfg = { ...env.config, ...stated };
713
- const configuration = cfg.configuration !== void 0 && Object.keys(cfg.configuration).length > 0 ? cfg.configuration : void 0;
714
- const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
715
- `));
716
- const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
717
- const externalKey = cfg.externalKey ?? null;
718
- const sessionMarker = randomUUID();
719
- const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
720
- const offerDiscovered = cfg.offerDiscovered ?? false;
721
- const token = cfg.token ?? loadToken() ?? "";
722
- const uploadsAtOnce = Math.min(Math.max(Math.floor(cfg.uploadConcurrency ?? UPLOAD_CONCURRENCY.default), UPLOAD_CONCURRENCY.min), UPLOAD_CONCURRENCY.max);
723
- const uploadRetries = Math.min(Math.max(Math.floor(cfg.uploadRetries ?? UPLOAD_RETRIES.default), UPLOAD_RETRIES.min), UPLOAD_RETRIES.max);
867
+ function fileSender(options) {
868
+ const { client, log, stats, uploadsAtOnce, uploadRetries } = options;
869
+ const without = options.without ?? "its result is reported without it";
724
870
  let retried = 0;
725
871
  let uploadMs = 0;
726
872
  let requests = 0;
727
873
  let existed = 0;
728
874
  let batchMissing = false;
729
- const client = createClient({
730
- apiUrl: resolveApiUrl(cfg.apiUrl),
731
- token,
732
- uploadRetries,
733
- onRetry: () => void (retried += 1),
734
- ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
735
- });
736
- const stats = {
737
- accepted: 0,
738
- duplicate: 0,
739
- conflict: 0,
740
- rejected: 0,
741
- unresolved: 0,
742
- offered: 0,
743
- created: 0,
744
- unoffered: 0,
745
- deferred: 0,
746
- screenshots: { uploaded: 0, skipped: 0, failed: 0 },
747
- textFiles: { uploaded: 0, skipped: 0, failed: 0 },
748
- otherFiles: { uploaded: 0, skipped: 0, failed: 0 }
749
- };
750
- const resolved = /* @__PURE__ */ new Map();
751
- let buffer = [];
752
- const discoveries = /* @__PURE__ */ new Map();
753
- const held = /* @__PURE__ */ new Map();
754
- let createdWithResult = 0;
755
- let createdUndelivered = 0;
756
- let runId = null;
757
- let joined = false;
758
- let offline = token === "";
759
- let done = false;
760
- const shortened = /* @__PURE__ */ new Set();
761
875
  const skipsSaid = /* @__PURE__ */ new Set();
762
876
  const countsOf = (kind) => kind === "text" ? stats.textFiles : kind === "file" ? stats.otherFiles : stats.screenshots;
763
877
  let bucketSeen = false;
@@ -766,168 +880,6 @@ async function startRun(passed, declared2) {
766
880
  const failedSaid = /* @__PURE__ */ new Set();
767
881
  const codesSaid = /* @__PURE__ */ new Set();
768
882
  const rooms = /* @__PURE__ */ new Map();
769
- function bound(keys) {
770
- return keys.map((key) => {
771
- const fit = boundKey(key);
772
- if (fit !== key && !shortened.has(key.value)) {
773
- shortened.add(key.value);
774
- if (shortened.size === 1) {
775
- log(
776
- `plune: a test name longer than ${KEY_MAX} characters was shortened to fit its key \u2014 ${JSON.stringify(printable(key.value.slice(0, 80)))}\u2026 Give the test a shorter name; until then this is its identity.`
777
- );
778
- }
779
- }
780
- return fit;
781
- });
782
- }
783
- const expected = declared2?.map(bound);
784
- if (offline) {
785
- log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
786
- }
787
- for (const warning of env.warnings) log(`plune: ${warning}`);
788
- if (env.ignored.length > 0) {
789
- log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
790
- }
791
- function defer(results) {
792
- appendBatch(fallbackPath, {
793
- runId,
794
- externalKey,
795
- session: sessionMarker,
796
- ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
797
- ...configuration !== void 0 ? { configuration } : {},
798
- results: results.map(onDisk)
799
- });
800
- stats.deferred += results.length;
801
- }
802
- async function resolveKeys(values) {
803
- const unknown = values.filter((k) => !resolved.has(k.value));
804
- if (unknown.length === 0 || offline) return;
805
- for (const part of chunk(unknown, RESOLVE_CHUNK)) {
806
- const out = await client.post(
807
- "/v1/test-cases/resolve",
808
- { keys: part }
809
- );
810
- if (!out.ok || !Array.isArray(out.body?.results)) {
811
- log(`plune: could not look up test cases (${out.ok ? "the answer had no results" : out.detail || out.kind}).`);
812
- return;
813
- }
814
- for (const row of out.body.results) {
815
- if (typeof row?.key?.value === "string") resolved.set(row.key.value, row.testCaseId);
816
- }
817
- }
818
- }
819
- if (!offline) {
820
- if (expected !== void 0) await resolveKeys(expected.flat());
821
- const stated2 = expected?.slice(0, EXPECTED_MAX) ?? [];
822
- const configuration2 = stated2.length === 0 ? void 0 : {
823
- expected: stated2.flatMap((keys) => {
824
- const hit = keys.map((k) => resolved.get(k.value)).find((v) => typeof v === "string");
825
- if (typeof hit === "string") return [{ testCaseId: hit }];
826
- return keys[0] === void 0 ? [] : [{ externalKey: keys[0] }];
827
- }),
828
- // The claim travels with the list it is about (D20). A runner that could not enumerate
829
- // its tests has no list, and a claim without one is nothing the platform can check —
830
- // so it is not sent, rather than sent and silently meaningless.
831
- ...cfg.full === true ? { full: true } : {}
832
- };
833
- if (expected !== void 0 && expected.length > EXPECTED_MAX) {
834
- log(`plune: ${expected.length} tests is more than the run configuration holds \u2014 reporting the first ${EXPECTED_MAX}.`);
835
- }
836
- const described = {
837
- ...cfg.title !== void 0 ? { title: cfg.title } : {},
838
- ...cfg.environment !== void 0 ? { environment: cfg.environment } : {},
839
- ...cfg.labels !== void 0 ? { labels: cfg.labels } : {}
840
- };
841
- const request = {
842
- schemaVersion: 2,
843
- kind: cfg.kind ?? "automated",
844
- ...externalKey !== null ? { externalKey } : {},
845
- ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
846
- ...configuration2 !== void 0 ? { configuration: configuration2 } : {},
847
- // Named even when nobody named it — the list has to read without opening a row. Only what
848
- // the caller DESCRIBED goes to `warnIfDropped` below: a title this side invented is not one
849
- // a person will miss, and a deployment older than the field must not be nagged on every run.
850
- title: defaultRunTitle(),
851
- ...described
852
- };
853
- let start = await client.post("/v1/runs", request);
854
- if (!start.ok && start.status === 413 && configuration2 !== void 0) {
855
- log(
856
- `plune: the platform refused the run's list of expected tests as too large (${start.detail || start.kind}) \u2014 starting without it: the results still land, but this run counts no tests that did not run, and claims no full run.`
857
- );
858
- start = await client.post("/v1/runs", { ...request, configuration: void 0 });
859
- }
860
- if (start.ok && typeof start.body?.run?.id === "string") {
861
- runId = start.body.run.id;
862
- joined = start.status === 200;
863
- warnIfDropped(described, start.body.run, log);
864
- } else {
865
- const why = start.ok ? "the answer had no run" : start.detail || start.kind;
866
- log(`plune: could not start the run (${why}). Results will be written to ${fallbackPath}.`);
867
- }
868
- }
869
- function matchFor(result) {
870
- if (result.testCaseId !== void 0) return { kind: "found", testCaseId: result.testCaseId };
871
- let unanswered = false;
872
- for (const key of result.keys) {
873
- const hit = resolved.get(key.value);
874
- if (typeof hit === "string") return { kind: "found", testCaseId: hit };
875
- if (hit === void 0) unanswered = true;
876
- }
877
- return unanswered ? { kind: "unanswered" } : { kind: "unmatched" };
878
- }
879
- function remember(result) {
880
- if (!offerDiscovered) return;
881
- if (result.title === void 0 || result.specRef === void 0) return;
882
- if (result.keys.length === 0) return;
883
- const title = boundTitle(result.title);
884
- if (title !== result.title) shortened.add(result.title);
885
- discoveries.set(result.keys[0].value, {
886
- keys: result.keys,
887
- title,
888
- source: result.source,
889
- specRef: result.specRef,
890
- rawStatus: result.rawStatus
891
- });
892
- held.set(result.keys[0].value, result);
893
- }
894
- async function offer() {
895
- if (discoveries.size === 0 || offline || runId === null) return;
896
- const batches = chunk([...discoveries.values()], DISCOVER_MAX);
897
- for (const [index, batch] of batches.entries()) {
898
- const out = await client.post("/v1/review-items/discovered", {
899
- discovered: batch,
900
- runId
901
- });
902
- if (!out.ok || !Array.isArray(out.body?.results)) {
903
- stats.unoffered = batches.slice(index).reduce((n, rest) => n + rest.length, 0);
904
- stats.unofferedWhy = whyUnoffered(out);
905
- log(
906
- `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.ok ? "the answer had no results" : out.detail || out.kind}).`
907
- );
908
- return;
909
- }
910
- stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
911
- const made = out.body.results.filter((r) => r?.outcome === "created");
912
- stats.created += made.length;
913
- const submissions = [];
914
- const filesByKey = /* @__PURE__ */ new Map();
915
- for (const r of made) {
916
- const pending = typeof r.id === "string" && r.id !== "" ? held.get(r.key?.value) : void 0;
917
- if (pending === void 0) continue;
918
- held.delete(r.key.value);
919
- const { keys: _keys, files, ...rest } = pending;
920
- submissions.push({ ...rest, testCaseId: r.id });
921
- if (files !== void 0) filesByKey.set(pending.resultKey, files);
922
- }
923
- if (submissions.length > 0) {
924
- const before = stats.deferred;
925
- await send(submissions, filesByKey);
926
- createdWithResult += submissions.length;
927
- createdUndelivered += stats.deferred - before;
928
- }
929
- }
930
- }
931
883
  function skip(kind, name, why) {
932
884
  countsOf(kind).skipped += 1;
933
885
  if (why === "noStorage") noStorage += 1;
@@ -937,24 +889,25 @@ async function startRun(passed, declared2) {
937
889
  if (why === "noStorage") log(`plune: "${name}" not stored \u2014 ${SKIPPED[why]}.`);
938
890
  else log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
939
891
  }
892
+ const filesOf2 = (job) => `/v1/${job.owner ?? "results"}/${encodeURIComponent(job.id)}/files`;
940
893
  function ask(job, size) {
941
894
  requests += 1;
942
- return client.post(`/v1/results/${encodeURIComponent(job.id)}/files/uploads`, {
943
- files: [{ name: job.name, contentType: job.type, size }]
895
+ return client.post(`${filesOf2(job)}/uploads`, {
896
+ files: [{ name: job.name, contentType: job.type, size, ...job.key !== void 0 ? { key: job.key } : {} }]
944
897
  }, uploadRetries);
945
898
  }
946
899
  function failed(job, why) {
947
900
  countsOf(job.kind).failed += 1;
948
901
  if (!failedSaid.has(job.kind)) {
949
902
  failedSaid.add(job.kind);
950
- log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 its result is reported without it.`);
903
+ log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 ${without}.`);
951
904
  }
952
905
  }
953
906
  function failedToBucket(job, code) {
954
907
  countsOf(job.kind).failed += 1;
955
908
  if (codesSaid.has(code)) return;
956
909
  codesSaid.add(code);
957
- log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 its result is reported without it.`);
910
+ log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 ${without}.`);
958
911
  }
959
912
  function refusedHere(job, size) {
960
913
  if (job.kind === "screenshot") {
@@ -982,7 +935,7 @@ async function startRun(passed, declared2) {
982
935
  if (refusal !== void 0) return skip(kind, job.name, refusal);
983
936
  requests += 1;
984
937
  const out = await client.upload(
985
- `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
938
+ `${filesOf2(job)}?name=${encodeURIComponent(job.name)}`,
986
939
  bytes,
987
940
  job.type
988
941
  );
@@ -1004,8 +957,8 @@ async function startRun(passed, declared2) {
1004
957
  link = fresh;
1005
958
  }
1006
959
  requests += 1;
1007
- const done2 = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
1008
- if (!done2.ok) return failedToBucket(job, codeOf(done2));
960
+ const done = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
961
+ if (!done.ok) return failedToBucket(job, codeOf(done));
1009
962
  countsOf(job.kind).uploaded += 1;
1010
963
  }
1011
964
  let free = uploadsAtOnce;
@@ -1332,6 +1285,295 @@ async function startRun(passed, declared2) {
1332
1285
  else await uploadBatched(jobs);
1333
1286
  uploadMs += Date.now() - started;
1334
1287
  }
1288
+ return {
1289
+ upload,
1290
+ uploadEach,
1291
+ onRetry: () => void (retried += 1),
1292
+ get bucketSeen() {
1293
+ return bucketSeen;
1294
+ },
1295
+ get noStorage() {
1296
+ return noStorage;
1297
+ },
1298
+ get existed() {
1299
+ return existed;
1300
+ },
1301
+ get retried() {
1302
+ return retried;
1303
+ },
1304
+ get uploadMs() {
1305
+ return uploadMs;
1306
+ },
1307
+ get requests() {
1308
+ return requests;
1309
+ }
1310
+ };
1311
+ }
1312
+ function warnIfDropped(sent, run, log) {
1313
+ const names = Object.keys(sent);
1314
+ if (names.length === 0) return;
1315
+ if (names.some((name) => run[name] != null)) return;
1316
+ log(
1317
+ `plune: this deployment stored none of ${names.join(", ")} \u2014 it is older than the fields. The run is otherwise reported in full.`
1318
+ );
1319
+ }
1320
+ async function startRun(passed, declared2) {
1321
+ const env = readEnv();
1322
+ if (env.shardError !== void 0) throw new Error(env.shardError);
1323
+ if (env.configurationError !== void 0 && passed.configuration === void 0) throw new Error(env.configurationError);
1324
+ const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
1325
+ const cfg = { ...env.config, ...stated };
1326
+ const configuration = cfg.configuration !== void 0 && Object.keys(cfg.configuration).length > 0 ? cfg.configuration : void 0;
1327
+ const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
1328
+ `));
1329
+ const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
1330
+ const externalKey = cfg.externalKey ?? null;
1331
+ const sessionMarker = randomUUID();
1332
+ const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
1333
+ const offerDiscovered = cfg.offerDiscovered ?? false;
1334
+ const token = cfg.token ?? loadToken() ?? "";
1335
+ const uploadsAtOnce = Math.min(Math.max(Math.floor(cfg.uploadConcurrency ?? UPLOAD_CONCURRENCY.default), UPLOAD_CONCURRENCY.min), UPLOAD_CONCURRENCY.max);
1336
+ const uploadRetries = Math.min(Math.max(Math.floor(cfg.uploadRetries ?? UPLOAD_RETRIES.default), UPLOAD_RETRIES.min), UPLOAD_RETRIES.max);
1337
+ const client = createClient({
1338
+ apiUrl: resolveApiUrl(cfg.apiUrl),
1339
+ token,
1340
+ uploadRetries,
1341
+ onRetry: () => files.onRetry(),
1342
+ ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
1343
+ });
1344
+ const stats = {
1345
+ accepted: 0,
1346
+ duplicate: 0,
1347
+ conflict: 0,
1348
+ rejected: 0,
1349
+ unresolved: 0,
1350
+ offered: 0,
1351
+ created: 0,
1352
+ unoffered: 0,
1353
+ deferred: 0,
1354
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 },
1355
+ textFiles: { uploaded: 0, skipped: 0, failed: 0 },
1356
+ otherFiles: { uploaded: 0, skipped: 0, failed: 0 }
1357
+ };
1358
+ const files = fileSender({ client, log, stats, uploadsAtOnce, uploadRetries });
1359
+ const resolved = /* @__PURE__ */ new Map();
1360
+ let buffer = [];
1361
+ const discoveries = /* @__PURE__ */ new Map();
1362
+ const held = /* @__PURE__ */ new Map();
1363
+ let createdWithResult = 0;
1364
+ let createdUndelivered = 0;
1365
+ let runId = null;
1366
+ let joined = false;
1367
+ let offline = token === "";
1368
+ let done = false;
1369
+ const shortened = /* @__PURE__ */ new Set();
1370
+ const specFiles = /* @__PURE__ */ new Map();
1371
+ const snapshotByKey = /* @__PURE__ */ new Map();
1372
+ const snapshots = /* @__PURE__ */ new Map();
1373
+ function bound(keys) {
1374
+ return keys.map((key) => {
1375
+ const fit = boundKey(key);
1376
+ if (fit !== key && !shortened.has(key.value)) {
1377
+ shortened.add(key.value);
1378
+ if (shortened.size === 1) {
1379
+ log(
1380
+ `plune: a test name longer than ${KEY_MAX} characters was shortened to fit its key \u2014 ${JSON.stringify(printable(key.value.slice(0, 80)))}\u2026 Give the test a shorter name; until then this is its identity.`
1381
+ );
1382
+ }
1383
+ }
1384
+ return fit;
1385
+ });
1386
+ }
1387
+ const expected = declared2?.map(bound);
1388
+ if (offline) {
1389
+ log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
1390
+ }
1391
+ for (const warning of env.warnings) log(`plune: ${warning}`);
1392
+ if (env.ignored.length > 0) {
1393
+ log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
1394
+ }
1395
+ function defer(results) {
1396
+ appendBatch(fallbackPath, {
1397
+ runId,
1398
+ externalKey,
1399
+ session: sessionMarker,
1400
+ ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
1401
+ ...configuration !== void 0 ? { configuration } : {},
1402
+ results: results.map(onDisk)
1403
+ });
1404
+ stats.deferred += results.length;
1405
+ }
1406
+ async function resolveKeys(values) {
1407
+ const unknown = values.filter((k) => !resolved.has(keyId(k)));
1408
+ if (unknown.length === 0 || offline) return;
1409
+ for (const part of chunk(unknown, RESOLVE_CHUNK)) {
1410
+ const out = await client.post(
1411
+ "/v1/test-cases/resolve",
1412
+ { keys: part }
1413
+ );
1414
+ if (!out.ok || !Array.isArray(out.body?.results)) {
1415
+ log(`plune: could not look up test cases (${out.ok ? "the answer had no results" : out.detail || out.kind}).`);
1416
+ return;
1417
+ }
1418
+ for (const row of out.body.results) {
1419
+ if (typeof row?.key?.value === "string") resolved.set(keyId(row.key), row.testCaseId);
1420
+ }
1421
+ }
1422
+ }
1423
+ if (!offline) {
1424
+ if (expected !== void 0) await resolveKeys(expected.flat());
1425
+ const stated2 = expected?.slice(0, EXPECTED_MAX) ?? [];
1426
+ const configuration2 = stated2.length === 0 ? void 0 : {
1427
+ expected: stated2.flatMap((keys) => {
1428
+ const hit = keys.map((k) => resolved.get(keyId(k))).find((v) => typeof v === "string");
1429
+ if (typeof hit === "string") return [{ testCaseId: hit }];
1430
+ return keys[0] === void 0 ? [] : [{ externalKey: keys[0] }];
1431
+ }),
1432
+ // The claim travels with the list it is about. A runner that could not enumerate
1433
+ // its tests has no list, and a claim without one is nothing the platform can check —
1434
+ // so it is not sent, rather than sent and silently meaningless.
1435
+ ...cfg.full === true ? { full: true } : {}
1436
+ };
1437
+ if (expected !== void 0 && expected.length > EXPECTED_MAX) {
1438
+ log(`plune: ${expected.length} tests is more than the run configuration holds \u2014 reporting the first ${EXPECTED_MAX}.`);
1439
+ }
1440
+ const described = {
1441
+ ...cfg.title !== void 0 ? { title: cfg.title } : {},
1442
+ ...cfg.environment !== void 0 ? { environment: cfg.environment } : {},
1443
+ ...cfg.labels !== void 0 ? { labels: cfg.labels } : {}
1444
+ };
1445
+ const request = {
1446
+ schemaVersion: 2,
1447
+ kind: cfg.kind ?? "automated",
1448
+ ...externalKey !== null ? { externalKey } : {},
1449
+ ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
1450
+ ...configuration2 !== void 0 ? { configuration: configuration2 } : {},
1451
+ // Named even when nobody named it — the list has to read without opening a row. Only what
1452
+ // the caller DESCRIBED goes to `warnIfDropped` below: a title this side invented is not one
1453
+ // a person will miss, and a deployment older than the field must not be nagged on every run.
1454
+ title: defaultRunTitle(),
1455
+ ...described
1456
+ };
1457
+ let start = await client.post("/v1/runs", request);
1458
+ if (!start.ok && start.status === 413 && configuration2 !== void 0) {
1459
+ log(
1460
+ `plune: the platform refused the run's list of expected tests as too large (${start.detail || start.kind}) \u2014 starting without it: the results still land, but this run counts no tests that did not run, and claims no full run.`
1461
+ );
1462
+ start = await client.post("/v1/runs", { ...request, configuration: void 0 });
1463
+ }
1464
+ if (start.ok && typeof start.body?.run?.id === "string") {
1465
+ runId = start.body.run.id;
1466
+ joined = start.status === 200;
1467
+ warnIfDropped(described, start.body.run, log);
1468
+ } else {
1469
+ const why = start.ok ? "the answer had no run" : start.detail || start.kind;
1470
+ log(`plune: could not start the run (${why}). Results will be written to ${fallbackPath}.`);
1471
+ }
1472
+ }
1473
+ function matchFor(result) {
1474
+ if (result.testCaseId !== void 0) return { kind: "found", testCaseId: result.testCaseId };
1475
+ let unanswered = false;
1476
+ for (const key of result.keys) {
1477
+ const hit = resolved.get(keyId(key));
1478
+ if (typeof hit === "string") return { kind: "found", testCaseId: hit };
1479
+ if (hit === void 0) unanswered = true;
1480
+ }
1481
+ return unanswered ? { kind: "unanswered" } : { kind: "unmatched" };
1482
+ }
1483
+ function remember(result) {
1484
+ if (!offerDiscovered) return;
1485
+ if (result.title === void 0 || result.specRef === void 0) return;
1486
+ if (result.keys.length === 0) return;
1487
+ const title = boundTitle(result.title);
1488
+ if (title !== result.title) shortened.add(result.title);
1489
+ discoveries.set(keyId(result.keys[0]), {
1490
+ keys: result.keys,
1491
+ title,
1492
+ source: result.source,
1493
+ specRef: result.specRef,
1494
+ rawStatus: result.rawStatus
1495
+ });
1496
+ for (const key of result.keys) held.set(keyId(key), result);
1497
+ }
1498
+ async function offer() {
1499
+ if (discoveries.size === 0 || offline || runId === null) return;
1500
+ const batches = chunk([...discoveries.values()], DISCOVER_MAX);
1501
+ for (const [index, batch] of batches.entries()) {
1502
+ const out = await client.post("/v1/review-items/discovered", {
1503
+ discovered: batch,
1504
+ runId
1505
+ });
1506
+ if (!out.ok || !Array.isArray(out.body?.results)) {
1507
+ stats.unoffered = batches.slice(index).reduce((n, rest) => n + rest.length, 0);
1508
+ stats.unofferedWhy = whyUnoffered(out);
1509
+ log(
1510
+ `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.ok ? "the answer had no results" : out.detail || out.kind}).`
1511
+ );
1512
+ return;
1513
+ }
1514
+ stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
1515
+ const made = out.body.results.filter((r) => r?.outcome === "created");
1516
+ stats.created += made.length;
1517
+ const submissions = [];
1518
+ const filesByKey = /* @__PURE__ */ new Map();
1519
+ for (const r of made) {
1520
+ const pending = typeof r.id === "string" && r.id !== "" && typeof r.key?.value === "string" ? held.get(keyId(r.key)) : void 0;
1521
+ if (pending === void 0) continue;
1522
+ for (const key of pending.keys) held.delete(keyId(key));
1523
+ const { keys: _keys, files: files2, ...rest } = pending;
1524
+ submissions.push({ ...rest, testCaseId: r.id });
1525
+ if (files2 !== void 0) filesByKey.set(pending.resultKey, files2);
1526
+ const text = snapshotByKey.get(pending.resultKey);
1527
+ if (text !== void 0) snapshots.set(r.id, text);
1528
+ }
1529
+ if (submissions.length > 0) {
1530
+ const before = stats.deferred;
1531
+ await send(submissions, filesByKey);
1532
+ createdWithResult += submissions.length;
1533
+ createdUndelivered += stats.deferred - before;
1534
+ }
1535
+ }
1536
+ }
1537
+ async function syncSnapshots() {
1538
+ if (snapshots.size === 0 || offline) return;
1539
+ const stored = /* @__PURE__ */ new Map();
1540
+ let cursor = null;
1541
+ do {
1542
+ const query = `type=automated&stability=0&limit=200${cursor === null ? "" : `&cursor=${encodeURIComponent(cursor)}`}`;
1543
+ const out = await client.get(`/v1/test-cases?${query}`);
1544
+ if (!out.ok || !Array.isArray(out.body?.testCases)) {
1545
+ log(`plune: could not update the code snapshots (${out.ok ? "the case list had no cases" : out.detail || out.kind}).`);
1546
+ return;
1547
+ }
1548
+ for (const row of out.body.testCases) {
1549
+ if (typeof row?.id === "string" && snapshots.has(row.id)) stored.set(row.id, row.codeSnapshotHash ?? null);
1550
+ }
1551
+ cursor = typeof out.body.nextCursor === "string" ? out.body.nextCursor : null;
1552
+ } while (cursor !== null && stored.size < snapshots.size);
1553
+ const sha = (text) => createHash2("sha256").update(text).digest("hex");
1554
+ const due = [...snapshots].filter(([id, text]) => stored.has(id) && stored.get(id) !== sha(text)).sort(([a], [b]) => sha(`${runId}:${a}`).localeCompare(sha(`${runId}:${b}`)));
1555
+ let updated = 0;
1556
+ let refused = 0;
1557
+ let tried = 0;
1558
+ for (const [id, text] of due.slice(0, SNAPSHOT_UPDATES_MAX)) {
1559
+ tried += 1;
1560
+ const out = await client.patch(`/v1/test-cases/${encodeURIComponent(id)}`, { codeSnapshot: text });
1561
+ if (out.ok) {
1562
+ updated += 1;
1563
+ continue;
1564
+ }
1565
+ if (out.kind === "auth" || out.kind === "unavailable" || out.status === 429) {
1566
+ log(`plune: could not update the code snapshot of test case ${id} (${out.detail || out.kind}); the rest are left as they are.`);
1567
+ break;
1568
+ }
1569
+ refused += 1;
1570
+ }
1571
+ const left = due.length - tried;
1572
+ const parts = [`${updated} code snapshot(s) updated`];
1573
+ if (refused > 0) parts.push(`${refused} not updated`);
1574
+ if (left > 0 && tried === Math.min(due.length, SNAPSHOT_UPDATES_MAX)) parts.push(`${left} left for the next run`);
1575
+ if (updated + refused > 0) log(`plune: ${parts.join(", ")}`);
1576
+ }
1335
1577
  const sending = /* @__PURE__ */ new Set();
1336
1578
  let sendError;
1337
1579
  let answered = false;
@@ -1372,9 +1614,11 @@ async function startRun(passed, declared2) {
1372
1614
  for (const result of pending) {
1373
1615
  const match = matchFor(result);
1374
1616
  if (match.kind === "found") {
1375
- const { keys: _keys, files, ...rest } = result;
1617
+ const { keys: _keys, files: files2, ...rest } = result;
1376
1618
  submissions.push({ ...rest, testCaseId: match.testCaseId });
1377
- if (files !== void 0) filesByKey.set(result.resultKey, files);
1619
+ const text = snapshotByKey.get(result.resultKey);
1620
+ if (text !== void 0) snapshots.set(match.testCaseId, text);
1621
+ if (files2 !== void 0) filesByKey.set(result.resultKey, files2);
1378
1622
  } else if (match.kind === "unmatched") {
1379
1623
  stats.unresolved += 1;
1380
1624
  remember(result);
@@ -1397,7 +1641,7 @@ async function startRun(passed, declared2) {
1397
1641
  }
1398
1642
  const out = await client.post(
1399
1643
  `/v1/runs/${runId}/results`,
1400
- // The job's combination on every batch (plune-ai/plune#1251); a refusal of it is a 422 said below as it came.
1644
+ // The job's combination on every batch; a refusal of it is a 422 said below as it came.
1401
1645
  { results: part, ...configuration !== void 0 ? { configuration } : {} }
1402
1646
  );
1403
1647
  const counts = out.ok ? out.body?.counts : void 0;
@@ -1405,7 +1649,7 @@ async function startRun(passed, declared2) {
1405
1649
  if (told.length > 0) {
1406
1650
  for (const k of told) stats[k] += counts[k];
1407
1651
  progress();
1408
- await upload(out.ok ? out.body?.items : void 0, filesByKey);
1652
+ await files.upload(out.ok ? out.body?.items : void 0, filesByKey);
1409
1653
  answered = true;
1410
1654
  continue;
1411
1655
  }
@@ -1441,10 +1685,10 @@ async function startRun(passed, declared2) {
1441
1685
  }
1442
1686
  const kinds = [stats.screenshots, stats.textFiles, stats.otherFiles];
1443
1687
  const sum = (what) => kinds.reduce((n, counts) => n + counts[what], 0);
1444
- if (bucketSeen) {
1445
- const other = sum("skipped") - noStorage;
1688
+ if (files.bucketSeen) {
1689
+ const other = sum("skipped") - files.noStorage;
1446
1690
  parts.push(
1447
- `${sum("uploaded")} file(s) uploaded to your bucket` + (noStorage > 0 ? `, ${noStorage} skipped (no bucket connected)` : "") + (other > 0 ? `, ${other} skipped` : "") + (sum("failed") > 0 ? `, ${sum("failed")} failed to upload` : "")
1691
+ `${sum("uploaded")} file(s) uploaded to your bucket` + (files.noStorage > 0 ? `, ${files.noStorage} skipped (no bucket connected)` : "") + (other > 0 ? `, ${other} skipped` : "") + (sum("failed") > 0 ? `, ${sum("failed")} failed to upload` : "")
1448
1692
  );
1449
1693
  } else {
1450
1694
  for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
@@ -1456,11 +1700,10 @@ async function startRun(passed, declared2) {
1456
1700
  }
1457
1701
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
1458
1702
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
1459
- const files = [stats.screenshots, stats.textFiles, stats.otherFiles];
1460
- const total = (what) => files.reduce((n, counts) => n + counts[what], 0);
1461
- if (total("uploaded") + total("skipped") + total("failed") + existed > 0) {
1703
+ const total = (what) => kinds.reduce((n, counts) => n + counts[what], 0);
1704
+ if (total("uploaded") + total("skipped") + total("failed") + files.existed > 0) {
1462
1705
  log(
1463
- `plune: files \u2014 ${total("uploaded")} uploaded, ${total("skipped")} skipped, ${existed} already there (skipped), ${retried} retried, ${total("failed")} dropped, in ${(uploadMs / 1e3).toFixed(1)} s (${uploadsAtOnce} at once, ${requests} request(s) to Plune)`
1706
+ `plune: files \u2014 ${total("uploaded")} uploaded, ${total("skipped")} skipped, ${files.existed} already there (skipped), ${files.retried} retried, ${total("failed")} dropped, in ${(files.uploadMs / 1e3).toFixed(1)} s (${uploadsAtOnce} at once, ${files.requests} request(s) to Plune)`
1464
1707
  );
1465
1708
  }
1466
1709
  log(`plune: ${parts.join(" \xB7 ")}`);
@@ -1480,7 +1723,10 @@ async function startRun(passed, declared2) {
1480
1723
  return stats;
1481
1724
  },
1482
1725
  async add(result) {
1483
- buffer.push({ ...result, keys: bound(result.keys) });
1726
+ const { codeAt, ...rest } = result;
1727
+ const text = codeAt === void 0 ? void 0 : snapshotAt(codeAt, specFiles);
1728
+ if (text !== void 0) snapshotByKey.set(result.resultKey, text);
1729
+ buffer.push({ ...rest, keys: bound(result.keys) });
1484
1730
  if (buffer.length >= batchSize) await flushBuffer();
1485
1731
  },
1486
1732
  flush,
@@ -1489,6 +1735,7 @@ async function startRun(passed, declared2) {
1489
1735
  done = true;
1490
1736
  await flush();
1491
1737
  await offer();
1738
+ await syncSnapshots();
1492
1739
  let frozen;
1493
1740
  if (runId !== null && !offline) {
1494
1741
  const out = await client.post(`/v1/runs/${runId}/events`, {
@@ -1512,6 +1759,7 @@ async function startRun(passed, declared2) {
1512
1759
  done = true;
1513
1760
  await flush();
1514
1761
  await offer();
1762
+ await syncSnapshots();
1515
1763
  let frozen;
1516
1764
  const after = [];
1517
1765
  const shard = env.shard;
@@ -1586,7 +1834,7 @@ function metadataOf(result) {
1586
1834
  const found = result.attachments.find((a) => a.contentType === METADATA_TYPE3);
1587
1835
  if (found === void 0) return void 0;
1588
1836
  try {
1589
- const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? readFileSync2(found.path, "utf8") : void 0;
1837
+ const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? readFileSync3(found.path, "utf8") : void 0;
1590
1838
  return raw === void 0 ? void 0 : JSON.parse(raw);
1591
1839
  } catch {
1592
1840
  return void 0;
@@ -1603,7 +1851,7 @@ function statedIdOf(test, metadata, mapped) {
1603
1851
  function readIds(file) {
1604
1852
  let raw;
1605
1853
  try {
1606
- raw = readFileSync2(file, "utf8");
1854
+ raw = readFileSync3(file, "utf8");
1607
1855
  } catch {
1608
1856
  return {};
1609
1857
  }
@@ -1643,7 +1891,7 @@ function attemptOf(test, result, ctx) {
1643
1891
  name,
1644
1892
  contentType,
1645
1893
  ...path3 !== void 0 ? { path: path3 } : {},
1646
- // What a test attached from memory has no file: the bytes are the reporter's only copy (plune#928).
1894
+ // What a test attached from memory has no file: the bytes are the reporter's only copy.
1647
1895
  ...body !== void 0 ? { body } : {}
1648
1896
  })),
1649
1897
  ...ctx.buildHref !== void 0 ? { buildHref: ctx.buildHref } : {},
@@ -1670,13 +1918,15 @@ function pendingFrom(test, result, ctx, ids = {}) {
1670
1918
  // Anything the test named itself comes before what we derived from its location: a Qase or
1671
1919
  // TestRail id written by a fixture is a deliberate statement, and a file path is a guess.
1672
1920
  keys: [...metadata?.keys ?? [], ...keysFor(test)],
1673
- // Read only if nothing resolves this test, and then it is what the review queue shows (D14).
1921
+ // Read only if nothing resolves this test, and then it is what the review queue shows.
1674
1922
  // The full `describe > title` path rather than `test.title` alone: two suites in one file
1675
1923
  // routinely share a title, and "adds an item" on its own is not something a person can judge.
1676
1924
  title: titlesOf(test).join(" \u203A "),
1677
1925
  // The line as well as the file. A reviewer's first move on an unknown test is to open it, and
1678
1926
  // `specRef` is the only thing the entry carries that can take them there.
1679
1927
  specRef: `${fileOf2(test)}:${test.location.line}`,
1928
+ // Where the core reads the test's text for its case's code snapshot; never sent as it is.
1929
+ codeAt: { file: test.location.file, line: test.location.line, column: test.location.column },
1680
1930
  source: SOURCE,
1681
1931
  // The runner's own word, untouched. Mapping it is the platform's job and a project's setting.
1682
1932
  rawStatus: result.status,
@@ -1750,7 +2000,7 @@ var PluneReporter = class {
1750
2000
  ...this.options.externalKey !== void 0 ? { externalKey: this.options.externalKey } : {},
1751
2001
  ...this.options.batchSize !== void 0 ? { batchSize: this.options.batchSize } : {},
1752
2002
  ...this.options.fallbackPath !== void 0 ? { fallbackPath: this.options.fallbackPath } : {},
1753
- // Where it ran (plune#927): the commit Playwright wrote into `metadata.ci`, and its branch —
2003
+ // Where it ran: the commit Playwright wrote into `metadata.ci`, and its branch —
1754
2004
  // which Playwright gives on GitLab and Jenkins, and the core reads from the job on GitHub.
1755
2005
  meta: { runner: SOURCE, ...ciUrl !== void 0 ? { ciUrl } : {}, ...ciCommit(ci) }
1756
2006
  },