@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.cjs CHANGED
@@ -58,6 +58,7 @@ var import_crypto2 = require("crypto");
58
58
  var import_fs5 = require("fs");
59
59
  var fs = __toESM(require("fs"), 1);
60
60
  var path2 = __toESM(require("path"), 1);
61
+ var import_fs6 = require("fs");
61
62
  var import_crypto3 = require("crypto");
62
63
  var DEFAULT_API_URL = "https://beta-api.plune.ai";
63
64
  function resolveApiUrl(explicit) {
@@ -259,6 +260,7 @@ function createClient(opts) {
259
260
  upload: (path3, bytes, contentType) => send("POST", path3, { body: bytes, type: contentType }, uploadRetries ?? DEFAULT_RETRIES),
260
261
  del: (path3) => send("DELETE", path3),
261
262
  get: (path3) => send("GET", path3),
263
+ patch: (path3, body) => send("PATCH", path3, { body: JSON.stringify(body), type: "application/json" }),
262
264
  async put(url, headers, source) {
263
265
  const putRetries = uploadRetries ?? 3;
264
266
  let last = { ok: false, status: null, code: "network" };
@@ -466,7 +468,7 @@ function cutErrorContext(attempt, home) {
466
468
  const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
467
469
  return cut(machineless(text, attempt.repoRoot, home));
468
470
  }
469
- var printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
471
+ var printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "?");
470
472
  var mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
471
473
  var TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
472
474
  var isTextType = (contentType) => TEXT_TYPES.has(mediaTypeOf(contentType) ?? "");
@@ -598,10 +600,175 @@ function appendBatch(file, batch) {
598
600
  fs.appendFileSync(file, `${JSON.stringify(line)}
599
601
  `, "utf8");
600
602
  }
603
+ var SNAPSHOT_MAX_BYTES = 16384;
604
+ var CALL = /\b(?:test|it)(?:\.(?:skip|fixme|only|fail|slow))?\s*\(/g;
605
+ var BEFORE_REGEX = /* @__PURE__ */ new Set([..."(,=:[!&|?{};+-*%<>~^"]);
606
+ function skipString(src, i, quote) {
607
+ for (let j = i + 1; j < src.length; j += 1) {
608
+ const c = src[j];
609
+ if (c === "\\") j += 1;
610
+ else if (c === quote) return j + 1;
611
+ else if (c === "\n") return -1;
612
+ }
613
+ return -1;
614
+ }
615
+ function skipTemplate(src, i) {
616
+ for (let j = i + 1; j < src.length; j += 1) {
617
+ const c = src[j];
618
+ if (c === "\\") j += 1;
619
+ else if (c === "`") return j + 1;
620
+ else if (c === "$" && src[j + 1] === "{") {
621
+ const end = matching(src, j + 2, "}");
622
+ if (end < 0) return -1;
623
+ j = end;
624
+ }
625
+ }
626
+ return -1;
627
+ }
628
+ function skipRegex(src, i) {
629
+ let inClass = false;
630
+ for (let j = i + 1; j < src.length; j += 1) {
631
+ const c = src[j];
632
+ if (c === "\\") j += 1;
633
+ else if (c === "\n") return -1;
634
+ else if (c === "[") inClass = true;
635
+ else if (c === "]") inClass = false;
636
+ else if (c === "/" && !inClass) {
637
+ let k = j + 1;
638
+ while (k < src.length && /[a-z]/i.test(src[k])) k += 1;
639
+ return k;
640
+ }
641
+ }
642
+ return -1;
643
+ }
644
+ function matching(src, i, close) {
645
+ const stack = [close];
646
+ let prev = "(";
647
+ while (i < src.length) {
648
+ const c = src[i];
649
+ const next = src[i + 1];
650
+ let to = -2;
651
+ if (c === "/" && next === "/") to = src.indexOf("\n", i);
652
+ else if (c === "/" && next === "*")
653
+ to = src.indexOf("*/", i + 2) < 0 ? -1 : src.indexOf("*/", i + 2) + 2;
654
+ else if (c === "'" || c === '"') to = skipString(src, i, c);
655
+ else if (c === "`") to = skipTemplate(src, i);
656
+ else if (c === "/" && BEFORE_REGEX.has(prev)) to = skipRegex(src, i);
657
+ if (to === -1) return -1;
658
+ if (to !== -2) {
659
+ if (c !== "/" || next !== "/" && next !== "*") prev = "a";
660
+ i = to;
661
+ continue;
662
+ }
663
+ if (c === "(") stack.push(")");
664
+ else if (c === "[") stack.push("]");
665
+ else if (c === "{") stack.push("}");
666
+ else if (c === ")" || c === "]" || c === "}") {
667
+ if (stack.pop() !== c) return -1;
668
+ if (stack.length === 0) return i;
669
+ }
670
+ if (!/\s/.test(c)) prev = c;
671
+ i += 1;
672
+ }
673
+ return -1;
674
+ }
675
+ function callTextAt(source, line, column) {
676
+ const lines = source.split("\n");
677
+ if (line < 1 || line > lines.length) return void 0;
678
+ const lineStart = lines.slice(0, line - 1).reduce((n, l) => n + l.length + 1, 0);
679
+ const lineEnd = lineStart + lines[line - 1].length;
680
+ const heads = [];
681
+ CALL.lastIndex = lineStart;
682
+ for (let h = CALL.exec(source); h !== null && h.index < lineEnd; h = CALL.exec(source))
683
+ heads.push(h);
684
+ const at = column === void 0 ? -1 : lineStart + column - 1;
685
+ const head = heads.find((h) => h.index <= at && at < h.index + h[0].length) ?? (heads.length === 1 ? heads[0] : void 0);
686
+ if (head === void 0) return void 0;
687
+ const end = matching(source, head.index + head[0].length, ")");
688
+ if (end < 0) return void 0;
689
+ const text = source.slice(head.index, end + 1).replace(/\r\n/g, "\n");
690
+ return Buffer.byteLength(text, "utf8") <= SNAPSHOT_MAX_BYTES ? text : void 0;
691
+ }
692
+ var CREDENTIAL = "password|passphrase|passwd|pass|pwd|token|secret|api[-_]?key|private[-_]?key|credential|auth|session|cookie";
693
+ var LITERAL = String.raw`(?<q>['"\x60])(?:\\.|(?!\k<q>)[^\\\n])*\k<q>`;
694
+ var TYPING = "(?:fill|type|pressSequentially)";
695
+ var SHAPES = [
696
+ { kind: "github-token", re: /\b(?:ghp|gho|ghs|ghu)_[A-Za-z0-9]{36}\b|\bgithub_pat_\w{20,}/g },
697
+ { kind: "api-key", re: /\bsk-[\w-]{20,}/g },
698
+ { kind: "api-key", re: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{10,}/g },
699
+ { kind: "npm-token", re: /\bnpm_[A-Za-z0-9]{20,}/g },
700
+ { kind: "google-key", re: /\bAIza[\w-]{30,}/g },
701
+ { kind: "plune-token", re: /\bplune_[A-Za-z0-9_]{16,}/g },
702
+ { kind: "aws-key", re: /\bAKIA[0-9A-Z]{16}\b/g },
703
+ { kind: "slack-token", re: /\bxox[abprs]-[A-Za-z0-9-]{10,}/g },
704
+ {
705
+ kind: "private-key",
706
+ re: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g
707
+ },
708
+ { kind: "jwt", re: /\beyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,}/g }
709
+ ];
710
+ var PLACES = [
711
+ // `password = '…'`, `apiKey: "…"`, `'x-api-key': '…'`
712
+ new RegExp(
713
+ String.raw`(?<lead>\b(?<role>[\w$-]*(?:${CREDENTIAL})[\w$-]*)['"]?\s*[:=]\s*)${LITERAL}`,
714
+ "gi"
715
+ ),
716
+ // `setToken('…')`: the call is named for a credential
717
+ new RegExp(String.raw`(?<lead>\b(?<role>[\w$]*(?:${CREDENTIAL})[\w$]*)\s*\(\s*)${LITERAL}`, "gi"),
718
+ // `.fill('#password', '…')`, `.type('#pwd', '…')`: the field is named in the same call
719
+ new RegExp(
720
+ String.raw`(?<lead>\.${TYPING}\(\s*['"][^'"\n]*?(?<role>${CREDENTIAL})[^'"\n]*['"]\s*,\s*)${LITERAL}`,
721
+ "gi"
722
+ ),
723
+ // `getByLabel('Password').fill('…')`, `getByRole('textbox', { name: 'Password' }).type('…')`: … or
724
+ // anywhere in the call the typing is chained off
725
+ new RegExp(
726
+ String.raw`(?<lead>\([^()\n]*?(?<role>${CREDENTIAL})[^()\n]*\)\s*\.${TYPING}\(\s*)${LITERAL}`,
727
+ "gi"
728
+ ),
729
+ // `{ name: 'session', value: '…' }`: a cookie (or any name/value pair) named for a credential
730
+ new RegExp(
731
+ String.raw`(?<lead>\bname\s*:\s*['"][^'"\n]*?(?<role>${CREDENTIAL})[^'"\n]*['"]\s*,\s*value\s*:\s*)${LITERAL}`,
732
+ "gi"
733
+ )
734
+ ];
735
+ var HEADER_LINE = /((?:^|\\[nr]|\x60)[ \t>*<+-]*['"]?)((?:proxy-)?authorization|(?:set-)?cookie|[\w-]*session[\w-]*)(['"]?[ \t]*:[ \t]*)(?![\w$.]+(?:\([^()\n]*\))?[ \t]*[,;)}\]])[^\s'"\x60\\][^\r\n'"\x60\\]*/gim;
736
+ var QUERY_PARAM = /([?&][\w.-]*(?:token|key|secret|password|passwd|pass|pwd|auth|signature|sig|credential|session)[\w.-]*=)(?!‹)[^&#\s'"\x60]+/gi;
737
+ function maskCredentials(text) {
738
+ let out = text;
739
+ for (const { kind, re } of SHAPES) out = out.replace(re, `\u2039${kind}\u203A`);
740
+ for (const re of PLACES) {
741
+ out = out.replace(re, (...args) => {
742
+ const groups = args.at(-1);
743
+ return `${groups.lead}${groups.q}\u2039${groups.role.toLowerCase().replace(/^[^a-z]+/, "")}\u203A${groups.q}`;
744
+ });
745
+ }
746
+ return out.replace(HEADER_LINE, "$1$2$3\u2039header\u203A").replace(/\b(Bearer)([ \t]+)(?!‹)[\w.~+/=-]{8,}/g, "$1$2\u2039credential\u203A").replace(
747
+ /\b(Basic|Token)([ \t]+)(?!‹)(?=[\w.~+/=-]*[\d=+/]|[\w.~+/=-]*[a-z][\w.~+/=-]*[A-Z])[\w.~+/=-]{8,}/g,
748
+ "$1$2\u2039credential\u203A"
749
+ ).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@");
750
+ }
751
+ function snapshotAt(at, files) {
752
+ let source = files.get(at.file);
753
+ if (source === void 0) {
754
+ try {
755
+ source = (0, import_fs6.readFileSync)(at.file, "utf8");
756
+ } catch {
757
+ source = null;
758
+ }
759
+ files.set(at.file, source);
760
+ }
761
+ if (source === null) return void 0;
762
+ const text = callTextAt(source, at.line, at.column);
763
+ if (text === void 0) return void 0;
764
+ const masked = maskCredentials(text);
765
+ return Buffer.byteLength(masked, "utf8") <= SNAPSHOT_MAX_BYTES ? masked : void 0;
766
+ }
601
767
  var RESOLVE_CHUNK = 500;
602
768
  var BATCH_MAX = 500;
603
769
  var DISCOVER_MAX = 500;
604
770
  var BATCH_DEFAULT = 500;
771
+ var SNAPSHOT_UPDATES_MAX = 100;
605
772
  var SEND_CONCURRENCY = 4;
606
773
  var EXPECTED_MAX = 1e4;
607
774
  var KEY_MAX = 1024;
@@ -697,6 +864,7 @@ function boundKey(key) {
697
864
  if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
698
865
  return { ...key, value: `${head}#${digest}` };
699
866
  }
867
+ var keyId = (key) => `${key.kind ?? ""}\0${key.value}`;
700
868
  function whyUnoffered(out) {
701
869
  if (out.ok || out.status !== 429) return "other";
702
870
  if (/review queue quota reached/i.test(out.detail)) return "queue";
@@ -730,68 +898,14 @@ function chunk(items, size) {
730
898
  for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
731
899
  return out;
732
900
  }
733
- function warnIfDropped(sent, run, log) {
734
- const names = Object.keys(sent);
735
- if (names.length === 0) return;
736
- if (names.some((name) => run[name] != null)) return;
737
- log(
738
- `plune: this deployment stored none of ${names.join(", ")} \u2014 it is older than the fields. The run is otherwise reported in full.`
739
- );
740
- }
741
- async function startRun(passed, declared2) {
742
- const env = readEnv();
743
- if (env.shardError !== void 0) throw new Error(env.shardError);
744
- if (env.configurationError !== void 0 && passed.configuration === void 0) throw new Error(env.configurationError);
745
- const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
746
- const cfg = { ...env.config, ...stated };
747
- const configuration = cfg.configuration !== void 0 && Object.keys(cfg.configuration).length > 0 ? cfg.configuration : void 0;
748
- const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
749
- `));
750
- const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
751
- const externalKey = cfg.externalKey ?? null;
752
- const sessionMarker = (0, import_crypto.randomUUID)();
753
- const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
754
- const offerDiscovered = cfg.offerDiscovered ?? false;
755
- const token = cfg.token ?? loadToken() ?? "";
756
- const uploadsAtOnce = Math.min(Math.max(Math.floor(cfg.uploadConcurrency ?? UPLOAD_CONCURRENCY.default), UPLOAD_CONCURRENCY.min), UPLOAD_CONCURRENCY.max);
757
- const uploadRetries = Math.min(Math.max(Math.floor(cfg.uploadRetries ?? UPLOAD_RETRIES.default), UPLOAD_RETRIES.min), UPLOAD_RETRIES.max);
901
+ function fileSender(options) {
902
+ const { client, log, stats, uploadsAtOnce, uploadRetries } = options;
903
+ const without = options.without ?? "its result is reported without it";
758
904
  let retried = 0;
759
905
  let uploadMs = 0;
760
906
  let requests = 0;
761
907
  let existed = 0;
762
908
  let batchMissing = false;
763
- const client = createClient({
764
- apiUrl: resolveApiUrl(cfg.apiUrl),
765
- token,
766
- uploadRetries,
767
- onRetry: () => void (retried += 1),
768
- ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
769
- });
770
- const stats = {
771
- accepted: 0,
772
- duplicate: 0,
773
- conflict: 0,
774
- rejected: 0,
775
- unresolved: 0,
776
- offered: 0,
777
- created: 0,
778
- unoffered: 0,
779
- deferred: 0,
780
- screenshots: { uploaded: 0, skipped: 0, failed: 0 },
781
- textFiles: { uploaded: 0, skipped: 0, failed: 0 },
782
- otherFiles: { uploaded: 0, skipped: 0, failed: 0 }
783
- };
784
- const resolved = /* @__PURE__ */ new Map();
785
- let buffer = [];
786
- const discoveries = /* @__PURE__ */ new Map();
787
- const held = /* @__PURE__ */ new Map();
788
- let createdWithResult = 0;
789
- let createdUndelivered = 0;
790
- let runId = null;
791
- let joined = false;
792
- let offline = token === "";
793
- let done = false;
794
- const shortened = /* @__PURE__ */ new Set();
795
909
  const skipsSaid = /* @__PURE__ */ new Set();
796
910
  const countsOf = (kind) => kind === "text" ? stats.textFiles : kind === "file" ? stats.otherFiles : stats.screenshots;
797
911
  let bucketSeen = false;
@@ -800,168 +914,6 @@ async function startRun(passed, declared2) {
800
914
  const failedSaid = /* @__PURE__ */ new Set();
801
915
  const codesSaid = /* @__PURE__ */ new Set();
802
916
  const rooms = /* @__PURE__ */ new Map();
803
- function bound(keys) {
804
- return keys.map((key) => {
805
- const fit = boundKey(key);
806
- if (fit !== key && !shortened.has(key.value)) {
807
- shortened.add(key.value);
808
- if (shortened.size === 1) {
809
- log(
810
- `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.`
811
- );
812
- }
813
- }
814
- return fit;
815
- });
816
- }
817
- const expected = declared2?.map(bound);
818
- if (offline) {
819
- log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
820
- }
821
- for (const warning of env.warnings) log(`plune: ${warning}`);
822
- if (env.ignored.length > 0) {
823
- log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
824
- }
825
- function defer(results) {
826
- appendBatch(fallbackPath, {
827
- runId,
828
- externalKey,
829
- session: sessionMarker,
830
- ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
831
- ...configuration !== void 0 ? { configuration } : {},
832
- results: results.map(onDisk)
833
- });
834
- stats.deferred += results.length;
835
- }
836
- async function resolveKeys(values) {
837
- const unknown = values.filter((k) => !resolved.has(k.value));
838
- if (unknown.length === 0 || offline) return;
839
- for (const part of chunk(unknown, RESOLVE_CHUNK)) {
840
- const out = await client.post(
841
- "/v1/test-cases/resolve",
842
- { keys: part }
843
- );
844
- if (!out.ok || !Array.isArray(out.body?.results)) {
845
- log(`plune: could not look up test cases (${out.ok ? "the answer had no results" : out.detail || out.kind}).`);
846
- return;
847
- }
848
- for (const row of out.body.results) {
849
- if (typeof row?.key?.value === "string") resolved.set(row.key.value, row.testCaseId);
850
- }
851
- }
852
- }
853
- if (!offline) {
854
- if (expected !== void 0) await resolveKeys(expected.flat());
855
- const stated2 = expected?.slice(0, EXPECTED_MAX) ?? [];
856
- const configuration2 = stated2.length === 0 ? void 0 : {
857
- expected: stated2.flatMap((keys) => {
858
- const hit = keys.map((k) => resolved.get(k.value)).find((v) => typeof v === "string");
859
- if (typeof hit === "string") return [{ testCaseId: hit }];
860
- return keys[0] === void 0 ? [] : [{ externalKey: keys[0] }];
861
- }),
862
- // The claim travels with the list it is about (D20). A runner that could not enumerate
863
- // its tests has no list, and a claim without one is nothing the platform can check —
864
- // so it is not sent, rather than sent and silently meaningless.
865
- ...cfg.full === true ? { full: true } : {}
866
- };
867
- if (expected !== void 0 && expected.length > EXPECTED_MAX) {
868
- log(`plune: ${expected.length} tests is more than the run configuration holds \u2014 reporting the first ${EXPECTED_MAX}.`);
869
- }
870
- const described = {
871
- ...cfg.title !== void 0 ? { title: cfg.title } : {},
872
- ...cfg.environment !== void 0 ? { environment: cfg.environment } : {},
873
- ...cfg.labels !== void 0 ? { labels: cfg.labels } : {}
874
- };
875
- const request = {
876
- schemaVersion: 2,
877
- kind: cfg.kind ?? "automated",
878
- ...externalKey !== null ? { externalKey } : {},
879
- ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
880
- ...configuration2 !== void 0 ? { configuration: configuration2 } : {},
881
- // Named even when nobody named it — the list has to read without opening a row. Only what
882
- // the caller DESCRIBED goes to `warnIfDropped` below: a title this side invented is not one
883
- // a person will miss, and a deployment older than the field must not be nagged on every run.
884
- title: defaultRunTitle(),
885
- ...described
886
- };
887
- let start = await client.post("/v1/runs", request);
888
- if (!start.ok && start.status === 413 && configuration2 !== void 0) {
889
- log(
890
- `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.`
891
- );
892
- start = await client.post("/v1/runs", { ...request, configuration: void 0 });
893
- }
894
- if (start.ok && typeof start.body?.run?.id === "string") {
895
- runId = start.body.run.id;
896
- joined = start.status === 200;
897
- warnIfDropped(described, start.body.run, log);
898
- } else {
899
- const why = start.ok ? "the answer had no run" : start.detail || start.kind;
900
- log(`plune: could not start the run (${why}). Results will be written to ${fallbackPath}.`);
901
- }
902
- }
903
- function matchFor(result) {
904
- if (result.testCaseId !== void 0) return { kind: "found", testCaseId: result.testCaseId };
905
- let unanswered = false;
906
- for (const key of result.keys) {
907
- const hit = resolved.get(key.value);
908
- if (typeof hit === "string") return { kind: "found", testCaseId: hit };
909
- if (hit === void 0) unanswered = true;
910
- }
911
- return unanswered ? { kind: "unanswered" } : { kind: "unmatched" };
912
- }
913
- function remember(result) {
914
- if (!offerDiscovered) return;
915
- if (result.title === void 0 || result.specRef === void 0) return;
916
- if (result.keys.length === 0) return;
917
- const title = boundTitle(result.title);
918
- if (title !== result.title) shortened.add(result.title);
919
- discoveries.set(result.keys[0].value, {
920
- keys: result.keys,
921
- title,
922
- source: result.source,
923
- specRef: result.specRef,
924
- rawStatus: result.rawStatus
925
- });
926
- held.set(result.keys[0].value, result);
927
- }
928
- async function offer() {
929
- if (discoveries.size === 0 || offline || runId === null) return;
930
- const batches = chunk([...discoveries.values()], DISCOVER_MAX);
931
- for (const [index, batch] of batches.entries()) {
932
- const out = await client.post("/v1/review-items/discovered", {
933
- discovered: batch,
934
- runId
935
- });
936
- if (!out.ok || !Array.isArray(out.body?.results)) {
937
- stats.unoffered = batches.slice(index).reduce((n, rest) => n + rest.length, 0);
938
- stats.unofferedWhy = whyUnoffered(out);
939
- log(
940
- `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.ok ? "the answer had no results" : out.detail || out.kind}).`
941
- );
942
- return;
943
- }
944
- stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
945
- const made = out.body.results.filter((r) => r?.outcome === "created");
946
- stats.created += made.length;
947
- const submissions = [];
948
- const filesByKey = /* @__PURE__ */ new Map();
949
- for (const r of made) {
950
- const pending = typeof r.id === "string" && r.id !== "" ? held.get(r.key?.value) : void 0;
951
- if (pending === void 0) continue;
952
- held.delete(r.key.value);
953
- const { keys: _keys, files, ...rest } = pending;
954
- submissions.push({ ...rest, testCaseId: r.id });
955
- if (files !== void 0) filesByKey.set(pending.resultKey, files);
956
- }
957
- if (submissions.length > 0) {
958
- const before = stats.deferred;
959
- await send(submissions, filesByKey);
960
- createdWithResult += submissions.length;
961
- createdUndelivered += stats.deferred - before;
962
- }
963
- }
964
- }
965
917
  function skip(kind, name, why) {
966
918
  countsOf(kind).skipped += 1;
967
919
  if (why === "noStorage") noStorage += 1;
@@ -971,24 +923,25 @@ async function startRun(passed, declared2) {
971
923
  if (why === "noStorage") log(`plune: "${name}" not stored \u2014 ${SKIPPED[why]}.`);
972
924
  else log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
973
925
  }
926
+ const filesOf2 = (job) => `/v1/${job.owner ?? "results"}/${encodeURIComponent(job.id)}/files`;
974
927
  function ask(job, size) {
975
928
  requests += 1;
976
- return client.post(`/v1/results/${encodeURIComponent(job.id)}/files/uploads`, {
977
- files: [{ name: job.name, contentType: job.type, size }]
929
+ return client.post(`${filesOf2(job)}/uploads`, {
930
+ files: [{ name: job.name, contentType: job.type, size, ...job.key !== void 0 ? { key: job.key } : {} }]
978
931
  }, uploadRetries);
979
932
  }
980
933
  function failed(job, why) {
981
934
  countsOf(job.kind).failed += 1;
982
935
  if (!failedSaid.has(job.kind)) {
983
936
  failedSaid.add(job.kind);
984
- log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 its result is reported without it.`);
937
+ log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 ${without}.`);
985
938
  }
986
939
  }
987
940
  function failedToBucket(job, code) {
988
941
  countsOf(job.kind).failed += 1;
989
942
  if (codesSaid.has(code)) return;
990
943
  codesSaid.add(code);
991
- log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 its result is reported without it.`);
944
+ log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 ${without}.`);
992
945
  }
993
946
  function refusedHere(job, size) {
994
947
  if (job.kind === "screenshot") {
@@ -1016,7 +969,7 @@ async function startRun(passed, declared2) {
1016
969
  if (refusal !== void 0) return skip(kind, job.name, refusal);
1017
970
  requests += 1;
1018
971
  const out = await client.upload(
1019
- `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
972
+ `${filesOf2(job)}?name=${encodeURIComponent(job.name)}`,
1020
973
  bytes,
1021
974
  job.type
1022
975
  );
@@ -1038,8 +991,8 @@ async function startRun(passed, declared2) {
1038
991
  link = fresh;
1039
992
  }
1040
993
  requests += 1;
1041
- const done2 = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
1042
- if (!done2.ok) return failedToBucket(job, codeOf(done2));
994
+ const done = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
995
+ if (!done.ok) return failedToBucket(job, codeOf(done));
1043
996
  countsOf(job.kind).uploaded += 1;
1044
997
  }
1045
998
  let free = uploadsAtOnce;
@@ -1366,6 +1319,295 @@ async function startRun(passed, declared2) {
1366
1319
  else await uploadBatched(jobs);
1367
1320
  uploadMs += Date.now() - started;
1368
1321
  }
1322
+ return {
1323
+ upload,
1324
+ uploadEach,
1325
+ onRetry: () => void (retried += 1),
1326
+ get bucketSeen() {
1327
+ return bucketSeen;
1328
+ },
1329
+ get noStorage() {
1330
+ return noStorage;
1331
+ },
1332
+ get existed() {
1333
+ return existed;
1334
+ },
1335
+ get retried() {
1336
+ return retried;
1337
+ },
1338
+ get uploadMs() {
1339
+ return uploadMs;
1340
+ },
1341
+ get requests() {
1342
+ return requests;
1343
+ }
1344
+ };
1345
+ }
1346
+ function warnIfDropped(sent, run, log) {
1347
+ const names = Object.keys(sent);
1348
+ if (names.length === 0) return;
1349
+ if (names.some((name) => run[name] != null)) return;
1350
+ log(
1351
+ `plune: this deployment stored none of ${names.join(", ")} \u2014 it is older than the fields. The run is otherwise reported in full.`
1352
+ );
1353
+ }
1354
+ async function startRun(passed, declared2) {
1355
+ const env = readEnv();
1356
+ if (env.shardError !== void 0) throw new Error(env.shardError);
1357
+ if (env.configurationError !== void 0 && passed.configuration === void 0) throw new Error(env.configurationError);
1358
+ const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
1359
+ const cfg = { ...env.config, ...stated };
1360
+ const configuration = cfg.configuration !== void 0 && Object.keys(cfg.configuration).length > 0 ? cfg.configuration : void 0;
1361
+ const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
1362
+ `));
1363
+ const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
1364
+ const externalKey = cfg.externalKey ?? null;
1365
+ const sessionMarker = (0, import_crypto.randomUUID)();
1366
+ const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
1367
+ const offerDiscovered = cfg.offerDiscovered ?? false;
1368
+ const token = cfg.token ?? loadToken() ?? "";
1369
+ const uploadsAtOnce = Math.min(Math.max(Math.floor(cfg.uploadConcurrency ?? UPLOAD_CONCURRENCY.default), UPLOAD_CONCURRENCY.min), UPLOAD_CONCURRENCY.max);
1370
+ const uploadRetries = Math.min(Math.max(Math.floor(cfg.uploadRetries ?? UPLOAD_RETRIES.default), UPLOAD_RETRIES.min), UPLOAD_RETRIES.max);
1371
+ const client = createClient({
1372
+ apiUrl: resolveApiUrl(cfg.apiUrl),
1373
+ token,
1374
+ uploadRetries,
1375
+ onRetry: () => files.onRetry(),
1376
+ ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
1377
+ });
1378
+ const stats = {
1379
+ accepted: 0,
1380
+ duplicate: 0,
1381
+ conflict: 0,
1382
+ rejected: 0,
1383
+ unresolved: 0,
1384
+ offered: 0,
1385
+ created: 0,
1386
+ unoffered: 0,
1387
+ deferred: 0,
1388
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 },
1389
+ textFiles: { uploaded: 0, skipped: 0, failed: 0 },
1390
+ otherFiles: { uploaded: 0, skipped: 0, failed: 0 }
1391
+ };
1392
+ const files = fileSender({ client, log, stats, uploadsAtOnce, uploadRetries });
1393
+ const resolved = /* @__PURE__ */ new Map();
1394
+ let buffer = [];
1395
+ const discoveries = /* @__PURE__ */ new Map();
1396
+ const held = /* @__PURE__ */ new Map();
1397
+ let createdWithResult = 0;
1398
+ let createdUndelivered = 0;
1399
+ let runId = null;
1400
+ let joined = false;
1401
+ let offline = token === "";
1402
+ let done = false;
1403
+ const shortened = /* @__PURE__ */ new Set();
1404
+ const specFiles = /* @__PURE__ */ new Map();
1405
+ const snapshotByKey = /* @__PURE__ */ new Map();
1406
+ const snapshots = /* @__PURE__ */ new Map();
1407
+ function bound(keys) {
1408
+ return keys.map((key) => {
1409
+ const fit = boundKey(key);
1410
+ if (fit !== key && !shortened.has(key.value)) {
1411
+ shortened.add(key.value);
1412
+ if (shortened.size === 1) {
1413
+ log(
1414
+ `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.`
1415
+ );
1416
+ }
1417
+ }
1418
+ return fit;
1419
+ });
1420
+ }
1421
+ const expected = declared2?.map(bound);
1422
+ if (offline) {
1423
+ log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
1424
+ }
1425
+ for (const warning of env.warnings) log(`plune: ${warning}`);
1426
+ if (env.ignored.length > 0) {
1427
+ log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
1428
+ }
1429
+ function defer(results) {
1430
+ appendBatch(fallbackPath, {
1431
+ runId,
1432
+ externalKey,
1433
+ session: sessionMarker,
1434
+ ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
1435
+ ...configuration !== void 0 ? { configuration } : {},
1436
+ results: results.map(onDisk)
1437
+ });
1438
+ stats.deferred += results.length;
1439
+ }
1440
+ async function resolveKeys(values) {
1441
+ const unknown = values.filter((k) => !resolved.has(keyId(k)));
1442
+ if (unknown.length === 0 || offline) return;
1443
+ for (const part of chunk(unknown, RESOLVE_CHUNK)) {
1444
+ const out = await client.post(
1445
+ "/v1/test-cases/resolve",
1446
+ { keys: part }
1447
+ );
1448
+ if (!out.ok || !Array.isArray(out.body?.results)) {
1449
+ log(`plune: could not look up test cases (${out.ok ? "the answer had no results" : out.detail || out.kind}).`);
1450
+ return;
1451
+ }
1452
+ for (const row of out.body.results) {
1453
+ if (typeof row?.key?.value === "string") resolved.set(keyId(row.key), row.testCaseId);
1454
+ }
1455
+ }
1456
+ }
1457
+ if (!offline) {
1458
+ if (expected !== void 0) await resolveKeys(expected.flat());
1459
+ const stated2 = expected?.slice(0, EXPECTED_MAX) ?? [];
1460
+ const configuration2 = stated2.length === 0 ? void 0 : {
1461
+ expected: stated2.flatMap((keys) => {
1462
+ const hit = keys.map((k) => resolved.get(keyId(k))).find((v) => typeof v === "string");
1463
+ if (typeof hit === "string") return [{ testCaseId: hit }];
1464
+ return keys[0] === void 0 ? [] : [{ externalKey: keys[0] }];
1465
+ }),
1466
+ // The claim travels with the list it is about. A runner that could not enumerate
1467
+ // its tests has no list, and a claim without one is nothing the platform can check —
1468
+ // so it is not sent, rather than sent and silently meaningless.
1469
+ ...cfg.full === true ? { full: true } : {}
1470
+ };
1471
+ if (expected !== void 0 && expected.length > EXPECTED_MAX) {
1472
+ log(`plune: ${expected.length} tests is more than the run configuration holds \u2014 reporting the first ${EXPECTED_MAX}.`);
1473
+ }
1474
+ const described = {
1475
+ ...cfg.title !== void 0 ? { title: cfg.title } : {},
1476
+ ...cfg.environment !== void 0 ? { environment: cfg.environment } : {},
1477
+ ...cfg.labels !== void 0 ? { labels: cfg.labels } : {}
1478
+ };
1479
+ const request = {
1480
+ schemaVersion: 2,
1481
+ kind: cfg.kind ?? "automated",
1482
+ ...externalKey !== null ? { externalKey } : {},
1483
+ ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
1484
+ ...configuration2 !== void 0 ? { configuration: configuration2 } : {},
1485
+ // Named even when nobody named it — the list has to read without opening a row. Only what
1486
+ // the caller DESCRIBED goes to `warnIfDropped` below: a title this side invented is not one
1487
+ // a person will miss, and a deployment older than the field must not be nagged on every run.
1488
+ title: defaultRunTitle(),
1489
+ ...described
1490
+ };
1491
+ let start = await client.post("/v1/runs", request);
1492
+ if (!start.ok && start.status === 413 && configuration2 !== void 0) {
1493
+ log(
1494
+ `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.`
1495
+ );
1496
+ start = await client.post("/v1/runs", { ...request, configuration: void 0 });
1497
+ }
1498
+ if (start.ok && typeof start.body?.run?.id === "string") {
1499
+ runId = start.body.run.id;
1500
+ joined = start.status === 200;
1501
+ warnIfDropped(described, start.body.run, log);
1502
+ } else {
1503
+ const why = start.ok ? "the answer had no run" : start.detail || start.kind;
1504
+ log(`plune: could not start the run (${why}). Results will be written to ${fallbackPath}.`);
1505
+ }
1506
+ }
1507
+ function matchFor(result) {
1508
+ if (result.testCaseId !== void 0) return { kind: "found", testCaseId: result.testCaseId };
1509
+ let unanswered = false;
1510
+ for (const key of result.keys) {
1511
+ const hit = resolved.get(keyId(key));
1512
+ if (typeof hit === "string") return { kind: "found", testCaseId: hit };
1513
+ if (hit === void 0) unanswered = true;
1514
+ }
1515
+ return unanswered ? { kind: "unanswered" } : { kind: "unmatched" };
1516
+ }
1517
+ function remember(result) {
1518
+ if (!offerDiscovered) return;
1519
+ if (result.title === void 0 || result.specRef === void 0) return;
1520
+ if (result.keys.length === 0) return;
1521
+ const title = boundTitle(result.title);
1522
+ if (title !== result.title) shortened.add(result.title);
1523
+ discoveries.set(keyId(result.keys[0]), {
1524
+ keys: result.keys,
1525
+ title,
1526
+ source: result.source,
1527
+ specRef: result.specRef,
1528
+ rawStatus: result.rawStatus
1529
+ });
1530
+ for (const key of result.keys) held.set(keyId(key), result);
1531
+ }
1532
+ async function offer() {
1533
+ if (discoveries.size === 0 || offline || runId === null) return;
1534
+ const batches = chunk([...discoveries.values()], DISCOVER_MAX);
1535
+ for (const [index, batch] of batches.entries()) {
1536
+ const out = await client.post("/v1/review-items/discovered", {
1537
+ discovered: batch,
1538
+ runId
1539
+ });
1540
+ if (!out.ok || !Array.isArray(out.body?.results)) {
1541
+ stats.unoffered = batches.slice(index).reduce((n, rest) => n + rest.length, 0);
1542
+ stats.unofferedWhy = whyUnoffered(out);
1543
+ log(
1544
+ `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.ok ? "the answer had no results" : out.detail || out.kind}).`
1545
+ );
1546
+ return;
1547
+ }
1548
+ stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
1549
+ const made = out.body.results.filter((r) => r?.outcome === "created");
1550
+ stats.created += made.length;
1551
+ const submissions = [];
1552
+ const filesByKey = /* @__PURE__ */ new Map();
1553
+ for (const r of made) {
1554
+ const pending = typeof r.id === "string" && r.id !== "" && typeof r.key?.value === "string" ? held.get(keyId(r.key)) : void 0;
1555
+ if (pending === void 0) continue;
1556
+ for (const key of pending.keys) held.delete(keyId(key));
1557
+ const { keys: _keys, files: files2, ...rest } = pending;
1558
+ submissions.push({ ...rest, testCaseId: r.id });
1559
+ if (files2 !== void 0) filesByKey.set(pending.resultKey, files2);
1560
+ const text = snapshotByKey.get(pending.resultKey);
1561
+ if (text !== void 0) snapshots.set(r.id, text);
1562
+ }
1563
+ if (submissions.length > 0) {
1564
+ const before = stats.deferred;
1565
+ await send(submissions, filesByKey);
1566
+ createdWithResult += submissions.length;
1567
+ createdUndelivered += stats.deferred - before;
1568
+ }
1569
+ }
1570
+ }
1571
+ async function syncSnapshots() {
1572
+ if (snapshots.size === 0 || offline) return;
1573
+ const stored = /* @__PURE__ */ new Map();
1574
+ let cursor = null;
1575
+ do {
1576
+ const query = `type=automated&stability=0&limit=200${cursor === null ? "" : `&cursor=${encodeURIComponent(cursor)}`}`;
1577
+ const out = await client.get(`/v1/test-cases?${query}`);
1578
+ if (!out.ok || !Array.isArray(out.body?.testCases)) {
1579
+ log(`plune: could not update the code snapshots (${out.ok ? "the case list had no cases" : out.detail || out.kind}).`);
1580
+ return;
1581
+ }
1582
+ for (const row of out.body.testCases) {
1583
+ if (typeof row?.id === "string" && snapshots.has(row.id)) stored.set(row.id, row.codeSnapshotHash ?? null);
1584
+ }
1585
+ cursor = typeof out.body.nextCursor === "string" ? out.body.nextCursor : null;
1586
+ } while (cursor !== null && stored.size < snapshots.size);
1587
+ const sha = (text) => (0, import_crypto.createHash)("sha256").update(text).digest("hex");
1588
+ const due = [...snapshots].filter(([id, text]) => stored.has(id) && stored.get(id) !== sha(text)).sort(([a], [b]) => sha(`${runId}:${a}`).localeCompare(sha(`${runId}:${b}`)));
1589
+ let updated = 0;
1590
+ let refused = 0;
1591
+ let tried = 0;
1592
+ for (const [id, text] of due.slice(0, SNAPSHOT_UPDATES_MAX)) {
1593
+ tried += 1;
1594
+ const out = await client.patch(`/v1/test-cases/${encodeURIComponent(id)}`, { codeSnapshot: text });
1595
+ if (out.ok) {
1596
+ updated += 1;
1597
+ continue;
1598
+ }
1599
+ if (out.kind === "auth" || out.kind === "unavailable" || out.status === 429) {
1600
+ log(`plune: could not update the code snapshot of test case ${id} (${out.detail || out.kind}); the rest are left as they are.`);
1601
+ break;
1602
+ }
1603
+ refused += 1;
1604
+ }
1605
+ const left = due.length - tried;
1606
+ const parts = [`${updated} code snapshot(s) updated`];
1607
+ if (refused > 0) parts.push(`${refused} not updated`);
1608
+ if (left > 0 && tried === Math.min(due.length, SNAPSHOT_UPDATES_MAX)) parts.push(`${left} left for the next run`);
1609
+ if (updated + refused > 0) log(`plune: ${parts.join(", ")}`);
1610
+ }
1369
1611
  const sending = /* @__PURE__ */ new Set();
1370
1612
  let sendError;
1371
1613
  let answered = false;
@@ -1406,9 +1648,11 @@ async function startRun(passed, declared2) {
1406
1648
  for (const result of pending) {
1407
1649
  const match = matchFor(result);
1408
1650
  if (match.kind === "found") {
1409
- const { keys: _keys, files, ...rest } = result;
1651
+ const { keys: _keys, files: files2, ...rest } = result;
1410
1652
  submissions.push({ ...rest, testCaseId: match.testCaseId });
1411
- if (files !== void 0) filesByKey.set(result.resultKey, files);
1653
+ const text = snapshotByKey.get(result.resultKey);
1654
+ if (text !== void 0) snapshots.set(match.testCaseId, text);
1655
+ if (files2 !== void 0) filesByKey.set(result.resultKey, files2);
1412
1656
  } else if (match.kind === "unmatched") {
1413
1657
  stats.unresolved += 1;
1414
1658
  remember(result);
@@ -1431,7 +1675,7 @@ async function startRun(passed, declared2) {
1431
1675
  }
1432
1676
  const out = await client.post(
1433
1677
  `/v1/runs/${runId}/results`,
1434
- // The job's combination on every batch (plune-ai/plune#1251); a refusal of it is a 422 said below as it came.
1678
+ // The job's combination on every batch; a refusal of it is a 422 said below as it came.
1435
1679
  { results: part, ...configuration !== void 0 ? { configuration } : {} }
1436
1680
  );
1437
1681
  const counts = out.ok ? out.body?.counts : void 0;
@@ -1439,7 +1683,7 @@ async function startRun(passed, declared2) {
1439
1683
  if (told.length > 0) {
1440
1684
  for (const k of told) stats[k] += counts[k];
1441
1685
  progress();
1442
- await upload(out.ok ? out.body?.items : void 0, filesByKey);
1686
+ await files.upload(out.ok ? out.body?.items : void 0, filesByKey);
1443
1687
  answered = true;
1444
1688
  continue;
1445
1689
  }
@@ -1475,10 +1719,10 @@ async function startRun(passed, declared2) {
1475
1719
  }
1476
1720
  const kinds = [stats.screenshots, stats.textFiles, stats.otherFiles];
1477
1721
  const sum = (what) => kinds.reduce((n, counts) => n + counts[what], 0);
1478
- if (bucketSeen) {
1479
- const other = sum("skipped") - noStorage;
1722
+ if (files.bucketSeen) {
1723
+ const other = sum("skipped") - files.noStorage;
1480
1724
  parts.push(
1481
- `${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` : "")
1725
+ `${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` : "")
1482
1726
  );
1483
1727
  } else {
1484
1728
  for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
@@ -1490,11 +1734,10 @@ async function startRun(passed, declared2) {
1490
1734
  }
1491
1735
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
1492
1736
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
1493
- const files = [stats.screenshots, stats.textFiles, stats.otherFiles];
1494
- const total = (what) => files.reduce((n, counts) => n + counts[what], 0);
1495
- if (total("uploaded") + total("skipped") + total("failed") + existed > 0) {
1737
+ const total = (what) => kinds.reduce((n, counts) => n + counts[what], 0);
1738
+ if (total("uploaded") + total("skipped") + total("failed") + files.existed > 0) {
1496
1739
  log(
1497
- `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)`
1740
+ `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)`
1498
1741
  );
1499
1742
  }
1500
1743
  log(`plune: ${parts.join(" \xB7 ")}`);
@@ -1514,7 +1757,10 @@ async function startRun(passed, declared2) {
1514
1757
  return stats;
1515
1758
  },
1516
1759
  async add(result) {
1517
- buffer.push({ ...result, keys: bound(result.keys) });
1760
+ const { codeAt, ...rest } = result;
1761
+ const text = codeAt === void 0 ? void 0 : snapshotAt(codeAt, specFiles);
1762
+ if (text !== void 0) snapshotByKey.set(result.resultKey, text);
1763
+ buffer.push({ ...rest, keys: bound(result.keys) });
1518
1764
  if (buffer.length >= batchSize) await flushBuffer();
1519
1765
  },
1520
1766
  flush,
@@ -1523,6 +1769,7 @@ async function startRun(passed, declared2) {
1523
1769
  done = true;
1524
1770
  await flush();
1525
1771
  await offer();
1772
+ await syncSnapshots();
1526
1773
  let frozen;
1527
1774
  if (runId !== null && !offline) {
1528
1775
  const out = await client.post(`/v1/runs/${runId}/events`, {
@@ -1546,6 +1793,7 @@ async function startRun(passed, declared2) {
1546
1793
  done = true;
1547
1794
  await flush();
1548
1795
  await offer();
1796
+ await syncSnapshots();
1549
1797
  let frozen;
1550
1798
  const after = [];
1551
1799
  const shard = env.shard;
@@ -1677,7 +1925,7 @@ function attemptOf(test, result, ctx) {
1677
1925
  name,
1678
1926
  contentType,
1679
1927
  ...path3 !== void 0 ? { path: path3 } : {},
1680
- // What a test attached from memory has no file: the bytes are the reporter's only copy (plune#928).
1928
+ // What a test attached from memory has no file: the bytes are the reporter's only copy.
1681
1929
  ...body !== void 0 ? { body } : {}
1682
1930
  })),
1683
1931
  ...ctx.buildHref !== void 0 ? { buildHref: ctx.buildHref } : {},
@@ -1704,13 +1952,15 @@ function pendingFrom(test, result, ctx, ids = {}) {
1704
1952
  // Anything the test named itself comes before what we derived from its location: a Qase or
1705
1953
  // TestRail id written by a fixture is a deliberate statement, and a file path is a guess.
1706
1954
  keys: [...metadata?.keys ?? [], ...keysFor(test)],
1707
- // Read only if nothing resolves this test, and then it is what the review queue shows (D14).
1955
+ // Read only if nothing resolves this test, and then it is what the review queue shows.
1708
1956
  // The full `describe > title` path rather than `test.title` alone: two suites in one file
1709
1957
  // routinely share a title, and "adds an item" on its own is not something a person can judge.
1710
1958
  title: titlesOf(test).join(" \u203A "),
1711
1959
  // The line as well as the file. A reviewer's first move on an unknown test is to open it, and
1712
1960
  // `specRef` is the only thing the entry carries that can take them there.
1713
1961
  specRef: `${fileOf2(test)}:${test.location.line}`,
1962
+ // Where the core reads the test's text for its case's code snapshot; never sent as it is.
1963
+ codeAt: { file: test.location.file, line: test.location.line, column: test.location.column },
1714
1964
  source: SOURCE,
1715
1965
  // The runner's own word, untouched. Mapping it is the platform's job and a project's setting.
1716
1966
  rawStatus: result.status,
@@ -1784,7 +2034,7 @@ var PluneReporter = class {
1784
2034
  ...this.options.externalKey !== void 0 ? { externalKey: this.options.externalKey } : {},
1785
2035
  ...this.options.batchSize !== void 0 ? { batchSize: this.options.batchSize } : {},
1786
2036
  ...this.options.fallbackPath !== void 0 ? { fallbackPath: this.options.fallbackPath } : {},
1787
- // Where it ran (plune#927): the commit Playwright wrote into `metadata.ci`, and its branch —
2037
+ // Where it ran: the commit Playwright wrote into `metadata.ci`, and its branch —
1788
2038
  // which Playwright gives on GitLab and Jenkins, and the core reads from the job on GitHub.
1789
2039
  meta: { runner: SOURCE, ...ciUrl !== void 0 ? { ciUrl } : {}, ...ciCommit(ci) }
1790
2040
  },