@warlock.js/grimoire 5.63.1 → 5.65.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 (197) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/esm/book/build.d.mts.map +1 -1
  3. package/esm/book/build.mjs +24 -2
  4. package/esm/book/build.mjs.map +1 -1
  5. package/esm/check/check-grimoire.d.mts.map +1 -1
  6. package/esm/check/check-grimoire.mjs +11 -1
  7. package/esm/check/check-grimoire.mjs.map +1 -1
  8. package/esm/check/rules/api-snapshot.mjs +39 -0
  9. package/esm/check/rules/api-snapshot.mjs.map +1 -0
  10. package/esm/check/rules/code-rules.mjs +45 -0
  11. package/esm/check/rules/code-rules.mjs.map +1 -0
  12. package/esm/check/rules/drift.mjs +54 -0
  13. package/esm/check/rules/drift.mjs.map +1 -0
  14. package/esm/check/rules/focused-tests.mjs +39 -0
  15. package/esm/check/rules/focused-tests.mjs.map +1 -0
  16. package/esm/check/rules/shows.mjs +52 -0
  17. package/esm/check/rules/shows.mjs.map +1 -0
  18. package/esm/codes/codes.d.mts +48 -0
  19. package/esm/codes/codes.d.mts.map +1 -1
  20. package/esm/codes/codes.mjs +26 -1
  21. package/esm/codes/codes.mjs.map +1 -1
  22. package/esm/contracts/adapter.d.mts +6 -0
  23. package/esm/contracts/adapter.d.mts.map +1 -1
  24. package/esm/contracts/guard.d.mts +104 -0
  25. package/esm/contracts/guard.d.mts.map +1 -0
  26. package/esm/contracts/index.mjs +5 -0
  27. package/esm/contracts/matrix.d.mts +75 -0
  28. package/esm/contracts/matrix.d.mts.map +1 -0
  29. package/esm/contracts/scry.d.mts +42 -0
  30. package/esm/contracts/scry.d.mts.map +1 -1
  31. package/esm/contracts/settings.d.mts +71 -0
  32. package/esm/contracts/settings.d.mts.map +1 -0
  33. package/esm/contracts/settings.mjs +67 -0
  34. package/esm/contracts/settings.mjs.map +1 -0
  35. package/esm/contracts/shots.d.mts +146 -0
  36. package/esm/contracts/shots.d.mts.map +1 -0
  37. package/esm/contracts/snapshot.d.mts +10 -0
  38. package/esm/contracts/snapshot.d.mts.map +1 -1
  39. package/esm/contracts/written.d.mts +13 -0
  40. package/esm/contracts/written.d.mts.map +1 -1
  41. package/esm/contracts/written.mjs +7 -1
  42. package/esm/contracts/written.mjs.map +1 -1
  43. package/esm/devtools/approvals.mjs +59 -0
  44. package/esm/devtools/approvals.mjs.map +1 -0
  45. package/esm/devtools/data.mjs +2 -0
  46. package/esm/devtools/data.mjs.map +1 -1
  47. package/esm/devtools/graphs.mjs +13 -3
  48. package/esm/devtools/graphs.mjs.map +1 -1
  49. package/esm/devtools/index.d.mts +7 -0
  50. package/esm/devtools/index.d.mts.map +1 -1
  51. package/esm/devtools/index.mjs +33 -3
  52. package/esm/devtools/index.mjs.map +1 -1
  53. package/esm/devtools/matrix.mjs +207 -0
  54. package/esm/devtools/matrix.mjs.map +1 -0
  55. package/esm/devtools/product-map.d.mts.map +1 -1
  56. package/esm/devtools/product-map.mjs +87 -1
  57. package/esm/devtools/product-map.mjs.map +1 -1
  58. package/esm/devtools/site.d.mts.map +1 -1
  59. package/esm/devtools/site.mjs +12 -3
  60. package/esm/devtools/site.mjs.map +1 -1
  61. package/esm/devtools/snapshot-source.mjs +13 -3
  62. package/esm/devtools/snapshot-source.mjs.map +1 -1
  63. package/esm/git/index.d.mts +20 -0
  64. package/esm/git/index.d.mts.map +1 -0
  65. package/esm/git/index.mjs +280 -0
  66. package/esm/git/index.mjs.map +1 -0
  67. package/esm/guard/api.mjs +70 -0
  68. package/esm/guard/api.mjs.map +1 -0
  69. package/esm/guard/assertions.mjs +18 -0
  70. package/esm/guard/assertions.mjs.map +1 -0
  71. package/esm/guard/collect.mjs +139 -0
  72. package/esm/guard/collect.mjs.map +1 -0
  73. package/esm/guard/format.mjs +27 -0
  74. package/esm/guard/format.mjs.map +1 -0
  75. package/esm/guard/glob.mjs +79 -0
  76. package/esm/guard/glob.mjs.map +1 -0
  77. package/esm/guard/index.mjs +9 -0
  78. package/esm/guard/rules.mjs +310 -0
  79. package/esm/guard/rules.mjs.map +1 -0
  80. package/esm/guard/scope.mjs +95 -0
  81. package/esm/guard/scope.mjs.map +1 -0
  82. package/esm/index.d.mts +10 -3
  83. package/esm/index.mjs +6 -2
  84. package/esm/paths/index.d.mts +15 -1
  85. package/esm/paths/index.d.mts.map +1 -1
  86. package/esm/paths/index.mjs +27 -3
  87. package/esm/paths/index.mjs.map +1 -1
  88. package/esm/proves/index.mjs +2 -1
  89. package/esm/proves/scan-proofs.mjs +1 -1
  90. package/esm/proves/scan-proofs.mjs.map +1 -1
  91. package/esm/proves/scan-shows.d.mts +21 -0
  92. package/esm/proves/scan-shows.d.mts.map +1 -0
  93. package/esm/proves/scan-shows.mjs +168 -0
  94. package/esm/proves/scan-shows.mjs.map +1 -0
  95. package/esm/releases/index.d.mts.map +1 -1
  96. package/esm/releases/index.mjs +5 -3
  97. package/esm/releases/index.mjs.map +1 -1
  98. package/esm/releases/stamp.mjs +121 -0
  99. package/esm/releases/stamp.mjs.map +1 -0
  100. package/esm/rules/focused.mjs +26 -0
  101. package/esm/rules/focused.mjs.map +1 -0
  102. package/esm/rules/index.mjs +88 -0
  103. package/esm/rules/index.mjs.map +1 -0
  104. package/esm/rules/logical-css.mjs +112 -0
  105. package/esm/rules/logical-css.mjs.map +1 -0
  106. package/esm/rules/no-js-imports.mjs +22 -0
  107. package/esm/rules/no-js-imports.mjs.map +1 -0
  108. package/esm/rules/scan.mjs +196 -0
  109. package/esm/rules/scan.mjs.map +1 -0
  110. package/esm/rules/specific-errors.mjs +51 -0
  111. package/esm/rules/specific-errors.mjs.map +1 -0
  112. package/esm/rules/type-discriminator.mjs +27 -0
  113. package/esm/rules/type-discriminator.mjs.map +1 -0
  114. package/esm/scry/also-changes.mjs +107 -0
  115. package/esm/scry/also-changes.mjs.map +1 -0
  116. package/esm/scry/format.d.mts.map +1 -1
  117. package/esm/scry/format.mjs +35 -0
  118. package/esm/scry/format.mjs.map +1 -1
  119. package/esm/scry/query.d.mts.map +1 -1
  120. package/esm/scry/query.mjs +40 -2
  121. package/esm/scry/query.mjs.map +1 -1
  122. package/esm/scry/search.d.mts.map +1 -1
  123. package/esm/scry/search.mjs +43 -11
  124. package/esm/scry/search.mjs.map +1 -1
  125. package/esm/shots/approve.mjs +195 -0
  126. package/esm/shots/approve.mjs.map +1 -0
  127. package/esm/shots/drift.mjs +174 -0
  128. package/esm/shots/drift.mjs.map +1 -0
  129. package/esm/shots/png.mjs +166 -0
  130. package/esm/shots/png.mjs.map +1 -0
  131. package/esm/shots/state.mjs +43 -0
  132. package/esm/shots/state.mjs.map +1 -0
  133. package/esm/shots/store.mjs +66 -0
  134. package/esm/shots/store.mjs.map +1 -0
  135. package/esm/shots/touched.mjs +38 -0
  136. package/esm/shots/touched.mjs.map +1 -0
  137. package/esm/warlock/adapter.d.mts.map +1 -1
  138. package/esm/warlock/adapter.mjs +22 -2
  139. package/esm/warlock/adapter.mjs.map +1 -1
  140. package/esm/warlock/api-command.mjs +41 -0
  141. package/esm/warlock/api-command.mjs.map +1 -0
  142. package/esm/warlock/approve-command.mjs +80 -0
  143. package/esm/warlock/approve-command.mjs.map +1 -0
  144. package/esm/warlock/collect-off-thread.mjs +66 -0
  145. package/esm/warlock/collect-off-thread.mjs.map +1 -0
  146. package/esm/warlock/commands.d.mts +1 -1
  147. package/esm/warlock/commands.d.mts.map +1 -1
  148. package/esm/warlock/commands.mjs +61 -8
  149. package/esm/warlock/commands.mjs.map +1 -1
  150. package/esm/warlock/guard-command.mjs +116 -0
  151. package/esm/warlock/guard-command.mjs.map +1 -0
  152. package/esm/warlock/index.d.mts +2 -1
  153. package/esm/warlock/index.mjs +2 -1
  154. package/esm/warlock/languages.mjs +75 -0
  155. package/esm/warlock/languages.mjs.map +1 -0
  156. package/esm/warlock/mcp-tools.mjs +2 -2
  157. package/esm/warlock/mcp-tools.mjs.map +1 -1
  158. package/esm/warlock/release-command.mjs +65 -0
  159. package/esm/warlock/release-command.mjs.map +1 -0
  160. package/esm/warlock/shows.d.mts +35 -0
  161. package/esm/warlock/shows.d.mts.map +1 -0
  162. package/esm/warlock/shows.mjs +195 -0
  163. package/esm/warlock/shows.mjs.map +1 -0
  164. package/esm/workspace/cache.mjs +4 -1
  165. package/esm/workspace/cache.mjs.map +1 -1
  166. package/esm/workspace/derived.mjs +11 -6
  167. package/esm/workspace/derived.mjs.map +1 -1
  168. package/esm/workspace/index.d.mts.map +1 -1
  169. package/esm/workspace/index.mjs +8 -1
  170. package/esm/workspace/index.mjs.map +1 -1
  171. package/esm/workspace/stored.mjs +4 -1
  172. package/esm/workspace/stored.mjs.map +1 -1
  173. package/esm/written/features.mjs +21 -5
  174. package/esm/written/features.mjs.map +1 -1
  175. package/esm/written/index.mjs +2 -1
  176. package/esm/written/parse-grimoire.d.mts.map +1 -1
  177. package/esm/written/parse-grimoire.mjs +16 -3
  178. package/esm/written/parse-grimoire.mjs.map +1 -1
  179. package/esm/written/settings.d.mts +11 -0
  180. package/esm/written/settings.d.mts.map +1 -0
  181. package/esm/written/settings.mjs +88 -0
  182. package/esm/written/settings.mjs.map +1 -0
  183. package/llms-full.txt +282 -39
  184. package/llms.txt +2 -0
  185. package/package.json +3 -3
  186. package/skills/backfill-a-grimoire/SKILL.md +4 -0
  187. package/skills/describe-an-app/SKILL.md +4 -1
  188. package/skills/guard-a-change/SKILL.md +85 -0
  189. package/skills/index.md +7 -3
  190. package/skills/record-a-change/SKILL.md +52 -16
  191. package/skills/review-a-change/SKILL.md +53 -0
  192. package/skills/use-the-grimoire/SKILL.md +27 -18
  193. package/skills/write-a-feature/SKILL.md +42 -1
  194. package/ui/grimoire-view.js +756 -40
  195. package/ui/grimoire.css +303 -28
  196. package/ui/product-map.css +43 -7
  197. package/ui/product-map.js +212 -37
package/CHANGELOG.md CHANGED
@@ -2,6 +2,67 @@
2
2
 
3
3
  `@warlock.js/grimoire` is new in 5.55.0 and experimental: its file layout, `GR` codes and API may change in any release until it is marked stable.
4
4
 
5
+ ## 5.65.0 - 2026-11-26
6
+
7
+ ### Added
8
+
9
+ - `warlock scry --search` (and the `grimoire_search` MCP tool) now folds the top file's impact into its answer: an `impact of <file>:` block with the importers not already listed (at most 8, with a `+n more` count) and the routes, flows and tests that reach it (at most 5 each). `--json` carries it as `impact`. One search answers "what changes with it" without a second `--impact` call; the `next:` line stays only when the answer has no impact block.
10
+ - The devtools panel takes a `warm` option to open the book ahead of the first tab view (default: on in development with the default adapter, off otherwise).
11
+
12
+ ### Changed
13
+
14
+ - Creating the devtools panel never scans the app. In production the book opens on the first tab view, from the stored book when it is current and built in memory otherwise; in development the optional warm-up starts after boot instead of during it.
15
+ - The source scan of a book build runs in a worker thread when the framework's tooling can be loaded there, so a large app keeps answering requests while the book builds.
16
+ - The `use-the-grimoire` skill and the MCP tool descriptions prefer the Grimoire MCP tools where a client supports them, and say the search answer already includes the impact list.
17
+
18
+ ### Fixed
19
+
20
+ - The Grimoire devtools tab no longer blocks the event loop for seconds at server start on large apps.
21
+
22
+ ## 5.64.0 - 2026-11-23
23
+
24
+ ### Added
25
+
26
+ - `warlock scry --search` answers with the files that change together with the top hits. After the hits it lists, as `changes with the top hits:`, the files the top three file-mapped hits import and the files that import them inside the same feature (the same module when unowned), the spec files that import them and the tests that prove a hit flow's criteria, most shared first, at most 10, then a `next: warlock scry --impact <file>` line. The search result gains `alsoChanges` (`ScryAlsoChange`: `file`, `reason`, `via`), `weak` and `next`. `grimoire_search` returns the same fields.
27
+ - A weak search answer. When the best hit is not a name match and holds fewer than half of the request's words, the answer ends with `weak match: no hit holds most of the request's words; use grep for literal text` and carries `weak: true`.
28
+ - `warlock grimoire release [version] --stamp [--date yyyy-mm-dd]` stamps the changelogs and collects. The version defaults to the app's `package.json` version and the date to the release file's date, else today. Each feature changelog with entries under `## Unreleased` gets them moved under `## <version> (<date>)` with an empty `## Unreleased` above, a missing `grimoire/releases/<version>.md` is written with a one-line brief naming the changed features, and the list is collected. `--json` prints `{ stamped, created, collect }`. It stops with `GR9006` for a missing version, a date that is not `yyyy-mm-dd`, or a version section with another date. This is the only edit Warlock makes to written files, and only with `--stamp`.
29
+ - `warlock grimoire guard [task] [--base <ref>] [--commits <range>] [--hook] [--json]` checks a change (the git diff against its base, including staged, unstaged and untracked files) against its task, without booting the app: `GR7006` a changed file outside the task's features, flow files, proving tests and `Files:` line; `GR7007` a flow, criterion or case removed without a `Removes:` line; `GR7008` a deleted `@proves` test; `GR7009` an edited `Locked:` test; `GR7010` a changed test with fewer assertions; `GR7011` a protected area the task does not name in `Touches:`; `GR7012` a commit of `--commits` that names no task; `GR9008` no task found; `GR9009` git could not answer. It prints the changes not approved without failing on them, exits 1 on an error, and in `--hook` mode writes to stderr and exits 2 on an error (0 when no task or no git repository is found, and when the hook input says the agent already went on once because of it, `stop_hook_active`, so the hook never keeps an agent going twice). The JSON report is the new `GuardReport` type.
30
+ - Tasks can carry `Files:`, `Features:`, `Locked:`, `Touches:` and `Removes:` body lines that the guard reads.
31
+ - Four code rules, `logical-css` (`GR3007`), `specific-errors` (`GR3008`), `type-discriminator` (`GR3009`) and `no-js-imports` (`GR3010`), over code, style and locale files, with the escape comment `grimoire-allow <rule>: <why>`. `grimoire check` runs the rules named in `rules:` of `grimoire/settings.md`; the guard runs all four on the lines a change adds when the key is absent.
32
+ - `grimoire check` reports a test focused with `.only` (`GR4011`) or skipped with `.skip` (`GR4012`, a warning); the guard raises both to errors when a change adds them.
33
+ - Protected areas (`DEFAULT_PROTECTED_AREAS`: migrations, auth, config, lockfile, dependencies, public API) change only when the task names them. `dependencies` fires only when a `package.json` adds or changes a dependency entry.
34
+ - `warlock grimoire approve api` writes the routes to `grimoire/approved/api.json`; `grimoire check` warns (`GR7013`) when the routes differ, and the guard reports `GR7011` for a change that does not name `public-api`.
35
+ - Skills `guard-a-change` and `review-a-change` (the reviewer gets the task and the diff, never the author's summary, and one question: "List every change the task did not ask for"); `write-a-feature` and `record-a-change` cover the new task fields, running the guard before you stop and listing every change that is not approved in the report.
36
+ - Guide "Drift controls" and the `guard` section of the commands guide.
37
+ - **Bird view tab.** One table of every feature, flow and criterion against the app's languages: the test status, the captured screenshot as a thumbnail, and the approval state of each cell, with a jump-to filter (`#grimoire/bird-view?q=AC-3`). A side-by-side panel compares the approved and the captured image and lists each change not approved, with Approve and Reject in development. It works with no screenshots and no baseline. The data is `GET /matrix` and the tab's count is `birdView` in the summary; the static export includes both, the share-safe export does not.
38
+ - **What's new.** `#grimoire/product/whats-new[/<release>]` and `GET /product/whats-new` list the releases newest first with their date, the first paragraph of the brief and the changes per feature in plain words; unreleased changes show only in the signed-in view. It is in the share routes and in both static exports.
39
+ - **Modules matrix.** Above 40 modules the Modules view opens on a matrix of the 20 most connected modules, with a Graph button; module nodes carry `title`, `group` and `files`.
40
+ - `@shows` scenes: a browser test shows a criterion with `// @shows <feature>/<flow> AC-n` above `shows(context, "<feature>/<flow> AC-n", scene)` (new `shows()` in `@warlock.js/grimoire/warlock`). The scene runs once per language and saves one screenshot each under `grimoire/screenshots/captured/`; a failing language is recorded and `shows()` throws after every language ran. `changed` (default), `all` and `off` modes, `GRIMOIRE_SHOTS` for one run, and `screenshots: false` in a flow's front matter to opt out.
41
+ - `grimoire/settings.md` (languages, screenshot mode, code rules, protected areas) is read and every snapshot carries `settings`; languages fall back to the adapter's `languages()`, which the Warlock adapter reads from `app.localeCodes` without booting the app.
42
+ - The approved baseline: changes since `grimoire/approved/baseline.json` (images, flows, criteria, cases, proving tests) show as "changed, not approved". `warlock grimoire approve <id|feature/flow>` / `reject <target>` (`--all`, `--lang`, `--note`, `--json`) and the tab's buttons write it; `approve --all` creates it.
43
+ - Check codes `GR4013` to `GR4019` for `@shows` lines, missing and failed captures, drift and rejected changes that are still there; `GR9010` for an approve or reject target nothing matches.
44
+ - Flows with a `page` step answer two more case questions, `server unreachable` and `server error` (`UI_CASE_QUESTIONS`); `GR1012` asks for them there and nowhere else.
45
+ - Skills teach the `design-system` feature first, `@shows` scenes, `screenshots: false` and approvals. New guide: Screenshots and approvals.
46
+
47
+ ### Changed
48
+
49
+ - `warlock scry --search` reads Arabic and accented Latin text. One tokeniser serves the query, the index and the `GR9006` check: accents and Arabic vowel marks are dropped, the tatweel is dropped, `ى` is read as `ي` and `ة` as `ه`, words split at every non-letter and non-digit in any script, camel case splits in any script, an Arabic word of five or more letters loses a leading `ال`, `وال`, `بال` or `لل`, and a few Arabic small words join `SCRY_STOP_WORDS`. `شحنة` finds `الشحنة`, `cafe` finds `café`, and an Arabic-only query no longer stops with `GR9006`. Stemming stays Latin only; `AC-5` stays one word.
50
+ - Search ranks spec, locale and type files below code: their BM25F score is multiplied by 0.6.
51
+ - The `use-the-grimoire` skill and the `grimoire_search` and `grimoire_impact` tool descriptions tell agents to search first, then run `--impact` on the top hit and read the `changes with` lines, and to use grep only for literal text or after a weak match.
52
+ - **Product map wording.** "Where you see it" lists a page once with its blocks under it and heads each app with its title; the flow line shows the audience without "For"; every case is a plain question, including "What if the server cannot be reached?" and "What if the server fails?"; "What changed" and "Checked by" no longer show criterion or task ids.
53
+ - **Overview task count.** The Tasks tile counts every open task, the same as the tab badge, and reads "N open, M of them waiting for approval".
54
+ - **Modules graph.** Labels are cut from the right with the full name in the node's tooltip, sites and mobile roots sit on their own ring, and a module over 500 files shows its file count.
55
+ - **Feature page.** The neighbour graph sits above the flows.
56
+ - **Phone width.** Under 640 px the tab bar wraps onto rows so no tab is hidden, and a group of more than 6 pages on the Apps page starts closed.
57
+ - **Logical CSS.** The tab's stylesheets use logical properties (`inline-start`, `inline-end`, `text-align: start`), so they mirror in right-to-left layouts.
58
+ - The devtools snapshot source and the stored open keep `settings` and `shots`, and serve a fresh snapshot after an approval or a new capture. Snapshots written by an earlier version are rebuilt once.
59
+
60
+ ### Fixed
61
+
62
+ - `warlock grimoire build`, `grimoire check` and `inspect` go on when the app's config or bootstrap fails during the command's preload, so `build` and `check` reach the cached-routes fallback (`GR8002`) instead of exiting first.
63
+ - The book lists the code files at the top of a mobile app folder (`App.tsx`, `index.ts`); tool configs (`babel.config.js`) and type shims (`*.d.ts`) stay out.
64
+ - Editing only a top-level file of a mobile app folder (`App.tsx`, `index.ts`) now marks the book stale. The freshness fingerprint also covers the code files that sit directly in the parent folder of a nested source root, without tool configs and type shims.
65
+
5
66
  ## 5.63.0 - 2026-11-22
6
67
 
7
68
  ### Added
@@ -1 +1 @@
1
- {"version":3,"file":"build.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/build.ts"],"mappings":";;;;;;;;;wBA8TsB,UACpB,cACA,SAAS,aACT,UAAS,mBACR,QAAQ;;wBAiMW,SAAS,eAAe,QAAQ;;YAgB1C;;EAEV,MAAM;;EAEN;;;;;;;;;;;wBAYoB,UAAU,cAAc,SAAS,cAAc,QAAQ"}
1
+ {"version":3,"file":"build.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/build.ts"],"mappings":";;;;;;;;;wBAiXsB,UACpB,cACA,SAAS,aACT,UAAS,mBACR,QAAQ;;wBAiMW,SAAS,eAAe,QAAQ;;YAgB1C;;EAEV,MAAM;;EAEN;;;;;;;;;;;wBAYoB,UAAU,cAAc,SAAS,cAAc,QAAQ"}
@@ -6,7 +6,7 @@ import { cleanFolder, hashFile, hashIfExists, isMissing, listFiles, mapLimit, re
6
6
  import { cleanPath, normalizeFiles, normalizeMobile, normalizeNamed, normalizePages, normalizeRoutes, normalizeSites } from "./normalize.mjs";
7
7
  import { entryPathsFor } from "./render.mjs";
8
8
  import path from "node:path";
9
- import { rm, stat } from "node:fs/promises";
9
+ import { readdir, rm, stat } from "node:fs/promises";
10
10
  import { readFileSync } from "node:fs";
11
11
 
12
12
  //#region ../../packages/grimoire/src/book/build.ts
@@ -38,11 +38,33 @@ async function readStoredBook(root) {
38
38
  facts: cache.facts
39
39
  };
40
40
  }
41
+ /**
42
+ * Code files that sit directly in the parent folder of a nested source root
43
+ * (a mobile app's `App.tsx` next to its `src` folder), which a folder walk of
44
+ * the roots never lists. Tool configs, type shims and dot files are left out.
45
+ * The project root itself is never scanned.
46
+ */
47
+ async function listTopFiles(root, sourceRoots) {
48
+ const parents = /* @__PURE__ */ new Set();
49
+ for (const folder of sourceRoots) {
50
+ const parent = path.posix.dirname(folder);
51
+ if (parent === "." || parent === "/" || sourceRoots.some((item) => item === "." || isInsideFolder(parent, item))) continue;
52
+ parents.add(parent);
53
+ }
54
+ const found = [];
55
+ for (const parent of parents) try {
56
+ const entries = await readdir(path.join(root, ...parent.split("/")), { withFileTypes: true });
57
+ for (const entry of entries) if (entry.isFile() && !entry.name.startsWith(".") && isCodeFile(entry.name) && !entry.name.endsWith(".d.ts") && !/\.config\.[^.]+$/.test(entry.name)) found.push(`${parent}/${entry.name}`);
58
+ } catch (error) {
59
+ if (!isMissing(error)) throw error;
60
+ }
61
+ return found.sort();
62
+ }
41
63
  /** Stat every code file; hash only those whose size or mtime differ from the previous manifest. */
42
64
  async function scanSourceRoots(root, sourceRoots, previous) {
43
65
  let files;
44
66
  try {
45
- files = (await listFiles(root, sourceRoots)).filter(isCodeFile);
67
+ files = [...(await listFiles(root, sourceRoots)).filter(isCodeFile), ...await listTopFiles(root, sourceRoots)];
46
68
  } catch (error) {
47
69
  throw new GrimoireError("GR8001", `The source roots could not be read: ${error.message}`);
48
70
  }
@@ -1 +1 @@
1
- {"version":3,"file":"build.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/build.ts"],"sourcesContent":["/**\n * `buildBook` and `loadBook`: the freshness fingerprint, the facts cache and\n * the route (boot) cache. Entries are written by `writeBook` (write.ts).\n */\nimport { readFileSync } from \"node:fs\";\nimport { rm, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { BookAdapter, BookFacts, BookFile } from \"../contracts/adapter\";\nimport {\n BOOK_SCHEMA_VERSION,\n type BookFactsCache,\n type BookManifest,\n type BookManifestFile,\n type BuildBookOptions,\n type BuildBookResult,\n type LoadedBook,\n} from \"../contracts/book\";\nimport type { RouteFreshness } from \"../contracts/findings\";\nimport { GrimoireError } from \"../codes\";\nimport { importClosure, fileGraph } from \"../graph\";\nimport { GRIMOIRE_PATHS, isCodeFile, isInsideFolder } from \"../paths\";\nimport {\n cleanFolder,\n hashFile,\n hashIfExists,\n IO_CONCURRENCY,\n isMissing,\n listFiles,\n mapLimit,\n readJson,\n toJson,\n writeBookFile,\n} from \"./io\";\nimport {\n cleanPath,\n normalizeFiles,\n normalizeMobile,\n normalizeNamed,\n normalizePages,\n normalizeRoutes,\n normalizeSites,\n} from \"./normalize\";\nimport { entryPathsFor } from \"./render\";\n\n/** Where `writeBook` remembers what it wrote (see write.ts). */\nexport const WRITE_STATE_PATH = `${GRIMOIRE_PATHS.book}/.cache/written.json`;\n\nlet cachedVersion: string | null = null;\n\n/** The `@warlock.js/grimoire` version, from its package.json. */\nexport function grimoireVersion(): string {\n if (cachedVersion !== null) return cachedVersion;\n\n try {\n const manifest = JSON.parse(\n readFileSync(new URL(\"../../package.json\", import.meta.url), \"utf8\"),\n ) as {\n version?: unknown;\n };\n cachedVersion = typeof manifest.version === \"string\" ? manifest.version : \"0.0.0\";\n } catch {\n cachedVersion = \"0.0.0\";\n }\n\n return cachedVersion;\n}\n\nconst absolutePath = (root: string, file: string): string => path.join(root, ...file.split(\"/\"));\n\ntype StoredBook = { manifest: BookManifest; facts: BookFacts };\n\n/**\n * `facts.json` as written since type-only import edges were recorded. A cache\n * without the marker comes from an older version: it is not reused, so file\n * facts are scanned once more.\n */\ntype StoredFactsCache = BookFactsCache & { typeOnlyEdges?: boolean };\n\nasync function readStoredBook(root: string): Promise<StoredBook | null> {\n const manifest = await readJson<BookManifest>(absolutePath(root, GRIMOIRE_PATHS.bookManifest));\n const cache = await readJson<StoredFactsCache>(absolutePath(root, GRIMOIRE_PATHS.bookFactsCache));\n\n if (\n manifest === null ||\n cache === null ||\n manifest.schemaVersion !== BOOK_SCHEMA_VERSION ||\n cache.schemaVersion !== BOOK_SCHEMA_VERSION ||\n cache.typeOnlyEdges !== true ||\n typeof manifest.files !== \"object\" ||\n typeof cache.facts !== \"object\"\n ) {\n return null;\n }\n\n return { manifest, facts: cache.facts };\n}\n\n/** The current state of every code file under the source roots (images, fonts and certificates are not part of the book). */\ntype Scan = {\n files: Record<string, Omit<BookManifestFile, \"entry\">>;\n /** A file kept its hash but its size or mtime moved: the manifest needs the new stat. */\n statMoved: boolean;\n};\n\n/** Stat every code file; hash only those whose size or mtime differ from the previous manifest. */\nasync function scanSourceRoots(\n root: string,\n sourceRoots: readonly string[],\n previous: Record<string, BookManifestFile>,\n): Promise<Scan> {\n let files: string[];\n\n try {\n files = (await listFiles(root, sourceRoots)).filter(isCodeFile);\n } catch (error) {\n throw new GrimoireError(\n \"GR8001\",\n `The source roots could not be read: ${(error as Error).message}`,\n );\n }\n\n let statMoved = false;\n const states = await mapLimit(files, IO_CONCURRENCY, async (file) => {\n const absolute = absolutePath(root, file);\n\n try {\n const info = await stat(absolute);\n const before = previous[file];\n\n if (before !== undefined && before.size === info.size && before.mtimeMs === info.mtimeMs) {\n return { file, hash: before.hash, size: info.size, mtimeMs: info.mtimeMs };\n }\n\n const hash = await hashFile(absolute, info.size);\n\n if (before !== undefined && before.hash === hash) statMoved = true;\n\n return { file, hash, size: info.size, mtimeMs: info.mtimeMs };\n } catch (error) {\n // Deleted between the walk and the stat: treat it as gone.\n if (isMissing(error)) return null;\n throw new GrimoireError(\"GR8001\", `${file} could not be read: ${(error as Error).message}`);\n }\n });\n const result: Scan[\"files\"] = {};\n\n for (const state of states) {\n if (state !== null)\n result[state.file] = { hash: state.hash, size: state.size, mtimeMs: state.mtimeMs };\n }\n\n return { files: result, statMoved };\n}\n\n/** Hashes of the given files: from the scan when inside the source roots, else read (`\"\"` when missing). */\nasync function hashFiles(\n root: string,\n files: readonly string[],\n scan: Scan[\"files\"],\n sourceRoots: readonly string[],\n): Promise<Record<string, string>> {\n const hashes = await mapLimit([...new Set(files)].sort(), IO_CONCURRENCY, async (file) => {\n const scanned = scan[file];\n\n if (scanned !== undefined) return [file, scanned.hash] as const;\n // A code file inside a source root that the scan did not find is gone; any other input (a JSON config) is read.\n if (\n isCodeFile(file) &&\n sourceRoots.some((folder) => folder === \".\" || isInsideFolder(file, folder))\n )\n return [file, \"\"] as const;\n\n return [file, await hashIfExists(root, file)] as const;\n });\n\n return Object.fromEntries(hashes);\n}\n\nfunction sameRecord(left: Record<string, string>, right: Record<string, string>): boolean {\n const leftKeys = Object.keys(left);\n\n return (\n leftKeys.length === Object.keys(right).length &&\n leftKeys.every((key) => right[key] === left[key])\n );\n}\n\n/** Source files added, changed or removed between two manifests, sorted. */\nfunction changedFiles(\n previous: Record<string, BookManifestFile>,\n current: Scan[\"files\"],\n): string[] {\n const changed: string[] = [];\n\n for (const [file, state] of Object.entries(current)) {\n if (previous[file]?.hash !== state.hash) changed.push(file);\n }\n\n for (const file of Object.keys(previous)) {\n if (current[file] === undefined) changed.push(file);\n }\n\n return changed.sort();\n}\n\nconst NAMED_FILE_TYPES = new Set([\"mail\", \"job\", \"event\"]);\n\n/**\n * Files whose change makes the route cache stale: every `routes` file and\n * everything it imports, every `config` file, `warlock.config.ts`,\n * `package.json`, and every mail, job, event and notification file (the\n * named things are cached with the routes).\n */\nexport function defaultRouteInputs(files: readonly BookFile[]): string[] {\n const routesFiles = files.filter((file) => file.type === \"routes\").map((file) => file.file);\n const inputs = new Set(importClosure(fileGraph(files), routesFiles));\n\n for (const file of files) {\n if (\n file.type === \"config\" ||\n NAMED_FILE_TYPES.has(file.type) ||\n /\\.notification\\.[^/]+$/.test(file.file)\n ) {\n inputs.add(file.file);\n }\n }\n\n inputs.add(\"warlock.config.ts\");\n inputs.add(\"package.json\");\n\n return [...inputs].sort();\n}\n\n/** The route cache's input files: the adapter's list when it has one, else the default. */\nasync function routeInputFiles(\n root: string,\n adapter: BookAdapter,\n files: readonly BookFile[],\n): Promise<string[]> {\n return adapter.routeInputs\n ? (await adapter.routeInputs(root, files)).map(cleanPath)\n : defaultRouteInputs(files);\n}\n\nconst hasBootFacts = (adapter: BookAdapter): boolean =>\n typeof adapter.routes === \"function\" || typeof adapter.named === \"function\";\n\nasync function collectBootFacts(\n root: string,\n adapter: BookAdapter,\n): Promise<Pick<BookFacts, \"routes\" | \"named\">> {\n try {\n return {\n routes: adapter.routes ? normalizeRoutes(await adapter.routes(root)) : null,\n named: adapter.named ? normalizeNamed(await adapter.named(root)) : [],\n };\n } catch (error) {\n if (error instanceof GrimoireError) throw error;\n throw new GrimoireError(\"GR8002\", `Route facts could not be read: ${(error as Error).message}`);\n }\n}\n\n/** How the stored route facts relate to the current inputs. */\nfunction bootState(\n boot: BookManifest[\"boot\"],\n routes: BookFacts[\"routes\"],\n inputs: Record<string, string>,\n): \"fresh\" | \"stale\" | \"missing\" {\n if (boot.collectedAt === null || routes === null) return \"missing\";\n\n return sameRecord(boot.inputs, inputs) ? \"fresh\" : \"stale\";\n}\n\n/**\n * A fresh read that found under half the routes the book already holds is not trusted over the stored list,\n * unless the build was forced (`warlock grimoire build --force`): that is how a real removal is accepted.\n */\nfunction shrankTooFar(\n stored: BookFacts[\"routes\"],\n read: BookFacts[\"routes\"],\n force: boolean,\n): boolean {\n return (\n !force &&\n stored !== null &&\n read !== null &&\n stored.length > 0 &&\n read.length * 2 < stored.length\n );\n}\n\nconst shrankNote = (kept: number, read: number): string =>\n `a live read found ${read} routes against the ${kept} stored; kept the stored routes; run warlock grimoire build again, or warlock grimoire build --force when the routes were removed`;\n\nasync function writeStoredBook(\n root: string,\n manifest: BookManifest,\n facts: BookFacts | null,\n): Promise<void> {\n if (facts !== null) {\n const cache: StoredFactsCache = {\n schemaVersion: BOOK_SCHEMA_VERSION,\n typeOnlyEdges: true,\n facts,\n };\n await writeBookFile(root, GRIMOIRE_PATHS.bookFactsCache, toJson(cache));\n }\n\n // The manifest last: a reader that sees it also sees the facts it describes.\n await writeBookFile(root, GRIMOIRE_PATHS.bookManifest, toJson(manifest));\n}\n\n/**\n * Bring the book's facts up to date and write `manifest.json` and\n * `.cache/facts.json`. Does not write entries (see `writeBook`).\n *\n * @param root Absolute project root.\n */\nexport async function buildBook(\n root: string,\n adapter: BookAdapter,\n options: BuildBookOptions = {},\n): Promise<BuildBookResult> {\n const projectRoot = path.resolve(root);\n const mode = options.routes ?? \"cached\";\n const now = options.now ?? (() => new Date());\n // `write: false` (passed by `openGrimoire({ write: false })`) computes in memory only.\n const write = options.write !== false;\n const sourceRoots = [\n ...new Set((await adapter.sourceRoots(projectRoot)).map(cleanFolder)),\n ].sort();\n const stored = await readStoredBook(projectRoot);\n const previousFiles = stored?.manifest.files ?? {};\n const scan = await scanSourceRoots(projectRoot, sourceRoots, previousFiles);\n const version = grimoireVersion();\n\n // ── The fast path: nothing under the source roots (or the tests) changed. ──\n if (stored !== null && options.force !== true) {\n const { manifest, facts } = stored;\n const sameSetup =\n manifest.grimoireVersion === version &&\n manifest.adapter.name === adapter.name &&\n manifest.adapter.version === adapter.version &&\n manifest.sourceRoots.length === sourceRoots.length &&\n manifest.sourceRoots.every((folder, index) => folder === sourceRoots[index]);\n const sameFiles =\n sameSetup &&\n Object.keys(previousFiles).length === Object.keys(scan.files).length &&\n Object.entries(scan.files).every(([file, state]) => previousFiles[file]?.hash === state.hash);\n const sameTests =\n sameFiles &&\n sameRecord(\n manifest.tests,\n await hashFiles(projectRoot, Object.keys(manifest.tests), scan.files, sourceRoots),\n );\n\n if (sameTests) {\n const inputs = await hashFiles(\n projectRoot,\n Object.keys(manifest.boot.inputs),\n scan.files,\n sourceRoots,\n );\n let routes: RouteFreshness = hasBootFacts(adapter)\n ? bootState(manifest.boot, facts.routes, inputs)\n : \"missing\";\n let changedBook = false;\n let routeNote: string | undefined;\n\n if (mode === \"fresh\" && hasBootFacts(adapter) && routes !== \"fresh\") {\n // The stored input list can be older than the files (a cached rebuild keeps it): work it out again.\n const current = await hashFiles(\n projectRoot,\n await routeInputFiles(projectRoot, adapter, facts.files),\n scan.files,\n sourceRoots,\n );\n const read = await collectBootFacts(projectRoot, adapter);\n\n if (shrankTooFar(facts.routes, read.routes, false)) {\n routeNote = shrankNote(facts.routes?.length ?? 0, read.routes?.length ?? 0);\n routes = \"stale\";\n } else {\n Object.assign(facts, read);\n manifest.boot = {\n collectedAt: now().toISOString(),\n inputs: current,\n counts: { routes: read.routes?.length ?? 0, pages: facts.pages.length },\n };\n routes = \"fresh\";\n changedBook = true;\n }\n }\n\n if (changedBook || scan.statMoved) {\n for (const [file, state] of Object.entries(scan.files)) {\n manifest.files[file] = { ...state, entry: manifest.files[file]?.entry ?? null };\n }\n\n if (changedBook) manifest.builtAt = now().toISOString();\n\n if (write) await writeStoredBook(projectRoot, manifest, changedBook ? facts : null);\n }\n\n return {\n book: { root: projectRoot, manifest, facts, routes, ...(routeNote ? { routeNote } : {}) },\n rebuilt: changedBook,\n changed: [],\n };\n }\n }\n\n // ── Rebuild the static facts. ──\n let files: BookFile[];\n\n try {\n files = normalizeFiles(await adapter.files(projectRoot));\n } catch (error) {\n if (error instanceof GrimoireError) throw error;\n throw new GrimoireError(\n \"GR8001\",\n `The source files could not be read: ${(error as Error).message}`,\n );\n }\n\n let staticFacts: Omit<BookFacts, \"files\" | \"routes\" | \"named\">;\n\n try {\n staticFacts = {\n sites: adapter.sites ? normalizeSites(await adapter.sites(projectRoot)) : [],\n pages: adapter.pages ? normalizePages(await adapter.pages(projectRoot)) : [],\n mobile: adapter.mobile ? normalizeMobile(await adapter.mobile(projectRoot)) : [],\n tests: adapter.tests\n ? (await adapter.tests(projectRoot)).map(cleanPath)\n : files.filter((file) => file.type === \"spec\").map((file) => file.file),\n };\n } catch (error) {\n if (error instanceof GrimoireError) throw error;\n throw new GrimoireError(\n \"GR8004\",\n `Pages or screens could not be read: ${(error as Error).message}`,\n );\n }\n\n staticFacts.tests = [...new Set(staticFacts.tests)].sort();\n\n const inputs = await hashFiles(\n projectRoot,\n await routeInputFiles(projectRoot, adapter, files),\n scan.files,\n sourceRoots,\n );\n const previousBoot = stored?.manifest.boot ?? { collectedAt: null, inputs: {} };\n let boot = previousBoot;\n let routeNote: string | undefined;\n let bootFacts: Pick<BookFacts, \"routes\" | \"named\"> = {\n routes: stored?.facts.routes ?? null,\n named: stored?.facts.named ?? [],\n };\n let routes: RouteFreshness = hasBootFacts(adapter)\n ? bootState(previousBoot, bootFacts.routes, inputs)\n : \"missing\";\n\n if (mode === \"fresh\" && hasBootFacts(adapter) && (routes !== \"fresh\" || options.force === true)) {\n const read = await collectBootFacts(projectRoot, adapter);\n\n if (shrankTooFar(bootFacts.routes, read.routes, options.force === true)) {\n routeNote = shrankNote(bootFacts.routes?.length ?? 0, read.routes?.length ?? 0);\n routes = \"stale\";\n } else {\n bootFacts = read;\n boot = {\n collectedAt: now().toISOString(),\n inputs,\n counts: { routes: read.routes?.length ?? 0, pages: staticFacts.pages.length },\n };\n routes = \"fresh\";\n }\n }\n\n const facts: BookFacts = { files, ...bootFacts, ...staticFacts };\n const entries = entryPathsFor(facts);\n const manifest: BookManifest = {\n schemaVersion: BOOK_SCHEMA_VERSION,\n grimoireVersion: version,\n adapter: { name: adapter.name, version: adapter.version },\n builtAt: now().toISOString(),\n sourceRoots,\n files: Object.fromEntries(\n Object.entries(scan.files).map(([file, state]) => [\n file,\n { ...state, entry: entries.get(file) ?? null },\n ]),\n ),\n tests: await hashFiles(projectRoot, facts.tests, scan.files, sourceRoots),\n writtenHash: stored?.manifest.writtenHash ?? \"\",\n boot,\n };\n\n // A forced build rewrites every entry: forget what `writeBook` wrote.\n if (write) {\n if (options.force === true)\n await rm(absolutePath(projectRoot, WRITE_STATE_PATH), { force: true });\n\n await writeStoredBook(projectRoot, manifest, facts);\n }\n\n return {\n book: { root: projectRoot, manifest, facts, routes, ...(routeNote ? { routeNote } : {}) },\n rebuilt: true,\n changed: changedFiles(previousFiles, scan.files),\n };\n}\n\n/** Read the book from disk without calling an adapter; `null` when it was never built. */\nexport async function loadBook(root: string): Promise<LoadedBook | null> {\n const projectRoot = path.resolve(root);\n const stored = await readStoredBook(projectRoot);\n\n if (stored === null) return null;\n\n return {\n root: projectRoot,\n manifest: stored.manifest,\n facts: stored.facts,\n // Not checked against the sources here; `buildBook` tells fresh from stale.\n routes: stored.facts.routes === null ? \"missing\" : \"cached\",\n };\n}\n\n/** What `checkBook` found: the stored book, and how far the files have moved from it. */\nexport type BookCheck = {\n /** The stored book, with its route freshness measured against the files as they are now. */\n book: LoadedBook;\n /** Code and test files added, changed or removed since the last build, sorted. */\n changed: string[];\n};\n\n/**\n * The cheap change check of `buildBook` with nothing rebuilt and nothing\n * written: scans the source roots (hashing only files whose size or time\n * moved) and compares them, and the tests, with the manifest. The adapter is\n * asked for its source roots only, never for files or route facts. `null`\n * when the book was never built (or was written by an older schema).\n *\n * @param root Absolute project root.\n */\nexport async function checkBook(root: string, adapter: BookAdapter): Promise<BookCheck | null> {\n const projectRoot = path.resolve(root);\n const stored = await readStoredBook(projectRoot);\n\n if (stored === null) return null;\n\n const { manifest, facts } = stored;\n const sourceRoots = [\n ...new Set((await adapter.sourceRoots(projectRoot)).map(cleanFolder)),\n ].sort();\n const scan = await scanSourceRoots(projectRoot, sourceRoots, manifest.files);\n const changed = new Set(changedFiles(manifest.files, scan.files));\n const tests = await hashFiles(projectRoot, Object.keys(manifest.tests), scan.files, sourceRoots);\n\n for (const [file, hash] of Object.entries(tests)) {\n if (manifest.tests[file] !== hash) changed.add(file);\n }\n\n const inputs = await hashFiles(\n projectRoot,\n Object.keys(manifest.boot.inputs),\n scan.files,\n sourceRoots,\n );\n const routes: RouteFreshness = hasBootFacts(adapter)\n ? bootState(manifest.boot, facts.routes, inputs)\n : \"missing\";\n\n return {\n book: { root: projectRoot, manifest, facts, routes },\n changed: [...changed].sort(),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6CA,MAAa,mBAAmB,GAAG,eAAe,KAAK;AAEvD,IAAI,gBAA+B;;AAGnC,SAAgB,kBAA0B;CACxC,IAAI,kBAAkB,MAAM,OAAO;CAEnC,IAAI;EACF,MAAM,WAAW,KAAK,MACpB,aAAa,IAAI,IAAI,sBAAsB,YAAY,G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AAC,CAAC,KAAK;CAC7B;AACF"}
1
+ {"version":3,"file":"build.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/build.ts"],"sourcesContent":["/**\n * `buildBook` and `loadBook`: the freshness fingerprint, the facts cache and\n * the route (boot) cache. Entries are written by `writeBook` (write.ts).\n */\nimport { readFileSync } from \"node:fs\";\nimport { readdir, rm, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { BookAdapter, BookFacts, BookFile } from \"../contracts/adapter\";\nimport {\n BOOK_SCHEMA_VERSION,\n type BookFactsCache,\n type BookManifest,\n type BookManifestFile,\n type BuildBookOptions,\n type BuildBookResult,\n type LoadedBook,\n} from \"../contracts/book\";\nimport type { RouteFreshness } from \"../contracts/findings\";\nimport { GrimoireError } from \"../codes\";\nimport { importClosure, fileGraph } from \"../graph\";\nimport { GRIMOIRE_PATHS, isCodeFile, isInsideFolder } from \"../paths\";\nimport {\n cleanFolder,\n hashFile,\n hashIfExists,\n IO_CONCURRENCY,\n isMissing,\n listFiles,\n mapLimit,\n readJson,\n toJson,\n writeBookFile,\n} from \"./io\";\nimport {\n cleanPath,\n normalizeFiles,\n normalizeMobile,\n normalizeNamed,\n normalizePages,\n normalizeRoutes,\n normalizeSites,\n} from \"./normalize\";\nimport { entryPathsFor } from \"./render\";\n\n/** Where `writeBook` remembers what it wrote (see write.ts). */\nexport const WRITE_STATE_PATH = `${GRIMOIRE_PATHS.book}/.cache/written.json`;\n\nlet cachedVersion: string | null = null;\n\n/** The `@warlock.js/grimoire` version, from its package.json. */\nexport function grimoireVersion(): string {\n if (cachedVersion !== null) return cachedVersion;\n\n try {\n const manifest = JSON.parse(\n readFileSync(new URL(\"../../package.json\", import.meta.url), \"utf8\"),\n ) as {\n version?: unknown;\n };\n cachedVersion = typeof manifest.version === \"string\" ? manifest.version : \"0.0.0\";\n } catch {\n cachedVersion = \"0.0.0\";\n }\n\n return cachedVersion;\n}\n\nconst absolutePath = (root: string, file: string): string => path.join(root, ...file.split(\"/\"));\n\ntype StoredBook = { manifest: BookManifest; facts: BookFacts };\n\n/**\n * `facts.json` as written since type-only import edges were recorded. A cache\n * without the marker comes from an older version: it is not reused, so file\n * facts are scanned once more.\n */\ntype StoredFactsCache = BookFactsCache & { typeOnlyEdges?: boolean };\n\nasync function readStoredBook(root: string): Promise<StoredBook | null> {\n const manifest = await readJson<BookManifest>(absolutePath(root, GRIMOIRE_PATHS.bookManifest));\n const cache = await readJson<StoredFactsCache>(absolutePath(root, GRIMOIRE_PATHS.bookFactsCache));\n\n if (\n manifest === null ||\n cache === null ||\n manifest.schemaVersion !== BOOK_SCHEMA_VERSION ||\n cache.schemaVersion !== BOOK_SCHEMA_VERSION ||\n cache.typeOnlyEdges !== true ||\n typeof manifest.files !== \"object\" ||\n typeof cache.facts !== \"object\"\n ) {\n return null;\n }\n\n return { manifest, facts: cache.facts };\n}\n\n/** The current state of every code file under the source roots (images, fonts and certificates are not part of the book). */\ntype Scan = {\n files: Record<string, Omit<BookManifestFile, \"entry\">>;\n /** A file kept its hash but its size or mtime moved: the manifest needs the new stat. */\n statMoved: boolean;\n};\n\n/**\n * Code files that sit directly in the parent folder of a nested source root\n * (a mobile app's `App.tsx` next to its `src` folder), which a folder walk of\n * the roots never lists. Tool configs, type shims and dot files are left out.\n * The project root itself is never scanned.\n */\nasync function listTopFiles(root: string, sourceRoots: readonly string[]): Promise<string[]> {\n const parents = new Set<string>();\n\n for (const folder of sourceRoots) {\n const parent = path.posix.dirname(folder);\n\n if (\n parent === \".\" ||\n parent === \"/\" ||\n sourceRoots.some((item) => item === \".\" || isInsideFolder(parent, item))\n ) {\n continue;\n }\n\n parents.add(parent);\n }\n\n const found: string[] = [];\n\n for (const parent of parents) {\n try {\n const entries = await readdir(path.join(root, ...parent.split(\"/\")), { withFileTypes: true });\n\n for (const entry of entries) {\n if (\n entry.isFile() &&\n !entry.name.startsWith(\".\") &&\n isCodeFile(entry.name) &&\n !entry.name.endsWith(\".d.ts\") &&\n !/\\.config\\.[^.]+$/.test(entry.name)\n ) {\n found.push(`${parent}/${entry.name}`);\n }\n }\n } catch (error) {\n if (!isMissing(error)) throw error;\n }\n }\n\n return found.sort();\n}\n\n/** Stat every code file; hash only those whose size or mtime differ from the previous manifest. */\nasync function scanSourceRoots(\n root: string,\n sourceRoots: readonly string[],\n previous: Record<string, BookManifestFile>,\n): Promise<Scan> {\n let files: string[];\n\n try {\n files = [\n ...(await listFiles(root, sourceRoots)).filter(isCodeFile),\n ...(await listTopFiles(root, sourceRoots)),\n ];\n } catch (error) {\n throw new GrimoireError(\n \"GR8001\",\n `The source roots could not be read: ${(error as Error).message}`,\n );\n }\n\n let statMoved = false;\n const states = await mapLimit(files, IO_CONCURRENCY, async (file) => {\n const absolute = absolutePath(root, file);\n\n try {\n const info = await stat(absolute);\n const before = previous[file];\n\n if (before !== undefined && before.size === info.size && before.mtimeMs === info.mtimeMs) {\n return { file, hash: before.hash, size: info.size, mtimeMs: info.mtimeMs };\n }\n\n const hash = await hashFile(absolute, info.size);\n\n if (before !== undefined && before.hash === hash) statMoved = true;\n\n return { file, hash, size: info.size, mtimeMs: info.mtimeMs };\n } catch (error) {\n // Deleted between the walk and the stat: treat it as gone.\n if (isMissing(error)) return null;\n throw new GrimoireError(\"GR8001\", `${file} could not be read: ${(error as Error).message}`);\n }\n });\n const result: Scan[\"files\"] = {};\n\n for (const state of states) {\n if (state !== null)\n result[state.file] = { hash: state.hash, size: state.size, mtimeMs: state.mtimeMs };\n }\n\n return { files: result, statMoved };\n}\n\n/** Hashes of the given files: from the scan when inside the source roots, else read (`\"\"` when missing). */\nasync function hashFiles(\n root: string,\n files: readonly string[],\n scan: Scan[\"files\"],\n sourceRoots: readonly string[],\n): Promise<Record<string, string>> {\n const hashes = await mapLimit([...new Set(files)].sort(), IO_CONCURRENCY, async (file) => {\n const scanned = scan[file];\n\n if (scanned !== undefined) return [file, scanned.hash] as const;\n // A code file inside a source root that the scan did not find is gone; any other input (a JSON config) is read.\n if (\n isCodeFile(file) &&\n sourceRoots.some((folder) => folder === \".\" || isInsideFolder(file, folder))\n )\n return [file, \"\"] as const;\n\n return [file, await hashIfExists(root, file)] as const;\n });\n\n return Object.fromEntries(hashes);\n}\n\nfunction sameRecord(left: Record<string, string>, right: Record<string, string>): boolean {\n const leftKeys = Object.keys(left);\n\n return (\n leftKeys.length === Object.keys(right).length &&\n leftKeys.every((key) => right[key] === left[key])\n );\n}\n\n/** Source files added, changed or removed between two manifests, sorted. */\nfunction changedFiles(\n previous: Record<string, BookManifestFile>,\n current: Scan[\"files\"],\n): string[] {\n const changed: string[] = [];\n\n for (const [file, state] of Object.entries(current)) {\n if (previous[file]?.hash !== state.hash) changed.push(file);\n }\n\n for (const file of Object.keys(previous)) {\n if (current[file] === undefined) changed.push(file);\n }\n\n return changed.sort();\n}\n\nconst NAMED_FILE_TYPES = new Set([\"mail\", \"job\", \"event\"]);\n\n/**\n * Files whose change makes the route cache stale: every `routes` file and\n * everything it imports, every `config` file, `warlock.config.ts`,\n * `package.json`, and every mail, job, event and notification file (the\n * named things are cached with the routes).\n */\nexport function defaultRouteInputs(files: readonly BookFile[]): string[] {\n const routesFiles = files.filter((file) => file.type === \"routes\").map((file) => file.file);\n const inputs = new Set(importClosure(fileGraph(files), routesFiles));\n\n for (const file of files) {\n if (\n file.type === \"config\" ||\n NAMED_FILE_TYPES.has(file.type) ||\n /\\.notification\\.[^/]+$/.test(file.file)\n ) {\n inputs.add(file.file);\n }\n }\n\n inputs.add(\"warlock.config.ts\");\n inputs.add(\"package.json\");\n\n return [...inputs].sort();\n}\n\n/** The route cache's input files: the adapter's list when it has one, else the default. */\nasync function routeInputFiles(\n root: string,\n adapter: BookAdapter,\n files: readonly BookFile[],\n): Promise<string[]> {\n return adapter.routeInputs\n ? (await adapter.routeInputs(root, files)).map(cleanPath)\n : defaultRouteInputs(files);\n}\n\nconst hasBootFacts = (adapter: BookAdapter): boolean =>\n typeof adapter.routes === \"function\" || typeof adapter.named === \"function\";\n\nasync function collectBootFacts(\n root: string,\n adapter: BookAdapter,\n): Promise<Pick<BookFacts, \"routes\" | \"named\">> {\n try {\n return {\n routes: adapter.routes ? normalizeRoutes(await adapter.routes(root)) : null,\n named: adapter.named ? normalizeNamed(await adapter.named(root)) : [],\n };\n } catch (error) {\n if (error instanceof GrimoireError) throw error;\n throw new GrimoireError(\"GR8002\", `Route facts could not be read: ${(error as Error).message}`);\n }\n}\n\n/** How the stored route facts relate to the current inputs. */\nfunction bootState(\n boot: BookManifest[\"boot\"],\n routes: BookFacts[\"routes\"],\n inputs: Record<string, string>,\n): \"fresh\" | \"stale\" | \"missing\" {\n if (boot.collectedAt === null || routes === null) return \"missing\";\n\n return sameRecord(boot.inputs, inputs) ? \"fresh\" : \"stale\";\n}\n\n/**\n * A fresh read that found under half the routes the book already holds is not trusted over the stored list,\n * unless the build was forced (`warlock grimoire build --force`): that is how a real removal is accepted.\n */\nfunction shrankTooFar(\n stored: BookFacts[\"routes\"],\n read: BookFacts[\"routes\"],\n force: boolean,\n): boolean {\n return (\n !force &&\n stored !== null &&\n read !== null &&\n stored.length > 0 &&\n read.length * 2 < stored.length\n );\n}\n\nconst shrankNote = (kept: number, read: number): string =>\n `a live read found ${read} routes against the ${kept} stored; kept the stored routes; run warlock grimoire build again, or warlock grimoire build --force when the routes were removed`;\n\nasync function writeStoredBook(\n root: string,\n manifest: BookManifest,\n facts: BookFacts | null,\n): Promise<void> {\n if (facts !== null) {\n const cache: StoredFactsCache = {\n schemaVersion: BOOK_SCHEMA_VERSION,\n typeOnlyEdges: true,\n facts,\n };\n await writeBookFile(root, GRIMOIRE_PATHS.bookFactsCache, toJson(cache));\n }\n\n // The manifest last: a reader that sees it also sees the facts it describes.\n await writeBookFile(root, GRIMOIRE_PATHS.bookManifest, toJson(manifest));\n}\n\n/**\n * Bring the book's facts up to date and write `manifest.json` and\n * `.cache/facts.json`. Does not write entries (see `writeBook`).\n *\n * @param root Absolute project root.\n */\nexport async function buildBook(\n root: string,\n adapter: BookAdapter,\n options: BuildBookOptions = {},\n): Promise<BuildBookResult> {\n const projectRoot = path.resolve(root);\n const mode = options.routes ?? \"cached\";\n const now = options.now ?? (() => new Date());\n // `write: false` (passed by `openGrimoire({ write: false })`) computes in memory only.\n const write = options.write !== false;\n const sourceRoots = [\n ...new Set((await adapter.sourceRoots(projectRoot)).map(cleanFolder)),\n ].sort();\n const stored = await readStoredBook(projectRoot);\n const previousFiles = stored?.manifest.files ?? {};\n const scan = await scanSourceRoots(projectRoot, sourceRoots, previousFiles);\n const version = grimoireVersion();\n\n // ── The fast path: nothing under the source roots (or the tests) changed. ──\n if (stored !== null && options.force !== true) {\n const { manifest, facts } = stored;\n const sameSetup =\n manifest.grimoireVersion === version &&\n manifest.adapter.name === adapter.name &&\n manifest.adapter.version === adapter.version &&\n manifest.sourceRoots.length === sourceRoots.length &&\n manifest.sourceRoots.every((folder, index) => folder === sourceRoots[index]);\n const sameFiles =\n sameSetup &&\n Object.keys(previousFiles).length === Object.keys(scan.files).length &&\n Object.entries(scan.files).every(([file, state]) => previousFiles[file]?.hash === state.hash);\n const sameTests =\n sameFiles &&\n sameRecord(\n manifest.tests,\n await hashFiles(projectRoot, Object.keys(manifest.tests), scan.files, sourceRoots),\n );\n\n if (sameTests) {\n const inputs = await hashFiles(\n projectRoot,\n Object.keys(manifest.boot.inputs),\n scan.files,\n sourceRoots,\n );\n let routes: RouteFreshness = hasBootFacts(adapter)\n ? bootState(manifest.boot, facts.routes, inputs)\n : \"missing\";\n let changedBook = false;\n let routeNote: string | undefined;\n\n if (mode === \"fresh\" && hasBootFacts(adapter) && routes !== \"fresh\") {\n // The stored input list can be older than the files (a cached rebuild keeps it): work it out again.\n const current = await hashFiles(\n projectRoot,\n await routeInputFiles(projectRoot, adapter, facts.files),\n scan.files,\n sourceRoots,\n );\n const read = await collectBootFacts(projectRoot, adapter);\n\n if (shrankTooFar(facts.routes, read.routes, false)) {\n routeNote = shrankNote(facts.routes?.length ?? 0, read.routes?.length ?? 0);\n routes = \"stale\";\n } else {\n Object.assign(facts, read);\n manifest.boot = {\n collectedAt: now().toISOString(),\n inputs: current,\n counts: { routes: read.routes?.length ?? 0, pages: facts.pages.length },\n };\n routes = \"fresh\";\n changedBook = true;\n }\n }\n\n if (changedBook || scan.statMoved) {\n for (const [file, state] of Object.entries(scan.files)) {\n manifest.files[file] = { ...state, entry: manifest.files[file]?.entry ?? null };\n }\n\n if (changedBook) manifest.builtAt = now().toISOString();\n\n if (write) await writeStoredBook(projectRoot, manifest, changedBook ? facts : null);\n }\n\n return {\n book: { root: projectRoot, manifest, facts, routes, ...(routeNote ? { routeNote } : {}) },\n rebuilt: changedBook,\n changed: [],\n };\n }\n }\n\n // ── Rebuild the static facts. ──\n let files: BookFile[];\n\n try {\n files = normalizeFiles(await adapter.files(projectRoot));\n } catch (error) {\n if (error instanceof GrimoireError) throw error;\n throw new GrimoireError(\n \"GR8001\",\n `The source files could not be read: ${(error as Error).message}`,\n );\n }\n\n let staticFacts: Omit<BookFacts, \"files\" | \"routes\" | \"named\">;\n\n try {\n staticFacts = {\n sites: adapter.sites ? normalizeSites(await adapter.sites(projectRoot)) : [],\n pages: adapter.pages ? normalizePages(await adapter.pages(projectRoot)) : [],\n mobile: adapter.mobile ? normalizeMobile(await adapter.mobile(projectRoot)) : [],\n tests: adapter.tests\n ? (await adapter.tests(projectRoot)).map(cleanPath)\n : files.filter((file) => file.type === \"spec\").map((file) => file.file),\n };\n } catch (error) {\n if (error instanceof GrimoireError) throw error;\n throw new GrimoireError(\n \"GR8004\",\n `Pages or screens could not be read: ${(error as Error).message}`,\n );\n }\n\n staticFacts.tests = [...new Set(staticFacts.tests)].sort();\n\n const inputs = await hashFiles(\n projectRoot,\n await routeInputFiles(projectRoot, adapter, files),\n scan.files,\n sourceRoots,\n );\n const previousBoot = stored?.manifest.boot ?? { collectedAt: null, inputs: {} };\n let boot = previousBoot;\n let routeNote: string | undefined;\n let bootFacts: Pick<BookFacts, \"routes\" | \"named\"> = {\n routes: stored?.facts.routes ?? null,\n named: stored?.facts.named ?? [],\n };\n let routes: RouteFreshness = hasBootFacts(adapter)\n ? bootState(previousBoot, bootFacts.routes, inputs)\n : \"missing\";\n\n if (mode === \"fresh\" && hasBootFacts(adapter) && (routes !== \"fresh\" || options.force === true)) {\n const read = await collectBootFacts(projectRoot, adapter);\n\n if (shrankTooFar(bootFacts.routes, read.routes, options.force === true)) {\n routeNote = shrankNote(bootFacts.routes?.length ?? 0, read.routes?.length ?? 0);\n routes = \"stale\";\n } else {\n bootFacts = read;\n boot = {\n collectedAt: now().toISOString(),\n inputs,\n counts: { routes: read.routes?.length ?? 0, pages: staticFacts.pages.length },\n };\n routes = \"fresh\";\n }\n }\n\n const facts: BookFacts = { files, ...bootFacts, ...staticFacts };\n const entries = entryPathsFor(facts);\n const manifest: BookManifest = {\n schemaVersion: BOOK_SCHEMA_VERSION,\n grimoireVersion: version,\n adapter: { name: adapter.name, version: adapter.version },\n builtAt: now().toISOString(),\n sourceRoots,\n files: Object.fromEntries(\n Object.entries(scan.files).map(([file, state]) => [\n file,\n { ...state, entry: entries.get(file) ?? null },\n ]),\n ),\n tests: await hashFiles(projectRoot, facts.tests, scan.files, sourceRoots),\n writtenHash: stored?.manifest.writtenHash ?? \"\",\n boot,\n };\n\n // A forced build rewrites every entry: forget what `writeBook` wrote.\n if (write) {\n if (options.force === true)\n await rm(absolutePath(projectRoot, WRITE_STATE_PATH), { force: true });\n\n await writeStoredBook(projectRoot, manifest, facts);\n }\n\n return {\n book: { root: projectRoot, manifest, facts, routes, ...(routeNote ? { routeNote } : {}) },\n rebuilt: true,\n changed: changedFiles(previousFiles, scan.files),\n };\n}\n\n/** Read the book from disk without calling an adapter; `null` when it was never built. */\nexport async function loadBook(root: string): Promise<LoadedBook | null> {\n const projectRoot = path.resolve(root);\n const stored = await readStoredBook(projectRoot);\n\n if (stored === null) return null;\n\n return {\n root: projectRoot,\n manifest: stored.manifest,\n facts: stored.facts,\n // Not checked against the sources here; `buildBook` tells fresh from stale.\n routes: stored.facts.routes === null ? \"missing\" : \"cached\",\n };\n}\n\n/** What `checkBook` found: the stored book, and how far the files have moved from it. */\nexport type BookCheck = {\n /** The stored book, with its route freshness measured against the files as they are now. */\n book: LoadedBook;\n /** Code and test files added, changed or removed since the last build, sorted. */\n changed: string[];\n};\n\n/**\n * The cheap change check of `buildBook` with nothing rebuilt and nothing\n * written: scans the source roots (hashing only files whose size or time\n * moved) and compares them, and the tests, with the manifest. The adapter is\n * asked for its source roots only, never for files or route facts. `null`\n * when the book was never built (or was written by an older schema).\n *\n * @param root Absolute project root.\n */\nexport async function checkBook(root: string, adapter: BookAdapter): Promise<BookCheck | null> {\n const projectRoot = path.resolve(root);\n const stored = await readStoredBook(projectRoot);\n\n if (stored === null) return null;\n\n const { manifest, facts } = stored;\n const sourceRoots = [\n ...new Set((await adapter.sourceRoots(projectRoot)).map(cleanFolder)),\n ].sort();\n const scan = await scanSourceRoots(projectRoot, sourceRoots, manifest.files);\n const changed = new Set(changedFiles(manifest.files, scan.files));\n const tests = await hashFiles(projectRoot, Object.keys(manifest.tests), scan.files, sourceRoots);\n\n for (const [file, hash] of Object.entries(tests)) {\n if (manifest.tests[file] !== hash) changed.add(file);\n }\n\n const inputs = await hashFiles(\n projectRoot,\n Object.keys(manifest.boot.inputs),\n scan.files,\n sourceRoots,\n );\n const routes: RouteFreshness = hasBootFacts(adapter)\n ? bootState(manifest.boot, facts.routes, inputs)\n : \"missing\";\n\n return {\n book: { root: projectRoot, manifest, facts, routes },\n changed: [...changed].sort(),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6CA,MAAa,mBAAmB,GAAG,eAAe,KAAK;AAEvD,IAAI,gBAA+B;;AAGnC,SAAgB,kBAA0B;CACxC,IAAI,kBAAkB,MAAM,OAAO;CAEnC,IAAI;EACF,MAAM,WAAW,KAAK,MACpB,aAAa,IAAI,IAAI,sBAAsB,YAAY,GAAG,GAAG,MAAM,CACrE;EAGA,gBAAgB,OAAO,SAAS,YAAY,WAAW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,eAAe,WAAW;CAE/C,IAAI,WAAW,MAAM,OAAO;CAE5B,MAAM,EAAE,UAAU,UAAU;CAC5B,MAAM,cAAc,CAClB,GAAG,IAAI,KAAK,MAAM,QAAQ,YAAY,WAAW,EAAC,CAAE,IAAI,WAAW,CAAC,CACtE,CAAC,CAAC,KAAK;CACP,MAAM,OAAO,MAAM,gBAAgB,aAAa,aAAa,SAAS,KAAK;CAC3E,MAAM,UAAU,IAAI,IAAI,aAAa,SAAS,OAAO,KAAK,KAAK,CAAC;CAChE,MAAM,QAAQ,MAAM,UAAU,aAAa,OAAO,KAAK,SAAS,KAAK,GAAG,KAAK,OAAO,WAAW;CAE/F,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,KAAK,GAC7C,IAAI,SAAS,MAAM,UAAU,MAAM,QAAQ,IAAI,IAAI;CAGrD,MAAM,SAAS,MAAM,UACnB,aACA,OAAO,KAAK,SAAS,KAAK,MAAM,GAChC,KAAK,OACL,WACF;CAKA,OAAO;EACL,MAAM;GAAE,MAAM;GAAa;GAAU;GAAO,QALf,aAAa,OAAO,IAC/C,UAAU,SAAS,MAAM,MAAM,QAAQ,MAAM,IAC7C;EAGiD;EACnD,SAAS,CAAC,GAAG,OAAO,CAAC,CAAC,KAAK;CAC7B;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"check-grimoire.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/check/check-grimoire.ts"],"mappings":";;;;wBAiCgB,cAAc,UAAU,mBAAmB"}
1
+ {"version":3,"file":"check-grimoire.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/check/check-grimoire.ts"],"mappings":";;;;wBA2CgB,cAAc,UAAU,mBAAmB"}
@@ -3,10 +3,15 @@ import "../apps/index.mjs";
3
3
  import { checkTestResults } from "../test-results/index.mjs";
4
4
  import { checkReleases } from "../releases/index.mjs";
5
5
  import { checkTasks } from "../tasks/index.mjs";
6
+ import { checkApiSnapshot } from "./rules/api-snapshot.mjs";
6
7
  import { checkBookNotes } from "./rules/book-notes.mjs";
8
+ import { checkCodeRules } from "./rules/code-rules.mjs";
7
9
  import { checkCaseCriteria, checkCriteriaTests, checkProofTargets } from "./rules/criteria.mjs";
10
+ import { checkDrift } from "./rules/drift.mjs";
11
+ import { checkFocusedTests } from "./rules/focused-tests.mjs";
8
12
  import { checkAppNames, checkChangelogLinks, checkRelations, checkSteps } from "./rules/links.mjs";
9
13
  import { checkScreenshots } from "./rules/screenshots.mjs";
14
+ import { checkShows } from "./rules/shows.mjs";
10
15
  import { checkFolders, checkHeaders, checkOwners, checkUnreached } from "./rules/source-files.mjs";
11
16
  import { checkChangeWords, checkFlowVersions, checkReadmeDates } from "./rules/versions.mjs";
12
17
 
@@ -27,7 +32,12 @@ const CHECK_RULES = [
27
32
  checkProofTargets,
28
33
  checkReadmeDates,
29
34
  checkChangeWords,
30
- checkFlowVersions
35
+ checkFlowVersions,
36
+ checkCodeRules,
37
+ checkFocusedTests,
38
+ checkApiSnapshot,
39
+ checkShows,
40
+ checkDrift
31
41
  ];
32
42
  /** Run every rule over a snapshot. Pure; never writes. */
33
43
  function checkGrimoire(snapshot) {
@@ -1 +1 @@
1
- {"version":3,"file":"check-grimoire.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/check/check-grimoire.ts"],"sourcesContent":["import { checkApps } from \"../apps\";\nimport type { GrimoireCheckReport, GrimoireFinding } from \"../contracts/findings\";\nimport type { GrimoireRule, GrimoireSnapshot } from \"../contracts/snapshot\";\nimport { checkReleases } from \"../releases\";\nimport { checkTasks } from \"../tasks\";\nimport { checkTestResults } from \"../test-results\";\nimport { checkBookNotes } from \"./rules/book-notes\";\nimport { checkCaseCriteria, checkCriteriaTests, checkProofTargets } from \"./rules/criteria\";\nimport { checkAppNames, checkChangelogLinks, checkRelations, checkSteps } from \"./rules/links\";\nimport { checkScreenshots } from \"./rules/screenshots\";\nimport { checkFolders, checkHeaders, checkOwners, checkUnreached } from \"./rules/source-files\";\nimport { checkChangeWords, checkFlowVersions, checkReadmeDates } from \"./rules/versions\";\n\n/** The check's own rules, in report order before sorting. */\nexport const CHECK_RULES: readonly GrimoireRule[] = [\n checkSteps,\n checkAppNames,\n checkChangelogLinks,\n checkRelations,\n checkHeaders,\n checkOwners,\n checkFolders,\n checkUnreached,\n checkCaseCriteria,\n checkScreenshots,\n checkCriteriaTests,\n checkProofTargets,\n checkReadmeDates,\n checkChangeWords,\n checkFlowVersions,\n];\n\n/** Run every rule over a snapshot. Pure; never writes. */\nexport function checkGrimoire(snapshot: GrimoireSnapshot): GrimoireCheckReport {\n const findings = [\n ...snapshot.structure,\n ...snapshot.proofFindings,\n ...CHECK_RULES.flatMap((rule) => rule(snapshot)),\n ...checkApps(snapshot),\n ...checkReleases(snapshot),\n ...checkTasks(snapshot),\n ...checkTestResults(snapshot),\n ...checkBookNotes(snapshot),\n ];\n\n return finishReport(snapshot, findings);\n}\n\n/**\n * Mark the findings on proposed features and flows as expected, sort them\n * and count them. The findings of the snapshot are copied, never changed.\n */\nexport function finishReport(\n snapshot: GrimoireSnapshot,\n findings: readonly GrimoireFinding[],\n): GrimoireCheckReport {\n const proposed = proposedWork(snapshot);\n const marked = findings\n .map((finding) => ({ ...finding, expected: finding.expected || isProposed(finding, proposed) }))\n .sort(compareFindings);\n const unexpected = marked.filter((finding) => !finding.expected);\n const errors = unexpected.filter((finding) => finding.severity === \"error\").length;\n\n return {\n schemaVersion: 1,\n root: snapshot.root,\n findings: marked,\n counts: {\n errors,\n warnings: unexpected.length - errors,\n expected: marked.length - unexpected.length,\n },\n ok: errors === 0,\n routes: snapshot.routes,\n };\n}\n\n/** Feature ids and `<feature>/<flow>` refs whose status is `proposed`. */\nfunction proposedWork(snapshot: GrimoireSnapshot): Set<string> {\n const proposed = new Set<string>();\n\n for (const feature of snapshot.written.features) {\n if (feature.readme?.status.value === \"proposed\") proposed.add(feature.id);\n\n for (const flow of feature.flows) {\n if (flow.status.value === \"proposed\") proposed.add(flow.ref);\n }\n }\n\n return proposed;\n}\n\nfunction isProposed(finding: GrimoireFinding, proposed: ReadonlySet<string>): boolean {\n const { feature, flow } = finding.subject;\n const flowFeature = flow?.split(\"/\")[0] ?? null;\n\n return [feature, flow, flowFeature].some((id) => id !== null && proposed.has(id));\n}\n\n/** Unexpected findings first, then expected; within each, errors before warnings, then by file, line and code. */\nfunction compareFindings(left: GrimoireFinding, right: GrimoireFinding): number {\n return (\n Number(left.expected) - Number(right.expected) ||\n severityRank(left) - severityRank(right) ||\n compareText(\n left.at?.file ?? left.subject.file ?? \"\",\n right.at?.file ?? right.subject.file ?? \"\",\n ) ||\n (left.at?.line ?? 0) - (right.at?.line ?? 0) ||\n compareText(left.code, right.code) ||\n compareText(left.message, right.message)\n );\n}\n\nfunction severityRank(finding: GrimoireFinding): number {\n return finding.severity === \"error\" ? 0 : 1;\n}\n\n/** Locale-free comparison, so the order is the same on every machine. */\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,cAAuC;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAgB,cAAc,UAAiD;CAY7E,OAAO,aAAa,UAAU;EAV5B,GAAG,SAAS;EACZ,GAAG,SAAS;EACZ,GAAG,YAAY,SAAS,SAAS,KAAK,QAAQ,CAAC;EAC/C,GAAG,UAAU,QAAQ;EACrB,GAAG,cAAc,QAAQ;EACzB,GAAG,WAAW,QAAQ;EACtB,GAAG,iBAAiB,QAAQ;EAC5B,GAAG,eAAe,QAAQ;CAGS,CAAC;AACxC;;;;;AAMA,SAAgB,aACd,UACA,UACqB;CACrB,MAAM,WAAW,aAAa,QAAQ;CACtC,MAAM,SAAS,SACZ,KAAK,aAAa;EAAE,GAAG;EAAS,UAAU,QAAQ,YAAY,WAAW,SAAS,QAAQ;CAAE,EAAE,CAAC,CAC/F,KAAK,eAAe;CACvB,MAAM,aAAa,O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AY,MAAc,OAAuB;CACxD,OAAO,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChD"}
1
+ {"version":3,"file":"check-grimoire.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/check/check-grimoire.ts"],"sourcesContent":["import { checkApps } from \"../apps\";\nimport type { GrimoireCheckReport, GrimoireFinding } from \"../contracts/findings\";\nimport type { GrimoireRule, GrimoireSnapshot } from \"../contracts/snapshot\";\nimport { checkReleases } from \"../releases\";\nimport { checkTasks } from \"../tasks\";\nimport { checkTestResults } from \"../test-results\";\nimport { checkApiSnapshot } from \"./rules/api-snapshot\";\nimport { checkBookNotes } from \"./rules/book-notes\";\nimport { checkCodeRules } from \"./rules/code-rules\";\nimport { checkCaseCriteria, checkCriteriaTests, checkProofTargets } from \"./rules/criteria\";\nimport { checkDrift } from \"./rules/drift\";\nimport { checkFocusedTests } from \"./rules/focused-tests\";\nimport { checkAppNames, checkChangelogLinks, checkRelations, checkSteps } from \"./rules/links\";\nimport { checkScreenshots } from \"./rules/screenshots\";\nimport { checkShows } from \"./rules/shows\";\nimport { checkFolders, checkHeaders, checkOwners, checkUnreached } from \"./rules/source-files\";\nimport { checkChangeWords, checkFlowVersions, checkReadmeDates } from \"./rules/versions\";\n\n/** The check's own rules, in report order before sorting. */\nexport const CHECK_RULES: readonly GrimoireRule[] = [\n checkSteps,\n checkAppNames,\n checkChangelogLinks,\n checkRelations,\n checkHeaders,\n checkOwners,\n checkFolders,\n checkUnreached,\n checkCaseCriteria,\n checkScreenshots,\n checkCriteriaTests,\n checkProofTargets,\n checkReadmeDates,\n checkChangeWords,\n checkFlowVersions,\n checkCodeRules,\n checkFocusedTests,\n checkApiSnapshot,\n checkShows,\n checkDrift,\n];\n\n/** Run every rule over a snapshot. Pure; never writes. */\nexport function checkGrimoire(snapshot: GrimoireSnapshot): GrimoireCheckReport {\n const findings = [\n ...snapshot.structure,\n ...snapshot.proofFindings,\n ...CHECK_RULES.flatMap((rule) => rule(snapshot)),\n ...checkApps(snapshot),\n ...checkReleases(snapshot),\n ...checkTasks(snapshot),\n ...checkTestResults(snapshot),\n ...checkBookNotes(snapshot),\n ];\n\n return finishReport(snapshot, findings);\n}\n\n/**\n * Mark the findings on proposed features and flows as expected, sort them\n * and count them. The findings of the snapshot are copied, never changed.\n */\nexport function finishReport(\n snapshot: GrimoireSnapshot,\n findings: readonly GrimoireFinding[],\n): GrimoireCheckReport {\n const proposed = proposedWork(snapshot);\n const marked = findings\n .map((finding) => ({ ...finding, expected: finding.expected || isProposed(finding, proposed) }))\n .sort(compareFindings);\n const unexpected = marked.filter((finding) => !finding.expected);\n const errors = unexpected.filter((finding) => finding.severity === \"error\").length;\n\n return {\n schemaVersion: 1,\n root: snapshot.root,\n findings: marked,\n counts: {\n errors,\n warnings: unexpected.length - errors,\n expected: marked.length - unexpected.length,\n },\n ok: errors === 0,\n routes: snapshot.routes,\n };\n}\n\n/** Feature ids and `<feature>/<flow>` refs whose status is `proposed`. */\nfunction proposedWork(snapshot: GrimoireSnapshot): Set<string> {\n const proposed = new Set<string>();\n\n for (const feature of snapshot.written.features) {\n if (feature.readme?.status.value === \"proposed\") proposed.add(feature.id);\n\n for (const flow of feature.flows) {\n if (flow.status.value === \"proposed\") proposed.add(flow.ref);\n }\n }\n\n return proposed;\n}\n\nfunction isProposed(finding: GrimoireFinding, proposed: ReadonlySet<string>): boolean {\n const { feature, flow } = finding.subject;\n const flowFeature = flow?.split(\"/\")[0] ?? null;\n\n return [feature, flow, flowFeature].some((id) => id !== null && proposed.has(id));\n}\n\n/** Unexpected findings first, then expected; within each, errors before warnings, then by file, line and code. */\nfunction compareFindings(left: GrimoireFinding, right: GrimoireFinding): number {\n return (\n Number(left.expected) - Number(right.expected) ||\n severityRank(left) - severityRank(right) ||\n compareText(\n left.at?.file ?? left.subject.file ?? \"\",\n right.at?.file ?? right.subject.file ?? \"\",\n ) ||\n (left.at?.line ?? 0) - (right.at?.line ?? 0) ||\n compareText(left.code, right.code) ||\n compareText(left.message, right.message)\n );\n}\n\nfunction severityRank(finding: GrimoireFinding): number {\n return finding.severity === \"error\" ? 0 : 1;\n}\n\n/** Locale-free comparison, so the order is the same on every machine. */\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,MAAa,cAAuC;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAgB,cAAc,UAAiD;CAY7E,OAAO,aAAa,UAAU;EAV5B,GAAG,SAAS;EACZ,GAAG,SAAS;EACZ,GAAG,YAAY,SAAS,SAAS,KAAK,QAAQ,CAAC;EAC/C,GAAG,UAAU,QAAQ;EACrB,GAAG,cAAc,QAAQ;EACzB,GAAG,WAAW,QAAQ;EACtB,GAAG,iBAAiB,QAAQ;EAC5B,GAAG,eAAe,QAAQ;CAGS,CAAC;AACxC;;;;;AAMA,SAAgB,aACd,UACA,UACqB;CACrB,MAAM,WAAW,aAAa,QAAQ;CACtC,MAAM,SAAS,SACZ,KAAK,aAAa;EAAE,GAAG;EAAS,UAAU,QAAQ,YAAY,WAAW,SAAS,QAAQ;CAAE,EAAE,CAAC,CAC/F,KAAK,eAAe;CACvB,MAAM,aAAa,OAAO,QAAQ,YAAY,CAAC,QAAQ,QAAQ;CAC/D,MAAM,SAAS,WAAW,QAAQ,YAAY,QAAQ,aAAa,OAAO,CAAC,CAAC;CAE5E,OAAO;EACL,eAAe;EACf,MAAM,SAAS;EACf,UAAU;EACV,QAAQ;GACN;GACA,UAAU,WAAW,SAAS;GAC9B,UAAU,OAAO,SAAS,WAAW;EACvC;EACA,IAAI,WAAW;EACf,QAAQ,SAAS;CACnB;AACF;;AAGA,SAAS,aAAa,UAAyC;CAC7D,MAAM,2BAAW,IAAI,IAAY;CAEjC,KAAK,MAAM,WAAW,SAAS,QAAQ,UAAU;EAC/C,IAAI,QAAQ,QAAQ,OAAO,UAAU,YAAY,SAAS,IAAI,QAAQ,EAAE;EAExE,KAAK,MAAM,QAAQ,QAAQ,OACzB,IAAI,KAAK,OAAO,UAAU,YAAY,SAAS,IAAI,KAAK,GAAG;CAE/D;CAEA,OAAO;AACT;AAEA,SAAS,WAAW,SAA0B,UAAwC;CACpF,MAAM,EAAE,SAAS,SAAS,QAAQ;CAGlC,OAAO;EAAC;EAAS;EAFG,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM;CAET,CAAC,CAAC,MAAM,OAAO,OAAO,QAAQ,SAAS,IAAI,EAAE,CAAC;AAClF;;AAGA,SAAS,gBAAgB,MAAuB,OAAgC;CAC9E,OACE,OAAO,KAAK,QAAQ,IAAI,OAAO,MAAM,QAAQ,KAC7C,aAAa,IAAI,IAAI,aAAa,KAAK,KACvC,YACE,KAAK,IAAI,QAAQ,KAAK,QAAQ,QAAQ,IACtC,MAAM,IAAI,QAAQ,MAAM,QAAQ,QAAQ,EAC1C,MACC,KAAK,IAAI,QAAQ,MAAM,MAAM,IAAI,QAAQ,MAC1C,YAAY,KAAK,MAAM,MAAM,IAAI,KACjC,YAAY,KAAK,SAAS,MAAM,OAAO;AAE3C;AAEA,SAAS,aAAa,SAAkC;CACtD,OAAO,QAAQ,aAAa,UAAU,IAAI;AAC5C;;AAGA,SAAS,YAAY,MAAc,OAAuB;CACxD,OAAO,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChD"}
@@ -0,0 +1,39 @@
1
+ import { createFinding } from "../../codes/index.mjs";
2
+ import { GRIMOIRE_PATHS } from "../../paths/index.mjs";
3
+ import { describeRouteDiff, diffRoutes, parseApiSnapshot, routeLines } from "../../guard/api.mjs";
4
+ import path from "node:path";
5
+ import { readFileSync } from "node:fs";
6
+
7
+ //#region ../../packages/grimoire/src/check/rules/api-snapshot.ts
8
+ /**
9
+ * GR7013: the routes differ from the approved public API
10
+ * (`grimoire/approved/api.json`, written by `warlock grimoire approve api`).
11
+ * Nothing is reported while no API was approved or no route facts exist.
12
+ */
13
+ function readApprovedSync(root) {
14
+ try {
15
+ return parseApiSnapshot(readFileSync(path.join(root, ...GRIMOIRE_PATHS.apiSnapshot.split("/")), "utf8"));
16
+ } catch {
17
+ return null;
18
+ }
19
+ }
20
+ function checkApiSnapshot(snapshot) {
21
+ const routes = snapshot.book.facts.routes;
22
+ const approved = readApprovedSync(snapshot.root);
23
+ if (approved === null || routes === null) return [];
24
+ const diff = diffRoutes(approved.routes, routeLines(routes));
25
+ if (diff.added.length + diff.removed.length === 0) return [];
26
+ return [createFinding({
27
+ code: "GR7013",
28
+ message: `the public API differs from the approved one: ${describeRouteDiff(diff)}`,
29
+ at: {
30
+ file: GRIMOIRE_PATHS.apiSnapshot,
31
+ line: 1,
32
+ column: null
33
+ }
34
+ })];
35
+ }
36
+
37
+ //#endregion
38
+ export { checkApiSnapshot };
39
+ //# sourceMappingURL=api-snapshot.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-snapshot.mjs","names":[],"sources":["../../../../../../../../../packages/grimoire/src/check/rules/api-snapshot.ts"],"sourcesContent":["/**\n * GR7013: the routes differ from the approved public API\n * (`grimoire/approved/api.json`, written by `warlock grimoire approve api`).\n * Nothing is reported while no API was approved or no route facts exist.\n */\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { createFinding } from \"../../codes\";\nimport type { GrimoireFinding } from \"../../contracts/findings\";\nimport type { ApiSnapshot } from \"../../contracts/guard\";\nimport type { GrimoireSnapshot } from \"../../contracts/snapshot\";\nimport { describeRouteDiff, diffRoutes, parseApiSnapshot, routeLines } from \"../../guard/api\";\nimport { GRIMOIRE_PATHS } from \"../../paths\";\n\nfunction readApprovedSync(root: string): ApiSnapshot | null {\n try {\n return parseApiSnapshot(\n readFileSync(path.join(root, ...GRIMOIRE_PATHS.apiSnapshot.split(\"/\")), \"utf8\"),\n );\n } catch {\n return null;\n }\n}\n\nexport function checkApiSnapshot(snapshot: GrimoireSnapshot): GrimoireFinding[] {\n const routes = snapshot.book.facts.routes;\n const approved = readApprovedSync(snapshot.root);\n\n if (approved === null || routes === null) return [];\n\n const diff = diffRoutes(approved.routes, routeLines(routes));\n\n if (diff.added.length + diff.removed.length === 0) return [];\n\n return [\n createFinding({\n code: \"GR7013\",\n message: `the public API differs from the approved one: ${describeRouteDiff(diff)}`,\n at: { file: GRIMOIRE_PATHS.apiSnapshot, line: 1, column: null },\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;;;AAcA,SAAS,iBAAiB,MAAkC;CAC1D,IAAI;EACF,OAAO,iBACL,aAAa,KAAK,KAAK,MAAM,GAAG,eAAe,YAAY,MAAM,GAAG,CAAC,GAAG,MAAM,CAChF;CACF,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAgB,iBAAiB,UAA+C;CAC9E,MAAM,SAAS,SAAS,KAAK,MAAM;CACnC,MAAM,WAAW,iBAAiB,SAAS,IAAI;CAE/C,IAAI,aAAa,QAAQ,WAAW,MAAM,OAAO,CAAC;CAElD,MAAM,OAAO,WAAW,SAAS,QAAQ,WAAW,MAAM,CAAC;CAE3D,IAAI,KAAK,MAAM,SAAS,KAAK,QAAQ,WAAW,GAAG,OAAO,CAAC;CAE3D,OAAO,CACL,cAAc;EACZ,MAAM;EACN,SAAS,iDAAiD,kBAAkB,IAAI;EAChF,IAAI;GAAE,MAAM,eAAe;GAAa,MAAM;GAAG,QAAQ;EAAK;CAChE,CAAC,CACH;AACF"}
@@ -0,0 +1,45 @@
1
+ import { DEFAULT_GRIMOIRE_SETTINGS } from "../../contracts/settings.mjs";
2
+ import { createFinding } from "../../codes/index.mjs";
3
+ import { isRuleFile, runCodeRules } from "../../rules/index.mjs";
4
+ import path from "node:path";
5
+ import { readFileSync } from "node:fs";
6
+
7
+ //#region ../../packages/grimoire/src/check/rules/code-rules.ts
8
+ /**
9
+ * GR3007-GR3010: the code rules the settings turn on (`rules:` in
10
+ * `grimoire/settings.md`), over every code and style file of the source
11
+ * roots. A project that writes no `rules:` runs none here (the guard still
12
+ * runs all four on the lines a change adds).
13
+ */
14
+ function checkCodeRules(snapshot) {
15
+ const rules = (snapshot.settings ?? DEFAULT_GRIMOIRE_SETTINGS).rules;
16
+ if (rules === null || rules.length === 0) return [];
17
+ const findings = [];
18
+ const files = Object.keys(snapshot.book.manifest.files).filter(isRuleFile).sort();
19
+ for (const file of files) {
20
+ let text;
21
+ try {
22
+ text = readFileSync(path.join(snapshot.root, ...file.split("/")), "utf8");
23
+ } catch {
24
+ continue;
25
+ }
26
+ for (const hit of runCodeRules(file, text, rules)) {
27
+ const owner = snapshot.ownership.files[file]?.owner ?? null;
28
+ findings.push(createFinding({
29
+ code: hit.code,
30
+ message: hit.message,
31
+ at: {
32
+ file,
33
+ line: hit.line,
34
+ column: hit.column
35
+ },
36
+ feature: owner
37
+ }));
38
+ }
39
+ }
40
+ return findings;
41
+ }
42
+
43
+ //#endregion
44
+ export { checkCodeRules };
45
+ //# sourceMappingURL=code-rules.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"code-rules.mjs","names":[],"sources":["../../../../../../../../../packages/grimoire/src/check/rules/code-rules.ts"],"sourcesContent":["/**\n * GR3007-GR3010: the code rules the settings turn on (`rules:` in\n * `grimoire/settings.md`), over every code and style file of the source\n * roots. A project that writes no `rules:` runs none here (the guard still\n * runs all four on the lines a change adds).\n */\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { createFinding } from \"../../codes\";\nimport type { GrimoireFinding } from \"../../contracts/findings\";\nimport { DEFAULT_GRIMOIRE_SETTINGS } from \"../../contracts/settings\";\nimport type { GrimoireSnapshot } from \"../../contracts/snapshot\";\nimport { isRuleFile, runCodeRules } from \"../../rules\";\n\nexport function checkCodeRules(snapshot: GrimoireSnapshot): GrimoireFinding[] {\n const rules = (snapshot.settings ?? DEFAULT_GRIMOIRE_SETTINGS).rules;\n\n if (rules === null || rules.length === 0) return [];\n\n const findings: GrimoireFinding[] = [];\n const files = Object.keys(snapshot.book.manifest.files).filter(isRuleFile).sort();\n\n for (const file of files) {\n let text: string;\n\n try {\n text = readFileSync(path.join(snapshot.root, ...file.split(\"/\")), \"utf8\");\n } catch {\n continue;\n }\n\n for (const hit of runCodeRules(file, text, rules)) {\n const owner = snapshot.ownership.files[file]?.owner ?? null;\n\n findings.push(\n createFinding({\n code: hit.code,\n message: hit.message,\n at: { file, line: hit.line, column: hit.column },\n feature: owner,\n }),\n );\n }\n }\n\n return findings;\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,SAAgB,eAAe,UAA+C;CAC5E,MAAM,SAAS,SAAS,YAAY,0BAAyB,CAAE;CAE/D,IAAI,UAAU,QAAQ,MAAM,WAAW,GAAG,OAAO,CAAC;CAElD,MAAM,WAA8B,CAAC;CACrC,MAAM,QAAQ,OAAO,KAAK,SAAS,KAAK,SAAS,KAAK,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,KAAK;CAEhF,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI;EAEJ,IAAI;GACF,OAAO,aAAa,KAAK,KAAK,SAAS,MAAM,GAAG,KAAK,MAAM,GAAG,CAAC,GAAG,MAAM;EAC1E,QAAQ;GACN;EACF;EAEA,KAAK,MAAM,OAAO,aAAa,MAAM,MAAM,KAAK,GAAG;GACjD,MAAM,QAAQ,SAAS,UAAU,MAAM,KAAK,EAAE,SAAS;GAEvD,SAAS,KACP,cAAc;IACZ,MAAM,IAAI;IACV,SAAS,IAAI;IACb,IAAI;KAAE;KAAM,MAAM,IAAI;KAAM,QAAQ,IAAI;IAAO;IAC/C,SAAS;GACX,CAAC,CACH;EACF;CACF;CAEA,OAAO;AACT"}
@@ -0,0 +1,54 @@
1
+ import { createFinding } from "../../codes/index.mjs";
2
+
3
+ //#region ../../packages/grimoire/src/check/rules/drift.ts
4
+ /**
5
+ * GR4017-GR4019: changes since the approved baseline, and rejected changes still there.
6
+ */
7
+ const DESCRIPTION = {
8
+ "shot-changed": "the capture differs from the approved image",
9
+ "shot-added": "the capture has no approved image yet",
10
+ "shot-removed": "the approved image no longer has a scene",
11
+ "flow-added": "the flow is new",
12
+ "flow-removed": "the flow is gone",
13
+ "criterion-added": "the criterion is new",
14
+ "criterion-removed": "the criterion is gone",
15
+ "criterion-changed": "the criterion's text changed",
16
+ "case-added": "the case is new",
17
+ "case-removed": "the case is gone",
18
+ "proof-removed": "the criterion lost its proving test"
19
+ };
20
+ function describe(item) {
21
+ const where = [
22
+ item.ref,
23
+ item.criterion,
24
+ item.language === null || item.language === "" ? null : item.language,
25
+ item.case === null ? null : `"${item.case}"`
26
+ ].filter((part) => part !== null).join(" ");
27
+ const text = item.type === "criterion-changed" && item.before !== null && item.after !== null ? ` (${JSON.stringify(item.before)} became ${JSON.stringify(item.after)})` : "";
28
+ return `${where}: ${DESCRIPTION[item.type]}${text}`;
29
+ }
30
+ function checkDrift(snapshot) {
31
+ const findings = [];
32
+ for (const item of snapshot.shots?.drift ?? []) {
33
+ const flow = item.ref;
34
+ const feature = flow.split("/")[0] ?? null;
35
+ const reason = describe(item);
36
+ if (item.rejected !== null) findings.push(createFinding({
37
+ code: "GR4019",
38
+ message: `change ${item.id} was rejected${item.rejected.note === null ? "" : ` (${item.rejected.note})`} and is still there: ${reason}`,
39
+ feature,
40
+ flow
41
+ }));
42
+ else findings.push(createFinding({
43
+ code: item.type.startsWith("shot-") ? "GR4017" : "GR4018",
44
+ message: `${reason} (change ${item.id}, not approved)`,
45
+ feature,
46
+ flow
47
+ }));
48
+ }
49
+ return findings;
50
+ }
51
+
52
+ //#endregion
53
+ export { checkDrift };
54
+ //# sourceMappingURL=drift.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drift.mjs","names":[],"sources":["../../../../../../../../../packages/grimoire/src/check/rules/drift.ts"],"sourcesContent":["/**\n * GR4017-GR4019: changes since the approved baseline, and rejected changes still there.\n */\nimport { createFinding } from \"../../codes\";\nimport type { GrimoireFinding } from \"../../contracts/findings\";\nimport type { DriftItem } from \"../../contracts/shots\";\nimport type { GrimoireSnapshot } from \"../../contracts/snapshot\";\n\nconst DESCRIPTION: Record<DriftItem[\"type\"], string> = {\n \"shot-changed\": \"the capture differs from the approved image\",\n \"shot-added\": \"the capture has no approved image yet\",\n \"shot-removed\": \"the approved image no longer has a scene\",\n \"flow-added\": \"the flow is new\",\n \"flow-removed\": \"the flow is gone\",\n \"criterion-added\": \"the criterion is new\",\n \"criterion-removed\": \"the criterion is gone\",\n \"criterion-changed\": \"the criterion's text changed\",\n \"case-added\": \"the case is new\",\n \"case-removed\": \"the case is gone\",\n \"proof-removed\": \"the criterion lost its proving test\",\n};\n\nfunction describe(item: DriftItem): string {\n const where = [\n item.ref,\n item.criterion,\n item.language === null || item.language === \"\" ? null : item.language,\n item.case === null ? null : `\"${item.case}\"`,\n ]\n .filter((part) => part !== null)\n .join(\" \");\n const text =\n item.type === \"criterion-changed\" && item.before !== null && item.after !== null\n ? ` (${JSON.stringify(item.before)} became ${JSON.stringify(item.after)})`\n : \"\";\n\n return `${where}: ${DESCRIPTION[item.type]}${text}`;\n}\n\nexport function checkDrift(snapshot: GrimoireSnapshot): GrimoireFinding[] {\n const findings: GrimoireFinding[] = [];\n\n for (const item of snapshot.shots?.drift ?? []) {\n const flow = item.ref;\n const feature = flow.split(\"/\")[0] ?? null;\n const reason = describe(item);\n\n if (item.rejected !== null) {\n findings.push(\n createFinding({\n code: \"GR4019\",\n message: `change ${item.id} was rejected${item.rejected.note === null ? \"\" : ` (${item.rejected.note})`} and is still there: ${reason}`,\n feature,\n flow,\n }),\n );\n } else {\n findings.push(\n createFinding({\n code: item.type.startsWith(\"shot-\") ? \"GR4017\" : \"GR4018\",\n message: `${reason} (change ${item.id}, not approved)`,\n feature,\n flow,\n }),\n );\n }\n }\n\n return findings;\n}\n"],"mappings":";;;;;;AAQA,MAAM,cAAiD;CACrD,gBAAgB;CAChB,cAAc;CACd,gBAAgB;CAChB,cAAc;CACd,gBAAgB;CAChB,mBAAmB;CACnB,qBAAqB;CACrB,qBAAqB;CACrB,cAAc;CACd,gBAAgB;CAChB,iBAAiB;AACnB;AAEA,SAAS,SAAS,MAAyB;CACzC,MAAM,QAAQ;EACZ,KAAK;EACL,KAAK;EACL,KAAK,aAAa,QAAQ,KAAK,aAAa,KAAK,OAAO,KAAK;EAC7D,KAAK,SAAS,OAAO,OAAO,IAAI,KAAK,KAAK;CAC5C,CAAC,CACE,QAAQ,SAAS,SAAS,IAAI,CAAC,CAC/B,KAAK,GAAG;CACX,MAAM,OACJ,KAAK,SAAS,uBAAuB,KAAK,WAAW,QAAQ,KAAK,UAAU,OACxE,KAAK,KAAK,UAAU,KAAK,MAAM,EAAE,UAAU,KAAK,UAAU,KAAK,KAAK,EAAE,KACtE;CAEN,OAAO,GAAG,MAAM,IAAI,YAAY,KAAK,QAAQ;AAC/C;AAEA,SAAgB,WAAW,UAA+C;CACxE,MAAM,WAA8B,CAAC;CAErC,KAAK,MAAM,QAAQ,SAAS,OAAO,SAAS,CAAC,GAAG;EAC9C,MAAM,OAAO,KAAK;EAClB,MAAM,UAAU,KAAK,MAAM,GAAG,CAAC,CAAC,MAAM;EACtC,MAAM,SAAS,SAAS,IAAI;EAE5B,IAAI,KAAK,aAAa,MACpB,SAAS,KACP,cAAc;GACZ,MAAM;GACN,SAAS,UAAU,KAAK,GAAG,eAAe,KAAK,SAAS,SAAS,OAAO,KAAK,KAAK,KAAK,SAAS,KAAK,GAAG,uBAAuB;GAC/H;GACA;EACF,CAAC,CACH;OAEA,SAAS,KACP,cAAc;GACZ,MAAM,KAAK,KAAK,WAAW,OAAO,IAAI,WAAW;GACjD,SAAS,GAAG,OAAO,WAAW,KAAK,GAAG;GACtC;GACA;EACF,CAAC,CACH;CAEJ;CAEA,OAAO;AACT"}
@@ -0,0 +1,39 @@
1
+ import { createFinding } from "../../codes/index.mjs";
2
+ import { findFocusedTests } from "../../rules/focused.mjs";
3
+ import { isTestPath } from "../../guard/rules.mjs";
4
+ import path from "node:path";
5
+ import { readFileSync } from "node:fs";
6
+
7
+ //#region ../../packages/grimoire/src/check/rules/focused-tests.ts
8
+ /**
9
+ * GR4011, GR4012: tests focused with `.only` or skipped with `.skip`, in
10
+ * every test file the book knows. `.skipIf(...)` is not flagged.
11
+ */
12
+ function checkFocusedTests(snapshot) {
13
+ const findings = [];
14
+ const files = new Set(snapshot.book.facts.tests);
15
+ for (const file of Object.keys(snapshot.book.manifest.files)) if (/\.[cm]?[jt]sx?$/.test(file) && isTestPath(file) && !file.includes("node_modules/")) files.add(file);
16
+ for (const file of [...files].sort()) {
17
+ let text;
18
+ try {
19
+ text = readFileSync(path.join(snapshot.root, ...file.split("/")), "utf8");
20
+ } catch {
21
+ continue;
22
+ }
23
+ for (const hit of findFocusedTests(text)) findings.push(createFinding({
24
+ code: hit.type === "only" ? "GR4011" : "GR4012",
25
+ message: `${hit.call} in ${file}`,
26
+ at: {
27
+ file,
28
+ line: hit.line,
29
+ column: null
30
+ },
31
+ feature: snapshot.ownership.files[file]?.owner ?? null
32
+ }));
33
+ }
34
+ return findings;
35
+ }
36
+
37
+ //#endregion
38
+ export { checkFocusedTests };
39
+ //# sourceMappingURL=focused-tests.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"focused-tests.mjs","names":[],"sources":["../../../../../../../../../packages/grimoire/src/check/rules/focused-tests.ts"],"sourcesContent":["/**\n * GR4011, GR4012: tests focused with `.only` or skipped with `.skip`, in\n * every test file the book knows. `.skipIf(...)` is not flagged.\n */\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { createFinding } from \"../../codes\";\nimport type { GrimoireFinding } from \"../../contracts/findings\";\nimport type { GrimoireSnapshot } from \"../../contracts/snapshot\";\nimport { isTestPath } from \"../../guard/rules\";\nimport { findFocusedTests } from \"../../rules/focused\";\n\nexport function checkFocusedTests(snapshot: GrimoireSnapshot): GrimoireFinding[] {\n const findings: GrimoireFinding[] = [];\n const files = new Set(snapshot.book.facts.tests);\n\n for (const file of Object.keys(snapshot.book.manifest.files)) {\n if (/\\.[cm]?[jt]sx?$/.test(file) && isTestPath(file) && !file.includes(\"node_modules/\"))\n files.add(file);\n }\n\n for (const file of [...files].sort()) {\n let text: string;\n\n try {\n text = readFileSync(path.join(snapshot.root, ...file.split(\"/\")), \"utf8\");\n } catch {\n continue;\n }\n\n for (const hit of findFocusedTests(text)) {\n findings.push(\n createFinding({\n code: hit.type === \"only\" ? \"GR4011\" : \"GR4012\",\n message: `${hit.call} in ${file}`,\n at: { file, line: hit.line, column: null },\n feature: snapshot.ownership.files[file]?.owner ?? null,\n }),\n );\n }\n }\n\n return findings;\n}\n"],"mappings":";;;;;;;;;;;AAYA,SAAgB,kBAAkB,UAA+C;CAC/E,MAAM,WAA8B,CAAC;CACrC,MAAM,QAAQ,IAAI,IAAI,SAAS,KAAK,MAAM,KAAK;CAE/C,KAAK,MAAM,QAAQ,OAAO,KAAK,SAAS,KAAK,SAAS,KAAK,GACzD,IAAI,kBAAkB,KAAK,IAAI,KAAK,WAAW,IAAI,KAAK,CAAC,KAAK,SAAS,eAAe,GACpF,MAAM,IAAI,IAAI;CAGlB,KAAK,MAAM,QAAQ,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK,GAAG;EACpC,IAAI;EAEJ,IAAI;GACF,OAAO,aAAa,KAAK,KAAK,SAAS,MAAM,GAAG,KAAK,MAAM,GAAG,CAAC,GAAG,MAAM;EAC1E,QAAQ;GACN;EACF;EAEA,KAAK,MAAM,OAAO,iBAAiB,IAAI,GACrC,SAAS,KACP,cAAc;GACZ,MAAM,IAAI,SAAS,SAAS,WAAW;GACvC,SAAS,GAAG,IAAI,KAAK,MAAM;GAC3B,IAAI;IAAE;IAAM,MAAM,IAAI;IAAM,QAAQ;GAAK;GACzC,SAAS,SAAS,UAAU,MAAM,KAAK,EAAE,SAAS;EACpD,CAAC,CACH;CAEJ;CAEA,OAAO;AACT"}
@@ -0,0 +1,52 @@
1
+ import { DEFAULT_GRIMOIRE_SETTINGS } from "../../contracts/settings.mjs";
2
+ import { createFinding } from "../../codes/index.mjs";
3
+
4
+ //#region ../../packages/grimoire/src/check/rules/shows.ts
5
+ /**
6
+ * GR4013-GR4016: `@shows` lines that are malformed or name nothing, criteria
7
+ * with no capture in a language, scenes that failed.
8
+ */
9
+ function checkShows(snapshot) {
10
+ const shots = snapshot.shots;
11
+ if (shots === void 0) return [];
12
+ const findings = [...shots.showsFindings];
13
+ const settings = snapshot.settings ?? DEFAULT_GRIMOIRE_SETTINGS;
14
+ const languages = settings.languages.length > 0 ? settings.languages : [""];
15
+ const optedOut = new Set(shots.optedOut);
16
+ const captures = new Map((shots.captures?.captures ?? []).map((capture) => [`${capture.ref} ${capture.criterion} ${capture.language}`, capture]));
17
+ const approved = new Set((shots.baseline?.shots ?? []).map((shot) => `${shot.ref} ${shot.criterion} ${shot.language}`));
18
+ const seen = /* @__PURE__ */ new Set();
19
+ for (const line of shots.shows) {
20
+ if (line.call === null) continue;
21
+ const key = `${line.ref} ${line.criterion}`;
22
+ if (seen.has(key)) continue;
23
+ seen.add(key);
24
+ for (const language of languages) {
25
+ const capture = captures.get(`${key} ${language}`);
26
+ const label = language === "" ? "" : ` in ${language}`;
27
+ const subject = {
28
+ feature: line.feature,
29
+ flow: line.ref,
30
+ at: line.at
31
+ };
32
+ if (capture === void 0) {
33
+ if (shots.mode === "off" || optedOut.has(line.ref)) continue;
34
+ if (shots.mode !== "all" && approved.has(`${key} ${language}`)) continue;
35
+ findings.push(createFinding({
36
+ code: "GR4015",
37
+ message: `${line.ref} ${line.criterion} is shown by a scene but has no capture${label}`,
38
+ ...subject
39
+ }));
40
+ } else if (capture.outcome === "fail") findings.push(createFinding({
41
+ code: "GR4016",
42
+ message: `${line.ref} ${line.criterion} failed${label}: ${capture.error ?? "the scene threw"}`,
43
+ ...subject
44
+ }));
45
+ }
46
+ }
47
+ return findings;
48
+ }
49
+
50
+ //#endregion
51
+ export { checkShows };
52
+ //# sourceMappingURL=shows.mjs.map