@warlock.js/grimoire 5.63.1 → 5.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/esm/book/build.d.mts.map +1 -1
  3. package/esm/book/build.mjs +24 -2
  4. package/esm/book/build.mjs.map +1 -1
  5. package/esm/check/check-grimoire.d.mts.map +1 -1
  6. package/esm/check/check-grimoire.mjs +11 -1
  7. package/esm/check/check-grimoire.mjs.map +1 -1
  8. package/esm/check/rules/api-snapshot.mjs +39 -0
  9. package/esm/check/rules/api-snapshot.mjs.map +1 -0
  10. package/esm/check/rules/code-rules.mjs +45 -0
  11. package/esm/check/rules/code-rules.mjs.map +1 -0
  12. package/esm/check/rules/drift.mjs +54 -0
  13. package/esm/check/rules/drift.mjs.map +1 -0
  14. package/esm/check/rules/focused-tests.mjs +39 -0
  15. package/esm/check/rules/focused-tests.mjs.map +1 -0
  16. package/esm/check/rules/shows.mjs +52 -0
  17. package/esm/check/rules/shows.mjs.map +1 -0
  18. package/esm/codes/codes.d.mts +48 -0
  19. package/esm/codes/codes.d.mts.map +1 -1
  20. package/esm/codes/codes.mjs +26 -1
  21. package/esm/codes/codes.mjs.map +1 -1
  22. package/esm/contracts/adapter.d.mts +6 -0
  23. package/esm/contracts/adapter.d.mts.map +1 -1
  24. package/esm/contracts/guard.d.mts +104 -0
  25. package/esm/contracts/guard.d.mts.map +1 -0
  26. package/esm/contracts/index.mjs +5 -0
  27. package/esm/contracts/matrix.d.mts +75 -0
  28. package/esm/contracts/matrix.d.mts.map +1 -0
  29. package/esm/contracts/scry.d.mts +42 -0
  30. package/esm/contracts/scry.d.mts.map +1 -1
  31. package/esm/contracts/settings.d.mts +71 -0
  32. package/esm/contracts/settings.d.mts.map +1 -0
  33. package/esm/contracts/settings.mjs +67 -0
  34. package/esm/contracts/settings.mjs.map +1 -0
  35. package/esm/contracts/shots.d.mts +146 -0
  36. package/esm/contracts/shots.d.mts.map +1 -0
  37. package/esm/contracts/snapshot.d.mts +10 -0
  38. package/esm/contracts/snapshot.d.mts.map +1 -1
  39. package/esm/contracts/written.d.mts +13 -0
  40. package/esm/contracts/written.d.mts.map +1 -1
  41. package/esm/contracts/written.mjs +7 -1
  42. package/esm/contracts/written.mjs.map +1 -1
  43. package/esm/devtools/approvals.mjs +59 -0
  44. package/esm/devtools/approvals.mjs.map +1 -0
  45. package/esm/devtools/data.mjs +2 -0
  46. package/esm/devtools/data.mjs.map +1 -1
  47. package/esm/devtools/graphs.mjs +13 -3
  48. package/esm/devtools/graphs.mjs.map +1 -1
  49. package/esm/devtools/index.d.mts +7 -0
  50. package/esm/devtools/index.d.mts.map +1 -1
  51. package/esm/devtools/index.mjs +33 -3
  52. package/esm/devtools/index.mjs.map +1 -1
  53. package/esm/devtools/matrix.mjs +207 -0
  54. package/esm/devtools/matrix.mjs.map +1 -0
  55. package/esm/devtools/product-map.d.mts.map +1 -1
  56. package/esm/devtools/product-map.mjs +87 -1
  57. package/esm/devtools/product-map.mjs.map +1 -1
  58. package/esm/devtools/site.d.mts.map +1 -1
  59. package/esm/devtools/site.mjs +12 -3
  60. package/esm/devtools/site.mjs.map +1 -1
  61. package/esm/devtools/snapshot-source.mjs +13 -3
  62. package/esm/devtools/snapshot-source.mjs.map +1 -1
  63. package/esm/git/index.d.mts +20 -0
  64. package/esm/git/index.d.mts.map +1 -0
  65. package/esm/git/index.mjs +280 -0
  66. package/esm/git/index.mjs.map +1 -0
  67. package/esm/guard/api.mjs +70 -0
  68. package/esm/guard/api.mjs.map +1 -0
  69. package/esm/guard/assertions.mjs +18 -0
  70. package/esm/guard/assertions.mjs.map +1 -0
  71. package/esm/guard/collect.mjs +139 -0
  72. package/esm/guard/collect.mjs.map +1 -0
  73. package/esm/guard/format.mjs +27 -0
  74. package/esm/guard/format.mjs.map +1 -0
  75. package/esm/guard/glob.mjs +79 -0
  76. package/esm/guard/glob.mjs.map +1 -0
  77. package/esm/guard/index.mjs +9 -0
  78. package/esm/guard/rules.mjs +310 -0
  79. package/esm/guard/rules.mjs.map +1 -0
  80. package/esm/guard/scope.mjs +95 -0
  81. package/esm/guard/scope.mjs.map +1 -0
  82. package/esm/index.d.mts +10 -3
  83. package/esm/index.mjs +6 -2
  84. package/esm/paths/index.d.mts +15 -1
  85. package/esm/paths/index.d.mts.map +1 -1
  86. package/esm/paths/index.mjs +27 -3
  87. package/esm/paths/index.mjs.map +1 -1
  88. package/esm/proves/index.mjs +2 -1
  89. package/esm/proves/scan-proofs.mjs +1 -1
  90. package/esm/proves/scan-proofs.mjs.map +1 -1
  91. package/esm/proves/scan-shows.d.mts +21 -0
  92. package/esm/proves/scan-shows.d.mts.map +1 -0
  93. package/esm/proves/scan-shows.mjs +168 -0
  94. package/esm/proves/scan-shows.mjs.map +1 -0
  95. package/esm/releases/index.d.mts.map +1 -1
  96. package/esm/releases/index.mjs +5 -3
  97. package/esm/releases/index.mjs.map +1 -1
  98. package/esm/releases/stamp.mjs +121 -0
  99. package/esm/releases/stamp.mjs.map +1 -0
  100. package/esm/rules/focused.mjs +26 -0
  101. package/esm/rules/focused.mjs.map +1 -0
  102. package/esm/rules/index.mjs +88 -0
  103. package/esm/rules/index.mjs.map +1 -0
  104. package/esm/rules/logical-css.mjs +112 -0
  105. package/esm/rules/logical-css.mjs.map +1 -0
  106. package/esm/rules/no-js-imports.mjs +22 -0
  107. package/esm/rules/no-js-imports.mjs.map +1 -0
  108. package/esm/rules/scan.mjs +196 -0
  109. package/esm/rules/scan.mjs.map +1 -0
  110. package/esm/rules/specific-errors.mjs +51 -0
  111. package/esm/rules/specific-errors.mjs.map +1 -0
  112. package/esm/rules/type-discriminator.mjs +27 -0
  113. package/esm/rules/type-discriminator.mjs.map +1 -0
  114. package/esm/scry/also-changes.mjs +107 -0
  115. package/esm/scry/also-changes.mjs.map +1 -0
  116. package/esm/scry/format.d.mts.map +1 -1
  117. package/esm/scry/format.mjs +35 -0
  118. package/esm/scry/format.mjs.map +1 -1
  119. package/esm/scry/query.d.mts.map +1 -1
  120. package/esm/scry/query.mjs +40 -2
  121. package/esm/scry/query.mjs.map +1 -1
  122. package/esm/scry/search.d.mts.map +1 -1
  123. package/esm/scry/search.mjs +43 -11
  124. package/esm/scry/search.mjs.map +1 -1
  125. package/esm/shots/approve.mjs +195 -0
  126. package/esm/shots/approve.mjs.map +1 -0
  127. package/esm/shots/drift.mjs +174 -0
  128. package/esm/shots/drift.mjs.map +1 -0
  129. package/esm/shots/png.mjs +166 -0
  130. package/esm/shots/png.mjs.map +1 -0
  131. package/esm/shots/state.mjs +43 -0
  132. package/esm/shots/state.mjs.map +1 -0
  133. package/esm/shots/store.mjs +66 -0
  134. package/esm/shots/store.mjs.map +1 -0
  135. package/esm/shots/touched.mjs +38 -0
  136. package/esm/shots/touched.mjs.map +1 -0
  137. package/esm/warlock/adapter.d.mts.map +1 -1
  138. package/esm/warlock/adapter.mjs +22 -2
  139. package/esm/warlock/adapter.mjs.map +1 -1
  140. package/esm/warlock/api-command.mjs +41 -0
  141. package/esm/warlock/api-command.mjs.map +1 -0
  142. package/esm/warlock/approve-command.mjs +80 -0
  143. package/esm/warlock/approve-command.mjs.map +1 -0
  144. package/esm/warlock/collect-off-thread.mjs +66 -0
  145. package/esm/warlock/collect-off-thread.mjs.map +1 -0
  146. package/esm/warlock/commands.d.mts +1 -1
  147. package/esm/warlock/commands.d.mts.map +1 -1
  148. package/esm/warlock/commands.mjs +61 -8
  149. package/esm/warlock/commands.mjs.map +1 -1
  150. package/esm/warlock/guard-command.mjs +116 -0
  151. package/esm/warlock/guard-command.mjs.map +1 -0
  152. package/esm/warlock/index.d.mts +2 -1
  153. package/esm/warlock/index.mjs +2 -1
  154. package/esm/warlock/languages.mjs +75 -0
  155. package/esm/warlock/languages.mjs.map +1 -0
  156. package/esm/warlock/mcp-tools.mjs +2 -2
  157. package/esm/warlock/mcp-tools.mjs.map +1 -1
  158. package/esm/warlock/release-command.mjs +65 -0
  159. package/esm/warlock/release-command.mjs.map +1 -0
  160. package/esm/warlock/shows.d.mts +35 -0
  161. package/esm/warlock/shows.d.mts.map +1 -0
  162. package/esm/warlock/shows.mjs +195 -0
  163. package/esm/warlock/shows.mjs.map +1 -0
  164. package/esm/workspace/cache.mjs +4 -1
  165. package/esm/workspace/cache.mjs.map +1 -1
  166. package/esm/workspace/derived.mjs +11 -6
  167. package/esm/workspace/derived.mjs.map +1 -1
  168. package/esm/workspace/index.d.mts.map +1 -1
  169. package/esm/workspace/index.mjs +8 -1
  170. package/esm/workspace/index.mjs.map +1 -1
  171. package/esm/workspace/stored.mjs +4 -1
  172. package/esm/workspace/stored.mjs.map +1 -1
  173. package/esm/written/features.mjs +21 -5
  174. package/esm/written/features.mjs.map +1 -1
  175. package/esm/written/index.mjs +2 -1
  176. package/esm/written/parse-grimoire.d.mts.map +1 -1
  177. package/esm/written/parse-grimoire.mjs +16 -3
  178. package/esm/written/parse-grimoire.mjs.map +1 -1
  179. package/esm/written/settings.d.mts +11 -0
  180. package/esm/written/settings.d.mts.map +1 -0
  181. package/esm/written/settings.mjs +88 -0
  182. package/esm/written/settings.mjs.map +1 -0
  183. package/llms-full.txt +282 -39
  184. package/llms.txt +2 -0
  185. package/package.json +3 -3
  186. package/skills/backfill-a-grimoire/SKILL.md +4 -0
  187. package/skills/describe-an-app/SKILL.md +4 -1
  188. package/skills/guard-a-change/SKILL.md +85 -0
  189. package/skills/index.md +7 -3
  190. package/skills/record-a-change/SKILL.md +52 -16
  191. package/skills/review-a-change/SKILL.md +53 -0
  192. package/skills/use-the-grimoire/SKILL.md +27 -18
  193. package/skills/write-a-feature/SKILL.md +42 -1
  194. package/ui/grimoire-view.js +756 -40
  195. package/ui/grimoire.css +303 -28
  196. package/ui/product-map.css +43 -7
  197. package/ui/product-map.js +212 -37
@@ -1 +1 @@
1
- {"version":3,"file":"site.mjs","names":["data.summary","data.features","data.apps","data.tasks","data.releases","data.check","data.graphOfModules","data.checkGroups","feature","data.feature","flowAnswer","data.flowAnswer","page","data.page","file","data.file"],"sources":["../../../../../../../../packages/grimoire/src/devtools/site.ts"],"sourcesContent":["/**\n * The static export: one folder with an `index.html` that holds the view, the\n * loader, the styles and the data as JSON. It opens from disk (`file://`) or\n * any static host and needs no running app.\n */\nimport { createHash } from \"node:crypto\";\nimport { copyFile, mkdir, open, readFile, realpath, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenFlow } from \"../contracts/written\";\nimport { GRIMOIRE_PATHS, projectPath, toPosixPath } from \"../paths\";\nimport { stampOf } from \"../workspace/cache\";\nimport * as data from \"./data\";\nimport { featureGraph, fileGraph, pageGraph } from \"./graphs\";\nimport { productFeature, productFlow, productMap } from \"./product-map\";\nimport { createSnapshotSource } from \"./snapshot-source\";\n\n/** Options of `exportGrimoireSite()`. */\nexport type ExportGrimoireSiteOptions = {\n /** Output folder, project-relative or absolute. Default `grimoire/book/site` (the book writer leaves it alone and git ignores it). */\n outDir?: string;\n /** The adapter to open the book with. Default: the Warlock adapter. */\n adapter?: BookAdapter | (() => Promise<BookAdapter>);\n /** An already opened snapshot; skips opening one. */\n snapshot?: GrimoireSnapshot;\n /**\n * Export the business view only: the share-safe Product map (no file paths, test\n * names or export names, no per-file answers, no check or search of code). The\n * page opens on the Product map.\n */\n product?: boolean;\n /** Write the page even when the folder already holds one built from the same book. Default `false`. */\n force?: boolean;\n};\n\n/** What `exportGrimoireSite()` did. */\nexport type GrimoireSiteExport = {\n /** The output folder, project-relative. */\n outDir: string;\n /** `true` when the folder already held a page built from the same book and nothing was written. */\n upToDate: boolean;\n};\n\n/** The most files the export keeps per-file answers for (the most imported first). */\nexport const SITE_FILE_LIMIT = 3000;\n\n/** One entry of the exported search list. `text` is written content (a flow's summary, story, cases and criteria) the search also reads. */\ntype SearchItem = { type: string; id: string; detail: string | null; text?: string };\n\n/** The written text of a flow the exported search reads, with criteria ids so `AC-5` is findable. */\nfunction flowSearchText(flow: WrittenFlow): string {\n return [\n flow.summary ?? \"\",\n ...flow.story.map((step) => step.text),\n ...flow.cases.map((item) => `${item.question} ${item.answer} ${item.criteria.join(\" \")}`),\n ...flow.criteria.map((item) => `${item.id} ${item.text}`),\n ]\n .filter((part) => part !== \"\")\n .join(\" | \");\n}\n\nconst uiFolder = fileURLToPath(new URL(\"../../ui/\", import.meta.url));\n\n/** Every answer the static page can give, keyed by the data route it replaces. */\nexport function buildSiteData(snapshot: GrimoireSnapshot) {\n const routes: Record<string, unknown> = {\n summary: data.summary(snapshot),\n features: data.features(snapshot),\n apps: data.apps(snapshot),\n tasks: data.tasks(snapshot),\n releases: data.releases(snapshot),\n // The page is meant to be shared: it does not name where the project sits on this machine.\n check: { ...data.check(snapshot), root: \".\" },\n \"graph/modules\": data.graphOfModules(snapshot),\n };\n // The static page is the signed-in view: developer detail stays, and no monitor reports errors.\n const productOptions = { shared: false, errors: null } as const;\n const productAnswer = attempt(() => productMap(snapshot, productOptions));\n const groups = attempt(() => data.checkGroups(snapshot));\n\n if (productAnswer !== undefined) routes.product = productAnswer;\n\n if (groups !== undefined) routes[\"check/groups\"] = groups;\n\n const search: SearchItem[] = [];\n\n for (const release of snapshot.written.releases) {\n routes[`releases/${release.release.value}`] = release;\n }\n\n for (const feature of snapshot.written.features) {\n const readme = feature.readme;\n\n search.push({\n type: \"feature\",\n id: feature.id,\n detail: readme?.title.value ?? null,\n text: [readme?.summary ?? \"\", readme?.why ?? \"\"].filter((part) => part !== \"\").join(\" | \"),\n });\n const answered = attempt(() => data.feature(snapshot, feature.id));\n\n if (answered !== undefined) routes[`features/${feature.id}`] = answered;\n\n const graph = featureGraph(snapshot, feature.id);\n\n if (graph !== null) routes[`graph/feature/${feature.id}`] = graph;\n\n const product = attempt(() => productFeature(snapshot, feature.id, productOptions));\n\n if (product !== undefined) routes[`product/features/${feature.id}`] = product;\n\n for (const flow of feature.flows) {\n search.push({\n type: \"flow\",\n id: flow.ref,\n detail: flow.heading?.value ?? null,\n text: flowSearchText(flow),\n });\n const flowAnswer = attempt(() => data.flowAnswer(snapshot, feature.id, flow.id.value));\n const productFlowAnswer = attempt(() =>\n productFlow(snapshot, feature.id, flow.id.value, productOptions),\n );\n\n if (flowAnswer !== undefined) routes[`flows/${flow.ref}`] = flowAnswer;\n\n if (productFlowAnswer !== undefined) routes[`product/flows/${flow.ref}`] = productFlowAnswer;\n }\n }\n\n for (const app of snapshot.written.apps) {\n const appId = app.id.value;\n\n for (const page of [...app.pages, ...app.screens]) {\n const route = page.route?.value ?? page.screen?.value ?? null;\n const answer = attempt(() => data.page(snapshot, appId, page.id));\n const graph = pageGraph(snapshot, appId, page.id);\n\n for (const key of new Set([page.id, ...(route === null ? [] : [route])])) {\n if (answer !== undefined) routes[`apps/${appId}/pages/${key}`] = answer;\n\n if (graph !== null) routes[`graph/page/${appId}/${key}`] = graph;\n }\n\n if (route !== null)\n search.push({\n type: page.type,\n id: `${appId} ${route}`,\n detail: page.heading?.value ?? null,\n });\n\n for (const block of page.blockFiles) {\n search.push({\n type: \"block\",\n id: `${appId}/${page.id}/${block.id}`,\n detail: block.flow?.value ?? null,\n });\n }\n }\n }\n\n for (const found of snapshot.book.facts.routes ?? []) {\n search.push({\n type: \"route\",\n id: `${found.method} ${found.path}`,\n detail: found.description ?? found.handler,\n });\n }\n\n for (const task of snapshot.collected.tasksIndex.open.concat(\n snapshot.collected.tasksIndex.done,\n )) {\n search.push({ type: \"task\", id: task.id, detail: task.title });\n }\n\n const files: Record<string, { result: unknown; graph: unknown }> = {};\n const ranked = [...snapshot.book.facts.files].sort(\n (left, right) =>\n right.importedBy.length - left.importedBy.length || left.file.localeCompare(right.file),\n );\n\n for (const [index, file] of ranked.entries()) {\n search.push({ type: \"file\", id: file.file, detail: file.about });\n\n if (index >= SITE_FILE_LIMIT) continue;\n\n const result = attempt(() => data.file(snapshot, file.file));\n\n if (result !== undefined) files[file.file] = { result, graph: fileGraph(snapshot, file.file) };\n }\n\n return { routes, files, search };\n}\n\n/**\n * The business-only data of the static export: the share-safe Product map, its feature\n * and flow pages, and nothing else. No file paths, test names, export names, check\n * findings or per-file answers; the search list is empty.\n */\nexport function buildProductSiteData(snapshot: GrimoireSnapshot) {\n const options = { shared: true, errors: null } as const;\n const routes: Record<string, unknown> = {};\n const map = attempt(() => productMap(snapshot, options));\n\n if (map !== undefined) routes.product = map;\n\n for (const feature of snapshot.written.features) {\n const answer = attempt(() => productFeature(snapshot, feature.id, options));\n\n if (answer !== undefined) routes[`product/features/${feature.id}`] = answer;\n\n for (const flow of feature.flows) {\n const flowAnswer = attempt(() => productFlow(snapshot, feature.id, flow.id.value, options));\n\n if (flowAnswer !== undefined) routes[`product/flows/${flow.ref}`] = flowAnswer;\n }\n }\n\n return { routes, files: {}, search: [] as SearchItem[] };\n}\n\n/** JSON for an inline `<script>`: every `<` is escaped, so no `</script` or `<!--` can appear. */\nfunction inlineJson(value: unknown): string {\n return JSON.stringify(value).replaceAll(\"<\", \"\\\\u003c\");\n}\n\n/** Code for an inline `<script>`: `</script` (in any case) and `<!--` (only possible in strings and comments) are broken up. */\nfunction inlineCode(code: string): string {\n return code.replace(/<\\/(script)/gi, \"<\\\\/$1\").replaceAll(\"<!--\", \"<\\\\!--\");\n}\n\n/** The image types the export copies (the same list the devtools panel serves). */\nconst SCREENSHOT_EXTENSIONS = new Set([\".png\", \".jpg\", \".jpeg\", \".webp\", \".gif\"]);\n\n/** Every `WrittenScreenshot.path` in the written files, once each. */\nexport function collectScreenshotPaths(written: unknown): string[] {\n const found = new Set<string>();\n const walk = (value: unknown): void => {\n if (Array.isArray(value)) {\n for (const item of value) walk(item);\n } else if (value !== null && typeof value === \"object\") {\n const record = value as Record<string, unknown>;\n\n if (\n typeof record.path === \"string\" &&\n typeof record.written === \"string\" &&\n typeof record.alt === \"string\"\n )\n found.add(record.path);\n\n for (const item of Object.values(record)) walk(item);\n }\n };\n\n walk(written);\n\n return [...found].sort();\n}\n\n/**\n * Copy the screenshots the written files use into `<out>/screenshots/`. A path that leaves\n * `grimoire/screenshots/`, has another extension or does not exist is skipped.\n *\n * @returns The paths that were copied.\n */\nexport async function copyScreenshots(\n root: string,\n outFolder: string,\n paths: readonly string[],\n): Promise<string[]> {\n const folder = await realpath(path.join(root, GRIMOIRE_PATHS.screenshots)).catch(() => null);\n const copied: string[] = [];\n\n if (folder === null) return copied;\n\n for (const written of paths) {\n const segments = written.split(\"/\");\n\n if (\n written === \"\" ||\n written.includes(\"\\\\\") ||\n written.includes(\"\\0\") ||\n path.isAbsolute(written) ||\n segments.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\") ||\n !SCREENSHOT_EXTENSIONS.has(path.extname(written).toLowerCase())\n )\n continue;\n\n const source = await realpath(path.join(folder, ...segments)).catch(() => null);\n\n if (source === null || !source.startsWith(folder + path.sep)) continue;\n\n if (!(await stat(source)).isFile()) continue;\n\n const target = path.join(outFolder, \"screenshots\", ...segments);\n\n await mkdir(path.dirname(target), { recursive: true });\n await copyFile(source, target);\n copied.push(written);\n }\n\n return copied;\n}\n\n/** The answer, or `undefined` when the item cannot be answered (the export skips it). */\nfunction attempt<Value>(answer: () => Value): Value | undefined {\n try {\n return answer();\n } catch {\n return undefined;\n }\n}\n\n/** Everything before the page's `export default`, so the view can sit in an inline module. */\nexport function inlineView(source: string): string {\n const marker = \"export default renderGrimoire;\";\n\n if (!source.includes(marker))\n throw new Error(\"grimoire-view.js must end with `export default renderGrimoire;`.\");\n\n return source.replace(marker, \"\");\n}\n\n/**\n * The product map module as inline code: its `export` keywords are removed and the Grimoire view\n * finds it as `globalThis.grimoireProductMap`.\n */\nexport function inlineProductMap(source: string): string {\n const marker = \"export default renderProductMap;\";\n\n if (!source.includes(marker))\n throw new Error(\"product-map.js must end with `export default renderProductMap;`.\");\n\n return `${source.replace(marker, \"\").replace(/^export (async )?function /gm, \"$1function \")}\\nglobalThis.grimoireProductMap = { productMapView };\\n`;\n}\n\n/**\n * The page's own styles: it defines every devtools panel token (light, then dark under\n * `prefers-color-scheme`), so `grimoire.css` renders the same here as in the dashboard.\n * The values keep text AA on `--background` and `--card`.\n */\nexport const PAGE_STYLE = `\n:root{color-scheme:light dark;--background:#faf8f2;--foreground:#1a1814;--card:#fff;--card-foreground:#1a1814;--popover:#fff;--popover-foreground:#1a1814;--primary:#1a1814;--primary-foreground:#faf8f2;--secondary:#f0ece0;--secondary-foreground:#1a1814;--muted:#f0ece0;--muted-foreground:#5c574b;--accent:#f3ecd6;--accent-foreground:#1a1814;--destructive:#b42318;--border:#e0d9c6;--input:#d2cab3;--ring:#8a5a00;--radius:10px;--brand:#8a5a00;--brand-foreground:#fff;--success:#13693b;--warning:#8a5300;--info:#0b66a3;--chart-1:#8a5a00;--chart-2:#13693b;--chart-3:#0b66a3;--chart-4:#6d3ac7;--chart-5:#b4306b;font-family:system-ui,-apple-system,\"Segoe UI\",sans-serif}\n@media (prefers-color-scheme:dark){:root{--background:#0b0b0c;--foreground:#f2f2ee;--card:#141416;--card-foreground:#f2f2ee;--popover:#141416;--popover-foreground:#f2f2ee;--primary:#ffc61a;--primary-foreground:#1a1300;--secondary:#1f1f22;--secondary-foreground:#f2f2ee;--muted:#1f1f22;--muted-foreground:#a9a9b0;--accent:#26262a;--accent-foreground:#f2f2ee;--destructive:#ff8f86;--border:#2a2a2e;--input:#34343a;--ring:#ffc61a;--radius:10px;--brand:#ffc61a;--brand-foreground:#1a1300;--success:#5fd391;--warning:#f3a24a;--info:#6cc0f5;--chart-1:#ffc61a;--chart-2:#5fd391;--chart-3:#6cc0f5;--chart-4:#b79cff;--chart-5:#ff8fbd}}\n*{box-sizing:border-box}body{margin:0;background:var(--background);color:var(--foreground);font-size:14px;line-height:1.5}\nmain{max-width:1180px;margin:0 auto;padding:16px}\n.empty{padding:12px;color:var(--muted-foreground)}.error{padding:12px;color:var(--destructive)}\n`;\n\n/** The `index.html` text. */\nexport function renderSiteHtml(\n siteData: unknown,\n sources: {\n view: string;\n loader: string;\n css: string;\n productMap?: string;\n productCss?: string;\n /** Mount the share-safe Product map alone (the business export): `view` and `css` are not inlined. */\n product?: boolean;\n /** A freshness stamp written into the page, so the next export can tell it is current. */\n stamp?: string;\n },\n): string {\n const json = inlineJson(siteData);\n\n if (sources.product === true && sources.productMap === undefined) {\n throw new Error(\"A product export needs product-map.js.\");\n }\n\n const mounted = sources.product === true ? \"renderProductMap\" : \"renderGrimoire\";\n const script = inlineCode(\n `${sources.productMap === undefined ? \"\" : inlineProductMap(sources.productMap)}${sources.product === true ? \"\" : inlineView(sources.view)}\\n${sources.loader}\\ngrimoireStaticMount(JSON.parse(document.getElementById(\"grimoire-data\").textContent), document.getElementById(\"grimoire-root\"), ${mounted});\\n`,\n );\n const styles = sources.product === true ? \"\" : sources.css;\n const stamp =\n sources.stamp === undefined ? \"\" : `<meta name=\"grimoire-stamp\" content=\"${sources.stamp}\">\\n`;\n\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n${stamp}<title>${sources.product === true ? \"Product map\" : \"Grimoire\"}</title>\n<style>${PAGE_STYLE}${styles}${sources.productCss ?? \"\"}</style>\n</head>\n<body>\n<main id=\"grimoire-root\"><p class=\"empty\">Opening the book…</p></main>\n<script type=\"application/json\" id=\"grimoire-data\">${json}</script>\n<script type=\"module\">${script}</script>\n</body>\n</html>\n`;\n}\n\n/** The stamp is written near the top of the page; this much of the file is enough to find it. */\nconst STAMP_HEAD_BYTES = 2048;\n\n/** The stamp of the page that is already in `index.html`, or `null` (no page, or one without a stamp). */\nasync function writtenStamp(file: string): Promise<string | null> {\n let handle;\n\n try {\n handle = await open(file, \"r\");\n\n const { buffer, bytesRead } = await handle.read(\n Buffer.alloc(STAMP_HEAD_BYTES),\n 0,\n STAMP_HEAD_BYTES,\n 0,\n );\n\n return (\n /<meta name=\"grimoire-stamp\" content=\"([0-9a-f]+)\">/.exec(\n buffer.toString(\"utf8\", 0, bytesRead),\n )?.[1] ?? null\n );\n } catch {\n return null;\n } finally {\n await handle?.close();\n }\n}\n\n/** Modified times of the files the page is built from, so a new framework version rebuilds the page. */\nasync function uiStamp(): Promise<string> {\n const names = [\n \"grimoire-view.js\",\n \"grimoire-static.js\",\n \"grimoire.css\",\n \"product-map.js\",\n \"product-map.css\",\n ];\n const times = await Promise.all(\n names.map(async (name) => {\n try {\n return (await stat(path.join(uiFolder, name))).mtimeMs;\n } catch {\n return 0;\n }\n }),\n );\n\n return times.join(\",\");\n}\n\n/**\n * Write the tab as a static folder for people without the app running.\n *\n * The folder holds `index.html` only: the view, the loader, the styles and\n * the data (as JSON) are inside it, so it opens straight from disk. Open the\n * page and use `#grimoire/...` links; the answers that need the running app\n * (impact of a file) say so in place.\n *\n * With `product: true` the page is the business export: the share-safe\n * Product map only, no file paths, test names or per-file answers.\n *\n * The page carries a freshness stamp (the files of the book, the written\n * folders and the test results). When the folder already holds a page with\n * the same stamp and the same mode, nothing is rebuilt or written (`force`\n * writes it anyway).\n *\n * @param root Absolute project root.\n */\nexport async function exportGrimoireSiteDetailed(\n root: string,\n options: ExportGrimoireSiteOptions = {},\n): Promise<GrimoireSiteExport> {\n // Project-relative from here on; an absolute folder is kept where it is.\n const outDir = projectPath(\n root,\n toPosixPath(options.outDir ?? GRIMOIRE_PATHS.staticSite),\n ).replace(/\\/+$/, \"\");\n const snapshot =\n options.snapshot ??\n (await createSnapshotSource(\n root,\n options.adapter === undefined ? {} : { adapter: options.adapter },\n ).get());\n const absolute = path.resolve(root, outDir);\n const product = options.product === true;\n const stamp = createHash(\"sha1\")\n .update(`${product ? \"product\" : \"full\"}|${await stampOf(root, snapshot)}|${await uiStamp()}`)\n .digest(\"hex\");\n\n if (options.force !== true && (await writtenStamp(path.join(absolute, \"index.html\"))) === stamp) {\n return { outDir, upToDate: true };\n }\n\n const [view, loader, css, productMapSource, productCss] = await Promise.all(\n [\n \"grimoire-view.js\",\n \"grimoire-static.js\",\n \"grimoire.css\",\n \"product-map.js\",\n \"product-map.css\",\n ].map((name) => readFile(path.join(uiFolder, name), \"utf8\")),\n );\n const html = renderSiteHtml(product ? buildProductSiteData(snapshot) : buildSiteData(snapshot), {\n view: view ?? \"\",\n loader: loader ?? \"\",\n css: css ?? \"\",\n productMap: productMapSource ?? \"\",\n productCss: productCss ?? \"\",\n product,\n stamp,\n });\n\n await mkdir(absolute, { recursive: true });\n await writeFile(path.join(absolute, \"index.html\"), html);\n await copyScreenshots(root, absolute, collectScreenshotPaths(snapshot.written));\n\n return { outDir, upToDate: false };\n}\n\n/** `exportGrimoireSiteDetailed()` that returns only the output folder, project-relative. */\nexport async function exportGrimoireSite(\n root: string,\n options: ExportGrimoireSiteOptions = {},\n): Promise<string> {\n return (await exportGrimoireSiteDetailed(root, options)).outDir;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8CA,MAAa,kBAAkB;;AAM/B,SAAS,eAAe,MAA2B;CACjD,OAAO;EACL,KAAK,WAAW;EAChB,GAAG,KAAK,MAAM,KAAK,SAAS,KAAK,IAAI;EACrC,GAAG,KAAK,MAAM,KAAK,SAAS,GAAG,KAAK,SAAS,GAAG,KAAK,OAAO,GAAG,KAAK,SAAS,KAAK,GAAG,GAAG;EACxF,GAAG,KAAK,SAAS,KAAK,SAAS,GAAG,KAAK,GAAG,GAAG,KAAK,MAAM;CAC1D,CAAC,CACE,QAAQ,SAAS,SAAS,EAAE,CAAC,CAC7B,KAAK,KAAK;AACf;AAEA,MAAM,WAAW,cAAc,IAAI,IAAI,aAAa,YAAY,GAAG,CAAC;;AAGpE,SAAgB,cAAc,UAA4B;CACxD,MAAM,SAAkC;EACtC,SAASA,QAAa,QAAQ;EAC9B,UAAUC,SAAc,QAAQ;EAChC,MAAMC,KAAU,QAAQ;EACxB,OAAOC,MAAW,QAAQ;EAC1B,UAAUC,SAAc,QAAQ;EAEhC,OAAO;GAAE,GAAGC,MAAW,QAAQ;GAAG,MAAM;EAAI;EA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EAAE,SAAS,QAAQ,QAAQ,CAClE,CAAC,CAAC,IAAI;CACR,MAAM,WAAW,KAAK,QAAQ,MAAM,MAAM;CAC1C,MAAM,UAAU,QAAQ,YAAY;CACpC,MAAM,QAAQ,WAAW,MAAM,CAAC,CAC7B,OAAO,GAAG,UAAU,YAAY,OAAO,GAAG,MAAM,QAAQ,MAAM,QAAQ,EAAE,GAAG,MAAM,QAAQ,GAAG,CAAC,CAC7F,OAAO,KAAK;CAEf,IAAI,QAAQ,UAAU,QAAS,MAAM,aAAa,KAAK,KAAK,UAAU,YAAY,CAAC,MAAO,OACxF,OAAO;EAAE;EAAQ,UAAU;CAAK;CAGlC,MAAM,CAAC,MAAM,QAAQ,KAAK,kBAAkB,cAAc,MAAM,QAAQ,IACtE;EACE;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,SAAS,SAAS,KAAK,KAAK,UAAU,IAAI,GAAG,MAAM,CAAC,CAC7D;CACA,MAAM,OAAO,eAAe,UAAU,qBAAqB,QAAQ,IAAI,cAAc,QAAQ,GAAG;EAC9F,MAAM,QAAQ;EACd,QAAQ,UAAU;EAClB,KAAK,OAAO;EACZ,YAAY,oBAAoB;EAChC,YAAY,cAAc;EAC1B;EACA;CACF,CAAC;CAED,MAAM,MAAM,UAAU,EAAE,WAAW,KAAK,CAAC;CACzC,MAAM,UAAU,KAAK,KAAK,UAAU,YAAY,GAAG,IAAI;CACvD,MAAM,gBAAgB,MAAM,UAAU,uBAAuB,SAAS,OAAO,CAAC;CAE9E,OAAO;EAAE;EAAQ,UAAU;CAAM;AACnC;;AAGA,eAAsB,mBACpB,MACA,UAAqC,CAAC,GACrB;CACjB,QAAQ,MAAM,2BAA2B,MAAM,OAAO,EAAC,CAAE;AAC3D"}
1
+ {"version":3,"file":"site.mjs","names":["data.summary","data.features","data.apps","data.tasks","data.releases","data.check","data.graphOfModules","data.checkGroups","feature","data.feature","flowAnswer","data.flowAnswer","page","data.page","file","data.file"],"sources":["../../../../../../../../packages/grimoire/src/devtools/site.ts"],"sourcesContent":["/**\n * The static export: one folder with an `index.html` that holds the view, the\n * loader, the styles and the data as JSON. It opens from disk (`file://`) or\n * any static host and needs no running app.\n */\nimport { createHash } from \"node:crypto\";\nimport { copyFile, mkdir, open, readFile, realpath, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenFlow } from \"../contracts/written\";\nimport { GRIMOIRE_PATHS, projectPath, toPosixPath } from \"../paths\";\nimport { stampOf } from \"../workspace/cache\";\nimport * as data from \"./data\";\nimport { matrix, matrixImagePaths } from \"./matrix\";\nimport { featureGraph, fileGraph, pageGraph } from \"./graphs\";\nimport { productFeature, productFlow, productMap, productWhatsNew } from \"./product-map\";\nimport { createSnapshotSource } from \"./snapshot-source\";\n\n/** Options of `exportGrimoireSite()`. */\nexport type ExportGrimoireSiteOptions = {\n /** Output folder, project-relative or absolute. Default `grimoire/book/site` (the book writer leaves it alone and git ignores it). */\n outDir?: string;\n /** The adapter to open the book with. Default: the Warlock adapter. */\n adapter?: BookAdapter | (() => Promise<BookAdapter>);\n /** An already opened snapshot; skips opening one. */\n snapshot?: GrimoireSnapshot;\n /**\n * Export the business view only: the share-safe Product map (no file paths, test\n * names or export names, no per-file answers, no check or search of code). The\n * page opens on the Product map.\n */\n product?: boolean;\n /** Write the page even when the folder already holds one built from the same book. Default `false`. */\n force?: boolean;\n};\n\n/** What `exportGrimoireSite()` did. */\nexport type GrimoireSiteExport = {\n /** The output folder, project-relative. */\n outDir: string;\n /** `true` when the folder already held a page built from the same book and nothing was written. */\n upToDate: boolean;\n};\n\n/** The most files the export keeps per-file answers for (the most imported first). */\nexport const SITE_FILE_LIMIT = 3000;\n\n/** One entry of the exported search list. `text` is written content (a flow's summary, story, cases and criteria) the search also reads. */\ntype SearchItem = { type: string; id: string; detail: string | null; text?: string };\n\n/** The written text of a flow the exported search reads, with criteria ids so `AC-5` is findable. */\nfunction flowSearchText(flow: WrittenFlow): string {\n return [\n flow.summary ?? \"\",\n ...flow.story.map((step) => step.text),\n ...flow.cases.map((item) => `${item.question} ${item.answer} ${item.criteria.join(\" \")}`),\n ...flow.criteria.map((item) => `${item.id} ${item.text}`),\n ]\n .filter((part) => part !== \"\")\n .join(\" | \");\n}\n\nconst uiFolder = fileURLToPath(new URL(\"../../ui/\", import.meta.url));\n\n/** Every answer the static page can give, keyed by the data route it replaces. */\nexport function buildSiteData(snapshot: GrimoireSnapshot) {\n const routes: Record<string, unknown> = {\n summary: data.summary(snapshot),\n features: data.features(snapshot),\n apps: data.apps(snapshot),\n tasks: data.tasks(snapshot),\n releases: data.releases(snapshot),\n // The page is meant to be shared: it does not name where the project sits on this machine.\n check: { ...data.check(snapshot), root: \".\" },\n \"graph/modules\": data.graphOfModules(snapshot),\n // The page is read-only: no Approve or Reject buttons.\n matrix: { ...matrix(snapshot), development: false },\n };\n // The static page is the signed-in view: developer detail stays, and no monitor reports errors.\n const productOptions = { shared: false, errors: null } as const;\n const productAnswer = attempt(() => productMap(snapshot, productOptions));\n const groups = attempt(() => data.checkGroups(snapshot));\n\n if (productAnswer !== undefined) routes.product = productAnswer;\n\n const whatsNew = attempt(() => productWhatsNew(snapshot, productOptions));\n\n if (whatsNew !== undefined) routes[\"product/whats-new\"] = whatsNew;\n\n if (groups !== undefined) routes[\"check/groups\"] = groups;\n\n const search: SearchItem[] = [];\n\n for (const release of snapshot.written.releases) {\n routes[`releases/${release.release.value}`] = release;\n }\n\n for (const feature of snapshot.written.features) {\n const readme = feature.readme;\n\n search.push({\n type: \"feature\",\n id: feature.id,\n detail: readme?.title.value ?? null,\n text: [readme?.summary ?? \"\", readme?.why ?? \"\"].filter((part) => part !== \"\").join(\" | \"),\n });\n const answered = attempt(() => data.feature(snapshot, feature.id));\n\n if (answered !== undefined) routes[`features/${feature.id}`] = answered;\n\n const graph = featureGraph(snapshot, feature.id);\n\n if (graph !== null) routes[`graph/feature/${feature.id}`] = graph;\n\n const product = attempt(() => productFeature(snapshot, feature.id, productOptions));\n\n if (product !== undefined) routes[`product/features/${feature.id}`] = product;\n\n for (const flow of feature.flows) {\n search.push({\n type: \"flow\",\n id: flow.ref,\n detail: flow.heading?.value ?? null,\n text: flowSearchText(flow),\n });\n const flowAnswer = attempt(() => data.flowAnswer(snapshot, feature.id, flow.id.value));\n const productFlowAnswer = attempt(() =>\n productFlow(snapshot, feature.id, flow.id.value, productOptions),\n );\n\n if (flowAnswer !== undefined) routes[`flows/${flow.ref}`] = flowAnswer;\n\n if (productFlowAnswer !== undefined) routes[`product/flows/${flow.ref}`] = productFlowAnswer;\n }\n }\n\n for (const app of snapshot.written.apps) {\n const appId = app.id.value;\n\n for (const page of [...app.pages, ...app.screens]) {\n const route = page.route?.value ?? page.screen?.value ?? null;\n const answer = attempt(() => data.page(snapshot, appId, page.id));\n const graph = pageGraph(snapshot, appId, page.id);\n\n for (const key of new Set([page.id, ...(route === null ? [] : [route])])) {\n if (answer !== undefined) routes[`apps/${appId}/pages/${key}`] = answer;\n\n if (graph !== null) routes[`graph/page/${appId}/${key}`] = graph;\n }\n\n if (route !== null)\n search.push({\n type: page.type,\n id: `${appId} ${route}`,\n detail: page.heading?.value ?? null,\n });\n\n for (const block of page.blockFiles) {\n search.push({\n type: \"block\",\n id: `${appId}/${page.id}/${block.id}`,\n detail: block.flow?.value ?? null,\n });\n }\n }\n }\n\n for (const found of snapshot.book.facts.routes ?? []) {\n search.push({\n type: \"route\",\n id: `${found.method} ${found.path}`,\n detail: found.description ?? found.handler,\n });\n }\n\n for (const task of snapshot.collected.tasksIndex.open.concat(\n snapshot.collected.tasksIndex.done,\n )) {\n search.push({ type: \"task\", id: task.id, detail: task.title });\n }\n\n const files: Record<string, { result: unknown; graph: unknown }> = {};\n const ranked = [...snapshot.book.facts.files].sort(\n (left, right) =>\n right.importedBy.length - left.importedBy.length || left.file.localeCompare(right.file),\n );\n\n for (const [index, file] of ranked.entries()) {\n search.push({ type: \"file\", id: file.file, detail: file.about });\n\n if (index >= SITE_FILE_LIMIT) continue;\n\n const result = attempt(() => data.file(snapshot, file.file));\n\n if (result !== undefined) files[file.file] = { result, graph: fileGraph(snapshot, file.file) };\n }\n\n return { routes, files, search };\n}\n\n/**\n * The business-only data of the static export: the share-safe Product map, its feature\n * and flow pages, and nothing else. No file paths, test names, export names, check\n * findings or per-file answers; the search list is empty.\n */\nexport function buildProductSiteData(snapshot: GrimoireSnapshot) {\n const options = { shared: true, errors: null } as const;\n const routes: Record<string, unknown> = {};\n const map = attempt(() => productMap(snapshot, options));\n\n if (map !== undefined) routes.product = map;\n\n const whatsNew = attempt(() => productWhatsNew(snapshot, options));\n\n if (whatsNew !== undefined) routes[\"product/whats-new\"] = whatsNew;\n\n for (const feature of snapshot.written.features) {\n const answer = attempt(() => productFeature(snapshot, feature.id, options));\n\n if (answer !== undefined) routes[`product/features/${feature.id}`] = answer;\n\n for (const flow of feature.flows) {\n const flowAnswer = attempt(() => productFlow(snapshot, feature.id, flow.id.value, options));\n\n if (flowAnswer !== undefined) routes[`product/flows/${flow.ref}`] = flowAnswer;\n }\n }\n\n return { routes, files: {}, search: [] as SearchItem[] };\n}\n\n/** JSON for an inline `<script>`: every `<` is escaped, so no `</script` or `<!--` can appear. */\nfunction inlineJson(value: unknown): string {\n return JSON.stringify(value).replaceAll(\"<\", \"\\\\u003c\");\n}\n\n/** Code for an inline `<script>`: `</script` (in any case) and `<!--` (only possible in strings and comments) are broken up. */\nfunction inlineCode(code: string): string {\n return code.replace(/<\\/(script)/gi, \"<\\\\/$1\").replaceAll(\"<!--\", \"<\\\\!--\");\n}\n\n/** The image types the export copies (the same list the devtools panel serves). */\nconst SCREENSHOT_EXTENSIONS = new Set([\".png\", \".jpg\", \".jpeg\", \".webp\", \".gif\"]);\n\n/** Every `WrittenScreenshot.path` in the written files, once each. */\nexport function collectScreenshotPaths(written: unknown): string[] {\n const found = new Set<string>();\n const walk = (value: unknown): void => {\n if (Array.isArray(value)) {\n for (const item of value) walk(item);\n } else if (value !== null && typeof value === \"object\") {\n const record = value as Record<string, unknown>;\n\n if (\n typeof record.path === \"string\" &&\n typeof record.written === \"string\" &&\n typeof record.alt === \"string\"\n )\n found.add(record.path);\n\n for (const item of Object.values(record)) walk(item);\n }\n };\n\n walk(written);\n\n return [...found].sort();\n}\n\n/**\n * Copy the screenshots the written files use into `<out>/screenshots/`. A path that leaves\n * `grimoire/screenshots/`, has another extension or does not exist is skipped.\n *\n * @returns The paths that were copied.\n */\nexport async function copyScreenshots(\n root: string,\n outFolder: string,\n paths: readonly string[],\n): Promise<string[]> {\n const folder = await realpath(path.join(root, GRIMOIRE_PATHS.screenshots)).catch(() => null);\n const copied: string[] = [];\n\n if (folder === null) return copied;\n\n for (const written of paths) {\n const segments = written.split(\"/\");\n\n if (\n written === \"\" ||\n written.includes(\"\\\\\") ||\n written.includes(\"\\0\") ||\n path.isAbsolute(written) ||\n segments.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\") ||\n !SCREENSHOT_EXTENSIONS.has(path.extname(written).toLowerCase())\n )\n continue;\n\n const source = await realpath(path.join(folder, ...segments)).catch(() => null);\n\n if (source === null || !source.startsWith(folder + path.sep)) continue;\n\n if (!(await stat(source)).isFile()) continue;\n\n const target = path.join(outFolder, \"screenshots\", ...segments);\n\n await mkdir(path.dirname(target), { recursive: true });\n await copyFile(source, target);\n copied.push(written);\n }\n\n return copied;\n}\n\n/** The answer, or `undefined` when the item cannot be answered (the export skips it). */\nfunction attempt<Value>(answer: () => Value): Value | undefined {\n try {\n return answer();\n } catch {\n return undefined;\n }\n}\n\n/** Everything before the page's `export default`, so the view can sit in an inline module. */\nexport function inlineView(source: string): string {\n const marker = \"export default renderGrimoire;\";\n\n if (!source.includes(marker))\n throw new Error(\"grimoire-view.js must end with `export default renderGrimoire;`.\");\n\n return source.replace(marker, \"\");\n}\n\n/**\n * The product map module as inline code: its `export` keywords are removed and the Grimoire view\n * finds it as `globalThis.grimoireProductMap`.\n */\nexport function inlineProductMap(source: string): string {\n const marker = \"export default renderProductMap;\";\n\n if (!source.includes(marker))\n throw new Error(\"product-map.js must end with `export default renderProductMap;`.\");\n\n return `${source.replace(marker, \"\").replace(/^export (async )?function /gm, \"$1function \")}\\nglobalThis.grimoireProductMap = { productMapView };\\n`;\n}\n\n/**\n * The page's own styles: it defines every devtools panel token (light, then dark under\n * `prefers-color-scheme`), so `grimoire.css` renders the same here as in the dashboard.\n * The values keep text AA on `--background` and `--card`.\n */\nexport const PAGE_STYLE = `\n:root{color-scheme:light dark;--background:#faf8f2;--foreground:#1a1814;--card:#fff;--card-foreground:#1a1814;--popover:#fff;--popover-foreground:#1a1814;--primary:#1a1814;--primary-foreground:#faf8f2;--secondary:#f0ece0;--secondary-foreground:#1a1814;--muted:#f0ece0;--muted-foreground:#5c574b;--accent:#f3ecd6;--accent-foreground:#1a1814;--destructive:#b42318;--border:#e0d9c6;--input:#d2cab3;--ring:#8a5a00;--radius:10px;--brand:#8a5a00;--brand-foreground:#fff;--success:#13693b;--warning:#8a5300;--info:#0b66a3;--chart-1:#8a5a00;--chart-2:#13693b;--chart-3:#0b66a3;--chart-4:#6d3ac7;--chart-5:#b4306b;font-family:system-ui,-apple-system,\"Segoe UI\",sans-serif}\n@media (prefers-color-scheme:dark){:root{--background:#0b0b0c;--foreground:#f2f2ee;--card:#141416;--card-foreground:#f2f2ee;--popover:#141416;--popover-foreground:#f2f2ee;--primary:#ffc61a;--primary-foreground:#1a1300;--secondary:#1f1f22;--secondary-foreground:#f2f2ee;--muted:#1f1f22;--muted-foreground:#a9a9b0;--accent:#26262a;--accent-foreground:#f2f2ee;--destructive:#ff8f86;--border:#2a2a2e;--input:#34343a;--ring:#ffc61a;--radius:10px;--brand:#ffc61a;--brand-foreground:#1a1300;--success:#5fd391;--warning:#f3a24a;--info:#6cc0f5;--chart-1:#ffc61a;--chart-2:#5fd391;--chart-3:#6cc0f5;--chart-4:#b79cff;--chart-5:#ff8fbd}}\n*{box-sizing:border-box}body{margin:0;background:var(--background);color:var(--foreground);font-size:14px;line-height:1.5}\nmain{max-width:1180px;margin:0 auto;padding:16px}\n.empty{padding:12px;color:var(--muted-foreground)}.error{padding:12px;color:var(--destructive)}\n`;\n\n/** The `index.html` text. */\nexport function renderSiteHtml(\n siteData: unknown,\n sources: {\n view: string;\n loader: string;\n css: string;\n productMap?: string;\n productCss?: string;\n /** Mount the share-safe Product map alone (the business export): `view` and `css` are not inlined. */\n product?: boolean;\n /** A freshness stamp written into the page, so the next export can tell it is current. */\n stamp?: string;\n },\n): string {\n const json = inlineJson(siteData);\n\n if (sources.product === true && sources.productMap === undefined) {\n throw new Error(\"A product export needs product-map.js.\");\n }\n\n const mounted = sources.product === true ? \"renderProductMap\" : \"renderGrimoire\";\n const script = inlineCode(\n `${sources.productMap === undefined ? \"\" : inlineProductMap(sources.productMap)}${sources.product === true ? \"\" : inlineView(sources.view)}\\n${sources.loader}\\ngrimoireStaticMount(JSON.parse(document.getElementById(\"grimoire-data\").textContent), document.getElementById(\"grimoire-root\"), ${mounted});\\n`,\n );\n const styles = sources.product === true ? \"\" : sources.css;\n const stamp =\n sources.stamp === undefined ? \"\" : `<meta name=\"grimoire-stamp\" content=\"${sources.stamp}\">\\n`;\n\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n${stamp}<title>${sources.product === true ? \"Product map\" : \"Grimoire\"}</title>\n<style>${PAGE_STYLE}${styles}${sources.productCss ?? \"\"}</style>\n</head>\n<body>\n<main id=\"grimoire-root\"><p class=\"empty\">Opening the book…</p></main>\n<script type=\"application/json\" id=\"grimoire-data\">${json}</script>\n<script type=\"module\">${script}</script>\n</body>\n</html>\n`;\n}\n\n/** The stamp is written near the top of the page; this much of the file is enough to find it. */\nconst STAMP_HEAD_BYTES = 2048;\n\n/** The stamp of the page that is already in `index.html`, or `null` (no page, or one without a stamp). */\nasync function writtenStamp(file: string): Promise<string | null> {\n let handle;\n\n try {\n handle = await open(file, \"r\");\n\n const { buffer, bytesRead } = await handle.read(\n Buffer.alloc(STAMP_HEAD_BYTES),\n 0,\n STAMP_HEAD_BYTES,\n 0,\n );\n\n return (\n /<meta name=\"grimoire-stamp\" content=\"([0-9a-f]+)\">/.exec(\n buffer.toString(\"utf8\", 0, bytesRead),\n )?.[1] ?? null\n );\n } catch {\n return null;\n } finally {\n await handle?.close();\n }\n}\n\n/** Modified times of the files the page is built from, so a new framework version rebuilds the page. */\nasync function uiStamp(): Promise<string> {\n const names = [\n \"grimoire-view.js\",\n \"grimoire-static.js\",\n \"grimoire.css\",\n \"product-map.js\",\n \"product-map.css\",\n ];\n const times = await Promise.all(\n names.map(async (name) => {\n try {\n return (await stat(path.join(uiFolder, name))).mtimeMs;\n } catch {\n return 0;\n }\n }),\n );\n\n return times.join(\",\");\n}\n\n/**\n * Write the tab as a static folder for people without the app running.\n *\n * The folder holds `index.html` only: the view, the loader, the styles and\n * the data (as JSON) are inside it, so it opens straight from disk. Open the\n * page and use `#grimoire/...` links; the answers that need the running app\n * (impact of a file) say so in place.\n *\n * With `product: true` the page is the business export: the share-safe\n * Product map only, no file paths, test names or per-file answers.\n *\n * The page carries a freshness stamp (the files of the book, the written\n * folders and the test results). When the folder already holds a page with\n * the same stamp and the same mode, nothing is rebuilt or written (`force`\n * writes it anyway).\n *\n * @param root Absolute project root.\n */\nexport async function exportGrimoireSiteDetailed(\n root: string,\n options: ExportGrimoireSiteOptions = {},\n): Promise<GrimoireSiteExport> {\n // Project-relative from here on; an absolute folder is kept where it is.\n const outDir = projectPath(\n root,\n toPosixPath(options.outDir ?? GRIMOIRE_PATHS.staticSite),\n ).replace(/\\/+$/, \"\");\n const snapshot =\n options.snapshot ??\n (await createSnapshotSource(\n root,\n options.adapter === undefined ? {} : { adapter: options.adapter },\n ).get());\n const absolute = path.resolve(root, outDir);\n const product = options.product === true;\n const stamp = createHash(\"sha1\")\n .update(`${product ? \"product\" : \"full\"}|${await stampOf(root, snapshot)}|${await uiStamp()}`)\n .digest(\"hex\");\n\n if (options.force !== true && (await writtenStamp(path.join(absolute, \"index.html\"))) === stamp) {\n return { outDir, upToDate: true };\n }\n\n const [view, loader, css, productMapSource, productCss] = await Promise.all(\n [\n \"grimoire-view.js\",\n \"grimoire-static.js\",\n \"grimoire.css\",\n \"product-map.js\",\n \"product-map.css\",\n ].map((name) => readFile(path.join(uiFolder, name), \"utf8\")),\n );\n const html = renderSiteHtml(product ? buildProductSiteData(snapshot) : buildSiteData(snapshot), {\n view: view ?? \"\",\n loader: loader ?? \"\",\n css: css ?? \"\",\n productMap: productMapSource ?? \"\",\n productCss: productCss ?? \"\",\n product,\n stamp,\n });\n\n await mkdir(absolute, { recursive: true });\n await writeFile(path.join(absolute, \"index.html\"), html);\n // The business export carries no bird-view, so it does not carry the captured and approved images either.\n await copyScreenshots(root, absolute, [\n ...collectScreenshotPaths(snapshot.written),\n ...(product ? [] : matrixImagePaths(matrix(snapshot))),\n ]);\n\n return { outDir, upToDate: false };\n}\n\n/** `exportGrimoireSiteDetailed()` that returns only the output folder, project-relative. */\nexport async function exportGrimoireSite(\n root: string,\n options: ExportGrimoireSiteOptions = {},\n): Promise<string> {\n return (await exportGrimoireSiteDetailed(root, options)).outDir;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+CA,MAAa,kBAAkB;;AAM/B,SAAS,eAAe,MAA2B;CACjD,OAAO;EACL,KAAK,WAAW;EAChB,GAAG,KAAK,MAAM,KAAK,SAAS,KAAK,IAAI;EACrC,GAAG,KAAK,MAAM,KAAK,SAAS,GAAG,KAAK,SAAS,GAAG,KAAK,OAAO,GAAG,KAAK,SAAS,KAAK,GAAG,GAAG;EACxF,GAAG,KAAK,SAAS,KAAK,SAAS,GAAG,KAAK,GAAG,GAAG,KAAK,MAAM;CAC1D,CAAC,CACE,QAAQ,SAAS,SAAS,EAAE,CAAC,CAC7B,KAAK,KAAK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,UAAU;EAClB,KAAK,OAAO;EACZ,YAAY,oBAAoB;EAChC,YAAY,cAAc;EAC1B;EACA;CACF,CAAC;CAED,MAAM,MAAM,UAAU,EAAE,WAAW,KAAK,CAAC;CACzC,MAAM,UAAU,KAAK,KAAK,UAAU,YAAY,GAAG,IAAI;CAEvD,MAAM,gBAAgB,MAAM,UAAU,CACpC,GAAG,uBAAuB,SAAS,OAAO,GAC1C,GAAI,UAAU,CAAC,IAAI,iBAAiB,OAAO,QAAQ,CAAC,CACtD,CAAC;CAED,OAAO;EAAE;EAAQ,UAAU;CAAM;AACnC;;AAGA,eAAsB,mBACpB,MACA,UAAqC,CAAC,GACrB;CACjB,QAAQ,MAAM,2BAA2B,MAAM,OAAO,EAAC,CAAE;AAC3D"}
@@ -1,6 +1,7 @@
1
1
  import { GRIMOIRE_PATHS } from "../paths/index.mjs";
2
2
  import { resolveResultsFile } from "../test-results/index.mjs";
3
3
  import { openGrimoire } from "../workspace/index.mjs";
4
+ import { openStoredGrimoire } from "../workspace/stored.mjs";
4
5
  import path from "node:path";
5
6
  import { stat } from "node:fs/promises";
6
7
 
@@ -14,7 +15,8 @@ import { stat } from "node:fs/promises";
14
15
  * facts (`liveFacts`, development), an edit to a file the route facts were read from reads them again from
15
16
  * the running app on the next open, so a route edit shows without `warlock grimoire build`.
16
17
  *
17
- * - Production (`mode: "production"`): a snapshot is reused until the stamp
18
+ * - Production (`mode: "production"`): the stored book is read when it is current (no build), otherwise the
19
+ * book is built in memory. A snapshot is reused until the stamp
18
20
  * changes, with no time limit, unless `ttlMs` is set. A request that finds
19
21
  * the stamp changed waits for the new open. `warm()` opens the book ahead
20
22
  * of the first request.
@@ -41,7 +43,11 @@ const STAMPED = [
41
43
  GRIMOIRE_PATHS.apps,
42
44
  GRIMOIRE_PATHS.openTasks,
43
45
  GRIMOIRE_PATHS.doneTasks,
44
- GRIMOIRE_PATHS.releases
46
+ GRIMOIRE_PATHS.releases,
47
+ GRIMOIRE_PATHS.settings,
48
+ GRIMOIRE_PATHS.approved,
49
+ GRIMOIRE_PATHS.baseline,
50
+ GRIMOIRE_PATHS.captureIndex
45
51
  ];
46
52
  /** The modified times of `files`, joined (`0` for a missing file). */
47
53
  async function timesOf(files) {
@@ -92,7 +98,11 @@ function createSnapshotSource(root, options = {}) {
92
98
  ...options.testResultsFile === void 0 ? {} : { testResultsFile: options.testResultsFile }
93
99
  };
94
100
  let snapshot;
95
- if (!liveCollected || refreshRoutes) {
101
+ if (options.mode === "production") try {
102
+ const stored = await openStoredGrimoire(root, adapter, openOptions);
103
+ if (stored.behind === void 0) snapshot = stored;
104
+ } catch {}
105
+ if (snapshot !== void 0) {} else if (!liveCollected || refreshRoutes) {
96
106
  liveCollected = true;
97
107
  refreshRoutes = false;
98
108
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"snapshot-source.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/devtools/snapshot-source.ts"],"sourcesContent":["/**\n * Where the panel's routes get the snapshot: opened once with\n * `routes: \"cached\"` (a devtools request never boots the app) and kept in\n * memory. Concurrent requests share one open. A change stamp (the book\n * manifest, the agent-written folders and indexes and the files the route\n * facts were read from, a few `stat` calls and no directory walk) tells when the book changed. With live\n * facts (`liveFacts`, development), an edit to a file the route facts were read from reads them again from\n * the running app on the next open, so a route edit shows without `warlock grimoire build`.\n *\n * - Production (`mode: \"production\"`): a snapshot is reused until the stamp\n * changes, with no time limit, unless `ttlMs` is set. A request that finds\n * the stamp changed waits for the new open. `warm()` opens the book ahead\n * of the first request.\n * - Development: the snapshot is reused for a short window (2 s, or five times\n * the last open when that is longer, so a slow open on a large app is not\n * repeated on every view; written files change while an agent works). A\n * request that finds the stamp changed waits for the new open. After the\n * window, with the stamp unchanged (a file edited in place), the cached\n * snapshot is served at once and one background open refreshes it (stale\n * while revalidate).\n *\n * An open that fails keeps serving the old snapshot; its error surfaces on a\n * request only when there is no snapshot at all. The panel passes\n * `write: true` in development, so the generated book stays current and the\n * next open is incremental; with `write: false` a stored book behind the\n * sources is rebuilt in memory on every open.\n */\nimport { stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport { GRIMOIRE_PATHS } from \"../paths\";\nimport { resolveResultsFile } from \"../test-results\";\nimport { openGrimoire } from \"../workspace\";\n\n/** Options of the panel's snapshot source. */\nexport type SnapshotSourceOptions = {\n /** The adapter, or a function that loads it. Default: the Warlock adapter, imported on first use. */\n adapter?: BookAdapter | (() => Promise<BookAdapter>);\n /**\n * How long a snapshot is reused when the book did not change (ms).\n * Default in development: 2000, or five times as long as the last open took\n * when that is longer. Default in production: no limit (reused until the\n * book changes).\n */\n ttlMs?: number;\n /** Where the source runs. `\"production\"` keeps a snapshot until the book changes. Default: `\"development\"`. */\n mode?: \"development\" | \"production\";\n /** Let `openGrimoire` write the generated book and collected files (never agent-written files). Default `false`; the devtools panel passes `true`. */\n write?: boolean;\n /**\n * Where the test results are read from (project-relative or absolute).\n * Default `grimoire/book/test-results.json`. The file's modified time is part\n * of the change stamp, so results written after the snapshot opened show up\n * without a restart.\n */\n testResultsFile?: string;\n /**\n * Read the route facts once when the first open finds none (`routes: \"missing\"`), so the development tab is\n * never \"missing\" without a manual `warlock grimoire build`. The adapter's booted inspect runs at most once per\n * process; a boot that fails keeps the cached answer. Default `false`. Never set it in a process that serves the app: the boot\n * pass boots every connector and re-imports the route and event modules, which registers them twice. The devtools panel\n * does not set it; use it from a separate tool process.\n */\n collectRoutes?: boolean;\n /**\n * The adapter reads the route, event and job facts from the running process (`createWarlockAdapter({ live: true })`),\n * which is cheap and boots nothing. The first open then collects them in the same pass as the book\n * (`routes: \"fresh\"`), so the tab never opens \"missing\" and the first open runs once. Safe in the process that\n * serves the app. Default `false`; the devtools panel sets it in development with the Warlock adapter.\n */\n liveFacts?: boolean;\n};\n\n/** A cached, shared snapshot of one project. */\nexport type SnapshotSource = {\n get(): Promise<GrimoireSnapshot>;\n /** Forget the cached snapshot; the next `get()` opens again. */\n invalidate(): void;\n /** Start opening the book now, so the first `get()` is fast. Failures are ignored here and surface on `get()`. */\n warm(): void;\n /** Resolves when no open is running (specs and shutdown). Never rejects. */\n idle(): Promise<void>;\n};\n\n/** Files and folders whose modified time moves when the book or an agent-written file is added, removed or regenerated. */\nconst STAMPED = [\n GRIMOIRE_PATHS.bookManifest,\n GRIMOIRE_PATHS.featuresIndex,\n GRIMOIRE_PATHS.tasksIndex,\n GRIMOIRE_PATHS.features,\n GRIMOIRE_PATHS.apps,\n GRIMOIRE_PATHS.openTasks,\n GRIMOIRE_PATHS.doneTasks,\n GRIMOIRE_PATHS.releases,\n];\n\n/** The modified times of `files`, joined (`0` for a missing file). */\nasync function timesOf(files: string[]): Promise<string> {\n const times = await Promise.all(\n files.map(async (file) => {\n try {\n return (await stat(file)).mtimeMs;\n } catch {\n return 0;\n }\n }),\n );\n\n return times.join(\",\");\n}\n\n/**\n * The change stamp in two parts: `book` (the book manifest, the written folders, the results file) and `routes`\n * (the project-relative files the route facts were read from, `manifest.boot.inputs`). An edit to a route input\n * ends the reuse window; with live facts the next open reads the routes again, otherwise it reports them stale.\n */\nasync function changeStamp(\n root: string,\n resultsFile: string,\n routeInputs: string[] = [],\n): Promise<{ book: string; routes: string }> {\n const [book, routes] = await Promise.all([\n timesOf([...STAMPED.map((entry) => path.join(root, ...entry.split(\"/\"))), resultsFile]),\n timesOf(routeInputs.map((file) => path.join(root, ...file.split(\"/\")))),\n ]);\n\n return { book, routes };\n}\n\nconst routeInputsOf = (snapshot: GrimoireSnapshot): string[] =>\n Object.keys(snapshot.book.manifest.boot.inputs).sort();\n\nasync function loadAdapter(option: SnapshotSourceOptions[\"adapter\"]): Promise<BookAdapter> {\n if (option === undefined) {\n const { createWarlockAdapter } = await import(\"../warlock\");\n\n return createWarlockAdapter();\n }\n\n return typeof option === \"function\" ? option() : option;\n}\n\n/** Create the source for the project at `root`. */\nexport function createSnapshotSource(\n root: string,\n options: SnapshotSourceOptions = {},\n): SnapshotSource {\n let cached: {\n snapshot: GrimoireSnapshot;\n at: number;\n stamp: { book: string; routes: string };\n took: number;\n } | null = null;\n let opening: Promise<GrimoireSnapshot> | null = null;\n\n const live = options.liveFacts === true && options.mode !== \"production\";\n let collected = options.collectRoutes !== true || options.mode === \"production\";\n let liveCollected = !live;\n // Set when a route input changed: with live facts, the next open reads the routes from the running app again.\n let refreshRoutes = false;\n const resultsFile = resolveResultsFile(root, options.testResultsFile);\n\n const keepUntilChanged = options.mode === \"production\" && options.ttlMs === undefined;\n const reuseFor = (took: number): number => options.ttlMs ?? Math.max(2000, took * 5);\n\n async function open(): Promise<GrimoireSnapshot> {\n const started = Date.now();\n const adapter = await loadAdapter(options.adapter);\n const openOptions = {\n write: options.write ?? false,\n ...(options.testResultsFile === undefined\n ? {}\n : { testResultsFile: options.testResultsFile }),\n };\n let snapshot: GrimoireSnapshot;\n\n if (!liveCollected || refreshRoutes) {\n // One pass: the book and the live route facts together, so a first open never builds twice.\n // After a routes-file edit: the dev server reloads the file on save, so the live read sees its new routes.\n liveCollected = true;\n refreshRoutes = false;\n\n try {\n snapshot = await openGrimoire(root, adapter, { routes: \"fresh\", ...openOptions });\n } catch {\n // The facts could not be read: fall back to what the book already holds.\n snapshot = await openGrimoire(root, adapter, { routes: \"cached\", ...openOptions });\n }\n } else {\n snapshot = await openGrimoire(root, adapter, { routes: \"cached\", ...openOptions });\n }\n\n if (!collected && snapshot.routes === \"missing\") {\n // Once per source: the route, event and job facts come from one boot pass, then live in the book.\n collected = true;\n\n try {\n snapshot = await openGrimoire(root, adapter, { routes: \"fresh\", ...openOptions });\n } catch {\n // The app did not boot (GR8002): keep the cached answer; the tab says the facts are missing.\n }\n }\n\n const at = Date.now();\n\n cached = {\n snapshot,\n at,\n stamp: await changeStamp(root, resultsFile, routeInputsOf(snapshot)),\n took: at - started,\n };\n\n return snapshot;\n }\n\n /** The open in flight, or a new one; concurrent callers share it. */\n function ensureOpening(): Promise<GrimoireSnapshot> {\n opening ??= open().finally(() => {\n opening = null;\n });\n\n return opening;\n }\n\n return {\n async get() {\n if (cached === null) return ensureOpening();\n\n const known = cached;\n const stamp = await changeStamp(root, resultsFile, routeInputsOf(known.snapshot));\n const routesMoved = stamp.routes !== known.stamp.routes;\n const changed = routesMoved || stamp.book !== known.stamp.book;\n\n if (routesMoved && live) refreshRoutes = true;\n\n if (changed || options.mode === \"production\") {\n if (!changed && (keepUntilChanged || Date.now() - known.at < reuseFor(known.took))) {\n return known.snapshot;\n }\n\n // A failed open keeps the old snapshot; the next request tries again.\n return ensureOpening().catch(() => known.snapshot);\n }\n\n if (Date.now() - known.at < reuseFor(known.took)) return known.snapshot;\n\n // Development, nothing known to have changed: serve the old snapshot now and refresh behind it.\n ensureOpening().catch(() => {});\n\n return known.snapshot;\n },\n invalidate() {\n cached = null;\n },\n warm() {\n if (cached === null) ensureOpening().catch(() => {});\n },\n async idle() {\n await opening?.catch(() => {});\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsFA,MAAM,UAAU;CACd,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;AACjB;;AAGA,eAAe,QAAQ,OAAkC;CAWvD,QAAO,MAVa,QAAQ,IAC1B,MAAM,IAAI,OAAO,SAAS;EACxB,IAAI;GACF,QAAQ,MAAM,KAAK,IAAI,EAAC,CAAE;EAC5B,QAAQ;GACN,OAAO;EACT;CACF,CAAC,CACH,EAEY,CAAC,KAAK,GAAG;AACvB;;;;;;AAOA,eAAe,YACb,MACA,aACA,cAAwB,CAAC,GACkB;CAC3C,MAAM,CAAC,MAAM,UAAU,MAAM,QAAQ,IAAI,CACvC,QAAQ,CAAC,GAAG,QAAQ,KAAK,UAAU,KAAK,KAAK,MAAM,GAAG,MAAM,MAAM,GAAG,CAAC,CAAC,GAAG,WAAW,CAAC,GACtF,QAAQ,YAAY,KAAK,SA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O;GACX,MAAM,SAAS,YAAY,CAAC,CAAC;EAC/B;CACF;AACF"}
1
+ {"version":3,"file":"snapshot-source.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/devtools/snapshot-source.ts"],"sourcesContent":["/**\n * Where the panel's routes get the snapshot: opened once with\n * `routes: \"cached\"` (a devtools request never boots the app) and kept in\n * memory. Concurrent requests share one open. A change stamp (the book\n * manifest, the agent-written folders and indexes and the files the route\n * facts were read from, a few `stat` calls and no directory walk) tells when the book changed. With live\n * facts (`liveFacts`, development), an edit to a file the route facts were read from reads them again from\n * the running app on the next open, so a route edit shows without `warlock grimoire build`.\n *\n * - Production (`mode: \"production\"`): the stored book is read when it is current (no build), otherwise the\n * book is built in memory. A snapshot is reused until the stamp\n * changes, with no time limit, unless `ttlMs` is set. A request that finds\n * the stamp changed waits for the new open. `warm()` opens the book ahead\n * of the first request.\n * - Development: the snapshot is reused for a short window (2 s, or five times\n * the last open when that is longer, so a slow open on a large app is not\n * repeated on every view; written files change while an agent works). A\n * request that finds the stamp changed waits for the new open. After the\n * window, with the stamp unchanged (a file edited in place), the cached\n * snapshot is served at once and one background open refreshes it (stale\n * while revalidate).\n *\n * An open that fails keeps serving the old snapshot; its error surfaces on a\n * request only when there is no snapshot at all. The panel passes\n * `write: true` in development, so the generated book stays current and the\n * next open is incremental; with `write: false` a stored book behind the\n * sources is rebuilt in memory on every open.\n */\nimport { stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport { GRIMOIRE_PATHS } from \"../paths\";\nimport { resolveResultsFile } from \"../test-results\";\nimport { openGrimoire } from \"../workspace\";\nimport { openStoredGrimoire } from \"../workspace/stored\";\n\n/** Options of the panel's snapshot source. */\nexport type SnapshotSourceOptions = {\n /** The adapter, or a function that loads it. Default: the Warlock adapter, imported on first use. */\n adapter?: BookAdapter | (() => Promise<BookAdapter>);\n /**\n * How long a snapshot is reused when the book did not change (ms).\n * Default in development: 2000, or five times as long as the last open took\n * when that is longer. Default in production: no limit (reused until the\n * book changes).\n */\n ttlMs?: number;\n /** Where the source runs. `\"production\"` keeps a snapshot until the book changes. Default: `\"development\"`. */\n mode?: \"development\" | \"production\";\n /** Let `openGrimoire` write the generated book and collected files (never agent-written files). Default `false`; the devtools panel passes `true`. */\n write?: boolean;\n /**\n * Where the test results are read from (project-relative or absolute).\n * Default `grimoire/book/test-results.json`. The file's modified time is part\n * of the change stamp, so results written after the snapshot opened show up\n * without a restart.\n */\n testResultsFile?: string;\n /**\n * Read the route facts once when the first open finds none (`routes: \"missing\"`), so the development tab is\n * never \"missing\" without a manual `warlock grimoire build`. The adapter's booted inspect runs at most once per\n * process; a boot that fails keeps the cached answer. Default `false`. Never set it in a process that serves the app: the boot\n * pass boots every connector and re-imports the route and event modules, which registers them twice. The devtools panel\n * does not set it; use it from a separate tool process.\n */\n collectRoutes?: boolean;\n /**\n * The adapter reads the route, event and job facts from the running process (`createWarlockAdapter({ live: true })`),\n * which is cheap and boots nothing. The first open then collects them in the same pass as the book\n * (`routes: \"fresh\"`), so the tab never opens \"missing\" and the first open runs once. Safe in the process that\n * serves the app. Default `false`; the devtools panel sets it in development with the Warlock adapter.\n */\n liveFacts?: boolean;\n};\n\n/** A cached, shared snapshot of one project. */\nexport type SnapshotSource = {\n get(): Promise<GrimoireSnapshot>;\n /** Forget the cached snapshot; the next `get()` opens again. */\n invalidate(): void;\n /** Start opening the book now, so the first `get()` is fast. Failures are ignored here and surface on `get()`. */\n warm(): void;\n /** Resolves when no open is running (specs and shutdown). Never rejects. */\n idle(): Promise<void>;\n};\n\n/** Files and folders whose modified time moves when the book or an agent-written file is added, removed or regenerated. */\nconst STAMPED = [\n GRIMOIRE_PATHS.bookManifest,\n GRIMOIRE_PATHS.featuresIndex,\n GRIMOIRE_PATHS.tasksIndex,\n GRIMOIRE_PATHS.features,\n GRIMOIRE_PATHS.apps,\n GRIMOIRE_PATHS.openTasks,\n GRIMOIRE_PATHS.doneTasks,\n GRIMOIRE_PATHS.releases,\n // Settings, the approved baseline and the capture index change what the tab shows.\n GRIMOIRE_PATHS.settings,\n GRIMOIRE_PATHS.approved,\n GRIMOIRE_PATHS.baseline,\n GRIMOIRE_PATHS.captureIndex,\n];\n\n/** The modified times of `files`, joined (`0` for a missing file). */\nasync function timesOf(files: string[]): Promise<string> {\n const times = await Promise.all(\n files.map(async (file) => {\n try {\n return (await stat(file)).mtimeMs;\n } catch {\n return 0;\n }\n }),\n );\n\n return times.join(\",\");\n}\n\n/**\n * The change stamp in two parts: `book` (the book manifest, the written folders, the results file) and `routes`\n * (the project-relative files the route facts were read from, `manifest.boot.inputs`). An edit to a route input\n * ends the reuse window; with live facts the next open reads the routes again, otherwise it reports them stale.\n */\nasync function changeStamp(\n root: string,\n resultsFile: string,\n routeInputs: string[] = [],\n): Promise<{ book: string; routes: string }> {\n const [book, routes] = await Promise.all([\n timesOf([...STAMPED.map((entry) => path.join(root, ...entry.split(\"/\"))), resultsFile]),\n timesOf(routeInputs.map((file) => path.join(root, ...file.split(\"/\")))),\n ]);\n\n return { book, routes };\n}\n\nconst routeInputsOf = (snapshot: GrimoireSnapshot): string[] =>\n Object.keys(snapshot.book.manifest.boot.inputs).sort();\n\nasync function loadAdapter(option: SnapshotSourceOptions[\"adapter\"]): Promise<BookAdapter> {\n if (option === undefined) {\n const { createWarlockAdapter } = await import(\"../warlock\");\n\n return createWarlockAdapter();\n }\n\n return typeof option === \"function\" ? option() : option;\n}\n\n/** Create the source for the project at `root`. */\nexport function createSnapshotSource(\n root: string,\n options: SnapshotSourceOptions = {},\n): SnapshotSource {\n let cached: {\n snapshot: GrimoireSnapshot;\n at: number;\n stamp: { book: string; routes: string };\n took: number;\n } | null = null;\n let opening: Promise<GrimoireSnapshot> | null = null;\n\n const live = options.liveFacts === true && options.mode !== \"production\";\n let collected = options.collectRoutes !== true || options.mode === \"production\";\n let liveCollected = !live;\n // Set when a route input changed: with live facts, the next open reads the routes from the running app again.\n let refreshRoutes = false;\n const resultsFile = resolveResultsFile(root, options.testResultsFile);\n\n const keepUntilChanged = options.mode === \"production\" && options.ttlMs === undefined;\n const reuseFor = (took: number): number => options.ttlMs ?? Math.max(2000, took * 5);\n\n async function open(): Promise<GrimoireSnapshot> {\n const started = Date.now();\n const adapter = await loadAdapter(options.adapter);\n const openOptions = {\n write: options.write ?? false,\n ...(options.testResultsFile === undefined\n ? {}\n : { testResultsFile: options.testResultsFile }),\n };\n let snapshot: GrimoireSnapshot | undefined;\n\n // Production reads the stored book when it is current: no build, so the first view is fast.\n if (options.mode === \"production\") {\n try {\n const stored = await openStoredGrimoire(root, adapter, openOptions);\n\n if (stored.behind === undefined) snapshot = stored;\n } catch {\n // No book, or one from another version: build it in memory below.\n }\n }\n\n if (snapshot !== undefined) {\n // The stored book answers as it is.\n } else if (!liveCollected || refreshRoutes) {\n // One pass: the book and the live route facts together, so a first open never builds twice.\n // After a routes-file edit: the dev server reloads the file on save, so the live read sees its new routes.\n liveCollected = true;\n refreshRoutes = false;\n\n try {\n snapshot = await openGrimoire(root, adapter, { routes: \"fresh\", ...openOptions });\n } catch {\n // The facts could not be read: fall back to what the book already holds.\n snapshot = await openGrimoire(root, adapter, { routes: \"cached\", ...openOptions });\n }\n } else {\n snapshot = await openGrimoire(root, adapter, { routes: \"cached\", ...openOptions });\n }\n\n if (!collected && snapshot.routes === \"missing\") {\n // Once per source: the route, event and job facts come from one boot pass, then live in the book.\n collected = true;\n\n try {\n snapshot = await openGrimoire(root, adapter, { routes: \"fresh\", ...openOptions });\n } catch {\n // The app did not boot (GR8002): keep the cached answer; the tab says the facts are missing.\n }\n }\n\n const at = Date.now();\n\n cached = {\n snapshot,\n at,\n stamp: await changeStamp(root, resultsFile, routeInputsOf(snapshot)),\n took: at - started,\n };\n\n return snapshot;\n }\n\n /** The open in flight, or a new one; concurrent callers share it. */\n function ensureOpening(): Promise<GrimoireSnapshot> {\n opening ??= open().finally(() => {\n opening = null;\n });\n\n return opening;\n }\n\n return {\n async get() {\n if (cached === null) return ensureOpening();\n\n const known = cached;\n const stamp = await changeStamp(root, resultsFile, routeInputsOf(known.snapshot));\n const routesMoved = stamp.routes !== known.stamp.routes;\n const changed = routesMoved || stamp.book !== known.stamp.book;\n\n if (routesMoved && live) refreshRoutes = true;\n\n if (changed || options.mode === \"production\") {\n if (!changed && (keepUntilChanged || Date.now() - known.at < reuseFor(known.took))) {\n return known.snapshot;\n }\n\n // A failed open keeps the old snapshot; the next request tries again.\n return ensureOpening().catch(() => known.snapshot);\n }\n\n if (Date.now() - known.at < reuseFor(known.took)) return known.snapshot;\n\n // Development, nothing known to have changed: serve the old snapshot now and refresh behind it.\n ensureOpening().catch(() => {});\n\n return known.snapshot;\n },\n invalidate() {\n cached = null;\n },\n warm() {\n if (cached === null) ensureOpening().catch(() => {});\n },\n async idle() {\n await opening?.catch(() => {});\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwFA,MAAM,UAAU;CACd,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CAEf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;AACjB;;AAGA,eAAe,QAAQ,OAAkC;CAWvD,QAAO,MAVa,QAAQ,IAC1B,MAAM,IAAI,OAAO,SAAS;EACxB,IAAI;GACF,QAAQ,MAAM,KAAK,IAAI,EAAC,CAAE;EAC5B,QAAQ;GACN,OAAO;EACT;CACF,CAAC,CACH,EAEY,CAAC,KAAK,GAAG;AACvB;;;;;;AAOA,eAAe,YACb,MACA,aACA,cAAwB,CAAC,GACkB;CAC3C,MAAM,CAAC,MAAM,UAAU,MAAM,QAAQ,IAAI,CACvC,QAAQ,CAAC,GAAG,QAAQ,KAAK,UAAU,KAAK,KAAK,MAAM,GAAG,MAAM,MAAM,GAAG,CAAC,CAAC,GAAG,WAAW,CAAC,GACtF,QAAQ,YAAY,KAA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,cAAc,CAAC,CAAC,YAAY,CAAC,CAAC;GAE9B,OAAO,MAAM;EACf;EACA,aAAa;GACX,SAAS;EACX;EACA,OAAO;GACL,IAAI,WAAW,MAAM,cAAc,CAAC,CAAC,YAAY,CAAC,CAAC;EACrD;EACA,MAAM,OAAO;GACX,MAAM,SAAS,YAAY,CAAC,CAAC;EAC/B;CACF;AACF"}
@@ -0,0 +1,20 @@
1
+ //#region ../../packages/grimoire/src/git/index.d.ts
2
+ /** How a file changed between the base and the working tree. */
3
+ export type ChangedFileStatus = "added" | "modified" | "deleted" | "renamed";
4
+ /** One changed file, project-relative POSIX paths. */
5
+ export type ChangedFile = {
6
+ file: string;
7
+ status: ChangedFileStatus;
8
+ /** The path at the base for a rename, else `null`. */
9
+ from: string | null;
10
+ /** Line numbers (1-based, in the new file) the change adds; empty for a deleted file. */
11
+ addedLines: number[];
12
+ };
13
+ /** One commit of a range. */
14
+ export type CommitInfo = {
15
+ sha: string;
16
+ subject: string;
17
+ body: string;
18
+ };
19
+ //#endregion
20
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/git/index.ts"],"mappings":";;YAaY;;YAGA;EACV;EACA,QAAQ;;EAER;;EAEA;;;YAIU;EAAe;EAAa;EAAiB"}
@@ -0,0 +1,280 @@
1
+ import { GrimoireError } from "../codes/index.mjs";
2
+ import path from "node:path";
3
+ import { readFile } from "node:fs/promises";
4
+ import { execFile } from "node:child_process";
5
+
6
+ //#region ../../packages/grimoire/src/git/index.ts
7
+ /**
8
+ * The few git questions the guard and the `changed` screenshot mode ask.
9
+ * Read-only: every call runs `git` with an argument array (never a shell)
10
+ * in the project root, and every path is relative to that root, so a project
11
+ * inside a larger repository works. Failures throw `GrimoireError` with
12
+ * `GR9009`.
13
+ */
14
+ const MAX_BUFFER = 268435456;
15
+ /** Run git in `root`; never throws. */
16
+ function runGit(root, args) {
17
+ return new Promise((resolve) => {
18
+ execFile("git", [
19
+ "-c",
20
+ "core.quotePath=false",
21
+ "-C",
22
+ root,
23
+ ...args
24
+ ], {
25
+ maxBuffer: MAX_BUFFER,
26
+ encoding: "utf8",
27
+ env: {
28
+ ...process.env,
29
+ GIT_OPTIONAL_LOCKS: "0",
30
+ GIT_TERMINAL_PROMPT: "0",
31
+ LC_ALL: "C"
32
+ }
33
+ }, (error, stdout, stderr) => {
34
+ if (error === null) {
35
+ resolve({
36
+ ok: true,
37
+ stdout
38
+ });
39
+ return;
40
+ }
41
+ const failure = error;
42
+ resolve({
43
+ ok: false,
44
+ stderr: failure.code === "ENOENT" ? "git is not installed or not on the PATH" : String(stderr),
45
+ code: failure.code ?? null
46
+ });
47
+ });
48
+ });
49
+ }
50
+ function gitError(what, result) {
51
+ const detail = result.stderr.trim().split("\n")[0] ?? "";
52
+ return new GrimoireError("GR9009", `Git could not ${what}${detail === "" ? "" : `: ${detail}`}. Run inside a git repository and pass a base that exists (--base origin/main); in CI, fetch the full history.`);
53
+ }
54
+ async function git(root, args, what) {
55
+ const result = await runGit(root, args);
56
+ if (!result.ok) throw gitError(what, result);
57
+ return result.stdout;
58
+ }
59
+ /** The commit a ref names, or `null` when there is none. */
60
+ async function commitOf(root, ref) {
61
+ const result = await runGit(root, [
62
+ "rev-parse",
63
+ "--verify",
64
+ "--quiet",
65
+ `${ref}^{commit}`
66
+ ]);
67
+ return result.ok ? result.stdout.trim() : null;
68
+ }
69
+ /** The merge base of `HEAD` and a commit, or the commit itself when the histories share nothing. */
70
+ async function mergeBaseWithHead(root, commit) {
71
+ const result = await runGit(root, [
72
+ "merge-base",
73
+ "HEAD",
74
+ commit
75
+ ]);
76
+ return result.ok && result.stdout.trim() !== "" ? result.stdout.trim() : commit;
77
+ }
78
+ /**
79
+ * The base to compare with: `base` when given (it must exist), else the
80
+ * default branch (`origin/HEAD`, then `main`, then `master`), else `HEAD`.
81
+ * The answer is the commit where `HEAD` left that ref (their merge base), so
82
+ * a branch that is behind its base does not show the base's own work.
83
+ */
84
+ async function resolveBase(root, base) {
85
+ const inside = await runGit(root, ["rev-parse", "--is-inside-work-tree"]);
86
+ if (!inside.ok) throw gitError("read the repository", inside);
87
+ if (base !== void 0 && base.trim() !== "") {
88
+ const commit = await commitOf(root, base.trim());
89
+ if (commit === null) throw new GrimoireError("GR9009", `Git has no base ${JSON.stringify(base)}. Pass a ref that exists (--base origin/main); in CI, fetch the full history.`);
90
+ return mergeBaseWithHead(root, commit);
91
+ }
92
+ const head = await commitOf(root, "HEAD");
93
+ if (head === null) throw new GrimoireError("GR9009", "Git has no commit to compare with yet. Commit once, or pass --base <ref>.");
94
+ const symbolic = await runGit(root, [
95
+ "symbolic-ref",
96
+ "--quiet",
97
+ "--short",
98
+ "refs/remotes/origin/HEAD"
99
+ ]);
100
+ const candidates = [
101
+ symbolic.ok ? symbolic.stdout.trim() : "",
102
+ "main",
103
+ "master"
104
+ ].filter((name) => name !== "");
105
+ for (const name of candidates) {
106
+ const commit = await commitOf(root, name);
107
+ if (commit !== null) return mergeBaseWithHead(root, commit);
108
+ }
109
+ return head;
110
+ }
111
+ function posix(file) {
112
+ return file.split("\\").join("/");
113
+ }
114
+ /** `@@ -a,b +c,d @@` → the new file's added line numbers. */
115
+ function parseDiffLines(diff) {
116
+ const added = /* @__PURE__ */ new Map();
117
+ let current = null;
118
+ let header = false;
119
+ for (const line of diff.split("\n")) {
120
+ if (line.startsWith("diff --git ")) {
121
+ header = true;
122
+ continue;
123
+ }
124
+ if (header && line.startsWith("+++ ")) {
125
+ const target = line.slice(4).replace(/\t.*$/, "");
126
+ if (target === "/dev/null") {
127
+ current = null;
128
+ continue;
129
+ }
130
+ const file = posix(target.startsWith("\"") ? unquote(target) : target);
131
+ current = added.get(file) ?? [];
132
+ added.set(file, current);
133
+ continue;
134
+ }
135
+ const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);
136
+ if (hunk) header = false;
137
+ if (hunk && current !== null) {
138
+ const start = Number(hunk[1]);
139
+ const count = hunk[2] === void 0 ? 1 : Number(hunk[2]);
140
+ for (let offset = 0; offset < count; offset++) current.push(start + offset);
141
+ }
142
+ }
143
+ return added;
144
+ }
145
+ /** A C-style quoted path from git (`"a\"b"`). */
146
+ function unquote(quoted) {
147
+ return quoted.slice(1, -1).replace(/\\(["\\])/g, "$1").replace(/\\t/g, " ").replace(/\\n/g, "\n");
148
+ }
149
+ /** Line numbers of a whole new file (binary files have none). */
150
+ async function allLines(root, file) {
151
+ let content;
152
+ try {
153
+ content = await readFile(path.join(root, ...file.split("/")));
154
+ } catch {
155
+ return [];
156
+ }
157
+ if (content.subarray(0, 8e3).includes(0)) return [];
158
+ const text = content.toString("utf8");
159
+ if (text === "") return [];
160
+ const count = text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
161
+ return Array.from({ length: count }, (_value, index) => index + 1);
162
+ }
163
+ /**
164
+ * Every file that differs between `base` and the working tree: committed
165
+ * since the base, staged, unstaged and untracked (not ignored) files, sorted
166
+ * by path. `addedLines` come from `git diff --unified=0`; an untracked file
167
+ * counts as added with every line added.
168
+ */
169
+ async function changedFiles(root, base) {
170
+ const status = await git(root, [
171
+ "diff",
172
+ "--name-status",
173
+ "-z",
174
+ "-M",
175
+ "--relative",
176
+ "--no-color",
177
+ "--no-ext-diff",
178
+ base,
179
+ "--"
180
+ ], "list the changed files");
181
+ const diff = await git(root, [
182
+ "diff",
183
+ "--unified=0",
184
+ "-M",
185
+ "--relative",
186
+ "--no-prefix",
187
+ "--no-color",
188
+ "--no-ext-diff",
189
+ base,
190
+ "--"
191
+ ], "read the changed lines");
192
+ const untracked = await git(root, [
193
+ "ls-files",
194
+ "-z",
195
+ "--others",
196
+ "--exclude-standard"
197
+ ], "list the untracked files");
198
+ const lines = parseDiffLines(diff);
199
+ const files = /* @__PURE__ */ new Map();
200
+ const fields = status.split("\0");
201
+ for (let index = 0; index < fields.length; index++) {
202
+ const code = fields[index] ?? "";
203
+ if (code === "") continue;
204
+ const letter = code[0];
205
+ if (letter === "R" || letter === "C") {
206
+ const from = posix(fields[index + 1] ?? "");
207
+ const file = posix(fields[index + 2] ?? "");
208
+ index += 2;
209
+ files.set(file, {
210
+ file,
211
+ status: letter === "R" ? "renamed" : "added",
212
+ from: letter === "R" ? from : null,
213
+ addedLines: lines.get(file) ?? []
214
+ });
215
+ continue;
216
+ }
217
+ const file = posix(fields[index + 1] ?? "");
218
+ index += 1;
219
+ files.set(file, {
220
+ file,
221
+ status: letter === "A" ? "added" : letter === "D" ? "deleted" : "modified",
222
+ from: null,
223
+ addedLines: letter === "D" ? [] : lines.get(file) ?? []
224
+ });
225
+ }
226
+ for (const name of untracked.split("\0")) {
227
+ const file = posix(name);
228
+ if (file === "" || files.has(file)) continue;
229
+ files.set(file, {
230
+ file,
231
+ status: "added",
232
+ from: null,
233
+ addedLines: await allLines(root, file)
234
+ });
235
+ }
236
+ for (const entry of files.values()) if (entry.status === "added" && entry.addedLines.length === 0) entry.addedLines = await allLines(root, entry.file);
237
+ return [...files.values()].sort((left, right) => left.file < right.file ? -1 : left.file > right.file ? 1 : 0);
238
+ }
239
+ /** The text of `file` at `ref`, or `null` when it does not exist there. */
240
+ async function showFile(root, ref, file) {
241
+ const result = await runGit(root, ["show", `${ref}:./${posix(file).replace(/^\.\//, "")}`]);
242
+ if (result.ok) return result.stdout;
243
+ if (await commitOf(root, ref) === null) throw new GrimoireError("GR9009", `Git has no ref ${JSON.stringify(ref)}. Pass a ref that exists (--base origin/main); in CI, fetch the full history.`);
244
+ return null;
245
+ }
246
+ /** The files under `folder` (a project-relative folder) at `ref`, sorted. */
247
+ async function filesAt(root, ref, folder) {
248
+ const result = await runGit(root, [
249
+ "ls-tree",
250
+ "-r",
251
+ "-z",
252
+ "--name-only",
253
+ ref,
254
+ "--",
255
+ `${posix(folder)}/`
256
+ ]);
257
+ if (!result.ok) return [];
258
+ return result.stdout.split("\0").filter((name) => name !== "").map(posix).sort();
259
+ }
260
+ /** The commits of a range (`origin/main..HEAD`), oldest first. */
261
+ async function commitsIn(root, range) {
262
+ return (await git(root, [
263
+ "log",
264
+ "--reverse",
265
+ "--format=%H%x1f%s%x1f%b%x1e",
266
+ range,
267
+ "--"
268
+ ], `list the commits of ${range}`)).split("").map((record) => record.replace(/^\n+/, "")).filter((record) => record.trim() !== "").map((record) => {
269
+ const [sha = "", subject = "", body = ""] = record.split("");
270
+ return {
271
+ sha: sha.trim(),
272
+ subject: subject.trim(),
273
+ body: body.trim()
274
+ };
275
+ });
276
+ }
277
+
278
+ //#endregion
279
+ export { changedFiles, commitsIn, filesAt, resolveBase, showFile };
280
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/git/index.ts"],"sourcesContent":["/**\n * The few git questions the guard and the `changed` screenshot mode ask.\n * Read-only: every call runs `git` with an argument array (never a shell)\n * in the project root, and every path is relative to that root, so a project\n * inside a larger repository works. Failures throw `GrimoireError` with\n * `GR9009`.\n */\nimport { execFile } from \"node:child_process\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { GrimoireError } from \"../codes\";\n\n/** How a file changed between the base and the working tree. */\nexport type ChangedFileStatus = \"added\" | \"modified\" | \"deleted\" | \"renamed\";\n\n/** One changed file, project-relative POSIX paths. */\nexport type ChangedFile = {\n file: string;\n status: ChangedFileStatus;\n /** The path at the base for a rename, else `null`. */\n from: string | null;\n /** Line numbers (1-based, in the new file) the change adds; empty for a deleted file. */\n addedLines: number[];\n};\n\n/** One commit of a range. */\nexport type CommitInfo = { sha: string; subject: string; body: string };\n\ntype GitResult =\n | { ok: true; stdout: string }\n | { ok: false; stderr: string; code: number | string | null };\n\nconst MAX_BUFFER = 256 * 1024 * 1024;\n\n/** Run git in `root`; never throws. */\nfunction runGit(root: string, args: readonly string[]): Promise<GitResult> {\n return new Promise((resolve) => {\n execFile(\n \"git\",\n [\"-c\", \"core.quotePath=false\", \"-C\", root, ...args],\n {\n maxBuffer: MAX_BUFFER,\n encoding: \"utf8\",\n env: { ...process.env, GIT_OPTIONAL_LOCKS: \"0\", GIT_TERMINAL_PROMPT: \"0\", LC_ALL: \"C\" },\n },\n (error, stdout, stderr) => {\n if (error === null) {\n resolve({ ok: true, stdout });\n\n return;\n }\n\n const failure = error as NodeJS.ErrnoException & { code?: number | string };\n\n resolve({\n ok: false,\n stderr:\n failure.code === \"ENOENT\" ? \"git is not installed or not on the PATH\" : String(stderr),\n code: failure.code ?? null,\n });\n },\n );\n });\n}\n\nfunction gitError(what: string, result: Extract<GitResult, { ok: false }>): GrimoireError {\n const detail = result.stderr.trim().split(\"\\n\")[0] ?? \"\";\n\n return new GrimoireError(\n \"GR9009\",\n `Git could not ${what}${detail === \"\" ? \"\" : `: ${detail}`}. Run inside a git repository and pass a base that exists (--base origin/main); in CI, fetch the full history.`,\n );\n}\n\nasync function git(root: string, args: readonly string[], what: string): Promise<string> {\n const result = await runGit(root, args);\n\n if (!result.ok) throw gitError(what, result);\n\n return result.stdout;\n}\n\n/** The commit a ref names, or `null` when there is none. */\nasync function commitOf(root: string, ref: string): Promise<string | null> {\n const result = await runGit(root, [\"rev-parse\", \"--verify\", \"--quiet\", `${ref}^{commit}`]);\n\n return result.ok ? result.stdout.trim() : null;\n}\n\n/** The merge base of `HEAD` and a commit, or the commit itself when the histories share nothing. */\nasync function mergeBaseWithHead(root: string, commit: string): Promise<string> {\n const result = await runGit(root, [\"merge-base\", \"HEAD\", commit]);\n\n return result.ok && result.stdout.trim() !== \"\" ? result.stdout.trim() : commit;\n}\n\n/**\n * The base to compare with: `base` when given (it must exist), else the\n * default branch (`origin/HEAD`, then `main`, then `master`), else `HEAD`.\n * The answer is the commit where `HEAD` left that ref (their merge base), so\n * a branch that is behind its base does not show the base's own work.\n */\nexport async function resolveBase(root: string, base?: string): Promise<string> {\n const inside = await runGit(root, [\"rev-parse\", \"--is-inside-work-tree\"]);\n\n if (!inside.ok) throw gitError(\"read the repository\", inside);\n\n if (base !== undefined && base.trim() !== \"\") {\n const commit = await commitOf(root, base.trim());\n\n if (commit === null) {\n throw new GrimoireError(\n \"GR9009\",\n `Git has no base ${JSON.stringify(base)}. Pass a ref that exists (--base origin/main); in CI, fetch the full history.`,\n );\n }\n\n return mergeBaseWithHead(root, commit);\n }\n\n const head = await commitOf(root, \"HEAD\");\n\n if (head === null) {\n throw new GrimoireError(\n \"GR9009\",\n \"Git has no commit to compare with yet. Commit once, or pass --base <ref>.\",\n );\n }\n\n const symbolic = await runGit(root, [\n \"symbolic-ref\",\n \"--quiet\",\n \"--short\",\n \"refs/remotes/origin/HEAD\",\n ]);\n const candidates = [symbolic.ok ? symbolic.stdout.trim() : \"\", \"main\", \"master\"].filter(\n (name) => name !== \"\",\n );\n\n for (const name of candidates) {\n const commit = await commitOf(root, name);\n\n if (commit !== null) return mergeBaseWithHead(root, commit);\n }\n\n return head;\n}\n\nfunction posix(file: string): string {\n return file.split(\"\\\\\").join(\"/\");\n}\n\n/** `@@ -a,b +c,d @@` → the new file's added line numbers. */\nfunction parseDiffLines(diff: string): Map<string, number[]> {\n const added = new Map<string, number[]>();\n let current: number[] | null = null;\n // `+++ ` names the file only in a file's header: inside a hunk it is an added line that starts with `++`.\n let header = false;\n\n for (const line of diff.split(\"\\n\")) {\n if (line.startsWith(\"diff --git \")) {\n header = true;\n continue;\n }\n\n if (header && line.startsWith(\"+++ \")) {\n const target = line.slice(4).replace(/\\t.*$/, \"\");\n\n if (target === \"/dev/null\") {\n current = null;\n continue;\n }\n\n const file = posix(target.startsWith('\"') ? unquote(target) : target);\n\n current = added.get(file) ?? [];\n added.set(file, current);\n continue;\n }\n\n const hunk = /^@@ -\\d+(?:,\\d+)? \\+(\\d+)(?:,(\\d+))? @@/.exec(line);\n\n if (hunk) header = false;\n\n if (hunk && current !== null) {\n const start = Number(hunk[1]);\n const count = hunk[2] === undefined ? 1 : Number(hunk[2]);\n\n for (let offset = 0; offset < count; offset++) current.push(start + offset);\n }\n }\n\n return added;\n}\n\n/** A C-style quoted path from git (`\"a\\\"b\"`). */\nfunction unquote(quoted: string): string {\n return quoted\n .slice(1, -1)\n .replace(/\\\\([\"\\\\])/g, \"$1\")\n .replace(/\\\\t/g, \"\\t\")\n .replace(/\\\\n/g, \"\\n\");\n}\n\n/** Line numbers of a whole new file (binary files have none). */\nasync function allLines(root: string, file: string): Promise<number[]> {\n let content: Buffer;\n\n try {\n content = await readFile(path.join(root, ...file.split(\"/\")));\n } catch {\n return [];\n }\n\n if (content.subarray(0, 8000).includes(0)) return [];\n\n const text = content.toString(\"utf8\");\n\n if (text === \"\") return [];\n\n const count = text.split(\"\\n\").length - (text.endsWith(\"\\n\") ? 1 : 0);\n\n return Array.from({ length: count }, (_value, index) => index + 1);\n}\n\n/**\n * Every file that differs between `base` and the working tree: committed\n * since the base, staged, unstaged and untracked (not ignored) files, sorted\n * by path. `addedLines` come from `git diff --unified=0`; an untracked file\n * counts as added with every line added.\n */\nexport async function changedFiles(root: string, base: string): Promise<ChangedFile[]> {\n const status = await git(\n root,\n [\"diff\", \"--name-status\", \"-z\", \"-M\", \"--relative\", \"--no-color\", \"--no-ext-diff\", base, \"--\"],\n \"list the changed files\",\n );\n const diff = await git(\n root,\n [\n \"diff\",\n \"--unified=0\",\n \"-M\",\n \"--relative\",\n \"--no-prefix\",\n \"--no-color\",\n \"--no-ext-diff\",\n base,\n \"--\",\n ],\n \"read the changed lines\",\n );\n const untracked = await git(\n root,\n [\"ls-files\", \"-z\", \"--others\", \"--exclude-standard\"],\n \"list the untracked files\",\n );\n const lines = parseDiffLines(diff);\n const files = new Map<string, ChangedFile>();\n const fields = status.split(\"\\0\");\n\n for (let index = 0; index < fields.length; index++) {\n const code = fields[index] ?? \"\";\n\n if (code === \"\") continue;\n\n const letter = code[0];\n\n if (letter === \"R\" || letter === \"C\") {\n const from = posix(fields[index + 1] ?? \"\");\n const file = posix(fields[index + 2] ?? \"\");\n\n index += 2;\n files.set(file, {\n file,\n status: letter === \"R\" ? \"renamed\" : \"added\",\n from: letter === \"R\" ? from : null,\n addedLines: lines.get(file) ?? [],\n });\n continue;\n }\n\n const file = posix(fields[index + 1] ?? \"\");\n\n index += 1;\n files.set(file, {\n file,\n status: letter === \"A\" ? \"added\" : letter === \"D\" ? \"deleted\" : \"modified\",\n from: null,\n addedLines: letter === \"D\" ? [] : (lines.get(file) ?? []),\n });\n }\n\n for (const name of untracked.split(\"\\0\")) {\n const file = posix(name);\n\n if (file === \"\" || files.has(file)) continue;\n\n files.set(file, { file, status: \"added\", from: null, addedLines: await allLines(root, file) });\n }\n\n // An added file that git reports without hunks (the diff of a staged new file) still has every line added.\n for (const entry of files.values()) {\n if (entry.status === \"added\" && entry.addedLines.length === 0) {\n entry.addedLines = await allLines(root, entry.file);\n }\n }\n\n return [...files.values()].sort((left, right) =>\n left.file < right.file ? -1 : left.file > right.file ? 1 : 0,\n );\n}\n\n/** The text of `file` at `ref`, or `null` when it does not exist there. */\nexport async function showFile(root: string, ref: string, file: string): Promise<string | null> {\n const result = await runGit(root, [\"show\", `${ref}:./${posix(file).replace(/^\\.\\//, \"\")}`]);\n\n if (result.ok) return result.stdout;\n\n if ((await commitOf(root, ref)) === null) {\n throw new GrimoireError(\n \"GR9009\",\n `Git has no ref ${JSON.stringify(ref)}. Pass a ref that exists (--base origin/main); in CI, fetch the full history.`,\n );\n }\n\n return null;\n}\n\n/** The files under `folder` (a project-relative folder) at `ref`, sorted. */\nexport async function filesAt(root: string, ref: string, folder: string): Promise<string[]> {\n const result = await runGit(root, [\n \"ls-tree\",\n \"-r\",\n \"-z\",\n \"--name-only\",\n ref,\n \"--\",\n `${posix(folder)}/`,\n ]);\n\n if (!result.ok) return [];\n\n // `ls-tree` prints paths relative to the current folder when it runs inside one.\n return result.stdout\n .split(\"\\0\")\n .filter((name) => name !== \"\")\n .map(posix)\n .sort();\n}\n\n/** The commits of a range (`origin/main..HEAD`), oldest first. */\nexport async function commitsIn(root: string, range: string): Promise<CommitInfo[]> {\n const out = await git(\n root,\n [\"log\", \"--reverse\", \"--format=%H%x1f%s%x1f%b%x1e\", range, \"--\"],\n `list the commits of ${range}`,\n );\n\n return out\n .split(\"\\x1e\")\n .map((record) => record.replace(/^\\n+/, \"\"))\n .filter((record) => record.trim() !== \"\")\n .map((record) => {\n const [sha = \"\", subject = \"\", body = \"\"] = record.split(\"\\x1f\");\n\n return { sha: sha.trim(), subject: subject.trim(), body: body.trim() };\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAgCA,MAAM,aAAa;;AAGnB,SAAS,OAAO,MAAc,MAA6C;CACzE,OAAO,IAAI,SAAS,YAAY;EAC9B,SACE,OACA;GAAC;GAAM;GAAwB;GAAM;GAAM,GAAG;EAAI,GAClD;GACE,WAAW;GACX,UAAU;GACV,KAAK;IAAE,GAAG,QAAQ;IAAK,oBAAoB;IAAK,qBAAqB;IAAK,QAAQ;GAAI;EACxF,IACC,OAAO,QAAQ,WAAW;GACzB,IAAI,UAAU,MAAM;IAClB,QAAQ;KAAE,IAAI;KAAM;IAAO,CAAC;IAE5B;GACF;GAEA,MAAM,UAAU;GAEhB,QAAQ;IACN,IAAI;IACJ,QACE,QAAQ,SAAS,WAAW,4CAA4C,OAAO,MAAM;IACvF,MAAM,QAAQ,QAAQ;GACxB,CAAC;EACH,CACF;CACF,CAAC;AACH;AAEA,SAAS,SAAS,MAAc,QAA0D;CACxF,MAAM,SAAS,OAAO,OAAO,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM;CAEtD,OAAO,IAAI,cACT,UACA,iBAAiB,OAAO,WAAW,KAAK,KAAK,KAAK,SAAS,+GAC7D;AACF;AAEA,eAAe,IAAI,MAAc,MAAyB,MAA+B;CACvF,MAAM,SAAS,MAAM,OAAO,MAAM,IAAI;CAEtC,IAAI,CAAC,OAAO,IAAI,MAAM,SAAS,MAAM,MAAM;CAE3C,OAAO,OAAO;AAChB;;AAGA,eAAe,SAAS,MAAc,KAAqC;CACzE,MAAM,SAAS,MAAM,O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