@warlock.js/grimoire 5.56.0 → 5.58.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.
- package/CHANGELOG.md +35 -0
- package/esm/book/build.d.mts.map +1 -1
- package/esm/book/build.mjs +2 -1
- package/esm/book/build.mjs.map +1 -1
- package/esm/book/render.mjs +10 -0
- package/esm/book/render.mjs.map +1 -1
- package/esm/bookmap/build.d.mts.map +1 -1
- package/esm/bookmap/build.mjs +2 -2
- package/esm/bookmap/build.mjs.map +1 -1
- package/esm/bookmap/steps.mjs +53 -38
- package/esm/bookmap/steps.mjs.map +1 -1
- package/esm/check/check-grimoire.d.mts.map +1 -1
- package/esm/check/check-grimoire.mjs +4 -1
- package/esm/check/check-grimoire.mjs.map +1 -1
- package/esm/check/rules/criteria.mjs +21 -2
- package/esm/check/rules/criteria.mjs.map +1 -1
- package/esm/check/rules/screenshots.mjs +57 -0
- package/esm/check/rules/screenshots.mjs.map +1 -0
- package/esm/codes/codes.d.mts +12 -0
- package/esm/codes/codes.d.mts.map +1 -1
- package/esm/codes/codes.mjs +6 -0
- package/esm/codes/codes.mjs.map +1 -1
- package/esm/contracts/adapter.d.mts +6 -0
- package/esm/contracts/adapter.d.mts.map +1 -1
- package/esm/contracts/book.d.mts +2 -0
- package/esm/contracts/book.d.mts.map +1 -1
- package/esm/contracts/book.mjs.map +1 -1
- package/esm/contracts/bookmap.d.mts +19 -1
- package/esm/contracts/bookmap.d.mts.map +1 -1
- package/esm/contracts/snapshot.d.mts +11 -0
- package/esm/contracts/snapshot.d.mts.map +1 -1
- package/esm/contracts/test-results.d.mts +34 -0
- package/esm/contracts/test-results.d.mts.map +1 -1
- package/esm/contracts/written.d.mts +44 -0
- package/esm/contracts/written.d.mts.map +1 -1
- package/esm/contracts/written.mjs.map +1 -1
- package/esm/devtools/data.mjs +126 -4
- package/esm/devtools/data.mjs.map +1 -1
- package/esm/devtools/index.d.mts +31 -1
- package/esm/devtools/index.d.mts.map +1 -1
- package/esm/devtools/index.mjs +94 -5
- package/esm/devtools/index.mjs.map +1 -1
- package/esm/devtools/product-map.d.mts +14 -0
- package/esm/devtools/product-map.d.mts.map +1 -0
- package/esm/devtools/product-map.mjs +385 -0
- package/esm/devtools/product-map.mjs.map +1 -0
- package/esm/devtools/site.d.mts.map +1 -1
- package/esm/devtools/site.mjs +97 -21
- package/esm/devtools/site.mjs.map +1 -1
- package/esm/devtools/snapshot-source.mjs +71 -22
- package/esm/devtools/snapshot-source.mjs.map +1 -1
- package/esm/graph/index.d.mts +10 -1
- package/esm/graph/index.d.mts.map +1 -1
- package/esm/graph/index.mjs +3 -2
- package/esm/graph/index.mjs.map +1 -1
- package/esm/index.d.mts +4 -4
- package/esm/paths/index.d.mts +2 -0
- package/esm/paths/index.d.mts.map +1 -1
- package/esm/paths/index.mjs +3 -1
- package/esm/paths/index.mjs.map +1 -1
- package/esm/scry/compact.mjs +169 -0
- package/esm/scry/compact.mjs.map +1 -0
- package/esm/scry/format.d.mts.map +1 -1
- package/esm/scry/format.mjs +7 -1
- package/esm/scry/format.mjs.map +1 -1
- package/esm/scry/query.d.mts.map +1 -1
- package/esm/scry/query.mjs +12 -1
- package/esm/scry/query.mjs.map +1 -1
- package/esm/test-results/index.d.mts +7 -2
- package/esm/test-results/index.d.mts.map +1 -1
- package/esm/test-results/index.mjs +79 -12
- package/esm/test-results/index.mjs.map +1 -1
- package/esm/vitest/index.d.mts +6 -0
- package/esm/vitest/index.d.mts.map +1 -1
- package/esm/vitest/index.mjs +22 -6
- package/esm/vitest/index.mjs.map +1 -1
- package/esm/warlock/adapter.d.mts.map +1 -1
- package/esm/warlock/adapter.mjs +6 -2
- package/esm/warlock/adapter.mjs.map +1 -1
- package/esm/warlock/mcp-tools.mjs +48 -12
- package/esm/warlock/mcp-tools.mjs.map +1 -1
- package/esm/workspace/index.d.mts.map +1 -1
- package/esm/workspace/index.mjs +4 -2
- package/esm/workspace/index.mjs.map +1 -1
- package/esm/written/apps.mjs +4 -2
- package/esm/written/apps.mjs.map +1 -1
- package/esm/written/features.mjs +119 -6
- package/esm/written/features.mjs.map +1 -1
- package/esm/written/markdown.mjs +66 -1
- package/esm/written/markdown.mjs.map +1 -1
- package/esm/written/parse-grimoire.d.mts.map +1 -1
- package/esm/written/parse-grimoire.mjs +1 -1
- package/esm/written/parse-grimoire.mjs.map +1 -1
- package/llms-full.txt +77 -2
- package/package.json +3 -3
- package/skills/backfill-a-grimoire/SKILL.md +5 -0
- package/skills/describe-an-app/SKILL.md +12 -0
- package/skills/record-a-change/SKILL.md +8 -0
- package/skills/use-the-grimoire/SKILL.md +15 -0
- package/skills/write-a-feature/SKILL.md +37 -2
- package/ui/grimoire-static.js +4 -0
- package/ui/grimoire-view.js +2283 -428
- package/ui/grimoire.css +1036 -45
- package/ui/product-map.css +636 -0
- package/ui/product-map.js +817 -0
package/esm/scry/query.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/query.ts"],"sourcesContent":["/**\n * Answers one scry query from a snapshot. Pure: reads the snapshot only.\n */\nimport { packagesOf } from \"../book\";\nimport { normalizeRoutePath, routeMatches } from \"../bookmap\";\nimport { checkGrimoire } from \"../check\";\nimport { GrimoireError } from \"../codes\";\nimport type { BookFile, BookRoute } from \"../contracts/adapter\";\nimport { BOOK_SCHEMA_VERSION, type BookEntry } from \"../contracts/book\";\nimport type { FeatureBookmap, FlowBookmap } from \"../contracts/bookmap\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type {\n ScryFeatureResult,\n ScryFileResult,\n ScryFlowResult,\n ScryHit,\n ScryHitType,\n ScryImpactResult,\n ScryNotes,\n ScryPageRef,\n ScryQuery,\n ScryResult,\n ScryRouteResult,\n ScrySearchResult,\n} from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenFeature, WrittenFlow } from \"../contracts/written\";\nimport { fileGraph, importClosure, importerClosure } from \"../graph\";\nimport { bookEntryPaths, projectPath, toPosixPath } from \"../paths\";\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\nconst sortedUnique = (items: Iterable<string>): string[] => [...new Set(items)].sort(byText);\n\n/** Notes every answer carries: how fresh the route facts are. */\nfunction notesOf(snapshot: GrimoireSnapshot, needsRoutes: boolean): ScryNotes {\n const notes: string[] = [];\n\n if (snapshot.routes === \"stale\") notes.push(\"route facts are stale; run warlock grimoire build\");\n if (snapshot.routes === \"missing\" && needsRoutes) {\n notes.push(\"route facts were never read; run warlock grimoire build\");\n }\n\n return { routes: snapshot.routes, notes };\n}\n\n/** A project-relative POSIX path for what the caller typed (either separator, absolute or relative). */\nfunction fileOf(snapshot: GrimoireSnapshot, file: string): string {\n return projectPath(snapshot.root, toPosixPath(file.trim()));\n}\n\nfunction bookFile(snapshot: GrimoireSnapshot, file: string): BookFile {\n const found = snapshot.book.facts.files.find((item) => item.file === file);\n\n if (!found) {\n const roots = [\n ...new Set(snapshot.book.facts.files.map((item) => item.file.split(\"/\")[0] ?? \"\")),\n ]\n .filter((root) => root !== \"\")\n .sort(byText);\n\n throw new GrimoireError(\n \"GR9001\",\n `${file} is not in the book. Pass a code file under ${roots.join(\", \") || \"the source roots\"} as a project-relative path; if the file is new, run warlock grimoire build.`,\n );\n }\n\n return found;\n}\n\n/** The written app id that shows a site, or the site id when no written app matches it. */\nfunction siteApp(snapshot: GrimoireSnapshot, site: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.site?.id === site);\n\n return match?.app ?? site;\n}\n\n/** The written app id of a mobile app, or its own id. */\nfunction mobileApp(snapshot: GrimoireSnapshot, mobile: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.mobile?.id === mobile);\n\n return match?.app ?? mobile;\n}\n\n/** The book entry of one file, as the book writes it. */\nfunction entryOf(snapshot: GrimoireSnapshot, file: BookFile): BookEntry {\n const facts = snapshot.book.facts;\n const annotation = snapshot.annotations.files[file.file];\n const routeRef = (route: BookRoute) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n });\n const routes = facts.routes ?? [];\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n file: file.file,\n module: file.module,\n type: file.type,\n lines: file.lines,\n about: file.about,\n feature: annotation?.feature ?? null,\n borrowedBy: sortedUnique(annotation?.borrowedBy ?? []),\n flows: sortedUnique(annotation?.flows ?? []),\n exports: file.exports.map((entry) => ({ name: entry.name, about: entry.about })),\n // The same list the book entry holds (bare Node builtins such as `fs` left out too).\n packages: packagesOf(file),\n imports: sortedUnique(\n file.imports.flatMap((entry) => (entry.file === null ? [] : [entry.file])),\n ),\n importedBy: sortedUnique(file.importedBy),\n routes: [\n ...routes\n .filter((route) => route.sourceFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"registers\" as const })),\n ...routes\n .filter((route) => route.handlerFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"handles\" as const })),\n ],\n pages: facts.pages\n .flatMap((page) => [\n ...(page.file === file.file\n ? [{ site: page.site, route: page.route, via: \"page\" as const }]\n : []),\n ...(page.setupFile === file.file\n ? [{ site: page.site, route: page.route, via: \"setup\" as const }]\n : []),\n ...(page.layouts.includes(file.file)\n ? [{ site: page.site, route: page.route, via: \"layout\" as const }]\n : []),\n ])\n .sort(\n (left, right) =>\n byText(left.site, right.site) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n screens: facts.mobile\n .flatMap((app) =>\n app.screens.flatMap((screen) => [\n ...(screen.file === file.file\n ? [{ app: app.id, route: screen.route, via: \"screen\" as const }]\n : []),\n ...(screen.layouts.includes(file.file)\n ? [{ app: app.id, route: screen.route, via: \"layout\" as const }]\n : []),\n ]),\n )\n .sort(\n (left, right) =>\n byText(left.app, right.app) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n };\n}\n\n/** Where the book keeps the entry of `file`, or `null` when it has none. */\nfunction bookEntryOf(snapshot: GrimoireSnapshot, file: string): string | null {\n const facts = snapshot.book.facts;\n const roots = new Map(facts.mobile.map((app) => [app.id, app.root]));\n const paths = bookEntryPaths(\n facts.files.map((item) => {\n const root = item.mobileApp === null ? undefined : roots.get(item.mobileApp);\n\n return {\n file: item.file,\n mobileApp:\n item.mobileApp === null || root === undefined ? null : { id: item.mobileApp, root },\n };\n }),\n );\n const entry = paths.get(file);\n\n return entry === undefined || entry.split(\"/\").includes(\"..\") ? null : entry;\n}\n\nfunction scryFile(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"file\" }>,\n): ScryFileResult {\n const file = bookFile(snapshot, fileOf(snapshot, query.file));\n\n return {\n type: \"file\",\n ...notesOf(snapshot, false),\n entry: entryOf(snapshot, file),\n bookEntry: bookEntryOf(snapshot, file.file),\n };\n}\n\nfunction flowBookmaps(snapshot: GrimoireSnapshot): FlowBookmap[] {\n return Object.values(snapshot.collected.flows).sort((left, right) => byText(left.ref, right.ref));\n}\n\nfunction scryImpact(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"impact\" }>,\n): ScryImpactResult {\n const facts = snapshot.book.facts;\n const target = bookFile(snapshot, fileOf(snapshot, query.file));\n const graph = fileGraph(facts.files);\n const reach = new Set(importerClosure(graph, [target.file]));\n const importers = [...reach].filter((file) => file !== target.file).sort(byText);\n const routes = (facts.routes ?? []).filter(\n (route) =>\n !route.isPage &&\n (route.handlerFile !== null\n ? reach.has(route.handlerFile)\n : route.sourceFile !== null && reach.has(route.sourceFile)),\n );\n const pages: ScryPageRef[] = [\n ...facts.pages\n .filter(\n (page) =>\n reach.has(page.file) ||\n (page.setupFile !== null && reach.has(page.setupFile)) ||\n page.layouts.some((layout) => reach.has(layout)),\n )\n .map((page) => ({\n app: siteApp(snapshot, page.site),\n route: page.route,\n file: page.file,\n type: \"page\" as const,\n })),\n ...facts.mobile.flatMap((app) =>\n app.screens\n .filter(\n (screen) => reach.has(screen.file) || screen.layouts.some((layout) => reach.has(layout)),\n )\n .map((screen) => ({\n app: mobileApp(snapshot, app.id),\n route: screen.route,\n file: screen.file,\n type: \"screen\" as const,\n })),\n ),\n ];\n const flows = flowBookmaps(snapshot)\n .filter((bookmap) => bookmap.steps.some((step) => step.files.includes(target.file)))\n .map((bookmap) => bookmap.ref);\n const ownership = snapshot.ownership.files;\n const owner = ownership[target.file]?.owner ?? null;\n // Looked up once per importer: an app with thousands of files stays linear.\n const specFiles = new Set(\n facts.files.filter((item) => item.type === \"spec\").map((item) => item.file),\n );\n const borrowers = sortedUnique([\n ...(ownership[target.file]?.borrowedBy ?? []),\n ...importers.flatMap((file) => {\n const ownerOf = ownership[file]?.owner;\n\n return ownerOf === undefined || ownerOf === null || specFiles.has(file) ? [] : [ownerOf];\n }),\n ]).filter((feature) => feature !== owner);\n const testFiles = new Set(facts.tests);\n const flowSet = new Set(flows);\n const tests = sortedUnique([\n ...importers.filter((file) => testFiles.has(file) || specFiles.has(file)),\n ...snapshot.proofs.filter((proof) => flowSet.has(proof.ref)).map((proof) => proof.at.file),\n ]);\n\n return {\n type: \"impact\",\n ...notesOf(snapshot, true),\n file: target.file,\n importers: { direct: sortedUnique(target.importedBy), all: importers },\n routes: routes.map((route) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n handlerFile: route.handlerFile,\n })),\n pages,\n flows,\n features: [\n ...(owner === null ? [] : [{ id: owner, via: \"owner\" as const }]),\n ...borrowers.map((id) => ({ id, via: \"borrower\" as const })),\n ],\n tests,\n };\n}\n\nfunction scryRoute(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"route\" }>,\n): ScryRouteResult {\n const facts = snapshot.book.facts;\n const method = query.method.toUpperCase();\n const asked = `${method} ${query.path}`;\n\n if (facts.routes === null) {\n throw new GrimoireError(\n \"GR9002\",\n `No route facts yet, so ${asked} cannot be looked up. Run warlock grimoire build (it boots the app once to read the routes), then ask again.`,\n );\n }\n\n const route = facts.routes.find((item) => routeMatches(item, method, query.path));\n\n if (!route) {\n const samePath = facts.routes\n .filter((item) => normalizeRoutePath(item.path) === normalizeRoutePath(query.path))\n .map((item) => `${item.method} ${item.path}`);\n const hint =\n samePath.length > 0\n ? ` Routes on that path: ${samePath.join(\", \")}.`\n : \" Run warlock routes to list them, or warlock grimoire build when the route is new.\";\n\n throw new GrimoireError(\"GR9002\", `No route matches ${asked}.${hint}`);\n }\n\n const graph = fileGraph(facts.files);\n const start = route.handlerFile ?? route.sourceFile;\n const files = start === null ? [] : importClosure(graph, [start]);\n const steps = snapshot.written.features.flatMap((feature) =>\n feature.flows.flatMap((flow) =>\n flow.steps\n .filter(\n (step) =>\n step.type === \"route\" &&\n step.route !== null &&\n routeMatches(route, step.route.method, step.route.path),\n )\n .map((step) => ({ flow: flow.ref, index: step.index })),\n ),\n );\n const page = route.isPage\n ? (facts.pages.find((item) => item.file === route.handlerFile) ??\n facts.pages.find(\n (item) => normalizeRoutePath(item.route) === normalizeRoutePath(route.path),\n ) ??\n null)\n : null;\n\n return {\n type: \"route\",\n ...notesOf(snapshot, true),\n route,\n files,\n steps: steps.sort((left, right) => byText(left.flow, right.flow) || left.index - right.index),\n page,\n };\n}\n\nfunction writtenFeature(snapshot: GrimoireSnapshot, id: string): WrittenFeature {\n const feature = snapshot.written.features.find((item) => item.id === id);\n\n if (!feature) {\n const known = snapshot.written.features.map((item) => item.id).sort(byText);\n const list =\n known.length > 0\n ? ` Features: ${known.join(\", \")}.`\n : \" The project has no grimoire/features/ folder yet.\";\n\n throw new GrimoireError(\"GR9003\", `No feature has the id ${JSON.stringify(id)}.${list}`);\n }\n\n return feature;\n}\n\nfunction findingsFor(\n snapshot: GrimoireSnapshot,\n match: (finding: GrimoireFinding) => boolean,\n): GrimoireFinding[] {\n return checkGrimoire(snapshot).findings.filter(match);\n}\n\nfunction emptyFeatureBookmap(feature: string): FeatureBookmap {\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature,\n own: [],\n borrowed: [],\n routes: [],\n pages: {},\n unreached: [],\n };\n}\n\nfunction scryFeature(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"feature\" }>,\n): ScryFeatureResult {\n const feature = writtenFeature(snapshot, query.feature);\n\n if (feature.readme === null) {\n throw new GrimoireError(\n \"GR9003\",\n `grimoire/features/${feature.id} has no README.md, so the feature cannot be shown. Write the README (see warlock grimoire check), then ask again.`,\n );\n }\n\n return {\n type: \"feature\",\n ...notesOf(snapshot, false),\n readme: feature.readme,\n flows: [...feature.flows]\n .sort((left, right) => byText(left.id.value, right.id.value))\n .map((flow) => ({\n id: flow.id.value,\n status: flow.status.value,\n since: flow.since.value,\n heading: flow.heading?.value ?? null,\n })),\n bookmap: snapshot.collected.features[feature.id] ?? emptyFeatureBookmap(feature.id),\n changes: (feature.changelog?.entries ?? []).slice(0, 10),\n tasks: snapshot.collected.tasksIndex.open.filter((task) => task.feature === feature.id),\n findings: findingsFor(\n snapshot,\n (finding) =>\n finding.subject.feature === feature.id ||\n (finding.subject.flow ?? \"\").startsWith(`${feature.id}/`),\n ),\n };\n}\n\nfunction scryFlow(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"flow\" }>,\n): ScryFlowResult {\n const feature = writtenFeature(snapshot, query.feature);\n const flow: WrittenFlow | undefined = feature.flows.find((item) => item.id.value === query.flow);\n\n if (!flow) {\n const known = feature.flows.map((item) => item.id.value).sort(byText);\n const list =\n known.length > 0\n ? ` Flows of ${feature.id}: ${known.join(\", \")}.`\n : ` ${feature.id} has no flows yet.`;\n\n throw new GrimoireError(\"GR9004\", `No flow ${feature.id}/${query.flow}.${list}`);\n }\n\n const bookmap =\n Object.values(snapshot.collected.flows).find(\n (item) => item.feature === feature.id && item.flow === flow.id.value,\n ) ?? snapshot.collected.flows[flow.ref];\n\n if (!bookmap) {\n throw new GrimoireError(\n \"GR9004\",\n `${flow.ref} has no book map yet. Run warlock grimoire build, then ask again.`,\n );\n }\n\n return {\n type: \"flow\",\n ...notesOf(snapshot, true),\n flow,\n bookmap,\n history: (feature.changelog?.entries ?? []).filter((entry) => entry.flow === flow.id.value),\n findings: findingsFor(snapshot, (finding) => finding.subject.flow === flow.ref),\n };\n}\n\n// ── Search ─────────────────────────────────────────────────────────────────\n\nconst TYPE_ORDER: readonly ScryHitType[] = [\n \"feature\",\n \"flow\",\n \"block\",\n \"page\",\n \"screen\",\n \"route\",\n \"mail\",\n \"job\",\n \"file\",\n \"export\",\n \"task\",\n];\n\n/** Lower-case words: `catalog/new-arrivals.service.ts` → `catalog new arrivals service ts`. */\nfunction words(text: string): string {\n return text\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \" \")\n .trim();\n}\n\n/** The last segment of an id (`catalog/new-arrivals` → `new-arrivals`). */\nfunction lastSegment(id: string): string {\n const parts = id.split(/[\\s/#]+/).filter((part) => part !== \"\");\n\n return parts[parts.length - 1] ?? id;\n}\n\n/** The slug of a block name (`New arrivals` → `new-arrivals`). */\nfunction slug(text: string): string {\n return words(text).split(\" \").join(\"-\");\n}\n\ntype Candidate = Omit<ScryHit, \"score\">;\n\nfunction candidates(snapshot: GrimoireSnapshot): Candidate[] {\n const facts = snapshot.book.facts;\n const list: Candidate[] = [];\n\n for (const feature of snapshot.written.features) {\n list.push({ type: \"feature\", id: feature.id, detail: feature.readme?.title.value ?? null });\n\n for (const flow of feature.flows) {\n list.push({ type: \"flow\", id: flow.ref, detail: flow.heading?.value ?? null });\n }\n }\n\n for (const app of snapshot.written.apps) {\n const appId = app.id.value;\n\n for (const layout of app.layouts) {\n for (const row of layout.blocks) {\n list.push({\n type: \"block\",\n id: `${appId}/${layout.id}/${slug(row.block)}`,\n detail: row.flow ?? row.block,\n });\n }\n }\n\n for (const page of [...app.pages, ...app.screens]) {\n for (const row of page.blocks) {\n list.push({\n type: \"block\",\n id: `${appId}/${page.id}/${slug(row.block)}`,\n detail: row.flow ?? row.block,\n });\n }\n }\n }\n\n for (const page of facts.pages) {\n list.push({\n type: \"page\",\n id: `${siteApp(snapshot, page.site)} ${page.route}`,\n detail: page.file,\n });\n }\n\n for (const app of facts.mobile) {\n for (const screen of app.screens) {\n list.push({\n type: \"screen\",\n id: `${mobileApp(snapshot, app.id)} ${screen.route}`,\n detail: screen.file,\n });\n }\n }\n\n for (const route of facts.routes ?? []) {\n if (route.isPage) continue;\n\n list.push({ type: \"route\", id: `${route.method} ${route.path}`, detail: route.name });\n }\n\n for (const thing of facts.named) {\n if (thing.type !== \"mail\" && thing.type !== \"job\") continue;\n\n list.push({ type: thing.type, id: thing.name, detail: thing.file });\n }\n\n for (const file of facts.files) {\n list.push({ type: \"file\", id: file.file, detail: file.about });\n\n for (const entry of file.exports) {\n if (entry.name === \"default\" || entry.name === \"*\") continue;\n\n list.push({ type: \"export\", id: `${file.file}#${entry.name}`, detail: entry.about });\n }\n }\n\n for (const task of [\n ...snapshot.collected.tasksIndex.open,\n ...snapshot.collected.tasksIndex.done,\n ]) {\n list.push({ type: \"task\", id: task.id, detail: task.title });\n }\n\n return list;\n}\n\n/** Whether every character of `needle` appears in `text` in order. */\nfunction isSubsequence(needle: string, text: string): boolean {\n let position = 0;\n\n for (const char of text) {\n if (char === needle[position]) position++;\n\n if (position === needle.length) return true;\n }\n\n return needle.length === 0;\n}\n\n/** Shortest query that may match by fuzzy (in-order letters), so short queries stay precise. */\nconst FUZZY_MIN = 4;\n\n/**\n * Score of a candidate for the query words, or 0 when it does not match. From best\n * to worst: exact name or path (7), prefix (6), whole-word match (5), substring of\n * the name or path (4), the words found only in the detail (3), fuzzy (2).\n */\nfunction scoreOf(candidate: Candidate, query: string, tokens: readonly string[]): number {\n const id = words(\n candidate.type === \"export\" ? (candidate.id.split(\"#\")[1] ?? candidate.id) : candidate.id,\n );\n const last = words(lastSegment(candidate.id));\n const all = `${id} ${words(candidate.detail ?? \"\")}`;\n\n if (!tokens.every((token) => all.includes(token))) {\n const squeezed = id.replace(/ /g, \"\");\n\n return query.length >= FUZZY_MIN && tokens.every((token) => isSubsequence(token, squeezed))\n ? 2\n : 0;\n }\n\n if (id === query || last === query) return 7;\n if (id.startsWith(query) || last.startsWith(query)) return 6;\n\n const idWords = id.split(\" \");\n\n if (tokens.every((token) => idWords.includes(token))) return 5;\n if (tokens.every((token) => id.includes(token))) return 4;\n\n return 3;\n}\n\nfunction scrySearch(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"search\" }>,\n): ScrySearchResult {\n const text = words(query.text);\n const tokens = text.split(\" \").filter((token) => token !== \"\");\n\n if (tokens.length === 0) {\n throw new GrimoireError(\n \"GR9006\",\n `Search text ${JSON.stringify(query.text)} has no letters or digits; pass a word to look for.`,\n );\n }\n\n const seen = new Set<string>();\n const hits: ScryHit[] = [];\n\n for (const candidate of candidates(snapshot)) {\n const key = `${candidate.type} ${candidate.id}`;\n\n if (seen.has(key)) continue;\n\n seen.add(key);\n\n const score = scoreOf(candidate, text, tokens);\n\n if (score > 0) hits.push({ ...candidate, score });\n }\n\n hits.sort(\n (left, right) =>\n right.score - left.score ||\n TYPE_ORDER.indexOf(left.type) - TYPE_ORDER.indexOf(right.type) ||\n byText(left.id, right.id),\n );\n\n return {\n type: \"search\",\n ...notesOf(snapshot, false),\n text: query.text,\n hits: hits.slice(0, query.limit ?? 20),\n };\n}\n\n/**\n * Answer one query. Throws a `GrimoireError`: `GR9001` for a file not in the\n * book, `GR9002` no route, `GR9003` no feature, `GR9004` no flow, `GR9006`\n * a search with no words. Pure.\n */\nexport function scry(snapshot: GrimoireSnapshot, query: ScryQuery): ScryResult {\n switch (query.type) {\n case \"file\":\n return scryFile(snapshot, query);\n case \"impact\":\n return scryImpact(snapshot, query);\n case \"route\":\n return scryRoute(snapshot, query);\n case \"feature\":\n return scryFeature(snapshot, query);\n case \"flow\":\n return scryFlow(snapshot, query);\n case \"search\":\n return scrySearch(snapshot, query);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI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,UAAU,KAAK;EAClC,KAAK,WACH,OAAO,YAAY,UAAU,KAAK;EACpC,KAAK,QACH,OAAO,SAAS,UAAU,KAAK;EACjC,KAAK,UACH,OAAO,WAAW,UAAU,KAAK;CACrC;AACF"}
|
|
1
|
+
{"version":3,"file":"query.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/query.ts"],"sourcesContent":["/**\n * Answers one scry query from a snapshot. Pure: reads the snapshot only.\n */\nimport { packagesOf } from \"../book\";\nimport { normalizeRoutePath, routeMatches } from \"../bookmap\";\nimport { checkGrimoire } from \"../check\";\nimport { GrimoireError } from \"../codes\";\nimport type { BookFile, BookRoute } from \"../contracts/adapter\";\nimport { BOOK_SCHEMA_VERSION, type BookEntry } from \"../contracts/book\";\nimport type { FeatureBookmap, FlowBookmap } from \"../contracts/bookmap\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type {\n ScryFeatureResult,\n ScryFileResult,\n ScryFlowResult,\n ScryHit,\n ScryHitType,\n ScryImpactResult,\n ScryNotes,\n ScryPageRef,\n ScryQuery,\n ScryResult,\n ScryRouteResult,\n ScrySearchResult,\n} from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenFeature, WrittenFlow } from \"../contracts/written\";\nimport { fileGraph, importClosure, importerClosure } from \"../graph\";\nimport { bookEntryPaths, projectPath, toPosixPath } from \"../paths\";\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\nconst sortedUnique = (items: Iterable<string>): string[] => [...new Set(items)].sort(byText);\n\n/** Notes every answer carries: how fresh the route facts are. */\nfunction notesOf(snapshot: GrimoireSnapshot, needsRoutes: boolean): ScryNotes {\n const notes: string[] = [];\n\n if (snapshot.routes === \"stale\") notes.push(\"route facts are stale; run warlock grimoire build\");\n if (snapshot.routes === \"missing\" && needsRoutes) {\n notes.push(\"route facts were never read; run warlock grimoire build\");\n }\n\n return { routes: snapshot.routes, notes };\n}\n\n/** A project-relative POSIX path for what the caller typed (either separator, absolute or relative). */\nfunction fileOf(snapshot: GrimoireSnapshot, file: string): string {\n return projectPath(snapshot.root, toPosixPath(file.trim()));\n}\n\nfunction bookFile(snapshot: GrimoireSnapshot, file: string): BookFile {\n const found = snapshot.book.facts.files.find((item) => item.file === file);\n\n if (!found) {\n const roots = [\n ...new Set(snapshot.book.facts.files.map((item) => item.file.split(\"/\")[0] ?? \"\")),\n ]\n .filter((root) => root !== \"\")\n .sort(byText);\n\n throw new GrimoireError(\n \"GR9001\",\n `${file} is not in the book. Pass a code file under ${roots.join(\", \") || \"the source roots\"} as a project-relative path; if the file is new, run warlock grimoire build.`,\n );\n }\n\n return found;\n}\n\n/** The written app id that shows a site, or the site id when no written app matches it. */\nfunction siteApp(snapshot: GrimoireSnapshot, site: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.site?.id === site);\n\n return match?.app ?? site;\n}\n\n/** The written app id of a mobile app, or its own id. */\nfunction mobileApp(snapshot: GrimoireSnapshot, mobile: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.mobile?.id === mobile);\n\n return match?.app ?? mobile;\n}\n\n/** The project files a file imports only through type-only imports, sorted. */\nfunction typeOnlyImportsOf(file: BookFile): string[] {\n const value = new Set<string>();\n const typeOnly = new Set<string>();\n\n for (const entry of file.imports) {\n if (entry.file === null) continue;\n\n (entry.typeOnly === true ? typeOnly : value).add(entry.file);\n }\n\n return sortedUnique([...typeOnly].filter((target) => !value.has(target)));\n}\n\n/** The book entry of one file, as the book writes it. */\nfunction entryOf(snapshot: GrimoireSnapshot, file: BookFile): BookEntry {\n const facts = snapshot.book.facts;\n const annotation = snapshot.annotations.files[file.file];\n const routeRef = (route: BookRoute) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n });\n const routes = facts.routes ?? [];\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n file: file.file,\n module: file.module,\n type: file.type,\n lines: file.lines,\n about: file.about,\n feature: annotation?.feature ?? null,\n borrowedBy: sortedUnique(annotation?.borrowedBy ?? []),\n flows: sortedUnique(annotation?.flows ?? []),\n exports: file.exports.map((entry) => ({ name: entry.name, about: entry.about })),\n // The same list the book entry holds (bare Node builtins such as `fs` left out too).\n packages: packagesOf(file),\n imports: sortedUnique(\n file.imports.flatMap((entry) => (entry.file === null ? [] : [entry.file])),\n ),\n // The same rule as the book entry: project files whose every import edge is type-only.\n typeOnlyImports: typeOnlyImportsOf(file),\n importedBy: sortedUnique(file.importedBy),\n routes: [\n ...routes\n .filter((route) => route.sourceFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"registers\" as const })),\n ...routes\n .filter((route) => route.handlerFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"handles\" as const })),\n ],\n pages: facts.pages\n .flatMap((page) => [\n ...(page.file === file.file\n ? [{ site: page.site, route: page.route, via: \"page\" as const }]\n : []),\n ...(page.setupFile === file.file\n ? [{ site: page.site, route: page.route, via: \"setup\" as const }]\n : []),\n ...(page.layouts.includes(file.file)\n ? [{ site: page.site, route: page.route, via: \"layout\" as const }]\n : []),\n ])\n .sort(\n (left, right) =>\n byText(left.site, right.site) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n screens: facts.mobile\n .flatMap((app) =>\n app.screens.flatMap((screen) => [\n ...(screen.file === file.file\n ? [{ app: app.id, route: screen.route, via: \"screen\" as const }]\n : []),\n ...(screen.layouts.includes(file.file)\n ? [{ app: app.id, route: screen.route, via: \"layout\" as const }]\n : []),\n ]),\n )\n .sort(\n (left, right) =>\n byText(left.app, right.app) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n };\n}\n\n/** Where the book keeps the entry of `file`, or `null` when it has none. */\nfunction bookEntryOf(snapshot: GrimoireSnapshot, file: string): string | null {\n const facts = snapshot.book.facts;\n const roots = new Map(facts.mobile.map((app) => [app.id, app.root]));\n const paths = bookEntryPaths(\n facts.files.map((item) => {\n const root = item.mobileApp === null ? undefined : roots.get(item.mobileApp);\n\n return {\n file: item.file,\n mobileApp:\n item.mobileApp === null || root === undefined ? null : { id: item.mobileApp, root },\n };\n }),\n );\n const entry = paths.get(file);\n\n return entry === undefined || entry.split(\"/\").includes(\"..\") ? null : entry;\n}\n\nfunction scryFile(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"file\" }>,\n): ScryFileResult {\n const file = bookFile(snapshot, fileOf(snapshot, query.file));\n\n return {\n type: \"file\",\n ...notesOf(snapshot, false),\n entry: entryOf(snapshot, file),\n bookEntry: bookEntryOf(snapshot, file.file),\n };\n}\n\nfunction flowBookmaps(snapshot: GrimoireSnapshot): FlowBookmap[] {\n return Object.values(snapshot.collected.flows).sort((left, right) => byText(left.ref, right.ref));\n}\n\nfunction scryImpact(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"impact\" }>,\n): ScryImpactResult {\n const facts = snapshot.book.facts;\n const target = bookFile(snapshot, fileOf(snapshot, query.file));\n const graph = fileGraph(facts.files);\n const reach = new Set(importerClosure(graph, [target.file]));\n const importers = [...reach].filter((file) => file !== target.file).sort(byText);\n const routes = (facts.routes ?? []).filter(\n (route) =>\n !route.isPage &&\n (route.handlerFile !== null\n ? reach.has(route.handlerFile)\n : route.sourceFile !== null && reach.has(route.sourceFile)),\n );\n const pages: ScryPageRef[] = [\n ...facts.pages\n .filter(\n (page) =>\n reach.has(page.file) ||\n (page.setupFile !== null && reach.has(page.setupFile)) ||\n page.layouts.some((layout) => reach.has(layout)),\n )\n .map((page) => ({\n app: siteApp(snapshot, page.site),\n route: page.route,\n file: page.file,\n type: \"page\" as const,\n })),\n ...facts.mobile.flatMap((app) =>\n app.screens\n .filter(\n (screen) => reach.has(screen.file) || screen.layouts.some((layout) => reach.has(layout)),\n )\n .map((screen) => ({\n app: mobileApp(snapshot, app.id),\n route: screen.route,\n file: screen.file,\n type: \"screen\" as const,\n })),\n ),\n ];\n const flows = flowBookmaps(snapshot)\n .filter((bookmap) =>\n bookmap.steps.some(\n (step) => step.files.includes(target.file) || step.typeOnlyFiles.includes(target.file),\n ),\n )\n .map((bookmap) => bookmap.ref);\n const ownership = snapshot.ownership.files;\n const owner = ownership[target.file]?.owner ?? null;\n // Looked up once per importer: an app with thousands of files stays linear.\n const specFiles = new Set(\n facts.files.filter((item) => item.type === \"spec\").map((item) => item.file),\n );\n const borrowers = sortedUnique([\n ...(ownership[target.file]?.borrowedBy ?? []),\n ...importers.flatMap((file) => {\n const ownerOf = ownership[file]?.owner;\n\n return ownerOf === undefined || ownerOf === null || specFiles.has(file) ? [] : [ownerOf];\n }),\n ]).filter((feature) => feature !== owner);\n const testFiles = new Set(facts.tests);\n const flowSet = new Set(flows);\n const tests = sortedUnique([\n ...importers.filter((file) => testFiles.has(file) || specFiles.has(file)),\n ...snapshot.proofs.filter((proof) => flowSet.has(proof.ref)).map((proof) => proof.at.file),\n ]);\n\n return {\n type: \"impact\",\n ...notesOf(snapshot, true),\n file: target.file,\n importers: { direct: sortedUnique(target.importedBy), all: importers },\n routes: routes.map((route) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n handlerFile: route.handlerFile,\n })),\n pages,\n flows,\n features: [\n ...(owner === null ? [] : [{ id: owner, via: \"owner\" as const }]),\n ...borrowers.map((id) => ({ id, via: \"borrower\" as const })),\n ],\n tests,\n };\n}\n\nfunction scryRoute(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"route\" }>,\n): ScryRouteResult {\n const facts = snapshot.book.facts;\n const method = query.method.toUpperCase();\n const asked = `${method} ${query.path}`;\n\n if (facts.routes === null) {\n throw new GrimoireError(\n \"GR9002\",\n `No route facts yet, so ${asked} cannot be looked up. Run warlock grimoire build (it boots the app once to read the routes), then ask again.`,\n );\n }\n\n const route = facts.routes.find((item) => routeMatches(item, method, query.path));\n\n if (!route) {\n const samePath = facts.routes\n .filter((item) => normalizeRoutePath(item.path) === normalizeRoutePath(query.path))\n .map((item) => `${item.method} ${item.path}`);\n const hint =\n samePath.length > 0\n ? ` Routes on that path: ${samePath.join(\", \")}.`\n : \" Run warlock routes to list them, or warlock grimoire build when the route is new.\";\n\n throw new GrimoireError(\"GR9002\", `No route matches ${asked}.${hint}`);\n }\n\n const graph = fileGraph(facts.files);\n const start = route.handlerFile ?? route.sourceFile;\n const files = start === null ? [] : importClosure(graph, [start]);\n const steps = snapshot.written.features.flatMap((feature) =>\n feature.flows.flatMap((flow) =>\n flow.steps\n .filter(\n (step) =>\n step.type === \"route\" &&\n step.route !== null &&\n routeMatches(route, step.route.method, step.route.path),\n )\n .map((step) => ({ flow: flow.ref, index: step.index })),\n ),\n );\n const page = route.isPage\n ? (facts.pages.find((item) => item.file === route.handlerFile) ??\n facts.pages.find(\n (item) => normalizeRoutePath(item.route) === normalizeRoutePath(route.path),\n ) ??\n null)\n : null;\n\n return {\n type: \"route\",\n ...notesOf(snapshot, true),\n route,\n files,\n steps: steps.sort((left, right) => byText(left.flow, right.flow) || left.index - right.index),\n page,\n };\n}\n\nfunction writtenFeature(snapshot: GrimoireSnapshot, id: string): WrittenFeature {\n const feature = snapshot.written.features.find((item) => item.id === id);\n\n if (!feature) {\n const known = snapshot.written.features.map((item) => item.id).sort(byText);\n const list =\n known.length > 0\n ? ` Features: ${known.join(\", \")}.`\n : \" The project has no grimoire/features/ folder yet.\";\n\n throw new GrimoireError(\"GR9003\", `No feature has the id ${JSON.stringify(id)}.${list}`);\n }\n\n return feature;\n}\n\nfunction findingsFor(\n snapshot: GrimoireSnapshot,\n match: (finding: GrimoireFinding) => boolean,\n): GrimoireFinding[] {\n return checkGrimoire(snapshot).findings.filter(match);\n}\n\nfunction emptyFeatureBookmap(feature: string): FeatureBookmap {\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature,\n own: [],\n borrowed: [],\n routes: [],\n pages: {},\n unreached: [],\n };\n}\n\nfunction scryFeature(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"feature\" }>,\n): ScryFeatureResult {\n const feature = writtenFeature(snapshot, query.feature);\n\n if (feature.readme === null) {\n throw new GrimoireError(\n \"GR9003\",\n `grimoire/features/${feature.id} has no README.md, so the feature cannot be shown. Write the README (see warlock grimoire check), then ask again.`,\n );\n }\n\n return {\n type: \"feature\",\n ...notesOf(snapshot, false),\n readme: feature.readme,\n flows: [...feature.flows]\n .sort((left, right) => byText(left.id.value, right.id.value))\n .map((flow) => ({\n id: flow.id.value,\n status: flow.status.value,\n since: flow.since.value,\n heading: flow.heading?.value ?? null,\n })),\n bookmap: snapshot.collected.features[feature.id] ?? emptyFeatureBookmap(feature.id),\n changes: (feature.changelog?.entries ?? []).slice(0, 10),\n tasks: snapshot.collected.tasksIndex.open.filter((task) => task.feature === feature.id),\n findings: findingsFor(\n snapshot,\n (finding) =>\n finding.subject.feature === feature.id ||\n (finding.subject.flow ?? \"\").startsWith(`${feature.id}/`),\n ),\n };\n}\n\nfunction scryFlow(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"flow\" }>,\n): ScryFlowResult {\n const feature = writtenFeature(snapshot, query.feature);\n const flow: WrittenFlow | undefined = feature.flows.find((item) => item.id.value === query.flow);\n\n if (!flow) {\n const known = feature.flows.map((item) => item.id.value).sort(byText);\n const list =\n known.length > 0\n ? ` Flows of ${feature.id}: ${known.join(\", \")}.`\n : ` ${feature.id} has no flows yet.`;\n\n throw new GrimoireError(\"GR9004\", `No flow ${feature.id}/${query.flow}.${list}`);\n }\n\n const bookmap =\n Object.values(snapshot.collected.flows).find(\n (item) => item.feature === feature.id && item.flow === flow.id.value,\n ) ?? snapshot.collected.flows[flow.ref];\n\n if (!bookmap) {\n throw new GrimoireError(\n \"GR9004\",\n `${flow.ref} has no book map yet. Run warlock grimoire build, then ask again.`,\n );\n }\n\n return {\n type: \"flow\",\n ...notesOf(snapshot, true),\n flow,\n bookmap,\n history: (feature.changelog?.entries ?? []).filter((entry) => entry.flow === flow.id.value),\n findings: findingsFor(snapshot, (finding) => finding.subject.flow === flow.ref),\n };\n}\n\n// ── Search ─────────────────────────────────────────────────────────────────\n\nconst TYPE_ORDER: readonly ScryHitType[] = [\n \"feature\",\n \"flow\",\n \"block\",\n \"page\",\n \"screen\",\n \"route\",\n \"mail\",\n \"job\",\n \"file\",\n \"export\",\n \"task\",\n];\n\n/** Lower-case words: `catalog/new-arrivals.service.ts` → `catalog new arrivals service ts`. */\nfunction words(text: string): string {\n return text\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \" \")\n .trim();\n}\n\n/** The last segment of an id (`catalog/new-arrivals` → `new-arrivals`). */\nfunction lastSegment(id: string): string {\n const parts = id.split(/[\\s/#]+/).filter((part) => part !== \"\");\n\n return parts[parts.length - 1] ?? id;\n}\n\n/** The slug of a block name (`New arrivals` → `new-arrivals`). */\nfunction slug(text: string): string {\n return words(text).split(\" \").join(\"-\");\n}\n\ntype Candidate = Omit<ScryHit, \"score\">;\n\nfunction candidates(snapshot: GrimoireSnapshot): Candidate[] {\n const facts = snapshot.book.facts;\n const list: Candidate[] = [];\n\n for (const feature of snapshot.written.features) {\n list.push({ type: \"feature\", id: feature.id, detail: feature.readme?.title.value ?? null });\n\n for (const flow of feature.flows) {\n list.push({ type: \"flow\", id: flow.ref, detail: flow.heading?.value ?? null });\n }\n }\n\n for (const app of snapshot.written.apps) {\n const appId = app.id.value;\n\n for (const layout of app.layouts) {\n for (const row of layout.blocks) {\n list.push({\n type: \"block\",\n id: `${appId}/${layout.id}/${slug(row.block)}`,\n detail: row.flow ?? row.block,\n });\n }\n }\n\n for (const page of [...app.pages, ...app.screens]) {\n for (const row of page.blocks) {\n list.push({\n type: \"block\",\n id: `${appId}/${page.id}/${slug(row.block)}`,\n detail: row.flow ?? row.block,\n });\n }\n }\n }\n\n for (const page of facts.pages) {\n list.push({\n type: \"page\",\n id: `${siteApp(snapshot, page.site)} ${page.route}`,\n detail: page.file,\n });\n }\n\n for (const app of facts.mobile) {\n for (const screen of app.screens) {\n list.push({\n type: \"screen\",\n id: `${mobileApp(snapshot, app.id)} ${screen.route}`,\n detail: screen.file,\n });\n }\n }\n\n for (const route of facts.routes ?? []) {\n if (route.isPage) continue;\n\n list.push({ type: \"route\", id: `${route.method} ${route.path}`, detail: route.name });\n }\n\n for (const thing of facts.named) {\n if (thing.type !== \"mail\" && thing.type !== \"job\") continue;\n\n list.push({ type: thing.type, id: thing.name, detail: thing.file });\n }\n\n for (const file of facts.files) {\n list.push({ type: \"file\", id: file.file, detail: file.about });\n\n for (const entry of file.exports) {\n if (entry.name === \"default\" || entry.name === \"*\") continue;\n\n list.push({ type: \"export\", id: `${file.file}#${entry.name}`, detail: entry.about });\n }\n }\n\n for (const task of [\n ...snapshot.collected.tasksIndex.open,\n ...snapshot.collected.tasksIndex.done,\n ]) {\n list.push({ type: \"task\", id: task.id, detail: task.title });\n }\n\n return list;\n}\n\n/** Whether every character of `needle` appears in `text` in order. */\nfunction isSubsequence(needle: string, text: string): boolean {\n let position = 0;\n\n for (const char of text) {\n if (char === needle[position]) position++;\n\n if (position === needle.length) return true;\n }\n\n return needle.length === 0;\n}\n\n/** Shortest query that may match by fuzzy (in-order letters), so short queries stay precise. */\nconst FUZZY_MIN = 4;\n\n/**\n * Score of a candidate for the query words, or 0 when it does not match. From best\n * to worst: exact name or path (7), prefix (6), whole-word match (5), substring of\n * the name or path (4), the words found only in the detail (3), fuzzy (2).\n */\nfunction scoreOf(candidate: Candidate, query: string, tokens: readonly string[]): number {\n const id = words(\n candidate.type === \"export\" ? (candidate.id.split(\"#\")[1] ?? candidate.id) : candidate.id,\n );\n const last = words(lastSegment(candidate.id));\n const all = `${id} ${words(candidate.detail ?? \"\")}`;\n\n if (!tokens.every((token) => all.includes(token))) {\n const squeezed = id.replace(/ /g, \"\");\n\n return query.length >= FUZZY_MIN && tokens.every((token) => isSubsequence(token, squeezed))\n ? 2\n : 0;\n }\n\n if (id === query || last === query) return 7;\n if (id.startsWith(query) || last.startsWith(query)) return 6;\n\n const idWords = id.split(\" \");\n\n if (tokens.every((token) => idWords.includes(token))) return 5;\n if (tokens.every((token) => id.includes(token))) return 4;\n\n return 3;\n}\n\nfunction scrySearch(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"search\" }>,\n): ScrySearchResult {\n const text = words(query.text);\n const tokens = text.split(\" \").filter((token) => token !== \"\");\n\n if (tokens.length === 0) {\n throw new GrimoireError(\n \"GR9006\",\n `Search text ${JSON.stringify(query.text)} has no letters or digits; pass a word to look for.`,\n );\n }\n\n const seen = new Set<string>();\n const hits: ScryHit[] = [];\n\n for (const candidate of candidates(snapshot)) {\n const key = `${candidate.type} ${candidate.id}`;\n\n if (seen.has(key)) continue;\n\n seen.add(key);\n\n const score = scoreOf(candidate, text, tokens);\n\n if (score > 0) hits.push({ ...candidate, score });\n }\n\n hits.sort(\n (left, right) =>\n right.score - left.score ||\n TYPE_ORDER.indexOf(left.type) - TYPE_ORDER.indexOf(right.type) ||\n byText(left.id, right.id),\n );\n\n return {\n type: \"search\",\n ...notesOf(snapshot, false),\n text: query.text,\n hits: hits.slice(0, query.limit ?? 20),\n };\n}\n\n/**\n * Answer one query. Throws a `GrimoireError`: `GR9001` for a file not in the\n * book, `GR9002` no route, `GR9003` no feature, `GR9004` no flow, `GR9006`\n * a search with no words. Pure.\n */\nexport function scry(snapshot: GrimoireSnapshot, query: ScryQuery): ScryResult {\n switch (query.type) {\n case \"file\":\n return scryFile(snapshot, query);\n case \"impact\":\n return scryImpact(snapshot, query);\n case \"route\":\n return scryRoute(snapshot, query);\n case \"feature\":\n return scryFeature(snapshot, query);\n case \"flow\":\n return scryFlow(snapshot, query);\n case \"search\":\n return scrySearch(snapshot, query);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChG,MAAM,gBAAgB,UAAsC,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,MAAM;;AAG3F,SAAS,QAAQ,UAA4B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AM;EACN,GAAG,QAAQ,UAAU,KAAK;EAC1B,MAAM,MAAM;EACZ,MAAM,KAAK,MAAM,GAAG,MAAM,SAAS,EAAE;CACvC;AACF;;;;;;AAOA,SAAgB,KAAK,UAA4B,OAA8B;CAC7E,QAAQ,MAAM,MAAd;EACE,KAAK,QACH,OAAO,SAAS,UAAU,KAAK;EACjC,KAAK,UACH,OAAO,WAAW,UAAU,KAAK;EACnC,KAAK,SACH,OAAO,UAAU,UAAU,KAAK;EAClC,KAAK,WACH,OAAO,YAAY,UAAU,KAAK;EACpC,KAAK,QACH,OAAO,SAAS,UAAU,KAAK;EACjC,KAAK,UACH,OAAO,WAAW,UAAU,KAAK;CACrC;AACF"}
|
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import { TestResultsStore } from "../contracts/test-results.mjs";
|
|
2
2
|
import { CriterionTestResult, criterionStatus } from "./criterion-status.mjs";
|
|
3
3
|
//#region ../../packages/grimoire/src/test-results/index.d.ts
|
|
4
|
-
/**
|
|
5
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Read the results store (`grimoire/book/test-results.json`, or `file`);
|
|
6
|
+
* `null` when absent or unreadable.
|
|
7
|
+
*
|
|
8
|
+
* @param file Project-relative or absolute path of another results file.
|
|
9
|
+
*/
|
|
10
|
+
export declare function readTestResults(root: string, file?: string): Promise<TestResultsStore | null>;
|
|
6
11
|
//#endregion
|
|
7
12
|
export { type CriterionTestResult, criterionStatus };
|
|
8
13
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/test-results/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/test-results/index.ts"],"mappings":";;;;;;;;;wBAuDsB,gBAAgB,cAAc,gBAAgB,QAAQ"}
|
|
@@ -9,16 +9,38 @@ import { readFileSync } from "node:fs";
|
|
|
9
9
|
//#region ../../packages/grimoire/src/test-results/index.ts
|
|
10
10
|
/**
|
|
11
11
|
* Test results per criterion: reading, merging, writing the store the Vitest
|
|
12
|
-
* reporter fills, and the check rules over it (`GR4006`–`
|
|
12
|
+
* reporter fills, and the check rules over it (`GR4006`–`GR4010`).
|
|
13
13
|
*/
|
|
14
14
|
/** sha256 (hex) of a test file's bytes: the value stored as `testFileHash`. */
|
|
15
15
|
function hashTestFile(content) {
|
|
16
16
|
return createHash("sha256").update(content).digest("hex");
|
|
17
17
|
}
|
|
18
|
-
/**
|
|
19
|
-
|
|
18
|
+
/**
|
|
19
|
+
* The absolute path of the results file: `file` (project-relative or
|
|
20
|
+
* absolute) when given, else `grimoire/book/test-results.json`.
|
|
21
|
+
*/
|
|
22
|
+
function resolveResultsFile(root, file) {
|
|
23
|
+
return file === void 0 || file === "" ? path.join(root, ...GRIMOIRE_PATHS.testResults.split("/")) : path.resolve(root, file);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The results file as the snapshot reports it: project-relative POSIX when it
|
|
27
|
+
* lies inside the project, else the absolute path.
|
|
28
|
+
*/
|
|
29
|
+
function resultsFileLabel(root, file) {
|
|
30
|
+
const absolute = resolveResultsFile(root, file);
|
|
31
|
+
const relative = path.relative(root, absolute);
|
|
32
|
+
if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return toPosixPath(absolute);
|
|
33
|
+
return toPosixPath(relative);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Read the results store (`grimoire/book/test-results.json`, or `file`);
|
|
37
|
+
* `null` when absent or unreadable.
|
|
38
|
+
*
|
|
39
|
+
* @param file Project-relative or absolute path of another results file.
|
|
40
|
+
*/
|
|
41
|
+
async function readTestResults(root, file) {
|
|
20
42
|
try {
|
|
21
|
-
const parsed = JSON.parse(await readFile(
|
|
43
|
+
const parsed = JSON.parse(await readFile(resolveResultsFile(root, file), "utf8"));
|
|
22
44
|
if (!isStore(parsed)) return null;
|
|
23
45
|
return parsed;
|
|
24
46
|
} catch {
|
|
@@ -30,6 +52,24 @@ function isStore(value) {
|
|
|
30
52
|
const store = value;
|
|
31
53
|
return store.schemaVersion === 1 && Array.isArray(store.results);
|
|
32
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* What the readers know about the results store: whether one was read, where
|
|
57
|
+
* from, and how many `@proves` lines have a result. Lets a view tell "never
|
|
58
|
+
* recorded" from "did not run".
|
|
59
|
+
*/
|
|
60
|
+
function testResultsInfo(snapshot) {
|
|
61
|
+
const store = snapshot.results;
|
|
62
|
+
const results = store?.results ?? [];
|
|
63
|
+
const withResult = snapshot.proofs.filter((proof) => results.some((result) => toPosixPath(result.testFile) === toPosixPath(proof.at.file) && result.feature === proof.feature && result.flow === proof.flow && result.criterion === proof.criterion)).length;
|
|
64
|
+
return {
|
|
65
|
+
recorded: store !== null,
|
|
66
|
+
file: snapshot.resultsFile,
|
|
67
|
+
updatedAt: store?.updatedAt ?? null,
|
|
68
|
+
proofs: snapshot.proofs.length,
|
|
69
|
+
withResult,
|
|
70
|
+
unmatched: store?.unmatched?.length ?? 0
|
|
71
|
+
};
|
|
72
|
+
}
|
|
33
73
|
function compareResults(a, b) {
|
|
34
74
|
if (a.testFile !== b.testFile) return a.testFile < b.testFile ? -1 : 1;
|
|
35
75
|
if (a.line !== b.line) return a.line - b.line;
|
|
@@ -43,19 +83,21 @@ function compareResults(a, b) {
|
|
|
43
83
|
*
|
|
44
84
|
* @param ranFiles Test files the run executed (even those with no proving test).
|
|
45
85
|
*/
|
|
46
|
-
function mergeTestResults(store, run, ranFiles, now) {
|
|
86
|
+
function mergeTestResults(store, run, ranFiles, now, unmatched = []) {
|
|
47
87
|
const ran = new Set([...ranFiles, ...run.map((result) => result.testFile)].map(toPosixPath));
|
|
48
88
|
const kept = (store?.results ?? []).filter((result) => !ran.has(toPosixPath(result.testFile)));
|
|
89
|
+
const allUnmatched = [...(store?.unmatched ?? []).filter((entry) => !ran.has(toPosixPath(entry.testFile))), ...unmatched].sort((a, b) => (a.testFile < b.testFile ? -1 : a.testFile > b.testFile ? 1 : 0) || a.line - b.line);
|
|
49
90
|
return {
|
|
50
91
|
schemaVersion: 1,
|
|
51
92
|
updatedAt: now.toISOString(),
|
|
52
93
|
runner: "vitest",
|
|
53
|
-
results: [...kept, ...run].sort(compareResults)
|
|
94
|
+
results: [...kept, ...run].sort(compareResults),
|
|
95
|
+
...allUnmatched.length > 0 ? { unmatched: allUnmatched } : {}
|
|
54
96
|
};
|
|
55
97
|
}
|
|
56
|
-
/** Write the store (atomically: temp file, then rename). */
|
|
57
|
-
async function writeTestResults(root, store) {
|
|
58
|
-
const target =
|
|
98
|
+
/** Write the store (atomically: temp file, then rename), to `file` when given. */
|
|
99
|
+
async function writeTestResults(root, store, file) {
|
|
100
|
+
const target = resolveResultsFile(root, file);
|
|
59
101
|
const temp = `${target}.${process.pid}.${Date.now()}.tmp`;
|
|
60
102
|
await mkdir(path.dirname(target), { recursive: true });
|
|
61
103
|
try {
|
|
@@ -66,10 +108,20 @@ async function writeTestResults(root, store) {
|
|
|
66
108
|
throw error;
|
|
67
109
|
}
|
|
68
110
|
}
|
|
69
|
-
/** The GR4006–
|
|
111
|
+
/** The GR4006–GR4010 rules. Read-only. */
|
|
70
112
|
function checkTestResults(snapshot) {
|
|
71
113
|
const store = snapshot.results;
|
|
72
|
-
if (!store)
|
|
114
|
+
if (!store) {
|
|
115
|
+
const first = snapshot.proofs[0];
|
|
116
|
+
return first === void 0 ? [] : [createFinding({
|
|
117
|
+
code: "GR4009",
|
|
118
|
+
message: `${snapshot.proofs.length} proving ${snapshot.proofs.length === 1 ? "test is" : "tests are"} written but no test results were found at ${snapshot.resultsFile}`,
|
|
119
|
+
at: first.at,
|
|
120
|
+
feature: first.feature,
|
|
121
|
+
flow: first.ref,
|
|
122
|
+
file: toPosixPath(first.at.file)
|
|
123
|
+
})];
|
|
124
|
+
}
|
|
73
125
|
const proposed = new Set(snapshot.written.features.flatMap((feature) => feature.flows.filter((flow) => flow.status.value === "proposed").map((flow) => flow.ref)));
|
|
74
126
|
const hashes = /* @__PURE__ */ new Map();
|
|
75
127
|
const currentHash = (file) => {
|
|
@@ -116,9 +168,24 @@ function checkTestResults(snapshot) {
|
|
|
116
168
|
findings.push(finding);
|
|
117
169
|
}
|
|
118
170
|
}
|
|
171
|
+
for (const entry of store.unmatched ?? []) {
|
|
172
|
+
const file = toPosixPath(entry.testFile);
|
|
173
|
+
const proof = snapshot.proofs.find((item) => toPosixPath(item.at.file) === file && item.at.line === entry.line && item.feature === entry.feature && item.flow === entry.flow && item.criterion === entry.criterion);
|
|
174
|
+
if (!proof) continue;
|
|
175
|
+
const finding = createFinding({
|
|
176
|
+
code: "GR4010",
|
|
177
|
+
message: `${proof.ref} ${proof.criterion}: the reporter could not match the test under this @proves line to a result`,
|
|
178
|
+
at: proof.at,
|
|
179
|
+
feature: proof.feature,
|
|
180
|
+
flow: proof.ref,
|
|
181
|
+
file
|
|
182
|
+
});
|
|
183
|
+
if (proposed.has(proof.ref)) finding.expected = true;
|
|
184
|
+
findings.push(finding);
|
|
185
|
+
}
|
|
119
186
|
return findings;
|
|
120
187
|
}
|
|
121
188
|
|
|
122
189
|
//#endregion
|
|
123
|
-
export { checkTestResults, criterionStatus, hashTestFile, mergeTestResults, readTestResults, writeTestResults };
|
|
190
|
+
export { checkTestResults, criterionStatus, hashTestFile, mergeTestResults, readTestResults, resolveResultsFile, resultsFileLabel, testResultsInfo, writeTestResults };
|
|
124
191
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/test-results/index.ts"],"sourcesContent":["/**\n * Test results per criterion: reading, merging, writing the store the Vitest\n * reporter fills, and the check rules over it (`GR4006`–`GR4008`).\n */\nimport { createHash } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { createFinding } from \"../codes\";\nimport { GRIMOIRE_PATHS, toPosixPath } from \"../paths\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { ProofResult, TestResultsStore } from \"../contracts/test-results\";\n\nexport { criterionStatus, type CriterionTestResult } from \"./criterion-status\";\n\n/** sha256 (hex) of a test file's bytes: the value stored as `testFileHash`. */\nexport function hashTestFile(content: string | Uint8Array): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\n/** Read `grimoire/book/test-results.json`; `null` when absent or unreadable. */\nexport async function readTestResults(root: string): Promise<TestResultsStore | null> {\n try {\n const parsed: unknown = JSON.parse(\n await readFile(path.join(root, GRIMOIRE_PATHS.testResults), \"utf8\"),\n );\n\n if (!isStore(parsed)) return null;\n\n return parsed;\n } catch {\n return null;\n }\n}\n\nfunction isStore(value: unknown): value is TestResultsStore {\n if (typeof value !== \"object\" || value === null) return false;\n\n const store = value as Partial<TestResultsStore>;\n\n return store.schemaVersion === 1 && Array.isArray(store.results);\n}\n\nfunction compareResults(a: ProofResult, b: ProofResult): number {\n if (a.testFile !== b.testFile) return a.testFile < b.testFile ? -1 : 1;\n if (a.line !== b.line) return a.line - b.line;\n if (a.feature !== b.feature) return a.feature < b.feature ? -1 : 1;\n if (a.flow !== b.flow) return a.flow < b.flow ? -1 : 1;\n\n return a.criterion < b.criterion ? -1 : a.criterion > b.criterion ? 1 : 0;\n}\n\n/**\n * Merge one run into the store: results of the test files the run covered\n * replace the old ones; results of other files stay. Pure.\n *\n * @param ranFiles Test files the run executed (even those with no proving test).\n */\nexport function mergeTestResults(\n store: TestResultsStore | null,\n run: readonly ProofResult[],\n ranFiles: readonly string[],\n now: Date,\n): TestResultsStore {\n const ran = new Set([...ranFiles, ...run.map((result) => result.testFile)].map(toPosixPath));\n const kept = (store?.results ?? []).filter((result) => !ran.has(toPosixPath(result.testFile)));\n\n return {\n schemaVersion: 1,\n updatedAt: now.toISOString(),\n runner: \"vitest\",\n results: [...kept, ...run].sort(compareResults),\n };\n}\n\n/** Write the store (atomically: temp file, then rename). */\nexport async function writeTestResults(root: string, store: TestResultsStore): Promise<void> {\n const target = path.join(root, GRIMOIRE_PATHS.testResults);\n const temp = `${target}.${process.pid}.${Date.now()}.tmp`;\n\n await mkdir(path.dirname(target), { recursive: true });\n\n try {\n await writeFile(temp, `${JSON.stringify(store, null, 2)}\\n`, \"utf8\");\n await rename(temp, target);\n } catch (error) {\n await rm(temp, { force: true });\n\n throw error;\n }\n}\n\n/** The GR4006–GR4008 rules. Read-only; nothing when no results exist. */\nexport function checkTestResults(snapshot: GrimoireSnapshot): GrimoireFinding[] {\n const store = snapshot.results;\n\n if (!store) return [];\n\n const proposed = new Set(\n snapshot.written.features.flatMap((feature) =>\n feature.flows.filter((flow) => flow.status.value === \"proposed\").map((flow) => flow.ref),\n ),\n );\n const hashes = new Map<string, string | null>();\n const currentHash = (file: string): string | null => {\n if (!hashes.has(file)) {\n try {\n hashes.set(file, hashTestFile(readFileSync(path.join(snapshot.root, file))));\n } catch {\n hashes.set(file, null);\n }\n }\n\n return hashes.get(file) ?? null;\n };\n const findings: GrimoireFinding[] = [];\n\n for (const proof of snapshot.proofs) {\n const file = toPosixPath(proof.at.file);\n const candidates = store.results.filter(\n (result) =>\n toPosixPath(result.testFile) === file &&\n result.feature === proof.feature &&\n result.flow === proof.flow &&\n result.criterion === proof.criterion,\n );\n const result = candidates.find((item) => item.outcome === \"fail\") ?? candidates[0];\n const label = `${proof.ref} ${proof.criterion}`;\n const base = { at: proof.at, feature: proof.feature, flow: proof.ref, file };\n let finding: GrimoireFinding | null = null;\n\n if (!result || result.outcome === \"skip\") {\n finding = createFinding({\n ...base,\n code: \"GR4008\",\n message: `${label}: its test did not run in the last run${proof.test?.name ? ` (\"${proof.test.name}\")` : \"\"}`,\n });\n } else if (result.outcome === \"fail\") {\n finding = createFinding({\n ...base,\n code: \"GR4006\",\n message: `${label}: its test failed in the last run (\"${result.testName}\")`,\n });\n } else {\n const hash = currentHash(file);\n\n if (hash !== null && hash !== result.testFileHash) {\n finding = createFinding({\n ...base,\n code: \"GR4007\",\n message: `${label}: its result is older than ${file} (ran ${result.ranAt})`,\n });\n }\n }\n\n if (finding) {\n if (proposed.has(proof.ref)) finding.expected = true;\n\n findings.push(finding);\n }\n }\n\n return findings;\n}\n"],"mappings":";;;;;;;;;;;;;;AAiBA,SAAgB,aAAa,SAAsC;CACjE,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,OAAO,KAAK;AAC1D;;AAGA,eAAsB,gBAAgB,MAAgD;CACpF,IAAI;EACF,MAAM,SAAkB,KAAK,MAC3B,MAAM,SAAS,KAAK,KAAK,MAAM,eAAe,WAAW,GAAG,MAAM,CACpE;EAEA,IAAI,CAAC,QAAQ,MAAM,GAAG,OAAO;EAE7B,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,QAAQ,OAA2C;CAC1D,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CAExD,MAAM,QAAQ;CAEd,OAAO,MAAM,kBAAkB,KAAK,MAAM,QAAQ,MAAM,OAAO;AACjE;AAEA,SAAS,eAAe,GAAgB,GAAwB;CAC9D,IAAI,EAAE,aAAa,EAAE,UAAU,OAAO,EAAE,WAAW,EAAE,WAAW,KAAK;CACrE,IAAI,EAAE,SAAS,EAAE,MAAM,OAAO,EAAE,OAAO,EAAE;CACzC,IAAI,EAAE,YAAY,EAAE,SAAS,OAAO,EAAE,UAAU,EAAE,UAAU,KAAK;CACjE,IAAI,EAAE,SAAS,EAAE,MAAM,OAAO,EAAE,OAAO,EAAE,OAAO,KAAK;CAErD,OAAO,EAAE,YAAY,EAAE,YAAY,KAAK,EAAE,YAAY,EAAE,YAAY,IAAI;AAC1E;;;;;;;AAQA,SAAgB,iBACd,OACA,KACA,UACA,KACkB;CAClB,MAAM,MAAM,IAAI,IAAI,CAAC,GAAG,UAAU,GAAG,IA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AAI;EACvB;EAGF,OAAO,OAAO,IAAI,IAAI,KAAK;CAC7B;CACA,MAAM,WAA8B,CAAC;CAErC,KAAK,MAAM,SAAS,SAAS,QAAQ;EACnC,MAAM,OAAO,YAAY,MAAM,GAAG,IAAI;EACtC,MAAM,aAAa,MAAM,QAAQ,QAC9B,WACC,YAAY,OAAO,QAAQ,MAAM,QACjC,OAAO,YAAY,MAAM,WACzB,OAAO,SAAS,MAAM,QACtB,OAAO,cAAc,MAAM,SAC/B;EACA,MAAM,SAAS,WAAW,MAAM,SAAS,KAAK,YAAY,MAAM,KAAK,WAAW;EAChF,MAAM,QAAQ,GAAG,MAAM,IAAI,GAAG,MAAM;EACpC,MAAM,OAAO;GAAE,IAAI,MAAM;GAAI,SAAS,MAAM;GAAS,MAAM,MAAM;GAAK;EAAK;EAC3E,IAAI,UAAkC;EAEtC,IAAI,CAAC,UAAU,OAAO,YAAY,QAChC,UAAU,cAAc;GACtB,GAAG;GACH,MAAM;GACN,SAAS,GAAG,MAAM,wCAAwC,MAAM,MAAM,OAAO,MAAM,MAAM,KAAK,KAAK,MAAM;EAC3G,CAAC;OACI,IAAI,OAAO,YAAY,QAC5B,UAAU,cAAc;GACtB,GAAG;GACH,MAAM;GACN,SAAS,GAAG,MAAM,sCAAsC,OAAO,SAAS;EAC1E,CAAC;OACI;GACL,MAAM,OAAO,YAAY,IAAI;GAE7B,IAAI,SAAS,QAAQ,SAAS,OAAO,cACnC,UAAU,cAAc;IACtB,GAAG;IACH,MAAM;IACN,SAAS,GAAG,MAAM,6BAA6B,KAAK,QAAQ,OAAO,MAAM;GAC3E,CAAC;EAEL;EAEA,IAAI,SAAS;GACX,IAAI,SAAS,IAAI,MAAM,GAAG,GAAG,QAAQ,WAAW;GAEhD,SAAS,KAAK,OAAO;EACvB;CACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/test-results/index.ts"],"sourcesContent":["/**\n * Test results per criterion: reading, merging, writing the store the Vitest\n * reporter fills, and the check rules over it (`GR4006`–`GR4010`).\n */\nimport { createHash } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { createFinding } from \"../codes\";\nimport { GRIMOIRE_PATHS, toPosixPath } from \"../paths\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type {\n ProofResult,\n TestResultsInfo,\n TestResultsStore,\n UnmatchedProof,\n} from \"../contracts/test-results\";\n\nexport { criterionStatus, type CriterionTestResult } from \"./criterion-status\";\n\n/** sha256 (hex) of a test file's bytes: the value stored as `testFileHash`. */\nexport function hashTestFile(content: string | Uint8Array): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\n/**\n * The absolute path of the results file: `file` (project-relative or\n * absolute) when given, else `grimoire/book/test-results.json`.\n */\nexport function resolveResultsFile(root: string, file?: string): string {\n return file === undefined || file === \"\"\n ? path.join(root, ...GRIMOIRE_PATHS.testResults.split(\"/\"))\n : path.resolve(root, file);\n}\n\n/**\n * The results file as the snapshot reports it: project-relative POSIX when it\n * lies inside the project, else the absolute path.\n */\nexport function resultsFileLabel(root: string, file?: string): string {\n const absolute = resolveResultsFile(root, file);\n const relative = path.relative(root, absolute);\n\n if (relative === \"\" || relative.startsWith(\"..\") || path.isAbsolute(relative)) return toPosixPath(absolute);\n\n return toPosixPath(relative);\n}\n\n/**\n * Read the results store (`grimoire/book/test-results.json`, or `file`);\n * `null` when absent or unreadable.\n *\n * @param file Project-relative or absolute path of another results file.\n */\nexport async function readTestResults(root: string, file?: string): Promise<TestResultsStore | null> {\n try {\n const parsed: unknown = JSON.parse(await readFile(resolveResultsFile(root, file), \"utf8\"));\n\n if (!isStore(parsed)) return null;\n\n return parsed;\n } catch {\n return null;\n }\n}\n\nfunction isStore(value: unknown): value is TestResultsStore {\n if (typeof value !== \"object\" || value === null) return false;\n\n const store = value as Partial<TestResultsStore>;\n\n return store.schemaVersion === 1 && Array.isArray(store.results);\n}\n\n/**\n * What the readers know about the results store: whether one was read, where\n * from, and how many `@proves` lines have a result. Lets a view tell \"never\n * recorded\" from \"did not run\".\n */\nexport function testResultsInfo(snapshot: GrimoireSnapshot): TestResultsInfo {\n const store = snapshot.results;\n const results = store?.results ?? [];\n const withResult = snapshot.proofs.filter((proof) =>\n results.some(\n (result) =>\n toPosixPath(result.testFile) === toPosixPath(proof.at.file) &&\n result.feature === proof.feature &&\n result.flow === proof.flow &&\n result.criterion === proof.criterion,\n ),\n ).length;\n\n return {\n recorded: store !== null,\n file: snapshot.resultsFile,\n updatedAt: store?.updatedAt ?? null,\n proofs: snapshot.proofs.length,\n withResult,\n unmatched: store?.unmatched?.length ?? 0,\n };\n}\n\nfunction compareResults(a: ProofResult, b: ProofResult): number {\n if (a.testFile !== b.testFile) return a.testFile < b.testFile ? -1 : 1;\n if (a.line !== b.line) return a.line - b.line;\n if (a.feature !== b.feature) return a.feature < b.feature ? -1 : 1;\n if (a.flow !== b.flow) return a.flow < b.flow ? -1 : 1;\n\n return a.criterion < b.criterion ? -1 : a.criterion > b.criterion ? 1 : 0;\n}\n\n/**\n * Merge one run into the store: results of the test files the run covered\n * replace the old ones; results of other files stay. Pure.\n *\n * @param ranFiles Test files the run executed (even those with no proving test).\n */\nexport function mergeTestResults(\n store: TestResultsStore | null,\n run: readonly ProofResult[],\n ranFiles: readonly string[],\n now: Date,\n unmatched: readonly UnmatchedProof[] = [],\n): TestResultsStore {\n const ran = new Set([...ranFiles, ...run.map((result) => result.testFile)].map(toPosixPath));\n const kept = (store?.results ?? []).filter((result) => !ran.has(toPosixPath(result.testFile)));\n const keptUnmatched = (store?.unmatched ?? []).filter(\n (entry) => !ran.has(toPosixPath(entry.testFile)),\n );\n const allUnmatched = [...keptUnmatched, ...unmatched].sort(\n (a, b) => (a.testFile < b.testFile ? -1 : a.testFile > b.testFile ? 1 : 0) || a.line - b.line,\n );\n\n return {\n schemaVersion: 1,\n updatedAt: now.toISOString(),\n runner: \"vitest\",\n results: [...kept, ...run].sort(compareResults),\n ...(allUnmatched.length > 0 ? { unmatched: allUnmatched } : {}),\n };\n}\n\n/** Write the store (atomically: temp file, then rename), to `file` when given. */\nexport async function writeTestResults(\n root: string,\n store: TestResultsStore,\n file?: string,\n): Promise<void> {\n const target = resolveResultsFile(root, file);\n const temp = `${target}.${process.pid}.${Date.now()}.tmp`;\n\n await mkdir(path.dirname(target), { recursive: true });\n\n try {\n await writeFile(temp, `${JSON.stringify(store, null, 2)}\\n`, \"utf8\");\n await rename(temp, target);\n } catch (error) {\n await rm(temp, { force: true });\n\n throw error;\n }\n}\n\n/** The GR4006–GR4010 rules. Read-only. */\nexport function checkTestResults(snapshot: GrimoireSnapshot): GrimoireFinding[] {\n const store = snapshot.results;\n\n if (!store) {\n const first = snapshot.proofs[0];\n\n // Proofs exist and no run ever wrote results: one finding for the project, at the first proof.\n return first === undefined\n ? []\n : [\n createFinding({\n code: \"GR4009\",\n message: `${snapshot.proofs.length} proving ${snapshot.proofs.length === 1 ? \"test is\" : \"tests are\"} written but no test results were found at ${snapshot.resultsFile}`,\n at: first.at,\n feature: first.feature,\n flow: first.ref,\n file: toPosixPath(first.at.file),\n }),\n ];\n }\n\n const proposed = new Set(\n snapshot.written.features.flatMap((feature) =>\n feature.flows.filter((flow) => flow.status.value === \"proposed\").map((flow) => flow.ref),\n ),\n );\n const hashes = new Map<string, string | null>();\n const currentHash = (file: string): string | null => {\n if (!hashes.has(file)) {\n try {\n hashes.set(file, hashTestFile(readFileSync(path.join(snapshot.root, file))));\n } catch {\n hashes.set(file, null);\n }\n }\n\n return hashes.get(file) ?? null;\n };\n const findings: GrimoireFinding[] = [];\n\n for (const proof of snapshot.proofs) {\n const file = toPosixPath(proof.at.file);\n const candidates = store.results.filter(\n (result) =>\n toPosixPath(result.testFile) === file &&\n result.feature === proof.feature &&\n result.flow === proof.flow &&\n result.criterion === proof.criterion,\n );\n const result = candidates.find((item) => item.outcome === \"fail\") ?? candidates[0];\n const label = `${proof.ref} ${proof.criterion}`;\n const base = { at: proof.at, feature: proof.feature, flow: proof.ref, file };\n let finding: GrimoireFinding | null = null;\n\n if (!result || result.outcome === \"skip\") {\n finding = createFinding({\n ...base,\n code: \"GR4008\",\n message: `${label}: its test did not run in the last run${proof.test?.name ? ` (\"${proof.test.name}\")` : \"\"}`,\n });\n } else if (result.outcome === \"fail\") {\n finding = createFinding({\n ...base,\n code: \"GR4006\",\n message: `${label}: its test failed in the last run (\"${result.testName}\")`,\n });\n } else {\n const hash = currentHash(file);\n\n if (hash !== null && hash !== result.testFileHash) {\n finding = createFinding({\n ...base,\n code: \"GR4007\",\n message: `${label}: its result is older than ${file} (ran ${result.ranAt})`,\n });\n }\n }\n\n if (finding) {\n if (proposed.has(proof.ref)) finding.expected = true;\n\n findings.push(finding);\n }\n }\n\n for (const entry of store.unmatched ?? []) {\n const file = toPosixPath(entry.testFile);\n const proof = snapshot.proofs.find(\n (item) =>\n toPosixPath(item.at.file) === file &&\n item.at.line === entry.line &&\n item.feature === entry.feature &&\n item.flow === entry.flow &&\n item.criterion === entry.criterion,\n );\n\n // The `@proves` line is gone or moved since the run: the next run replaces the entry.\n if (!proof) continue;\n\n const finding = createFinding({\n code: \"GR4010\",\n message: `${proof.ref} ${proof.criterion}: the reporter could not match the test under this @proves line to a result`,\n at: proof.at,\n feature: proof.feature,\n flow: proof.ref,\n file,\n });\n\n if (proposed.has(proof.ref)) finding.expected = true;\n\n findings.push(finding);\n }\n\n return findings;\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,SAAgB,aAAa,SAAsC;CACjE,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,OAAO,KAAK;AAC1D;;;;;AAMA,SAAgB,mBAAmB,MAAc,MAAuB;CACtE,OAAO,SAAS,UAAa,SAAS,KAClC,KAAK,KAAK,MAAM,GAAG,eAAe,YAAY,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,GAAG,MAAM,IAAI,GAAG,MAAM,UAAU;GACzC,IAAI,MAAM;GACV,SAAS,MAAM;GACf,MAAM,MAAM;GACZ;EACF,CAAC;EAED,IAAI,SAAS,IAAI,MAAM,GAAG,GAAG,QAAQ,WAAW;EAEhD,SAAS,KAAK,OAAO;CACvB;CAEA,OAAO;AACT"}
|
package/esm/vitest/index.d.mts
CHANGED
|
@@ -3,6 +3,12 @@
|
|
|
3
3
|
export type GrimoireReporterOptions = {
|
|
4
4
|
/** Project root. Default: Vitest's `config.root`, else `process.cwd()`. */
|
|
5
5
|
root?: string;
|
|
6
|
+
/**
|
|
7
|
+
* Where to write the results: a project-relative or absolute path. Default
|
|
8
|
+
* `grimoire/book/test-results.json`. Point it at a file the deploy ships
|
|
9
|
+
* and give the panel the same `testResultsFile`.
|
|
10
|
+
*/
|
|
11
|
+
file?: string;
|
|
6
12
|
};
|
|
7
13
|
/** The reporter, typed structurally (only the hooks it implements). */
|
|
8
14
|
export type GrimoireReporter = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/vitest/index.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/vitest/index.ts"],"mappings":";;YA6BY;;EAEV;;;;;;EAMA;;;YAIU;EACV,QAAQ;EACR,iBAAiB,yBAAyB;;;wBA4B5B,iBAAiB,UAAS,0BAA+B"}
|
package/esm/vitest/index.mjs
CHANGED
|
@@ -8,7 +8,8 @@ import { readFile } from "node:fs/promises";
|
|
|
8
8
|
//#region ../../packages/grimoire/src/vitest/index.ts
|
|
9
9
|
/**
|
|
10
10
|
* `@warlock.js/grimoire/vitest`: a Vitest reporter that records the outcome
|
|
11
|
-
* of every test proving a criterion in `grimoire/book/test-results.json
|
|
11
|
+
* of every test proving a criterion in `grimoire/book/test-results.json`
|
|
12
|
+
* (or the file given in `grimoireReporter({ file })`).
|
|
12
13
|
*
|
|
13
14
|
* ```ts
|
|
14
15
|
* // vitest.config.ts
|
|
@@ -44,18 +45,20 @@ function grimoireReporter(options = {}) {
|
|
|
44
45
|
try {
|
|
45
46
|
const modules = Array.isArray(args[0]) ? args[0] : [];
|
|
46
47
|
const root = options.root ?? configRoot ?? process.cwd();
|
|
47
|
-
const previous = await readTestResults(root);
|
|
48
|
+
const previous = await readTestResults(root, options.file);
|
|
48
49
|
const now = /* @__PURE__ */ new Date();
|
|
49
50
|
const run = [];
|
|
50
51
|
const ranFiles = [];
|
|
52
|
+
const unmatched = [];
|
|
51
53
|
for (const module of modules) {
|
|
52
54
|
const done = await recordModule(root, module, previous, now);
|
|
53
55
|
if (!done) continue;
|
|
54
56
|
ranFiles.push(done.file);
|
|
55
57
|
run.push(...done.results);
|
|
58
|
+
unmatched.push(...done.unmatched);
|
|
56
59
|
}
|
|
57
60
|
if (ranFiles.length === 0) return;
|
|
58
|
-
await writeTestResults(root, mergeTestResults(previous, run, ranFiles, now));
|
|
61
|
+
await writeTestResults(root, mergeTestResults(previous, run, ranFiles, now, unmatched), options.file);
|
|
59
62
|
} catch (error) {
|
|
60
63
|
warn(error);
|
|
61
64
|
}
|
|
@@ -79,9 +82,11 @@ async function recordModule(root, module, previous, now) {
|
|
|
79
82
|
const hash = hashTestFile(buffer);
|
|
80
83
|
const { proofs } = scanProofsInText(buffer.toString("utf8"), relative);
|
|
81
84
|
const results = [];
|
|
85
|
+
const unmatched = [];
|
|
82
86
|
if (proofs.length === 0) return {
|
|
83
87
|
file: relative,
|
|
84
|
-
results
|
|
88
|
+
results,
|
|
89
|
+
unmatched
|
|
85
90
|
};
|
|
86
91
|
const cases = [...module.children.allTests()];
|
|
87
92
|
for (const proof of proofs) {
|
|
@@ -90,7 +95,17 @@ async function recordModule(root, module, previous, now) {
|
|
|
90
95
|
outcome: OUTCOMES[test.result().state]
|
|
91
96
|
}));
|
|
92
97
|
if (outcomes.some((item) => item.outcome === void 0)) return null;
|
|
93
|
-
if (
|
|
98
|
+
if (!proof.test) continue;
|
|
99
|
+
if (outcomes.length === 0) {
|
|
100
|
+
unmatched.push({
|
|
101
|
+
feature: proof.feature,
|
|
102
|
+
flow: proof.flow,
|
|
103
|
+
criterion: proof.criterion,
|
|
104
|
+
testFile: relative,
|
|
105
|
+
line: proof.at.line
|
|
106
|
+
});
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
94
109
|
const outcome = combine(outcomes.map((item) => item.outcome));
|
|
95
110
|
const first = outcomes[0]?.test;
|
|
96
111
|
if (!first) continue;
|
|
@@ -114,7 +129,8 @@ async function recordModule(root, module, previous, now) {
|
|
|
114
129
|
}
|
|
115
130
|
return {
|
|
116
131
|
file: relative,
|
|
117
|
-
results
|
|
132
|
+
results,
|
|
133
|
+
unmatched
|
|
118
134
|
};
|
|
119
135
|
}
|
|
120
136
|
function matches(proof, test) {
|
package/esm/vitest/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/vitest/index.ts"],"sourcesContent":["/**\n * `@warlock.js/grimoire/vitest`: a Vitest reporter that records the outcome\n * of every test proving a criterion in `grimoire/book/test-results.json`.\n *\n * ```ts\n * // vitest.config.ts\n * import { grimoireReporter } from \"@warlock.js/grimoire/vitest\";\n *\n * export default defineConfig({ test: { reporters: [\"default\", grimoireReporter()] } });\n * ```\n *\n * Framework-neutral: this entry must not import `@warlock.js/core`,\n * `@warlock.js/web` or `vitest` at runtime (the reporter is typed structurally).\n */\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type {\n ProofLine,\n ProofResult,\n TestOutcome,\n TestResultsStore,\n} from \"../contracts/test-results\";\nimport { toPosixPath } from \"../paths\";\nimport { scanProofsInText } from \"../proves\";\nimport { hashTestFile, mergeTestResults, readTestResults, writeTestResults } from \"../test-results\";\n\n/** Options of `grimoireReporter()`. */\nexport type GrimoireReporterOptions = {\n /** Project root. Default: Vitest's `config.root`, else `process.cwd()`. */\n root?: string;\n};\n\n/** The reporter, typed structurally (only the hooks it implements). */\nexport type GrimoireReporter = {\n onInit?(context: unknown): void;\n onTestRunEnd?(...args: unknown[]): void | Promise<void>;\n};\n\n/** The part of Vitest's `TestCase` the reporter reads. */\ntype ReportedCase = {\n name: string;\n fullName: string;\n location?: { line: number } | undefined;\n result(): { state: string };\n diagnostic?(): { duration?: number } | undefined;\n};\n\n/** The part of Vitest's `TestModule` the reporter reads. */\ntype ReportedModule = {\n moduleId: string;\n state?(): string;\n children: { allTests(): Iterable<ReportedCase> };\n};\n\ntype VitestContext = { config?: { root?: string; includeTaskLocation?: boolean } };\n\nconst OUTCOMES: Record<string, TestOutcome | undefined> = {\n passed: \"pass\",\n failed: \"fail\",\n skipped: \"skip\",\n};\n\n/** Create the reporter. */\nexport function grimoireReporter(options: GrimoireReporterOptions = {}): GrimoireReporter {\n let configRoot: string | undefined;\n let warned = false;\n\n const warn = (error: unknown): void => {\n if (warned) return;\n\n warned = true;\n console.warn(\n `[grimoire] Could not record test results: ${error instanceof Error ? error.message : String(error)}`,\n );\n };\n\n return {\n onInit(context) {\n const config = (context as VitestContext | undefined)?.config;\n\n configRoot = config?.root;\n\n // Test locations are how a test is matched to its `@proves` line.\n if (config) config.includeTaskLocation = true;\n },\n\n async onTestRunEnd(...args) {\n try {\n const modules = (Array.isArray(args[0]) ? args[0] : []) as ReportedModule[];\n const root = options.root ?? configRoot ?? process.cwd();\n const previous = await readTestResults(root);\n const now = new Date();\n const run: ProofResult[] = [];\n const ranFiles: string[] = [];\n\n for (const module of modules) {\n const done = await recordModule(root, module, previous, now);\n\n if (!done) continue;\n\n ranFiles.push(done.file);\n run.push(...done.results);\n }\n\n if (ranFiles.length === 0) return;\n\n await writeTestResults(root, mergeTestResults(previous, run, ranFiles, now));\n } catch (error) {\n warn(error);\n }\n },\n };\n}\n\ntype ModuleRecord = { file: string; results: ProofResult[] };\n\n/** Results of one test file, or `null` when the file did not finish (it must not erase old results). */\nasync function recordModule(\n root: string,\n module: ReportedModule,\n previous: TestResultsStore | null,\n now: Date,\n): Promise<ModuleRecord | null> {\n // `queued` (never started) and `pending` (cut short) files must keep their old results.\n const state = module.state?.();\n\n if (state === \"pending\" || state === \"queued\") return null;\n\n const absolute = path.resolve(root, module.moduleId);\n const fromRoot = path.relative(root, absolute);\n const relative = toPosixPath(fromRoot);\n\n // Outside the project (another drive on Windows gives an absolute path).\n if (relative === \"..\" || relative.startsWith(\"../\") || path.isAbsolute(fromRoot)) return null;\n\n let buffer: Buffer;\n\n try {\n buffer = await readFile(absolute);\n } catch {\n return null;\n }\n\n const hash = hashTestFile(buffer);\n const { proofs } = scanProofsInText(buffer.toString(\"utf8\"), relative);\n const results: ProofResult[] = [];\n\n if (proofs.length === 0) return { file: relative, results };\n\n const cases = [...module.children.allTests()];\n\n for (const proof of proofs) {\n const matched = cases.filter((test) => matches(proof, test));\n const outcomes = matched.map((test) => ({ test, outcome: OUTCOMES[test.result().state] }));\n\n // A test still pending means the run was cut short: say nothing about this file.\n if (outcomes.some((item) => item.outcome === undefined)) return null;\n if (outcomes.length === 0 || !proof.test) continue;\n\n const outcome = combine(outcomes.map((item) => item.outcome as TestOutcome));\n const first = outcomes[0]?.test;\n\n if (!first) continue;\n\n const old = previous?.results.find(\n (item) =>\n item.testFile === relative &&\n item.feature === proof.feature &&\n item.flow === proof.flow &&\n item.criterion === proof.criterion &&\n item.testFileHash === hash,\n );\n\n // A skipped test (a `-t` filter, `.skip`) keeps the last real result of the same file content.\n if (outcome === \"skip\" && old) {\n results.push(old);\n\n continue;\n }\n\n results.push({\n feature: proof.feature,\n flow: proof.flow,\n criterion: proof.criterion,\n testFile: relative,\n testName: first.fullName,\n line: proof.test.line,\n outcome,\n durationMs: totalDuration(outcomes.map((item) => item.test)),\n ranAt: now.toISOString(),\n testFileHash: hash,\n });\n }\n\n return { file: relative, results };\n}\n\nfunction matches(proof: ProofLine, test: ReportedCase): boolean {\n if (!proof.test) return false;\n if (test.location) return test.location.line === proof.test.line;\n\n return proof.test.name !== null && proof.test.name === test.name;\n}\n\n/** One proving test can run several times (`it.each`): fail beats pass, pass beats skip. */\nfunction combine(outcomes: TestOutcome[]): TestOutcome {\n if (outcomes.includes(\"fail\")) return \"fail\";\n if (outcomes.includes(\"pass\")) return \"pass\";\n\n return \"skip\";\n}\n\nfunction totalDuration(tests: ReportedCase[]): number | null {\n let total = 0;\n let known = false;\n\n for (const test of tests) {\n const duration = test.diagnostic?.()?.duration;\n\n if (typeof duration === \"number\") {\n total += duration;\n known = true;\n }\n }\n\n return known ? Math.round(total) : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,WAAoD;CACxD,QAAQ;CACR,QAAQ;CACR,SAAS;AACX;;AAGA,SAAgB,iBAAiB,UAAmC,CAAC,GAAqB;CACxF,IAAI;CACJ,IAAI,SAAS;CAEb,MAAM,QAAQ,UAAyB;EACrC,IAAI,QAAQ;EAEZ,SAAS;EACT,QAAQ,KACN,6CAA6C,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACpG;CACF;CAEA,OAAO;EACL,OAAO,SAAS;GACd,MAAM,SAAU,SAAuC;GAEvD,aAAa,QAAQ;GAGrB,IAAI,QAAQ,OAAO,sBAAsB;EAC3C;EAEA,MAAM,aAAa,GAAG,MAAM;GAC1B,IAAI;IACF,MAAM,UAAW,MAAM,QAAQ,KAAK,EAAE,IAAI,KAAK,KAAK,CAAC;IACrD,MAAM,OAAO,QAAQ,QAAQ,cAAc,QAAQ,IAAI;IACvD,MAAM,WAAW,MAAM,gBAAgB,IAAI;IAC3C,MAAM,sBAAM,IAAI,KAAK;IACrB,MAAM,MAAqB,CAAC;IAC5B,MAAM,WAAqB,CAAC;IAE5B,KAAK,MAAM,UAAU,SAAS;KAC5B,MAAM,OAAO,MAAM,aAAa,MAAM,QAAQ,UAAU,GAAG;KAE3D,IAAI,CAAC,MAAM;KAEX,SAAS,KAAK,KAAK,IAAI;KACvB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EAE3B,IAAI,CAAC,OAAO;EAEZ,MAAM,MAAM,UAAU,QAAQ,MAC3B,SACC,KAAK,aAAa,YAClB,KAAK,YAAY,MAAM,WACvB,KAAK,SAAS,MAAM,QACpB,KAAK,cAAc,MAAM,aACzB,KAAK,iBAAiB,IAC1B;EAGA,IAAI,YAAY,UAAU,KAAK;GAC7B,QAAQ,KAAK,GAAG;GAEhB;EACF;EAEA,QAAQ,KAAK;GACX,SAAS,MAAM;GACf,MAAM,MAAM;GACZ,WAAW,MAAM;GACjB,UAAU;GACV,UAAU,MAAM;GAChB,MAAM,MAAM,KAAK;GACjB;GACA,YAAY,cAAc,SAAS,KAAK,SAAS,KAAK,IAAI,CAAC;GAC3D,OAAO,IAAI,YAAY;GACvB,cAAc;EAChB,CAAC;CACH;CAEA,OAAO;EAAE,MAAM;EAAU;CAAQ;AACnC;AAEA,SAAS,QAAQ,OAAkB,MAA6B;CAC9D,IAAI,CAAC,MAAM,MAAM,OAAO;CACxB,IAAI,KAAK,UAAU,OAAO,KAAK,SAAS,SAAS,MAAM,KAAK;CAE5D,OAAO,MAAM,KAAK,SAAS,QAAQ,MAAM,KAAK,SAAS,KAAK;AAC9D;;AAGA,SAAS,QAAQ,UAAsC;CACrD,IAAI,SAAS,SAAS,MAAM,GAAG,OAAO;CACtC,IAAI,SAAS,SAAS,MAAM,GAAG,OAAO;CAEtC,OAAO;AACT;AAEA,SAAS,cAAc,OAAsC;CAC3D,IAAI,QAAQ;CACZ,IAAI,QAAQ;CAEZ,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,WAAW,KAAK,aAAa,CAAC,EAAE;EAEtC,IAAI,OAAO,aAAa,UAAU;GAChC,SAAS;GACT,QAAQ;EACV;CACF;CAEA,OAAO,QAAQ,KAAK,MAAM,KAAK,IAAI;AACrC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/vitest/index.ts"],"sourcesContent":["/**\n * `@warlock.js/grimoire/vitest`: a Vitest reporter that records the outcome\n * of every test proving a criterion in `grimoire/book/test-results.json`\n * (or the file given in `grimoireReporter({ file })`).\n *\n * ```ts\n * // vitest.config.ts\n * import { grimoireReporter } from \"@warlock.js/grimoire/vitest\";\n *\n * export default defineConfig({ test: { reporters: [\"default\", grimoireReporter()] } });\n * ```\n *\n * Framework-neutral: this entry must not import `@warlock.js/core`,\n * `@warlock.js/web` or `vitest` at runtime (the reporter is typed structurally).\n */\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type {\n ProofLine,\n ProofResult,\n TestOutcome,\n TestResultsStore,\n UnmatchedProof,\n} from \"../contracts/test-results\";\nimport { toPosixPath } from \"../paths\";\nimport { scanProofsInText } from \"../proves\";\nimport { hashTestFile, mergeTestResults, readTestResults, writeTestResults } from \"../test-results\";\n\n/** Options of `grimoireReporter()`. */\nexport type GrimoireReporterOptions = {\n /** Project root. Default: Vitest's `config.root`, else `process.cwd()`. */\n root?: string;\n /**\n * Where to write the results: a project-relative or absolute path. Default\n * `grimoire/book/test-results.json`. Point it at a file the deploy ships\n * and give the panel the same `testResultsFile`.\n */\n file?: string;\n};\n\n/** The reporter, typed structurally (only the hooks it implements). */\nexport type GrimoireReporter = {\n onInit?(context: unknown): void;\n onTestRunEnd?(...args: unknown[]): void | Promise<void>;\n};\n\n/** The part of Vitest's `TestCase` the reporter reads. */\ntype ReportedCase = {\n name: string;\n fullName: string;\n location?: { line: number } | undefined;\n result(): { state: string };\n diagnostic?(): { duration?: number } | undefined;\n};\n\n/** The part of Vitest's `TestModule` the reporter reads. */\ntype ReportedModule = {\n moduleId: string;\n state?(): string;\n children: { allTests(): Iterable<ReportedCase> };\n};\n\ntype VitestContext = { config?: { root?: string; includeTaskLocation?: boolean } };\n\nconst OUTCOMES: Record<string, TestOutcome | undefined> = {\n passed: \"pass\",\n failed: \"fail\",\n skipped: \"skip\",\n};\n\n/** Create the reporter. */\nexport function grimoireReporter(options: GrimoireReporterOptions = {}): GrimoireReporter {\n let configRoot: string | undefined;\n let warned = false;\n\n const warn = (error: unknown): void => {\n if (warned) return;\n\n warned = true;\n console.warn(\n `[grimoire] Could not record test results: ${error instanceof Error ? error.message : String(error)}`,\n );\n };\n\n return {\n onInit(context) {\n const config = (context as VitestContext | undefined)?.config;\n\n configRoot = config?.root;\n\n // Test locations are how a test is matched to its `@proves` line.\n if (config) config.includeTaskLocation = true;\n },\n\n async onTestRunEnd(...args) {\n try {\n const modules = (Array.isArray(args[0]) ? args[0] : []) as ReportedModule[];\n const root = options.root ?? configRoot ?? process.cwd();\n const previous = await readTestResults(root, options.file);\n const now = new Date();\n const run: ProofResult[] = [];\n const ranFiles: string[] = [];\n const unmatched: UnmatchedProof[] = [];\n\n for (const module of modules) {\n const done = await recordModule(root, module, previous, now);\n\n if (!done) continue;\n\n ranFiles.push(done.file);\n run.push(...done.results);\n unmatched.push(...done.unmatched);\n }\n\n if (ranFiles.length === 0) return;\n\n await writeTestResults(\n root,\n mergeTestResults(previous, run, ranFiles, now, unmatched),\n options.file,\n );\n } catch (error) {\n warn(error);\n }\n },\n };\n}\n\ntype ModuleRecord = { file: string; results: ProofResult[]; unmatched: UnmatchedProof[] };\n\n/** Results of one test file, or `null` when the file did not finish (it must not erase old results). */\nasync function recordModule(\n root: string,\n module: ReportedModule,\n previous: TestResultsStore | null,\n now: Date,\n): Promise<ModuleRecord | null> {\n // `queued` (never started) and `pending` (cut short) files must keep their old results.\n const state = module.state?.();\n\n if (state === \"pending\" || state === \"queued\") return null;\n\n const absolute = path.resolve(root, module.moduleId);\n const fromRoot = path.relative(root, absolute);\n const relative = toPosixPath(fromRoot);\n\n // Outside the project (another drive on Windows gives an absolute path).\n if (relative === \"..\" || relative.startsWith(\"../\") || path.isAbsolute(fromRoot)) return null;\n\n let buffer: Buffer;\n\n try {\n buffer = await readFile(absolute);\n } catch {\n return null;\n }\n\n const hash = hashTestFile(buffer);\n const { proofs } = scanProofsInText(buffer.toString(\"utf8\"), relative);\n const results: ProofResult[] = [];\n const unmatched: UnmatchedProof[] = [];\n\n if (proofs.length === 0) return { file: relative, results, unmatched };\n\n const cases = [...module.children.allTests()];\n\n for (const proof of proofs) {\n const matched = cases.filter((test) => matches(proof, test));\n const outcomes = matched.map((test) => ({ test, outcome: OUTCOMES[test.result().state] }));\n\n // A test still pending means the run was cut short: say nothing about this file.\n if (outcomes.some((item) => item.outcome === undefined)) return null;\n if (!proof.test) continue;\n\n if (outcomes.length === 0) {\n unmatched.push({\n feature: proof.feature,\n flow: proof.flow,\n criterion: proof.criterion,\n testFile: relative,\n line: proof.at.line,\n });\n\n continue;\n }\n\n const outcome = combine(outcomes.map((item) => item.outcome as TestOutcome));\n const first = outcomes[0]?.test;\n\n if (!first) continue;\n\n const old = previous?.results.find(\n (item) =>\n item.testFile === relative &&\n item.feature === proof.feature &&\n item.flow === proof.flow &&\n item.criterion === proof.criterion &&\n item.testFileHash === hash,\n );\n\n // A skipped test (a `-t` filter, `.skip`) keeps the last real result of the same file content.\n if (outcome === \"skip\" && old) {\n results.push(old);\n\n continue;\n }\n\n results.push({\n feature: proof.feature,\n flow: proof.flow,\n criterion: proof.criterion,\n testFile: relative,\n testName: first.fullName,\n line: proof.test.line,\n outcome,\n durationMs: totalDuration(outcomes.map((item) => item.test)),\n ranAt: now.toISOString(),\n testFileHash: hash,\n });\n }\n\n return { file: relative, results, unmatched };\n}\n\nfunction matches(proof: ProofLine, test: ReportedCase): boolean {\n if (!proof.test) return false;\n if (test.location) return test.location.line === proof.test.line;\n\n return proof.test.name !== null && proof.test.name === test.name;\n}\n\n/** One proving test can run several times (`it.each`): fail beats pass, pass beats skip. */\nfunction combine(outcomes: TestOutcome[]): TestOutcome {\n if (outcomes.includes(\"fail\")) return \"fail\";\n if (outcomes.includes(\"pass\")) return \"pass\";\n\n return \"skip\";\n}\n\nfunction totalDuration(tests: ReportedCase[]): number | null {\n let total = 0;\n let known = false;\n\n for (const test of tests) {\n const duration = test.diagnostic?.()?.duration;\n\n if (typeof duration === \"number\") {\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AAkB;;EAElB,UAAU;;;
|
|
1
|
+
{"version":3,"file":"adapter.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/adapter.ts"],"mappings":";;;;;;;;;;YAsCY,kBACV,cACA,mBAAmB,qBAChB,QAAQ;;YAGD;;;;;;;;EAQV,kBAAkB;;EAElB,UAAU;;;wBAwSI,qBAAqB,UAAS,wBAA6B"}
|
package/esm/warlock/adapter.mjs
CHANGED
|
@@ -113,10 +113,14 @@ function toBookFile(file, mobile) {
|
|
|
113
113
|
name,
|
|
114
114
|
about: docs[name] ?? null
|
|
115
115
|
})),
|
|
116
|
-
imports: file.imports.map((entry) =>
|
|
116
|
+
imports: file.imports.map((entry) => entry.typeOnly === true ? {
|
|
117
|
+
specifier: entry.specifier,
|
|
118
|
+
file: entry.file,
|
|
119
|
+
typeOnly: true
|
|
120
|
+
} : {
|
|
117
121
|
specifier: entry.specifier,
|
|
118
122
|
file: entry.file
|
|
119
|
-
})
|
|
123
|
+
}),
|
|
120
124
|
importedBy: [...file.importedBy],
|
|
121
125
|
mobileApp: app?.id ?? null
|
|
122
126
|
};
|