@cevek/screentest 0.3.6 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -14663,13 +14663,26 @@ import { createServer } from "http";
14663
14663
  import { Router } from "express";
14664
14664
 
14665
14665
  // src/cloudflare.ts
14666
+ function storeKey(project, hash2) {
14667
+ return `${project}/${hash2}.png`;
14668
+ }
14669
+ function storePrefix(project) {
14670
+ return `${project}/`;
14671
+ }
14672
+ function hashFromKey(project, key) {
14673
+ const prefix = storePrefix(project);
14674
+ if (!key.startsWith(prefix)) return null;
14675
+ const rest = key.slice(prefix.length);
14676
+ const m = /^([a-f0-9]{64})\.png$/.exec(rest);
14677
+ return m ? m[1] : null;
14678
+ }
14666
14679
  async function uploadPng(cfg, hash2, body) {
14667
- const url2 = `${cfg.workerUrl}/${hash2}.png`;
14680
+ const key = storeKey(cfg.project, hash2);
14668
14681
  const res = await fetch(cfg.workerUrl, {
14669
14682
  method: "POST",
14670
14683
  headers: {
14671
14684
  "Content-Type": "image/png",
14672
- "X-File-Name": `${hash2}.png`,
14685
+ "X-File-Name": key,
14673
14686
  Authorization: `Bearer ${cfg.token}`
14674
14687
  },
14675
14688
  body: new Uint8Array(body)
@@ -14678,13 +14691,48 @@ async function uploadPng(cfg, hash2, body) {
14678
14691
  const text = await res.text().catch(() => "");
14679
14692
  throw new Error(`Cloudflare upload failed: ${res.status} ${res.statusText} ${text}`.trim());
14680
14693
  }
14681
- return url2;
14694
+ return `${cfg.workerUrl}/${key}`;
14695
+ }
14696
+ async function existsInStore(cfg, hash2) {
14697
+ const key = storeKey(cfg.project, hash2);
14698
+ const res = await fetch(`${cfg.workerUrl}/${key}`);
14699
+ if (res.body) await res.arrayBuffer().catch(() => void 0);
14700
+ if (res.ok) return true;
14701
+ if (res.status === 404) return false;
14702
+ throw new Error(`Cloudflare probe failed for ${key}: ${res.status} ${res.statusText}`);
14703
+ }
14704
+ async function listStore(cfg) {
14705
+ const out = [];
14706
+ let cursor = null;
14707
+ do {
14708
+ const url2 = new URL(cfg.workerUrl);
14709
+ url2.searchParams.set("list", "1");
14710
+ url2.searchParams.set("prefix", storePrefix(cfg.project));
14711
+ if (cursor) url2.searchParams.set("cursor", cursor);
14712
+ const res = await fetch(url2, { headers: { Authorization: `Bearer ${cfg.token}` } });
14713
+ if (!res.ok) {
14714
+ throw new Error(`Cloudflare list failed: ${res.status} ${res.statusText}`);
14715
+ }
14716
+ const page = await res.json();
14717
+ out.push(...page.keys);
14718
+ cursor = page.cursor;
14719
+ } while (cursor);
14720
+ return out;
14721
+ }
14722
+ async function deleteKey(cfg, key) {
14723
+ const res = await fetch(`${cfg.workerUrl}/${key}`, {
14724
+ method: "DELETE",
14725
+ headers: { Authorization: `Bearer ${cfg.token}` }
14726
+ });
14727
+ if (!res.ok) {
14728
+ throw new Error(`Cloudflare delete failed: ${res.status} ${res.statusText}`);
14729
+ }
14682
14730
  }
14683
- function expectedUrlFor(workerUrl, hash2) {
14684
- return `${workerUrl}/${hash2}.png`;
14731
+ function expectedUrlFor(cfg, hash2) {
14732
+ return `${cfg.workerUrl}/${storeKey(cfg.project, hash2)}`;
14685
14733
  }
14686
- function expectedUrlPattern(workerUrl) {
14687
- return `${workerUrl}/{hash}.png`;
14734
+ function expectedUrlPattern(cfg) {
14735
+ return `${cfg.workerUrl}/${storeKey(cfg.project, "{hash}")}`;
14688
14736
  }
14689
14737
 
14690
14738
  // src/version.ts
@@ -14713,8 +14761,8 @@ function docRoute(state) {
14713
14761
  r.get("/doc", (_req, res) => {
14714
14762
  res.json({
14715
14763
  doc: state.doc,
14716
- expectedUrlPattern: expectedUrlPattern(state.workerUrl),
14717
- workerUrl: state.workerUrl,
14764
+ expectedUrlPattern: expectedUrlPattern(state.store),
14765
+ workerUrl: state.store.workerUrl,
14718
14766
  serverVersion: SCREENTEST_VERSION
14719
14767
  });
14720
14768
  });
@@ -14937,7 +14985,7 @@ function acceptRoute(state) {
14937
14985
  }
14938
14986
  const buf = await fs2.readFile(entry.actualAbsPath);
14939
14987
  const hash2 = sha256Hex(buf);
14940
- await uploadPng({ workerUrl: state.workerUrl, token: state.token }, hash2, buf);
14988
+ await uploadPng(state.store, hash2, buf);
14941
14989
  await patchSnapshot({
14942
14990
  docDir: state.docDir,
14943
14991
  patchSnapshotJsonFile: entry.item.patchSnapshotJsonFile,
@@ -14946,7 +14994,7 @@ function acceptRoute(state) {
14946
14994
  });
14947
14995
  res.json({
14948
14996
  hash: hash2,
14949
- url: expectedUrlFor(state.workerUrl, hash2)
14997
+ url: expectedUrlFor(state.store, hash2)
14950
14998
  });
14951
14999
  } catch (err) {
14952
15000
  const msg = err instanceof Error ? err.message : String(err);
@@ -15014,7 +15062,7 @@ async function startServer(state, requestedPort) {
15014
15062
  if (webDist) {
15015
15063
  app.use(express.static(webDist));
15016
15064
  app.get("/{*splat}", (_req, res) => {
15017
- res.sendFile(join(webDist, "index.html"));
15065
+ res.sendFile("index.html", { root: webDist });
15018
15066
  });
15019
15067
  }
15020
15068
  const port = requestedPort === 0 ? await pickRandomFreePort() : await findFreePort(requestedPort);
@@ -15058,28 +15106,62 @@ function isFree(port) {
15058
15106
  });
15059
15107
  }
15060
15108
 
15061
- // src/ui.ts
15109
+ // src/project.ts
15110
+ import { readFileSync as readFileSync2 } from "fs";
15111
+ import { basename, join as join2 } from "path";
15112
+ function resolveProjectId(projectRoot) {
15113
+ const explicit = process.env.SCREENTEST_PROJECT?.trim();
15114
+ if (explicit) return sanitize(explicit);
15115
+ try {
15116
+ const pkg = JSON.parse(readFileSync2(join2(projectRoot, "package.json"), "utf8"));
15117
+ if (typeof pkg.name === "string" && pkg.name.trim()) return sanitize(pkg.name);
15118
+ } catch {
15119
+ }
15120
+ return sanitize(basename(projectRoot));
15121
+ }
15122
+ function sanitize(raw) {
15123
+ const out = raw.replace(/^@/, "").replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
15124
+ return out || "project";
15125
+ }
15126
+
15127
+ // src/store-args.ts
15062
15128
  var DEFAULT_WORKER_URL = "https://screentests.x-cevek.workers.dev";
15063
15129
  var DEFAULT_TOKEN = "SECRET_123";
15064
- function parseUIArgs(rawArgs) {
15065
- let docPath = null;
15066
- let port = Number(process.env.PORT) || 0;
15067
- let doOpen = true;
15130
+ function parseStoreArgs(rawArgs) {
15068
15131
  let workerUrl = process.env.CLOUDFLARE_WORKER_URL || DEFAULT_WORKER_URL;
15069
15132
  let token = process.env.CLOUDFLARE_TOKEN || DEFAULT_TOKEN;
15133
+ const rest = [];
15070
15134
  for (let i = 0; i < rawArgs.length; i++) {
15071
15135
  const a = rawArgs[i];
15072
- if (a === "--port") {
15073
- port = Number(rawArgs[++i]);
15074
- if (!Number.isFinite(port) || port <= 0) throw new Error("--port must be a number");
15075
- } else if (a === "--no-open") {
15076
- doOpen = false;
15077
- } else if (a === "--worker-url") {
15136
+ if (a === "--worker-url") {
15078
15137
  workerUrl = rawArgs[++i] ?? "";
15079
15138
  if (!workerUrl) throw new Error("--worker-url requires a value");
15080
15139
  } else if (a === "--token") {
15081
15140
  token = rawArgs[++i] ?? "";
15082
15141
  if (!token) throw new Error("--token requires a value");
15142
+ } else {
15143
+ rest.push(a);
15144
+ }
15145
+ }
15146
+ return { store: { workerUrl: workerUrl.replace(/\/+$/, ""), token }, rest };
15147
+ }
15148
+ function storeConfigFor(store, projectRoot) {
15149
+ return { ...store, project: resolveProjectId(projectRoot) };
15150
+ }
15151
+
15152
+ // src/ui.ts
15153
+ function parseUIArgs(rawArgs) {
15154
+ const { store, rest } = parseStoreArgs(rawArgs);
15155
+ let docPath = null;
15156
+ let port = Number(process.env.PORT) || 0;
15157
+ let doOpen = true;
15158
+ for (let i = 0; i < rest.length; i++) {
15159
+ const a = rest[i];
15160
+ if (a === "--port") {
15161
+ port = Number(rest[++i]);
15162
+ if (!Number.isFinite(port) || port <= 0) throw new Error("--port must be a number");
15163
+ } else if (a === "--no-open") {
15164
+ doOpen = false;
15083
15165
  } else if (a.startsWith("--")) {
15084
15166
  throw new Error(`Unknown flag: ${a}`);
15085
15167
  } else if (!docPath) {
@@ -15089,13 +15171,7 @@ function parseUIArgs(rawArgs) {
15089
15171
  }
15090
15172
  }
15091
15173
  if (!docPath) throw new Error("doc-json path is required");
15092
- return {
15093
- docPath,
15094
- port,
15095
- open: doOpen,
15096
- workerUrl: workerUrl.replace(/\/+$/, ""),
15097
- token
15098
- };
15174
+ return { docPath, port, open: doOpen, store };
15099
15175
  }
15100
15176
  async function runUI(opts) {
15101
15177
  const docAbs = isAbsolute(opts.docPath) ? opts.docPath : resolve5(process.cwd(), opts.docPath);
@@ -15141,8 +15217,9 @@ async function runUI(opts) {
15141
15217
  const state = {
15142
15218
  doc,
15143
15219
  docDir,
15144
- workerUrl: opts.workerUrl,
15145
- token: opts.token,
15220
+ // Pre-0.3 doc.json has no `project` block; the cwd is the best guess left,
15221
+ // and it is right whenever the UI is launched from the project.
15222
+ store: storeConfigFor(opts.store, doc.project?.path ?? process.cwd()),
15146
15223
  flat: flatResult.flat,
15147
15224
  actualWhitelist: flatResult.whitelist
15148
15225
  };
@@ -15168,9 +15245,8 @@ import { spawn } from "child_process";
15168
15245
 
15169
15246
  // src/doc-builder.ts
15170
15247
  import { spawnSync } from "child_process";
15171
- import { createHash as createHash2 } from "crypto";
15172
15248
  import { promises as fs4 } from "fs";
15173
- import { join as join2, relative, sep } from "path";
15249
+ import { join as join3, relative, sep } from "path";
15174
15250
  function detectBranch(projectRoot) {
15175
15251
  const r = spawnSync("git", ["-C", projectRoot, "rev-parse", "--abbrev-ref", "HEAD"], {
15176
15252
  stdio: "pipe",
@@ -15198,7 +15274,7 @@ function indexSnapshot(snap) {
15198
15274
  else out.set([...prefix, it.name].join("/"), it.hash);
15199
15275
  }
15200
15276
  };
15201
- for (const g of snap.groups) walk(g.items ?? [], [g.name]);
15277
+ for (const g of snap.groups ?? []) walk(g.items ?? [], [g.name]);
15202
15278
  return out;
15203
15279
  }
15204
15280
  async function walkActual(dir, prefix = []) {
@@ -15211,10 +15287,10 @@ async function walkActual(dir, prefix = []) {
15211
15287
  const out = [];
15212
15288
  for (const e of entries) {
15213
15289
  if (e.isDirectory()) {
15214
- out.push(...await walkActual(join2(dir, e.name), [...prefix, e.name]));
15290
+ out.push(...await walkActual(join3(dir, e.name), [...prefix, e.name]));
15215
15291
  } else if (e.isFile() && e.name.endsWith(".png")) {
15216
15292
  const stem = e.name.slice(0, -4);
15217
- out.push({ path: [...prefix, stem], absFile: join2(dir, e.name) });
15293
+ out.push({ path: [...prefix, stem], absFile: join3(dir, e.name) });
15218
15294
  }
15219
15295
  }
15220
15296
  return out;
@@ -15232,6 +15308,17 @@ function insertLeaf(doc, path, leaf) {
15232
15308
  }
15233
15309
  groups.push({ name: path[path.length - 1], ...leaf });
15234
15310
  }
15311
+ function countLeaves(doc) {
15312
+ let n = 0;
15313
+ const walk = (items) => {
15314
+ for (const it of items) {
15315
+ if ("items" in it) walk(it.items);
15316
+ else n++;
15317
+ }
15318
+ };
15319
+ for (const g of doc.groups) walk(g.items);
15320
+ return n;
15321
+ }
15235
15322
  async function generateDoc(projectRoot, snapshotFile, actualDir, docFile, cacheDir, opts = {}) {
15236
15323
  const detectDeletions = opts.detectDeletions ?? true;
15237
15324
  const snap = await readSnapshot(snapshotFile);
@@ -15243,10 +15330,9 @@ async function generateDoc(projectRoot, snapshotFile, actualDir, docFile, cacheD
15243
15330
  groups: []
15244
15331
  };
15245
15332
  const summary = { new: 0, change: 0, deleted: 0, unchanged: 0 };
15246
- const leaves = [];
15247
15333
  for (const a of actuals) {
15248
15334
  const buf = await fs4.readFile(a.absFile);
15249
- const hash2 = createHash2("sha256").update(buf).digest("hex");
15335
+ const hash2 = sha256Hex(buf);
15250
15336
  const key = a.path.join("/");
15251
15337
  seen.add(key);
15252
15338
  const expHash = expectedByPath.get(key);
@@ -15257,7 +15343,6 @@ async function generateDoc(projectRoot, snapshotFile, actualDir, docFile, cacheD
15257
15343
  actualFilename: relPath,
15258
15344
  patchSnapshotJsonFile: snapshotFile
15259
15345
  });
15260
- leaves.push({ path: a.path, type: "new", absFile: a.absFile });
15261
15346
  summary.new++;
15262
15347
  continue;
15263
15348
  }
@@ -15271,7 +15356,6 @@ async function generateDoc(projectRoot, snapshotFile, actualDir, docFile, cacheD
15271
15356
  actualFilename: relPath,
15272
15357
  patchSnapshotJsonFile: snapshotFile
15273
15358
  });
15274
- leaves.push({ path: a.path, type: "change", absFile: a.absFile });
15275
15359
  summary.change++;
15276
15360
  }
15277
15361
  if (detectDeletions) {
@@ -15282,44 +15366,42 @@ async function generateDoc(projectRoot, snapshotFile, actualDir, docFile, cacheD
15282
15366
  expectedHash: hash2,
15283
15367
  patchSnapshotJsonFile: snapshotFile
15284
15368
  });
15285
- leaves.push({ path: key.split("/"), type: "deleted" });
15286
15369
  summary.deleted++;
15287
15370
  }
15288
15371
  }
15289
15372
  await fs4.mkdir(cacheDir, { recursive: true });
15290
15373
  await fs4.writeFile(docFile, JSON.stringify(doc, null, 2));
15291
- const total = leaves.length;
15374
+ const total = countLeaves(doc);
15292
15375
  const deletedSummary = detectDeletions ? `deleted: ${summary.deleted}, ` : "";
15293
15376
  process.stdout.write(
15294
15377
  `Wrote ${docFile}
15295
15378
  ${total} diff${total === 1 ? "" : "s"} to review (new: ${summary.new}, change: ${summary.change}, ${deletedSummary}unchanged: ${summary.unchanged}${detectDeletions ? "" : "; deletion detection disabled \u2014 subset run"})
15296
15379
  `
15297
15380
  );
15298
- return { total, leaves };
15381
+ return total;
15299
15382
  }
15300
15383
 
15301
15384
  // src/runner/paths.ts
15302
15385
  import { existsSync as existsSync2 } from "fs";
15303
- import { isAbsolute as isAbsolute2, join as join3, resolve as resolve6 } from "path";
15386
+ import { isAbsolute as isAbsolute2, join as join4, resolve as resolve6 } from "path";
15304
15387
  function resolveRunnerPaths(cwd = process.cwd()) {
15305
15388
  const projectRoot = resolve6(cwd);
15306
- const cacheDir = join3(projectRoot, "node_modules", ".cache", "screentest");
15389
+ const cacheDir = join4(projectRoot, "node_modules", ".cache", "screentest");
15307
15390
  return {
15308
15391
  projectRoot,
15309
15392
  snapshotFile: resolveSnapshotFile(projectRoot),
15310
15393
  cacheDir,
15311
- actualDir: join3(cacheDir, "actual"),
15312
- docFile: join3(cacheDir, "doc.json"),
15313
- softReportFile: join3(cacheDir, "soft-report.json")
15394
+ actualDir: join4(cacheDir, "actual"),
15395
+ docFile: join4(cacheDir, "doc.json")
15314
15396
  };
15315
15397
  }
15316
15398
  function resolveSnapshotFile(projectRoot) {
15317
15399
  const envPath = process.env.SCREENTEST_SNAPSHOT_FILE;
15318
15400
  if (envPath) {
15319
- return isAbsolute2(envPath) ? envPath : join3(projectRoot, envPath);
15401
+ return isAbsolute2(envPath) ? envPath : join4(projectRoot, envPath);
15320
15402
  }
15321
- const legacyRoot = join3(projectRoot, "snapshot.json");
15322
- const insideTests = join3(projectRoot, "tests", "snapshot.json");
15403
+ const legacyRoot = join4(projectRoot, "snapshot.json");
15404
+ const insideTests = join4(projectRoot, "tests", "snapshot.json");
15323
15405
  if (existsSync2(legacyRoot) && !existsSync2(insideTests)) return legacyRoot;
15324
15406
  return insideTests;
15325
15407
  }
@@ -15333,7 +15415,7 @@ function run(cmd, argv) {
15333
15415
  }
15334
15416
  async function runReview() {
15335
15417
  const paths = resolveRunnerPaths();
15336
- const { total } = await generateDoc(
15418
+ const total = await generateDoc(
15337
15419
  paths.projectRoot,
15338
15420
  paths.snapshotFile,
15339
15421
  paths.actualDir,
@@ -15350,7 +15432,7 @@ async function runReview() {
15350
15432
  // src/init.ts
15351
15433
  import { copyFile, mkdir } from "fs/promises";
15352
15434
  import { existsSync as existsSync3 } from "fs";
15353
- import { dirname as dirname5, join as join4, resolve as resolve7 } from "path";
15435
+ import { dirname as dirname5, join as join5, resolve as resolve7 } from "path";
15354
15436
  import { fileURLToPath as fileURLToPath3 } from "url";
15355
15437
  async function runInit() {
15356
15438
  const here = dirname5(fileURLToPath3(import.meta.url));
@@ -15361,8 +15443,8 @@ async function runInit() {
15361
15443
  { from: "example.test.ts", to: "tests/example.test.ts" }
15362
15444
  ];
15363
15445
  for (const { from, to } of targets) {
15364
- const src = join4(templatesDir, from);
15365
- const dst = join4(cwd, to);
15446
+ const src = join5(templatesDir, from);
15447
+ const dst = join5(cwd, to);
15366
15448
  if (existsSync3(dst)) {
15367
15449
  process.stdout.write(` exists ${to}
15368
15450
  `);
@@ -15571,6 +15653,282 @@ async function printStatus() {
15571
15653
  return 0;
15572
15654
  }
15573
15655
 
15656
+ // src/repair.ts
15657
+ import { promises as fs5 } from "fs";
15658
+
15659
+ // src/concurrency.ts
15660
+ async function mapLimit(items, limit, fn) {
15661
+ const out = new Array(items.length);
15662
+ let next = 0;
15663
+ await Promise.all(
15664
+ Array.from({ length: Math.min(limit, items.length) }, async () => {
15665
+ for (; ; ) {
15666
+ const i = next++;
15667
+ if (i >= items.length) return;
15668
+ out[i] = await fn(items[i]);
15669
+ }
15670
+ })
15671
+ );
15672
+ return out;
15673
+ }
15674
+
15675
+ // src/repair.ts
15676
+ var PROBE_CONCURRENCY = 8;
15677
+ function parseRepairArgs(rawArgs) {
15678
+ const { store, rest } = parseStoreArgs(rawArgs);
15679
+ let dryRun = false;
15680
+ for (const a of rest) {
15681
+ if (a === "--dry-run") dryRun = true;
15682
+ else throw new Error(`Unknown argument: ${a}`);
15683
+ }
15684
+ return { store, dryRun };
15685
+ }
15686
+ async function indexActualsByHash(actualDir) {
15687
+ const files = await walkActual(actualDir);
15688
+ const byHash = /* @__PURE__ */ new Map();
15689
+ for (const f of files) {
15690
+ const buf = await fs5.readFile(f.absFile);
15691
+ const hash2 = sha256Hex(buf);
15692
+ if (!byHash.has(hash2)) byHash.set(hash2, f.absFile);
15693
+ }
15694
+ return byHash;
15695
+ }
15696
+ async function runRepair(opts) {
15697
+ const paths = resolveRunnerPaths();
15698
+ const snapshot = await readSnapshot(paths.snapshotFile);
15699
+ const entries = [...indexSnapshot(snapshot)].filter(
15700
+ (e) => typeof e[1] === "string"
15701
+ );
15702
+ if (entries.length === 0) {
15703
+ process.stdout.write(`No hashes in ${paths.snapshotFile}
15704
+ `);
15705
+ return 0;
15706
+ }
15707
+ const cfg = storeConfigFor(opts.store, paths.projectRoot);
15708
+ const byHash = await indexActualsByHash(paths.actualDir);
15709
+ const hashes = [...new Set(entries.map(([, hash2]) => hash2))];
15710
+ process.stdout.write(
15711
+ `${paths.snapshotFile}: ${entries.length} entries, ${hashes.length} unique hashes
15712
+ Local actuals: ${byHash.size} unique hashes
15713
+ Probing ${cfg.workerUrl}/${cfg.project}/ \u2026
15714
+ `
15715
+ );
15716
+ const present = await mapLimit(hashes, PROBE_CONCURRENCY, (h) => existsInStore(cfg, h));
15717
+ const missing = hashes.filter((_, i) => !present[i]);
15718
+ if (missing.length === 0) {
15719
+ process.stdout.write(`All ${hashes.length} blobs present. Nothing to repair.
15720
+ `);
15721
+ return 0;
15722
+ }
15723
+ const recoverable = missing.filter((h) => byHash.has(h));
15724
+ const lost = missing.filter((h) => !byHash.has(h));
15725
+ process.stdout.write(
15726
+ `Missing: ${missing.length} (recoverable ${recoverable.length}, lost ${lost.length})
15727
+ `
15728
+ );
15729
+ if (lost.length > 0) {
15730
+ const nameOf = /* @__PURE__ */ new Map();
15731
+ for (const [name, hash2] of entries) if (!nameOf.has(hash2)) nameOf.set(hash2, name);
15732
+ process.stdout.write(`
15733
+ Gone from the store and not in the local cache:
15734
+ `);
15735
+ for (const h of lost) process.stdout.write(` ${h.slice(0, 12)}\u2026 ${nameOf.get(h) ?? "?"}
15736
+ `);
15737
+ process.stdout.write(
15738
+ `
15739
+ Re-run the tests, then accept these in the review UI \u2014 their baseline
15740
+ content no longer exists anywhere.
15741
+
15742
+ `
15743
+ );
15744
+ }
15745
+ if (opts.dryRun) {
15746
+ process.stdout.write(
15747
+ `Dry run \u2014 would upload ${recoverable.length}. Re-run without --dry-run.
15748
+ `
15749
+ );
15750
+ return lost.length > 0 ? 1 : 0;
15751
+ }
15752
+ let uploaded = 0;
15753
+ const failed = [];
15754
+ await mapLimit(recoverable, PROBE_CONCURRENCY, async (hash2) => {
15755
+ try {
15756
+ const buf = await fs5.readFile(byHash.get(hash2));
15757
+ if (sha256Hex(buf) !== hash2) {
15758
+ failed.push(`${hash2.slice(0, 12)}\u2026: local file changed since scan, skipped`);
15759
+ return;
15760
+ }
15761
+ await uploadPng(cfg, hash2, buf);
15762
+ uploaded++;
15763
+ } catch (err) {
15764
+ failed.push(`${hash2.slice(0, 12)}\u2026: ${err instanceof Error ? err.message : String(err)}`);
15765
+ }
15766
+ });
15767
+ process.stdout.write(`Uploaded ${uploaded}, failed ${failed.length}
15768
+ `);
15769
+ for (const f of failed) process.stdout.write(` ${f}
15770
+ `);
15771
+ return failed.length > 0 || lost.length > 0 ? 1 : 0;
15772
+ }
15773
+
15774
+ // src/gc.ts
15775
+ import { promises as fs6 } from "fs";
15776
+ import { isAbsolute as isAbsolute3, join as join6, relative as relative2, resolve as resolve9 } from "path";
15777
+ var DELETE_CONCURRENCY = 8;
15778
+ function parseGcArgs(rawArgs) {
15779
+ const { store, rest } = parseStoreArgs(rawArgs);
15780
+ const snapshotFiles = [];
15781
+ let confirmed = false;
15782
+ for (let i = 0; i < rest.length; i++) {
15783
+ const a = rest[i];
15784
+ if (a === "--snapshot") {
15785
+ const v = rest[++i];
15786
+ if (!v) throw new Error("--snapshot requires a path");
15787
+ snapshotFiles.push(v);
15788
+ } else if (a === "--yes") {
15789
+ confirmed = true;
15790
+ } else if (a === "--dry-run") {
15791
+ confirmed = false;
15792
+ } else {
15793
+ throw new Error(`Unknown argument: ${a}`);
15794
+ }
15795
+ }
15796
+ return { store, snapshotFiles, confirmed };
15797
+ }
15798
+ async function discoverSnapshotFiles(projectRoot, configured, extra) {
15799
+ const required2 = extra.map((p) => isAbsolute3(p) ? p : resolve9(projectRoot, p));
15800
+ for (const f of required2) {
15801
+ try {
15802
+ await fs6.access(f);
15803
+ } catch {
15804
+ throw new Error(`Snapshot file not found: ${f}`);
15805
+ }
15806
+ }
15807
+ const found = /* @__PURE__ */ new Set([...required2, configured]);
15808
+ for (const dir of [projectRoot, join6(projectRoot, "tests")]) {
15809
+ let entries;
15810
+ try {
15811
+ entries = await fs6.readdir(dir, { withFileTypes: true });
15812
+ } catch {
15813
+ continue;
15814
+ }
15815
+ for (const e of entries) {
15816
+ if (e.isFile() && /^snapshot.*\.json$/.test(e.name)) found.add(join6(dir, e.name));
15817
+ }
15818
+ }
15819
+ const existing = [];
15820
+ for (const f of found) {
15821
+ try {
15822
+ await fs6.access(f);
15823
+ existing.push(f);
15824
+ } catch {
15825
+ }
15826
+ }
15827
+ return existing.sort();
15828
+ }
15829
+ async function readSnapshotStrict(file2) {
15830
+ const raw = await fs6.readFile(file2, "utf8");
15831
+ let parsed;
15832
+ try {
15833
+ parsed = JSON.parse(raw);
15834
+ } catch (err) {
15835
+ throw new Error(
15836
+ `${file2} is not valid JSON (${err instanceof Error ? err.message : String(err)}). Refusing to run \u2014 a file that fails to parse would look like an empty baseline.`
15837
+ );
15838
+ }
15839
+ const result = snapshotDocSchema.safeParse(parsed);
15840
+ if (!result.success) {
15841
+ throw new Error(
15842
+ `${file2} is not a snapshot document: ${result.error.issues.map((i) => `${i.path.join(".")} ${i.message}`).join("; ")}`
15843
+ );
15844
+ }
15845
+ return result.data;
15846
+ }
15847
+ async function runGc(opts) {
15848
+ const paths = resolveRunnerPaths();
15849
+ const cfg = storeConfigFor(opts.store, paths.projectRoot);
15850
+ const snapshotFiles = await discoverSnapshotFiles(
15851
+ paths.projectRoot,
15852
+ paths.snapshotFile,
15853
+ opts.snapshotFiles
15854
+ );
15855
+ if (snapshotFiles.length === 0) {
15856
+ process.stderr.write(
15857
+ `No snapshot files found under ${paths.projectRoot}.
15858
+ Refusing to run: with nothing to compare against, every blob would look
15859
+ unreferenced. Pass --snapshot <path> if they live elsewhere.
15860
+ `
15861
+ );
15862
+ return 1;
15863
+ }
15864
+ const live = /* @__PURE__ */ new Set();
15865
+ process.stdout.write(`Live hashes from:
15866
+ `);
15867
+ for (const file2 of snapshotFiles) {
15868
+ const before = live.size;
15869
+ for (const hash2 of indexSnapshot(await readSnapshotStrict(file2)).values()) {
15870
+ if (typeof hash2 === "string") live.add(hash2);
15871
+ }
15872
+ process.stdout.write(` ${relative2(paths.projectRoot, file2)} (+${live.size - before} new)
15873
+ `);
15874
+ }
15875
+ if (live.size === 0) {
15876
+ process.stderr.write(
15877
+ `
15878
+ Every snapshot file parsed, and not one hash among them.
15879
+ Refusing to delete: an empty baseline set makes the whole store look
15880
+ unreferenced. Accept something first, or narrow with --snapshot.
15881
+ `
15882
+ );
15883
+ return 1;
15884
+ }
15885
+ process.stdout.write(`
15886
+ ${live.size} live hashes. Listing ${cfg.workerUrl}/${cfg.project}/ \u2026
15887
+ `);
15888
+ const objects = await listStore(cfg);
15889
+ const unrecognized = [];
15890
+ const garbage = objects.filter((o) => {
15891
+ const hash2 = hashFromKey(cfg.project, o.key);
15892
+ if (hash2 === null) {
15893
+ unrecognized.push(o.key);
15894
+ return false;
15895
+ }
15896
+ return !live.has(hash2);
15897
+ });
15898
+ const bytes = garbage.reduce((n, o) => n + o.size, 0);
15899
+ process.stdout.write(
15900
+ `Stored: ${objects.length} objects. Unreferenced: ${garbage.length} (${(bytes / 1048576).toFixed(1)} MB)
15901
+ `
15902
+ );
15903
+ if (unrecognized.length > 0) {
15904
+ process.stdout.write(
15905
+ `Left alone \u2014 ${unrecognized.length} object(s) under the prefix that are not blob keys:
15906
+ ` + unrecognized.slice(0, 10).map((k) => ` ${k}
15907
+ `).join("")
15908
+ );
15909
+ }
15910
+ if (garbage.length === 0) return 0;
15911
+ if (!opts.confirmed) {
15912
+ process.stdout.write(`
15913
+ Dry run \u2014 nothing deleted. Re-run with --yes to delete.
15914
+ `);
15915
+ return 0;
15916
+ }
15917
+ const failed = [];
15918
+ await mapLimit(garbage, DELETE_CONCURRENCY, async (o) => {
15919
+ try {
15920
+ await deleteKey(cfg, o.key);
15921
+ } catch (err) {
15922
+ failed.push(`${o.key}: ${err instanceof Error ? err.message : String(err)}`);
15923
+ }
15924
+ });
15925
+ process.stdout.write(`Deleted ${garbage.length - failed.length}, failed ${failed.length}
15926
+ `);
15927
+ for (const f of failed) process.stdout.write(` ${f}
15928
+ `);
15929
+ return failed.length > 0 ? 1 : 0;
15930
+ }
15931
+
15574
15932
  // src/index.ts
15575
15933
  function printHelp() {
15576
15934
  process.stderr.write(
@@ -15589,6 +15947,16 @@ function printHelp() {
15589
15947
  " screentest review regenerate doc.json from cached actuals + open UI",
15590
15948
  " (useful when you closed the UI without accepting)",
15591
15949
  "",
15950
+ " screentest repair [--dry-run] [--worker-url URL] [--token TOKEN]",
15951
+ " re-upload snapshot.json hashes whose blob is",
15952
+ " missing from the store, using the cached actual",
15953
+ " with the same content hash. Exits 1 if some are",
15954
+ " gone from both \u2014 those need a re-run + accept",
15955
+ "",
15956
+ " screentest gc [--yes] [--snapshot PATH]\u2026",
15957
+ " delete blobs under this project that no snapshot",
15958
+ " file references any more. Reports only until --yes",
15959
+ "",
15592
15960
  " screentest init scaffold vitest.screentest.config.ts and",
15593
15961
  " tests/example.test.ts into the current project",
15594
15962
  "",
@@ -15607,10 +15975,6 @@ function printHelp() {
15607
15975
  " APP_URL default http://localhost:5050",
15608
15976
  " CI if set, do not auto-open the review UI on failure",
15609
15977
  " SCREENTEST_NO_UI if set, never auto-open the review UI",
15610
- " SCREENTEST_SOFT snapshot diffs (new/changed) warn instead of failing",
15611
- " the run; a machine-readable soft-report.json is written",
15612
- " to node_modules/.cache/screentest/. Off for empty, 0",
15613
- " and false; on for any other value",
15614
15978
  " SCREENTEST_FIREFOX_WS override the daemon WS endpoint",
15615
15979
  " SCREENTEST_SNAPSHOT_FILE override snapshot.json path (default tests/snapshot.json)",
15616
15980
  ""
@@ -15655,6 +16019,16 @@ Or add it as a script in package.json:
15655
16019
  process.exit(await printStatus());
15656
16020
  return;
15657
16021
  }
16022
+ if (cmd === "repair") {
16023
+ const code = await runRepair(parseRepairArgs(argv.slice(1)));
16024
+ process.exit(code);
16025
+ return;
16026
+ }
16027
+ if (cmd === "gc") {
16028
+ const code = await runGc(parseGcArgs(argv.slice(1)));
16029
+ process.exit(code);
16030
+ return;
16031
+ }
15658
16032
  if (cmd === "init") {
15659
16033
  const code = await runInit();
15660
16034
  process.exit(code);