@warlock.js/grimoire 0.0.0-stage → 5.55.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 (211) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/LICENSE +21 -0
  3. package/README.md +55 -2
  4. package/esm/apps/check-apps.mjs +207 -0
  5. package/esm/apps/check-apps.mjs.map +1 -0
  6. package/esm/apps/index.mjs +4 -0
  7. package/esm/apps/match-apps.d.mts +12 -0
  8. package/esm/apps/match-apps.d.mts.map +1 -0
  9. package/esm/apps/match-apps.mjs +30 -0
  10. package/esm/apps/match-apps.mjs.map +1 -0
  11. package/esm/book/build.d.mts +14 -0
  12. package/esm/book/build.d.mts.map +1 -0
  13. package/esm/book/build.mjs +300 -0
  14. package/esm/book/build.mjs.map +1 -0
  15. package/esm/book/index.mjs +5 -0
  16. package/esm/book/io.mjs +162 -0
  17. package/esm/book/io.mjs.map +1 -0
  18. package/esm/book/normalize.mjs +71 -0
  19. package/esm/book/normalize.mjs.map +1 -0
  20. package/esm/book/render.mjs +262 -0
  21. package/esm/book/render.mjs.map +1 -0
  22. package/esm/book/write.d.mts +12 -0
  23. package/esm/book/write.d.mts.map +1 -0
  24. package/esm/book/write.mjs +90 -0
  25. package/esm/book/write.mjs.map +1 -0
  26. package/esm/bookmap/build.d.mts +21 -0
  27. package/esm/bookmap/build.d.mts.map +1 -0
  28. package/esm/bookmap/build.mjs +272 -0
  29. package/esm/bookmap/build.mjs.map +1 -0
  30. package/esm/bookmap/index.mjs +5 -0
  31. package/esm/bookmap/steps.mjs +137 -0
  32. package/esm/bookmap/steps.mjs.map +1 -0
  33. package/esm/bookmap/write.d.mts +19 -0
  34. package/esm/bookmap/write.d.mts.map +1 -0
  35. package/esm/bookmap/write.mjs +118 -0
  36. package/esm/bookmap/write.mjs.map +1 -0
  37. package/esm/check/check-grimoire.d.mts +7 -0
  38. package/esm/check/check-grimoire.d.mts.map +1 -0
  39. package/esm/check/check-grimoire.mjs +98 -0
  40. package/esm/check/check-grimoire.mjs.map +1 -0
  41. package/esm/check/format-check-report.d.mts +20 -0
  42. package/esm/check/format-check-report.d.mts.map +1 -0
  43. package/esm/check/format-check-report.mjs +55 -0
  44. package/esm/check/format-check-report.mjs.map +1 -0
  45. package/esm/check/index.mjs +4 -0
  46. package/esm/check/rules/book-notes.mjs +18 -0
  47. package/esm/check/rules/book-notes.mjs.map +1 -0
  48. package/esm/check/rules/criteria.mjs +48 -0
  49. package/esm/check/rules/criteria.mjs.map +1 -0
  50. package/esm/check/rules/links.mjs +196 -0
  51. package/esm/check/rules/links.mjs.map +1 -0
  52. package/esm/check/rules/lookup.mjs +41 -0
  53. package/esm/check/rules/lookup.mjs.map +1 -0
  54. package/esm/check/rules/source-files.mjs +119 -0
  55. package/esm/check/rules/source-files.mjs.map +1 -0
  56. package/esm/check/rules/versions.mjs +92 -0
  57. package/esm/check/rules/versions.mjs.map +1 -0
  58. package/esm/codes/codes.d.mts +182 -0
  59. package/esm/codes/codes.d.mts.map +1 -0
  60. package/esm/codes/codes.mjs +111 -0
  61. package/esm/codes/codes.mjs.map +1 -0
  62. package/esm/codes/index.d.mts +33 -0
  63. package/esm/codes/index.d.mts.map +1 -0
  64. package/esm/codes/index.mjs +63 -0
  65. package/esm/codes/index.mjs.map +1 -0
  66. package/esm/contracts/adapter.d.mts +209 -0
  67. package/esm/contracts/adapter.d.mts.map +1 -0
  68. package/esm/contracts/book.d.mts +233 -0
  69. package/esm/contracts/book.d.mts.map +1 -0
  70. package/esm/contracts/book.mjs +7 -0
  71. package/esm/contracts/book.mjs.map +1 -0
  72. package/esm/contracts/bookmap.d.mts +175 -0
  73. package/esm/contracts/bookmap.d.mts.map +1 -0
  74. package/esm/contracts/findings.d.mts +79 -0
  75. package/esm/contracts/findings.d.mts.map +1 -0
  76. package/esm/contracts/location.d.mts +22 -0
  77. package/esm/contracts/location.d.mts.map +1 -0
  78. package/esm/contracts/releases.d.mts +53 -0
  79. package/esm/contracts/releases.d.mts.map +1 -0
  80. package/esm/contracts/scry.d.mts +143 -0
  81. package/esm/contracts/scry.d.mts.map +1 -0
  82. package/esm/contracts/snapshot.d.mts +52 -0
  83. package/esm/contracts/snapshot.d.mts.map +1 -0
  84. package/esm/contracts/test-results.d.mts +63 -0
  85. package/esm/contracts/test-results.d.mts.map +1 -0
  86. package/esm/contracts/written.d.mts +363 -0
  87. package/esm/contracts/written.d.mts.map +1 -0
  88. package/esm/contracts/written.mjs +19 -0
  89. package/esm/contracts/written.mjs.map +1 -0
  90. package/esm/devtools/data.mjs +171 -0
  91. package/esm/devtools/data.mjs.map +1 -0
  92. package/esm/devtools/graphs.mjs +142 -0
  93. package/esm/devtools/graphs.mjs.map +1 -0
  94. package/esm/devtools/index.d.mts +35 -0
  95. package/esm/devtools/index.d.mts.map +1 -0
  96. package/esm/devtools/index.mjs +102 -0
  97. package/esm/devtools/index.mjs.map +1 -0
  98. package/esm/devtools/site.d.mts +26 -0
  99. package/esm/devtools/site.d.mts.map +1 -0
  100. package/esm/devtools/site.mjs +190 -0
  101. package/esm/devtools/site.mjs.map +1 -0
  102. package/esm/devtools/snapshot-source.mjs +70 -0
  103. package/esm/devtools/snapshot-source.mjs.map +1 -0
  104. package/esm/front-matter/index.d.mts +33 -0
  105. package/esm/front-matter/index.d.mts.map +1 -0
  106. package/esm/front-matter/index.mjs +130 -0
  107. package/esm/front-matter/index.mjs.map +1 -0
  108. package/esm/graph/index.d.mts +15 -0
  109. package/esm/graph/index.d.mts.map +1 -0
  110. package/esm/graph/index.mjs +42 -0
  111. package/esm/graph/index.mjs.map +1 -0
  112. package/esm/index.d.mts +33 -0
  113. package/esm/index.mjs +33 -0
  114. package/esm/ownership/index.d.mts +8 -0
  115. package/esm/ownership/index.d.mts.map +1 -0
  116. package/esm/ownership/index.mjs +137 -0
  117. package/esm/ownership/index.mjs.map +1 -0
  118. package/esm/paths/index.d.mts +58 -0
  119. package/esm/paths/index.d.mts.map +1 -0
  120. package/esm/paths/index.mjs +137 -0
  121. package/esm/paths/index.mjs.map +1 -0
  122. package/esm/proves/index.mjs +3 -0
  123. package/esm/proves/scan-proofs.d.mts +22 -0
  124. package/esm/proves/scan-proofs.d.mts.map +1 -0
  125. package/esm/proves/scan-proofs.mjs +214 -0
  126. package/esm/proves/scan-proofs.mjs.map +1 -0
  127. package/esm/releases/index.d.mts +29 -0
  128. package/esm/releases/index.d.mts.map +1 -0
  129. package/esm/releases/index.mjs +157 -0
  130. package/esm/releases/index.mjs.map +1 -0
  131. package/esm/scry/format.d.mts +14 -0
  132. package/esm/scry/format.d.mts.map +1 -0
  133. package/esm/scry/format.mjs +193 -0
  134. package/esm/scry/format.mjs.map +1 -0
  135. package/esm/scry/index.mjs +5 -0
  136. package/esm/scry/parse.d.mts +10 -0
  137. package/esm/scry/parse.d.mts.map +1 -0
  138. package/esm/scry/parse.mjs +108 -0
  139. package/esm/scry/parse.mjs.map +1 -0
  140. package/esm/scry/query.d.mts +11 -0
  141. package/esm/scry/query.d.mts.map +1 -0
  142. package/esm/scry/query.mjs +457 -0
  143. package/esm/scry/query.mjs.map +1 -0
  144. package/esm/tasks/index.mjs +116 -0
  145. package/esm/tasks/index.mjs.map +1 -0
  146. package/esm/test-results/criterion-status.d.mts +15 -0
  147. package/esm/test-results/criterion-status.d.mts.map +1 -0
  148. package/esm/test-results/criterion-status.mjs +17 -0
  149. package/esm/test-results/criterion-status.mjs.map +1 -0
  150. package/esm/test-results/index.d.mts +8 -0
  151. package/esm/test-results/index.d.mts.map +1 -0
  152. package/esm/test-results/index.mjs +124 -0
  153. package/esm/test-results/index.mjs.map +1 -0
  154. package/esm/vitest/index.d.mts +15 -0
  155. package/esm/vitest/index.d.mts.map +1 -0
  156. package/esm/vitest/index.mjs +146 -0
  157. package/esm/vitest/index.mjs.map +1 -0
  158. package/esm/warlock/actions.mjs +265 -0
  159. package/esm/warlock/actions.mjs.map +1 -0
  160. package/esm/warlock/adapter.d.mts +28 -0
  161. package/esm/warlock/adapter.d.mts.map +1 -0
  162. package/esm/warlock/adapter.mjs +377 -0
  163. package/esm/warlock/adapter.mjs.map +1 -0
  164. package/esm/warlock/commands.d.mts +15 -0
  165. package/esm/warlock/commands.d.mts.map +1 -0
  166. package/esm/warlock/commands.mjs +199 -0
  167. package/esm/warlock/commands.mjs.map +1 -0
  168. package/esm/warlock/index.d.mts +4 -0
  169. package/esm/warlock/index.mjs +5 -0
  170. package/esm/warlock/mcp-tools.mjs +247 -0
  171. package/esm/warlock/mcp-tools.mjs.map +1 -0
  172. package/esm/warlock/mobile-facts.d.mts +32 -0
  173. package/esm/warlock/mobile-facts.d.mts.map +1 -0
  174. package/esm/warlock/mobile-facts.mjs +185 -0
  175. package/esm/warlock/mobile-facts.mjs.map +1 -0
  176. package/esm/workspace/index.d.mts +11 -0
  177. package/esm/workspace/index.d.mts.map +1 -0
  178. package/esm/workspace/index.mjs +122 -0
  179. package/esm/workspace/index.mjs.map +1 -0
  180. package/esm/written/apps.mjs +227 -0
  181. package/esm/written/apps.mjs.map +1 -0
  182. package/esm/written/features.mjs +400 -0
  183. package/esm/written/features.mjs.map +1 -0
  184. package/esm/written/fields.mjs +173 -0
  185. package/esm/written/fields.mjs.map +1 -0
  186. package/esm/written/index.mjs +3 -0
  187. package/esm/written/lists.mjs +68 -0
  188. package/esm/written/lists.mjs.map +1 -0
  189. package/esm/written/markdown.mjs +173 -0
  190. package/esm/written/markdown.mjs.map +1 -0
  191. package/esm/written/parse-grimoire.d.mts +20 -0
  192. package/esm/written/parse-grimoire.d.mts.map +1 -0
  193. package/esm/written/parse-grimoire.mjs +552 -0
  194. package/esm/written/parse-grimoire.mjs.map +1 -0
  195. package/esm/written/sink.mjs +65 -0
  196. package/esm/written/sink.mjs.map +1 -0
  197. package/esm/written/tasks-releases.mjs +166 -0
  198. package/esm/written/tasks-releases.mjs.map +1 -0
  199. package/llms-full.txt +869 -0
  200. package/llms.txt +15 -0
  201. package/package.json +66 -4
  202. package/skills/backfill-a-grimoire/SKILL.md +128 -0
  203. package/skills/describe-an-app/SKILL.md +162 -0
  204. package/skills/document-a-file/SKILL.md +75 -0
  205. package/skills/index.md +26 -0
  206. package/skills/record-a-change/SKILL.md +139 -0
  207. package/skills/use-the-grimoire/SKILL.md +137 -0
  208. package/skills/write-a-feature/SKILL.md +168 -0
  209. package/ui/grimoire-static.js +136 -0
  210. package/ui/grimoire-view.js +1005 -0
  211. package/ui/grimoire.css +88 -0
@@ -0,0 +1,262 @@
1
+ import { BOOK_SCHEMA_VERSION } from "../contracts/book.mjs";
2
+ import { GRIMOIRE_PATHS, bookEntryPaths, isInsideFolder, mobileScreensPath, moduleSummaryPath, sitePagesPath } from "../paths/index.mjs";
3
+ import { packageNameOf } from "../graph/index.mjs";
4
+ import { isInsideBook, toJson } from "./io.mjs";
5
+ import { isBuiltin } from "node:module";
6
+ import path from "node:path";
7
+
8
+ //#region ../../packages/grimoire/src/book/render.ts
9
+ /**
10
+ * Turns facts and annotations into the content of every book file: the
11
+ * per-file entries, the module summaries, `app/routes.json` and the page and
12
+ * screen lists. Pure: no IO, so a spec can build inputs by hand.
13
+ */
14
+ /** Key of `BookRoutesFile.modules` for routes with no routes file. */
15
+ const NO_MODULE = "(none)";
16
+ const byText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
17
+ /**
18
+ * Book entry path of every code file in the facts. A file whose mirror would
19
+ * leave `grimoire/book/` (a path with `..`) has no entry.
20
+ */
21
+ function entryPathsFor(facts) {
22
+ const mobileRoots = new Map(facts.mobile.map((app) => [app.id, app.root]));
23
+ const paths = bookEntryPaths(facts.files.map((file) => {
24
+ const mobileRoot = file.mobileApp === null ? void 0 : mobileRoots.get(file.mobileApp);
25
+ return {
26
+ file: file.file,
27
+ mobileApp: file.mobileApp === null || mobileRoot === void 0 ? null : {
28
+ id: file.mobileApp,
29
+ root: mobileRoot
30
+ }
31
+ };
32
+ }));
33
+ for (const [file, entry] of paths) if (!isInsideBook(entry)) paths.delete(file);
34
+ return paths;
35
+ }
36
+ function routeRef(route) {
37
+ return {
38
+ method: route.method,
39
+ path: route.path,
40
+ name: route.name
41
+ };
42
+ }
43
+ /** External package names a file imports: sorted, unique, Node builtins left out. */
44
+ function packagesOf(file) {
45
+ const names = /* @__PURE__ */ new Set();
46
+ for (const entry of file.imports) {
47
+ if (entry.file !== null) continue;
48
+ const name = packageNameOf(entry.specifier);
49
+ if (name !== null && !isBuiltin(name)) names.add(name);
50
+ }
51
+ return [...names].sort(byText);
52
+ }
53
+ /** Lists indexed by a key, built once so lookups per file stay constant time. */
54
+ function groupBy(items) {
55
+ const groups = /* @__PURE__ */ new Map();
56
+ for (const [key, item] of items) {
57
+ if (key === null) continue;
58
+ const group = groups.get(key);
59
+ if (group) group.push(item);
60
+ else groups.set(key, [item]);
61
+ }
62
+ return groups;
63
+ }
64
+ const NO_ANNOTATION = {
65
+ feature: null,
66
+ borrowedBy: [],
67
+ flows: []
68
+ };
69
+ /** The entry of every code file, by source file. */
70
+ function buildEntries(facts, annotations) {
71
+ const routes = facts.routes ?? [];
72
+ const registered = groupBy(routes.map((route) => [route.sourceFile, route]));
73
+ const handled = groupBy(routes.map((route) => [route.handlerFile, route]));
74
+ const pages = groupBy(facts.pages.flatMap((page) => [
75
+ [page.file, {
76
+ site: page.site,
77
+ route: page.route,
78
+ via: "page"
79
+ }],
80
+ [page.setupFile, {
81
+ site: page.site,
82
+ route: page.route,
83
+ via: "setup"
84
+ }],
85
+ ...page.layouts.map((layout) => [layout, {
86
+ site: page.site,
87
+ route: page.route,
88
+ via: "layout"
89
+ }])
90
+ ]));
91
+ const screens = groupBy(facts.mobile.flatMap((app) => app.screens.flatMap((screen) => [[screen.file, {
92
+ app: app.id,
93
+ route: screen.route,
94
+ via: "screen"
95
+ }], ...screen.layouts.map((layout) => [layout, {
96
+ app: app.id,
97
+ route: screen.route,
98
+ via: "layout"
99
+ }])])));
100
+ const entries = /* @__PURE__ */ new Map();
101
+ for (const file of facts.files) {
102
+ const annotation = annotations.files[file.file] ?? NO_ANNOTATION;
103
+ const fileRoutes = [...(registered.get(file.file) ?? []).map((route) => ({
104
+ ...routeRef(route),
105
+ via: "registers"
106
+ })), ...(handled.get(file.file) ?? []).map((route) => ({
107
+ ...routeRef(route),
108
+ via: "handles"
109
+ }))];
110
+ entries.set(file.file, {
111
+ schemaVersion: 1,
112
+ file: file.file,
113
+ module: file.module,
114
+ type: file.type,
115
+ lines: file.lines,
116
+ about: file.about,
117
+ feature: annotation.feature,
118
+ borrowedBy: [...new Set(annotation.borrowedBy)].sort(byText),
119
+ flows: [...new Set(annotation.flows)].sort(byText),
120
+ exports: file.exports.map((entry) => ({
121
+ name: entry.name,
122
+ about: entry.about
123
+ })),
124
+ packages: packagesOf(file),
125
+ imports: [...new Set(file.imports.flatMap((entry) => entry.file === null ? [] : [entry.file]))].sort(byText),
126
+ importedBy: [...new Set(file.importedBy)].sort(byText),
127
+ routes: fileRoutes,
128
+ pages: (pages.get(file.file) ?? []).sort((left, right) => byText(left.site, right.site) || byText(left.route, right.route) || byText(left.via, right.via)),
129
+ screens: (screens.get(file.file) ?? []).sort((left, right) => byText(left.app, right.app) || byText(left.route, right.route) || byText(left.via, right.via))
130
+ });
131
+ }
132
+ return entries;
133
+ }
134
+ /** `app/routes.json`: routes grouped by the module of their routes file, in registration order. */
135
+ function buildRoutesFile(facts) {
136
+ if (facts.routes === null) return null;
137
+ const moduleOf = new Map(facts.files.map((file) => [file.file, file.module]));
138
+ const grouped = groupBy(facts.routes.map((route) => [route.sourceFile === null ? NO_MODULE : moduleOf.get(route.sourceFile) ?? "(none)", {
139
+ ...routeRef(route),
140
+ handlerFile: route.handlerFile
141
+ }]));
142
+ return {
143
+ schemaVersion: 1,
144
+ modules: Object.fromEntries([...grouped].sort(([left], [right]) => byText(left, right)))
145
+ };
146
+ }
147
+ /** One `BookModuleSummary` per `module` value of the code files, sorted by module. */
148
+ function buildModuleSummaries(facts, annotations) {
149
+ const moduleOf = new Map(facts.files.map((file) => [file.file, file.module]));
150
+ const byModule = groupBy(facts.files.map((file) => [file.module, file]));
151
+ const routesByModule = groupBy((facts.routes ?? []).map((route) => {
152
+ const home = route.sourceFile ?? route.handlerFile;
153
+ return [home === null ? null : moduleOf.get(home) ?? null, routeRef(route)];
154
+ }));
155
+ const summaries = [];
156
+ for (const [module, files] of [...byModule].sort(([left], [right]) => byText(left, right))) {
157
+ const featureCounts = /* @__PURE__ */ new Map();
158
+ const importers = /* @__PURE__ */ new Map();
159
+ for (const file of files) {
160
+ const feature = annotations.files[file.file]?.feature ?? null;
161
+ if (feature !== null) featureCounts.set(feature, (featureCounts.get(feature) ?? 0) + 1);
162
+ for (const importer of file.importedBy) {
163
+ const importerModule = moduleOf.get(importer);
164
+ if (importerModule === void 0 || importerModule === module) continue;
165
+ const set = importers.get(importerModule) ?? /* @__PURE__ */ new Set();
166
+ set.add(importer);
167
+ importers.set(importerModule, set);
168
+ }
169
+ }
170
+ summaries.push({
171
+ module,
172
+ features: [...featureCounts].sort(([leftName, left], [rightName, right]) => right - left || byText(leftName, rightName)).map(([feature]) => feature),
173
+ files: files.map((file) => ({
174
+ file: file.file,
175
+ type: file.type,
176
+ lines: file.lines,
177
+ about: file.about
178
+ })).sort((left, right) => byText(left.file, right.file)),
179
+ routes: routesByModule.get(module) ?? [],
180
+ usedBy: [...importers].map(([importer, set]) => ({
181
+ module: importer,
182
+ files: set.size
183
+ })).sort((left, right) => right.files - left.files || byText(left.module, right.module))
184
+ });
185
+ }
186
+ return summaries;
187
+ }
188
+ const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
189
+ /** The Markdown of one module summary (format in `BookModuleSummary`). */
190
+ function renderModuleSummary(summary) {
191
+ const lines = summary.files.reduce((total, file) => total + file.lines, 0);
192
+ const counts = `${plural(summary.files.length, "file")}, ${plural(lines, "line")}.`;
193
+ const features = summary.features.length === 0 ? "" : `${summary.features.length === 1 ? "Feature" : "Features"}: ${summary.features.join(", ")}. `;
194
+ const out = [
195
+ `# ${summary.module}`,
196
+ "",
197
+ `${features}${counts}`
198
+ ];
199
+ if (summary.files.length > 0) {
200
+ out.push("", "## Files");
201
+ for (const file of summary.files) {
202
+ const relative = isInsideFolder(file.file, summary.module) ? path.posix.relative(summary.module, file.file) : file.file;
203
+ out.push(`- ${[
204
+ relative,
205
+ file.type,
206
+ ...file.about === null ? [] : [file.about]
207
+ ].join(" ")}`);
208
+ }
209
+ }
210
+ if (summary.routes.length > 0) {
211
+ out.push("", "## Routes");
212
+ for (const route of summary.routes) out.push(`- ${route.method} ${route.path}`);
213
+ }
214
+ if (summary.usedBy.length > 0) {
215
+ out.push("", "## Used by");
216
+ for (const user of summary.usedBy) out.push(`- ${user.module} (${plural(user.files, "file")})`);
217
+ }
218
+ return `${out.join("\n")}\n`;
219
+ }
220
+ /**
221
+ * The content of every book file Warlock writes from the facts and the
222
+ * annotations, by project-relative path. `manifest.json`, `.cache/` and
223
+ * `test-results.json` are not part of it.
224
+ */
225
+ function renderBook(facts, annotations) {
226
+ const contents = /* @__PURE__ */ new Map();
227
+ const entries = buildEntries(facts, annotations);
228
+ for (const [file, entryPath] of entryPathsFor(facts)) {
229
+ const entry = entries.get(file);
230
+ if (entry !== void 0) contents.set(entryPath, toJson(entry));
231
+ }
232
+ for (const summary of buildModuleSummaries(facts, annotations)) {
233
+ const summaryPath = moduleSummaryPath(summary.module);
234
+ if (isInsideBook(summaryPath)) contents.set(summaryPath, renderModuleSummary(summary));
235
+ }
236
+ const routesFile = buildRoutesFile(facts);
237
+ if (routesFile !== null) contents.set(GRIMOIRE_PATHS.bookRoutes, toJson(routesFile));
238
+ for (const site of facts.sites) {
239
+ const sitePath = sitePagesPath(site.id);
240
+ const file = {
241
+ schemaVersion: 1,
242
+ site,
243
+ pages: facts.pages.filter((page) => page.site === site.id)
244
+ };
245
+ if (isInsideBook(sitePath)) contents.set(sitePath, toJson(file));
246
+ }
247
+ for (const app of facts.mobile) {
248
+ const screensPath = mobileScreensPath(app.id);
249
+ const { screens, ...rest } = app;
250
+ const file = {
251
+ schemaVersion: 1,
252
+ app: rest,
253
+ screens
254
+ };
255
+ if (isInsideBook(screensPath)) contents.set(screensPath, toJson(file));
256
+ }
257
+ return contents;
258
+ }
259
+
260
+ //#endregion
261
+ export { NO_MODULE, buildEntries, buildModuleSummaries, buildRoutesFile, entryPathsFor, packagesOf, renderBook, renderModuleSummary };
262
+ //# sourceMappingURL=render.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/render.ts"],"sourcesContent":["/**\n * Turns facts and annotations into the content of every book file: the\n * per-file entries, the module summaries, `app/routes.json` and the page and\n * screen lists. Pure: no IO, so a spec can build inputs by hand.\n */\nimport { isBuiltin } from \"node:module\";\nimport path from \"node:path\";\nimport type { BookFacts, BookFile, BookRoute } from \"../contracts/adapter\";\nimport {\n BOOK_SCHEMA_VERSION,\n type BookAnnotations,\n type BookEntry,\n type BookMobileScreensFile,\n type BookModuleSummary,\n type BookRouteRef,\n type BookRoutesFile,\n type BookSitePagesFile,\n} from \"../contracts/book\";\nimport { packageNameOf } from \"../graph\";\nimport {\n bookEntryPaths,\n GRIMOIRE_PATHS,\n isInsideFolder,\n mobileScreensPath,\n moduleSummaryPath,\n sitePagesPath,\n} from \"../paths\";\nimport { isInsideBook, toJson } from \"./io\";\n\n/** Key of `BookRoutesFile.modules` for routes with no routes file. */\nexport const NO_MODULE = \"(none)\";\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\n\n/**\n * Book entry path of every code file in the facts. A file whose mirror would\n * leave `grimoire/book/` (a path with `..`) has no entry.\n */\nexport function entryPathsFor(facts: Pick<BookFacts, \"files\" | \"mobile\">): Map<string, string> {\n const mobileRoots = new Map(facts.mobile.map((app) => [app.id, app.root]));\n const paths = bookEntryPaths(\n facts.files.map((file) => {\n const mobileRoot = file.mobileApp === null ? undefined : mobileRoots.get(file.mobileApp);\n\n return {\n file: file.file,\n mobileApp:\n file.mobileApp === null || mobileRoot === undefined\n ? null\n : { id: file.mobileApp, root: mobileRoot },\n };\n }),\n );\n\n for (const [file, entry] of paths) {\n if (!isInsideBook(entry)) paths.delete(file);\n }\n\n return paths;\n}\n\nfunction routeRef(route: BookRoute): BookRouteRef {\n return { method: route.method, path: route.path, name: route.name };\n}\n\n/** External package names a file imports: sorted, unique, Node builtins left out. */\nexport function packagesOf(file: BookFile): string[] {\n const names = new Set<string>();\n\n for (const entry of file.imports) {\n if (entry.file !== null) continue;\n\n const name = packageNameOf(entry.specifier);\n\n if (name !== null && !isBuiltin(name)) names.add(name);\n }\n\n return [...names].sort(byText);\n}\n\n/** Lists indexed by a key, built once so lookups per file stay constant time. */\nfunction groupBy<T>(items: Iterable<readonly [string | null, T]>): Map<string, T[]> {\n const groups = new Map<string, T[]>();\n\n for (const [key, item] of items) {\n if (key === null) continue;\n\n const group = groups.get(key);\n\n if (group) group.push(item);\n else groups.set(key, [item]);\n }\n\n return groups;\n}\n\ntype PageUse = {\n readonly site: string;\n readonly route: string;\n readonly via: \"page\" | \"setup\" | \"layout\";\n};\ntype ScreenUse = {\n readonly app: string;\n readonly route: string;\n readonly via: \"screen\" | \"layout\";\n};\n\nconst NO_ANNOTATION = { feature: null, borrowedBy: [], flows: [] } as const;\n\n/** The entry of every code file, by source file. */\nexport function buildEntries(\n facts: BookFacts,\n annotations: BookAnnotations,\n): Map<string, BookEntry> {\n const routes = facts.routes ?? [];\n const registered = groupBy(routes.map((route) => [route.sourceFile, route] as const));\n const handled = groupBy(routes.map((route) => [route.handlerFile, route] as const));\n const pages = groupBy<PageUse>(\n facts.pages.flatMap((page): (readonly [string | null, PageUse])[] => [\n [page.file, { site: page.site, route: page.route, via: \"page\" as const }] as const,\n [page.setupFile, { site: page.site, route: page.route, via: \"setup\" as const }] as const,\n ...page.layouts.map(\n (layout) =>\n [layout, { site: page.site, route: page.route, via: \"layout\" as const }] as const,\n ),\n ]),\n );\n const screens = groupBy<ScreenUse>(\n facts.mobile.flatMap((app) =>\n app.screens.flatMap((screen): (readonly [string | null, ScreenUse])[] => [\n [screen.file, { app: app.id, route: screen.route, via: \"screen\" as const }] as const,\n ...screen.layouts.map(\n (layout) =>\n [layout, { app: app.id, route: screen.route, via: \"layout\" as const }] as const,\n ),\n ]),\n ),\n );\n const entries = new Map<string, BookEntry>();\n\n for (const file of facts.files) {\n const annotation = annotations.files[file.file] ?? NO_ANNOTATION;\n const fileRoutes: BookEntry[\"routes\"] = [\n ...(registered.get(file.file) ?? []).map((route) => ({\n ...routeRef(route),\n via: \"registers\" as const,\n })),\n ...(handled.get(file.file) ?? []).map((route) => ({\n ...routeRef(route),\n via: \"handles\" as const,\n })),\n ];\n\n entries.set(file.file, {\n schemaVersion: BOOK_SCHEMA_VERSION,\n file: file.file,\n module: file.module,\n type: file.type,\n lines: file.lines,\n about: file.about,\n feature: annotation.feature,\n borrowedBy: [...new Set(annotation.borrowedBy)].sort(byText),\n flows: [...new Set(annotation.flows)].sort(byText),\n exports: file.exports.map((entry) => ({ name: entry.name, about: entry.about })),\n packages: packagesOf(file),\n imports: [\n ...new Set(file.imports.flatMap((entry) => (entry.file === null ? [] : [entry.file]))),\n ].sort(byText),\n importedBy: [...new Set(file.importedBy)].sort(byText),\n routes: fileRoutes,\n pages: (pages.get(file.file) ?? []).sort(\n (left, right) =>\n byText(left.site, right.site) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n screens: (screens.get(file.file) ?? []).sort(\n (left, right) =>\n byText(left.app, right.app) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n });\n }\n\n return entries;\n}\n\n/** `app/routes.json`: routes grouped by the module of their routes file, in registration order. */\nexport function buildRoutesFile(facts: BookFacts): BookRoutesFile | null {\n if (facts.routes === null) return null;\n\n const moduleOf = new Map(facts.files.map((file) => [file.file, file.module]));\n const grouped = groupBy(\n facts.routes.map(\n (route) =>\n [\n route.sourceFile === null ? NO_MODULE : (moduleOf.get(route.sourceFile) ?? NO_MODULE),\n { ...routeRef(route), handlerFile: route.handlerFile },\n ] as const,\n ),\n );\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n modules: Object.fromEntries([...grouped].sort(([left], [right]) => byText(left, right))),\n };\n}\n\n/** One `BookModuleSummary` per `module` value of the code files, sorted by module. */\nexport function buildModuleSummaries(\n facts: BookFacts,\n annotations: BookAnnotations,\n): BookModuleSummary[] {\n const moduleOf = new Map(facts.files.map((file) => [file.file, file.module]));\n const byModule = groupBy(facts.files.map((file) => [file.module, file] as const));\n const routesByModule = groupBy(\n (facts.routes ?? []).map((route) => {\n const home = route.sourceFile ?? route.handlerFile;\n\n return [home === null ? null : (moduleOf.get(home) ?? null), routeRef(route)] as const;\n }),\n );\n const summaries: BookModuleSummary[] = [];\n\n for (const [module, files] of [...byModule].sort(([left], [right]) => byText(left, right))) {\n const featureCounts = new Map<string, number>();\n const importers = new Map<string, Set<string>>();\n\n for (const file of files) {\n const feature = annotations.files[file.file]?.feature ?? null;\n\n if (feature !== null) featureCounts.set(feature, (featureCounts.get(feature) ?? 0) + 1);\n\n for (const importer of file.importedBy) {\n const importerModule = moduleOf.get(importer);\n\n if (importerModule === undefined || importerModule === module) continue;\n\n const set = importers.get(importerModule) ?? new Set<string>();\n set.add(importer);\n importers.set(importerModule, set);\n }\n }\n\n summaries.push({\n module,\n features: [...featureCounts]\n .sort(([leftName, left], [rightName, right]) => right - left || byText(leftName, rightName))\n .map(([feature]) => feature),\n files: files\n .map((file) => ({ file: file.file, type: file.type, lines: file.lines, about: file.about }))\n .sort((left, right) => byText(left.file, right.file)),\n routes: routesByModule.get(module) ?? [],\n usedBy: [...importers]\n .map(([importer, set]) => ({ module: importer, files: set.size }))\n .sort((left, right) => right.files - left.files || byText(left.module, right.module)),\n });\n }\n\n return summaries;\n}\n\nconst plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n\n/** The Markdown of one module summary (format in `BookModuleSummary`). */\nexport function renderModuleSummary(summary: BookModuleSummary): string {\n const lines = summary.files.reduce((total, file) => total + file.lines, 0);\n const counts = `${plural(summary.files.length, \"file\")}, ${plural(lines, \"line\")}.`;\n const features =\n summary.features.length === 0\n ? \"\"\n : `${summary.features.length === 1 ? \"Feature\" : \"Features\"}: ${summary.features.join(\", \")}. `;\n const out = [`# ${summary.module}`, \"\", `${features}${counts}`];\n\n if (summary.files.length > 0) {\n out.push(\"\", \"## Files\");\n\n for (const file of summary.files) {\n const relative = isInsideFolder(file.file, summary.module)\n ? path.posix.relative(summary.module, file.file)\n : file.file;\n\n out.push(\n `- ${[relative, file.type, ...(file.about === null ? [] : [file.about])].join(\" \")}`,\n );\n }\n }\n\n if (summary.routes.length > 0) {\n out.push(\"\", \"## Routes\");\n\n for (const route of summary.routes) out.push(`- ${route.method} ${route.path}`);\n }\n\n if (summary.usedBy.length > 0) {\n out.push(\"\", \"## Used by\");\n\n for (const user of summary.usedBy) out.push(`- ${user.module} (${plural(user.files, \"file\")})`);\n }\n\n return `${out.join(\"\\n\")}\\n`;\n}\n\n/**\n * The content of every book file Warlock writes from the facts and the\n * annotations, by project-relative path. `manifest.json`, `.cache/` and\n * `test-results.json` are not part of it.\n */\nexport function renderBook(facts: BookFacts, annotations: BookAnnotations): Map<string, string> {\n const contents = new Map<string, string>();\n const entries = buildEntries(facts, annotations);\n\n for (const [file, entryPath] of entryPathsFor(facts)) {\n const entry = entries.get(file);\n\n if (entry !== undefined) contents.set(entryPath, toJson(entry));\n }\n\n for (const summary of buildModuleSummaries(facts, annotations)) {\n const summaryPath = moduleSummaryPath(summary.module);\n\n if (isInsideBook(summaryPath)) contents.set(summaryPath, renderModuleSummary(summary));\n }\n\n const routesFile = buildRoutesFile(facts);\n\n if (routesFile !== null) contents.set(GRIMOIRE_PATHS.bookRoutes, toJson(routesFile));\n\n for (const site of facts.sites) {\n const sitePath = sitePagesPath(site.id);\n const file: BookSitePagesFile = {\n schemaVersion: BOOK_SCHEMA_VERSION,\n site,\n pages: facts.pages.filter((page) => page.site === site.id),\n };\n\n if (isInsideBook(sitePath)) contents.set(sitePath, toJson(file));\n }\n\n for (const app of facts.mobile) {\n const screensPath = mobileScreensPath(app.id);\n const { screens, ...rest } = app;\n const file: BookMobileScreensFile = { schemaVersion: BOOK_SCHEMA_VERSION, app: rest, screens };\n\n if (isInsideBook(screensPath)) contents.set(screensPath, toJson(file));\n }\n\n return contents;\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAa,YAAY;AAEzB,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;;;;;AAMhG,SAAgB,cAAc,OAAiE;CAC7F,MAAM,cAAc,IAAI,IAAI,MAAM,OAAO,KAAK,QAAQ,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC;CACzE,MAAM,QAAQ,eACZ,MAAM,MAAM,KAAK,SAAS;EACxB,MAAM,aAAa,KAAK,cAAc,OAAO,SAAY,YAAY,IAAI,KAAK,SAAS;EAEvF,OAAO;GACL,MAAM,KAAK;GACX,WACE,KAAK,cAAc,QAAQ,eAAe,SACtC,OACA;IAAE,IAAI,KAAK;IAAW,MAAM;GAAW;EAC/C;CACF,CAAC,CACH;CAEA,KAAK,MAAM,CAAC,MAAM,UAAU,OAC1B,IAAI,CAAC,aAAa,KAAK,GAAG,MAAM,OAAO,IAAI;CAG7C,OAAO;AACT;AAEA,SAAS,SAAS,OAAgC;CAChD,OAAO;EAAE,QAAQ,MAAM;EAAQ,MAAM,MAAM;EAAM,MAAM,MAAM;CAAK;AACpE;;AAGA,SAAgB,WAAW,MAA0B;CACnD,MAAM,wBAAQ,IAAI,IAAY;CAE9B,KAAK,MAAM,SAAS,KAAK,SAAS;EAChC,IAAI,MAAM,SAAS,MAAM;EAEzB,MAAM,OAAO,cAAc,MAAM,SAAS;EAE1C,IAAI,SAAS,QAAQ,CAAC,UAAU,IAAI,GAAG,MAAM,IAAI,IAAI;CACvD;CAEA,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK,MAAM;AAC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,UAAU,aAAa,OAAO,WAAW;CAE/C,KAAK,MAAM,CAAC,MAAM,cAAc,cAAc,KAAK,GAAG;EACpD,MAAM,QAAQ,QAAQ,IAAI,IAAI;EAE9B,IAAI,UAAU,QAAW,SAAS,IAAI,WAAW,OAAO,KAAK,CAAC;CAChE;CAEA,KAAK,MAAM,WAAW,qBAAqB,OAAO,WAAW,GAAG;EAC9D,MAAM,cAAc,kBAAkB,QAAQ,MAAM;EAEpD,IAAI,aAAa,WAAW,GAAG,SAAS,IAAI,aAAa,oBAAoB,OAAO,CAAC;CACvF;CAEA,MAAM,aAAa,gBAAgB,KAAK;CAExC,IAAI,eAAe,MAAM,SAAS,IAAI,eAAe,YAAY,OAAO,UAAU,CAAC;CAEnF,KAAK,MAAM,QAAQ,MAAM,OAAO;EAC9B,MAAM,WAAW,cAAc,KAAK,EAAE;EACtC,MAAM,OAA0B;GAC9B;GACA;GACA,OAAO,MAAM,MAAM,QAAQ,SAAS,KAAK,SAAS,KAAK,EAAE;EAC3D;EAEA,IAAI,aAAa,QAAQ,GAAG,SAAS,IAAI,UAAU,OAAO,IAAI,CAAC;CACjE;CAEA,KAAK,MAAM,OAAO,MAAM,QAAQ;EAC9B,MAAM,cAAc,kBAAkB,IAAI,EAAE;EAC5C,MAAM,EAAE,SAAS,GAAG,SAAS;EAC7B,MAAM,OAA8B;GAAE;GAAoC,KAAK;GAAM;EAAQ;EAE7F,IAAI,aAAa,WAAW,GAAG,SAAS,IAAI,aAAa,OAAO,IAAI,CAAC;CACvE;CAEA,OAAO;AACT"}
@@ -0,0 +1,12 @@
1
+ import { BookAnnotations, LoadedBook, WriteBookResult } from "../contracts/book.mjs";
2
+ //#region ../../packages/grimoire/src/book/write.d.ts
3
+ /**
4
+ * Write the book files that depend on the written files too: one entry per
5
+ * code file, `index.md` per module, `app/routes.json`, the page and screen
6
+ * lists. Rewrites only files whose content changed, removes entries whose
7
+ * source is gone, and stores `annotations.writtenHash` and `tests` in the
8
+ * manifest (`book.manifest` is updated in place).
9
+ */
10
+ export declare function writeBook(book: LoadedBook, annotations: BookAnnotations): Promise<WriteBookResult>;
11
+ //#endregion
12
+ //# sourceMappingURL=write.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/write.ts"],"mappings":";;;;;;;;;wBAuEsB,UACpB,MAAM,YACN,aAAa,kBACZ,QAAQ"}
@@ -0,0 +1,90 @@
1
+ import { BOOK_SCHEMA_VERSION } from "../contracts/book.mjs";
2
+ import { GRIMOIRE_PATHS } from "../paths/index.mjs";
3
+ import { bookFile, hashText, isInsideBook, listBookFiles, mapLimit, readJson, removeBookFile, toJson, writeBookFile } from "./io.mjs";
4
+ import { renderBook } from "./render.mjs";
5
+ import { WRITE_STATE_PATH, grimoireVersion } from "./build.mjs";
6
+ import path from "node:path";
7
+ import { readFile } from "node:fs/promises";
8
+
9
+ //#region ../../packages/grimoire/src/book/write.ts
10
+ /**
11
+ * `writeBook`: writes the entries, module summaries, `app/routes.json` and
12
+ * the page and screen lists, touching only files whose content changed.
13
+ *
14
+ * It remembers what it wrote in `.cache/written.json` (a hash per book file
15
+ * and a stamp of its inputs), so a run with the same facts and annotations
16
+ * returns at once without reading or writing any book file, and a run after a
17
+ * change compares hashes in memory instead of reading every entry back.
18
+ */
19
+ /** Book files `writeBook` never removes. */
20
+ function isKept(bookPath) {
21
+ return bookPath === GRIMOIRE_PATHS.bookManifest || bookPath === GRIMOIRE_PATHS.testResults || bookPath.startsWith(`${GRIMOIRE_PATHS.book}/.cache/`) || bookPath.startsWith(`${GRIMOIRE_PATHS.staticSite}/`);
22
+ }
23
+ /** Whether a book file not listed in a write state looks like one `writeBook` wrote. */
24
+ const isGenerated = (bookPath) => /\.(?:json|md)$/.test(bookPath) && !isKept(bookPath);
25
+ async function readDiskText(root, bookPath) {
26
+ try {
27
+ return await readFile(bookFile(root, bookPath), "utf8");
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+ /**
33
+ * Write the book files that depend on the written files too: one entry per
34
+ * code file, `index.md` per module, `app/routes.json`, the page and screen
35
+ * lists. Rewrites only files whose content changed, removes entries whose
36
+ * source is gone, and stores `annotations.writtenHash` and `tests` in the
37
+ * manifest (`book.manifest` is updated in place).
38
+ */
39
+ async function writeBook(book, annotations) {
40
+ const root = book.root;
41
+ const statePath = path.join(root, ...WRITE_STATE_PATH.split("/"));
42
+ const previous = await readJson(statePath);
43
+ const state = previous?.schemaVersion === 1 && typeof previous.files === "object" ? previous : null;
44
+ const stamp = hashText(JSON.stringify([
45
+ grimoireVersion(),
46
+ 1,
47
+ book.facts,
48
+ annotations.files
49
+ ]));
50
+ const written = [];
51
+ const removed = [];
52
+ if (state === null || state.stamp !== stamp) {
53
+ const contents = renderBook(book.facts, annotations);
54
+ const hashes = new Map([...contents].map(([bookPath, content]) => [bookPath, hashText(content)]));
55
+ const changed = await mapLimit([...contents.keys()].sort(), 32, async (bookPath) => {
56
+ const content = contents.get(bookPath) ?? "";
57
+ if (state !== null) {
58
+ if (state.files[bookPath] === hashes.get(bookPath)) return null;
59
+ } else if (await readDiskText(root, bookPath) === content) return null;
60
+ await writeBookFile(root, bookPath, content);
61
+ return bookPath;
62
+ });
63
+ for (const bookPath of changed) if (bookPath !== null) written.push(bookPath);
64
+ const gone = (state === null ? (await listBookFiles(root)).filter(isGenerated) : Object.keys(state.files)).filter((bookPath) => isInsideBook(bookPath) && !contents.has(bookPath) && !isKept(bookPath)).sort();
65
+ await mapLimit(gone, 32, async (bookPath) => removeBookFile(root, bookPath));
66
+ removed.push(...gone);
67
+ const next = {
68
+ schemaVersion: 1,
69
+ stamp,
70
+ files: Object.fromEntries([...hashes].sort(([left], [right]) => left < right ? -1 : 1))
71
+ };
72
+ await writeBookFile(root, WRITE_STATE_PATH, toJson(next));
73
+ }
74
+ const manifest = book.manifest;
75
+ const sameTests = Object.keys(manifest.tests).length === Object.keys(annotations.tests).length && Object.entries(annotations.tests).every(([file, hash]) => manifest.tests[file] === hash);
76
+ if (manifest.writtenHash !== annotations.writtenHash || !sameTests || written.length > 0 || removed.length > 0) {
77
+ manifest.writtenHash = annotations.writtenHash;
78
+ manifest.tests = { ...annotations.tests };
79
+ if (written.length > 0 || removed.length > 0) manifest.builtAt = (/* @__PURE__ */ new Date()).toISOString();
80
+ await writeBookFile(root, GRIMOIRE_PATHS.bookManifest, toJson(manifest));
81
+ }
82
+ return {
83
+ written,
84
+ removed
85
+ };
86
+ }
87
+
88
+ //#endregion
89
+ export { writeBook };
90
+ //# sourceMappingURL=write.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/book/write.ts"],"sourcesContent":["/**\n * `writeBook`: writes the entries, module summaries, `app/routes.json` and\n * the page and screen lists, touching only files whose content changed.\n *\n * It remembers what it wrote in `.cache/written.json` (a hash per book file\n * and a stamp of its inputs), so a run with the same facts and annotations\n * returns at once without reading or writing any book file, and a run after a\n * change compares hashes in memory instead of reading every entry back.\n */\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n BOOK_SCHEMA_VERSION,\n type BookAnnotations,\n type LoadedBook,\n type WriteBookResult,\n} from \"../contracts/book\";\nimport { GRIMOIRE_PATHS } from \"../paths\";\nimport { grimoireVersion, WRITE_STATE_PATH } from \"./build\";\nimport {\n bookFile,\n hashText,\n isInsideBook,\n IO_CONCURRENCY,\n listBookFiles,\n mapLimit,\n readJson,\n removeBookFile,\n toJson,\n writeBookFile,\n} from \"./io\";\nimport { renderBook } from \"./render\";\n\n/** `.cache/written.json`: what the last `writeBook` wrote. Machine use only. */\ntype WriteState = {\n schemaVersion: typeof BOOK_SCHEMA_VERSION;\n /** Hash of everything the content depends on (version, facts, annotations). */\n stamp: string;\n /** Book file → sha256 of the content written. */\n files: Record<string, string>;\n};\n\n/** Book files `writeBook` never removes. */\nfunction isKept(bookPath: string): boolean {\n return (\n bookPath === GRIMOIRE_PATHS.bookManifest ||\n bookPath === GRIMOIRE_PATHS.testResults ||\n bookPath.startsWith(`${GRIMOIRE_PATHS.book}/.cache/`) ||\n bookPath.startsWith(`${GRIMOIRE_PATHS.staticSite}/`)\n );\n}\n\n/** Whether a book file not listed in a write state looks like one `writeBook` wrote. */\nconst isGenerated = (bookPath: string): boolean =>\n /\\.(?:json|md)$/.test(bookPath) && !isKept(bookPath);\n\nasync function readDiskText(root: string, bookPath: string): Promise<string | null> {\n try {\n return await readFile(bookFile(root, bookPath), \"utf8\");\n } catch {\n return null;\n }\n}\n\n/**\n * Write the book files that depend on the written files too: one entry per\n * code file, `index.md` per module, `app/routes.json`, the page and screen\n * lists. Rewrites only files whose content changed, removes entries whose\n * source is gone, and stores `annotations.writtenHash` and `tests` in the\n * manifest (`book.manifest` is updated in place).\n */\nexport async function writeBook(\n book: LoadedBook,\n annotations: BookAnnotations,\n): Promise<WriteBookResult> {\n const root = book.root;\n const statePath = path.join(root, ...WRITE_STATE_PATH.split(\"/\"));\n const previous = await readJson<WriteState>(statePath);\n const state =\n previous?.schemaVersion === BOOK_SCHEMA_VERSION && typeof previous.files === \"object\"\n ? previous\n : null;\n const stamp = hashText(\n JSON.stringify([grimoireVersion(), BOOK_SCHEMA_VERSION, book.facts, annotations.files]),\n );\n const written: string[] = [];\n const removed: string[] = [];\n\n if (state === null || state.stamp !== stamp) {\n const contents = renderBook(book.facts, annotations);\n const hashes = new Map(\n [...contents].map(([bookPath, content]) => [bookPath, hashText(content)]),\n );\n const changed = await mapLimit(\n [...contents.keys()].sort(),\n IO_CONCURRENCY,\n async (bookPath) => {\n const content = contents.get(bookPath) ?? \"\";\n\n if (state !== null) {\n if (state.files[bookPath] === hashes.get(bookPath)) return null;\n } else if ((await readDiskText(root, bookPath)) === content) {\n // No record of the last write (first run, or after `force`): compare with the disk once.\n return null;\n }\n\n await writeBookFile(root, bookPath, content);\n\n return bookPath;\n },\n );\n\n for (const bookPath of changed) if (bookPath !== null) written.push(bookPath);\n\n const known =\n state === null ? (await listBookFiles(root)).filter(isGenerated) : Object.keys(state.files);\n // `written.json` is a file on disk: a path in it that leaves `grimoire/book/` is ignored, never removed.\n const gone = known\n .filter((bookPath) => isInsideBook(bookPath) && !contents.has(bookPath) && !isKept(bookPath))\n .sort();\n\n await mapLimit(gone, IO_CONCURRENCY, async (bookPath) => removeBookFile(root, bookPath));\n removed.push(...gone);\n\n const next: WriteState = {\n schemaVersion: BOOK_SCHEMA_VERSION,\n stamp,\n files: Object.fromEntries([...hashes].sort(([left], [right]) => (left < right ? -1 : 1))),\n };\n\n await writeBookFile(root, WRITE_STATE_PATH, toJson(next));\n }\n\n const manifest = book.manifest;\n const sameTests =\n Object.keys(manifest.tests).length === Object.keys(annotations.tests).length &&\n Object.entries(annotations.tests).every(([file, hash]) => manifest.tests[file] === hash);\n\n if (\n manifest.writtenHash !== annotations.writtenHash ||\n !sameTests ||\n written.length > 0 ||\n removed.length > 0\n ) {\n manifest.writtenHash = annotations.writtenHash;\n manifest.tests = { ...annotations.tests };\n\n if (written.length > 0 || removed.length > 0) manifest.builtAt = new Date().toISOString();\n\n await writeBookFile(root, GRIMOIRE_PATHS.bookManifest, toJson(manifest));\n }\n\n return { written, removed };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2CA,SAAS,OAAO,UAA2B;CACzC,OACE,aAAa,eAAe,gBAC5B,aAAa,eAAe,eAC5B,SAAS,WAAW,GAAG,eAAe,KAAK,SAAS,KACpD,SAAS,WAAW,GAAG,eAAe,WAAW,EAAE;AAEvD;;AAGA,MAAM,eAAe,aACnB,iBAAiB,KAAK,QAAQ,KAAK,CAAC,OAAO,QAAQ;AAErD,eAAe,aAAa,MAAc,UAA0C;CAClF,IAAI;EACF,OAAO,MAAM,SAAS,SAAS,MAAM,QAAQ,GAAG,MAAM;CACxD,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;AASA,eAAsB,UACpB,MACA,aAC0B;CAC1B,MAAM,OAAO,KAAK;CAClB,MAAM,YAAY,KAAK,KAAK,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pB,MAAM,OAAmB;GACvB;GACA;GACA,OAAO,OAAO,YAAY,CAAC,GAAG,MAAM,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,WAAY,OAAO,QAAQ,KAAK,CAAE,CAAC;EAC1F;EAEA,MAAM,cAAc,MAAM,kBAAkB,OAAO,IAAI,CAAC;CAC1D;CAEA,MAAM,WAAW,KAAK;CACtB,MAAM,YACJ,OAAO,KAAK,SAAS,KAAK,CAAC,CAAC,WAAW,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,UACtE,OAAO,QAAQ,YAAY,KAAK,CAAC,CAAC,OAAO,CAAC,MAAM,UAAU,SAAS,MAAM,UAAU,IAAI;CAEzF,IACE,SAAS,gBAAgB,YAAY,eACrC,CAAC,aACD,QAAQ,SAAS,KACjB,QAAQ,SAAS,GACjB;EACA,SAAS,cAAc,YAAY;EACnC,SAAS,QAAQ,EAAE,GAAG,YAAY,MAAM;EAExC,IAAI,QAAQ,SAAS,KAAK,QAAQ,SAAS,GAAG,SAAS,2BAAU,IAAI,KAAK,EAAC,CAAC,YAAY;EAExF,MAAM,cAAc,MAAM,eAAe,cAAc,OAAO,QAAQ,CAAC;CACzE;CAEA,OAAO;EAAE;EAAS;CAAQ;AAC5B"}
@@ -0,0 +1,21 @@
1
+ import { BookFacts } from "../contracts/adapter.mjs";
2
+ import { WrittenGrimoire } from "../contracts/written.mjs";
3
+ import { ProofLine, TestResultsStore } from "../contracts/test-results.mjs";
4
+ import { CollectedFiles, Ownership } from "../contracts/bookmap.mjs";
5
+ import { AppMatch } from "../contracts/snapshot.mjs";
6
+ //#region ../../packages/grimoire/src/bookmap/build.d.ts
7
+ /** Everything the book maps are computed from. */
8
+ export type CollectedInput = {
9
+ written: WrittenGrimoire;
10
+ facts: BookFacts;
11
+ ownership: Ownership;
12
+ apps: Record<string, AppMatch>;
13
+ proofs: ProofLine[];
14
+ results: TestResultsStore | null;
15
+ /** Test file → current sha256 (a result with another hash is stale). */
16
+ testHashes: Record<string, string>;
17
+ };
18
+ /** Every feature and flow book map, `features/index.json` and `tasks/index.json`. Pure. */
19
+ export declare function buildCollectedFiles(input: CollectedInput): CollectedFiles;
20
+ //#endregion
21
+ //# sourceMappingURL=build.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/bookmap/build.ts"],"mappings":";;;;;;;YA8BY;EACV,SAAS;EACT,OAAO;EACP,WAAW;EACX,MAAM,eAAe;EACrB,QAAQ;EACR,SAAS;;EAET,YAAY;;;wBA8VE,oBAAoB,OAAO,iBAAiB"}