@warlock.js/grimoire 5.57.0 → 5.59.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 (123) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/esm/apps/check-apps.mjs +11 -5
  3. package/esm/apps/check-apps.mjs.map +1 -1
  4. package/esm/book/build.d.mts.map +1 -1
  5. package/esm/book/build.mjs +2 -1
  6. package/esm/book/build.mjs.map +1 -1
  7. package/esm/book/render.mjs +10 -0
  8. package/esm/book/render.mjs.map +1 -1
  9. package/esm/bookmap/build.d.mts.map +1 -1
  10. package/esm/bookmap/build.mjs +7 -5
  11. package/esm/bookmap/build.mjs.map +1 -1
  12. package/esm/bookmap/steps.mjs +85 -39
  13. package/esm/bookmap/steps.mjs.map +1 -1
  14. package/esm/check/check-grimoire.d.mts.map +1 -1
  15. package/esm/check/check-grimoire.mjs +4 -1
  16. package/esm/check/check-grimoire.mjs.map +1 -1
  17. package/esm/check/rules/criteria.mjs +21 -2
  18. package/esm/check/rules/criteria.mjs.map +1 -1
  19. package/esm/check/rules/screenshots.mjs +57 -0
  20. package/esm/check/rules/screenshots.mjs.map +1 -0
  21. package/esm/codes/codes.d.mts +12 -0
  22. package/esm/codes/codes.d.mts.map +1 -1
  23. package/esm/codes/codes.mjs +6 -0
  24. package/esm/codes/codes.mjs.map +1 -1
  25. package/esm/contracts/adapter.d.mts +28 -1
  26. package/esm/contracts/adapter.d.mts.map +1 -1
  27. package/esm/contracts/book.d.mts +2 -0
  28. package/esm/contracts/book.d.mts.map +1 -1
  29. package/esm/contracts/book.mjs.map +1 -1
  30. package/esm/contracts/bookmap.d.mts +19 -1
  31. package/esm/contracts/bookmap.d.mts.map +1 -1
  32. package/esm/contracts/scry.d.mts +26 -6
  33. package/esm/contracts/scry.d.mts.map +1 -1
  34. package/esm/contracts/snapshot.d.mts +14 -1
  35. package/esm/contracts/snapshot.d.mts.map +1 -1
  36. package/esm/contracts/test-results.d.mts +34 -0
  37. package/esm/contracts/test-results.d.mts.map +1 -1
  38. package/esm/contracts/written.d.mts +44 -0
  39. package/esm/contracts/written.d.mts.map +1 -1
  40. package/esm/contracts/written.mjs.map +1 -1
  41. package/esm/devtools/data.mjs +116 -5
  42. package/esm/devtools/data.mjs.map +1 -1
  43. package/esm/devtools/feature-map.mjs +149 -0
  44. package/esm/devtools/feature-map.mjs.map +1 -0
  45. package/esm/devtools/index.d.mts +28 -2
  46. package/esm/devtools/index.d.mts.map +1 -1
  47. package/esm/devtools/index.mjs +111 -7
  48. package/esm/devtools/index.mjs.map +1 -1
  49. package/esm/devtools/product-map.d.mts +14 -0
  50. package/esm/devtools/product-map.d.mts.map +1 -0
  51. package/esm/devtools/product-map.mjs +460 -0
  52. package/esm/devtools/product-map.mjs.map +1 -0
  53. package/esm/devtools/site.d.mts +43 -1
  54. package/esm/devtools/site.d.mts.map +1 -1
  55. package/esm/devtools/site.mjs +190 -22
  56. package/esm/devtools/site.mjs.map +1 -1
  57. package/esm/devtools/snapshot-source.mjs +24 -7
  58. package/esm/devtools/snapshot-source.mjs.map +1 -1
  59. package/esm/graph/index.d.mts +10 -1
  60. package/esm/graph/index.d.mts.map +1 -1
  61. package/esm/graph/index.mjs +3 -2
  62. package/esm/graph/index.mjs.map +1 -1
  63. package/esm/index.d.mts +5 -5
  64. package/esm/ownership/index.d.mts.map +1 -1
  65. package/esm/ownership/index.mjs +60 -1
  66. package/esm/ownership/index.mjs.map +1 -1
  67. package/esm/paths/index.d.mts +2 -0
  68. package/esm/paths/index.d.mts.map +1 -1
  69. package/esm/paths/index.mjs +3 -1
  70. package/esm/paths/index.mjs.map +1 -1
  71. package/esm/scry/compact.mjs +170 -0
  72. package/esm/scry/compact.mjs.map +1 -0
  73. package/esm/scry/format.d.mts.map +1 -1
  74. package/esm/scry/format.mjs +19 -2
  75. package/esm/scry/format.mjs.map +1 -1
  76. package/esm/scry/query.d.mts.map +1 -1
  77. package/esm/scry/query.mjs +159 -24
  78. package/esm/scry/query.mjs.map +1 -1
  79. package/esm/test-results/index.d.mts +7 -2
  80. package/esm/test-results/index.d.mts.map +1 -1
  81. package/esm/test-results/index.mjs +79 -12
  82. package/esm/test-results/index.mjs.map +1 -1
  83. package/esm/vitest/index.d.mts +6 -0
  84. package/esm/vitest/index.d.mts.map +1 -1
  85. package/esm/vitest/index.mjs +22 -6
  86. package/esm/vitest/index.mjs.map +1 -1
  87. package/esm/warlock/actions.mjs +15 -7
  88. package/esm/warlock/actions.mjs.map +1 -1
  89. package/esm/warlock/adapter.d.mts.map +1 -1
  90. package/esm/warlock/adapter.mjs +42 -4
  91. package/esm/warlock/adapter.mjs.map +1 -1
  92. package/esm/warlock/commands.mjs +7 -2
  93. package/esm/warlock/commands.mjs.map +1 -1
  94. package/esm/warlock/logo.mjs +12 -0
  95. package/esm/warlock/logo.mjs.map +1 -0
  96. package/esm/warlock/mcp-tools.mjs +51 -15
  97. package/esm/warlock/mcp-tools.mjs.map +1 -1
  98. package/esm/workspace/cache.mjs +194 -0
  99. package/esm/workspace/cache.mjs.map +1 -0
  100. package/esm/workspace/index.d.mts.map +1 -1
  101. package/esm/workspace/index.mjs +7 -3
  102. package/esm/workspace/index.mjs.map +1 -1
  103. package/esm/written/apps.mjs +4 -2
  104. package/esm/written/apps.mjs.map +1 -1
  105. package/esm/written/features.mjs +119 -6
  106. package/esm/written/features.mjs.map +1 -1
  107. package/esm/written/markdown.mjs +66 -1
  108. package/esm/written/markdown.mjs.map +1 -1
  109. package/esm/written/parse-grimoire.d.mts.map +1 -1
  110. package/esm/written/parse-grimoire.mjs +1 -1
  111. package/esm/written/parse-grimoire.mjs.map +1 -1
  112. package/llms-full.txt +108 -12
  113. package/package.json +3 -3
  114. package/skills/backfill-a-grimoire/SKILL.md +5 -0
  115. package/skills/describe-an-app/SKILL.md +12 -0
  116. package/skills/record-a-change/SKILL.md +10 -0
  117. package/skills/use-the-grimoire/SKILL.md +44 -10
  118. package/skills/write-a-feature/SKILL.md +37 -2
  119. package/ui/grimoire-static.js +61 -6
  120. package/ui/grimoire-view.js +2133 -316
  121. package/ui/grimoire.css +1030 -24
  122. package/ui/product-map.css +785 -0
  123. package/ui/product-map.js +1265 -0
package/CHANGELOG.md CHANGED
@@ -2,6 +2,50 @@
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.59.0 - 2026-11-19
6
+
7
+ ### Added
8
+
9
+ - The adapter has an optional `host()` that reports the framework name, version and logo and the app's name and version (its `package.json`). The devtools tab shows them in the header and footer, and the static export does too. The Warlock adapter implements it.
10
+ - The flow list shows flow cards with the counts that matter (steps, cases, criteria, proven criteria, unexpected findings), and `scry --feature` answers carry the same counts per flow.
11
+ - A "What changed" timeline lists releases, tasks and changes with reference chips that jump to the feature or flow they name.
12
+ - Feature and flow pages are tabbed. A feature map shows flows against apps, and the flow page's journey and health strip sit in their own tabs. A loading skeleton shows while the book opens.
13
+ - The Product map sorts its features and shows what changed since a release you pick.
14
+ - `warlock grimoire build --site --product` exports the share-safe Product map only: no file paths, test names or per-file answers, and the page opens on the map.
15
+ - Search indexes the written text of flows (summary, who, story, cases and criteria such as AC-5), and written content ranks above files and exports; hits are grouped by type.
16
+ - `openGrimoire`'s snapshot source takes an opt-in `collectRoutes` option that collects route, event and job facts once when the book has none. It boots the app for inspection, so it is meant for tooling processes only, never for a process that serves the app; the devtools panel does not use it.
17
+
18
+ ### Changed
19
+
20
+ - The MCP server (and any long-running process that queries the book) keeps the opened book in memory between calls and opens it again only when a file or folder it lists changed; a one-off `warlock scry` call still opens the book once. `build --site` leaves the page alone when it was built from the same book; `--force` writes it again.
21
+ - Steps that could not be checked (no route facts yet) are counted as unchecked, apart from the missing ones, and never count against a flow's health.
22
+ - The shared Product map shows a grey "not measured" instead of a problem when no test results were recorded.
23
+
24
+ ### Fixed
25
+
26
+ - GR3006 no longer reports files that are reached: route middleware is followed, files with a role that runs by being present (migration, seed, command, main, layout, root) are exempt, and test helpers (files under `tests/`, `__tests__/`, `fixtures/`, `support/` or named `*.test-utils.*`) that only specs import count as reached. A source file that only its own spec imports still warns.
27
+ - GR5008 is skipped for mail and notification entries when the book has no route facts, instead of reporting an entry the booted app would have confirmed.
28
+
29
+ ## 5.58.0 - 2026-11-18
30
+
31
+ ### Added
32
+
33
+ - Flows have a summary: the paragraph under the `# Title`. It shows on the flow page, in `scry --flow` and in the product map. A flow without one gets the warning GR1030.
34
+ - The devtools Grimoire tab has a flow page: summary, status and origin, previous and next flow, a health strip, a "Fix next" box with a ready `@proves` line, the journey as a stepper with file counts, one row per criterion with its tests, and edge cases with "does not apply" collapsed.
35
+ - A "Product map" view in the Grimoire tab for readers who do not read code: feature cards with a plain summary, audience, apps and a health light; feature pages with why, flows as short stories, where each appears in the apps with screenshots, release history and planned work; flow pages with the steps in the user's words and what proves them. Code detail sits behind "For developers". In the production monitor an admin can share it with a read-only link.
36
+ - Written format: feature `audience` and `## Why`, flow `## Story`, screenshots as image lines pointing into `grimoire/screenshots/` (pages, blocks and story steps), and `(AC-n)` at the end of a case line to link it to a criterion. New checks GR1029, GR2013 and GR2014.
37
+ - The panel option `testResultsFile` reads test results from another file; the reporter writes there with `grimoireReporter({ file })`. New warnings GR4009 (proofs but no recorded results) and GR4010 (a proving test the reporter could not match).
38
+ - The static export includes the product map and its screenshots.
39
+ - A new route pages through the files of one flow step.
40
+
41
+ ### Changed
42
+
43
+ - Flow steps list the files that run: type-only imports are no longer followed, so a page that imports a type through a barrel no longer lists the server files behind it. Book maps add `entries`, `direct` and `typeOnlyFiles` per step, and book entries add `typeOnlyImports`. Ownership coverage (GR3006) still counts type-only reach.
44
+ - The devtools flow answer and the MCP `grimoire_flow` tool send counts and direct imports per step instead of every reachable file. Flow answers on large apps drop from megabytes to kilobytes.
45
+ - The Check tab groups findings by code with counts and the fix shown once, filters by severity, code, feature and flow, and shows "files no flow reaches" (GR3006) one row per feature. The Overview's top problems rank by severity, then by count.
46
+ - The devtools tab works on phones: cards instead of tables, scrolling sub-tabs, no overflowing tables or wrapped ids, and readable module graph labels. Code spans in criteria and task text render as code.
47
+ - The Test results view tells "no results recorded" apart from "did not run" and picks up new results without a restart.
48
+
5
49
  ## 5.57.0 - 2026-11-18
6
50
 
7
51
  ### Added
@@ -106,7 +106,7 @@ function checkApps(snapshot) {
106
106
  app: appId,
107
107
  ...subject
108
108
  }));
109
- if (match) checkReached(page, label, subject, appId, facts, match, app.screens, findings);
109
+ if (match) checkReached(page, label, subject, appId, facts, match, app.screens, findings, snapshot.routes);
110
110
  }
111
111
  if (app.file !== null && (!match || !match.site && !match.mobile)) {
112
112
  findings.push(createFinding({
@@ -154,12 +154,18 @@ function checkApps(snapshot) {
154
154
  checkUncovered(snapshot, findings);
155
155
  return findings;
156
156
  }
157
- /** GR5008: an `Also reached from` entry that names nothing the code has. */
158
- function checkReached(page, label, subject, appId, facts, match, declaredScreens, findings) {
157
+ /**
158
+ * GR5008: an `Also reached from` entry that names nothing the code has. A mail
159
+ * or notification entry is not checked without route facts (`routes: missing`):
160
+ * the booted app is what reports them, so their absence proves nothing.
161
+ */
162
+ function checkReached(page, label, subject, appId, facts, match, declaredScreens, findings, routes) {
159
163
  for (const entry of page.alsoReachedFrom) {
160
164
  let found = true;
161
- if (entry.type === "mail" || entry.type === "notification") found = facts.named.some((item) => item.type === entry.type && item.name === entry.name);
162
- else if (entry.type === "page") {
165
+ if (entry.type === "mail" || entry.type === "notification") {
166
+ if (routes === "missing") continue;
167
+ found = facts.named.some((item) => item.type === entry.type && item.name === entry.name);
168
+ } else if (entry.type === "page") {
163
169
  const site = match.site;
164
170
  const wanted = normalizeRoute(entry.name);
165
171
  found = site !== null && facts.pages.some((item) => item.site === site.id && (normalizeRoute(item.route) === wanted || item.name === entry.name));
@@ -1 +1 @@
1
- {"version":3,"file":"check-apps.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/apps/check-apps.ts"],"sourcesContent":["/**\n * GR5001–GR5009: the written apps against the sites, pages, screens, flows\n * and conditions they mention.\n */\nimport { createFinding } from \"../codes\";\nimport type { BookFacts } from \"../contracts/adapter\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type { SourceLocation } from \"../contracts/location\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenApp, WrittenBlockRow, WrittenPage } from \"../contracts/written\";\nimport { toPosixPath } from \"../paths\";\n\ntype Subject = { feature: string | null; flow: string | null };\n\n/** The feature and flow a block row points at, split from `<feature>/<flow>`. */\nfunction flowSubject(flow: string | null): Subject {\n if (!flow) return { feature: null, flow: null };\n\n return { feature: flow.split(\"/\")[0] ?? null, flow };\n}\n\n/** The flow all blocks of a page share, else their feature when they share one, else nothing. */\nfunction pageSubject(page: WrittenPage): Subject {\n const refs = [...new Set(page.blocks.map((row) => row.flow).filter((ref) => ref !== null))];\n\n if (refs.length === 1) return flowSubject(refs[0] ?? null);\n\n const features = [...new Set(refs.map((ref) => ref.split(\"/\")[0] ?? \"\"))];\n\n return { feature: features.length === 1 ? (features[0] ?? null) : null, flow: null };\n}\n\n/** A route as the router and the page graph compare it: `[id]` and `:id` are one parameter. */\nfunction normalizeRoute(route: string): string {\n const withSlash = toPosixPath(route.trim())\n .replace(/\\[\\.\\.\\.(\\w+)\\]/g, \":$1*\")\n .replace(/\\[(\\w+)\\]/g, \":$1\");\n const trimmed = withSlash.replace(/\\/+$/, \"\");\n\n return trimmed === \"\" ? \"/\" : trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n}\n\n/** The id of a block file for a table row: `New arrivals` → `new-arrivals`. */\nfunction blockSlug(block: string): string {\n return block\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\n\nfunction pagesOf(app: WrittenApp): WrittenPage[] {\n return [...app.pages, ...app.screens];\n}\n\n/**\n * GR5001–GR5009. Read-only. Pages and screens are compared with the adapter's\n * facts only when the app matched a site or mobile app (`GR5005` otherwise).\n */\nexport function checkApps(snapshot: GrimoireSnapshot): GrimoireFinding[] {\n const findings: GrimoireFinding[] = [];\n const facts = snapshot.book.facts;\n const flows = new Set<string>();\n\n for (const feature of snapshot.written.features) {\n for (const flow of feature.flows) flows.add(`${feature.id}/${flow.id.value}`);\n }\n\n for (const app of snapshot.written.apps) {\n const match = snapshot.apps[app.id.value] ?? null;\n const appId = app.id.value;\n const declared = new Set(app.conditions.map((line) => line.name));\n const layoutIds = new Set(app.layouts.map((layout) => layout.id));\n\n const checkRow = (row: WrittenBlockRow): void => {\n const subject = flowSubject(row.flow);\n\n if (row.flow !== null && !flows.has(row.flow)) {\n findings.push(\n createFinding({\n code: \"GR5001\",\n message: `block \"${row.block}\" points to flow \"${row.flow}\", which does not exist`,\n at: row.at,\n app: appId,\n ...subject,\n }),\n );\n }\n\n const used = [\n ...row.who.conditions,\n ...row.changesWith.flatMap((item) => (item.condition === null ? [] : [item.condition])),\n ];\n\n for (const condition of new Set(used)) {\n if (declared.has(condition)) continue;\n\n findings.push(\n createFinding({\n code: \"GR5002\",\n message: `condition \"${condition}\" is not declared in the README of app \"${appId}\"`,\n at: row.at,\n app: appId,\n ...subject,\n }),\n );\n }\n };\n\n for (const layout of app.layouts) layout.blocks.forEach(checkRow);\n\n for (const page of pagesOf(app)) {\n const subject = pageSubject(page);\n const label = `${page.type} \"${page.id}\"`;\n\n page.blocks.forEach(checkRow);\n\n for (const block of page.blockFiles) {\n if (block.flow !== null && !flows.has(block.flow.value)) {\n findings.push(\n createFinding({\n code: \"GR5001\",\n message: `block file \"${block.id}\" of ${label} points to flow \"${block.flow.value}\", which does not exist`,\n at: block.flow.at,\n app: appId,\n ...flowSubject(block.flow.value),\n }),\n );\n }\n\n if (!page.blocks.some((row) => blockSlug(row.block) === block.id)) {\n findings.push(\n createFinding({\n code: \"GR5007\",\n message: `block file \"${block.id}\" has no row in the Blocks table of ${label}`,\n at: { file: block.file, line: 1, column: null },\n app: appId,\n ...(block.flow ? flowSubject(block.flow.value) : subject),\n }),\n );\n }\n }\n\n if (page.layout !== null && !layoutIds.has(page.layout.value)) {\n findings.push(\n createFinding({\n code: \"GR5004\",\n message: `${label} names layout \"${page.layout.value}\", but ${app.dir}/layouts/${page.layout.value}.md does not exist`,\n at: page.layout.at,\n app: appId,\n ...subject,\n }),\n );\n }\n\n if (match) checkReached(page, label, subject, appId, facts, match, app.screens, findings);\n }\n\n // An app folder with no README is reported as GR1021 by the parser.\n if (app.file !== null && (!match || (!match.site && !match.mobile))) {\n findings.push(\n createFinding({\n code: \"GR5005\",\n message: `the root \"${app.root.value}\" of app \"${appId}\" matches no ${app.type.value === \"site\" ? \"site\" : \"mobile app\"} the code reports`,\n at: app.root.at,\n app: appId,\n }),\n );\n continue;\n }\n\n if (!match) continue;\n\n if (match.site) {\n const routes = new Set(\n facts.pages\n .filter((item) => item.site === match.site?.id)\n .map((item) => normalizeRoute(item.route)),\n );\n\n for (const page of app.pages) {\n if (!page.route || routes.has(normalizeRoute(page.route.value))) continue;\n\n findings.push(\n createFinding({\n code: \"GR5003\",\n message: `page \"${page.id}\" has route \"${page.route.value}\", which is not a page of site \"${match.site.id}\"`,\n at: page.route.at,\n app: appId,\n ...pageSubject(page),\n }),\n );\n }\n }\n\n if (match.mobile && match.mobile.routing === \"files\") {\n const routes = new Set(match.mobile.screens.map((screen) => normalizeRoute(screen.route)));\n\n for (const screen of app.screens) {\n const where: SourceLocation | null = screen.route?.at ?? screen.screen?.at ?? null;\n const route = screen.route?.value ?? null;\n\n if (route !== null && routes.has(normalizeRoute(route))) continue;\n\n findings.push(\n createFinding({\n code: \"GR5006\",\n message:\n route === null\n ? `screen \"${screen.id}\" has no route, and mobile app \"${match.mobile.id}\" uses file-based routing`\n : `screen \"${screen.id}\" has route \"${route}\", which is not a screen of mobile app \"${match.mobile.id}\"`,\n at: where ?? { file: screen.file, line: 1, column: null },\n app: appId,\n ...pageSubject(screen),\n }),\n );\n }\n }\n }\n\n checkUncovered(snapshot, findings);\n\n return findings;\n}\n\n/** GR5008: an `Also reached from` entry that names nothing the code has. */\nfunction checkReached(\n page: WrittenPage,\n label: string,\n subject: Subject,\n appId: string,\n facts: BookFacts,\n match: NonNullable<GrimoireSnapshot[\"apps\"][string]>,\n declaredScreens: readonly WrittenPage[],\n findings: GrimoireFinding[],\n): void {\n for (const entry of page.alsoReachedFrom) {\n let found = true;\n\n if (entry.type === \"mail\" || entry.type === \"notification\") {\n found = facts.named.some((item) => item.type === entry.type && item.name === entry.name);\n } else if (entry.type === \"page\") {\n const site = match.site;\n const wanted = normalizeRoute(entry.name);\n\n found =\n site !== null &&\n facts.pages.some(\n (item) =>\n item.site === site.id &&\n (normalizeRoute(item.route) === wanted || item.name === entry.name),\n );\n } else if (entry.type === \"screen\") {\n const wanted = normalizeRoute(entry.name);\n\n found =\n match.mobile?.screens.some((item) => normalizeRoute(item.route) === wanted) === true ||\n declaredScreens.some(\n (item) =>\n item.id === entry.name ||\n item.screen?.value === entry.name ||\n (item.route !== null && normalizeRoute(item.route.value) === wanted),\n );\n }\n\n if (found) continue;\n\n findings.push(\n createFinding({\n code: \"GR5008\",\n message: `${label} is reached from ${entry.type} \"${entry.name}\", which does not exist`,\n at: entry.at,\n app: appId,\n ...subject,\n }),\n );\n }\n}\n\n/** GR5009: a site or mobile app the code reports that no written app describes. */\nfunction checkUncovered(snapshot: GrimoireSnapshot, findings: GrimoireFinding[]): void {\n if (snapshot.written.apps.length === 0) return;\n\n const sites = new Set<string>();\n const mobiles = new Set<string>();\n\n for (const match of Object.values(snapshot.apps)) {\n if (match.site) sites.add(match.site.id);\n if (match.mobile) mobiles.add(match.mobile.id);\n }\n\n for (const site of snapshot.book.facts.sites) {\n if (sites.has(site.id)) continue;\n\n findings.push(\n createFinding({\n code: \"GR5009\",\n message: `site \"${site.id}\" (${site.root}) has no folder in grimoire/apps`,\n }),\n );\n }\n\n for (const mobile of snapshot.book.facts.mobile) {\n if (mobiles.has(mobile.id)) continue;\n\n findings.push(\n createFinding({\n code: \"GR5009\",\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QAAQ,SAAS,KAAK,MAAM,OAAO;EAC5C,IAAI,MAAM,IAAI,KAAK,EAAE,GAAG;EAExB,SAAS,KACP,cAAc;GACZ,MAAM;GACN,SAAS,SAAS,KAAK,GAAG,KAAK,KAAK,KAAK;EAC3C,CAAC,CACH;CACF;CAEA,KAAK,MAAM,UAAU,SAAS,KAAK,MAAM,QAAQ;EAC/C,IAAI,QAAQ,IAAI,OAAO,EAAE,GAAG;EAE5B,SAAS,KACP,cAAc;GACZ,MAAM;GACN,SAAS,eAAe,OAAO,GAAG,KAAK,OAAO,KAAK;EACrD,CAAC,CACH;CACF;AACF"}
1
+ {"version":3,"file":"check-apps.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/apps/check-apps.ts"],"sourcesContent":["/**\n * GR5001–GR5009: the written apps against the sites, pages, screens, flows\n * and conditions they mention.\n */\nimport { createFinding } from \"../codes\";\nimport type { BookFacts } from \"../contracts/adapter\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type { SourceLocation } from \"../contracts/location\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenApp, WrittenBlockRow, WrittenPage } from \"../contracts/written\";\nimport { toPosixPath } from \"../paths\";\n\ntype Subject = { feature: string | null; flow: string | null };\n\n/** The feature and flow a block row points at, split from `<feature>/<flow>`. */\nfunction flowSubject(flow: string | null): Subject {\n if (!flow) return { feature: null, flow: null };\n\n return { feature: flow.split(\"/\")[0] ?? null, flow };\n}\n\n/** The flow all blocks of a page share, else their feature when they share one, else nothing. */\nfunction pageSubject(page: WrittenPage): Subject {\n const refs = [...new Set(page.blocks.map((row) => row.flow).filter((ref) => ref !== null))];\n\n if (refs.length === 1) return flowSubject(refs[0] ?? null);\n\n const features = [...new Set(refs.map((ref) => ref.split(\"/\")[0] ?? \"\"))];\n\n return { feature: features.length === 1 ? (features[0] ?? null) : null, flow: null };\n}\n\n/** A route as the router and the page graph compare it: `[id]` and `:id` are one parameter. */\nfunction normalizeRoute(route: string): string {\n const withSlash = toPosixPath(route.trim())\n .replace(/\\[\\.\\.\\.(\\w+)\\]/g, \":$1*\")\n .replace(/\\[(\\w+)\\]/g, \":$1\");\n const trimmed = withSlash.replace(/\\/+$/, \"\");\n\n return trimmed === \"\" ? \"/\" : trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n}\n\n/** The id of a block file for a table row: `New arrivals` → `new-arrivals`. */\nfunction blockSlug(block: string): string {\n return block\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\n\nfunction pagesOf(app: WrittenApp): WrittenPage[] {\n return [...app.pages, ...app.screens];\n}\n\n/**\n * GR5001–GR5009. Read-only. Pages and screens are compared with the adapter's\n * facts only when the app matched a site or mobile app (`GR5005` otherwise).\n */\nexport function checkApps(snapshot: GrimoireSnapshot): GrimoireFinding[] {\n const findings: GrimoireFinding[] = [];\n const facts = snapshot.book.facts;\n const flows = new Set<string>();\n\n for (const feature of snapshot.written.features) {\n for (const flow of feature.flows) flows.add(`${feature.id}/${flow.id.value}`);\n }\n\n for (const app of snapshot.written.apps) {\n const match = snapshot.apps[app.id.value] ?? null;\n const appId = app.id.value;\n const declared = new Set(app.conditions.map((line) => line.name));\n const layoutIds = new Set(app.layouts.map((layout) => layout.id));\n\n const checkRow = (row: WrittenBlockRow): void => {\n const subject = flowSubject(row.flow);\n\n if (row.flow !== null && !flows.has(row.flow)) {\n findings.push(\n createFinding({\n code: \"GR5001\",\n message: `block \"${row.block}\" points to flow \"${row.flow}\", which does not exist`,\n at: row.at,\n app: appId,\n ...subject,\n }),\n );\n }\n\n const used = [\n ...row.who.conditions,\n ...row.changesWith.flatMap((item) => (item.condition === null ? [] : [item.condition])),\n ];\n\n for (const condition of new Set(used)) {\n if (declared.has(condition)) continue;\n\n findings.push(\n createFinding({\n code: \"GR5002\",\n message: `condition \"${condition}\" is not declared in the README of app \"${appId}\"`,\n at: row.at,\n app: appId,\n ...subject,\n }),\n );\n }\n };\n\n for (const layout of app.layouts) layout.blocks.forEach(checkRow);\n\n for (const page of pagesOf(app)) {\n const subject = pageSubject(page);\n const label = `${page.type} \"${page.id}\"`;\n\n page.blocks.forEach(checkRow);\n\n for (const block of page.blockFiles) {\n if (block.flow !== null && !flows.has(block.flow.value)) {\n findings.push(\n createFinding({\n code: \"GR5001\",\n message: `block file \"${block.id}\" of ${label} points to flow \"${block.flow.value}\", which does not exist`,\n at: block.flow.at,\n app: appId,\n ...flowSubject(block.flow.value),\n }),\n );\n }\n\n if (!page.blocks.some((row) => blockSlug(row.block) === block.id)) {\n findings.push(\n createFinding({\n code: \"GR5007\",\n message: `block file \"${block.id}\" has no row in the Blocks table of ${label}`,\n at: { file: block.file, line: 1, column: null },\n app: appId,\n ...(block.flow ? flowSubject(block.flow.value) : subject),\n }),\n );\n }\n }\n\n if (page.layout !== null && !layoutIds.has(page.layout.value)) {\n findings.push(\n createFinding({\n code: \"GR5004\",\n message: `${label} names layout \"${page.layout.value}\", but ${app.dir}/layouts/${page.layout.value}.md does not exist`,\n at: page.layout.at,\n app: appId,\n ...subject,\n }),\n );\n }\n\n if (match)\n checkReached(\n page,\n label,\n subject,\n appId,\n facts,\n match,\n app.screens,\n findings,\n snapshot.routes,\n );\n }\n\n // An app folder with no README is reported as GR1021 by the parser.\n if (app.file !== null && (!match || (!match.site && !match.mobile))) {\n findings.push(\n createFinding({\n code: \"GR5005\",\n message: `the root \"${app.root.value}\" of app \"${appId}\" matches no ${app.type.value === \"site\" ? \"site\" : \"mobile app\"} the code reports`,\n at: app.root.at,\n app: appId,\n }),\n );\n continue;\n }\n\n if (!match) continue;\n\n if (match.site) {\n const routes = new Set(\n facts.pages\n .filter((item) => item.site === match.site?.id)\n .map((item) => normalizeRoute(item.route)),\n );\n\n for (const page of app.pages) {\n if (!page.route || routes.has(normalizeRoute(page.route.value))) continue;\n\n findings.push(\n createFinding({\n code: \"GR5003\",\n message: `page \"${page.id}\" has route \"${page.route.value}\", which is not a page of site \"${match.site.id}\"`,\n at: page.route.at,\n app: appId,\n ...pageSubject(page),\n }),\n );\n }\n }\n\n if (match.mobile && match.mobile.routing === \"files\") {\n const routes = new Set(match.mobile.screens.map((screen) => normalizeRoute(screen.route)));\n\n for (const screen of app.screens) {\n const where: SourceLocation | null = screen.route?.at ?? screen.screen?.at ?? null;\n const route = screen.route?.value ?? null;\n\n if (route !== null && routes.has(normalizeRoute(route))) continue;\n\n findings.push(\n createFinding({\n code: \"GR5006\",\n message:\n route === null\n ? `screen \"${screen.id}\" has no route, and mobile app \"${match.mobile.id}\" uses file-based routing`\n : `screen \"${screen.id}\" has route \"${route}\", which is not a screen of mobile app \"${match.mobile.id}\"`,\n at: where ?? { file: screen.file, line: 1, column: null },\n app: appId,\n ...pageSubject(screen),\n }),\n );\n }\n }\n }\n\n checkUncovered(snapshot, findings);\n\n return findings;\n}\n\n/**\n * GR5008: an `Also reached from` entry that names nothing the code has. A mail\n * or notification entry is not checked without route facts (`routes: missing`):\n * the booted app is what reports them, so their absence proves nothing.\n */\nfunction checkReached(\n page: WrittenPage,\n label: string,\n subject: Subject,\n appId: string,\n facts: BookFacts,\n match: NonNullable<GrimoireSnapshot[\"apps\"][string]>,\n declaredScreens: readonly WrittenPage[],\n findings: GrimoireFinding[],\n routes: GrimoireSnapshot[\"routes\"],\n): void {\n for (const entry of page.alsoReachedFrom) {\n let found = true;\n\n if (entry.type === \"mail\" || entry.type === \"notification\") {\n if (routes === \"missing\") continue;\n\n found = facts.named.some((item) => item.type === entry.type && item.name === entry.name);\n } else if (entry.type === \"page\") {\n const site = match.site;\n const wanted = normalizeRoute(entry.name);\n\n found =\n site !== null &&\n facts.pages.some(\n (item) =>\n item.site === site.id &&\n (normalizeRoute(item.route) === wanted || item.name === entry.name),\n );\n } else if (entry.type === \"screen\") {\n const wanted = normalizeRoute(entry.name);\n\n found =\n match.mobile?.screens.some((item) => normalizeRoute(item.route) === wanted) === true ||\n declaredScreens.some(\n (item) =>\n item.id === entry.name ||\n item.screen?.value === entry.name ||\n (item.route !== null && normalizeRoute(item.route.value) === wanted),\n );\n }\n\n if (found) continue;\n\n findings.push(\n createFinding({\n code: \"GR5008\",\n message: `${label} is reached from ${entry.type} \"${entry.name}\", which does not exist`,\n at: entry.at,\n app: appId,\n ...subject,\n }),\n );\n }\n}\n\n/** GR5009: a site or mobile app the code reports that no written app describes. */\nfunction checkUncovered(snapshot: GrimoireSnapshot, findings: GrimoireFinding[]): void {\n if (snapshot.written.apps.length === 0) return;\n\n const sites = new Set<string>();\n const mobiles = new Set<string>();\n\n for (const match of Object.values(snapshot.apps)) {\n if (match.site) sites.add(match.site.id);\n if (match.mobile) mobiles.add(match.mobile.id);\n }\n\n for (const site of snapshot.book.facts.sites) {\n if (sites.has(site.id)) continue;\n\n findings.push(\n createFinding({\n code: \"GR5009\",\n message: `site \"${site.id}\" (${site.root}) has no folder in grimoire/apps`,\n }),\n );\n }\n\n for (const mobile of snapshot.book.facts.mobile) {\n if (mobiles.has(mobile.id)) continue;\n\n findings.push(\n createFinding({\n code: \"GR5009\",\n message: `mobile app \"${mobile.id}\" (${mobile.root}) has no folder in grimoire/apps`,\n }),\n );\n }\n}\n"],"mappings":";;;;;;;;;AAeA,SAAS,YAAY,MAA8B;CACjD,IAAI,CAAC,MAAM,OAAO;EAAE,SAAS;EAAM,MAAM;CAAK;CAE9C,OAAO;EAAE,SAAS,KAAK,MAAM,GAAG,CAAC,CAAC,MAAM;EAAM;CAAK;AACrD;;AAGA,SAAS,YAAY,MAA4B;CAC/C,MAAM,OAAO,CAAC,GAAG,IAAI,IAAI,KAAK,OAAO,KAAK,QAAQ,IAAI,IAAI,CAAC,CAAC,QAAQ,QAAQ,QAAQ,IAAI,CAAC,CAAC;CAE1F,IAAI,KAAK,WAAW,GAAG,OAAO,YAAY,KAAK,MAAM,IAAI;CAEzD,MAAM,WAAW,CAAC,GAAG,IAAI,IAAI,KAAK,KAAK,QAAQ,IAAI,MAAM,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC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AyKW,SAAS,eAAe,QAAQ"}
1
+ {"version":3,"file":"build.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/build.ts"],"mappings":";;;;;;;;;wBAySsB,UACpB,cACA,SAAS,aACT,UAAS,mBACR,QAAQ;;wBAyKW,SAAS,eAAe,QAAQ"}
@@ -32,7 +32,7 @@ const absolutePath = (root, file) => path.join(root, ...file.split("/"));
32
32
  async function readStoredBook(root) {
33
33
  const manifest = await readJson(absolutePath(root, GRIMOIRE_PATHS.bookManifest));
34
34
  const cache = await readJson(absolutePath(root, GRIMOIRE_PATHS.bookFactsCache));
35
- if (manifest === null || cache === null || manifest.schemaVersion !== 1 || cache.schemaVersion !== 1 || typeof manifest.files !== "object" || typeof cache.facts !== "object") return null;
35
+ if (manifest === null || cache === null || manifest.schemaVersion !== 1 || cache.schemaVersion !== 1 || cache.typeOnlyEdges !== true || typeof manifest.files !== "object" || typeof cache.facts !== "object") return null;
36
36
  return {
37
37
  manifest,
38
38
  facts: cache.facts
@@ -147,6 +147,7 @@ async function writeStoredBook(root, manifest, facts) {
147
147
  if (facts !== null) {
148
148
  const cache = {
149
149
  schemaVersion: 1,
150
+ typeOnlyEdges: true,
150
151
  facts
151
152
  };
152
153
  await writeBookFile(root, GRIMOIRE_PATHS.bookFactsCache, toJson(cache));
@@ -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\nasync function readStoredBook(root: string): Promise<StoredBook | null> {\n const manifest = await readJson<BookManifest>(absolutePath(root, GRIMOIRE_PATHS.bookManifest));\n const cache = await readJson<BookFactsCache>(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 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\nasync function writeStoredBook(\n root: string,\n manifest: BookManifest,\n facts: BookFacts | null,\n): Promise<void> {\n if (facts !== null) {\n const cache: BookFactsCache = { schemaVersion: BOOK_SCHEMA_VERSION, facts };\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\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 Object.assign(facts, await collectBootFacts(projectRoot, adapter));\n manifest.boot = { collectedAt: now().toISOString(), inputs: current };\n routes = \"fresh\";\n changedBook = true;\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 },\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 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 bootFacts = await collectBootFacts(projectRoot, adapter);\n boot = { collectedAt: now().toISOString(), inputs };\n routes = \"fresh\";\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 },\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"],"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,SAAS,UAAU;CAC5E,QAAQ;EACN,gBAAgB;CAClB;CAEA,OAAO;AACT;AAEA,MAAM,gBAAgB,MAAc,SAAyB,KAAK,KAAK,MAAM,GAAG,KAAK,MAAM,GAAG,CAAC;AAI/F,eAAe,eAAe,MAA0C;CACtE,MAAM,WAAW,MAAM,SAAuB,aAAa,MAAM,eAAe,YAAY,CAAC;CAC7F,MAAM,QAAQ,MAAM,SAAyB,aAAa,MAAM,eAAe,cAAc,CAAC;CAE9F,IACE,aAAa,QACb,UAAU,QACV,SAAS,uBACT,MAAM,uBACN,OAAO,SAAS,UAAU,YAC1B,OAAO,MAAM,UAAU,UAEvB,OAAO;CAGT,OAAO;EAAE;EAAU,OAAO,MAAM;CAAM;AACxC;;AAUA,eAAe,gBACb,MACA,aACA,UACe;CACf,IAAI;CAEJ,IAAI;EACF,SAAS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,MAAM,SAAS,MAAM,eAAe,WAAW;CAE/C,IAAI,WAAW,MAAM,OAAO;CAE5B,OAAO;EACL,MAAM;EACN,UAAU,OAAO;EACjB,OAAO,OAAO;EAEd,QAAQ,OAAO,MAAM,WAAW,OAAO,YAAY;CACrD;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 { 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\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\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 Object.assign(facts, await collectBootFacts(projectRoot, adapter));\n manifest.boot = { collectedAt: now().toISOString(), inputs: current };\n routes = \"fresh\";\n changedBook = true;\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 },\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 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 bootFacts = await collectBootFacts(projectRoot, adapter);\n boot = { collectedAt: now().toISOString(), inputs };\n routes = \"fresh\";\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 },\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"],"mappings":";;;;;;;;;;;;;;;;;AA6CA,MAAa,mB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CAAY;CAC/D,MAAM,UAAU,cAAc,KAAK;CACnC,MAAM,WAAyB;EAC7B;EACA,iBAAiB;EACjB,SAAS;GAAE,MAAM,QAAQ;GAAM,SAAS,QAAQ;EAAQ;EACxD,SAAS,IAAI,CAAC,CAAC,YAAY;EAC3B;EACA,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,CAChD,MACA;GAAE,GAAG;GAAO,OAAO,QAAQ,IAAI,IAAI,KAAK;EAAK,CAC/C,CAAC,CACH;EACA,OAAO,MAAM,UAAU,aAAa,MAAM,OAAO,KAAK,OAAO,WAAW;EACxE,aAAa,QAAQ,SAAS,eAAe;EAC7C;CACF;CAGA,IAAI,OAAO;EACT,IAAI,QAAQ,UAAU,MACpB,MAAM,GAAG,aAAa,aAAa,gBAAgB,GAAG,EAAE,OAAO,KAAK,CAAC;EAEvE,MAAM,gBAAgB,aAAa,UAAU,KAAK;CACpD;CAEA,OAAO;EACL,MAAM;GAAE,MAAM;GAAa;GAAU;GAAO;EAAO;EACnD,SAAS;EACT,SAAS,aAAa,eAAe,KAAK,KAAK;CACjD;AACF;;AAGA,eAAsB,SAAS,MAA0C;CACvE,MAAM,cAAc,KAAK,QAAQ,IAAI;CACrC,MAAM,SAAS,MAAM,eAAe,WAAW;CAE/C,IAAI,WAAW,MAAM,OAAO;CAE5B,OAAO;EACL,MAAM;EACN,UAAU,OAAO;EACjB,OAAO,OAAO;EAEd,QAAQ,OAAO,MAAM,WAAW,OAAO,YAAY;CACrD;AACF"}
@@ -40,6 +40,15 @@ function routeRef(route) {
40
40
  name: route.name
41
41
  };
42
42
  }
43
+ /** Project files whose every import edge from the file is type-only: sorted, unique. */
44
+ function typeOnlyImportsOf(file) {
45
+ const edges = /* @__PURE__ */ new Map();
46
+ for (const entry of file.imports) {
47
+ if (entry.file === null) continue;
48
+ edges.set(entry.file, (edges.get(entry.file) ?? true) && entry.typeOnly === true);
49
+ }
50
+ return [...edges].flatMap(([target, typeOnly]) => typeOnly ? [target] : []).sort(byText);
51
+ }
43
52
  /** External package names a file imports: sorted, unique, Node builtins left out. */
44
53
  function packagesOf(file) {
45
54
  const names = /* @__PURE__ */ new Set();
@@ -123,6 +132,7 @@ function buildEntries(facts, annotations) {
123
132
  })),
124
133
  packages: packagesOf(file),
125
134
  imports: [...new Set(file.imports.flatMap((entry) => entry.file === null ? [] : [entry.file]))].sort(byText),
135
+ typeOnlyImports: typeOnlyImportsOf(file),
126
136
  importedBy: [...new Set(file.importedBy)].sort(byText),
127
137
  routes: fileRoutes,
128
138
  pages: (pages.get(file.file) ?? []).sort((left, right) => byText(left.site, right.site) || byText(left.route, right.route) || byText(left.via, right.via)),
@@ -1 +1 @@
1
- {"version":3,"file":"render.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/render.ts"],"sourcesContent":["/**\n * Turns facts and annotations into the content of every book file: the\n * per-file entries, the module summaries, `app/routes.json` and the page and\n * screen lists. Pure: no IO, so a spec can build inputs by hand.\n */\nimport { isBuiltin } from \"node:module\";\nimport path from \"node:path\";\nimport type { BookFacts, BookFile, BookRoute } from \"../contracts/adapter\";\nimport {\n BOOK_SCHEMA_VERSION,\n type BookAnnotations,\n type BookEntry,\n type BookMobileScreensFile,\n type BookModuleSummary,\n type BookRouteRef,\n type BookRoutesFile,\n type BookSitePagesFile,\n} from \"../contracts/book\";\nimport { packageNameOf } from \"../graph\";\nimport {\n bookEntryPaths,\n GRIMOIRE_PATHS,\n isInsideFolder,\n mobileScreensPath,\n moduleSummaryPath,\n sitePagesPath,\n} from \"../paths\";\nimport { isInsideBook, toJson } from \"./io\";\n\n/** Key of `BookRoutesFile.modules` for routes with no routes file. */\nexport const NO_MODULE = \"(none)\";\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\n\n/**\n * Book entry path of every code file in the facts. A file whose mirror would\n * leave `grimoire/book/` (a path with `..`) has no entry.\n */\nexport function entryPathsFor(facts: Pick<BookFacts, \"files\" | \"mobile\">): Map<string, string> {\n const mobileRoots = new Map(facts.mobile.map((app) => [app.id, app.root]));\n const paths = bookEntryPaths(\n facts.files.map((file) => {\n const mobileRoot = file.mobileApp === null ? undefined : mobileRoots.get(file.mobileApp);\n\n return {\n file: file.file,\n mobileApp:\n file.mobileApp === null || mobileRoot === undefined\n ? null\n : { id: file.mobileApp, root: mobileRoot },\n };\n }),\n );\n\n for (const [file, entry] of paths) {\n if (!isInsideBook(entry)) paths.delete(file);\n }\n\n return paths;\n}\n\nfunction routeRef(route: BookRoute): BookRouteRef {\n return { method: route.method, path: route.path, name: route.name };\n}\n\n/** External package names a file imports: sorted, unique, Node builtins left out. */\nexport function packagesOf(file: BookFile): string[] {\n const names = new Set<string>();\n\n for (const entry of file.imports) {\n if (entry.file !== null) continue;\n\n const name = packageNameOf(entry.specifier);\n\n if (name !== null && !isBuiltin(name)) names.add(name);\n }\n\n return [...names].sort(byText);\n}\n\n/** Lists indexed by a key, built once so lookups per file stay constant time. */\nfunction groupBy<T>(items: Iterable<readonly [string | null, T]>): Map<string, T[]> {\n const groups = new Map<string, T[]>();\n\n for (const [key, item] of items) {\n if (key === null) continue;\n\n const group = groups.get(key);\n\n if (group) group.push(item);\n else groups.set(key, [item]);\n }\n\n return groups;\n}\n\ntype PageUse = {\n readonly site: string;\n readonly route: string;\n readonly via: \"page\" | \"setup\" | \"layout\";\n};\ntype ScreenUse = {\n readonly app: string;\n readonly route: string;\n readonly via: \"screen\" | \"layout\";\n};\n\nconst NO_ANNOTATION = { feature: null, borrowedBy: [], flows: [] } as const;\n\n/** The entry of every code file, by source file. */\nexport function buildEntries(\n facts: BookFacts,\n annotations: BookAnnotations,\n): Map<string, BookEntry> {\n const routes = facts.routes ?? [];\n const registered = groupBy(routes.map((route) => [route.sourceFile, route] as const));\n const handled = groupBy(routes.map((route) => [route.handlerFile, route] as const));\n const pages = groupBy<PageUse>(\n facts.pages.flatMap((page): (readonly [string | null, PageUse])[] => [\n [page.file, { site: page.site, route: page.route, via: \"page\" as const }] as const,\n [page.setupFile, { site: page.site, route: page.route, via: \"setup\" as const }] as const,\n ...page.layouts.map(\n (layout) =>\n [layout, { site: page.site, route: page.route, via: \"layout\" as const }] as const,\n ),\n ]),\n );\n const screens = groupBy<ScreenUse>(\n facts.mobile.flatMap((app) =>\n app.screens.flatMap((screen): (readonly [string | null, ScreenUse])[] => [\n [screen.file, { app: app.id, route: screen.route, via: \"screen\" as const }] as const,\n ...screen.layouts.map(\n (layout) =>\n [layout, { app: app.id, route: screen.route, via: \"layout\" as const }] as const,\n ),\n ]),\n ),\n );\n const entries = new Map<string, BookEntry>();\n\n for (const file of facts.files) {\n const annotation = annotations.files[file.file] ?? NO_ANNOTATION;\n const fileRoutes: BookEntry[\"routes\"] = [\n ...(registered.get(file.file) ?? []).map((route) => ({\n ...routeRef(route),\n via: \"registers\" as const,\n })),\n ...(handled.get(file.file) ?? []).map((route) => ({\n ...routeRef(route),\n via: \"handles\" as const,\n })),\n ];\n\n entries.set(file.file, {\n schemaVersion: BOOK_SCHEMA_VERSION,\n file: file.file,\n module: file.module,\n type: file.type,\n lines: file.lines,\n about: file.about,\n feature: annotation.feature,\n borrowedBy: [...new Set(annotation.borrowedBy)].sort(byText),\n flows: [...new Set(annotation.flows)].sort(byText),\n exports: file.exports.map((entry) => ({ name: entry.name, about: entry.about })),\n packages: packagesOf(file),\n imports: [\n ...new Set(file.imports.flatMap((entry) => (entry.file === null ? [] : [entry.file]))),\n ].sort(byText),\n importedBy: [...new Set(file.importedBy)].sort(byText),\n routes: fileRoutes,\n pages: (pages.get(file.file) ?? []).sort(\n (left, right) =>\n byText(left.site, right.site) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n screens: (screens.get(file.file) ?? []).sort(\n (left, right) =>\n byText(left.app, right.app) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n });\n }\n\n return entries;\n}\n\n/** `app/routes.json`: routes grouped by the module of their routes file, in registration order. */\nexport function buildRoutesFile(facts: BookFacts): BookRoutesFile | null {\n if (facts.routes === null) return null;\n\n const moduleOf = new Map(facts.files.map((file) => [file.file, file.module]));\n const grouped = groupBy(\n facts.routes.map(\n (route) =>\n [\n route.sourceFile === null ? NO_MODULE : (moduleOf.get(route.sourceFile) ?? NO_MODULE),\n { ...routeRef(route), handlerFile: route.handlerFile },\n ] as const,\n ),\n );\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n modules: Object.fromEntries([...grouped].sort(([left], [right]) => byText(left, right))),\n };\n}\n\n/** One `BookModuleSummary` per `module` value of the code files, sorted by module. */\nexport function buildModuleSummaries(\n facts: BookFacts,\n annotations: BookAnnotations,\n): BookModuleSummary[] {\n const moduleOf = new Map(facts.files.map((file) => [file.file, file.module]));\n const byModule = groupBy(facts.files.map((file) => [file.module, file] as const));\n const routesByModule = groupBy(\n (facts.routes ?? []).map((route) => {\n const home = route.sourceFile ?? route.handlerFile;\n\n return [home === null ? null : (moduleOf.get(home) ?? null), routeRef(route)] as const;\n }),\n );\n const summaries: BookModuleSummary[] = [];\n\n for (const [module, files] of [...byModule].sort(([left], [right]) => byText(left, right))) {\n const featureCounts = new Map<string, number>();\n const importers = new Map<string, Set<string>>();\n\n for (const file of files) {\n const feature = annotations.files[file.file]?.feature ?? null;\n\n if (feature !== null) featureCounts.set(feature, (featureCounts.get(feature) ?? 0) + 1);\n\n for (const importer of file.importedBy) {\n const importerModule = moduleOf.get(importer);\n\n if (importerModule === undefined || importerModule === module) continue;\n\n const set = importers.get(importerModule) ?? new Set<string>();\n set.add(importer);\n importers.set(importerModule, set);\n }\n }\n\n summaries.push({\n module,\n features: [...featureCounts]\n .sort(([leftName, left], [rightName, right]) => right - left || byText(leftName, rightName))\n .map(([feature]) => feature),\n files: files\n .map((file) => ({ file: file.file, type: file.type, lines: file.lines, about: file.about }))\n .sort((left, right) => byText(left.file, right.file)),\n routes: routesByModule.get(module) ?? [],\n usedBy: [...importers]\n .map(([importer, set]) => ({ module: importer, files: set.size }))\n .sort((left, right) => right.files - left.files || byText(left.module, right.module)),\n });\n }\n\n return summaries;\n}\n\nconst plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n\n/** The Markdown of one module summary (format in `BookModuleSummary`). */\nexport function renderModuleSummary(summary: BookModuleSummary): string {\n const lines = summary.files.reduce((total, file) => total + file.lines, 0);\n const counts = `${plural(summary.files.length, \"file\")}, ${plural(lines, \"line\")}.`;\n const features =\n summary.features.length === 0\n ? \"\"\n : `${summary.features.length === 1 ? \"Feature\" : \"Features\"}: ${summary.features.join(\", \")}. `;\n const out = [`# ${summary.module}`, \"\", `${features}${counts}`];\n\n if (summary.files.length > 0) {\n out.push(\"\", \"## Files\");\n\n for (const file of summary.files) {\n const relative = isInsideFolder(file.file, summary.module)\n ? path.posix.relative(summary.module, file.file)\n : file.file;\n\n out.push(\n `- ${[relative, file.type, ...(file.about === null ? [] : [file.about])].join(\" \")}`,\n );\n }\n }\n\n if (summary.routes.length > 0) {\n out.push(\"\", \"## Routes\");\n\n for (const route of summary.routes) out.push(`- ${route.method} ${route.path}`);\n }\n\n if (summary.usedBy.length > 0) {\n out.push(\"\", \"## Used by\");\n\n for (const user of summary.usedBy) out.push(`- ${user.module} (${plural(user.files, \"file\")})`);\n }\n\n return `${out.join(\"\\n\")}\\n`;\n}\n\n/**\n * The content of every book file Warlock writes from the facts and the\n * annotations, by project-relative path. `manifest.json`, `.cache/` and\n * `test-results.json` are not part of it.\n */\nexport function renderBook(facts: BookFacts, annotations: BookAnnotations): Map<string, string> {\n const contents = new Map<string, string>();\n const entries = buildEntries(facts, annotations);\n\n for (const [file, entryPath] of entryPathsFor(facts)) {\n const entry = entries.get(file);\n\n if (entry !== undefined) contents.set(entryPath, toJson(entry));\n }\n\n for (const summary of buildModuleSummaries(facts, annotations)) {\n const summaryPath = moduleSummaryPath(summary.module);\n\n if (isInsideBook(summaryPath)) contents.set(summaryPath, renderModuleSummary(summary));\n }\n\n const routesFile = buildRoutesFile(facts);\n\n if (routesFile !== null) contents.set(GRIMOIRE_PATHS.bookRoutes, toJson(routesFile));\n\n for (const site of facts.sites) {\n const sitePath = sitePagesPath(site.id);\n const file: BookSitePagesFile = {\n schemaVersion: BOOK_SCHEMA_VERSION,\n site,\n pages: facts.pages.filter((page) => page.site === site.id),\n };\n\n if (isInsideBook(sitePath)) contents.set(sitePath, toJson(file));\n }\n\n for (const app of facts.mobile) {\n const screensPath = mobileScreensPath(app.id);\n const { screens, ...rest } = app;\n const file: BookMobileScreensFile = { schemaVersion: BOOK_SCHEMA_VERSION, app: rest, screens };\n\n if (isInsideBook(screensPath)) contents.set(screensPath, toJson(file));\n }\n\n return contents;\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAa,YAAY;AAEzB,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;;;;;AAMhG,SAAgB,cAAc,OAAiE;CAC7F,MAAM,cAAc,IAAI,IAAI,MAAM,OAAO,KAAK,QAAQ,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC;CACzE,MAAM,QAAQ,eACZ,MAAM,MAAM,KAAK,SAAS;EACxB,MAAM,aAAa,KAAK,cAAc,OAAO,SAAY,YAAY,IAAI,KAAK,SAAS;EAEvF,OAAO;GACL,MAAM,KAAK;GACX,WACE,KAAK,cAAc,QAAQ,eAAe,SACtC,OACA;IAAE,IAAI,KAAK;IAAW,MAAM;GAAW;EAC/C;CACF,CAAC,CACH;CAEA,KAAK,MAAM,CAAC,MAAM,UAAU,OAC1B,IAAI,CAAC,aAAa,KAAK,GAAG,MAAM,OAAO,IAAI;CAG7C,OAAO;AACT;AAEA,SAAS,SAAS,OAAgC;CAChD,OAAO;EAAE,QAAQ,MAAM;EAAQ,MAAM,MAAM;EAAM,MAAM,MAAM;CAAK;AACpE;;AAGA,SAAgB,WAAW,MAA0B;CACnD,MAAM,wBAAQ,IAAI,IAAY;CAE9B,KAAK,MAAM,SAAS,KAA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"],"sourcesContent":["/**\n * Turns facts and annotations into the content of every book file: the\n * per-file entries, the module summaries, `app/routes.json` and the page and\n * screen lists. Pure: no IO, so a spec can build inputs by hand.\n */\nimport { isBuiltin } from \"node:module\";\nimport path from \"node:path\";\nimport type { BookFacts, BookFile, BookRoute } from \"../contracts/adapter\";\nimport {\n BOOK_SCHEMA_VERSION,\n type BookAnnotations,\n type BookEntry,\n type BookMobileScreensFile,\n type BookModuleSummary,\n type BookRouteRef,\n type BookRoutesFile,\n type BookSitePagesFile,\n} from \"../contracts/book\";\nimport { packageNameOf } from \"../graph\";\nimport {\n bookEntryPaths,\n GRIMOIRE_PATHS,\n isInsideFolder,\n mobileScreensPath,\n moduleSummaryPath,\n sitePagesPath,\n} from \"../paths\";\nimport { isInsideBook, toJson } from \"./io\";\n\n/** Key of `BookRoutesFile.modules` for routes with no routes file. */\nexport const NO_MODULE = \"(none)\";\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\n\n/**\n * Book entry path of every code file in the facts. A file whose mirror would\n * leave `grimoire/book/` (a path with `..`) has no entry.\n */\nexport function entryPathsFor(facts: Pick<BookFacts, \"files\" | \"mobile\">): Map<string, string> {\n const mobileRoots = new Map(facts.mobile.map((app) => [app.id, app.root]));\n const paths = bookEntryPaths(\n facts.files.map((file) => {\n const mobileRoot = file.mobileApp === null ? undefined : mobileRoots.get(file.mobileApp);\n\n return {\n file: file.file,\n mobileApp:\n file.mobileApp === null || mobileRoot === undefined\n ? null\n : { id: file.mobileApp, root: mobileRoot },\n };\n }),\n );\n\n for (const [file, entry] of paths) {\n if (!isInsideBook(entry)) paths.delete(file);\n }\n\n return paths;\n}\n\nfunction routeRef(route: BookRoute): BookRouteRef {\n return { method: route.method, path: route.path, name: route.name };\n}\n\n/** Project files whose every import edge from the file is type-only: sorted, unique. */\nfunction typeOnlyImportsOf(file: BookFile): string[] {\n const edges = new Map<string, boolean>();\n\n for (const entry of file.imports) {\n if (entry.file === null) continue;\n edges.set(entry.file, (edges.get(entry.file) ?? true) && entry.typeOnly === true);\n }\n\n return [...edges].flatMap(([target, typeOnly]) => (typeOnly ? [target] : [])).sort(byText);\n}\n\n/** External package names a file imports: sorted, unique, Node builtins left out. */\nexport function packagesOf(file: BookFile): string[] {\n const names = new Set<string>();\n\n for (const entry of file.imports) {\n if (entry.file !== null) continue;\n\n const name = packageNameOf(entry.specifier);\n\n if (name !== null && !isBuiltin(name)) names.add(name);\n }\n\n return [...names].sort(byText);\n}\n\n/** Lists indexed by a key, built once so lookups per file stay constant time. */\nfunction groupBy<T>(items: Iterable<readonly [string | null, T]>): Map<string, T[]> {\n const groups = new Map<string, T[]>();\n\n for (const [key, item] of items) {\n if (key === null) continue;\n\n const group = groups.get(key);\n\n if (group) group.push(item);\n else groups.set(key, [item]);\n }\n\n return groups;\n}\n\ntype PageUse = {\n readonly site: string;\n readonly route: string;\n readonly via: \"page\" | \"setup\" | \"layout\";\n};\ntype ScreenUse = {\n readonly app: string;\n readonly route: string;\n readonly via: \"screen\" | \"layout\";\n};\n\nconst NO_ANNOTATION = { feature: null, borrowedBy: [], flows: [] } as const;\n\n/** The entry of every code file, by source file. */\nexport function buildEntries(\n facts: BookFacts,\n annotations: BookAnnotations,\n): Map<string, BookEntry> {\n const routes = facts.routes ?? [];\n const registered = groupBy(routes.map((route) => [route.sourceFile, route] as const));\n const handled = groupBy(routes.map((route) => [route.handlerFile, route] as const));\n const pages = groupBy<PageUse>(\n facts.pages.flatMap((page): (readonly [string | null, PageUse])[] => [\n [page.file, { site: page.site, route: page.route, via: \"page\" as const }] as const,\n [page.setupFile, { site: page.site, route: page.route, via: \"setup\" as const }] as const,\n ...page.layouts.map(\n (layout) =>\n [layout, { site: page.site, route: page.route, via: \"layout\" as const }] as const,\n ),\n ]),\n );\n const screens = groupBy<ScreenUse>(\n facts.mobile.flatMap((app) =>\n app.screens.flatMap((screen): (readonly [string | null, ScreenUse])[] => [\n [screen.file, { app: app.id, route: screen.route, via: \"screen\" as const }] as const,\n ...screen.layouts.map(\n (layout) =>\n [layout, { app: app.id, route: screen.route, via: \"layout\" as const }] as const,\n ),\n ]),\n ),\n );\n const entries = new Map<string, BookEntry>();\n\n for (const file of facts.files) {\n const annotation = annotations.files[file.file] ?? NO_ANNOTATION;\n const fileRoutes: BookEntry[\"routes\"] = [\n ...(registered.get(file.file) ?? []).map((route) => ({\n ...routeRef(route),\n via: \"registers\" as const,\n })),\n ...(handled.get(file.file) ?? []).map((route) => ({\n ...routeRef(route),\n via: \"handles\" as const,\n })),\n ];\n\n entries.set(file.file, {\n schemaVersion: BOOK_SCHEMA_VERSION,\n file: file.file,\n module: file.module,\n type: file.type,\n lines: file.lines,\n about: file.about,\n feature: annotation.feature,\n borrowedBy: [...new Set(annotation.borrowedBy)].sort(byText),\n flows: [...new Set(annotation.flows)].sort(byText),\n exports: file.exports.map((entry) => ({ name: entry.name, about: entry.about })),\n packages: packagesOf(file),\n imports: [\n ...new Set(file.imports.flatMap((entry) => (entry.file === null ? [] : [entry.file]))),\n ].sort(byText),\n typeOnlyImports: typeOnlyImportsOf(file),\n importedBy: [...new Set(file.importedBy)].sort(byText),\n routes: fileRoutes,\n pages: (pages.get(file.file) ?? []).sort(\n (left, right) =>\n byText(left.site, right.site) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n screens: (screens.get(file.file) ?? []).sort(\n (left, right) =>\n byText(left.app, right.app) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n });\n }\n\n return entries;\n}\n\n/** `app/routes.json`: routes grouped by the module of their routes file, in registration order. */\nexport function buildRoutesFile(facts: BookFacts): BookRoutesFile | null {\n if (facts.routes === null) return null;\n\n const moduleOf = new Map(facts.files.map((file) => [file.file, file.module]));\n const grouped = groupBy(\n facts.routes.map(\n (route) =>\n [\n route.sourceFile === null ? NO_MODULE : (moduleOf.get(route.sourceFile) ?? NO_MODULE),\n { ...routeRef(route), handlerFile: route.handlerFile },\n ] as const,\n ),\n );\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n modules: Object.fromEntries([...grouped].sort(([left], [right]) => byText(left, right))),\n };\n}\n\n/** One `BookModuleSummary` per `module` value of the code files, sorted by module. */\nexport function buildModuleSummaries(\n facts: BookFacts,\n annotations: BookAnnotations,\n): BookModuleSummary[] {\n const moduleOf = new Map(facts.files.map((file) => [file.file, file.module]));\n const byModule = groupBy(facts.files.map((file) => [file.module, file] as const));\n const routesByModule = groupBy(\n (facts.routes ?? []).map((route) => {\n const home = route.sourceFile ?? route.handlerFile;\n\n return [home === null ? null : (moduleOf.get(home) ?? null), routeRef(route)] as const;\n }),\n );\n const summaries: BookModuleSummary[] = [];\n\n for (const [module, files] of [...byModule].sort(([left], [right]) => byText(left, right))) {\n const featureCounts = new Map<string, number>();\n const importers = new Map<string, Set<string>>();\n\n for (const file of files) {\n const feature = annotations.files[file.file]?.feature ?? null;\n\n if (feature !== null) featureCounts.set(feature, (featureCounts.get(feature) ?? 0) + 1);\n\n for (const importer of file.importedBy) {\n const importerModule = moduleOf.get(importer);\n\n if (importerModule === undefined || importerModule === module) continue;\n\n const set = importers.get(importerModule) ?? new Set<string>();\n set.add(importer);\n importers.set(importerModule, set);\n }\n }\n\n summaries.push({\n module,\n features: [...featureCounts]\n .sort(([leftName, left], [rightName, right]) => right - left || byText(leftName, rightName))\n .map(([feature]) => feature),\n files: files\n .map((file) => ({ file: file.file, type: file.type, lines: file.lines, about: file.about }))\n .sort((left, right) => byText(left.file, right.file)),\n routes: routesByModule.get(module) ?? [],\n usedBy: [...importers]\n .map(([importer, set]) => ({ module: importer, files: set.size }))\n .sort((left, right) => right.files - left.files || byText(left.module, right.module)),\n });\n }\n\n return summaries;\n}\n\nconst plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n\n/** The Markdown of one module summary (format in `BookModuleSummary`). */\nexport function renderModuleSummary(summary: BookModuleSummary): string {\n const lines = summary.files.reduce((total, file) => total + file.lines, 0);\n const counts = `${plural(summary.files.length, \"file\")}, ${plural(lines, \"line\")}.`;\n const features =\n summary.features.length === 0\n ? \"\"\n : `${summary.features.length === 1 ? \"Feature\" : \"Features\"}: ${summary.features.join(\", \")}. `;\n const out = [`# ${summary.module}`, \"\", `${features}${counts}`];\n\n if (summary.files.length > 0) {\n out.push(\"\", \"## Files\");\n\n for (const file of summary.files) {\n const relative = isInsideFolder(file.file, summary.module)\n ? path.posix.relative(summary.module, file.file)\n : file.file;\n\n out.push(\n `- ${[relative, file.type, ...(file.about === null ? [] : [file.about])].join(\" \")}`,\n );\n }\n }\n\n if (summary.routes.length > 0) {\n out.push(\"\", \"## Routes\");\n\n for (const route of summary.routes) out.push(`- ${route.method} ${route.path}`);\n }\n\n if (summary.usedBy.length > 0) {\n out.push(\"\", \"## Used by\");\n\n for (const user of summary.usedBy) out.push(`- ${user.module} (${plural(user.files, \"file\")})`);\n }\n\n return `${out.join(\"\\n\")}\\n`;\n}\n\n/**\n * The content of every book file Warlock writes from the facts and the\n * annotations, by project-relative path. `manifest.json`, `.cache/` and\n * `test-results.json` are not part of it.\n */\nexport function renderBook(facts: BookFacts, annotations: BookAnnotations): Map<string, string> {\n const contents = new Map<string, string>();\n const entries = buildEntries(facts, annotations);\n\n for (const [file, entryPath] of entryPathsFor(facts)) {\n const entry = entries.get(file);\n\n if (entry !== undefined) contents.set(entryPath, toJson(entry));\n }\n\n for (const summary of buildModuleSummaries(facts, annotations)) {\n const summaryPath = moduleSummaryPath(summary.module);\n\n if (isInsideBook(summaryPath)) contents.set(summaryPath, renderModuleSummary(summary));\n }\n\n const routesFile = buildRoutesFile(facts);\n\n if (routesFile !== null) contents.set(GRIMOIRE_PATHS.bookRoutes, toJson(routesFile));\n\n for (const site of facts.sites) {\n const sitePath = sitePagesPath(site.id);\n const file: BookSitePagesFile = {\n schemaVersion: BOOK_SCHEMA_VERSION,\n site,\n pages: facts.pages.filter((page) => page.site === site.id),\n };\n\n if (isInsideBook(sitePath)) contents.set(sitePath, toJson(file));\n }\n\n for (const app of facts.mobile) {\n const screensPath = mobileScreensPath(app.id);\n const { screens, ...rest } = app;\n const file: BookMobileScreensFile = { schemaVersion: BOOK_SCHEMA_VERSION, app: rest, screens };\n\n if (isInsideBook(screensPath)) contents.set(screensPath, toJson(file));\n }\n\n return contents;\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAa,YAAY;AAEzB,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;;;;;AAMhG,SAAgB,cAAc,OAAiE;CAC7F,MAAM,cAAc,IAAI,IAAI,MAAM,OAAO,KAAK,QAAQ,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC;CACzE,MAAM,QAAQ,eACZ,MAAM,MAAM,KAAK,SAAS;EACxB,MAAM,aAAa,KAAK,cAAc,OAAO,SAAY,YAAY,IAAI,KAAK,SAAS;EAEvF,OAAO;GACL,MAAM,KAAK;GACX,WACE,KAAK,cAAc,QAAQ,eAAe,SACtC,OACA;IAAE,IAAI,KAAK;IAAW,MAAM;GAAW;EAC/C;CACF,CAAC,CACH;CAEA,KAAK,MAAM,CAAC,MAAM,UAAU,OAC1B,IAAI,CAAC,aAAa,KAAK,GAAG,MAAM,OAAO,IAAI;CAG7C,OAAO;AACT;AAEA,SAAS,SAAS,OAAgC;CAChD,OAAO;EAAE,QAAQ,MAAM;EAAQ,MAAM,MAAM;EAAM,MAAM,MAAM;CAAK;AACpE;;AAGA,SAAS,kBAAkB,MAA0B;CACnD,MAAM,wBAAQ,IAAI,IAAqB;CAEvC,KAAK,MAAM,SAAS,KAAK,SAAS;EAChC,IAAI,MAAM,SAAS,MAAM;EACzB,MAAM,IAAI,MAAM,OAAO,MAAM,IAAI,MAAM,IAAI,KAAK,SAAS,MAAM,aAAa,IAAI;CAClF;CAEA,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,SAAS,CAAC,QAAQ,cAAe,WAAW,CAAC,MAAM,IAAI,CAAC,CAAE,CAAC,CAAC,KAAK,M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AAG,SAAS,IAAI,aAAa,OAAO,IAAI,CAAC;CACvE;CAEA,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"build.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/build.ts"],"mappings":";;;;;;;YA8BY;EACV,SAAS;EACT,OAAO;EACP,WAAW;EACX,MAAM,eAAe;EACrB,QAAQ;EACR,SAAS;;EAET,YAAY;;;wBA8VE,oBAAoB,OAAO,iBAAiB"}
1
+ {"version":3,"file":"build.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/build.ts"],"mappings":";;;;;;;YA+BY;EACV,SAAS;EACT,OAAO;EACP,WAAW;EACX,MAAM,eAAe;EACrB,QAAQ;EACR,SAAS;;EAET,YAAY;;;wBAuWE,oBAAoB,OAAO,iBAAiB"}
@@ -1,6 +1,7 @@
1
1
  import { BOOK_SCHEMA_VERSION } from "../contracts/book.mjs";
2
2
  import { toPosixPath } from "../paths/index.mjs";
3
3
  import { fileGraph } from "../graph/index.mjs";
4
+ import { isExemptFromReach, specOnlyFiles } from "../ownership/index.mjs";
4
5
  import { criterionStatus } from "../test-results/criterion-status.mjs";
5
6
  import "../test-results/index.mjs";
6
7
  import { resolveStep } from "./steps.mjs";
@@ -87,7 +88,7 @@ function flowBookmap(feature, flow, input, context) {
87
88
  shownBy: shownBy(flow, input.written)
88
89
  };
89
90
  }
90
- function featureBookmap(feature, flows, input, byPath) {
91
+ function featureBookmap(feature, flows, input, byPath, specOnly) {
91
92
  const { ownership, facts } = input;
92
93
  const own = ownership.features[feature.id]?.own ?? [];
93
94
  const ownSet = new Set(own);
@@ -136,7 +137,7 @@ function featureBookmap(feature, flows, input, byPath) {
136
137
  });
137
138
  const sortedPages = {};
138
139
  for (const app of Object.keys(pages).sort()) sortedPages[app] = (pages[app] ?? []).sort((left, right) => left.route.localeCompare(right.route) || left.file.localeCompare(right.file));
139
- const reached = new Set(flows.flatMap((flow) => flow.steps.flatMap((step) => step.files)));
140
+ const reached = new Set(flows.flatMap((flow) => flow.steps.flatMap((step) => [...step.files, ...step.typeOnlyFiles])));
140
141
  return {
141
142
  schemaVersion: 1,
142
143
  feature: feature.id,
@@ -144,7 +145,7 @@ function featureBookmap(feature, flows, input, byPath) {
144
145
  borrowed,
145
146
  routes,
146
147
  pages: sortedPages,
147
- unreached: own.filter((file) => !reached.has(file))
148
+ unreached: own.filter((file) => !reached.has(file) && !specOnly.has(file) && !isExemptFromReach(byPath.get(file) ?? { type: "source" }))
148
149
  };
149
150
  }
150
151
  function compareVersions(left, right) {
@@ -229,12 +230,13 @@ function buildCollectedFiles(input) {
229
230
  graph: fileGraph(input.facts.files)
230
231
  };
231
232
  const byPath = new Map(input.facts.files.map((file) => [file.file, file]));
233
+ const specOnly = specOnlyFiles(input.facts.files);
232
234
  const features = {};
233
235
  const flows = {};
234
236
  for (const feature of [...input.written.features].sort((left, right) => left.id.localeCompare(right.id))) {
235
237
  const maps = feature.flows.map((flow) => flowBookmap(feature, flow, input, context));
236
238
  for (const map of maps) flows[map.ref] = map;
237
- features[feature.id] = featureBookmap(feature, maps, input, byPath);
239
+ features[feature.id] = featureBookmap(feature, maps, input, byPath, specOnly);
238
240
  }
239
241
  return {
240
242
  features,
@@ -246,7 +248,7 @@ function buildCollectedFiles(input) {
246
248
  /** The per-file owner, borrowers and flows the book entries show. Pure. */
247
249
  function annotationsFrom(input, collected, manifest) {
248
250
  const flowsOf = /* @__PURE__ */ new Map();
249
- for (const map of Object.values(collected.flows)) for (const step of map.steps) for (const file of step.files) {
251
+ for (const map of Object.values(collected.flows)) for (const step of map.steps) for (const file of [...step.files, ...step.typeOnlyFiles]) {
250
252
  const set = flowsOf.get(file) ?? /* @__PURE__ */ new Set();
251
253
  set.add(map.ref);
252
254
  flowsOf.set(file, set);