paseo-plugin-genui 0.0.0-stage → 0.1.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.
Files changed (375) hide show
  1. package/LICENSE +202 -0
  2. package/OVERVIEW.md +21 -0
  3. package/README.md +77 -2
  4. package/assets/fonts/Excalifont-OFL.txt +109 -0
  5. package/assets/fonts/Excalifont-Regular-latin.woff2 +0 -0
  6. package/assets/icon.png +0 -0
  7. package/assets/icon.svg +1 -0
  8. package/assets/screenshot-chat.png +0 -0
  9. package/assets/screenshot-gallery.png +0 -0
  10. package/assets/screenshot-playground.png +0 -0
  11. package/client/components/content.tsx +468 -0
  12. package/client/components/data.tsx +967 -0
  13. package/client/components/dev.tsx +998 -0
  14. package/client/components/diagram.tsx +513 -0
  15. package/client/components/inputs.tsx +994 -0
  16. package/client/components/layout.tsx +239 -0
  17. package/client/components/media.tsx +428 -0
  18. package/client/components/project.tsx +641 -0
  19. package/client/components/widgets.tsx +836 -0
  20. package/client/gallery.tsx +449 -0
  21. package/client/live-ui.tsx +525 -0
  22. package/client/loaders.ts +342 -0
  23. package/client/markdown.tsx +172 -0
  24. package/client/node-renderer.tsx +149 -0
  25. package/client/render.tsx +186 -0
  26. package/client/runtime.ts +103 -0
  27. package/client/settings.tsx +57 -0
  28. package/client/web.ts +186 -0
  29. package/gallery/Acceptance-baseline.ui +1 -0
  30. package/gallery/Acceptance-checklist.ui +14 -0
  31. package/gallery/Acceptance-evidence.ui +9 -0
  32. package/gallery/Acceptance.ui +1 -0
  33. package/gallery/Badge.ui +3 -0
  34. package/gallery/Benchmark-context.ui +8 -0
  35. package/gallery/Benchmark-hyperfine.ui +1 -0
  36. package/gallery/Benchmark-runs-list.ui +9 -0
  37. package/gallery/Benchmark-runs.ui +1 -0
  38. package/gallery/Benchmark-vitest.ui +1 -0
  39. package/gallery/Benchmark.ui +9 -0
  40. package/gallery/Board-bb-tasks.ui +1 -0
  41. package/gallery/Board-gh-issues.ui +1 -0
  42. package/gallery/Board-gh-prs.ui +1 -0
  43. package/gallery/Board.ui +12 -0
  44. package/gallery/Button-destructive.ui +4 -0
  45. package/gallery/Button.ui +5 -0
  46. package/gallery/Calendar.ui +15 -0
  47. package/gallery/CalendarHeatmap-short.ui +11 -0
  48. package/gallery/CalendarHeatmap.ui +4 -0
  49. package/gallery/Callout.ui +4 -0
  50. package/gallery/Card.ui +4 -0
  51. package/gallery/Carousel.ui +8 -0
  52. package/gallery/Changes-paths.ui +1 -0
  53. package/gallery/Changes-uncommitted.ui +1 -0
  54. package/gallery/Changes.ui +1 -0
  55. package/gallery/Chart-area.ui +3 -0
  56. package/gallery/Chart-funnel.ui +3 -0
  57. package/gallery/Chart-heatmap.ui +11 -0
  58. package/gallery/Chart-pie.ui +3 -0
  59. package/gallery/Chart-radar.ui +3 -0
  60. package/gallery/Chart-scatter.ui +4 -0
  61. package/gallery/Chart-stacked.ui +5 -0
  62. package/gallery/Chart.ui +3 -0
  63. package/gallery/Checklist.ui +6 -0
  64. package/gallery/Choice.ui +8 -0
  65. package/gallery/Code.ui +3 -0
  66. package/gallery/Commits-limit.ui +1 -0
  67. package/gallery/Commits.ui +1 -0
  68. package/gallery/Compare-conditions.ui +4 -0
  69. package/gallery/Compare-three.ui +7 -0
  70. package/gallery/Compare.ui +4 -0
  71. package/gallery/Coverage-go.ui +1 -0
  72. package/gallery/Coverage-lcov.ui +1 -0
  73. package/gallery/Coverage-python.ui +1 -0
  74. package/gallery/Coverage.ui +1 -0
  75. package/gallery/DateInput.ui +5 -0
  76. package/gallery/Decision-percent.ui +10 -0
  77. package/gallery/Decision.ui +12 -0
  78. package/gallery/Dependencies-audit.ui +1 -0
  79. package/gallery/Dependencies-both.ui +1 -0
  80. package/gallery/Dependencies-list.ui +7 -0
  81. package/gallery/Dependencies-pip.ui +1 -0
  82. package/gallery/Dependencies-pnpm.ui +1 -0
  83. package/gallery/Dependencies.ui +1 -0
  84. package/gallery/Details.ui +4 -0
  85. package/gallery/Diagram-flow.ui +16 -0
  86. package/gallery/Diagram-sequence.ui +15 -0
  87. package/gallery/Diagram.ui +16 -0
  88. package/gallery/Diff.ui +3 -0
  89. package/gallery/Divider.ui +5 -0
  90. package/gallery/EditableTable.ui +9 -0
  91. package/gallery/Entity-list.ui +6 -0
  92. package/gallery/Entity.ui +8 -0
  93. package/gallery/Environments.ui +1 -0
  94. package/gallery/Estimate-points.ui +6 -0
  95. package/gallery/Estimate.ui +8 -0
  96. package/gallery/File.ui +4 -0
  97. package/gallery/Findings-biome.ui +1 -0
  98. package/gallery/Findings-eslint.ui +1 -0
  99. package/gallery/Findings-oxlint.ui +1 -0
  100. package/gallery/Findings-review.ui +1 -0
  101. package/gallery/Findings-ruff.ui +1 -0
  102. package/gallery/Findings-sarif.ui +1 -0
  103. package/gallery/Findings-ship.ui +11 -0
  104. package/gallery/Findings-tsc.ui +1 -0
  105. package/gallery/Findings.ui +7 -0
  106. package/gallery/Flashcards.ui +3 -0
  107. package/gallery/FollowUps.ui +4 -0
  108. package/gallery/Form.ui +8 -0
  109. package/gallery/Gallery-links.ui +8 -0
  110. package/gallery/Gallery-strip.ui +14 -0
  111. package/gallery/Gallery.ui +10 -0
  112. package/gallery/Gauge.ui +7 -0
  113. package/gallery/Grid.ui +8 -0
  114. package/gallery/Hotspots-photo.ui +8 -0
  115. package/gallery/Hotspots.ui +11 -0
  116. package/gallery/Icon.ui +5 -0
  117. package/gallery/Image.ui +4 -0
  118. package/gallery/ImageSearch-aspects.ui +6 -0
  119. package/gallery/ImageSearch.ui +4 -0
  120. package/gallery/Input.ui +5 -0
  121. package/gallery/Json-api.ui +1 -0
  122. package/gallery/Json.ui +8 -0
  123. package/gallery/KeyValue.ui +3 -0
  124. package/gallery/List-dots.ui +8 -0
  125. package/gallery/List.ui +8 -0
  126. package/gallery/ListEditor.ui +5 -0
  127. package/gallery/Logs-jsonl.ui +1 -0
  128. package/gallery/Logs-lines.ui +11 -0
  129. package/gallery/Logs-python.ui +1 -0
  130. package/gallery/Logs.ui +1 -0
  131. package/gallery/Map-city.ui +8 -0
  132. package/gallery/Map.ui +8 -0
  133. package/gallery/Metric.ui +3 -0
  134. package/gallery/OptionCards-multi.ui +10 -0
  135. package/gallery/OptionCards.ui +10 -0
  136. package/gallery/Pipeline-checks.ui +1 -0
  137. package/gallery/Pipeline-passed.ui +1 -0
  138. package/gallery/Pipeline-running.ui +1 -0
  139. package/gallery/Pipeline-stages.ui +13 -0
  140. package/gallery/Pipeline.ui +1 -0
  141. package/gallery/Plan.ui +9 -0
  142. package/gallery/Progress.ui +4 -0
  143. package/gallery/Provenance-deploy.ui +6 -0
  144. package/gallery/Provenance-no-receipt.ui +1 -0
  145. package/gallery/Provenance.ui +1 -0
  146. package/gallery/PullRequest.ui +1 -0
  147. package/gallery/Quiz.ui +6 -0
  148. package/gallery/Radio.ui +5 -0
  149. package/gallery/Rating.ui +5 -0
  150. package/gallery/Roadmap-sprint.ui +8 -0
  151. package/gallery/Roadmap-year.ui +9 -0
  152. package/gallery/Roadmap.ui +12 -0
  153. package/gallery/Row.ui +3 -0
  154. package/gallery/SegmentedBar-status.ui +8 -0
  155. package/gallery/SegmentedBar.ui +8 -0
  156. package/gallery/Select.ui +5 -0
  157. package/gallery/Slider.ui +7 -0
  158. package/gallery/Snippet.ui +3 -0
  159. package/gallery/Sources-chips.ui +4 -0
  160. package/gallery/Sources.ui +8 -0
  161. package/gallery/Sparkline.ui +6 -0
  162. package/gallery/Stack.ui +7 -0
  163. package/gallery/StackTrace-aggregate.ui +1 -0
  164. package/gallery/StackTrace-browser.ui +1 -0
  165. package/gallery/StackTrace-go.ui +1 -0
  166. package/gallery/StackTrace-java.ui +1 -0
  167. package/gallery/StackTrace-python.ui +1 -0
  168. package/gallery/StackTrace-rust.ui +1 -0
  169. package/gallery/StackTrace.ui +1 -0
  170. package/gallery/Status.ui +9 -0
  171. package/gallery/Stepper.ui +5 -0
  172. package/gallery/Steps.ui +8 -0
  173. package/gallery/Swatches-long-names.ui +4 -0
  174. package/gallery/Swatches-picker.ui +5 -0
  175. package/gallery/Swatches.ui +10 -0
  176. package/gallery/Table.ui +7 -0
  177. package/gallery/Tabs.ui +8 -0
  178. package/gallery/Tests-junit.ui +1 -0
  179. package/gallery/Tests-vitest-junit.ui +1 -0
  180. package/gallery/Tests-vitest.ui +1 -0
  181. package/gallery/Tests.ui +9 -0
  182. package/gallery/Text.ui +4 -0
  183. package/gallery/TextArea.ui +5 -0
  184. package/gallery/Threads-ids.ui +1 -0
  185. package/gallery/Threads.ui +1 -0
  186. package/gallery/Timeline.ui +8 -0
  187. package/gallery/Timer.ui +4 -0
  188. package/gallery/Toggle.ui +5 -0
  189. package/gallery/Transcript-text.ui +1 -0
  190. package/gallery/Transcript-untimed.ui +1 -0
  191. package/gallery/Transcript-whisper.ui +1 -0
  192. package/gallery/Transcript.ui +1 -0
  193. package/gallery/Tree.ui +3 -0
  194. package/gallery/Treemap-du.ui +1 -0
  195. package/gallery/Treemap-esbuild.ui +1 -0
  196. package/gallery/Treemap-tree.ui +7 -0
  197. package/gallery/Treemap.ui +18 -0
  198. package/gallery/Walkthrough.ui +9 -0
  199. package/gallery/Waterfall-har.ui +1 -0
  200. package/gallery/Waterfall-trace.ui +1 -0
  201. package/gallery/Waterfall.ui +11 -0
  202. package/gallery/data/acceptance/coil/viewport-lifecycle.json +25 -0
  203. package/gallery/data/acceptance/coil-gate.json +153 -0
  204. package/gallery/data/acceptance/orbit-baseline.json +163 -0
  205. package/gallery/data/acceptance/shots/gate-cell-opened.png +0 -0
  206. package/gallery/data/acceptance/shots/gate-light.png +0 -0
  207. package/gallery/data/acceptance/shots/gate-phone-dark.png +0 -0
  208. package/gallery/data/activity.json +1 -0
  209. package/gallery/data/bb-tasks-orb.json +420 -0
  210. package/gallery/data/biome.json +229 -0
  211. package/gallery/data/compare/status-after.png +0 -0
  212. package/gallery/data/compare/status-before.png +0 -0
  213. package/gallery/data/compare/status-dark-2x.png +0 -0
  214. package/gallery/data/compare/status-rerender.png +0 -0
  215. package/gallery/data/coverage-py.json +1 -0
  216. package/gallery/data/coverage-summary.json +1 -0
  217. package/gallery/data/coverage.out +23 -0
  218. package/gallery/data/deploys.json +1 -0
  219. package/gallery/data/device-runs.json +285 -0
  220. package/gallery/data/du-node-modules.txt +359 -0
  221. package/gallery/data/esbuild-meta.json +292 -0
  222. package/gallery/data/eslint.json +266 -0
  223. package/gallery/data/eslint.sarif +343 -0
  224. package/gallery/data/findings-review.json +76 -0
  225. package/gallery/data/gh-issues-nextjs.json +293 -0
  226. package/gallery/data/gh-pr-checks.json +272 -0
  227. package/gallery/data/gh-prs-nextjs.json +419 -0
  228. package/gallery/data/gh-run-failed.json +1 -0
  229. package/gallery/data/gh-run-passed.json +1 -0
  230. package/gallery/data/gh-run-running.json +1 -0
  231. package/gallery/data/github-release.json +57 -0
  232. package/gallery/data/hyperfine-startup.json +187 -0
  233. package/gallery/data/lcov.info +234 -0
  234. package/gallery/data/logs/media-sync.log +127 -0
  235. package/gallery/data/logs/thumbnailer.jsonl +17 -0
  236. package/gallery/data/logs/vitest-run.log +89 -0
  237. package/gallery/data/npm-audit.json +672 -0
  238. package/gallery/data/npm-outdated.json +179 -0
  239. package/gallery/data/oxlint.json +156 -0
  240. package/gallery/data/pip-outdated.json +68 -0
  241. package/gallery/data/pnpm-outdated.json +58 -0
  242. package/gallery/data/provenance/devicectl-install.json +35 -0
  243. package/gallery/data/provenance/install-timeout.log +4 -0
  244. package/gallery/data/provenance/iphone-install.json +72 -0
  245. package/gallery/data/provenance/iphone-no-receipt.json +57 -0
  246. package/gallery/data/provenance/live-home.jpg +0 -0
  247. package/gallery/data/provenance/live-probe.txt +10 -0
  248. package/gallery/data/provenance/xcodebuild-2811.log +19 -0
  249. package/gallery/data/provenance/xcodebuild-4712.log +19 -0
  250. package/gallery/data/pytest-junit.xml +64 -0
  251. package/gallery/data/python-org-trace.json +35 -0
  252. package/gallery/data/python-org.har +31 -0
  253. package/gallery/data/retry.ts +13 -0
  254. package/gallery/data/ruff.json +261 -0
  255. package/gallery/data/src/durations.py +63 -0
  256. package/gallery/data/src/json-logic.ts +156 -0
  257. package/gallery/data/src/mapMath.ts +135 -0
  258. package/gallery/data/src/semver/bump.go +73 -0
  259. package/gallery/data/traces/browser-error.json +5 -0
  260. package/gallery/data/traces/go/main.go +27 -0
  261. package/gallery/data/traces/go-panic.txt +16 -0
  262. package/gallery/data/traces/java-caused-by.txt +15 -0
  263. package/gallery/data/traces/node-aggregate.txt +30 -0
  264. package/gallery/data/traces/node-cause.txt +21 -0
  265. package/gallery/data/traces/py/deploy.json +5 -0
  266. package/gallery/data/traces/py/deploy.py +17 -0
  267. package/gallery/data/traces/py/settings.py +19 -0
  268. package/gallery/data/traces/python-chain.txt +30 -0
  269. package/gallery/data/traces/rust/main.rs +11 -0
  270. package/gallery/data/traces/rust-panic.txt +16 -0
  271. package/gallery/data/traces/shop/cart.mjs +19 -0
  272. package/gallery/data/traces/shop/pricing.mjs +12 -0
  273. package/gallery/data/traces/shop/status.mjs +9 -0
  274. package/gallery/data/traces/web/app.js +11 -0
  275. package/gallery/data/traces/web/index.html +1 -0
  276. package/gallery/data/traces/web/search.js +10 -0
  277. package/gallery/data/transcript/call-noisy.wav +0 -0
  278. package/gallery/data/transcript/call.json +362 -0
  279. package/gallery/data/transcript/call.wav +0 -0
  280. package/gallery/data/transcript/mlx-whisper-tiny.en-noisy.json +1 -0
  281. package/gallery/data/transcript/whisper-cpp-base.en-noisy.json +658 -0
  282. package/gallery/data/transcript/whisper-cpp-base.en.json +658 -0
  283. package/gallery/data/transcript/whisper-cpp-base.en.srt +16 -0
  284. package/gallery/data/transcript/whisper-cpp-tiny.en-noisy.json +619 -0
  285. package/gallery/data/tsc.txt +4 -0
  286. package/gallery/data/vitest-bench.json +119 -0
  287. package/gallery/data/vitest-junit.xml +133 -0
  288. package/gallery/data/vitest-report.json +612 -0
  289. package/gallery/images/bell.svg +10 -0
  290. package/gallery/images/bike.svg +47 -0
  291. package/gallery/images/footer-planet.webp +0 -0
  292. package/gallery/images/front-light.svg +13 -0
  293. package/gallery/images/golden-hour.webp +0 -0
  294. package/gallery/images/option-flowers.webp +0 -0
  295. package/gallery/images/option-hilltop.webp +0 -0
  296. package/gallery/images/option-meadow.webp +0 -0
  297. package/gallery/images/option-sky.webp +0 -0
  298. package/gallery/images/u-lock.svg +10 -0
  299. package/index.client.tsx +164 -0
  300. package/index.server.ts +216 -0
  301. package/package.json +50 -4
  302. package/paseo-plugin.json +14 -0
  303. package/server/data-source.ts +407 -0
  304. package/server/project.ts +981 -0
  305. package/server/web/address.ts +57 -0
  306. package/server/web/cache.ts +85 -0
  307. package/server/web/commons.ts +126 -0
  308. package/server/web/geocode.ts +40 -0
  309. package/server/web/image.ts +35 -0
  310. package/server/web/lookups.ts +248 -0
  311. package/server/web/net.ts +210 -0
  312. package/shared/core/acceptance.ts +744 -0
  313. package/shared/core/ast.ts +76 -0
  314. package/shared/core/benchmark.ts +743 -0
  315. package/shared/core/catalog.ts +733 -0
  316. package/shared/core/compare.ts +225 -0
  317. package/shared/core/coverage.ts +456 -0
  318. package/shared/core/data.ts +334 -0
  319. package/shared/core/decisions.ts +527 -0
  320. package/shared/core/dependencies.ts +604 -0
  321. package/shared/core/diagnostics.ts +24 -0
  322. package/shared/core/environments.ts +212 -0
  323. package/shared/core/evaluate.ts +737 -0
  324. package/shared/core/fields.ts +66 -0
  325. package/shared/core/findings.ts +1172 -0
  326. package/shared/core/form.ts +69 -0
  327. package/shared/core/index.ts +44 -0
  328. package/shared/core/junit.ts +252 -0
  329. package/shared/core/lexer.ts +275 -0
  330. package/shared/core/logs.ts +496 -0
  331. package/shared/core/markdown.ts +2374 -0
  332. package/shared/core/parser.ts +355 -0
  333. package/shared/core/perf-units.ts +228 -0
  334. package/shared/core/pipeline.ts +679 -0
  335. package/shared/core/project.ts +472 -0
  336. package/shared/core/provenance.ts +725 -0
  337. package/shared/core/stack-trace.ts +718 -0
  338. package/shared/core/streaming.ts +136 -0
  339. package/shared/core/test-results.ts +562 -0
  340. package/shared/core/thread-activity.ts +203 -0
  341. package/shared/core/tracking.ts +887 -0
  342. package/shared/core/transcript.ts +1364 -0
  343. package/shared/core/treemap.ts +446 -0
  344. package/shared/core/types.ts +70 -0
  345. package/shared/core/validate.ts +574 -0
  346. package/shared/core/waterfall.ts +536 -0
  347. package/shared/diagram/flowchart.ts +205 -0
  348. package/shared/diagram/layout.ts +440 -0
  349. package/shared/diagram/markdown.ts +135 -0
  350. package/shared/diagram/sequence.ts +122 -0
  351. package/shared/diagram/zoom.ts +114 -0
  352. package/shared/fallback.ts +120 -0
  353. package/shared/genui.test.ts +122 -0
  354. package/shared/instructions.ts +144 -0
  355. package/shared/logic/calendarMath.ts +130 -0
  356. package/shared/logic/chartMath.ts +289 -0
  357. package/shared/logic/choose-logic.ts +196 -0
  358. package/shared/logic/compare-logic.ts +270 -0
  359. package/shared/logic/content-model.ts +227 -0
  360. package/shared/logic/environments-logic.ts +53 -0
  361. package/shared/logic/explain-logic.ts +315 -0
  362. package/shared/logic/fieldLogic.ts +138 -0
  363. package/shared/logic/gallery-search.ts +71 -0
  364. package/shared/logic/icons.ts +322 -0
  365. package/shared/logic/json-logic.ts +153 -0
  366. package/shared/logic/mapMath.ts +133 -0
  367. package/shared/logic/project-logic.ts +39 -0
  368. package/shared/logic/references-model.ts +201 -0
  369. package/shared/logic/sketch.ts +165 -0
  370. package/shared/logic/supersession.ts +77 -0
  371. package/shared/logic/values.ts +133 -0
  372. package/shared/logic/widget-logic.ts +163 -0
  373. package/shared/rpc.ts +252 -0
  374. package/shared/segment.ts +81 -0
  375. package/shared/settings.ts +12 -0
@@ -0,0 +1,225 @@
1
+ // Compare's input as both the renderer and the markdown fallback read it: the
2
+ // images (the first is the reference), their labels and capture conditions,
3
+ // which conditions differ between two of them, and how a candidate of another
4
+ // size is fitted onto the reference. Pure.
5
+ import { isPlainObject } from "./evaluate";
6
+ import type { Value } from "./types";
7
+
8
+ export interface CompareImage {
9
+ readonly src: string;
10
+ /** What the user calls it: the given label, else "Reference" for the first and the file name for the others. */
11
+ readonly label: string;
12
+ /** True when `label` was given rather than derived. */
13
+ readonly named: boolean;
14
+ readonly note: string | null;
15
+ /** Capture facts in the order given (build, viewport, device, theme, time…), values as text. */
16
+ readonly meta: readonly (readonly [key: string, value: string])[];
17
+ }
18
+
19
+ export type CompareRead =
20
+ | { readonly ok: true; readonly images: readonly CompareImage[]; readonly ignored: number }
21
+ | { readonly ok: false; readonly error: string };
22
+
23
+ const LABEL_KEYS = ["label", "name", "title", "caption", "alt"] as const;
24
+ const SRC_KEYS = ["src", "path", "url", "image"] as const;
25
+ /** Entry keys that are not capture facts; any other scalar key on an entry joins its meta. */
26
+ const ENTRY_KEYS: Record<string, true> = {
27
+ src: true,
28
+ path: true,
29
+ url: true,
30
+ image: true,
31
+ note: true,
32
+ detail: true,
33
+ meta: true,
34
+ label: true,
35
+ name: true,
36
+ title: true,
37
+ caption: true,
38
+ alt: true,
39
+ };
40
+
41
+ /**
42
+ * Facts that are expected to differ between a reference and what is compared
43
+ * with it (they say which build or capture each one is), so they never make
44
+ * the comparison "not the same conditions". Everything else (theme, viewport,
45
+ * device, browser, scale, time, state…) is a condition. Keys as `metaKey` writes them.
46
+ */
47
+ const IDENTITY_KEYS: Record<string, true> = {
48
+ build: true,
49
+ commit: true,
50
+ sha: true,
51
+ revision: true,
52
+ rev: true,
53
+ branch: true,
54
+ version: true,
55
+ tag: true,
56
+ pr: true,
57
+ run: true,
58
+ captured: true,
59
+ capturedat: true,
60
+ date: true,
61
+ timestamp: true,
62
+ source: true,
63
+ url: true,
64
+ path: true,
65
+ file: true,
66
+ };
67
+
68
+ function scalarText(value: Value | undefined): string | null {
69
+ if (typeof value === "string") return value.trim() === "" ? null : value.trim();
70
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : null;
71
+ if (typeof value === "boolean") return value ? "yes" : "no";
72
+ return null;
73
+ }
74
+
75
+ /** The last path segment of a src (query and fragment dropped), or the src itself. */
76
+ export function fileName(src: string): string {
77
+ const path = src.replace(/[?#].*$/, "");
78
+ const name = path.split(/[\\/]/).filter((part) => part !== "").pop();
79
+ try {
80
+ return name === undefined ? src : decodeURIComponent(name);
81
+ } catch {
82
+ return name ?? src;
83
+ }
84
+ }
85
+
86
+ function readMeta(entry: Readonly<Record<string, Value>>): [string, string][] {
87
+ const out: [string, string][] = [];
88
+ const seen = new Set<string>();
89
+ const add = (key: string, value: Value | undefined) => {
90
+ const text = scalarText(value);
91
+ const id = metaKey(key);
92
+ if (text === null || id === "" || seen.has(id)) return;
93
+ seen.add(id);
94
+ out.push([key.trim(), text]);
95
+ };
96
+ if (entry.meta !== undefined && isPlainObject(entry.meta)) for (const [key, value] of Object.entries(entry.meta)) add(key, value);
97
+ for (const [key, value] of Object.entries(entry)) if (!Object.hasOwn(ENTRY_KEYS, key)) add(key, value);
98
+ return out;
99
+ }
100
+
101
+ /**
102
+ * `images`: a list of a src string or `{src, label?, note?, meta?}` (scalar
103
+ * keys beside src such as `theme: "dark"` count as meta). Entries without a
104
+ * src are counted in `ignored`; the list must name at least one image.
105
+ */
106
+ export function readCompare(value: Value | undefined): CompareRead {
107
+ if (!Array.isArray(value)) return { ok: false, error: "Compare needs a list of images: the reference first, then what to compare with it" };
108
+ const images: CompareImage[] = [];
109
+ let ignored = 0;
110
+ for (const item of value as readonly Value[]) {
111
+ const entry: Readonly<Record<string, Value>> | null = isPlainObject(item) ? item : null;
112
+ const raw = entry === null ? item : SRC_KEYS.map((key) => entry[key]).find((field) => typeof field === "string" && field.trim() !== "");
113
+ if (typeof raw !== "string" || raw.trim() === "") {
114
+ ignored++;
115
+ continue;
116
+ }
117
+ const src = raw.trim();
118
+ const given = entry === null ? null : (LABEL_KEYS.map((key) => scalarText(entry[key])).find((label) => label !== null) ?? null);
119
+ images.push({
120
+ src,
121
+ label: given ?? (images.length === 0 ? "Reference" : fileName(src)),
122
+ named: given !== null,
123
+ note: entry === null ? null : scalarText(entry.note ?? entry.detail),
124
+ meta: entry === null ? [] : readMeta(entry),
125
+ });
126
+ }
127
+ return { ok: true, images, ignored };
128
+ }
129
+
130
+ /** A meta key compared without case, spaces, dashes or underscores: `capturedAt` = `captured_at`. */
131
+ export function metaKey(key: string): string {
132
+ return key.toLowerCase().replace(/[\s_-]+/g, "");
133
+ }
134
+
135
+ /** A meta value compared without case or spacing; `1440x900` = `1440 × 900`. */
136
+ function metaValue(value: string): string {
137
+ return value.toLowerCase().replace(/\s*[×x]\s*/g, "x").replace(/\s+/g, " ").trim();
138
+ }
139
+
140
+ export function isConditionKey(key: string): boolean {
141
+ return !Object.hasOwn(IDENTITY_KEYS, metaKey(key));
142
+ }
143
+
144
+ export interface ConditionDifference {
145
+ /** The key as the reference names it (else as the candidate does). */
146
+ readonly key: string;
147
+ /** Null where that image does not state it. */
148
+ readonly reference: string | null;
149
+ readonly candidate: string | null;
150
+ }
151
+
152
+ /**
153
+ * The capture conditions that differ between the reference and a candidate:
154
+ * stated on both with different values, or stated on one only (unknown is
155
+ * not the same). Identity facts (build, commit, capture date…) are left out.
156
+ */
157
+ export function conditionDifferences(reference: CompareImage, candidate: CompareImage): ConditionDifference[] {
158
+ const theirs = new Map(candidate.meta.map(([key, value]) => [metaKey(key), { key, value }]));
159
+ const out: ConditionDifference[] = [];
160
+ for (const [key, value] of reference.meta) {
161
+ if (!isConditionKey(key)) continue;
162
+ const other = theirs.get(metaKey(key));
163
+ theirs.delete(metaKey(key));
164
+ if (other === undefined) out.push({ key, reference: value, candidate: null });
165
+ else if (metaValue(other.value) !== metaValue(value)) out.push({ key, reference: value, candidate: other.value });
166
+ }
167
+ for (const { key, value } of theirs.values()) if (isConditionKey(key)) out.push({ key, reference: null, candidate: value });
168
+ return out;
169
+ }
170
+
171
+ /** "theme light vs dark", "device stated only for Reference (iPhone 15)". */
172
+ export function differenceText(difference: ConditionDifference, referenceLabel: string, candidateLabel: string): string {
173
+ const { key, reference, candidate } = difference;
174
+ if (reference !== null && candidate !== null) return `${key} ${reference} vs ${candidate}`;
175
+ return reference !== null ? `${key} stated only for ${referenceLabel} (${reference})` : `${key} stated only for ${candidateLabel} (${candidate ?? ""})`;
176
+ }
177
+
178
+ /** "Not the same conditions: theme light vs dark · viewport 1440 vs 390"; null when nothing differs. */
179
+ export function conditionsWarning(differences: readonly ConditionDifference[], referenceLabel: string, candidateLabel: string): string | null {
180
+ if (differences.length === 0) return null;
181
+ return `Not the same conditions: ${differences.map((difference) => differenceText(difference, referenceLabel, candidateLabel)).join(" · ")}`;
182
+ }
183
+
184
+ export interface Size {
185
+ readonly width: number;
186
+ readonly height: number;
187
+ }
188
+
189
+ /**
190
+ * Where a candidate lands on the reference's pixel grid: scaled to the
191
+ * reference's width (keeping its own aspect, so nothing is stretched) and
192
+ * top-aligned, as screenshots of one page line up. `height` may be shorter or
193
+ * taller than the reference; the part it misses counts as changed.
194
+ */
195
+ export interface Placement {
196
+ readonly scale: number;
197
+ readonly width: number;
198
+ readonly height: number;
199
+ readonly sameSize: boolean;
200
+ readonly sameAspect: boolean;
201
+ }
202
+
203
+ export function placement(reference: Size, candidate: Size): Placement {
204
+ const scale = candidate.width > 0 ? reference.width / candidate.width : 1;
205
+ const height = candidate.height * scale;
206
+ const sameSize = reference.width === candidate.width && reference.height === candidate.height;
207
+ // Within a pixel of the reference height after scaling: rounding, not a different aspect.
208
+ const sameAspect = Math.abs(height - reference.height) <= 1;
209
+ return { scale, width: reference.width, height: sameAspect ? reference.height : height, sameSize, sameAspect };
210
+ }
211
+
212
+ /**
213
+ * "Sizes differ: 1440×900 vs 1280×800, scaled ×1.13 to the reference"; with
214
+ * another aspect also how the heights compare. Null when the sizes match.
215
+ */
216
+ export function sizeWarning(reference: Size, candidate: Size, candidateLabel: string): string | null {
217
+ const fit = placement(reference, candidate);
218
+ if (fit.sameSize) return null;
219
+ const sizes = `Sizes differ: ${reference.width}×${reference.height} vs ${candidate.width}×${candidate.height}`;
220
+ const factor = `×${Number(fit.scale.toPrecision(3))}`;
221
+ if (fit.sameAspect) return `${sizes}, ${candidateLabel} scaled ${factor} to the reference`;
222
+ const scaled = fit.scale === 1 ? "" : ` scaled ${factor} to the reference width,`;
223
+ const rows = Math.round(Math.abs(fit.height - reference.height));
224
+ return `${sizes};${scaled} top-aligned, ${candidateLabel} is ${rows} px ${fit.height < reference.height ? "shorter (the rest counts as changed)" : "taller (cut at the reference height)"}`;
225
+ }
@@ -0,0 +1,456 @@
1
+ // What `Coverage` shows, from the reports it reads: istanbul's
2
+ // `coverage-summary.json` (the json-summary reporter of vitest, jest, nyc),
3
+ // `lcov.info`, coverage.py's `coverage json` and Go's `coverage.out`. Each
4
+ // becomes per-file ratios plus, where the format knows them, the uncovered
5
+ // line ranges; then the totals, the directory tree and the tone. Pure: no
6
+ // React, no DOM.
7
+ import { count, fieldsOf, listOf, plainLines, positiveInteger, reportPath, type Fields } from "./fields";
8
+ import type { Value } from "./types";
9
+
10
+ /** Covered of total (lines, statements, branches or functions). */
11
+ export interface Ratio {
12
+ readonly covered: number;
13
+ readonly total: number;
14
+ }
15
+
16
+ /** A run of uncovered lines from `start` to `end` (1-based, inclusive); `missed` are its executable lines that never ran. */
17
+ export interface LineRange {
18
+ readonly start: number;
19
+ readonly end: number;
20
+ readonly missed: readonly number[];
21
+ }
22
+
23
+ export type CoverageFormat = "istanbul" | "lcov" | "coverage.py" | "go";
24
+
25
+ /** What a report counts its headline in: lines, or statements for Go (it has no line metric). */
26
+ export type CoverageUnit = "lines" | "statements";
27
+
28
+ export interface CoverageMetrics {
29
+ readonly lines: Ratio | null;
30
+ readonly statements: Ratio | null;
31
+ readonly branches: Ratio | null;
32
+ readonly functions: Ratio | null;
33
+ }
34
+
35
+ export interface FileCoverage extends CoverageMetrics {
36
+ readonly path: string;
37
+ /** Uncovered lines (statements for Go): what "most uncovered" sorts by. */
38
+ readonly missed: number;
39
+ /** The uncovered ranges; null where the format only has totals (coverage-summary.json). */
40
+ readonly uncovered: readonly LineRange[] | null;
41
+ }
42
+
43
+ export interface CoverageReport {
44
+ readonly format: CoverageFormat;
45
+ readonly unit: CoverageUnit;
46
+ readonly total: CoverageMetrics;
47
+ readonly files: readonly FileCoverage[];
48
+ }
49
+
50
+ export type CoverageResult = { readonly ok: true; readonly report: CoverageReport } | { readonly ok: false; readonly error: string };
51
+
52
+ const SHAPE_HINT = "Coverage needs coverage-summary.json, lcov.info, coverage.py JSON or Go coverage.out";
53
+
54
+ /** A whole percentage of a ratio; null when there is nothing to cover. */
55
+ export function percent(ratio: Ratio | null): number | null {
56
+ return ratio === null || ratio.total === 0 ? null : (ratio.covered / ratio.total) * 100;
57
+ }
58
+
59
+ /** The ratio a report's headline uses. */
60
+ export function headline(metrics: CoverageMetrics, unit: CoverageUnit): Ratio | null {
61
+ return unit === "lines" ? (metrics.lines ?? metrics.statements) : (metrics.statements ?? metrics.lines);
62
+ }
63
+
64
+ export type CoverageTone = "good" | "warn" | "bad";
65
+
66
+ /** ≥ 80 % good, ≥ 60 % warn, below bad. */
67
+ export function coverageTone(value: number): CoverageTone {
68
+ return value >= 80 ? "good" : value >= 60 ? "warn" : "bad";
69
+ }
70
+
71
+ /**
72
+ * `84.7%`, `100%`, `0%`: one decimal, rounded as the tools print it (Go's
73
+ * 74.2 %), except that a file with one missed line never reads 100 % and one
74
+ * with a covered line never reads 0 %.
75
+ */
76
+ export function formatPercent(value: number): string {
77
+ const rounded = Math.min(Math.max(Math.round(value * 10) / 10, value > 0 ? 0.1 : 0), value < 100 ? 99.9 : 100);
78
+ return `${Number.isInteger(rounded) ? rounded.toFixed(0) : rounded.toFixed(1)}%`;
79
+ }
80
+
81
+ function sum(ratios: readonly (Ratio | null)[]): Ratio | null {
82
+ let covered = 0;
83
+ let total = 0;
84
+ let any = false;
85
+ for (const ratio of ratios) {
86
+ if (ratio === null) continue;
87
+ any = true;
88
+ covered += ratio.covered;
89
+ total += ratio.total;
90
+ }
91
+ return any ? { covered, total } : null;
92
+ }
93
+
94
+ function totals(files: readonly CoverageMetrics[]): CoverageMetrics {
95
+ return {
96
+ lines: sum(files.map((file) => file.lines)),
97
+ statements: sum(files.map((file) => file.statements)),
98
+ branches: sum(files.map((file) => file.branches)),
99
+ functions: sum(files.map((file) => file.functions)),
100
+ };
101
+ }
102
+
103
+ /**
104
+ * Uncovered ranges from the executable lines' hits: runs of missed lines,
105
+ * joined across lines that aren't executable (blanks, comments) but broken
106
+ * by any line that ran.
107
+ */
108
+ export function uncoveredRanges(hits: ReadonlyMap<number, boolean>): LineRange[] {
109
+ const lines = [...hits.keys()].sort((a, b) => a - b);
110
+ const ranges: LineRange[] = [];
111
+ let open: { start: number; end: number; missed: number[] } | null = null;
112
+ for (const line of lines) {
113
+ if (hits.get(line)) {
114
+ if (open !== null) ranges.push(open);
115
+ open = null;
116
+ } else if (open === null) open = { start: line, end: line, missed: [line] };
117
+ else {
118
+ open.end = line;
119
+ open.missed.push(line);
120
+ }
121
+ }
122
+ if (open !== null) ranges.push(open);
123
+ return ranges;
124
+ }
125
+
126
+ // ---------------------------------------------------------------------------
127
+ // istanbul coverage-summary.json
128
+
129
+ function istanbulRatio(value: Value | undefined): Ratio | null {
130
+ const fields = fieldsOf(value);
131
+ const total = count(fields?.total);
132
+ const covered = count(fields?.covered);
133
+ return total === null || covered === null ? null : { covered: Math.min(covered, total), total };
134
+ }
135
+
136
+ function istanbulMetrics(fields: Fields): CoverageMetrics {
137
+ return {
138
+ lines: istanbulRatio(fields.lines),
139
+ statements: istanbulRatio(fields.statements),
140
+ branches: istanbulRatio(fields.branches),
141
+ functions: istanbulRatio(fields.functions),
142
+ };
143
+ }
144
+
145
+ function isIstanbulSummary(object: Fields): boolean {
146
+ const total = fieldsOf(object.total);
147
+ return total !== null && (istanbulRatio(total.lines) !== null || istanbulRatio(total.statements) !== null);
148
+ }
149
+
150
+ function fromIstanbul(object: Fields): CoverageReport {
151
+ const files: FileCoverage[] = [];
152
+ for (const [path, value] of Object.entries(object)) {
153
+ const fields = fieldsOf(value);
154
+ if (path === "total" || fields === null) continue;
155
+ const metrics = istanbulMetrics(fields);
156
+ const lines = metrics.lines ?? metrics.statements;
157
+ files.push({ path: reportPath(path), ...metrics, missed: lines === null ? 0 : lines.total - lines.covered, uncovered: null });
158
+ }
159
+ return { format: "istanbul", unit: "lines", total: istanbulMetrics(fieldsOf(object.total)!), files };
160
+ }
161
+
162
+ // ---------------------------------------------------------------------------
163
+ // lcov.info
164
+
165
+ function isLcov(text: string): boolean {
166
+ return /^SF:/m.test(text) && /^end_of_record/m.test(text);
167
+ }
168
+
169
+ function fromLcov(text: string): CoverageReport {
170
+ const files: FileCoverage[] = [];
171
+ let path: string | null = null;
172
+ let hits = new Map<number, boolean>();
173
+ let found: Record<"LF" | "LH" | "FNF" | "FNH" | "BRF" | "BRH", number | null> = { LF: null, LH: null, FNF: null, FNH: null, BRF: null, BRH: null };
174
+ let functionHits = new Map<string, boolean>();
175
+ let branches = { total: 0, covered: 0 };
176
+ const ratio = (covered: number | null, total: number | null): Ratio | null =>
177
+ total === null ? null : { covered: Math.min(covered ?? 0, total), total };
178
+ for (const raw of plainLines(text)) {
179
+ const line = raw.trim();
180
+ const colon = line.indexOf(":");
181
+ const tag = colon === -1 ? line : line.slice(0, colon);
182
+ const rest = colon === -1 ? "" : line.slice(colon + 1);
183
+ switch (tag) {
184
+ case "SF":
185
+ path = reportPath(rest);
186
+ hits = new Map();
187
+ found = { LF: null, LH: null, FNF: null, FNH: null, BRF: null, BRH: null };
188
+ functionHits = new Map();
189
+ branches = { total: 0, covered: 0 };
190
+ break;
191
+ case "DA": {
192
+ const [lineText, hitText] = rest.split(",");
193
+ const number = positiveInteger(lineText);
194
+ if (number !== null) hits.set(number, (hits.get(number) ?? false) || Number(hitText) > 0);
195
+ break;
196
+ }
197
+ case "FNDA": {
198
+ const comma = rest.indexOf(",");
199
+ const name = rest.slice(comma + 1);
200
+ functionHits.set(name, (functionHits.get(name) ?? false) || Number(rest.slice(0, comma)) > 0);
201
+ break;
202
+ }
203
+ case "BRDA": {
204
+ const taken = rest.split(",")[3];
205
+ branches.total++;
206
+ if (taken !== undefined && taken !== "-" && Number(taken) > 0) branches.covered++;
207
+ break;
208
+ }
209
+ case "LF":
210
+ case "LH":
211
+ case "FNF":
212
+ case "FNH":
213
+ case "BRF":
214
+ case "BRH":
215
+ found[tag] = count(rest);
216
+ break;
217
+ case "end_of_record": {
218
+ if (path === null) break;
219
+ let covered = 0;
220
+ for (const ran of hits.values()) if (ran) covered++;
221
+ const lines = hits.size > 0 ? { covered, total: hits.size } : ratio(found.LH, found.LF);
222
+ let functionsCovered = 0;
223
+ for (const ran of functionHits.values()) if (ran) functionsCovered++;
224
+ files.push({
225
+ path,
226
+ lines,
227
+ statements: null,
228
+ branches: found.BRF !== null ? ratio(found.BRH, found.BRF) : branches.total > 0 ? branches : null,
229
+ functions: found.FNF !== null ? ratio(found.FNH, found.FNF) : functionHits.size > 0 ? { covered: functionsCovered, total: functionHits.size } : null,
230
+ missed: lines === null ? 0 : lines.total - lines.covered,
231
+ uncovered: hits.size > 0 ? uncoveredRanges(hits) : null,
232
+ });
233
+ path = null;
234
+ break;
235
+ }
236
+ }
237
+ }
238
+ return { format: "lcov", unit: "lines", total: totals(files), files };
239
+ }
240
+
241
+ // ---------------------------------------------------------------------------
242
+ // coverage.py JSON
243
+
244
+ function isCoveragePy(object: Fields): boolean {
245
+ const files = fieldsOf(object.files);
246
+ if (files === null) return false;
247
+ const first = fieldsOf(Object.values(files)[0]);
248
+ return first === null ? fieldsOf(object.totals) !== null : fieldsOf(first.summary) !== null || Array.isArray(first.missing_lines);
249
+ }
250
+
251
+ function pyMetrics(summary: Fields | null): CoverageMetrics {
252
+ const statements = count(summary?.num_statements);
253
+ const covered = count(summary?.covered_lines);
254
+ const branchTotal = count(summary?.num_branches);
255
+ const branchCovered = count(summary?.covered_branches);
256
+ return {
257
+ lines: statements === null || covered === null ? null : { covered: Math.min(covered, statements), total: statements },
258
+ statements: null,
259
+ branches: branchTotal === null || branchCovered === null ? null : { covered: Math.min(branchCovered, branchTotal), total: branchTotal },
260
+ functions: null,
261
+ };
262
+ }
263
+
264
+ function fromCoveragePy(object: Fields): CoverageReport {
265
+ const files: FileCoverage[] = [];
266
+ for (const [path, value] of Object.entries(fieldsOf(object.files) ?? {})) {
267
+ const fields = fieldsOf(value);
268
+ if (fields === null) continue;
269
+ const hits = new Map<number, boolean>();
270
+ for (const line of listOf(fields.executed_lines)) {
271
+ const number = positiveInteger(line);
272
+ if (number !== null) hits.set(number, true);
273
+ }
274
+ for (const line of listOf(fields.missing_lines)) {
275
+ const number = positiveInteger(line);
276
+ if (number !== null && !hits.has(number)) hits.set(number, false);
277
+ }
278
+ let metrics = pyMetrics(fieldsOf(fields.summary));
279
+ if (metrics.lines === null && hits.size > 0) {
280
+ let covered = 0;
281
+ for (const ran of hits.values()) if (ran) covered++;
282
+ metrics = { ...metrics, lines: { covered, total: hits.size } };
283
+ }
284
+ const lines = metrics.lines;
285
+ files.push({
286
+ path: reportPath(path),
287
+ ...metrics,
288
+ missed: lines === null ? 0 : lines.total - lines.covered,
289
+ uncovered: Array.isArray(fields.missing_lines) ? uncoveredRanges(hits) : null,
290
+ });
291
+ }
292
+ const given = fieldsOf(object.totals);
293
+ return { format: "coverage.py", unit: "lines", total: given === null ? totals(files) : pyMetrics(given), files };
294
+ }
295
+
296
+ // ---------------------------------------------------------------------------
297
+ // Go coverage.out
298
+
299
+ const GO_BLOCK = /^(.+):(\d+)\.(\d+),(\d+)\.(\d+) (\d+) (\d+)$/;
300
+
301
+ function isGoProfile(text: string): boolean {
302
+ return /^mode: (?:set|count|atomic)\s*$/m.test(text);
303
+ }
304
+
305
+ function fromGo(text: string): CoverageReport {
306
+ // The same block appears once per test binary with -coverpkg; it ran if it ran in any.
307
+ const blocks = new Map<string, { file: string; startLine: number; endLine: number; statements: number; ran: boolean }>();
308
+ for (const raw of plainLines(text)) {
309
+ const match = GO_BLOCK.exec(raw.trim());
310
+ if (match === null) continue;
311
+ const [, file, startLine, startColumn, endLine, endColumn, statements, hits] = match;
312
+ const key = `${file}:${startLine}.${startColumn},${endLine}.${endColumn}`;
313
+ const ran = Number(hits) > 0;
314
+ const known = blocks.get(key);
315
+ if (known !== undefined) known.ran ||= ran;
316
+ else blocks.set(key, { file: file!, startLine: Number(startLine), endLine: Number(endLine), statements: Number(statements), ran });
317
+ }
318
+ const byFile = new Map<string, { covered: number; total: number; ranLines: Set<number>; missedLines: Set<number> }>();
319
+ for (const block of blocks.values()) {
320
+ let file = byFile.get(block.file);
321
+ if (file === undefined) byFile.set(block.file, (file = { covered: 0, total: 0, ranLines: new Set(), missedLines: new Set() }));
322
+ file.total += block.statements;
323
+ if (block.ran) file.covered += block.statements;
324
+ const lines = block.ran ? file.ranLines : file.missedLines;
325
+ for (let line = block.startLine; line <= block.endLine; line++) lines.add(line);
326
+ }
327
+ const files: FileCoverage[] = [...byFile].map(([path, file]) => {
328
+ // A line a block that ran also touches (a closing brace, an `else`) isn't uncovered.
329
+ const hits = new Map<number, boolean>();
330
+ for (const line of file.ranLines) hits.set(line, true);
331
+ for (const line of file.missedLines) if (!hits.has(line)) hits.set(line, false);
332
+ return {
333
+ path,
334
+ lines: null,
335
+ statements: { covered: file.covered, total: file.total },
336
+ branches: null,
337
+ functions: null,
338
+ missed: file.total - file.covered,
339
+ uncovered: uncoveredRanges(hits),
340
+ };
341
+ });
342
+ return { format: "go", unit: "statements", total: totals(files), files };
343
+ }
344
+
345
+ // ---------------------------------------------------------------------------
346
+
347
+ /** The coverage `value` describes: a loaded report (object or text). */
348
+ export function readCoverage(value: Value | undefined): CoverageResult {
349
+ if (typeof value === "string") {
350
+ if (isGoProfile(value)) return { ok: true, report: fromGo(value) };
351
+ if (isLcov(value)) return { ok: true, report: fromLcov(value) };
352
+ return { ok: false, error: `${SHAPE_HINT}; this text is neither lcov (SF:… end_of_record) nor a Go profile (mode: …)` };
353
+ }
354
+ const object = fieldsOf(value);
355
+ if (object === null) return { ok: false, error: SHAPE_HINT };
356
+ if (isIstanbulSummary(object)) return { ok: true, report: fromIstanbul(object) };
357
+ if (isCoveragePy(object)) return { ok: true, report: fromCoveragePy(object) };
358
+ return { ok: false, error: SHAPE_HINT };
359
+ }
360
+
361
+ // ---------------------------------------------------------------------------
362
+ // Views
363
+
364
+ /** Files with the most uncovered lines (statements for Go) first, then the lowest coverage, then by path. */
365
+ export function mostUncovered(files: readonly FileCoverage[], unit: CoverageUnit): FileCoverage[] {
366
+ return [...files].sort((a, b) => {
367
+ if (b.missed !== a.missed) return b.missed - a.missed;
368
+ const pa = percent(headline(a, unit)) ?? 100;
369
+ const pb = percent(headline(b, unit)) ?? 100;
370
+ return pa - pb || a.path.localeCompare(b.path);
371
+ });
372
+ }
373
+
374
+ export interface CoverageFolder {
375
+ readonly kind: "folder";
376
+ /** The folder's name, single-child chains joined (`src/core`). */
377
+ readonly name: string;
378
+ /** Path from the shown root, for keys and labels. */
379
+ readonly path: string;
380
+ readonly children: readonly CoverageNode[];
381
+ readonly metrics: CoverageMetrics;
382
+ readonly missed: number;
383
+ readonly fileCount: number;
384
+ }
385
+
386
+ export interface CoverageLeaf {
387
+ readonly kind: "file";
388
+ readonly name: string;
389
+ readonly path: string;
390
+ readonly file: FileCoverage;
391
+ }
392
+
393
+ export type CoverageNode = CoverageFolder | CoverageLeaf;
394
+
395
+ interface Building {
396
+ folders: Map<string, Building>;
397
+ files: { name: string; file: FileCoverage }[];
398
+ }
399
+
400
+ /**
401
+ * Files as a directory tree under the shown paths (`shown` gives each file's
402
+ * display path), folders first then files, by name; folders with one child
403
+ * folder and no files fold into it (`src/core`).
404
+ */
405
+ export function coverageTree(files: readonly FileCoverage[], shown: (file: FileCoverage) => string): CoverageNode[] {
406
+ const root: Building = { folders: new Map(), files: [] };
407
+ for (const file of files) {
408
+ const parts = shown(file).split("/").filter((part) => part !== "");
409
+ let at = root;
410
+ for (const part of parts.slice(0, -1)) {
411
+ let next = at.folders.get(part);
412
+ if (next === undefined) at.folders.set(part, (next = { folders: new Map(), files: [] }));
413
+ at = next;
414
+ }
415
+ at.files.push({ name: parts.at(-1) ?? shown(file), file });
416
+ }
417
+ const build = (at: Building, prefix: string): CoverageNode[] => {
418
+ const folders = [...at.folders]
419
+ .sort(([a], [b]) => a.localeCompare(b))
420
+ .map(([name, folder]): CoverageFolder => {
421
+ let label = name;
422
+ let inner = folder;
423
+ while (inner.files.length === 0 && inner.folders.size === 1) {
424
+ const [childName, child] = inner.folders.entries().next().value!;
425
+ label = `${label}/${childName}`;
426
+ inner = child;
427
+ }
428
+ const path = `${prefix}${label}`;
429
+ const children = build(inner, `${path}/`);
430
+ const leaves = collectFiles(children);
431
+ return {
432
+ kind: "folder",
433
+ name: label,
434
+ path,
435
+ children,
436
+ metrics: totals(leaves),
437
+ missed: leaves.reduce((total, file) => total + file.missed, 0),
438
+ fileCount: leaves.length,
439
+ };
440
+ });
441
+ const leaves = [...at.files]
442
+ .sort((a, b) => a.name.localeCompare(b.name))
443
+ .map(({ name, file }): CoverageLeaf => ({ kind: "file", name, path: `${prefix}${name}`, file }));
444
+ return [...folders, ...leaves];
445
+ };
446
+ return build(root, "");
447
+ }
448
+
449
+ function collectFiles(nodes: readonly CoverageNode[]): FileCoverage[] {
450
+ return nodes.flatMap((node) => (node.kind === "file" ? [node.file] : collectFiles(node.children)));
451
+ }
452
+
453
+ /** `12–18`, or `12` for one line. */
454
+ export function rangeLabel(range: LineRange): string {
455
+ return range.start === range.end ? String(range.start) : `${range.start}–${range.end}`;
456
+ }