@warlock.js/grimoire 5.58.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 (71) hide show
  1. package/CHANGELOG.md +24 -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.map +1 -1
  6. package/esm/bookmap/build.d.mts.map +1 -1
  7. package/esm/bookmap/build.mjs +5 -3
  8. package/esm/bookmap/build.mjs.map +1 -1
  9. package/esm/bookmap/steps.mjs +34 -3
  10. package/esm/bookmap/steps.mjs.map +1 -1
  11. package/esm/contracts/adapter.d.mts +22 -1
  12. package/esm/contracts/adapter.d.mts.map +1 -1
  13. package/esm/contracts/scry.d.mts +26 -6
  14. package/esm/contracts/scry.d.mts.map +1 -1
  15. package/esm/contracts/snapshot.d.mts +3 -1
  16. package/esm/contracts/snapshot.d.mts.map +1 -1
  17. package/esm/devtools/data.mjs +23 -3
  18. package/esm/devtools/data.mjs.map +1 -1
  19. package/esm/devtools/feature-map.mjs +149 -0
  20. package/esm/devtools/feature-map.mjs.map +1 -0
  21. package/esm/devtools/index.d.mts +2 -2
  22. package/esm/devtools/index.mjs +30 -9
  23. package/esm/devtools/index.mjs.map +1 -1
  24. package/esm/devtools/product-map.d.mts.map +1 -1
  25. package/esm/devtools/product-map.mjs +82 -7
  26. package/esm/devtools/product-map.mjs.map +1 -1
  27. package/esm/devtools/site.d.mts +43 -1
  28. package/esm/devtools/site.d.mts.map +1 -1
  29. package/esm/devtools/site.mjs +111 -15
  30. package/esm/devtools/site.mjs.map +1 -1
  31. package/esm/devtools/snapshot-source.mjs +15 -2
  32. package/esm/devtools/snapshot-source.mjs.map +1 -1
  33. package/esm/index.d.mts +3 -3
  34. package/esm/ownership/index.d.mts.map +1 -1
  35. package/esm/ownership/index.mjs +60 -1
  36. package/esm/ownership/index.mjs.map +1 -1
  37. package/esm/scry/compact.mjs +2 -1
  38. package/esm/scry/compact.mjs.map +1 -1
  39. package/esm/scry/format.d.mts.map +1 -1
  40. package/esm/scry/format.mjs +12 -1
  41. package/esm/scry/format.mjs.map +1 -1
  42. package/esm/scry/query.d.mts.map +1 -1
  43. package/esm/scry/query.mjs +147 -23
  44. package/esm/scry/query.mjs.map +1 -1
  45. package/esm/test-results/index.d.mts.map +1 -1
  46. package/esm/test-results/index.mjs.map +1 -1
  47. package/esm/warlock/actions.mjs +15 -7
  48. package/esm/warlock/actions.mjs.map +1 -1
  49. package/esm/warlock/adapter.d.mts.map +1 -1
  50. package/esm/warlock/adapter.mjs +36 -2
  51. package/esm/warlock/adapter.mjs.map +1 -1
  52. package/esm/warlock/commands.mjs +7 -2
  53. package/esm/warlock/commands.mjs.map +1 -1
  54. package/esm/warlock/logo.mjs +12 -0
  55. package/esm/warlock/logo.mjs.map +1 -0
  56. package/esm/warlock/mcp-tools.mjs +6 -6
  57. package/esm/warlock/mcp-tools.mjs.map +1 -1
  58. package/esm/workspace/cache.mjs +194 -0
  59. package/esm/workspace/cache.mjs.map +1 -0
  60. package/esm/workspace/index.d.mts.map +1 -1
  61. package/esm/workspace/index.mjs +3 -1
  62. package/esm/workspace/index.mjs.map +1 -1
  63. package/llms-full.txt +32 -9
  64. package/package.json +3 -3
  65. package/skills/record-a-change/SKILL.md +2 -0
  66. package/skills/use-the-grimoire/SKILL.md +30 -9
  67. package/ui/grimoire-static.js +57 -6
  68. package/ui/grimoire-view.js +1289 -310
  69. package/ui/grimoire.css +583 -2
  70. package/ui/product-map.css +157 -8
  71. package/ui/product-map.js +507 -59
package/CHANGELOG.md CHANGED
@@ -2,6 +2,30 @@
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
+
5
29
  ## 5.58.0 - 2026-11-18
6
30
 
7
31
  ### 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\",\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,IAA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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,CAAC;CAExE,OAAO;EAAE,SAAS,SAAS,WAAW,IAAK,SAAS,MAAM,OAAQ;EAAM,MAAM;CAAK;AACrF;;AAGA,SAAS,eAAe,OAAuB;CAI7C,MAAM,UAHY,YAAY,MAAM,KAAK,CAAC,CAAC,CACxC,QAAQ,oBAAoB,MAAM,CAAC,CACnC,QAAQ,cAAc,KACD,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAE5C,OAAO,YAAY,KAAK,MAAM,QAAQ,WAAW,GAAG,IAAI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;GACV,KAAK;GACL,GAAG;EACL,CAAC,CACH;CACF;AACF;;AAGA,SAAS,eAAe,UAA4B,UAAmC;CACrF,IAAI,SAAS,QAAQ,KAAK,WAAW,GAAG;CAExC,MAAM,wBAAQ,IAAI,IAAY;CAC9B,MAAM,0BAAU,IAAI,IAAY;CAEhC,KAAK,MAAM,SAAS,OAAO,OAAO,SAAS,IAAI,GAAG;EAChD,IAAI,MAAM,MAAM,MAAM,IAAI,MAAM,KAAK,EAAE;EACvC,IAAI,MAAM,QAAQ,QAAQ,IAAI,MAAM,OAAO,EAAE;CAC/C;CAEA,KAAK,MAAM,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 +1 @@
1
- {"version":3,"file":"build.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/build.ts"],"mappings":";;;;;;;;;wBAqSsB,UACpB,cACA,SAAS,aACT,UAAS,mBACR,QAAQ;;wBAyKW,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"}
@@ -1 +1 @@
1
- {"version":3,"file":"build.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/build.ts"],"sourcesContent":["/**\n * `buildBook` and `loadBook`: the freshness fingerprint, the facts cache and\n * the route (boot) cache. Entries are written by `writeBook` (write.ts).\n */\nimport { readFileSync } from \"node:fs\";\nimport { rm, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { BookAdapter, BookFacts, BookFile } from \"../contracts/adapter\";\nimport {\n BOOK_SCHEMA_VERSION,\n type BookFactsCache,\n type BookManifest,\n type BookManifestFile,\n type BuildBookOptions,\n type BuildBookResult,\n type LoadedBook,\n} from \"../contracts/book\";\nimport type { RouteFreshness } from \"../contracts/findings\";\nimport { GrimoireError } from \"../codes\";\nimport { importClosure, fileGraph } from \"../graph\";\nimport { GRIMOIRE_PATHS, isCodeFile, isInsideFolder } from \"../paths\";\nimport {\n cleanFolder,\n hashFile,\n hashIfExists,\n IO_CONCURRENCY,\n isMissing,\n listFiles,\n mapLimit,\n readJson,\n toJson,\n writeBookFile,\n} from \"./io\";\nimport {\n cleanPath,\n normalizeFiles,\n normalizeMobile,\n normalizeNamed,\n normalizePages,\n normalizeRoutes,\n normalizeSites,\n} from \"./normalize\";\nimport { entryPathsFor } from \"./render\";\n\n/** Where `writeBook` remembers what it wrote (see write.ts). */\nexport const WRITE_STATE_PATH = `${GRIMOIRE_PATHS.book}/.cache/written.json`;\n\nlet cachedVersion: string | null = null;\n\n/** The `@warlock.js/grimoire` version, from its package.json. */\nexport function grimoireVersion(): string {\n if (cachedVersion !== null) return cachedVersion;\n\n try {\n const manifest = JSON.parse(\n readFileSync(new URL(\"../../package.json\", import.meta.url), \"utf8\"),\n ) as {\n version?: unknown;\n };\n cachedVersion = typeof manifest.version === \"string\" ? manifest.version : \"0.0.0\";\n } catch {\n cachedVersion = \"0.0.0\";\n }\n\n return cachedVersion;\n}\n\nconst absolutePath = (root: string, file: string): string => path.join(root, ...file.split(\"/\"));\n\ntype StoredBook = { manifest: BookManifest; facts: BookFacts };\n\n/**\n * `facts.json` as written since type-only import edges were recorded. A cache\n * without the marker comes from an older version: it is not reused, so file\n * facts are scanned once more.\n */\ntype StoredFactsCache = BookFactsCache & { typeOnlyEdges?: boolean };\n\nasync function readStoredBook(root: string): Promise<StoredBook | null> {\n const manifest = await readJson<BookManifest>(absolutePath(root, GRIMOIRE_PATHS.bookManifest));\n const cache = await readJson<StoredFactsCache>(absolutePath(root, GRIMOIRE_PATHS.bookFactsCache));\n\n if (\n manifest === null ||\n cache === null ||\n manifest.schemaVersion !== BOOK_SCHEMA_VERSION ||\n cache.schemaVersion !== BOOK_SCHEMA_VERSION ||\n cache.typeOnlyEdges !== true ||\n typeof manifest.files !== \"object\" ||\n typeof cache.facts !== \"object\"\n ) {\n return null;\n }\n\n return { manifest, facts: cache.facts };\n}\n\n/** The current state of every code file under the source roots (images, fonts and certificates are not part of the book). */\ntype Scan = {\n files: Record<string, Omit<BookManifestFile, \"entry\">>;\n /** A file kept its hash but its size or mtime moved: the manifest needs the new stat. */\n statMoved: boolean;\n};\n\n/** Stat every code file; hash only those whose size or mtime differ from the previous manifest. */\nasync function scanSourceRoots(\n root: string,\n sourceRoots: readonly string[],\n previous: Record<string, BookManifestFile>,\n): Promise<Scan> {\n let files: string[];\n\n try {\n files = (await listFiles(root, sourceRoots)).filter(isCodeFile);\n } catch (error) {\n throw new GrimoireError(\n \"GR8001\",\n `The source roots could not be read: ${(error as Error).message}`,\n );\n }\n\n let statMoved = false;\n const states = await mapLimit(files, IO_CONCURRENCY, async (file) => {\n const absolute = absolutePath(root, file);\n\n try {\n const info = await stat(absolute);\n const before = previous[file];\n\n if (before !== undefined && before.size === info.size && before.mtimeMs === info.mtimeMs) {\n return { file, hash: before.hash, size: info.size, mtimeMs: info.mtimeMs };\n }\n\n const hash = await hashFile(absolute, info.size);\n\n if (before !== undefined && before.hash === hash) statMoved = true;\n\n return { file, hash, size: info.size, mtimeMs: info.mtimeMs };\n } catch (error) {\n // Deleted between the walk and the stat: treat it as gone.\n if (isMissing(error)) return null;\n throw new GrimoireError(\"GR8001\", `${file} could not be read: ${(error as Error).message}`);\n }\n });\n const result: Scan[\"files\"] = {};\n\n for (const state of states) {\n if (state !== null)\n result[state.file] = { hash: state.hash, size: state.size, mtimeMs: state.mtimeMs };\n }\n\n return { files: result, statMoved };\n}\n\n/** Hashes of the given files: from the scan when inside the source roots, else read (`\"\"` when missing). */\nasync function hashFiles(\n root: string,\n files: readonly string[],\n scan: Scan[\"files\"],\n sourceRoots: readonly string[],\n): Promise<Record<string, string>> {\n const hashes = await mapLimit([...new Set(files)].sort(), IO_CONCURRENCY, async (file) => {\n const scanned = scan[file];\n\n if (scanned !== undefined) return [file, scanned.hash] as const;\n // A code file inside a source root that the scan did not find is gone; any other input (a JSON config) is read.\n if (\n isCodeFile(file) &&\n sourceRoots.some((folder) => folder === \".\" || isInsideFolder(file, folder))\n )\n return [file, \"\"] as const;\n\n return [file, await hashIfExists(root, file)] as const;\n });\n\n return Object.fromEntries(hashes);\n}\n\nfunction sameRecord(left: Record<string, string>, right: Record<string, string>): boolean {\n const leftKeys = Object.keys(left);\n\n return (\n leftKeys.length === Object.keys(right).length &&\n leftKeys.every((key) => right[key] === left[key])\n );\n}\n\n/** Source files added, changed or removed between two manifests, sorted. */\nfunction changedFiles(\n previous: Record<string, BookManifestFile>,\n current: Scan[\"files\"],\n): string[] {\n const changed: string[] = [];\n\n for (const [file, state] of Object.entries(current)) {\n if (previous[file]?.hash !== state.hash) changed.push(file);\n }\n\n for (const file of Object.keys(previous)) {\n if (current[file] === undefined) changed.push(file);\n }\n\n return changed.sort();\n}\n\nconst NAMED_FILE_TYPES = new Set([\"mail\", \"job\", \"event\"]);\n\n/**\n * Files whose change makes the route cache stale: every `routes` file and\n * everything it imports, every `config` file, `warlock.config.ts`,\n * `package.json`, and every mail, job, event and notification file (the\n * named things are cached with the routes).\n */\nexport function defaultRouteInputs(files: readonly BookFile[]): string[] {\n const routesFiles = files.filter((file) => file.type === \"routes\").map((file) => file.file);\n const inputs = new Set(importClosure(fileGraph(files), routesFiles));\n\n for (const file of files) {\n if (\n file.type === \"config\" ||\n NAMED_FILE_TYPES.has(file.type) ||\n /\\.notification\\.[^/]+$/.test(file.file)\n ) {\n inputs.add(file.file);\n }\n }\n\n inputs.add(\"warlock.config.ts\");\n inputs.add(\"package.json\");\n\n return [...inputs].sort();\n}\n\n/** The route cache's input files: the adapter's list when it has one, else the default. */\nasync function routeInputFiles(\n root: string,\n adapter: BookAdapter,\n files: readonly BookFile[],\n): Promise<string[]> {\n return adapter.routeInputs\n ? (await adapter.routeInputs(root, files)).map(cleanPath)\n : defaultRouteInputs(files);\n}\n\nconst hasBootFacts = (adapter: BookAdapter): boolean =>\n typeof adapter.routes === \"function\" || typeof adapter.named === \"function\";\n\nasync function collectBootFacts(\n root: string,\n adapter: BookAdapter,\n): Promise<Pick<BookFacts, \"routes\" | \"named\">> {\n try {\n return {\n routes: adapter.routes ? normalizeRoutes(await adapter.routes(root)) : null,\n named: adapter.named ? normalizeNamed(await adapter.named(root)) : [],\n };\n } catch (error) {\n if (error instanceof GrimoireError) throw error;\n throw new GrimoireError(\"GR8002\", `Route facts could not be read: ${(error as Error).message}`);\n }\n}\n\n/** How the stored route facts relate to the current inputs. */\nfunction bootState(\n boot: BookManifest[\"boot\"],\n routes: BookFacts[\"routes\"],\n inputs: Record<string, string>,\n): \"fresh\" | \"stale\" | \"missing\" {\n if (boot.collectedAt === null || routes === null) return \"missing\";\n\n return sameRecord(boot.inputs, inputs) ? \"fresh\" : \"stale\";\n}\n\nasync function writeStoredBook(\n root: string,\n manifest: BookManifest,\n facts: BookFacts | null,\n): Promise<void> {\n if (facts !== null) {\n const cache: StoredFactsCache = { schemaVersion: BOOK_SCHEMA_VERSION, typeOnlyEdges: true, 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;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AAO,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"}
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,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;AAW/F,eAAe,eAAe,MAA0C;CACtE,MAAM,WAAW,MAAM,SAAuB,aAAa,MAAM,eAAe,YAAY,CAAC;CAC7F,MAAM,QAAQ,MAAM,SAA2B,aAAa,MAAM,eAAe,cAAc,CAAC;CAEhG,IACE,aAAa,QACb,UAAU,QACV,SAAS,uBACT,MAAM,uBACN,MAAM,kBAAkB,QACxB,OAAO,SAAS,UAAU,YAC1B,OAAO,MAAM,UAAU,UAEvB,OAAO;CAGT,OAAO;EAAE;EAAU,OAAO,MAAM;CAAM;AACxC;;AAUA,eAAe,g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sB,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"}
@@ -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;;;wBAiWE,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);
@@ -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,
@@ -1 +1 @@
1
- {"version":3,"file":"build.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/build.ts"],"sourcesContent":["/**\n * Builds the book maps and the collected indexes in memory. Pure: reads only\n * its input.\n */\nimport type { BookFacts, BookFile } from \"../contracts/adapter\";\nimport { BOOK_SCHEMA_VERSION, type BookAnnotations, type BookManifest } from \"../contracts/book\";\nimport type {\n CollectedFiles,\n FeatureBookmap,\n FeaturesIndex,\n FlowBookmap,\n FlowBookmapCriterion,\n Ownership,\n TaskSummary,\n TasksIndex,\n} from \"../contracts/bookmap\";\nimport type { AppMatch } from \"../contracts/snapshot\";\nimport type { ProofLine, ProofResult, TestResultsStore } from \"../contracts/test-results\";\nimport type {\n WrittenFeature,\n WrittenFlow,\n WrittenGrimoire,\n WrittenTask,\n} from \"../contracts/written\";\nimport { fileGraph } from \"../graph\";\nimport { toPosixPath } from \"../paths\";\nimport { criterionStatus } from \"../test-results\";\nimport { resolveStep, type StepContext } from \"./steps\";\n\n/** Everything the book maps are computed from. */\nexport type CollectedInput = {\n written: WrittenGrimoire;\n facts: BookFacts;\n ownership: Ownership;\n apps: Record<string, AppMatch>;\n proofs: ProofLine[];\n results: TestResultsStore | null;\n /** Test file → current sha256 (a result with another hash is stale). */\n testHashes: Record<string, string>;\n};\n\n/** The file name of a flow without `.md`: the name of its book map. */\nexport function flowFileId(flow: WrittenFlow): string {\n const name = toPosixPath(flow.file).split(\"/\").pop() ?? flow.id.value;\n\n return name.endsWith(\".md\") ? name.slice(0, -3) : name;\n}\n\n// ── Flow book maps ─────────────────────────────────────────────────────────\n\n/**\n * The result recorded for the test a proof line points at: same file and\n * line, else (the test moved) same name among the results whose line no\n * proof of that file claims.\n */\nfunction resultFor(\n proof: ProofLine,\n line: number,\n results: readonly ProofResult[],\n claimedLines: ReadonlySet<string>,\n): ProofResult | null {\n const file = toPosixPath(proof.at.file);\n const sameProof = (result: ProofResult): boolean =>\n result.feature === proof.feature &&\n result.flow === proof.flow &&\n result.criterion === proof.criterion;\n const inFile = results.filter((result) => toPosixPath(result.testFile) === file);\n const atLine = inFile.filter((result) => result.line === line);\n const byLine = atLine.find(sameProof) ?? atLine[0];\n\n if (byLine) return byLine;\n\n const name = proof.test?.name ?? null;\n\n if (name === null) return null;\n\n const named = inFile.filter(\n (result) =>\n !claimedLines.has(`${file}:${result.line}`) &&\n (result.testName === name || result.testName.endsWith(` > ${name}`)),\n );\n\n return named.find(sameProof) ?? named[0] ?? null;\n}\n\nfunction flowCriteria(flow: WrittenFlow, input: CollectedInput): FlowBookmapCriterion[] {\n const results = input.results?.results ?? [];\n const claimedLines = new Set(\n input.proofs.flatMap((proof) =>\n proof.test === null ? [] : [`${toPosixPath(proof.at.file)}:${proof.test.line}`],\n ),\n );\n\n return flow.criteria.map((criterion) => {\n const tests = input.proofs\n .filter(\n (proof) =>\n proof.ref === flow.ref && proof.criterion === criterion.id && proof.test !== null,\n )\n .map((proof) => {\n const line = proof.test?.line ?? proof.at.line;\n const file = toPosixPath(proof.at.file);\n const result = resultFor(proof, line, results, claimedLines);\n const currentHash = input.testHashes[file];\n const stale =\n result !== null && currentHash !== undefined && result.testFileHash !== currentHash;\n\n return {\n file,\n line,\n name: proof.test?.name ?? null,\n result: result?.outcome ?? (\"not-run\" as const),\n stale,\n };\n })\n .sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line);\n\n return {\n id: criterion.id,\n app: criterion.app,\n text: criterion.text,\n tests,\n status: criterionStatus(tests),\n };\n });\n}\n\nfunction shownBy(flow: WrittenFlow, written: WrittenGrimoire): FlowBookmap[\"shownBy\"] {\n const shown: FlowBookmap[\"shownBy\"] = [];\n\n for (const app of written.apps) {\n const appId = app.id.value;\n\n for (const layout of app.layouts) {\n for (const row of layout.blocks) {\n if (row.flow === flow.ref) {\n shown.push({\n app: appId,\n type: \"layout\",\n id: layout.id,\n block: row.block,\n file: layout.file,\n });\n }\n }\n }\n\n for (const page of [...app.pages, ...app.screens]) {\n for (const row of page.blocks) {\n if (row.flow === flow.ref) {\n shown.push({\n app: appId,\n type: page.type,\n id: page.id,\n block: row.block,\n file: page.file,\n });\n }\n }\n }\n }\n\n return shown;\n}\n\nfunction flowBookmap(\n feature: WrittenFeature,\n flow: WrittenFlow,\n input: CollectedInput,\n context: StepContext,\n): FlowBookmap {\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature: feature.id,\n flow: flowFileId(flow),\n ref: flow.ref,\n steps: flow.steps.map((step) => resolveStep(step, feature, context)),\n criteria: flowCriteria(flow, input),\n shownBy: shownBy(flow, input.written),\n };\n}\n\n// ── Feature book maps ──────────────────────────────────────────────────────\n\nfunction featureBookmap(\n feature: WrittenFeature,\n flows: readonly FlowBookmap[],\n input: CollectedInput,\n byPath: ReadonlyMap<string, BookFile>,\n): FeatureBookmap {\n const { ownership, facts } = input;\n const own = ownership.features[feature.id]?.own ?? [];\n const ownSet = new Set(own);\n\n // Own files importing each file, from one pass over the own files' imports (`own` is sorted, so each list is too).\n const importersOf = new Map<string, string[]>();\n\n for (const ownFile of own) {\n for (const entry of byPath.get(ownFile)?.imports ?? []) {\n if (entry.file === null) continue;\n\n const list = importersOf.get(entry.file) ?? [];\n\n if (list.at(-1) !== ownFile) list.push(ownFile);\n importersOf.set(entry.file, list);\n }\n }\n\n const borrowed: FeatureBookmap[\"borrowed\"] = (ownership.features[feature.id]?.borrowed ?? []).map(\n (file) => ({\n file,\n owner: ownership.files[file]?.owner ?? null,\n by: importersOf.get(file) ?? [],\n }),\n );\n\n const routes: FeatureBookmap[\"routes\"] = [];\n\n for (const route of facts.routes ?? []) {\n if (route.isPage) continue;\n\n const file =\n route.handlerFile !== null && ownSet.has(route.handlerFile)\n ? route.handlerFile\n : route.sourceFile !== null && ownSet.has(route.sourceFile)\n ? route.sourceFile\n : null;\n\n if (file !== null)\n routes.push({ method: route.method, path: route.path, name: route.name, file });\n }\n\n const pages: FeatureBookmap[\"pages\"] = {};\n const add = (app: string, item: FeatureBookmap[\"pages\"][string][number]): void => {\n (pages[app] ??= []).push(item);\n };\n const appOfSite = new Map<string, string>();\n const appOfMobile = new Map<string, string>();\n\n for (const match of Object.values(input.apps)) {\n if (match.site && !appOfSite.has(match.site.id)) appOfSite.set(match.site.id, match.app);\n if (match.mobile && !appOfMobile.has(match.mobile.id))\n appOfMobile.set(match.mobile.id, match.app);\n }\n\n for (const page of facts.pages) {\n const owned = ownSet.has(page.file) || (page.setupFile !== null && ownSet.has(page.setupFile));\n\n if (owned)\n add(appOfSite.get(page.site) ?? page.site, {\n route: page.route,\n file: page.file,\n type: \"page\",\n });\n }\n\n for (const mobile of facts.mobile) {\n for (const screen of mobile.screens) {\n if (ownSet.has(screen.file)) {\n add(appOfMobile.get(mobile.id) ?? mobile.id, {\n route: screen.route,\n file: screen.file,\n type: \"screen\",\n });\n }\n }\n }\n\n const sortedPages: FeatureBookmap[\"pages\"] = {};\n\n for (const app of Object.keys(pages).sort()) {\n sortedPages[app] = (pages[app] ?? []).sort(\n (left, right) => left.route.localeCompare(right.route) || left.file.localeCompare(right.file),\n );\n }\n\n // Ownership coverage (GR3006) counts type-only reach too.\n const reached = new Set(\n flows.flatMap((flow) => flow.steps.flatMap((step) => [...step.files, ...step.typeOnlyFiles])),\n );\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature: feature.id,\n own,\n borrowed,\n routes,\n pages: sortedPages,\n unreached: own.filter((file) => !reached.has(file)),\n };\n}\n\n// ── Indexes ────────────────────────────────────────────────────────────────\n\nfunction compareVersions(left: string, right: string): number {\n const [leftWhole = 0, leftDecimal = 0] = left.split(\".\").map(Number);\n const [rightWhole = 0, rightDecimal = 0] = right.split(\".\").map(Number);\n\n return leftWhole - rightWhole || leftDecimal - rightDecimal;\n}\n\nfunction featuresIndex(written: WrittenGrimoire): FeaturesIndex {\n const features: FeaturesIndex[\"features\"] = [];\n\n for (const feature of [...written.features].sort((left, right) =>\n left.id.localeCompare(right.id),\n )) {\n const readme = feature.readme;\n\n if (readme === null) continue;\n\n const releases = new Map<string, { version: string; release: string; date: string }>();\n\n for (const entry of feature.changelog?.entries ?? []) {\n if (entry.release === null || entry.date === null) continue;\n\n const version = entry.version.value;\n const known = releases.get(version);\n\n if (!known || entry.date > known.date) {\n releases.set(version, { version, release: entry.release, date: entry.date });\n }\n }\n\n features.push({\n id: feature.id,\n title: readme.title.value,\n status: readme.status.value,\n version: readme.version.value,\n updated: readme.updated.value,\n apps: readme.apps.map((app) => app.value),\n origin: readme.origin?.value ?? null,\n flows: feature.flows.map((flow) => ({\n id: flow.id.value,\n status: flow.status.value,\n since: flow.since.value,\n })),\n releases: [...releases.values()].sort(\n (left, right) =>\n right.date.localeCompare(left.date) || compareVersions(right.version, left.version),\n ),\n });\n }\n\n return { schemaVersion: BOOK_SCHEMA_VERSION, features };\n}\n\nfunction taskNumber(id: string): number {\n const match = /^T-(\\d+)$/.exec(id);\n\n return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER;\n}\n\nfunction taskSummary(task: WrittenTask): TaskSummary {\n return {\n id: task.id.value,\n title: task.heading?.value ?? task.id.value,\n type: task.type.value,\n status: task.status.value,\n feature: task.feature?.value ?? null,\n flow: task.flow?.value ?? null,\n apps: task.apps.map((app) => app.value),\n file: task.file,\n shipped: task.shipped\n ? { feature: task.shipped.value.feature, version: task.shipped.value.version }\n : null,\n decisionNeeded: task.decisionNeeded,\n };\n}\n\nfunction tasksIndex(written: WrittenGrimoire): TasksIndex {\n const sorted = [...written.tasks].sort(\n (left, right) =>\n taskNumber(left.id.value) - taskNumber(right.id.value) ||\n left.id.value.localeCompare(right.id.value),\n );\n const open = sorted.filter((task) => task.folder === \"open\").map(taskSummary);\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n open,\n waiting: open.filter(\n (task) => task.status === \"waiting for approval\" || task.decisionNeeded !== null,\n ),\n done: sorted.filter((task) => task.folder === \"done\").map(taskSummary),\n };\n}\n\n// ── Public ─────────────────────────────────────────────────────────────────\n\n/** Every feature and flow book map, `features/index.json` and `tasks/index.json`. Pure. */\nexport function buildCollectedFiles(input: CollectedInput): CollectedFiles {\n const context: StepContext = {\n written: input.written,\n facts: input.facts,\n apps: input.apps,\n graph: fileGraph(input.facts.files),\n };\n const byPath = new Map(input.facts.files.map((file) => [file.file, file]));\n const features: CollectedFiles[\"features\"] = {};\n const flows: CollectedFiles[\"flows\"] = {};\n\n for (const feature of [...input.written.features].sort((left, right) =>\n left.id.localeCompare(right.id),\n )) {\n const maps = feature.flows.map((flow) => flowBookmap(feature, flow, input, context));\n\n for (const map of maps) flows[map.ref] = map;\n\n features[feature.id] = featureBookmap(feature, maps, input, byPath);\n }\n\n return {\n features,\n flows,\n featuresIndex: featuresIndex(input.written),\n tasksIndex: tasksIndex(input.written),\n };\n}\n\n/** The per-file owner, borrowers and flows the book entries show. Pure. */\nexport function annotationsFrom(\n input: CollectedInput,\n collected: CollectedFiles,\n manifest: Pick<BookManifest, \"tests\">,\n): BookAnnotations {\n const flowsOf = new Map<string, Set<string>>();\n\n for (const map of Object.values(collected.flows)) {\n for (const step of map.steps) {\n for (const file of [...step.files, ...step.typeOnlyFiles]) {\n const set = flowsOf.get(file) ?? new Set<string>();\n set.add(map.ref);\n flowsOf.set(file, set);\n }\n }\n }\n\n const files: BookAnnotations[\"files\"] = {};\n\n for (const file of input.facts.files) {\n const ownership = input.ownership.files[file.file];\n\n files[file.file] = {\n feature: ownership?.owner ?? null,\n borrowedBy: [...(ownership?.borrowedBy ?? [])],\n flows: [...(flowsOf.get(file.file) ?? [])].sort(),\n };\n }\n\n return { writtenHash: input.written.hash, tests: { ...manifest.tests }, files };\n}\n"],"mappings":";;;;;;;;;AA0CA,SAAgB,WAAW,MAA2B;CACpD,MAAM,OAAO,YAAY,KAAK,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK,KAAK,GAAG;CAEhE,OAAO,KAAK,SAAS,KAAK,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;AACpD;;;;;;AASA,SAAS,UACP,OACA,MACA,SACA,cACoB;CACpB,MAAM,OAAO,YAAY,MAAM,GAAG,IAAI;CACtC,MAAM,aAAa,WACjB,OAAO,YAAY,MAAM,WACzB,OAAO,SAAS,MAAM,QACtB,OAAO,cAAc,MAAM;CAC7B,MAAM,SAAS,QAAQ,QAAQ,WAAW,YAAY,OAAO,QAAQ,MAAM,IAAI;CAC/E,MAAM,SAAS,OAAO,QAAQ,WAAW,OAAO,SAAS,IAAI;CAC7D,MAAM,SAAS,OAAO,KAAK,SAAS,KAAK,OAAO;CAEhD,IAAI,QAAQ,OAAO;CAEnB,MAAM,OAAO,MAAM,MAAM,QAAQ;CAEjC,IAAI,SAAS,MAAM,OAAO;CAE1B,MAAM,QAAQ,OAAO,QAClB,WACC,CAAC,aAAa,IAAI,GAAG,KAAK,GAAG,OAAO,MAAM,MACzC,OAAO,aAAa,QAAQ,OAAO,SAAS,SAAS,MAAM,MAAM,EACtE;CAEA,OAAO,MAAM,KAAK,SAAS,KAAK,MAAM,MAAM;AAC9C;AAEA,SAAS,aAAa,MA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MAAM,QAAQ,CAAC,GAAG,KAAK,OAAO,GAAG,KAAK,aAAa,GAAG;EACzD,MAAM,MAAM,QAAQ,IAAI,IAAI,qBAAK,IAAI,IAAY;EACjD,IAAI,IAAI,IAAI,GAAG;EACf,QAAQ,IAAI,MAAM,GAAG;CACvB;CAIJ,MAAM,QAAkC,CAAC;CAEzC,KAAK,MAAM,QAAQ,MAAM,MAAM,OAAO;EACpC,MAAM,YAAY,MAAM,UAAU,MAAM,KAAK;EAE7C,MAAM,KAAK,QAAQ;GACjB,SAAS,WAAW,SAAS;GAC7B,YAAY,CAAC,GAAI,WAAW,cAAc,CAAC,CAAE;GAC7C,OAAO,CAAC,GAAI,QAAQ,IAAI,KAAK,IAAI,KAAK,CAAC,CAAE,CAAC,CAAC,KAAK;EAClD;CACF;CAEA,OAAO;EAAE,aAAa,MAAM,QAAQ;EAAM,OAAO,EAAE,GAAG,SAAS,MAAM;EAAG;CAAM;AAChF"}
1
+ {"version":3,"file":"build.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/build.ts"],"sourcesContent":["/**\n * Builds the book maps and the collected indexes in memory. Pure: reads only\n * its input.\n */\nimport type { BookFacts, BookFile } from \"../contracts/adapter\";\nimport { BOOK_SCHEMA_VERSION, type BookAnnotations, type BookManifest } from \"../contracts/book\";\nimport type {\n CollectedFiles,\n FeatureBookmap,\n FeaturesIndex,\n FlowBookmap,\n FlowBookmapCriterion,\n Ownership,\n TaskSummary,\n TasksIndex,\n} from \"../contracts/bookmap\";\nimport type { AppMatch } from \"../contracts/snapshot\";\nimport type { ProofLine, ProofResult, TestResultsStore } from \"../contracts/test-results\";\nimport type {\n WrittenFeature,\n WrittenFlow,\n WrittenGrimoire,\n WrittenTask,\n} from \"../contracts/written\";\nimport { fileGraph } from \"../graph\";\nimport { isExemptFromReach, specOnlyFiles } from \"../ownership\";\nimport { toPosixPath } from \"../paths\";\nimport { criterionStatus } from \"../test-results\";\nimport { resolveStep, type StepContext } from \"./steps\";\n\n/** Everything the book maps are computed from. */\nexport type CollectedInput = {\n written: WrittenGrimoire;\n facts: BookFacts;\n ownership: Ownership;\n apps: Record<string, AppMatch>;\n proofs: ProofLine[];\n results: TestResultsStore | null;\n /** Test file → current sha256 (a result with another hash is stale). */\n testHashes: Record<string, string>;\n};\n\n/** The file name of a flow without `.md`: the name of its book map. */\nexport function flowFileId(flow: WrittenFlow): string {\n const name = toPosixPath(flow.file).split(\"/\").pop() ?? flow.id.value;\n\n return name.endsWith(\".md\") ? name.slice(0, -3) : name;\n}\n\n// ── Flow book maps ─────────────────────────────────────────────────────────\n\n/**\n * The result recorded for the test a proof line points at: same file and\n * line, else (the test moved) same name among the results whose line no\n * proof of that file claims.\n */\nfunction resultFor(\n proof: ProofLine,\n line: number,\n results: readonly ProofResult[],\n claimedLines: ReadonlySet<string>,\n): ProofResult | null {\n const file = toPosixPath(proof.at.file);\n const sameProof = (result: ProofResult): boolean =>\n result.feature === proof.feature &&\n result.flow === proof.flow &&\n result.criterion === proof.criterion;\n const inFile = results.filter((result) => toPosixPath(result.testFile) === file);\n const atLine = inFile.filter((result) => result.line === line);\n const byLine = atLine.find(sameProof) ?? atLine[0];\n\n if (byLine) return byLine;\n\n const name = proof.test?.name ?? null;\n\n if (name === null) return null;\n\n const named = inFile.filter(\n (result) =>\n !claimedLines.has(`${file}:${result.line}`) &&\n (result.testName === name || result.testName.endsWith(` > ${name}`)),\n );\n\n return named.find(sameProof) ?? named[0] ?? null;\n}\n\nfunction flowCriteria(flow: WrittenFlow, input: CollectedInput): FlowBookmapCriterion[] {\n const results = input.results?.results ?? [];\n const claimedLines = new Set(\n input.proofs.flatMap((proof) =>\n proof.test === null ? [] : [`${toPosixPath(proof.at.file)}:${proof.test.line}`],\n ),\n );\n\n return flow.criteria.map((criterion) => {\n const tests = input.proofs\n .filter(\n (proof) =>\n proof.ref === flow.ref && proof.criterion === criterion.id && proof.test !== null,\n )\n .map((proof) => {\n const line = proof.test?.line ?? proof.at.line;\n const file = toPosixPath(proof.at.file);\n const result = resultFor(proof, line, results, claimedLines);\n const currentHash = input.testHashes[file];\n const stale =\n result !== null && currentHash !== undefined && result.testFileHash !== currentHash;\n\n return {\n file,\n line,\n name: proof.test?.name ?? null,\n result: result?.outcome ?? (\"not-run\" as const),\n stale,\n };\n })\n .sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line);\n\n return {\n id: criterion.id,\n app: criterion.app,\n text: criterion.text,\n tests,\n status: criterionStatus(tests),\n };\n });\n}\n\nfunction shownBy(flow: WrittenFlow, written: WrittenGrimoire): FlowBookmap[\"shownBy\"] {\n const shown: FlowBookmap[\"shownBy\"] = [];\n\n for (const app of written.apps) {\n const appId = app.id.value;\n\n for (const layout of app.layouts) {\n for (const row of layout.blocks) {\n if (row.flow === flow.ref) {\n shown.push({\n app: appId,\n type: \"layout\",\n id: layout.id,\n block: row.block,\n file: layout.file,\n });\n }\n }\n }\n\n for (const page of [...app.pages, ...app.screens]) {\n for (const row of page.blocks) {\n if (row.flow === flow.ref) {\n shown.push({\n app: appId,\n type: page.type,\n id: page.id,\n block: row.block,\n file: page.file,\n });\n }\n }\n }\n }\n\n return shown;\n}\n\nfunction flowBookmap(\n feature: WrittenFeature,\n flow: WrittenFlow,\n input: CollectedInput,\n context: StepContext,\n): FlowBookmap {\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature: feature.id,\n flow: flowFileId(flow),\n ref: flow.ref,\n steps: flow.steps.map((step) => resolveStep(step, feature, context)),\n criteria: flowCriteria(flow, input),\n shownBy: shownBy(flow, input.written),\n };\n}\n\n// ── Feature book maps ──────────────────────────────────────────────────────\n\nfunction featureBookmap(\n feature: WrittenFeature,\n flows: readonly FlowBookmap[],\n input: CollectedInput,\n byPath: ReadonlyMap<string, BookFile>,\n specOnly: ReadonlySet<string>,\n): FeatureBookmap {\n const { ownership, facts } = input;\n const own = ownership.features[feature.id]?.own ?? [];\n const ownSet = new Set(own);\n\n // Own files importing each file, from one pass over the own files' imports (`own` is sorted, so each list is too).\n const importersOf = new Map<string, string[]>();\n\n for (const ownFile of own) {\n for (const entry of byPath.get(ownFile)?.imports ?? []) {\n if (entry.file === null) continue;\n\n const list = importersOf.get(entry.file) ?? [];\n\n if (list.at(-1) !== ownFile) list.push(ownFile);\n importersOf.set(entry.file, list);\n }\n }\n\n const borrowed: FeatureBookmap[\"borrowed\"] = (ownership.features[feature.id]?.borrowed ?? []).map(\n (file) => ({\n file,\n owner: ownership.files[file]?.owner ?? null,\n by: importersOf.get(file) ?? [],\n }),\n );\n\n const routes: FeatureBookmap[\"routes\"] = [];\n\n for (const route of facts.routes ?? []) {\n if (route.isPage) continue;\n\n const file =\n route.handlerFile !== null && ownSet.has(route.handlerFile)\n ? route.handlerFile\n : route.sourceFile !== null && ownSet.has(route.sourceFile)\n ? route.sourceFile\n : null;\n\n if (file !== null)\n routes.push({ method: route.method, path: route.path, name: route.name, file });\n }\n\n const pages: FeatureBookmap[\"pages\"] = {};\n const add = (app: string, item: FeatureBookmap[\"pages\"][string][number]): void => {\n (pages[app] ??= []).push(item);\n };\n const appOfSite = new Map<string, string>();\n const appOfMobile = new Map<string, string>();\n\n for (const match of Object.values(input.apps)) {\n if (match.site && !appOfSite.has(match.site.id)) appOfSite.set(match.site.id, match.app);\n if (match.mobile && !appOfMobile.has(match.mobile.id))\n appOfMobile.set(match.mobile.id, match.app);\n }\n\n for (const page of facts.pages) {\n const owned = ownSet.has(page.file) || (page.setupFile !== null && ownSet.has(page.setupFile));\n\n if (owned)\n add(appOfSite.get(page.site) ?? page.site, {\n route: page.route,\n file: page.file,\n type: \"page\",\n });\n }\n\n for (const mobile of facts.mobile) {\n for (const screen of mobile.screens) {\n if (ownSet.has(screen.file)) {\n add(appOfMobile.get(mobile.id) ?? mobile.id, {\n route: screen.route,\n file: screen.file,\n type: \"screen\",\n });\n }\n }\n }\n\n const sortedPages: FeatureBookmap[\"pages\"] = {};\n\n for (const app of Object.keys(pages).sort()) {\n sortedPages[app] = (pages[app] ?? []).sort(\n (left, right) => left.route.localeCompare(right.route) || left.file.localeCompare(right.file),\n );\n }\n\n // Ownership coverage (GR3006) counts type-only reach too.\n const reached = new Set(\n flows.flatMap((flow) => flow.steps.flatMap((step) => [...step.files, ...step.typeOnlyFiles])),\n );\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature: feature.id,\n own,\n borrowed,\n routes,\n pages: sortedPages,\n unreached: own.filter(\n (file) =>\n !reached.has(file) &&\n !specOnly.has(file) &&\n !isExemptFromReach(byPath.get(file) ?? { type: \"source\" }),\n ),\n };\n}\n\n// ── Indexes ────────────────────────────────────────────────────────────────\n\nfunction compareVersions(left: string, right: string): number {\n const [leftWhole = 0, leftDecimal = 0] = left.split(\".\").map(Number);\n const [rightWhole = 0, rightDecimal = 0] = right.split(\".\").map(Number);\n\n return leftWhole - rightWhole || leftDecimal - rightDecimal;\n}\n\nfunction featuresIndex(written: WrittenGrimoire): FeaturesIndex {\n const features: FeaturesIndex[\"features\"] = [];\n\n for (const feature of [...written.features].sort((left, right) =>\n left.id.localeCompare(right.id),\n )) {\n const readme = feature.readme;\n\n if (readme === null) continue;\n\n const releases = new Map<string, { version: string; release: string; date: string }>();\n\n for (const entry of feature.changelog?.entries ?? []) {\n if (entry.release === null || entry.date === null) continue;\n\n const version = entry.version.value;\n const known = releases.get(version);\n\n if (!known || entry.date > known.date) {\n releases.set(version, { version, release: entry.release, date: entry.date });\n }\n }\n\n features.push({\n id: feature.id,\n title: readme.title.value,\n status: readme.status.value,\n version: readme.version.value,\n updated: readme.updated.value,\n apps: readme.apps.map((app) => app.value),\n origin: readme.origin?.value ?? null,\n flows: feature.flows.map((flow) => ({\n id: flow.id.value,\n status: flow.status.value,\n since: flow.since.value,\n })),\n releases: [...releases.values()].sort(\n (left, right) =>\n right.date.localeCompare(left.date) || compareVersions(right.version, left.version),\n ),\n });\n }\n\n return { schemaVersion: BOOK_SCHEMA_VERSION, features };\n}\n\nfunction taskNumber(id: string): number {\n const match = /^T-(\\d+)$/.exec(id);\n\n return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER;\n}\n\nfunction taskSummary(task: WrittenTask): TaskSummary {\n return {\n id: task.id.value,\n title: task.heading?.value ?? task.id.value,\n type: task.type.value,\n status: task.status.value,\n feature: task.feature?.value ?? null,\n flow: task.flow?.value ?? null,\n apps: task.apps.map((app) => app.value),\n file: task.file,\n shipped: task.shipped\n ? { feature: task.shipped.value.feature, version: task.shipped.value.version }\n : null,\n decisionNeeded: task.decisionNeeded,\n };\n}\n\nfunction tasksIndex(written: WrittenGrimoire): TasksIndex {\n const sorted = [...written.tasks].sort(\n (left, right) =>\n taskNumber(left.id.value) - taskNumber(right.id.value) ||\n left.id.value.localeCompare(right.id.value),\n );\n const open = sorted.filter((task) => task.folder === \"open\").map(taskSummary);\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n open,\n waiting: open.filter(\n (task) => task.status === \"waiting for approval\" || task.decisionNeeded !== null,\n ),\n done: sorted.filter((task) => task.folder === \"done\").map(taskSummary),\n };\n}\n\n// ── Public ─────────────────────────────────────────────────────────────────\n\n/** Every feature and flow book map, `features/index.json` and `tasks/index.json`. Pure. */\nexport function buildCollectedFiles(input: CollectedInput): CollectedFiles {\n const context: StepContext = {\n written: input.written,\n facts: input.facts,\n apps: input.apps,\n graph: fileGraph(input.facts.files),\n };\n const byPath = new Map(input.facts.files.map((file) => [file.file, file]));\n const specOnly = specOnlyFiles(input.facts.files);\n const features: CollectedFiles[\"features\"] = {};\n const flows: CollectedFiles[\"flows\"] = {};\n\n for (const feature of [...input.written.features].sort((left, right) =>\n left.id.localeCompare(right.id),\n )) {\n const maps = feature.flows.map((flow) => flowBookmap(feature, flow, input, context));\n\n for (const map of maps) flows[map.ref] = map;\n\n features[feature.id] = featureBookmap(feature, maps, input, byPath, specOnly);\n }\n\n return {\n features,\n flows,\n featuresIndex: featuresIndex(input.written),\n tasksIndex: tasksIndex(input.written),\n };\n}\n\n/** The per-file owner, borrowers and flows the book entries show. Pure. */\nexport function annotationsFrom(\n input: CollectedInput,\n collected: CollectedFiles,\n manifest: Pick<BookManifest, \"tests\">,\n): BookAnnotations {\n const flowsOf = new Map<string, Set<string>>();\n\n for (const map of Object.values(collected.flows)) {\n for (const step of map.steps) {\n for (const file of [...step.files, ...step.typeOnlyFiles]) {\n const set = flowsOf.get(file) ?? new Set<string>();\n set.add(map.ref);\n flowsOf.set(file, set);\n }\n }\n }\n\n const files: BookAnnotations[\"files\"] = {};\n\n for (const file of input.facts.files) {\n const ownership = input.ownership.files[file.file];\n\n files[file.file] = {\n feature: ownership?.owner ?? null,\n borrowedBy: [...(ownership?.borrowedBy ?? [])],\n flows: [...(flowsOf.get(file.file) ?? [])].sort(),\n };\n }\n\n return { writtenHash: input.written.hash, tests: { ...manifest.tests }, files };\n}\n"],"mappings":";;;;;;;;;;AA2CA,SAAgB,WAAW,MAA2B;CACpD,MAAM,OAAO,YAAY,KAAK,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK,KAAK,GAAG;CAEhE,OAAO,KAAK,SAAS,KAAK,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;AACpD;;;;;;AASA,SAAS,UACP,OACA,MACA,SACA,cACoB;CACpB,MAAM,OAAO,YAAY,MAAM,GAAG,IAAI;CACtC,MAAM,aAAa,WACjB,OAAO,YAAY,MAAM,WACzB,OAAO,SAAS,MAAM,QACtB,OAAO,cAAc,MAAM;CAC7B,MAAM,SAAS,QAAQ,QAAQ,WAAW,YAAY,OAAO,QAAQ,MAAM,IAAI;CAC/E,MAAM,SAAS,OAAO,QAAQ,WAAW,OAAO,SAAS,IAAI;CAC7D,MAAM,SAAS,OAAO,KAAK,SAAS,KAAK,OAAO;CAEhD,IAAI,QAAQ,OAAO;CAEnB,MAAM,OAAO,MAAM,MAAM,QAAQ;CAEjC,IAAI,SAAS,MAAM,OAAO;CAE1B,MAAM,QAAQ,OAAO,QAClB,WACC,CAAC,aAAa,IAAI,GAAG,KAAK,GAAG,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,eAAe,SAAS,MAAM,OAAO,QAAQ,QAAQ;CAC9E;CAEA,OAAO;EACL;EACA;EACA,eAAe,cAAc,MAAM,OAAO;EAC1C,YAAY,WAAW,MAAM,OAAO;CACtC;AACF;;AAGA,SAAgB,gBACd,OACA,WACA,UACiB;CACjB,MAAM,0BAAU,IAAI,IAAyB;CAE7C,KAAK,MAAM,OAAO,OAAO,OAAO,UAAU,KAAK,GAC7C,KAAK,MAAM,QAAQ,IAAI,OACrB,KAAK,MAAM,QAAQ,CAAC,GAAG,KAAK,OAAO,GAAG,KAAK,aAAa,GAAG;EACzD,MAAM,MAAM,QAAQ,IAAI,IAAI,qBAAK,IAAI,IAAY;EACjD,IAAI,IAAI,IAAI,GAAG;EACf,QAAQ,IAAI,MAAM,GAAG;CACvB;CAIJ,MAAM,QAAkC,CAAC;CAEzC,KAAK,MAAM,QAAQ,MAAM,MAAM,OAAO;EACpC,MAAM,YAAY,MAAM,UAAU,MAAM,KAAK;EAE7C,MAAM,KAAK,QAAQ;GACjB,SAAS,WAAW,SAAS;GAC7B,YAAY,CAAC,GAAI,WAAW,cAAc,CAAC,CAAE;GAC7C,OAAO,CAAC,GAAI,QAAQ,IAAI,KAAK,IAAI,KAAK,CAAC,CAAE,CAAC,CAAC,KAAK;EAClD;CACF;CAEA,OAAO;EAAE,aAAa,MAAM,QAAQ;EAAM,OAAO,EAAE,GAAG,SAAS,MAAM;EAAG;CAAM;AAChF"}
@@ -60,6 +60,32 @@ function reach(graph, entries, extra = []) {
60
60
  typeOnlyFiles: everything.filter((file) => !files.has(file))
61
61
  };
62
62
  }
63
+ /** `auth-only.middleware.ts` → `authOnly` (the camelCase stem without the role suffix). */
64
+ function middlewareNameOf(file) {
65
+ return (file.split("/").pop() ?? file).replace(/\.(?:d\.ts|[cm]?[jt]sx?)$/, "").replace(/\.middleware$/, "").replace(/[-_.]+([a-zA-Z0-9])/g, (_match, letter) => letter.toUpperCase());
66
+ }
67
+ /**
68
+ * The files of the middleware a route names. A name matches a file that exports
69
+ * it, or a `*.middleware.*` file whose stem is the name (`auth-only.middleware.ts` ↔ `authOnly`).
70
+ * When the routes file imports some of the matches, only those count (two
71
+ * modules may name a middleware the same). The routes file's other imports are
72
+ * not followed: it imports every controller of its module.
73
+ */
74
+ function middlewareFiles(names, routesFile, graph) {
75
+ const imported = new Set(routesFile === null ? [] : (graph.get(routesFile)?.imports ?? []).flatMap((edge) => edge.file === null ? [] : [edge.file]));
76
+ const found = [];
77
+ for (const name of names) {
78
+ const matches = [];
79
+ for (const [file, entry] of graph) {
80
+ const exports = entry.exports ?? [];
81
+ const byStem = /\.middleware\.(?:[cm]?[jt]sx?)$/.test(file) && middlewareNameOf(file) === name;
82
+ if (exports.some((item) => item.name === name) || byStem) matches.push(file);
83
+ }
84
+ const near = matches.filter((file) => imported.has(file));
85
+ found.push(...near.length > 0 ? near : matches.length === 1 ? matches : []);
86
+ }
87
+ return found;
88
+ }
63
89
  function routeStep(step, facts, graph) {
64
90
  if (facts.routes === null || step.route === null) return UNKNOWN;
65
91
  const target = step.route;
@@ -68,8 +94,13 @@ function routeStep(step, facts, graph) {
68
94
  if (!first) return NOTHING;
69
95
  const handlers = routes.flatMap((route) => route.handlerFile === null ? [] : [route.handlerFile]);
70
96
  const sources = routes.flatMap((route) => route.sourceFile === null ? [] : [route.sourceFile]);
71
- const handlerReach = reach(graph, handlers, sources);
72
- const entries = sortedUnique([...handlers, ...sources]);
97
+ const middleware = routes.flatMap((route) => middlewareFiles(route.middleware, route.sourceFile, graph));
98
+ const handlerReach = reach(graph, [...handlers, ...middleware], sources);
99
+ const entries = sortedUnique([
100
+ ...handlers,
101
+ ...middleware,
102
+ ...sources
103
+ ]);
73
104
  return {
74
105
  found: true,
75
106
  entry: first.handlerFile ?? first.sourceFile,
@@ -112,7 +143,7 @@ function pageStep(step, feature, facts, apps, graph) {
112
143
  function namedStep(step, facts, graph) {
113
144
  const named = facts.named.filter((thing) => thing.type === step.type && thing.name === step.target);
114
145
  const first = named[0];
115
- if (!first) return NOTHING;
146
+ if (!first) return facts.routes === null ? UNKNOWN : NOTHING;
116
147
  const entries = named.flatMap((thing) => thing.file === null ? [] : [thing.file]);
117
148
  return {
118
149
  found: true,
@@ -1 +1 @@
1
- {"version":3,"file":"steps.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/steps.ts"],"sourcesContent":["/**\n * The files behind each step of a flow: what a route, page, mail, job, event\n * or notification step reaches in the book.\n */\nimport type { BookFacts, BookNamedType } from \"../contracts/adapter\";\nimport type { FlowBookmapStep } from \"../contracts/bookmap\";\nimport type { AppMatch } from \"../contracts/snapshot\";\nimport type { WrittenFeature, WrittenGrimoire, WrittenStep } from \"../contracts/written\";\nimport { importClosure, type FileGraph } from \"../graph\";\n\nconst NAMED_TYPES: ReadonlySet<string> = new Set<BookNamedType>([\n \"mail\",\n \"job\",\n \"event\",\n \"notification\",\n]);\n\n/** A route path with params written one way (`:id` and `[id]` → `:id`) and no trailing `/`. */\nexport function normalizeRoutePath(route: string): string {\n const withParams = route\n .trim()\n .replace(/\\[\\.\\.\\.([^\\]]+)\\]/g, \":$1\")\n .replace(/\\[([^\\]]+)\\]/g, \":$1\");\n const trimmed = withParams.replace(/\\/+$/, \"\");\n\n return trimmed === \"\" ? \"/\" : trimmed;\n}\n\n/**\n * Whether a route answers `METHOD path`: paths compared after\n * `normalizeRoutePath` (`:id` ≡ `[id]`, trailing `/` ignored), methods\n * without regard to case, `ALL` on either side matching any method. The\n * check, the book maps and `scry --route` all match this way.\n */\nexport function routeMatches(\n route: { readonly method: string; readonly path: string },\n method: string,\n path: string,\n): boolean {\n const routeMethod = route.method.toUpperCase();\n const asked = method.toUpperCase();\n const methodMatches = routeMethod === asked || routeMethod === \"ALL\" || asked === \"ALL\";\n\n return methodMatches && normalizeRoutePath(route.path) === normalizeRoutePath(path);\n}\n\nfunction sortedUnique(files: Iterable<string>): string[] {\n return [...new Set(files)].sort();\n}\n\n/** What the step matched: its entry files and the files behind them. */\ntype StepMatch = Pick<\n FlowBookmapStep,\n \"found\" | \"entry\" | \"entries\" | \"direct\" | \"files\" | \"typeOnlyFiles\"\n>;\n\nconst NOTHING: StepMatch = {\n found: false,\n entry: null,\n entries: [],\n direct: [],\n files: [],\n typeOnlyFiles: [],\n};\n\nconst UNKNOWN: StepMatch = { ...NOTHING, found: null };\n\n/**\n * Work out a step's files from its entry files. `extra` are files that belong\n * to the step without being imported by an entry (a route's routes file).\n */\nfunction reach(\n graph: FileGraph,\n entries: readonly string[],\n extra: readonly string[] = [],\n): Pick<StepMatch, \"entries\" | \"direct\" | \"files\" | \"typeOnlyFiles\"> {\n const entryFiles = sortedUnique(entries);\n const known = new Set(entryFiles);\n const direct = new Set<string>();\n\n for (const entry of entryFiles) {\n for (const edge of graph.get(entry)?.imports ?? []) {\n if (edge.file !== null && !known.has(edge.file)) direct.add(edge.file);\n }\n }\n\n const files = new Set([\n ...entryFiles,\n ...extra,\n ...importClosure(graph, entryFiles, { skipTypeOnly: true }),\n ]);\n const everything = importClosure(graph, entryFiles);\n\n return {\n entries: entryFiles,\n direct: sortedUnique(direct),\n files: sortedUnique(files),\n typeOnlyFiles: everything.filter((file) => !files.has(file)),\n };\n}\n\nfunction routeStep(step: WrittenStep, facts: BookFacts, graph: FileGraph): StepMatch {\n if (facts.routes === null || step.route === null) return UNKNOWN;\n\n const target = step.route;\n const routes = facts.routes.filter((route) => routeMatches(route, target.method, target.path));\n const first = routes[0];\n\n if (!first) return NOTHING;\n\n const handlers = routes.flatMap((route) => (route.handlerFile === null ? [] : [route.handlerFile]));\n const sources = routes.flatMap((route) => (route.sourceFile === null ? [] : [route.sourceFile]));\n const handlerReach = reach(graph, handlers, sources);\n // The routes files are entries too, but their own imports are not part of the step.\n const entries = sortedUnique([...handlers, ...sources]);\n\n return {\n found: true,\n entry: first.handlerFile ?? first.sourceFile,\n ...handlerReach,\n entries,\n direct: handlerReach.direct.filter((file) => !entries.includes(file)),\n };\n}\n\nfunction pageStep(\n step: WrittenStep,\n feature: WrittenFeature,\n facts: BookFacts,\n apps: Record<string, AppMatch>,\n graph: FileGraph,\n): StepMatch {\n const wanted = normalizeRoutePath(step.target);\n const matched: string[] = [];\n const starts: string[] = [];\n\n // `page /support [web-admin]` looks in that app only; without a scope, in the feature's apps.\n const appIds =\n step.app === null ? (feature.readme?.apps.map((app) => app.value) ?? []) : [step.app];\n\n for (const appId of appIds) {\n const match = apps[appId];\n\n if (!match) continue;\n\n if (match.site) {\n const siteId = match.site.id;\n\n for (const page of facts.pages) {\n if (page.site !== siteId || normalizeRoutePath(page.route) !== wanted) continue;\n\n matched.push(page.file);\n starts.push(page.file);\n if (page.setupFile !== null) starts.push(page.setupFile);\n }\n }\n\n if (match.mobile) {\n for (const screen of match.mobile.screens) {\n if (normalizeRoutePath(screen.route) !== wanted) continue;\n\n matched.push(screen.file);\n starts.push(screen.file);\n }\n }\n }\n\n const entry = matched[0];\n\n if (entry === undefined) return NOTHING;\n\n return { found: true, entry, ...reach(graph, starts) };\n}\n\nfunction namedStep(step: WrittenStep, facts: BookFacts, graph: FileGraph): StepMatch {\n const named = facts.named.filter(\n (thing) => thing.type === step.type && thing.name === step.target,\n );\n const first = named[0];\n\n if (!first) return NOTHING;\n\n const entries = named.flatMap((thing) => (thing.file === null ? [] : [thing.file]));\n\n return { found: true, entry: first.file, ...reach(graph, entries) };\n}\n\nfunction affectsStep(step: WrittenStep, written: WrittenGrimoire): StepMatch {\n const target = step.affects;\n\n if (target === null) return NOTHING;\n\n const feature = written.features.find((candidate) => candidate.id === target.feature);\n const found =\n feature !== undefined &&\n (target.flow === null || feature.flows.some((flow) => flow.id.value === target.flow));\n\n return { ...NOTHING, found };\n}\n\n/** Everything the step resolver reads. */\nexport type StepContext = {\n written: WrittenGrimoire;\n facts: BookFacts;\n apps: Record<string, AppMatch>;\n graph: FileGraph;\n};\n\n/** One step of a flow of `feature`, with what it matched in the book. */\nexport function resolveStep(\n step: WrittenStep,\n feature: WrittenFeature,\n context: StepContext,\n): FlowBookmapStep {\n let match: StepMatch;\n\n if (step.type === \"route\") match = routeStep(step, context.facts, context.graph);\n else if (step.type === \"page\")\n match = pageStep(step, feature, context.facts, context.apps, context.graph);\n else if (NAMED_TYPES.has(step.type)) match = namedStep(step, context.facts, context.graph);\n else if (step.type === \"affects\") match = affectsStep(step, context.written);\n else match = UNKNOWN;\n\n const target = step.app === null ? step.target : `${step.target} [${step.app}]`;\n\n return { index: step.index, type: step.type, target, ...match };\n}\n"],"mappings":";;;AAUA,MAAM,8BAAmC,IAAI,IAAmB;CAC9D;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,mBAAmB,OAAuB;CAKxD,MAAM,UAJa,MAChB,KAAK,CAAC,CACN,QAAQ,uBAAuB,KAAK,CAAC,CACrC,QAAQ,iBAAiB,KACH,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAE7C,OAAO,YAAY,KAAK,MAAM;AAChC;;;;;;;AAQA,SAAgB,aACd,OACA,QACA,MACS;CACT,MAAM,cAAc,MAAM,OAAO,YAAY;CAC7C,MAAM,QAAQ,OAAO,YAAY;CAGjC,QAFsB,gBAAgB,SAAS,gBAAgB,SAAS,UAAU,UAE1D,mBAAmB,MAAM,IAAI,MAAM,mBAAmB,IAAI;AACpF;AAEA,SAAS,aAAa,OAAmC;CACvD,OAAO,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK;AAClC;AAQA,MAAM,UAAqB;CACzB,OAAO;CACP,OAAO;CACP,SAAS,CAAC;CACV,QAAQ,CAAC;CACT,OAAO,CAAC;CACR,eAAe,CAAC;AAClB;AAEA,MAAM,UAAqB;CAAE,GAAG;CAAS,OAAO;AAAK;;;;;AAMrD,SAAS,MACP,OACA,SACA,QAA2B,CAAC,GACuC;CACnE,MAAM,aAAa,aAAa,OAAO;CACvC,MAAM,QAAQ,IAAI,IAAI,UAAU;CAChC,MAAM,yBAAS,IAAI,IAAY;CAE/B,KAAK,MAAM,SAAS,YAClB,KAAK,MAAM,QAAQ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,SAAqC;CAC3E,MAAM,SAAS,KAAK;CAEpB,IAAI,WAAW,MAAM,OAAO;CAE5B,MAAM,UAAU,QAAQ,SAAS,MAAM,cAAc,UAAU,OAAO,OAAO,OAAO;CACpF,MAAM,QACJ,YAAY,WACX,OAAO,SAAS,QAAQ,QAAQ,MAAM,MAAM,SAAS,KAAK,GAAG,UAAU,OAAO,IAAI;CAErF,OAAO;EAAE,GAAG;EAAS;CAAM;AAC7B;;AAWA,SAAgB,YACd,MACA,SACA,SACiB;CACjB,IAAI;CAEJ,IAAI,KAAK,SAAS,SAAS,QAAQ,UAAU,MAAM,QAAQ,OAAO,QAAQ,KAAK;MAC1E,IAAI,KAAK,SAAS,QACrB,QAAQ,SAAS,MAAM,SAAS,QAAQ,OAAO,QAAQ,MAAM,QAAQ,KAAK;MACvE,IAAI,YAAY,IAAI,KAAK,IAAI,GAAG,QAAQ,UAAU,MAAM,QAAQ,OAAO,QAAQ,KAAK;MACpF,IAAI,KAAK,SAAS,WAAW,QAAQ,YAAY,MAAM,QAAQ,OAAO;MACtE,QAAQ;CAEb,MAAM,SAAS,KAAK,QAAQ,OAAO,KAAK,SAAS,GAAG,KAAK,OAAO,IAAI,KAAK,IAAI;CAE7E,OAAO;EAAE,OAAO,KAAK;EAAO,MAAM,KAAK;EAAM;EAAQ,GAAG;CAAM;AAChE"}
1
+ {"version":3,"file":"steps.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/steps.ts"],"sourcesContent":["/**\n * The files behind each step of a flow: what a route, page, mail, job, event\n * or notification step reaches in the book.\n */\nimport type { BookFacts, BookNamedType } from \"../contracts/adapter\";\nimport type { FlowBookmapStep } from \"../contracts/bookmap\";\nimport type { AppMatch } from \"../contracts/snapshot\";\nimport type { WrittenFeature, WrittenGrimoire, WrittenStep } from \"../contracts/written\";\nimport { importClosure, type FileGraph } from \"../graph\";\n\nconst NAMED_TYPES: ReadonlySet<string> = new Set<BookNamedType>([\n \"mail\",\n \"job\",\n \"event\",\n \"notification\",\n]);\n\n/** A route path with params written one way (`:id` and `[id]` → `:id`) and no trailing `/`. */\nexport function normalizeRoutePath(route: string): string {\n const withParams = route\n .trim()\n .replace(/\\[\\.\\.\\.([^\\]]+)\\]/g, \":$1\")\n .replace(/\\[([^\\]]+)\\]/g, \":$1\");\n const trimmed = withParams.replace(/\\/+$/, \"\");\n\n return trimmed === \"\" ? \"/\" : trimmed;\n}\n\n/**\n * Whether a route answers `METHOD path`: paths compared after\n * `normalizeRoutePath` (`:id` ≡ `[id]`, trailing `/` ignored), methods\n * without regard to case, `ALL` on either side matching any method. The\n * check, the book maps and `scry --route` all match this way.\n */\nexport function routeMatches(\n route: { readonly method: string; readonly path: string },\n method: string,\n path: string,\n): boolean {\n const routeMethod = route.method.toUpperCase();\n const asked = method.toUpperCase();\n const methodMatches = routeMethod === asked || routeMethod === \"ALL\" || asked === \"ALL\";\n\n return methodMatches && normalizeRoutePath(route.path) === normalizeRoutePath(path);\n}\n\nfunction sortedUnique(files: Iterable<string>): string[] {\n return [...new Set(files)].sort();\n}\n\n/** What the step matched: its entry files and the files behind them. */\ntype StepMatch = Pick<\n FlowBookmapStep,\n \"found\" | \"entry\" | \"entries\" | \"direct\" | \"files\" | \"typeOnlyFiles\"\n>;\n\nconst NOTHING: StepMatch = {\n found: false,\n entry: null,\n entries: [],\n direct: [],\n files: [],\n typeOnlyFiles: [],\n};\n\nconst UNKNOWN: StepMatch = { ...NOTHING, found: null };\n\n/**\n * Work out a step's files from its entry files. `extra` are files that belong\n * to the step without being imported by an entry (a route's routes file).\n */\nfunction reach(\n graph: FileGraph,\n entries: readonly string[],\n extra: readonly string[] = [],\n): Pick<StepMatch, \"entries\" | \"direct\" | \"files\" | \"typeOnlyFiles\"> {\n const entryFiles = sortedUnique(entries);\n const known = new Set(entryFiles);\n const direct = new Set<string>();\n\n for (const entry of entryFiles) {\n for (const edge of graph.get(entry)?.imports ?? []) {\n if (edge.file !== null && !known.has(edge.file)) direct.add(edge.file);\n }\n }\n\n const files = new Set([\n ...entryFiles,\n ...extra,\n ...importClosure(graph, entryFiles, { skipTypeOnly: true }),\n ]);\n const everything = importClosure(graph, entryFiles);\n\n return {\n entries: entryFiles,\n direct: sortedUnique(direct),\n files: sortedUnique(files),\n typeOnlyFiles: everything.filter((file) => !files.has(file)),\n };\n}\n\n/** `auth-only.middleware.ts` → `authOnly` (the camelCase stem without the role suffix). */\nfunction middlewareNameOf(file: string): string {\n const base = (file.split(\"/\").pop() ?? file).replace(/\\.(?:d\\.ts|[cm]?[jt]sx?)$/, \"\");\n const stem = base.replace(/\\.middleware$/, \"\");\n\n return stem.replace(/[-_.]+([a-zA-Z0-9])/g, (_match, letter: string) => letter.toUpperCase());\n}\n\n/**\n * The files of the middleware a route names. A name matches a file that exports\n * it, or a `*.middleware.*` file whose stem is the name (`auth-only.middleware.ts` ↔ `authOnly`).\n * When the routes file imports some of the matches, only those count (two\n * modules may name a middleware the same). The routes file's other imports are\n * not followed: it imports every controller of its module.\n */\nfunction middlewareFiles(\n names: readonly string[],\n routesFile: string | null,\n graph: FileGraph,\n): string[] {\n const imported = new Set(\n routesFile === null\n ? []\n : (graph.get(routesFile)?.imports ?? []).flatMap((edge) =>\n edge.file === null ? [] : [edge.file],\n ),\n );\n const found: string[] = [];\n\n for (const name of names) {\n const matches: string[] = [];\n\n for (const [file, entry] of graph) {\n const exports = (entry as { exports?: readonly { name: string }[] }).exports ?? [];\n\n const byStem =\n /\\.middleware\\.(?:[cm]?[jt]sx?)$/.test(file) && middlewareNameOf(file) === name;\n\n if (exports.some((item) => item.name === name) || byStem) matches.push(file);\n }\n\n const near = matches.filter((file) => imported.has(file));\n\n found.push(...(near.length > 0 ? near : matches.length === 1 ? matches : []));\n }\n\n return found;\n}\n\nfunction routeStep(step: WrittenStep, facts: BookFacts, graph: FileGraph): StepMatch {\n if (facts.routes === null || step.route === null) return UNKNOWN;\n\n const target = step.route;\n const routes = facts.routes.filter((route) => routeMatches(route, target.method, target.path));\n const first = routes[0];\n\n if (!first) return NOTHING;\n\n const handlers = routes.flatMap((route) =>\n route.handlerFile === null ? [] : [route.handlerFile],\n );\n const sources = routes.flatMap((route) => (route.sourceFile === null ? [] : [route.sourceFile]));\n const middleware = routes.flatMap((route) =>\n middlewareFiles(route.middleware, route.sourceFile, graph),\n );\n const handlerReach = reach(graph, [...handlers, ...middleware], sources);\n // The routes files are entries too, but their own imports are not part of the step.\n const entries = sortedUnique([...handlers, ...middleware, ...sources]);\n\n return {\n found: true,\n entry: first.handlerFile ?? first.sourceFile,\n ...handlerReach,\n entries,\n direct: handlerReach.direct.filter((file) => !entries.includes(file)),\n };\n}\n\nfunction pageStep(\n step: WrittenStep,\n feature: WrittenFeature,\n facts: BookFacts,\n apps: Record<string, AppMatch>,\n graph: FileGraph,\n): StepMatch {\n const wanted = normalizeRoutePath(step.target);\n const matched: string[] = [];\n const starts: string[] = [];\n\n // `page /support [web-admin]` looks in that app only; without a scope, in the feature's apps.\n const appIds =\n step.app === null ? (feature.readme?.apps.map((app) => app.value) ?? []) : [step.app];\n\n for (const appId of appIds) {\n const match = apps[appId];\n\n if (!match) continue;\n\n if (match.site) {\n const siteId = match.site.id;\n\n for (const page of facts.pages) {\n if (page.site !== siteId || normalizeRoutePath(page.route) !== wanted) continue;\n\n matched.push(page.file);\n starts.push(page.file);\n if (page.setupFile !== null) starts.push(page.setupFile);\n }\n }\n\n if (match.mobile) {\n for (const screen of match.mobile.screens) {\n if (normalizeRoutePath(screen.route) !== wanted) continue;\n\n matched.push(screen.file);\n starts.push(screen.file);\n }\n }\n }\n\n const entry = matched[0];\n\n if (entry === undefined) return NOTHING;\n\n return { found: true, entry, ...reach(graph, starts) };\n}\n\nfunction namedStep(step: WrittenStep, facts: BookFacts, graph: FileGraph): StepMatch {\n const named = facts.named.filter(\n (thing) => thing.type === step.type && thing.name === step.target,\n );\n const first = named[0];\n\n // Mails, jobs, events and notifications come from the booted app: without route facts they were not checked.\n if (!first) return facts.routes === null ? UNKNOWN : NOTHING;\n\n const entries = named.flatMap((thing) => (thing.file === null ? [] : [thing.file]));\n\n return { found: true, entry: first.file, ...reach(graph, entries) };\n}\n\nfunction affectsStep(step: WrittenStep, written: WrittenGrimoire): StepMatch {\n const target = step.affects;\n\n if (target === null) return NOTHING;\n\n const feature = written.features.find((candidate) => candidate.id === target.feature);\n const found =\n feature !== undefined &&\n (target.flow === null || feature.flows.some((flow) => flow.id.value === target.flow));\n\n return { ...NOTHING, found };\n}\n\n/** Everything the step resolver reads. */\nexport type StepContext = {\n written: WrittenGrimoire;\n facts: BookFacts;\n apps: Record<string, AppMatch>;\n graph: FileGraph;\n};\n\n/** One step of a flow of `feature`, with what it matched in the book. */\nexport function resolveStep(\n step: WrittenStep,\n feature: WrittenFeature,\n context: StepContext,\n): FlowBookmapStep {\n let match: StepMatch;\n\n if (step.type === \"route\") match = routeStep(step, context.facts, context.graph);\n else if (step.type === \"page\")\n match = pageStep(step, feature, context.facts, context.apps, context.graph);\n else if (NAMED_TYPES.has(step.type)) match = namedStep(step, context.facts, context.graph);\n else if (step.type === \"affects\") match = affectsStep(step, context.written);\n else match = UNKNOWN;\n\n const target = step.app === null ? step.target : `${step.target} [${step.app}]`;\n\n return { index: step.index, type: step.type, target, ...match };\n}\n"],"mappings":";;;AAUA,MAAM,8BAAmC,IAAI,IAAmB;CAC9D;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,mBAAmB,OAAuB;CAKxD,MAAM,UAJa,MAChB,KAAK,CAAC,CACN,QAAQ,uBAAuB,KAAK,CAAC,CACrC,QAAQ,iBAAiB,KACH,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAE7C,OAAO,YAAY,KAAK,MAAM;AAChC;;;;;;;AAQA,SAAgB,aACd,OACA,QACA,MACS;CACT,MAAM,cAAc,MAAM,OAAO,YAAY;CAC7C,MAAM,QAAQ,OAAO,YAAY;CAGjC,QAFsB,gBAAgB,SAAS,gBAAgB,SAAS,UAAU,UAE1D,mBAAmB,MAAM,IAAI,MAAM,m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breaks the book.
17
17
  */
18
- export type BookFileType = "controller" | "service" | "repository" | "model" | "use-case" | "seed" | "request" | "mail" | "job" | "event" | "client" | "migration" | "schema" | "resource" | "hook" | "component" | "util" | "type" | "config" | "locale" | "main" | "routes" | "worker" | "page" | "setup" | "layout" | "root" | "spec" | "source" | (string & {});
18
+ export type BookFileType = "controller" | "service" | "repository" | "model" | "use-case" | "seed" | "request" | "mail" | "job" | "event" | "client" | "migration" | "schema" | "resource" | "hook" | "component" | "util" | "type" | "config" | "locale" | "main" | "routes" | "worker" | "command" | "page" | "setup" | "layout" | "root" | "spec" | "source" | (string & {});
19
19
  /** One public export of a file. */
20
20
  export type BookExport = {
21
21
  /** Export name; `default` and `*` stand for default and star exports. */
@@ -170,6 +170,25 @@ export type BookFacts = {
170
170
  /** Test files to scan for `@proves` lines (inside and outside the source roots). */
171
171
  tests: string[];
172
172
  };
173
+ /**
174
+ * The framework the book was read from, and the app it describes. The
175
+ * Grimoire view shows it in its header (framework logo and version) and at
176
+ * the bottom (the app's own name and version); an adapter that supplies no
177
+ * host shows nothing.
178
+ */
179
+ export type BookHost = {
180
+ /** Framework name (`Warlock.js`). */
181
+ name: string;
182
+ /** Installed framework version, or `null` when unknown. */
183
+ version: string | null;
184
+ /** Small logo as a `data:image/...` URI (kept inline so the static export stays one file), or `null`. */
185
+ logo: string | null;
186
+ /** The app's own name and version (its `package.json`), or `null`. */
187
+ app: {
188
+ name: string;
189
+ version: string | null;
190
+ } | null;
191
+ };
173
192
  /**
174
193
  * What a framework adapter provides. Only `files` and `sourceRoots` are
175
194
  * required; a missing method means "this framework has none of those".
@@ -210,6 +229,8 @@ export type BookAdapter = {
210
229
  named?(root: string): Promise<BookNamedThing[]>;
211
230
  /** Test files to scan for `@proves` lines. Static. */
212
231
  tests?(root: string): Promise<string[]>;
232
+ /** The framework brand and the app's own name and version, for the view's header and footer. Optional; never boots the app. */
233
+ host?(root: string): Promise<BookHost | null> | BookHost | null;
213
234
  };
214
235
  //#endregion
215
236
  //# sourceMappingURL=adapter.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/contracts/adapter.ts"],"mappings":";;;;;;;;;;;;;;;;;YAiBY;;YAiCA;;EAEV;;EAEA;;;YAIU;;EAEV;;EAEA;;;;;;EAMA;;;YAIU;EACV;;EAEA;EACA,MAAM;EACN;;EAEA;;EAEA,MAAM;EACN,SAAS;EACT,SAAS;;EAET;;EAEA;;;YAIU;;EAEV;;EAEA;EACA;;EAEA;;EAEA;;EAEA;EACA;;EAEA;;EAEA;;EAEA;IAAQ;IAAmB;;;EAE3B;EACA;;;;;;;YAQU;EACV;EACA;;EAEA;;;YAIU;EACV;;EAEA;EACA;;;YAIU;;EAEV;;EAEA;EACA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;;;EAKA,aAAa;;;YAIH;;EAEV;EACA;;EAEA;;;YAIU;;EAEV;;EAEA;;;;;;EAMA;;EAEA;EACA,SAAS;;;YAIC;;YAGA;EACV,MAAM;;EAEN;;EAEA;;;YAIU;EACV,OAAO;;EAEP,QAAQ;EACR,OAAO;EACP,OAAO;EACP,QAAQ;EACR,OAAO;;EAEP;;;;;;;;;;YAWU;;EAEV;;EAEA;;EAEA,YAAY,eAAe;;EAE3B,MAAM,eAAe,QAAQ;;EAE7B,QAAQ,eAAe,QAAQ;;;;;;EAM/B,aAAa,cAAc,gBAAgB,aAAa;;EAExD,OAAO,eAAe,QAAQ;;EAE9B,OAAO,eAAe,QAAQ;;EAE9B,QAAQ,eAAe,QAAQ;;;;;;;EAO/B,OAAO,eAAe,QAAQ;;EAE9B,OAAO,eAAe"}
1
+ {"version":3,"file":"adapter.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/contracts/adapter.ts"],"mappings":";;;;;;;;;;;;;;;;;YAiBY;;YAkCA;;EAEV;;EAEA;;;YAIU;;EAEV;;EAEA;;;;;;EAMA;;;YAIU;EACV;;EAEA;EACA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