@plune-ai/playwright 0.7.1 → 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;
@@ -731,68 +898,14 @@ function chunk(items, size) {
731
898
  for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
732
899
  return out;
733
900
  }
734
- function warnIfDropped(sent, run, log) {
735
- const names = Object.keys(sent);
736
- if (names.length === 0) return;
737
- if (names.some((name) => run[name] != null)) return;
738
- log(
739
- `plune: this deployment stored none of ${names.join(", ")} \u2014 it is older than the fields. The run is otherwise reported in full.`
740
- );
741
- }
742
- async function startRun(passed, declared2) {
743
- const env = readEnv();
744
- if (env.shardError !== void 0) throw new Error(env.shardError);
745
- if (env.configurationError !== void 0 && passed.configuration === void 0) throw new Error(env.configurationError);
746
- const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
747
- const cfg = { ...env.config, ...stated };
748
- const configuration = cfg.configuration !== void 0 && Object.keys(cfg.configuration).length > 0 ? cfg.configuration : void 0;
749
- const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
750
- `));
751
- const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
752
- const externalKey = cfg.externalKey ?? null;
753
- const sessionMarker = (0, import_crypto.randomUUID)();
754
- const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
755
- const offerDiscovered = cfg.offerDiscovered ?? false;
756
- const token = cfg.token ?? loadToken() ?? "";
757
- const uploadsAtOnce = Math.min(Math.max(Math.floor(cfg.uploadConcurrency ?? UPLOAD_CONCURRENCY.default), UPLOAD_CONCURRENCY.min), UPLOAD_CONCURRENCY.max);
758
- 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";
759
904
  let retried = 0;
760
905
  let uploadMs = 0;
761
906
  let requests = 0;
762
907
  let existed = 0;
763
908
  let batchMissing = false;
764
- const client = createClient({
765
- apiUrl: resolveApiUrl(cfg.apiUrl),
766
- token,
767
- uploadRetries,
768
- onRetry: () => void (retried += 1),
769
- ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
770
- });
771
- const stats = {
772
- accepted: 0,
773
- duplicate: 0,
774
- conflict: 0,
775
- rejected: 0,
776
- unresolved: 0,
777
- offered: 0,
778
- created: 0,
779
- unoffered: 0,
780
- deferred: 0,
781
- screenshots: { uploaded: 0, skipped: 0, failed: 0 },
782
- textFiles: { uploaded: 0, skipped: 0, failed: 0 },
783
- otherFiles: { uploaded: 0, skipped: 0, failed: 0 }
784
- };
785
- const resolved = /* @__PURE__ */ new Map();
786
- let buffer = [];
787
- const discoveries = /* @__PURE__ */ new Map();
788
- const held = /* @__PURE__ */ new Map();
789
- let createdWithResult = 0;
790
- let createdUndelivered = 0;
791
- let runId = null;
792
- let joined = false;
793
- let offline = token === "";
794
- let done = false;
795
- const shortened = /* @__PURE__ */ new Set();
796
909
  const skipsSaid = /* @__PURE__ */ new Set();
797
910
  const countsOf = (kind) => kind === "text" ? stats.textFiles : kind === "file" ? stats.otherFiles : stats.screenshots;
798
911
  let bucketSeen = false;
@@ -801,168 +914,6 @@ async function startRun(passed, declared2) {
801
914
  const failedSaid = /* @__PURE__ */ new Set();
802
915
  const codesSaid = /* @__PURE__ */ new Set();
803
916
  const rooms = /* @__PURE__ */ new Map();
804
- function bound(keys) {
805
- return keys.map((key) => {
806
- const fit = boundKey(key);
807
- if (fit !== key && !shortened.has(key.value)) {
808
- shortened.add(key.value);
809
- if (shortened.size === 1) {
810
- log(
811
- `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.`
812
- );
813
- }
814
- }
815
- return fit;
816
- });
817
- }
818
- const expected = declared2?.map(bound);
819
- if (offline) {
820
- log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
821
- }
822
- for (const warning of env.warnings) log(`plune: ${warning}`);
823
- if (env.ignored.length > 0) {
824
- log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
825
- }
826
- function defer(results) {
827
- appendBatch(fallbackPath, {
828
- runId,
829
- externalKey,
830
- session: sessionMarker,
831
- ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
832
- ...configuration !== void 0 ? { configuration } : {},
833
- results: results.map(onDisk)
834
- });
835
- stats.deferred += results.length;
836
- }
837
- async function resolveKeys(values) {
838
- const unknown = values.filter((k) => !resolved.has(keyId(k)));
839
- if (unknown.length === 0 || offline) return;
840
- for (const part of chunk(unknown, RESOLVE_CHUNK)) {
841
- const out = await client.post(
842
- "/v1/test-cases/resolve",
843
- { keys: part }
844
- );
845
- if (!out.ok || !Array.isArray(out.body?.results)) {
846
- log(`plune: could not look up test cases (${out.ok ? "the answer had no results" : out.detail || out.kind}).`);
847
- return;
848
- }
849
- for (const row of out.body.results) {
850
- if (typeof row?.key?.value === "string") resolved.set(keyId(row.key), row.testCaseId);
851
- }
852
- }
853
- }
854
- if (!offline) {
855
- if (expected !== void 0) await resolveKeys(expected.flat());
856
- const stated2 = expected?.slice(0, EXPECTED_MAX) ?? [];
857
- const configuration2 = stated2.length === 0 ? void 0 : {
858
- expected: stated2.flatMap((keys) => {
859
- const hit = keys.map((k) => resolved.get(keyId(k))).find((v) => typeof v === "string");
860
- if (typeof hit === "string") return [{ testCaseId: hit }];
861
- return keys[0] === void 0 ? [] : [{ externalKey: keys[0] }];
862
- }),
863
- // The claim travels with the list it is about (D20). A runner that could not enumerate
864
- // its tests has no list, and a claim without one is nothing the platform can check —
865
- // so it is not sent, rather than sent and silently meaningless.
866
- ...cfg.full === true ? { full: true } : {}
867
- };
868
- if (expected !== void 0 && expected.length > EXPECTED_MAX) {
869
- log(`plune: ${expected.length} tests is more than the run configuration holds \u2014 reporting the first ${EXPECTED_MAX}.`);
870
- }
871
- const described = {
872
- ...cfg.title !== void 0 ? { title: cfg.title } : {},
873
- ...cfg.environment !== void 0 ? { environment: cfg.environment } : {},
874
- ...cfg.labels !== void 0 ? { labels: cfg.labels } : {}
875
- };
876
- const request = {
877
- schemaVersion: 2,
878
- kind: cfg.kind ?? "automated",
879
- ...externalKey !== null ? { externalKey } : {},
880
- ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
881
- ...configuration2 !== void 0 ? { configuration: configuration2 } : {},
882
- // Named even when nobody named it — the list has to read without opening a row. Only what
883
- // the caller DESCRIBED goes to `warnIfDropped` below: a title this side invented is not one
884
- // a person will miss, and a deployment older than the field must not be nagged on every run.
885
- title: defaultRunTitle(),
886
- ...described
887
- };
888
- let start = await client.post("/v1/runs", request);
889
- if (!start.ok && start.status === 413 && configuration2 !== void 0) {
890
- log(
891
- `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.`
892
- );
893
- start = await client.post("/v1/runs", { ...request, configuration: void 0 });
894
- }
895
- if (start.ok && typeof start.body?.run?.id === "string") {
896
- runId = start.body.run.id;
897
- joined = start.status === 200;
898
- warnIfDropped(described, start.body.run, log);
899
- } else {
900
- const why = start.ok ? "the answer had no run" : start.detail || start.kind;
901
- log(`plune: could not start the run (${why}). Results will be written to ${fallbackPath}.`);
902
- }
903
- }
904
- function matchFor(result) {
905
- if (result.testCaseId !== void 0) return { kind: "found", testCaseId: result.testCaseId };
906
- let unanswered = false;
907
- for (const key of result.keys) {
908
- const hit = resolved.get(keyId(key));
909
- if (typeof hit === "string") return { kind: "found", testCaseId: hit };
910
- if (hit === void 0) unanswered = true;
911
- }
912
- return unanswered ? { kind: "unanswered" } : { kind: "unmatched" };
913
- }
914
- function remember(result) {
915
- if (!offerDiscovered) return;
916
- if (result.title === void 0 || result.specRef === void 0) return;
917
- if (result.keys.length === 0) return;
918
- const title = boundTitle(result.title);
919
- if (title !== result.title) shortened.add(result.title);
920
- discoveries.set(keyId(result.keys[0]), {
921
- keys: result.keys,
922
- title,
923
- source: result.source,
924
- specRef: result.specRef,
925
- rawStatus: result.rawStatus
926
- });
927
- for (const key of result.keys) held.set(keyId(key), result);
928
- }
929
- async function offer() {
930
- if (discoveries.size === 0 || offline || runId === null) return;
931
- const batches = chunk([...discoveries.values()], DISCOVER_MAX);
932
- for (const [index, batch] of batches.entries()) {
933
- const out = await client.post("/v1/review-items/discovered", {
934
- discovered: batch,
935
- runId
936
- });
937
- if (!out.ok || !Array.isArray(out.body?.results)) {
938
- stats.unoffered = batches.slice(index).reduce((n, rest) => n + rest.length, 0);
939
- stats.unofferedWhy = whyUnoffered(out);
940
- log(
941
- `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.ok ? "the answer had no results" : out.detail || out.kind}).`
942
- );
943
- return;
944
- }
945
- stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
946
- const made = out.body.results.filter((r) => r?.outcome === "created");
947
- stats.created += made.length;
948
- const submissions = [];
949
- const filesByKey = /* @__PURE__ */ new Map();
950
- for (const r of made) {
951
- const pending = typeof r.id === "string" && r.id !== "" && typeof r.key?.value === "string" ? held.get(keyId(r.key)) : void 0;
952
- if (pending === void 0) continue;
953
- for (const key of pending.keys) held.delete(keyId(key));
954
- const { keys: _keys, files, ...rest } = pending;
955
- submissions.push({ ...rest, testCaseId: r.id });
956
- if (files !== void 0) filesByKey.set(pending.resultKey, files);
957
- }
958
- if (submissions.length > 0) {
959
- const before = stats.deferred;
960
- await send(submissions, filesByKey);
961
- createdWithResult += submissions.length;
962
- createdUndelivered += stats.deferred - before;
963
- }
964
- }
965
- }
966
917
  function skip(kind, name, why) {
967
918
  countsOf(kind).skipped += 1;
968
919
  if (why === "noStorage") noStorage += 1;
@@ -972,24 +923,25 @@ async function startRun(passed, declared2) {
972
923
  if (why === "noStorage") log(`plune: "${name}" not stored \u2014 ${SKIPPED[why]}.`);
973
924
  else log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
974
925
  }
926
+ const filesOf2 = (job) => `/v1/${job.owner ?? "results"}/${encodeURIComponent(job.id)}/files`;
975
927
  function ask(job, size) {
976
928
  requests += 1;
977
- return client.post(`/v1/results/${encodeURIComponent(job.id)}/files/uploads`, {
978
- 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 } : {} }]
979
931
  }, uploadRetries);
980
932
  }
981
933
  function failed(job, why) {
982
934
  countsOf(job.kind).failed += 1;
983
935
  if (!failedSaid.has(job.kind)) {
984
936
  failedSaid.add(job.kind);
985
- 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}.`);
986
938
  }
987
939
  }
988
940
  function failedToBucket(job, code) {
989
941
  countsOf(job.kind).failed += 1;
990
942
  if (codesSaid.has(code)) return;
991
943
  codesSaid.add(code);
992
- 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}.`);
993
945
  }
994
946
  function refusedHere(job, size) {
995
947
  if (job.kind === "screenshot") {
@@ -1017,7 +969,7 @@ async function startRun(passed, declared2) {
1017
969
  if (refusal !== void 0) return skip(kind, job.name, refusal);
1018
970
  requests += 1;
1019
971
  const out = await client.upload(
1020
- `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
972
+ `${filesOf2(job)}?name=${encodeURIComponent(job.name)}`,
1021
973
  bytes,
1022
974
  job.type
1023
975
  );
@@ -1039,8 +991,8 @@ async function startRun(passed, declared2) {
1039
991
  link = fresh;
1040
992
  }
1041
993
  requests += 1;
1042
- const done2 = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
1043
- 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));
1044
996
  countsOf(job.kind).uploaded += 1;
1045
997
  }
1046
998
  let free = uploadsAtOnce;
@@ -1367,6 +1319,295 @@ async function startRun(passed, declared2) {
1367
1319
  else await uploadBatched(jobs);
1368
1320
  uploadMs += Date.now() - started;
1369
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
+ }
1370
1611
  const sending = /* @__PURE__ */ new Set();
1371
1612
  let sendError;
1372
1613
  let answered = false;
@@ -1407,9 +1648,11 @@ async function startRun(passed, declared2) {
1407
1648
  for (const result of pending) {
1408
1649
  const match = matchFor(result);
1409
1650
  if (match.kind === "found") {
1410
- const { keys: _keys, files, ...rest } = result;
1651
+ const { keys: _keys, files: files2, ...rest } = result;
1411
1652
  submissions.push({ ...rest, testCaseId: match.testCaseId });
1412
- 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);
1413
1656
  } else if (match.kind === "unmatched") {
1414
1657
  stats.unresolved += 1;
1415
1658
  remember(result);
@@ -1432,7 +1675,7 @@ async function startRun(passed, declared2) {
1432
1675
  }
1433
1676
  const out = await client.post(
1434
1677
  `/v1/runs/${runId}/results`,
1435
- // 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.
1436
1679
  { results: part, ...configuration !== void 0 ? { configuration } : {} }
1437
1680
  );
1438
1681
  const counts = out.ok ? out.body?.counts : void 0;
@@ -1440,7 +1683,7 @@ async function startRun(passed, declared2) {
1440
1683
  if (told.length > 0) {
1441
1684
  for (const k of told) stats[k] += counts[k];
1442
1685
  progress();
1443
- await upload(out.ok ? out.body?.items : void 0, filesByKey);
1686
+ await files.upload(out.ok ? out.body?.items : void 0, filesByKey);
1444
1687
  answered = true;
1445
1688
  continue;
1446
1689
  }
@@ -1476,10 +1719,10 @@ async function startRun(passed, declared2) {
1476
1719
  }
1477
1720
  const kinds = [stats.screenshots, stats.textFiles, stats.otherFiles];
1478
1721
  const sum = (what) => kinds.reduce((n, counts) => n + counts[what], 0);
1479
- if (bucketSeen) {
1480
- const other = sum("skipped") - noStorage;
1722
+ if (files.bucketSeen) {
1723
+ const other = sum("skipped") - files.noStorage;
1481
1724
  parts.push(
1482
- `${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` : "")
1483
1726
  );
1484
1727
  } else {
1485
1728
  for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
@@ -1491,11 +1734,10 @@ async function startRun(passed, declared2) {
1491
1734
  }
1492
1735
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
1493
1736
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
1494
- const files = [stats.screenshots, stats.textFiles, stats.otherFiles];
1495
- const total = (what) => files.reduce((n, counts) => n + counts[what], 0);
1496
- 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) {
1497
1739
  log(
1498
- `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)`
1499
1741
  );
1500
1742
  }
1501
1743
  log(`plune: ${parts.join(" \xB7 ")}`);
@@ -1515,7 +1757,10 @@ async function startRun(passed, declared2) {
1515
1757
  return stats;
1516
1758
  },
1517
1759
  async add(result) {
1518
- 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) });
1519
1764
  if (buffer.length >= batchSize) await flushBuffer();
1520
1765
  },
1521
1766
  flush,
@@ -1524,6 +1769,7 @@ async function startRun(passed, declared2) {
1524
1769
  done = true;
1525
1770
  await flush();
1526
1771
  await offer();
1772
+ await syncSnapshots();
1527
1773
  let frozen;
1528
1774
  if (runId !== null && !offline) {
1529
1775
  const out = await client.post(`/v1/runs/${runId}/events`, {
@@ -1547,6 +1793,7 @@ async function startRun(passed, declared2) {
1547
1793
  done = true;
1548
1794
  await flush();
1549
1795
  await offer();
1796
+ await syncSnapshots();
1550
1797
  let frozen;
1551
1798
  const after = [];
1552
1799
  const shard = env.shard;
@@ -1678,7 +1925,7 @@ function attemptOf(test, result, ctx) {
1678
1925
  name,
1679
1926
  contentType,
1680
1927
  ...path3 !== void 0 ? { path: path3 } : {},
1681
- // 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.
1682
1929
  ...body !== void 0 ? { body } : {}
1683
1930
  })),
1684
1931
  ...ctx.buildHref !== void 0 ? { buildHref: ctx.buildHref } : {},
@@ -1705,13 +1952,15 @@ function pendingFrom(test, result, ctx, ids = {}) {
1705
1952
  // Anything the test named itself comes before what we derived from its location: a Qase or
1706
1953
  // TestRail id written by a fixture is a deliberate statement, and a file path is a guess.
1707
1954
  keys: [...metadata?.keys ?? [], ...keysFor(test)],
1708
- // 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.
1709
1956
  // The full `describe > title` path rather than `test.title` alone: two suites in one file
1710
1957
  // routinely share a title, and "adds an item" on its own is not something a person can judge.
1711
1958
  title: titlesOf(test).join(" \u203A "),
1712
1959
  // The line as well as the file. A reviewer's first move on an unknown test is to open it, and
1713
1960
  // `specRef` is the only thing the entry carries that can take them there.
1714
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 },
1715
1964
  source: SOURCE,
1716
1965
  // The runner's own word, untouched. Mapping it is the platform's job and a project's setting.
1717
1966
  rawStatus: result.status,
@@ -1785,7 +2034,7 @@ var PluneReporter = class {
1785
2034
  ...this.options.externalKey !== void 0 ? { externalKey: this.options.externalKey } : {},
1786
2035
  ...this.options.batchSize !== void 0 ? { batchSize: this.options.batchSize } : {},
1787
2036
  ...this.options.fallbackPath !== void 0 ? { fallbackPath: this.options.fallbackPath } : {},
1788
- // 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 —
1789
2038
  // which Playwright gives on GitLab and Jenkins, and the core reads from the job on GitHub.
1790
2039
  meta: { runner: SOURCE, ...ciUrl !== void 0 ? { ciUrl } : {}, ...ciCommit(ci) }
1791
2040
  },