@warlock.js/grimoire 5.63.1 → 5.64.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 +44 -0
- package/esm/book/build.d.mts.map +1 -1
- package/esm/book/build.mjs +24 -2
- package/esm/book/build.mjs.map +1 -1
- package/esm/check/check-grimoire.d.mts.map +1 -1
- package/esm/check/check-grimoire.mjs +11 -1
- package/esm/check/check-grimoire.mjs.map +1 -1
- package/esm/check/rules/api-snapshot.mjs +39 -0
- package/esm/check/rules/api-snapshot.mjs.map +1 -0
- package/esm/check/rules/code-rules.mjs +45 -0
- package/esm/check/rules/code-rules.mjs.map +1 -0
- package/esm/check/rules/drift.mjs +54 -0
- package/esm/check/rules/drift.mjs.map +1 -0
- package/esm/check/rules/focused-tests.mjs +39 -0
- package/esm/check/rules/focused-tests.mjs.map +1 -0
- package/esm/check/rules/shows.mjs +52 -0
- package/esm/check/rules/shows.mjs.map +1 -0
- package/esm/codes/codes.d.mts +48 -0
- package/esm/codes/codes.d.mts.map +1 -1
- package/esm/codes/codes.mjs +26 -1
- 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/guard.d.mts +104 -0
- package/esm/contracts/guard.d.mts.map +1 -0
- package/esm/contracts/index.mjs +5 -0
- package/esm/contracts/matrix.d.mts +75 -0
- package/esm/contracts/matrix.d.mts.map +1 -0
- package/esm/contracts/scry.d.mts +21 -0
- package/esm/contracts/scry.d.mts.map +1 -1
- package/esm/contracts/settings.d.mts +71 -0
- package/esm/contracts/settings.d.mts.map +1 -0
- package/esm/contracts/settings.mjs +67 -0
- package/esm/contracts/settings.mjs.map +1 -0
- package/esm/contracts/shots.d.mts +146 -0
- package/esm/contracts/shots.d.mts.map +1 -0
- package/esm/contracts/snapshot.d.mts +10 -0
- package/esm/contracts/snapshot.d.mts.map +1 -1
- package/esm/contracts/written.d.mts +13 -0
- package/esm/contracts/written.d.mts.map +1 -1
- package/esm/contracts/written.mjs +7 -1
- package/esm/contracts/written.mjs.map +1 -1
- package/esm/devtools/approvals.mjs +59 -0
- package/esm/devtools/approvals.mjs.map +1 -0
- package/esm/devtools/data.mjs +2 -0
- package/esm/devtools/data.mjs.map +1 -1
- package/esm/devtools/graphs.mjs +13 -3
- package/esm/devtools/graphs.mjs.map +1 -1
- package/esm/devtools/index.d.mts.map +1 -1
- package/esm/devtools/index.mjs +32 -2
- package/esm/devtools/index.mjs.map +1 -1
- package/esm/devtools/matrix.mjs +207 -0
- package/esm/devtools/matrix.mjs.map +1 -0
- package/esm/devtools/product-map.d.mts.map +1 -1
- package/esm/devtools/product-map.mjs +87 -1
- package/esm/devtools/product-map.mjs.map +1 -1
- package/esm/devtools/site.d.mts.map +1 -1
- package/esm/devtools/site.mjs +12 -3
- package/esm/devtools/site.mjs.map +1 -1
- package/esm/devtools/snapshot-source.mjs +5 -1
- package/esm/devtools/snapshot-source.mjs.map +1 -1
- package/esm/git/index.d.mts +20 -0
- package/esm/git/index.d.mts.map +1 -0
- package/esm/git/index.mjs +280 -0
- package/esm/git/index.mjs.map +1 -0
- package/esm/guard/api.mjs +70 -0
- package/esm/guard/api.mjs.map +1 -0
- package/esm/guard/assertions.mjs +18 -0
- package/esm/guard/assertions.mjs.map +1 -0
- package/esm/guard/collect.mjs +139 -0
- package/esm/guard/collect.mjs.map +1 -0
- package/esm/guard/format.mjs +27 -0
- package/esm/guard/format.mjs.map +1 -0
- package/esm/guard/glob.mjs +79 -0
- package/esm/guard/glob.mjs.map +1 -0
- package/esm/guard/index.mjs +9 -0
- package/esm/guard/rules.mjs +310 -0
- package/esm/guard/rules.mjs.map +1 -0
- package/esm/guard/scope.mjs +95 -0
- package/esm/guard/scope.mjs.map +1 -0
- package/esm/index.d.mts +10 -3
- package/esm/index.mjs +6 -2
- package/esm/paths/index.d.mts +15 -1
- package/esm/paths/index.d.mts.map +1 -1
- package/esm/paths/index.mjs +27 -3
- package/esm/paths/index.mjs.map +1 -1
- package/esm/proves/index.mjs +2 -1
- package/esm/proves/scan-proofs.mjs +1 -1
- package/esm/proves/scan-proofs.mjs.map +1 -1
- package/esm/proves/scan-shows.d.mts +21 -0
- package/esm/proves/scan-shows.d.mts.map +1 -0
- package/esm/proves/scan-shows.mjs +168 -0
- package/esm/proves/scan-shows.mjs.map +1 -0
- package/esm/releases/index.d.mts.map +1 -1
- package/esm/releases/index.mjs +5 -3
- package/esm/releases/index.mjs.map +1 -1
- package/esm/releases/stamp.mjs +121 -0
- package/esm/releases/stamp.mjs.map +1 -0
- package/esm/rules/focused.mjs +26 -0
- package/esm/rules/focused.mjs.map +1 -0
- package/esm/rules/index.mjs +88 -0
- package/esm/rules/index.mjs.map +1 -0
- package/esm/rules/logical-css.mjs +112 -0
- package/esm/rules/logical-css.mjs.map +1 -0
- package/esm/rules/no-js-imports.mjs +22 -0
- package/esm/rules/no-js-imports.mjs.map +1 -0
- package/esm/rules/scan.mjs +196 -0
- package/esm/rules/scan.mjs.map +1 -0
- package/esm/rules/specific-errors.mjs +51 -0
- package/esm/rules/specific-errors.mjs.map +1 -0
- package/esm/rules/type-discriminator.mjs +27 -0
- package/esm/rules/type-discriminator.mjs.map +1 -0
- package/esm/scry/also-changes.mjs +106 -0
- package/esm/scry/also-changes.mjs.map +1 -0
- package/esm/scry/format.d.mts.map +1 -1
- package/esm/scry/format.mjs +22 -0
- package/esm/scry/format.mjs.map +1 -1
- package/esm/scry/query.d.mts.map +1 -1
- package/esm/scry/query.mjs +7 -2
- package/esm/scry/query.mjs.map +1 -1
- package/esm/scry/search.d.mts.map +1 -1
- package/esm/scry/search.mjs +43 -11
- package/esm/scry/search.mjs.map +1 -1
- package/esm/shots/approve.mjs +195 -0
- package/esm/shots/approve.mjs.map +1 -0
- package/esm/shots/drift.mjs +174 -0
- package/esm/shots/drift.mjs.map +1 -0
- package/esm/shots/png.mjs +166 -0
- package/esm/shots/png.mjs.map +1 -0
- package/esm/shots/state.mjs +43 -0
- package/esm/shots/state.mjs.map +1 -0
- package/esm/shots/store.mjs +66 -0
- package/esm/shots/store.mjs.map +1 -0
- package/esm/shots/touched.mjs +38 -0
- package/esm/shots/touched.mjs.map +1 -0
- package/esm/warlock/adapter.d.mts.map +1 -1
- package/esm/warlock/adapter.mjs +15 -2
- package/esm/warlock/adapter.mjs.map +1 -1
- package/esm/warlock/api-command.mjs +41 -0
- package/esm/warlock/api-command.mjs.map +1 -0
- package/esm/warlock/approve-command.mjs +80 -0
- package/esm/warlock/approve-command.mjs.map +1 -0
- package/esm/warlock/commands.d.mts +1 -1
- package/esm/warlock/commands.d.mts.map +1 -1
- package/esm/warlock/commands.mjs +61 -8
- package/esm/warlock/commands.mjs.map +1 -1
- package/esm/warlock/guard-command.mjs +116 -0
- package/esm/warlock/guard-command.mjs.map +1 -0
- package/esm/warlock/index.d.mts +2 -1
- package/esm/warlock/index.mjs +2 -1
- package/esm/warlock/languages.mjs +75 -0
- package/esm/warlock/languages.mjs.map +1 -0
- package/esm/warlock/mcp-tools.mjs +2 -2
- package/esm/warlock/mcp-tools.mjs.map +1 -1
- package/esm/warlock/release-command.mjs +65 -0
- package/esm/warlock/release-command.mjs.map +1 -0
- package/esm/warlock/shows.d.mts +35 -0
- package/esm/warlock/shows.d.mts.map +1 -0
- package/esm/warlock/shows.mjs +195 -0
- package/esm/warlock/shows.mjs.map +1 -0
- package/esm/workspace/cache.mjs +4 -1
- package/esm/workspace/cache.mjs.map +1 -1
- package/esm/workspace/derived.mjs +11 -6
- package/esm/workspace/derived.mjs.map +1 -1
- package/esm/workspace/index.d.mts.map +1 -1
- package/esm/workspace/index.mjs +8 -1
- package/esm/workspace/index.mjs.map +1 -1
- package/esm/workspace/stored.mjs +4 -1
- package/esm/workspace/stored.mjs.map +1 -1
- package/esm/written/features.mjs +21 -5
- package/esm/written/features.mjs.map +1 -1
- package/esm/written/index.mjs +2 -1
- package/esm/written/parse-grimoire.d.mts.map +1 -1
- package/esm/written/parse-grimoire.mjs +16 -3
- package/esm/written/parse-grimoire.mjs.map +1 -1
- package/esm/written/settings.d.mts +11 -0
- package/esm/written/settings.d.mts.map +1 -0
- package/esm/written/settings.mjs +88 -0
- package/esm/written/settings.mjs.map +1 -0
- package/llms-full.txt +276 -39
- package/llms.txt +2 -0
- package/package.json +3 -3
- package/skills/backfill-a-grimoire/SKILL.md +4 -0
- package/skills/describe-an-app/SKILL.md +4 -1
- package/skills/guard-a-change/SKILL.md +85 -0
- package/skills/index.md +7 -3
- package/skills/record-a-change/SKILL.md +52 -16
- package/skills/review-a-change/SKILL.md +53 -0
- package/skills/use-the-grimoire/SKILL.md +21 -18
- package/skills/write-a-feature/SKILL.md +42 -1
- package/ui/grimoire-view.js +756 -40
- package/ui/grimoire.css +303 -28
- package/ui/product-map.css +43 -7
- package/ui/product-map.js +212 -37
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snapshot-source.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/devtools/snapshot-source.ts"],"sourcesContent":["/**\n * Where the panel's routes get the snapshot: opened once with\n * `routes: \"cached\"` (a devtools request never boots the app) and kept in\n * memory. Concurrent requests share one open. A change stamp (the book\n * manifest, the agent-written folders and indexes and the files the route\n * facts were read from, a few `stat` calls and no directory walk) tells when the book changed. With live\n * facts (`liveFacts`, development), an edit to a file the route facts were read from reads them again from\n * the running app on the next open, so a route edit shows without `warlock grimoire build`.\n *\n * - Production (`mode: \"production\"`): a snapshot is reused until the stamp\n * changes, with no time limit, unless `ttlMs` is set. A request that finds\n * the stamp changed waits for the new open. `warm()` opens the book ahead\n * of the first request.\n * - Development: the snapshot is reused for a short window (2 s, or five times\n * the last open when that is longer, so a slow open on a large app is not\n * repeated on every view; written files change while an agent works). A\n * request that finds the stamp changed waits for the new open. After the\n * window, with the stamp unchanged (a file edited in place), the cached\n * snapshot is served at once and one background open refreshes it (stale\n * while revalidate).\n *\n * An open that fails keeps serving the old snapshot; its error surfaces on a\n * request only when there is no snapshot at all. The panel passes\n * `write: true` in development, so the generated book stays current and the\n * next open is incremental; with `write: false` a stored book behind the\n * sources is rebuilt in memory on every open.\n */\nimport { stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport { GRIMOIRE_PATHS } from \"../paths\";\nimport { resolveResultsFile } from \"../test-results\";\nimport { openGrimoire } from \"../workspace\";\n\n/** Options of the panel's snapshot source. */\nexport type SnapshotSourceOptions = {\n /** The adapter, or a function that loads it. Default: the Warlock adapter, imported on first use. */\n adapter?: BookAdapter | (() => Promise<BookAdapter>);\n /**\n * How long a snapshot is reused when the book did not change (ms).\n * Default in development: 2000, or five times as long as the last open took\n * when that is longer. Default in production: no limit (reused until the\n * book changes).\n */\n ttlMs?: number;\n /** Where the source runs. `\"production\"` keeps a snapshot until the book changes. Default: `\"development\"`. */\n mode?: \"development\" | \"production\";\n /** Let `openGrimoire` write the generated book and collected files (never agent-written files). Default `false`; the devtools panel passes `true`. */\n write?: boolean;\n /**\n * Where the test results are read from (project-relative or absolute).\n * Default `grimoire/book/test-results.json`. The file's modified time is part\n * of the change stamp, so results written after the snapshot opened show up\n * without a restart.\n */\n testResultsFile?: string;\n /**\n * Read the route facts once when the first open finds none (`routes: \"missing\"`), so the development tab is\n * never \"missing\" without a manual `warlock grimoire build`. The adapter's booted inspect runs at most once per\n * process; a boot that fails keeps the cached answer. Default `false`. Never set it in a process that serves the app: the boot\n * pass boots every connector and re-imports the route and event modules, which registers them twice. The devtools panel\n * does not set it; use it from a separate tool process.\n */\n collectRoutes?: boolean;\n /**\n * The adapter reads the route, event and job facts from the running process (`createWarlockAdapter({ live: true })`),\n * which is cheap and boots nothing. The first open then collects them in the same pass as the book\n * (`routes: \"fresh\"`), so the tab never opens \"missing\" and the first open runs once. Safe in the process that\n * serves the app. Default `false`; the devtools panel sets it in development with the Warlock adapter.\n */\n liveFacts?: boolean;\n};\n\n/** A cached, shared snapshot of one project. */\nexport type SnapshotSource = {\n get(): Promise<GrimoireSnapshot>;\n /** Forget the cached snapshot; the next `get()` opens again. */\n invalidate(): void;\n /** Start opening the book now, so the first `get()` is fast. Failures are ignored here and surface on `get()`. */\n warm(): void;\n /** Resolves when no open is running (specs and shutdown). Never rejects. */\n idle(): Promise<void>;\n};\n\n/** Files and folders whose modified time moves when the book or an agent-written file is added, removed or regenerated. */\nconst STAMPED = [\n GRIMOIRE_PATHS.bookManifest,\n GRIMOIRE_PATHS.featuresIndex,\n GRIMOIRE_PATHS.tasksIndex,\n GRIMOIRE_PATHS.features,\n GRIMOIRE_PATHS.apps,\n GRIMOIRE_PATHS.openTasks,\n GRIMOIRE_PATHS.doneTasks,\n GRIMOIRE_PATHS.releases,\n];\n\n/** The modified times of `files`, joined (`0` for a missing file). */\nasync function timesOf(files: string[]): Promise<string> {\n const times = await Promise.all(\n files.map(async (file) => {\n try {\n return (await stat(file)).mtimeMs;\n } catch {\n return 0;\n }\n }),\n );\n\n return times.join(\",\");\n}\n\n/**\n * The change stamp in two parts: `book` (the book manifest, the written folders, the results file) and `routes`\n * (the project-relative files the route facts were read from, `manifest.boot.inputs`). An edit to a route input\n * ends the reuse window; with live facts the next open reads the routes again, otherwise it reports them stale.\n */\nasync function changeStamp(\n root: string,\n resultsFile: string,\n routeInputs: string[] = [],\n): Promise<{ book: string; routes: string }> {\n const [book, routes] = await Promise.all([\n timesOf([...STAMPED.map((entry) => path.join(root, ...entry.split(\"/\"))), resultsFile]),\n timesOf(routeInputs.map((file) => path.join(root, ...file.split(\"/\")))),\n ]);\n\n return { book, routes };\n}\n\nconst routeInputsOf = (snapshot: GrimoireSnapshot): string[] =>\n Object.keys(snapshot.book.manifest.boot.inputs).sort();\n\nasync function loadAdapter(option: SnapshotSourceOptions[\"adapter\"]): Promise<BookAdapter> {\n if (option === undefined) {\n const { createWarlockAdapter } = await import(\"../warlock\");\n\n return createWarlockAdapter();\n }\n\n return typeof option === \"function\" ? option() : option;\n}\n\n/** Create the source for the project at `root`. */\nexport function createSnapshotSource(\n root: string,\n options: SnapshotSourceOptions = {},\n): SnapshotSource {\n let cached: {\n snapshot: GrimoireSnapshot;\n at: number;\n stamp: { book: string; routes: string };\n took: number;\n } | null = null;\n let opening: Promise<GrimoireSnapshot> | null = null;\n\n const live = options.liveFacts === true && options.mode !== \"production\";\n let collected = options.collectRoutes !== true || options.mode === \"production\";\n let liveCollected = !live;\n // Set when a route input changed: with live facts, the next open reads the routes from the running app again.\n let refreshRoutes = false;\n const resultsFile = resolveResultsFile(root, options.testResultsFile);\n\n const keepUntilChanged = options.mode === \"production\" && options.ttlMs === undefined;\n const reuseFor = (took: number): number => options.ttlMs ?? Math.max(2000, took * 5);\n\n async function open(): Promise<GrimoireSnapshot> {\n const started = Date.now();\n const adapter = await loadAdapter(options.adapter);\n const openOptions = {\n write: options.write ?? false,\n ...(options.testResultsFile === undefined\n ? {}\n : { testResultsFile: options.testResultsFile }),\n };\n let snapshot: GrimoireSnapshot;\n\n if (!liveCollected || refreshRoutes) {\n // One pass: the book and the live route facts together, so a first open never builds twice.\n // After a routes-file edit: the dev server reloads the file on save, so the live read sees its new routes.\n liveCollected = true;\n refreshRoutes = false;\n\n try {\n snapshot = await openGrimoire(root, adapter, { routes: \"fresh\", ...openOptions });\n } catch {\n // The facts could not be read: fall back to what the book already holds.\n snapshot = await openGrimoire(root, adapter, { routes: \"cached\", ...openOptions });\n }\n } else {\n snapshot = await openGrimoire(root, adapter, { routes: \"cached\", ...openOptions });\n }\n\n if (!collected && snapshot.routes === \"missing\") {\n // Once per source: the route, event and job facts come from one boot pass, then live in the book.\n collected = true;\n\n try {\n snapshot = await openGrimoire(root, adapter, { routes: \"fresh\", ...openOptions });\n } catch {\n // The app did not boot (GR8002): keep the cached answer; the tab says the facts are missing.\n }\n }\n\n const at = Date.now();\n\n cached = {\n snapshot,\n at,\n stamp: await changeStamp(root, resultsFile, routeInputsOf(snapshot)),\n took: at - started,\n };\n\n return snapshot;\n }\n\n /** The open in flight, or a new one; concurrent callers share it. */\n function ensureOpening(): Promise<GrimoireSnapshot> {\n opening ??= open().finally(() => {\n opening = null;\n });\n\n return opening;\n }\n\n return {\n async get() {\n if (cached === null) return ensureOpening();\n\n const known = cached;\n const stamp = await changeStamp(root, resultsFile, routeInputsOf(known.snapshot));\n const routesMoved = stamp.routes !== known.stamp.routes;\n const changed = routesMoved || stamp.book !== known.stamp.book;\n\n if (routesMoved && live) refreshRoutes = true;\n\n if (changed || options.mode === \"production\") {\n if (!changed && (keepUntilChanged || Date.now() - known.at < reuseFor(known.took))) {\n return known.snapshot;\n }\n\n // A failed open keeps the old snapshot; the next request tries again.\n return ensureOpening().catch(() => known.snapshot);\n }\n\n if (Date.now() - known.at < reuseFor(known.took)) return known.snapshot;\n\n // Development, nothing known to have changed: serve the old snapshot now and refresh behind it.\n ensureOpening().catch(() => {});\n\n return known.snapshot;\n },\n invalidate() {\n cached = null;\n },\n warm() {\n if (cached === null) ensureOpening().catch(() => {});\n },\n async idle() {\n await opening?.catch(() => {});\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsFA,MAAM,UAAU;CACd,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;AACjB;;AAGA,eAAe,QAAQ,OAAkC;CAWvD,QAAO,MAVa,QAAQ,IAC1B,MAAM,IAAI,OAAO,SAAS;EACxB,IAAI;GACF,QAAQ,MAAM,KAAK,IAAI,EAAC,CAAE;EAC5B,QAAQ;GACN,OAAO;EACT;CACF,CAAC,CACH,EAEY,CAAC,KAAK,GAAG;AACvB;;;;;;AAOA,eAAe,YACb,MACA,aACA,cAAwB,CAAC,GACkB;CAC3C,MAAM,CAAC,MAAM,UAAU,MAAM,QAAQ,IAAI,CACvC,QAAQ,CAAC,GAAG,QAAQ,KAAK,UAAU,KAAK,KAAK,MAAM,GAAG,MAAM,M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WAAW,MAAM,cAAc,CAAC,CAAC,YAAY,CAAC,CAAC;EACrD;EACA,MAAM,OAAO;GACX,MAAM,SAAS,YAAY,CAAC,CAAC;EAC/B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"snapshot-source.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/devtools/snapshot-source.ts"],"sourcesContent":["/**\n * Where the panel's routes get the snapshot: opened once with\n * `routes: \"cached\"` (a devtools request never boots the app) and kept in\n * memory. Concurrent requests share one open. A change stamp (the book\n * manifest, the agent-written folders and indexes and the files the route\n * facts were read from, a few `stat` calls and no directory walk) tells when the book changed. With live\n * facts (`liveFacts`, development), an edit to a file the route facts were read from reads them again from\n * the running app on the next open, so a route edit shows without `warlock grimoire build`.\n *\n * - Production (`mode: \"production\"`): a snapshot is reused until the stamp\n * changes, with no time limit, unless `ttlMs` is set. A request that finds\n * the stamp changed waits for the new open. `warm()` opens the book ahead\n * of the first request.\n * - Development: the snapshot is reused for a short window (2 s, or five times\n * the last open when that is longer, so a slow open on a large app is not\n * repeated on every view; written files change while an agent works). A\n * request that finds the stamp changed waits for the new open. After the\n * window, with the stamp unchanged (a file edited in place), the cached\n * snapshot is served at once and one background open refreshes it (stale\n * while revalidate).\n *\n * An open that fails keeps serving the old snapshot; its error surfaces on a\n * request only when there is no snapshot at all. The panel passes\n * `write: true` in development, so the generated book stays current and the\n * next open is incremental; with `write: false` a stored book behind the\n * sources is rebuilt in memory on every open.\n */\nimport { stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { BookAdapter } from \"../contracts/adapter\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport { GRIMOIRE_PATHS } from \"../paths\";\nimport { resolveResultsFile } from \"../test-results\";\nimport { openGrimoire } from \"../workspace\";\n\n/** Options of the panel's snapshot source. */\nexport type SnapshotSourceOptions = {\n /** The adapter, or a function that loads it. Default: the Warlock adapter, imported on first use. */\n adapter?: BookAdapter | (() => Promise<BookAdapter>);\n /**\n * How long a snapshot is reused when the book did not change (ms).\n * Default in development: 2000, or five times as long as the last open took\n * when that is longer. Default in production: no limit (reused until the\n * book changes).\n */\n ttlMs?: number;\n /** Where the source runs. `\"production\"` keeps a snapshot until the book changes. Default: `\"development\"`. */\n mode?: \"development\" | \"production\";\n /** Let `openGrimoire` write the generated book and collected files (never agent-written files). Default `false`; the devtools panel passes `true`. */\n write?: boolean;\n /**\n * Where the test results are read from (project-relative or absolute).\n * Default `grimoire/book/test-results.json`. The file's modified time is part\n * of the change stamp, so results written after the snapshot opened show up\n * without a restart.\n */\n testResultsFile?: string;\n /**\n * Read the route facts once when the first open finds none (`routes: \"missing\"`), so the development tab is\n * never \"missing\" without a manual `warlock grimoire build`. The adapter's booted inspect runs at most once per\n * process; a boot that fails keeps the cached answer. Default `false`. Never set it in a process that serves the app: the boot\n * pass boots every connector and re-imports the route and event modules, which registers them twice. The devtools panel\n * does not set it; use it from a separate tool process.\n */\n collectRoutes?: boolean;\n /**\n * The adapter reads the route, event and job facts from the running process (`createWarlockAdapter({ live: true })`),\n * which is cheap and boots nothing. The first open then collects them in the same pass as the book\n * (`routes: \"fresh\"`), so the tab never opens \"missing\" and the first open runs once. Safe in the process that\n * serves the app. Default `false`; the devtools panel sets it in development with the Warlock adapter.\n */\n liveFacts?: boolean;\n};\n\n/** A cached, shared snapshot of one project. */\nexport type SnapshotSource = {\n get(): Promise<GrimoireSnapshot>;\n /** Forget the cached snapshot; the next `get()` opens again. */\n invalidate(): void;\n /** Start opening the book now, so the first `get()` is fast. Failures are ignored here and surface on `get()`. */\n warm(): void;\n /** Resolves when no open is running (specs and shutdown). Never rejects. */\n idle(): Promise<void>;\n};\n\n/** Files and folders whose modified time moves when the book or an agent-written file is added, removed or regenerated. */\nconst STAMPED = [\n GRIMOIRE_PATHS.bookManifest,\n GRIMOIRE_PATHS.featuresIndex,\n GRIMOIRE_PATHS.tasksIndex,\n GRIMOIRE_PATHS.features,\n GRIMOIRE_PATHS.apps,\n GRIMOIRE_PATHS.openTasks,\n GRIMOIRE_PATHS.doneTasks,\n GRIMOIRE_PATHS.releases,\n // Settings, the approved baseline and the capture index change what the tab shows.\n GRIMOIRE_PATHS.settings,\n GRIMOIRE_PATHS.approved,\n GRIMOIRE_PATHS.baseline,\n GRIMOIRE_PATHS.captureIndex,\n];\n\n/** The modified times of `files`, joined (`0` for a missing file). */\nasync function timesOf(files: string[]): Promise<string> {\n const times = await Promise.all(\n files.map(async (file) => {\n try {\n return (await stat(file)).mtimeMs;\n } catch {\n return 0;\n }\n }),\n );\n\n return times.join(\",\");\n}\n\n/**\n * The change stamp in two parts: `book` (the book manifest, the written folders, the results file) and `routes`\n * (the project-relative files the route facts were read from, `manifest.boot.inputs`). An edit to a route input\n * ends the reuse window; with live facts the next open reads the routes again, otherwise it reports them stale.\n */\nasync function changeStamp(\n root: string,\n resultsFile: string,\n routeInputs: string[] = [],\n): Promise<{ book: string; routes: string }> {\n const [book, routes] = await Promise.all([\n timesOf([...STAMPED.map((entry) => path.join(root, ...entry.split(\"/\"))), resultsFile]),\n timesOf(routeInputs.map((file) => path.join(root, ...file.split(\"/\")))),\n ]);\n\n return { book, routes };\n}\n\nconst routeInputsOf = (snapshot: GrimoireSnapshot): string[] =>\n Object.keys(snapshot.book.manifest.boot.inputs).sort();\n\nasync function loadAdapter(option: SnapshotSourceOptions[\"adapter\"]): Promise<BookAdapter> {\n if (option === undefined) {\n const { createWarlockAdapter } = await import(\"../warlock\");\n\n return createWarlockAdapter();\n }\n\n return typeof option === \"function\" ? option() : option;\n}\n\n/** Create the source for the project at `root`. */\nexport function createSnapshotSource(\n root: string,\n options: SnapshotSourceOptions = {},\n): SnapshotSource {\n let cached: {\n snapshot: GrimoireSnapshot;\n at: number;\n stamp: { book: string; routes: string };\n took: number;\n } | null = null;\n let opening: Promise<GrimoireSnapshot> | null = null;\n\n const live = options.liveFacts === true && options.mode !== \"production\";\n let collected = options.collectRoutes !== true || options.mode === \"production\";\n let liveCollected = !live;\n // Set when a route input changed: with live facts, the next open reads the routes from the running app again.\n let refreshRoutes = false;\n const resultsFile = resolveResultsFile(root, options.testResultsFile);\n\n const keepUntilChanged = options.mode === \"production\" && options.ttlMs === undefined;\n const reuseFor = (took: number): number => options.ttlMs ?? Math.max(2000, took * 5);\n\n async function open(): Promise<GrimoireSnapshot> {\n const started = Date.now();\n const adapter = await loadAdapter(options.adapter);\n const openOptions = {\n write: options.write ?? false,\n ...(options.testResultsFile === undefined\n ? {}\n : { testResultsFile: options.testResultsFile }),\n };\n let snapshot: GrimoireSnapshot;\n\n if (!liveCollected || refreshRoutes) {\n // One pass: the book and the live route facts together, so a first open never builds twice.\n // After a routes-file edit: the dev server reloads the file on save, so the live read sees its new routes.\n liveCollected = true;\n refreshRoutes = false;\n\n try {\n snapshot = await openGrimoire(root, adapter, { routes: \"fresh\", ...openOptions });\n } catch {\n // The facts could not be read: fall back to what the book already holds.\n snapshot = await openGrimoire(root, adapter, { routes: \"cached\", ...openOptions });\n }\n } else {\n snapshot = await openGrimoire(root, adapter, { routes: \"cached\", ...openOptions });\n }\n\n if (!collected && snapshot.routes === \"missing\") {\n // Once per source: the route, event and job facts come from one boot pass, then live in the book.\n collected = true;\n\n try {\n snapshot = await openGrimoire(root, adapter, { routes: \"fresh\", ...openOptions });\n } catch {\n // The app did not boot (GR8002): keep the cached answer; the tab says the facts are missing.\n }\n }\n\n const at = Date.now();\n\n cached = {\n snapshot,\n at,\n stamp: await changeStamp(root, resultsFile, routeInputsOf(snapshot)),\n took: at - started,\n };\n\n return snapshot;\n }\n\n /** The open in flight, or a new one; concurrent callers share it. */\n function ensureOpening(): Promise<GrimoireSnapshot> {\n opening ??= open().finally(() => {\n opening = null;\n });\n\n return opening;\n }\n\n return {\n async get() {\n if (cached === null) return ensureOpening();\n\n const known = cached;\n const stamp = await changeStamp(root, resultsFile, routeInputsOf(known.snapshot));\n const routesMoved = stamp.routes !== known.stamp.routes;\n const changed = routesMoved || stamp.book !== known.stamp.book;\n\n if (routesMoved && live) refreshRoutes = true;\n\n if (changed || options.mode === \"production\") {\n if (!changed && (keepUntilChanged || Date.now() - known.at < reuseFor(known.took))) {\n return known.snapshot;\n }\n\n // A failed open keeps the old snapshot; the next request tries again.\n return ensureOpening().catch(() => known.snapshot);\n }\n\n if (Date.now() - known.at < reuseFor(known.took)) return known.snapshot;\n\n // Development, nothing known to have changed: serve the old snapshot now and refresh behind it.\n ensureOpening().catch(() => {});\n\n return known.snapshot;\n },\n invalidate() {\n cached = null;\n },\n warm() {\n if (cached === null) ensureOpening().catch(() => {});\n },\n async idle() {\n await opening?.catch(() => {});\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsFA,MAAM,UAAU;CACd,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;CAEf,eAAe;CACf,eAAe;CACf,eAAe;CACf,eAAe;AACjB;;AAGA,eAAe,QAAQ,OAAkC;CAWvD,QAAO,MAVa,QAAQ,IAC1B,MAAM,IAAI,OAAO,SAAS;EACxB,IAAI;GACF,QAAQ,MAAM,KAAK,IAAI,EAAC,CAAE;EAC5B,QAAQ;GACN,OAAO;EACT;CACF,CAAC,CACH,EAEY,CAAC,KAAK,GAAG;AACvB;;;;;;AAOA,eAAe,YACb,MACA,aACA,cAAwB,CAAC,GACkB;CAC3C,MAAM,CAAC,MAAM,UAAU,MAAM,QAAQ,IAAI,CACvC,QAAQ,CAAC,GAAG,QAAQ,KAAK,UAAU,KAAK,KAAK,MAAM,GAAG,MAAM,MAAM,GAAG,CAAC,CAAC,GAAG,WAAW,CAAC,GACtF,QAAQ,YAAY,KAAK,SAAS,KAAK,KAAK,MAAM,GAAG,KAAK,MAAM,GAAG,CAAC,CAAC,CAAC,CACxE,CAAC;CAED,OAAO;EAAE;EAAM;CAAO;AACxB;AAEA,MAAM,iBAAiB,aACrB,OAAO,KAAK,SAAS,KAAK,SAAS,KAAK,MAAM,CAAC,CA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SAAS;KAAE,QAAQ;KAAS,GAAG;IAAY,CAAC;GAClF,QAAQ,CAER;EACF;EAEA,MAAM,KAAK,KAAK,IAAI;EAEpB,SAAS;GACP;GACA;GACA,OAAO,MAAM,YAAY,MAAM,aAAa,cAAc,QAAQ,CAAC;GACnE,MAAM,KAAK;EACb;EAEA,OAAO;CACT;;CAGA,SAAS,gBAA2C;EAClD,YAAY,KAAK,CAAC,CAAC,cAAc;GAC/B,UAAU;EACZ,CAAC;EAED,OAAO;CACT;CAEA,OAAO;EACL,MAAM,MAAM;GACV,IAAI,WAAW,MAAM,OAAO,cAAc;GAE1C,MAAM,QAAQ;GACd,MAAM,QAAQ,MAAM,YAAY,MAAM,aAAa,cAAc,MAAM,QAAQ,CAAC;GAChF,MAAM,cAAc,MAAM,WAAW,MAAM,MAAM;GACjD,MAAM,UAAU,eAAe,MAAM,SAAS,MAAM,MAAM;GAE1D,IAAI,eAAe,MAAM,gBAAgB;GAEzC,IAAI,WAAW,QAAQ,SAAS,cAAc;IAC5C,IAAI,CAAC,YAAY,oBAAoB,KAAK,IAAI,IAAI,MAAM,KAAK,SAAS,MAAM,IAAI,IAC9E,OAAO,MAAM;IAIf,OAAO,cAAc,CAAC,CAAC,YAAY,MAAM,QAAQ;GACnD;GAEA,IAAI,KAAK,IAAI,IAAI,MAAM,KAAK,SAAS,MAAM,IAAI,GAAG,OAAO,MAAM;GAG/D,cAAc,CAAC,CAAC,YAAY,CAAC,CAAC;GAE9B,OAAO,MAAM;EACf;EACA,aAAa;GACX,SAAS;EACX;EACA,OAAO;GACL,IAAI,WAAW,MAAM,cAAc,CAAC,CAAC,YAAY,CAAC,CAAC;EACrD;EACA,MAAM,OAAO;GACX,MAAM,SAAS,YAAY,CAAC,CAAC;EAC/B;CACF;AACF"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
//#region ../../packages/grimoire/src/git/index.d.ts
|
|
2
|
+
/** How a file changed between the base and the working tree. */
|
|
3
|
+
export type ChangedFileStatus = "added" | "modified" | "deleted" | "renamed";
|
|
4
|
+
/** One changed file, project-relative POSIX paths. */
|
|
5
|
+
export type ChangedFile = {
|
|
6
|
+
file: string;
|
|
7
|
+
status: ChangedFileStatus;
|
|
8
|
+
/** The path at the base for a rename, else `null`. */
|
|
9
|
+
from: string | null;
|
|
10
|
+
/** Line numbers (1-based, in the new file) the change adds; empty for a deleted file. */
|
|
11
|
+
addedLines: number[];
|
|
12
|
+
};
|
|
13
|
+
/** One commit of a range. */
|
|
14
|
+
export type CommitInfo = {
|
|
15
|
+
sha: string;
|
|
16
|
+
subject: string;
|
|
17
|
+
body: string;
|
|
18
|
+
};
|
|
19
|
+
//#endregion
|
|
20
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/git/index.ts"],"mappings":";;YAaY;;YAGA;EACV;EACA,QAAQ;;EAER;;EAEA;;;YAIU;EAAe;EAAa;EAAiB"}
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { GrimoireError } from "../codes/index.mjs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
|
|
6
|
+
//#region ../../packages/grimoire/src/git/index.ts
|
|
7
|
+
/**
|
|
8
|
+
* The few git questions the guard and the `changed` screenshot mode ask.
|
|
9
|
+
* Read-only: every call runs `git` with an argument array (never a shell)
|
|
10
|
+
* in the project root, and every path is relative to that root, so a project
|
|
11
|
+
* inside a larger repository works. Failures throw `GrimoireError` with
|
|
12
|
+
* `GR9009`.
|
|
13
|
+
*/
|
|
14
|
+
const MAX_BUFFER = 268435456;
|
|
15
|
+
/** Run git in `root`; never throws. */
|
|
16
|
+
function runGit(root, args) {
|
|
17
|
+
return new Promise((resolve) => {
|
|
18
|
+
execFile("git", [
|
|
19
|
+
"-c",
|
|
20
|
+
"core.quotePath=false",
|
|
21
|
+
"-C",
|
|
22
|
+
root,
|
|
23
|
+
...args
|
|
24
|
+
], {
|
|
25
|
+
maxBuffer: MAX_BUFFER,
|
|
26
|
+
encoding: "utf8",
|
|
27
|
+
env: {
|
|
28
|
+
...process.env,
|
|
29
|
+
GIT_OPTIONAL_LOCKS: "0",
|
|
30
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
31
|
+
LC_ALL: "C"
|
|
32
|
+
}
|
|
33
|
+
}, (error, stdout, stderr) => {
|
|
34
|
+
if (error === null) {
|
|
35
|
+
resolve({
|
|
36
|
+
ok: true,
|
|
37
|
+
stdout
|
|
38
|
+
});
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const failure = error;
|
|
42
|
+
resolve({
|
|
43
|
+
ok: false,
|
|
44
|
+
stderr: failure.code === "ENOENT" ? "git is not installed or not on the PATH" : String(stderr),
|
|
45
|
+
code: failure.code ?? null
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function gitError(what, result) {
|
|
51
|
+
const detail = result.stderr.trim().split("\n")[0] ?? "";
|
|
52
|
+
return new GrimoireError("GR9009", `Git could not ${what}${detail === "" ? "" : `: ${detail}`}. Run inside a git repository and pass a base that exists (--base origin/main); in CI, fetch the full history.`);
|
|
53
|
+
}
|
|
54
|
+
async function git(root, args, what) {
|
|
55
|
+
const result = await runGit(root, args);
|
|
56
|
+
if (!result.ok) throw gitError(what, result);
|
|
57
|
+
return result.stdout;
|
|
58
|
+
}
|
|
59
|
+
/** The commit a ref names, or `null` when there is none. */
|
|
60
|
+
async function commitOf(root, ref) {
|
|
61
|
+
const result = await runGit(root, [
|
|
62
|
+
"rev-parse",
|
|
63
|
+
"--verify",
|
|
64
|
+
"--quiet",
|
|
65
|
+
`${ref}^{commit}`
|
|
66
|
+
]);
|
|
67
|
+
return result.ok ? result.stdout.trim() : null;
|
|
68
|
+
}
|
|
69
|
+
/** The merge base of `HEAD` and a commit, or the commit itself when the histories share nothing. */
|
|
70
|
+
async function mergeBaseWithHead(root, commit) {
|
|
71
|
+
const result = await runGit(root, [
|
|
72
|
+
"merge-base",
|
|
73
|
+
"HEAD",
|
|
74
|
+
commit
|
|
75
|
+
]);
|
|
76
|
+
return result.ok && result.stdout.trim() !== "" ? result.stdout.trim() : commit;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The base to compare with: `base` when given (it must exist), else the
|
|
80
|
+
* default branch (`origin/HEAD`, then `main`, then `master`), else `HEAD`.
|
|
81
|
+
* The answer is the commit where `HEAD` left that ref (their merge base), so
|
|
82
|
+
* a branch that is behind its base does not show the base's own work.
|
|
83
|
+
*/
|
|
84
|
+
async function resolveBase(root, base) {
|
|
85
|
+
const inside = await runGit(root, ["rev-parse", "--is-inside-work-tree"]);
|
|
86
|
+
if (!inside.ok) throw gitError("read the repository", inside);
|
|
87
|
+
if (base !== void 0 && base.trim() !== "") {
|
|
88
|
+
const commit = await commitOf(root, base.trim());
|
|
89
|
+
if (commit === null) throw new GrimoireError("GR9009", `Git has no base ${JSON.stringify(base)}. Pass a ref that exists (--base origin/main); in CI, fetch the full history.`);
|
|
90
|
+
return mergeBaseWithHead(root, commit);
|
|
91
|
+
}
|
|
92
|
+
const head = await commitOf(root, "HEAD");
|
|
93
|
+
if (head === null) throw new GrimoireError("GR9009", "Git has no commit to compare with yet. Commit once, or pass --base <ref>.");
|
|
94
|
+
const symbolic = await runGit(root, [
|
|
95
|
+
"symbolic-ref",
|
|
96
|
+
"--quiet",
|
|
97
|
+
"--short",
|
|
98
|
+
"refs/remotes/origin/HEAD"
|
|
99
|
+
]);
|
|
100
|
+
const candidates = [
|
|
101
|
+
symbolic.ok ? symbolic.stdout.trim() : "",
|
|
102
|
+
"main",
|
|
103
|
+
"master"
|
|
104
|
+
].filter((name) => name !== "");
|
|
105
|
+
for (const name of candidates) {
|
|
106
|
+
const commit = await commitOf(root, name);
|
|
107
|
+
if (commit !== null) return mergeBaseWithHead(root, commit);
|
|
108
|
+
}
|
|
109
|
+
return head;
|
|
110
|
+
}
|
|
111
|
+
function posix(file) {
|
|
112
|
+
return file.split("\\").join("/");
|
|
113
|
+
}
|
|
114
|
+
/** `@@ -a,b +c,d @@` → the new file's added line numbers. */
|
|
115
|
+
function parseDiffLines(diff) {
|
|
116
|
+
const added = /* @__PURE__ */ new Map();
|
|
117
|
+
let current = null;
|
|
118
|
+
let header = false;
|
|
119
|
+
for (const line of diff.split("\n")) {
|
|
120
|
+
if (line.startsWith("diff --git ")) {
|
|
121
|
+
header = true;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (header && line.startsWith("+++ ")) {
|
|
125
|
+
const target = line.slice(4).replace(/\t.*$/, "");
|
|
126
|
+
if (target === "/dev/null") {
|
|
127
|
+
current = null;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
const file = posix(target.startsWith("\"") ? unquote(target) : target);
|
|
131
|
+
current = added.get(file) ?? [];
|
|
132
|
+
added.set(file, current);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);
|
|
136
|
+
if (hunk) header = false;
|
|
137
|
+
if (hunk && current !== null) {
|
|
138
|
+
const start = Number(hunk[1]);
|
|
139
|
+
const count = hunk[2] === void 0 ? 1 : Number(hunk[2]);
|
|
140
|
+
for (let offset = 0; offset < count; offset++) current.push(start + offset);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return added;
|
|
144
|
+
}
|
|
145
|
+
/** A C-style quoted path from git (`"a\"b"`). */
|
|
146
|
+
function unquote(quoted) {
|
|
147
|
+
return quoted.slice(1, -1).replace(/\\(["\\])/g, "$1").replace(/\\t/g, " ").replace(/\\n/g, "\n");
|
|
148
|
+
}
|
|
149
|
+
/** Line numbers of a whole new file (binary files have none). */
|
|
150
|
+
async function allLines(root, file) {
|
|
151
|
+
let content;
|
|
152
|
+
try {
|
|
153
|
+
content = await readFile(path.join(root, ...file.split("/")));
|
|
154
|
+
} catch {
|
|
155
|
+
return [];
|
|
156
|
+
}
|
|
157
|
+
if (content.subarray(0, 8e3).includes(0)) return [];
|
|
158
|
+
const text = content.toString("utf8");
|
|
159
|
+
if (text === "") return [];
|
|
160
|
+
const count = text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
|
|
161
|
+
return Array.from({ length: count }, (_value, index) => index + 1);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Every file that differs between `base` and the working tree: committed
|
|
165
|
+
* since the base, staged, unstaged and untracked (not ignored) files, sorted
|
|
166
|
+
* by path. `addedLines` come from `git diff --unified=0`; an untracked file
|
|
167
|
+
* counts as added with every line added.
|
|
168
|
+
*/
|
|
169
|
+
async function changedFiles(root, base) {
|
|
170
|
+
const status = await git(root, [
|
|
171
|
+
"diff",
|
|
172
|
+
"--name-status",
|
|
173
|
+
"-z",
|
|
174
|
+
"-M",
|
|
175
|
+
"--relative",
|
|
176
|
+
"--no-color",
|
|
177
|
+
"--no-ext-diff",
|
|
178
|
+
base,
|
|
179
|
+
"--"
|
|
180
|
+
], "list the changed files");
|
|
181
|
+
const diff = await git(root, [
|
|
182
|
+
"diff",
|
|
183
|
+
"--unified=0",
|
|
184
|
+
"-M",
|
|
185
|
+
"--relative",
|
|
186
|
+
"--no-prefix",
|
|
187
|
+
"--no-color",
|
|
188
|
+
"--no-ext-diff",
|
|
189
|
+
base,
|
|
190
|
+
"--"
|
|
191
|
+
], "read the changed lines");
|
|
192
|
+
const untracked = await git(root, [
|
|
193
|
+
"ls-files",
|
|
194
|
+
"-z",
|
|
195
|
+
"--others",
|
|
196
|
+
"--exclude-standard"
|
|
197
|
+
], "list the untracked files");
|
|
198
|
+
const lines = parseDiffLines(diff);
|
|
199
|
+
const files = /* @__PURE__ */ new Map();
|
|
200
|
+
const fields = status.split("\0");
|
|
201
|
+
for (let index = 0; index < fields.length; index++) {
|
|
202
|
+
const code = fields[index] ?? "";
|
|
203
|
+
if (code === "") continue;
|
|
204
|
+
const letter = code[0];
|
|
205
|
+
if (letter === "R" || letter === "C") {
|
|
206
|
+
const from = posix(fields[index + 1] ?? "");
|
|
207
|
+
const file = posix(fields[index + 2] ?? "");
|
|
208
|
+
index += 2;
|
|
209
|
+
files.set(file, {
|
|
210
|
+
file,
|
|
211
|
+
status: letter === "R" ? "renamed" : "added",
|
|
212
|
+
from: letter === "R" ? from : null,
|
|
213
|
+
addedLines: lines.get(file) ?? []
|
|
214
|
+
});
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const file = posix(fields[index + 1] ?? "");
|
|
218
|
+
index += 1;
|
|
219
|
+
files.set(file, {
|
|
220
|
+
file,
|
|
221
|
+
status: letter === "A" ? "added" : letter === "D" ? "deleted" : "modified",
|
|
222
|
+
from: null,
|
|
223
|
+
addedLines: letter === "D" ? [] : lines.get(file) ?? []
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
for (const name of untracked.split("\0")) {
|
|
227
|
+
const file = posix(name);
|
|
228
|
+
if (file === "" || files.has(file)) continue;
|
|
229
|
+
files.set(file, {
|
|
230
|
+
file,
|
|
231
|
+
status: "added",
|
|
232
|
+
from: null,
|
|
233
|
+
addedLines: await allLines(root, file)
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
for (const entry of files.values()) if (entry.status === "added" && entry.addedLines.length === 0) entry.addedLines = await allLines(root, entry.file);
|
|
237
|
+
return [...files.values()].sort((left, right) => left.file < right.file ? -1 : left.file > right.file ? 1 : 0);
|
|
238
|
+
}
|
|
239
|
+
/** The text of `file` at `ref`, or `null` when it does not exist there. */
|
|
240
|
+
async function showFile(root, ref, file) {
|
|
241
|
+
const result = await runGit(root, ["show", `${ref}:./${posix(file).replace(/^\.\//, "")}`]);
|
|
242
|
+
if (result.ok) return result.stdout;
|
|
243
|
+
if (await commitOf(root, ref) === null) throw new GrimoireError("GR9009", `Git has no ref ${JSON.stringify(ref)}. Pass a ref that exists (--base origin/main); in CI, fetch the full history.`);
|
|
244
|
+
return null;
|
|
245
|
+
}
|
|
246
|
+
/** The files under `folder` (a project-relative folder) at `ref`, sorted. */
|
|
247
|
+
async function filesAt(root, ref, folder) {
|
|
248
|
+
const result = await runGit(root, [
|
|
249
|
+
"ls-tree",
|
|
250
|
+
"-r",
|
|
251
|
+
"-z",
|
|
252
|
+
"--name-only",
|
|
253
|
+
ref,
|
|
254
|
+
"--",
|
|
255
|
+
`${posix(folder)}/`
|
|
256
|
+
]);
|
|
257
|
+
if (!result.ok) return [];
|
|
258
|
+
return result.stdout.split("\0").filter((name) => name !== "").map(posix).sort();
|
|
259
|
+
}
|
|
260
|
+
/** The commits of a range (`origin/main..HEAD`), oldest first. */
|
|
261
|
+
async function commitsIn(root, range) {
|
|
262
|
+
return (await git(root, [
|
|
263
|
+
"log",
|
|
264
|
+
"--reverse",
|
|
265
|
+
"--format=%H%x1f%s%x1f%b%x1e",
|
|
266
|
+
range,
|
|
267
|
+
"--"
|
|
268
|
+
], `list the commits of ${range}`)).split("").map((record) => record.replace(/^\n+/, "")).filter((record) => record.trim() !== "").map((record) => {
|
|
269
|
+
const [sha = "", subject = "", body = ""] = record.split("");
|
|
270
|
+
return {
|
|
271
|
+
sha: sha.trim(),
|
|
272
|
+
subject: subject.trim(),
|
|
273
|
+
body: body.trim()
|
|
274
|
+
};
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
//#endregion
|
|
279
|
+
export { changedFiles, commitsIn, filesAt, resolveBase, showFile };
|
|
280
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/git/index.ts"],"sourcesContent":["/**\n * The few git questions the guard and the `changed` screenshot mode ask.\n * Read-only: every call runs `git` with an argument array (never a shell)\n * in the project root, and every path is relative to that root, so a project\n * inside a larger repository works. Failures throw `GrimoireError` with\n * `GR9009`.\n */\nimport { execFile } from \"node:child_process\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { GrimoireError } from \"../codes\";\n\n/** How a file changed between the base and the working tree. */\nexport type ChangedFileStatus = \"added\" | \"modified\" | \"deleted\" | \"renamed\";\n\n/** One changed file, project-relative POSIX paths. */\nexport type ChangedFile = {\n file: string;\n status: ChangedFileStatus;\n /** The path at the base for a rename, else `null`. */\n from: string | null;\n /** Line numbers (1-based, in the new file) the change adds; empty for a deleted file. */\n addedLines: number[];\n};\n\n/** One commit of a range. */\nexport type CommitInfo = { sha: string; subject: string; body: string };\n\ntype GitResult =\n | { ok: true; stdout: string }\n | { ok: false; stderr: string; code: number | string | null };\n\nconst MAX_BUFFER = 256 * 1024 * 1024;\n\n/** Run git in `root`; never throws. */\nfunction runGit(root: string, args: readonly string[]): Promise<GitResult> {\n return new Promise((resolve) => {\n execFile(\n \"git\",\n [\"-c\", \"core.quotePath=false\", \"-C\", root, ...args],\n {\n maxBuffer: MAX_BUFFER,\n encoding: \"utf8\",\n env: { ...process.env, GIT_OPTIONAL_LOCKS: \"0\", GIT_TERMINAL_PROMPT: \"0\", LC_ALL: \"C\" },\n },\n (error, stdout, stderr) => {\n if (error === null) {\n resolve({ ok: true, stdout });\n\n return;\n }\n\n const failure = error as NodeJS.ErrnoException & { code?: number | string };\n\n resolve({\n ok: false,\n stderr:\n failure.code === \"ENOENT\" ? \"git is not installed or not on the PATH\" : String(stderr),\n code: failure.code ?? null,\n });\n },\n );\n });\n}\n\nfunction gitError(what: string, result: Extract<GitResult, { ok: false }>): GrimoireError {\n const detail = result.stderr.trim().split(\"\\n\")[0] ?? \"\";\n\n return new GrimoireError(\n \"GR9009\",\n `Git could not ${what}${detail === \"\" ? \"\" : `: ${detail}`}. Run inside a git repository and pass a base that exists (--base origin/main); in CI, fetch the full history.`,\n );\n}\n\nasync function git(root: string, args: readonly string[], what: string): Promise<string> {\n const result = await runGit(root, args);\n\n if (!result.ok) throw gitError(what, result);\n\n return result.stdout;\n}\n\n/** The commit a ref names, or `null` when there is none. */\nasync function commitOf(root: string, ref: string): Promise<string | null> {\n const result = await runGit(root, [\"rev-parse\", \"--verify\", \"--quiet\", `${ref}^{commit}`]);\n\n return result.ok ? result.stdout.trim() : null;\n}\n\n/** The merge base of `HEAD` and a commit, or the commit itself when the histories share nothing. */\nasync function mergeBaseWithHead(root: string, commit: string): Promise<string> {\n const result = await runGit(root, [\"merge-base\", \"HEAD\", commit]);\n\n return result.ok && result.stdout.trim() !== \"\" ? result.stdout.trim() : commit;\n}\n\n/**\n * The base to compare with: `base` when given (it must exist), else the\n * default branch (`origin/HEAD`, then `main`, then `master`), else `HEAD`.\n * The answer is the commit where `HEAD` left that ref (their merge base), so\n * a branch that is behind its base does not show the base's own work.\n */\nexport async function resolveBase(root: string, base?: string): Promise<string> {\n const inside = await runGit(root, [\"rev-parse\", \"--is-inside-work-tree\"]);\n\n if (!inside.ok) throw gitError(\"read the repository\", inside);\n\n if (base !== undefined && base.trim() !== \"\") {\n const commit = await commitOf(root, base.trim());\n\n if (commit === null) {\n throw new GrimoireError(\n \"GR9009\",\n `Git has no base ${JSON.stringify(base)}. Pass a ref that exists (--base origin/main); in CI, fetch the full history.`,\n );\n }\n\n return mergeBaseWithHead(root, commit);\n }\n\n const head = await commitOf(root, \"HEAD\");\n\n if (head === null) {\n throw new GrimoireError(\n \"GR9009\",\n \"Git has no commit to compare with yet. Commit once, or pass --base <ref>.\",\n );\n }\n\n const symbolic = await runGit(root, [\n \"symbolic-ref\",\n \"--quiet\",\n \"--short\",\n \"refs/remotes/origin/HEAD\",\n ]);\n const candidates = [symbolic.ok ? symbolic.stdout.trim() : \"\", \"main\", \"master\"].filter(\n (name) => name !== \"\",\n );\n\n for (const name of candidates) {\n const commit = await commitOf(root, name);\n\n if (commit !== null) return mergeBaseWithHead(root, commit);\n }\n\n return head;\n}\n\nfunction posix(file: string): string {\n return file.split(\"\\\\\").join(\"/\");\n}\n\n/** `@@ -a,b +c,d @@` → the new file's added line numbers. */\nfunction parseDiffLines(diff: string): Map<string, number[]> {\n const added = new Map<string, number[]>();\n let current: number[] | null = null;\n // `+++ ` names the file only in a file's header: inside a hunk it is an added line that starts with `++`.\n let header = false;\n\n for (const line of diff.split(\"\\n\")) {\n if (line.startsWith(\"diff --git \")) {\n header = true;\n continue;\n }\n\n if (header && line.startsWith(\"+++ \")) {\n const target = line.slice(4).replace(/\\t.*$/, \"\");\n\n if (target === \"/dev/null\") {\n current = null;\n continue;\n }\n\n const file = posix(target.startsWith('\"') ? unquote(target) : target);\n\n current = added.get(file) ?? [];\n added.set(file, current);\n continue;\n }\n\n const hunk = /^@@ -\\d+(?:,\\d+)? \\+(\\d+)(?:,(\\d+))? @@/.exec(line);\n\n if (hunk) header = false;\n\n if (hunk && current !== null) {\n const start = Number(hunk[1]);\n const count = hunk[2] === undefined ? 1 : Number(hunk[2]);\n\n for (let offset = 0; offset < count; offset++) current.push(start + offset);\n }\n }\n\n return added;\n}\n\n/** A C-style quoted path from git (`\"a\\\"b\"`). */\nfunction unquote(quoted: string): string {\n return quoted\n .slice(1, -1)\n .replace(/\\\\([\"\\\\])/g, \"$1\")\n .replace(/\\\\t/g, \"\\t\")\n .replace(/\\\\n/g, \"\\n\");\n}\n\n/** Line numbers of a whole new file (binary files have none). */\nasync function allLines(root: string, file: string): Promise<number[]> {\n let content: Buffer;\n\n try {\n content = await readFile(path.join(root, ...file.split(\"/\")));\n } catch {\n return [];\n }\n\n if (content.subarray(0, 8000).includes(0)) return [];\n\n const text = content.toString(\"utf8\");\n\n if (text === \"\") return [];\n\n const count = text.split(\"\\n\").length - (text.endsWith(\"\\n\") ? 1 : 0);\n\n return Array.from({ length: count }, (_value, index) => index + 1);\n}\n\n/**\n * Every file that differs between `base` and the working tree: committed\n * since the base, staged, unstaged and untracked (not ignored) files, sorted\n * by path. `addedLines` come from `git diff --unified=0`; an untracked file\n * counts as added with every line added.\n */\nexport async function changedFiles(root: string, base: string): Promise<ChangedFile[]> {\n const status = await git(\n root,\n [\"diff\", \"--name-status\", \"-z\", \"-M\", \"--relative\", \"--no-color\", \"--no-ext-diff\", base, \"--\"],\n \"list the changed files\",\n );\n const diff = await git(\n root,\n [\n \"diff\",\n \"--unified=0\",\n \"-M\",\n \"--relative\",\n \"--no-prefix\",\n \"--no-color\",\n \"--no-ext-diff\",\n base,\n \"--\",\n ],\n \"read the changed lines\",\n );\n const untracked = await git(\n root,\n [\"ls-files\", \"-z\", \"--others\", \"--exclude-standard\"],\n \"list the untracked files\",\n );\n const lines = parseDiffLines(diff);\n const files = new Map<string, ChangedFile>();\n const fields = status.split(\"\\0\");\n\n for (let index = 0; index < fields.length; index++) {\n const code = fields[index] ?? \"\";\n\n if (code === \"\") continue;\n\n const letter = code[0];\n\n if (letter === \"R\" || letter === \"C\") {\n const from = posix(fields[index + 1] ?? \"\");\n const file = posix(fields[index + 2] ?? \"\");\n\n index += 2;\n files.set(file, {\n file,\n status: letter === \"R\" ? \"renamed\" : \"added\",\n from: letter === \"R\" ? from : null,\n addedLines: lines.get(file) ?? [],\n });\n continue;\n }\n\n const file = posix(fields[index + 1] ?? \"\");\n\n index += 1;\n files.set(file, {\n file,\n status: letter === \"A\" ? \"added\" : letter === \"D\" ? \"deleted\" : \"modified\",\n from: null,\n addedLines: letter === \"D\" ? [] : (lines.get(file) ?? []),\n });\n }\n\n for (const name of untracked.split(\"\\0\")) {\n const file = posix(name);\n\n if (file === \"\" || files.has(file)) continue;\n\n files.set(file, { file, status: \"added\", from: null, addedLines: await allLines(root, file) });\n }\n\n // An added file that git reports without hunks (the diff of a staged new file) still has every line added.\n for (const entry of files.values()) {\n if (entry.status === \"added\" && entry.addedLines.length === 0) {\n entry.addedLines = await allLines(root, entry.file);\n }\n }\n\n return [...files.values()].sort((left, right) =>\n left.file < right.file ? -1 : left.file > right.file ? 1 : 0,\n );\n}\n\n/** The text of `file` at `ref`, or `null` when it does not exist there. */\nexport async function showFile(root: string, ref: string, file: string): Promise<string | null> {\n const result = await runGit(root, [\"show\", `${ref}:./${posix(file).replace(/^\\.\\//, \"\")}`]);\n\n if (result.ok) return result.stdout;\n\n if ((await commitOf(root, ref)) === null) {\n throw new GrimoireError(\n \"GR9009\",\n `Git has no ref ${JSON.stringify(ref)}. Pass a ref that exists (--base origin/main); in CI, fetch the full history.`,\n );\n }\n\n return null;\n}\n\n/** The files under `folder` (a project-relative folder) at `ref`, sorted. */\nexport async function filesAt(root: string, ref: string, folder: string): Promise<string[]> {\n const result = await runGit(root, [\n \"ls-tree\",\n \"-r\",\n \"-z\",\n \"--name-only\",\n ref,\n \"--\",\n `${posix(folder)}/`,\n ]);\n\n if (!result.ok) return [];\n\n // `ls-tree` prints paths relative to the current folder when it runs inside one.\n return result.stdout\n .split(\"\\0\")\n .filter((name) => name !== \"\")\n .map(posix)\n .sort();\n}\n\n/** The commits of a range (`origin/main..HEAD`), oldest first. */\nexport async function commitsIn(root: string, range: string): Promise<CommitInfo[]> {\n const out = await git(\n root,\n [\"log\", \"--reverse\", \"--format=%H%x1f%s%x1f%b%x1e\", range, \"--\"],\n `list the commits of ${range}`,\n );\n\n return out\n .split(\"\\x1e\")\n .map((record) => record.replace(/^\\n+/, \"\"))\n .filter((record) => record.trim() !== \"\")\n .map((record) => {\n const [sha = \"\", subject = \"\", body = \"\"] = record.split(\"\\x1f\");\n\n return { sha: sha.trim(), subject: subject.trim(), body: body.trim() };\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAgCA,MAAM,aAAa;;AAGnB,SAAS,OAAO,MAAc,MAA6C;CACzE,OAAO,IAAI,SAAS,YAAY;EAC9B,SACE,OACA;GAAC;GAAM;GAAwB;GAAM;GAAM,GAAG;EAAI,GAClD;GACE,WAAW;GACX,UAAU;GACV,KAAK;IAAE,GAAG,QAAQ;IAAK,oBAAoB;IAAK,qBAAqB;IAAK,QAAQ;GAAI;EACxF,IACC,OAAO,QAAQ,WAAW;GACzB,IAAI,UAAU,MAAM;IAClB,QAAQ;KAAE,IAAI;KA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
|
5
|
+
//#region ../../packages/grimoire/src/guard/api.ts
|
|
6
|
+
/**
|
|
7
|
+
* The approved public API: the HTTP routes the app serves, kept in
|
|
8
|
+
* `grimoire/approved/api.json` so that any change to them is deliberate.
|
|
9
|
+
*/
|
|
10
|
+
/** The sorted route lines of a route list: `GET /orders [auth]`. Page routes are not API. */
|
|
11
|
+
function routeLines(routes) {
|
|
12
|
+
const lines = /* @__PURE__ */ new Set();
|
|
13
|
+
for (const route of routes) {
|
|
14
|
+
if (route.isPage) continue;
|
|
15
|
+
lines.add(`${route.method.toUpperCase()} ${route.path}${route.auth.required ? " [auth]" : ""}`);
|
|
16
|
+
}
|
|
17
|
+
return [...lines].sort();
|
|
18
|
+
}
|
|
19
|
+
/** An `api.json` text, or `null` when it is not one. */
|
|
20
|
+
function parseApiSnapshot(text) {
|
|
21
|
+
try {
|
|
22
|
+
const parsed = JSON.parse(text);
|
|
23
|
+
if (!Array.isArray(parsed.routes)) return null;
|
|
24
|
+
return {
|
|
25
|
+
schemaVersion: 1,
|
|
26
|
+
approvedAt: typeof parsed.approvedAt === "string" ? parsed.approvedAt : "",
|
|
27
|
+
routes: parsed.routes.filter((line) => typeof line === "string")
|
|
28
|
+
};
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** `grimoire/approved/api.json`, or `null` when it was never approved or cannot be read. */
|
|
34
|
+
async function readApiSnapshot(root) {
|
|
35
|
+
try {
|
|
36
|
+
return parseApiSnapshot(await readFile(path.join(root, ...GRIMOIRE_PATHS.apiSnapshot.split("/")), "utf8"));
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** Write `grimoire/approved/api.json`. */
|
|
42
|
+
async function writeApiSnapshot(root, routes, now = /* @__PURE__ */ new Date()) {
|
|
43
|
+
const snapshot = {
|
|
44
|
+
schemaVersion: 1,
|
|
45
|
+
approvedAt: now.toISOString(),
|
|
46
|
+
routes: [...routes].sort()
|
|
47
|
+
};
|
|
48
|
+
const file = path.join(root, ...GRIMOIRE_PATHS.apiSnapshot.split("/"));
|
|
49
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
50
|
+
await writeFile(file, `${JSON.stringify(snapshot, null, 2)}\n`);
|
|
51
|
+
return snapshot;
|
|
52
|
+
}
|
|
53
|
+
/** The routes added to and removed from the approved list. */
|
|
54
|
+
function diffRoutes(approved, current) {
|
|
55
|
+
const before = new Set(approved);
|
|
56
|
+
const after = new Set(current);
|
|
57
|
+
return {
|
|
58
|
+
added: current.filter((line) => !before.has(line)),
|
|
59
|
+
removed: approved.filter((line) => !after.has(line))
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** A short text of a route difference: `added GET /a, removed POST /b`. */
|
|
63
|
+
function describeRouteDiff(diff) {
|
|
64
|
+
const part = (label, lines) => lines.length === 0 ? "" : `${label} ${lines.slice(0, 5).join(", ")}${lines.length > 5 ? `, … ${lines.length - 5} more` : ""}`;
|
|
65
|
+
return [part("added", diff.added), part("removed", diff.removed)].filter(Boolean).join("; ");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
//#endregion
|
|
69
|
+
export { describeRouteDiff, diffRoutes, parseApiSnapshot, readApiSnapshot, routeLines, writeApiSnapshot };
|
|
70
|
+
//# sourceMappingURL=api.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/guard/api.ts"],"sourcesContent":["/**\n * The approved public API: the HTTP routes the app serves, kept in\n * `grimoire/approved/api.json` so that any change to them is deliberate.\n */\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { BookRoute } from \"../contracts/adapter\";\nimport type { ApiSnapshot } from \"../contracts/guard\";\nimport { GRIMOIRE_PATHS } from \"../paths\";\n\n/** The sorted route lines of a route list: `GET /orders [auth]`. Page routes are not API. */\nexport function routeLines(routes: readonly BookRoute[]): string[] {\n const lines = new Set<string>();\n\n for (const route of routes) {\n if (route.isPage) continue;\n\n lines.add(`${route.method.toUpperCase()} ${route.path}${route.auth.required ? \" [auth]\" : \"\"}`);\n }\n\n return [...lines].sort();\n}\n\n/** An `api.json` text, or `null` when it is not one. */\nexport function parseApiSnapshot(text: string): ApiSnapshot | null {\n try {\n const parsed = JSON.parse(text) as Partial<ApiSnapshot>;\n\n if (!Array.isArray(parsed.routes)) return null;\n\n return {\n schemaVersion: 1,\n approvedAt: typeof parsed.approvedAt === \"string\" ? parsed.approvedAt : \"\",\n routes: parsed.routes.filter((line): line is string => typeof line === \"string\"),\n };\n } catch {\n return null;\n }\n}\n\n/** `grimoire/approved/api.json`, or `null` when it was never approved or cannot be read. */\nexport async function readApiSnapshot(root: string): Promise<ApiSnapshot | null> {\n try {\n return parseApiSnapshot(\n await readFile(path.join(root, ...GRIMOIRE_PATHS.apiSnapshot.split(\"/\")), \"utf8\"),\n );\n } catch {\n return null;\n }\n}\n\n/** Write `grimoire/approved/api.json`. */\nexport async function writeApiSnapshot(\n root: string,\n routes: readonly string[],\n now: Date = new Date(),\n): Promise<ApiSnapshot> {\n const snapshot: ApiSnapshot = {\n schemaVersion: 1,\n approvedAt: now.toISOString(),\n routes: [...routes].sort(),\n };\n const file = path.join(root, ...GRIMOIRE_PATHS.apiSnapshot.split(\"/\"));\n\n await mkdir(path.dirname(file), { recursive: true });\n await writeFile(file, `${JSON.stringify(snapshot, null, 2)}\\n`);\n\n return snapshot;\n}\n\n/** The routes added to and removed from the approved list. */\nexport function diffRoutes(\n approved: readonly string[],\n current: readonly string[],\n): { added: string[]; removed: string[] } {\n const before = new Set(approved);\n const after = new Set(current);\n\n return {\n added: current.filter((line) => !before.has(line)),\n removed: approved.filter((line) => !after.has(line)),\n };\n}\n\n/** A short text of a route difference: `added GET /a, removed POST /b`. */\nexport function describeRouteDiff(diff: { added: string[]; removed: string[] }): string {\n const part = (label: string, lines: string[]): string =>\n lines.length === 0\n ? \"\"\n : `${label} ${lines.slice(0, 5).join(\", \")}${lines.length > 5 ? `, … ${lines.length - 5} more` : \"\"}`;\n\n return [part(\"added\", diff.added), part(\"removed\", diff.removed)].filter(Boolean).join(\"; \");\n}\n"],"mappings":";;;;;;;;;;AAWA,SAAgB,WAAW,QAAwC;CACjE,MAAM,wBAAQ,IAAI,IAAY;CAE9B,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,MAAM,QAAQ;EAElB,MAAM,IAAI,GAAG,MAAM,OAAO,YAAY,EAAE,GAAG,MAAM,OAAO,MAAM,KAAK,WAAW,YAAY,IAAI;CAChG;CAEA,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK;AACzB;;AAGA,SAAgB,iBAAiB,MAAkC;CACjE,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;EAE9B,IAAI,CAAC,MAAM,QAAQ,OAAO,MAAM,GAAG,OAAO;EAE1C,OAAO;GACL,eAAe;GACf,YAAY,OAAO,OAAO,eAAe,WAAW,OAAO,aAAa;GACxE,QAAQ,OAAO,OAAO,QAAQ,SAAyB,OAAO,SAAS,QAAQ;EACjF;CACF,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,eAAsB,gBAAgB,MAA2C;CAC/E,IAAI;EACF,OAAO,iBACL,MAAM,SAAS,KAAK,KAAK,MAAM,GAAG,eAAe,YAAY,MAAM,GAAG,CAAC,GAAG,MAAM,CAClF;CACF,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,eAAsB,iBACpB,MACA,QACA,sBAAY,IAAI,KAAK,GACC;CACtB,MAAM,WAAwB;EAC5B,eAAe;EACf,YAAY,IAAI,YAAY;EAC5B,QAAQ,CAAC,GAAG,MAAM,CAAC,CAAC,KAAK;CAC3B;CACA,MAAM,OAAO,KAAK,KAAK,MAAM,GAAG,eAAe,YAAY,MAAM,GAAG,CAAC;CAErE,MAAM,MAAM,KAAK,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CACnD,MAAM,UAAU,MAAM,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,EAAE,GAAG;CAE9D,OAAO;AACT;;AAGA,SAAgB,WACd,UACA,SACwC;CACxC,MAAM,SAAS,IAAI,IAAI,QAAQ;CAC/B,MAAM,QAAQ,IAAI,IAAI,OAAO;CAE7B,OAAO;EACL,OAAO,QAAQ,QAAQ,SAAS,CAAC,OAAO,IAAI,IAAI,CAAC;EACjD,SAAS,SAAS,QAAQ,SAAS,CAAC,MAAM,IAAI,IAAI,CAAC;CACrD;AACF;;AAGA,SAAgB,kBAAkB,MAAsD;CACtF,MAAM,QAAQ,OAAe,UAC3B,MAAM,WAAW,IACb,KACA,GAAG,MAAM,GAAG,MAAM,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,MAAM,SAAS,IAAI,OAAO,MAAM,SAAS,EAAE,SAAS;CAErG,OAAO,CAAC,KAAK,SAAS,KAAK,KAAK,GAAG,KAAK,WAAW,KAAK,OAAO,CAAC,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,IAAI;AAC7F"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { scanSource } from "../rules/scan.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../../packages/grimoire/src/guard/assertions.ts
|
|
4
|
+
/**
|
|
5
|
+
* Counting a test file's assertions: `expect(`, `expect.soft(`,
|
|
6
|
+
* `expect.poll(`, `assert(`, `assert.<word>(` and `.should(`. Comments and
|
|
7
|
+
* strings are skipped by the source scanner. Limit: an assertion helper
|
|
8
|
+
* of your own (`checkTotals(…)`) is not counted.
|
|
9
|
+
*/
|
|
10
|
+
const ASSERTION = /(?<![\w$.])(?:expect(?:\.(?:soft|poll))?|assert(?:\.\w+)?)\s*\(|\.should\s*\(/g;
|
|
11
|
+
/** How many assertions the text holds. */
|
|
12
|
+
function countAssertions(text) {
|
|
13
|
+
return [...scanSource(text, "code").bare.matchAll(ASSERTION)].length;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
//#endregion
|
|
17
|
+
export { countAssertions };
|
|
18
|
+
//# sourceMappingURL=assertions.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"assertions.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/guard/assertions.ts"],"sourcesContent":["/**\n * Counting a test file's assertions: `expect(`, `expect.soft(`,\n * `expect.poll(`, `assert(`, `assert.<word>(` and `.should(`. Comments and\n * strings are skipped by the source scanner. Limit: an assertion helper\n * of your own (`checkTotals(…)`) is not counted.\n */\nimport { scanSource } from \"../rules/scan\";\n\nconst ASSERTION = /(?<![\\w$.])(?:expect(?:\\.(?:soft|poll))?|assert(?:\\.\\w+)?)\\s*\\(|\\.should\\s*\\(/g;\n\n/** How many assertions the text holds. */\nexport function countAssertions(text: string): number {\n return [...scanSource(text, \"code\").bare.matchAll(ASSERTION)].length;\n}\n"],"mappings":";;;;;;;;;AAQA,MAAM,YAAY;;AAGlB,SAAgB,gBAAgB,MAAsB;CACpD,OAAO,CAAC,GAAG,WAAW,MAAM,MAAM,CAAC,CAAC,KAAK,SAAS,SAAS,CAAC,CAAC,CAAC;AAChE"}
|