@warlock.js/grimoire 5.63.1 → 5.65.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +61 -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 +42 -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 +7 -0
- package/esm/devtools/index.d.mts.map +1 -1
- package/esm/devtools/index.mjs +33 -3
- 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 +13 -3
- 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 +107 -0
- package/esm/scry/also-changes.mjs.map +1 -0
- package/esm/scry/format.d.mts.map +1 -1
- package/esm/scry/format.mjs +35 -0
- package/esm/scry/format.mjs.map +1 -1
- package/esm/scry/query.d.mts.map +1 -1
- package/esm/scry/query.mjs +40 -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 +22 -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/collect-off-thread.mjs +66 -0
- package/esm/warlock/collect-off-thread.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 +282 -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 +27 -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
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { scanShows } from "../proves/scan-shows.mjs";
|
|
2
|
+
import { computeDrift } from "./drift.mjs";
|
|
3
|
+
import { readBaseline, readCaptureIndex } from "./store.mjs";
|
|
4
|
+
|
|
5
|
+
//#region ../../packages/grimoire/src/shots/state.ts
|
|
6
|
+
/** The flows whose front matter says `screenshots: false`. */
|
|
7
|
+
function optedOutFlows(written) {
|
|
8
|
+
return written.features.flatMap((feature) => feature.flows).filter((flow) => flow.screenshots?.value === false).map((flow) => flow.ref);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Read the `@shows` lines, the capture index and the baseline, and compute the drift.
|
|
12
|
+
*
|
|
13
|
+
* @param root Absolute project root.
|
|
14
|
+
* @param testFiles Project-relative test files of the book.
|
|
15
|
+
*/
|
|
16
|
+
async function loadShotsState(root, written, settings, testFiles, proofs) {
|
|
17
|
+
const scanned = await scanShows(root, testFiles, written);
|
|
18
|
+
const [captures, baseline] = await Promise.all([readCaptureIndex(root), readBaseline(root)]);
|
|
19
|
+
const optedOut = optedOutFlows(written);
|
|
20
|
+
const showsFindings = scanned.findings;
|
|
21
|
+
return {
|
|
22
|
+
mode: settings.screenshots,
|
|
23
|
+
shows: scanned.shows,
|
|
24
|
+
showsFindings,
|
|
25
|
+
captures,
|
|
26
|
+
baseline,
|
|
27
|
+
drift: baseline === null ? [] : await computeDrift({
|
|
28
|
+
root,
|
|
29
|
+
written,
|
|
30
|
+
proofs,
|
|
31
|
+
shows: scanned.shows,
|
|
32
|
+
captures,
|
|
33
|
+
baseline,
|
|
34
|
+
languages: settings.languages,
|
|
35
|
+
optedOut
|
|
36
|
+
}),
|
|
37
|
+
optedOut
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
//#endregion
|
|
42
|
+
export { loadShotsState, optedOutFlows };
|
|
43
|
+
//# sourceMappingURL=state.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"state.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/shots/state.ts"],"sourcesContent":["/**\n * What a snapshot carries about visual proof (`GrimoireSnapshot.shots`):\n * the `@shows` lines, the captures, the approved baseline and the drift.\n */\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type { GrimoireSettings } from \"../contracts/settings\";\nimport type { ShotsState } from \"../contracts/shots\";\nimport type { ProofLine } from \"../contracts/test-results\";\nimport type { WrittenGrimoire } from \"../contracts/written\";\nimport { scanShows } from \"../proves/scan-shows\";\nimport { computeDrift } from \"./drift\";\nimport { readBaseline, readCaptureIndex } from \"./store\";\n\n/** The flows whose front matter says `screenshots: false`. */\nexport function optedOutFlows(written: WrittenGrimoire): string[] {\n return written.features\n .flatMap((feature) => feature.flows)\n .filter((flow) => flow.screenshots?.value === false)\n .map((flow) => flow.ref);\n}\n\n/**\n * Read the `@shows` lines, the capture index and the baseline, and compute the drift.\n *\n * @param root Absolute project root.\n * @param testFiles Project-relative test files of the book.\n */\nexport async function loadShotsState(\n root: string,\n written: WrittenGrimoire,\n settings: GrimoireSettings,\n testFiles: readonly string[],\n proofs: readonly ProofLine[],\n): Promise<ShotsState> {\n const scanned = await scanShows(root, testFiles, written);\n const [captures, baseline] = await Promise.all([readCaptureIndex(root), readBaseline(root)]);\n const optedOut = optedOutFlows(written);\n const showsFindings: GrimoireFinding[] = scanned.findings;\n\n return {\n mode: settings.screenshots,\n shows: scanned.shows,\n showsFindings,\n captures,\n baseline,\n drift:\n baseline === null\n ? []\n : await computeDrift({\n root,\n written,\n proofs,\n shows: scanned.shows,\n captures,\n baseline,\n languages: settings.languages,\n optedOut,\n }),\n optedOut,\n };\n}\n"],"mappings":";;;;;;AAcA,SAAgB,cAAc,SAAoC;CAChE,OAAO,QAAQ,SACZ,SAAS,YAAY,QAAQ,KAAK,CAAC,CACnC,QAAQ,SAAS,KAAK,aAAa,UAAU,KAAK,CAAC,CACnD,KAAK,SAAS,KAAK,GAAG;AAC3B;;;;;;;AAQA,eAAsB,eACpB,MACA,SACA,UACA,WACA,QACqB;CACrB,MAAM,UAAU,MAAM,UAAU,MAAM,WAAW,OAAO;CACxD,MAAM,CAAC,UAAU,YAAY,MAAM,QAAQ,IAAI,CAAC,iBAAiB,IAAI,GAAG,aAAa,IAAI,CAAC,CAAC;CAC3F,MAAM,WAAW,cAAc,OAAO;CACtC,MAAM,gBAAmC,QAAQ;CAEjD,OAAO;EACL,MAAM,SAAS;EACf,OAAO,QAAQ;EACf;EACA;EACA;EACA,OACE,aAAa,OACT,CAAC,IACD,MAAM,aAAa;GACjB;GACA;GACA;GACA,OAAO,QAAQ;GACf;GACA;GACA,WAAW,SAAS;GACpB;EACF,CAAC;EACP;CACF;AACF"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { GRIMOIRE_PATHS } from "../paths/index.mjs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
4
|
+
|
|
5
|
+
//#region ../../packages/grimoire/src/shots/store.ts
|
|
6
|
+
/**
|
|
7
|
+
* Reading and writing the two JSON files of visual proof: the capture index
|
|
8
|
+
* (`grimoire/screenshots/captured/index.json`, Warlock, ignored by git) and
|
|
9
|
+
* the approved baseline (`grimoire/approved/baseline.json`, in git, written
|
|
10
|
+
* only by approve and reject).
|
|
11
|
+
*/
|
|
12
|
+
function absolute(root, file) {
|
|
13
|
+
return path.join(root, ...file.split("/"));
|
|
14
|
+
}
|
|
15
|
+
async function readJson(file) {
|
|
16
|
+
try {
|
|
17
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
18
|
+
} catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** Write through a temporary file so a reader never sees half a file. */
|
|
23
|
+
async function writeJson(file, value) {
|
|
24
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
25
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
26
|
+
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
27
|
+
await rename(temporary, file);
|
|
28
|
+
}
|
|
29
|
+
/** The key of a capture: one scene in one language. */
|
|
30
|
+
function captureKey(ref, criterion, language) {
|
|
31
|
+
return `${ref} ${criterion} ${language}`;
|
|
32
|
+
}
|
|
33
|
+
/** The capture index, or `null` when no scene ever ran (or the file is not an index). */
|
|
34
|
+
async function readCaptureIndex(root) {
|
|
35
|
+
const index = await readJson(absolute(root, GRIMOIRE_PATHS.captureIndex));
|
|
36
|
+
return index !== null && index.schemaVersion === 1 && Array.isArray(index.captures) ? index : null;
|
|
37
|
+
}
|
|
38
|
+
async function writeCaptureIndex(root, index) {
|
|
39
|
+
await writeJson(absolute(root, GRIMOIRE_PATHS.captureIndex), index);
|
|
40
|
+
}
|
|
41
|
+
/** The index with `ran` replacing the captures of the same scene and language; every other entry is kept. */
|
|
42
|
+
function mergeCaptures(index, ran, now) {
|
|
43
|
+
const replaced = new Set(ran.map((c) => captureKey(c.ref, c.criterion, c.language)));
|
|
44
|
+
return {
|
|
45
|
+
schemaVersion: 1,
|
|
46
|
+
updatedAt: now,
|
|
47
|
+
captures: [...(index?.captures ?? []).filter((capture) => !replaced.has(captureKey(capture.ref, capture.criterion, capture.language))), ...ran].sort((left, right) => left.ref.localeCompare(right.ref) || left.criterion.localeCompare(right.criterion, "en", { numeric: true }) || left.language.localeCompare(right.language))
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** The approved baseline, or `null` before the first approval. */
|
|
51
|
+
async function readBaseline(root) {
|
|
52
|
+
const baseline = await readJson(absolute(root, GRIMOIRE_PATHS.baseline));
|
|
53
|
+
return baseline !== null && baseline.schemaVersion === 1 && Array.isArray(baseline.flows) ? {
|
|
54
|
+
...baseline,
|
|
55
|
+
proofs: baseline.proofs ?? [],
|
|
56
|
+
shots: baseline.shots ?? [],
|
|
57
|
+
rejected: baseline.rejected ?? []
|
|
58
|
+
} : null;
|
|
59
|
+
}
|
|
60
|
+
async function writeBaseline(root, baseline) {
|
|
61
|
+
await writeJson(absolute(root, GRIMOIRE_PATHS.baseline), baseline);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
//#endregion
|
|
65
|
+
export { captureKey, mergeCaptures, readBaseline, readCaptureIndex, writeBaseline, writeCaptureIndex };
|
|
66
|
+
//# sourceMappingURL=store.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/shots/store.ts"],"sourcesContent":["/**\n * Reading and writing the two JSON files of visual proof: the capture index\n * (`grimoire/screenshots/captured/index.json`, Warlock, ignored by git) and\n * the approved baseline (`grimoire/approved/baseline.json`, in git, written\n * only by approve and reject).\n */\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { ApprovedBaseline, ShotCapture, ShotCaptureIndex } from \"../contracts/shots\";\nimport { GRIMOIRE_PATHS } from \"../paths\";\n\nfunction absolute(root: string, file: string): string {\n return path.join(root, ...file.split(\"/\"));\n}\n\nasync function readJson<T>(file: string): Promise<T | null> {\n try {\n return JSON.parse(await readFile(file, \"utf8\")) as T;\n } catch {\n return null;\n }\n}\n\n/** Write through a temporary file so a reader never sees half a file. */\nasync function writeJson(file: string, value: unknown): Promise<void> {\n await mkdir(path.dirname(file), { recursive: true });\n\n const temporary = `${file}.${process.pid}.tmp`;\n\n await writeFile(temporary, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\n await rename(temporary, file);\n}\n\n/** The key of a capture: one scene in one language. */\nexport function captureKey(ref: string, criterion: string, language: string): string {\n return `${ref} ${criterion} ${language}`;\n}\n\n/** The capture index, or `null` when no scene ever ran (or the file is not an index). */\nexport async function readCaptureIndex(root: string): Promise<ShotCaptureIndex | null> {\n const index = await readJson<ShotCaptureIndex>(absolute(root, GRIMOIRE_PATHS.captureIndex));\n\n return index !== null && index.schemaVersion === 1 && Array.isArray(index.captures)\n ? index\n : null;\n}\n\nexport async function writeCaptureIndex(root: string, index: ShotCaptureIndex): Promise<void> {\n await writeJson(absolute(root, GRIMOIRE_PATHS.captureIndex), index);\n}\n\n/** The index with `ran` replacing the captures of the same scene and language; every other entry is kept. */\nexport function mergeCaptures(\n index: ShotCaptureIndex | null,\n ran: readonly ShotCapture[],\n now: string,\n): ShotCaptureIndex {\n const replaced = new Set(ran.map((c) => captureKey(c.ref, c.criterion, c.language)));\n const kept = (index?.captures ?? []).filter(\n (capture) => !replaced.has(captureKey(capture.ref, capture.criterion, capture.language)),\n );\n const captures = [...kept, ...ran].sort(\n (left, right) =>\n left.ref.localeCompare(right.ref) ||\n left.criterion.localeCompare(right.criterion, \"en\", { numeric: true }) ||\n left.language.localeCompare(right.language),\n );\n\n return { schemaVersion: 1, updatedAt: now, captures };\n}\n\n/** The approved baseline, or `null` before the first approval. */\nexport async function readBaseline(root: string): Promise<ApprovedBaseline | null> {\n const baseline = await readJson<ApprovedBaseline>(absolute(root, GRIMOIRE_PATHS.baseline));\n\n return baseline !== null && baseline.schemaVersion === 1 && Array.isArray(baseline.flows)\n ? {\n ...baseline,\n proofs: baseline.proofs ?? [],\n shots: baseline.shots ?? [],\n rejected: baseline.rejected ?? [],\n }\n : null;\n}\n\nexport async function writeBaseline(root: string, baseline: ApprovedBaseline): Promise<void> {\n await writeJson(absolute(root, GRIMOIRE_PATHS.baseline), baseline);\n}\n"],"mappings":";;;;;;;;;;;AAWA,SAAS,SAAS,MAAc,MAAsB;CACpD,OAAO,KAAK,KAAK,MAAM,GAAG,KAAK,MAAM,GAAG,CAAC;AAC3C;AAEA,eAAe,SAAY,MAAiC;CAC1D,IAAI;EACF,OAAO,KAAK,MAAM,MAAM,SAAS,MAAM,MAAM,CAAC;CAChD,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,eAAe,UAAU,MAAc,OAA+B;CACpE,MAAM,MAAM,KAAK,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAEnD,MAAM,YAAY,GAAG,KAAK,GAAG,QAAQ,IAAI;CAEzC,MAAM,UAAU,WAAW,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,EAAE,KAAK,MAAM;CACxE,MAAM,OAAO,WAAW,IAAI;AAC9B;;AAGA,SAAgB,WAAW,KAAa,WAAmB,UAA0B;CACnF,OAAO,GAAG,IAAI,GAAG,UAAU,GAAG;AAChC;;AAGA,eAAsB,iBAAiB,MAAgD;CACrF,MAAM,QAAQ,MAAM,SAA2B,SAAS,MAAM,eAAe,YAAY,CAAC;CAE1F,OAAO,UAAU,QAAQ,MAAM,kBAAkB,KAAK,MAAM,QAAQ,MAAM,QAAQ,IAC9E,QACA;AACN;AAEA,eAAsB,kBAAkB,MAAc,OAAwC;CAC5F,MAAM,UAAU,SAAS,MAAM,eAAe,YAAY,GAAG,KAAK;AACpE;;AAGA,SAAgB,cACd,OACA,KACA,KACkB;CAClB,MAAM,WAAW,IAAI,IAAI,IAAI,KAAK,MAAM,WAAW,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC;CAWnF,OAAO;EAAE,eAAe;EAAG,WAAW;EAAK,UAP1B,CAAC,IAHJ,OAAO,YAAY,CAAC,EAAC,CAAE,QAClC,YAAY,CAAC,SAAS,IAAI,WAAW,QAAQ,KAAK,QAAQ,WAAW,QAAQ,QAAQ,CAAC,CAEjE,GAAG,GAAG,GAAG,CAAC,CAAC,MAChC,MAAM,UACL,KAAK,IAAI,cAAc,MAAM,GAAG,KAChC,KAAK,UAAU,cAAc,MAAM,WAAW,MAAM,EAAE,SAAS,KAAK,CAAC,KACrE,KAAK,SAAS,cAAc,MAAM,QAAQ,CAGI;CAAE;AACtD;;AAGA,eAAsB,aAAa,MAAgD;CACjF,MAAM,WAAW,MAAM,SAA2B,SAAS,MAAM,eAAe,QAAQ,CAAC;CAEzF,OAAO,aAAa,QAAQ,SAAS,kBAAkB,KAAK,MAAM,QAAQ,SAAS,KAAK,IACpF;EACE,GAAG;EACH,QAAQ,SAAS,UAAU,CAAC;EAC5B,OAAO,SAAS,SAAS,CAAC;EAC1B,UAAU,SAAS,YAAY,CAAC;CAClC,IACA;AACN;AAEA,eAAsB,cAAc,MAAc,UAA2C;CAC3F,MAAM,UAAU,SAAS,MAAM,eAAe,QAAQ,GAAG,QAAQ;AACnE"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { changedFiles, resolveBase } from "../git/index.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../../packages/grimoire/src/shots/touched.ts
|
|
4
|
+
/**
|
|
5
|
+
* The features a change touches, for the `changed` screenshot mode: the
|
|
6
|
+
* features whose files changed against the base (by the stored ownership),
|
|
7
|
+
* and the features whose `grimoire/features/<id>/` files changed.
|
|
8
|
+
*/
|
|
9
|
+
/** An {@link OwnerLookup} over the ownership a snapshot carries. */
|
|
10
|
+
function ownersFrom(ownership) {
|
|
11
|
+
return (file) => ownership.files[file]?.owner ?? null;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The ids of the touched features, or `null` when they cannot be known (no
|
|
15
|
+
* git, no base, a git error): the caller then captures everything.
|
|
16
|
+
*/
|
|
17
|
+
async function touchedFeatures(root, owners) {
|
|
18
|
+
try {
|
|
19
|
+
const base = await resolveBase(root);
|
|
20
|
+
const files = await changedFiles(root, base);
|
|
21
|
+
const touched = /* @__PURE__ */ new Set();
|
|
22
|
+
for (const change of files) {
|
|
23
|
+
const written = /^grimoire\/features\/([^/]+)\//.exec(change.file);
|
|
24
|
+
if (written?.[1]) touched.add(written[1]);
|
|
25
|
+
for (const file of [change.file, change.from]) {
|
|
26
|
+
const owner = file === null ? null : owners(file);
|
|
27
|
+
if (owner !== null) touched.add(owner);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return touched;
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
//#endregion
|
|
37
|
+
export { ownersFrom, touchedFeatures };
|
|
38
|
+
//# sourceMappingURL=touched.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"touched.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/shots/touched.ts"],"sourcesContent":["/**\n * The features a change touches, for the `changed` screenshot mode: the\n * features whose files changed against the base (by the stored ownership),\n * and the features whose `grimoire/features/<id>/` files changed.\n */\nimport { changedFiles, resolveBase } from \"../git\";\nimport type { Ownership } from \"../contracts/bookmap\";\n\n/** The feature that owns a project file (`null` when none does). */\nexport type OwnerLookup = (file: string) => string | null;\n\n/** An {@link OwnerLookup} over the ownership a snapshot carries. */\nexport function ownersFrom(ownership: Ownership): OwnerLookup {\n return (file) => ownership.files[file]?.owner ?? null;\n}\n\n/**\n * The ids of the touched features, or `null` when they cannot be known (no\n * git, no base, a git error): the caller then captures everything.\n */\nexport async function touchedFeatures(\n root: string,\n owners: OwnerLookup,\n): Promise<Set<string> | null> {\n try {\n const base = await resolveBase(root);\n const files = await changedFiles(root, base);\n const touched = new Set<string>();\n\n for (const change of files) {\n const written = /^grimoire\\/features\\/([^/]+)\\//.exec(change.file);\n\n if (written?.[1]) touched.add(written[1]);\n\n for (const file of [change.file, change.from]) {\n const owner = file === null ? null : owners(file);\n\n if (owner !== null) touched.add(owner);\n }\n }\n\n return touched;\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;;;AAYA,SAAgB,WAAW,WAAmC;CAC5D,QAAQ,SAAS,UAAU,MAAM,KAAK,EAAE,SAAS;AACnD;;;;;AAMA,eAAsB,gBACpB,MACA,QAC6B;CAC7B,IAAI;EACF,MAAM,OAAO,MAAM,YAAY,IAAI;EACnC,MAAM,QAAQ,MAAM,aAAa,MAAM,IAAI;EAC3C,MAAM,0BAAU,IAAI,IAAY;EAEhC,KAAK,MAAM,UAAU,OAAO;GAC1B,MAAM,UAAU,iCAAiC,KAAK,OAAO,IAAI;GAEjE,IAAI,UAAU,IAAI,QAAQ,IAAI,QAAQ,EAAE;GAExC,KAAK,MAAM,QAAQ,CAAC,OAAO,MAAM,OAAO,IAAI,GAAG;IAC7C,MAAM,QAAQ,SAAS,OAAO,OAAO,OAAO,IAAI;IAEhD,IAAI,UAAU,MAAM,QAAQ,IAAI,KAAK;GACvC;EACF;EAEA,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/adapter.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"adapter.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/adapter.ts"],"mappings":";;;;;;;;;;YA2CY,kBACV,cACA,mBAAmB,qBAChB,QAAQ;;YAGD;;;;;;;;EAQV,kBAAkB;;EAElB,UAAU;;;;;;EAMV;;;YAuJU;EACV,aAAa,SAAS,mBAAmB,QAAQ;EACjD,0BAA0B;;;;;;;wBAQZ,YACd,aAAY,QAAQ,sBACnB;;wBA0Na,qBAAqB,UAAS,wBAA6B"}
|
package/esm/warlock/adapter.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { isCodeFile, isInsideFolder, toPosixPath } from "../paths/index.mjs";
|
|
2
2
|
import { WARLOCK_LOGO_DATA_URI } from "./logo.mjs";
|
|
3
|
+
import { collectOffThread } from "./collect-off-thread.mjs";
|
|
3
4
|
import { collectMobileFacts } from "./mobile-facts.mjs";
|
|
5
|
+
import { readAppLanguages } from "./languages.mjs";
|
|
4
6
|
import path from "node:path";
|
|
5
7
|
import { readdir } from "node:fs/promises";
|
|
6
8
|
import { readFileSync } from "node:fs";
|
|
@@ -255,11 +257,19 @@ const MOBILE_SKIPPED_FOLDERS = /* @__PURE__ */ new Set([
|
|
|
255
257
|
* The source folders of a mobile app: its top-level folders minus native
|
|
256
258
|
* projects and build output (`android/`, `ios/` with Pods and builds can hold
|
|
257
259
|
* hundreds of megabytes). Code files directly in the app folder (`App.tsx`)
|
|
258
|
-
* are not
|
|
260
|
+
* are not folders; {@link mobileTopFiles} lists them.
|
|
259
261
|
*/
|
|
260
262
|
async function mobileSourceFolders(root, app) {
|
|
261
263
|
return (await folderNames(path.join(root, ...app.root.split("/")))).filter((name) => !name.startsWith(".") && !MOBILE_SKIPPED_FOLDERS.has(name)).map((name) => `${app.root}/${name}`);
|
|
262
264
|
}
|
|
265
|
+
/** Code files directly in a mobile app folder (`App.tsx`, `index.ts`), without tool configs and type shims. */
|
|
266
|
+
async function mobileTopFiles(root, app) {
|
|
267
|
+
try {
|
|
268
|
+
return (await readdir(path.join(root, ...app.root.split("/")), { withFileTypes: true })).filter((entry) => entry.isFile() && !entry.name.startsWith(".") && isCodeFile(entry.name) && !entry.name.endsWith(".d.ts") && !/\.config\.[^.]+$/.test(entry.name)).map((entry) => `${app.root}/${entry.name}`).sort();
|
|
269
|
+
} catch {
|
|
270
|
+
return [];
|
|
271
|
+
}
|
|
272
|
+
}
|
|
263
273
|
/** The adapter over `inspectApp()`, `collectFiles()` and the mobile app folders. */
|
|
264
274
|
function createWarlockAdapter(options = {}) {
|
|
265
275
|
const inspect = options.inspect ?? (options.live === true ? liveInspect() : bootedInspect());
|
|
@@ -274,7 +284,16 @@ function createWarlockAdapter(options = {}) {
|
|
|
274
284
|
async function files(root) {
|
|
275
285
|
const { collectFiles } = await import("@warlock.js/core/tooling");
|
|
276
286
|
const mobile = await mobileApps(root);
|
|
277
|
-
const
|
|
287
|
+
const dirs = await sourceFolders(root, mobile);
|
|
288
|
+
const topFiles = (await Promise.all(mobile.map((app) => mobileTopFiles(root, app)))).flat();
|
|
289
|
+
const collected = (await collectOffThread({
|
|
290
|
+
root,
|
|
291
|
+
dirs,
|
|
292
|
+
files: topFiles
|
|
293
|
+
}) ?? collectFiles(root, [], {
|
|
294
|
+
dirs,
|
|
295
|
+
files: topFiles
|
|
296
|
+
})).filter((file) => isCodeFile(file.file)).map((file) => toBookFile(file, mobile));
|
|
278
297
|
lastFiles = {
|
|
279
298
|
root,
|
|
280
299
|
files: collected
|
|
@@ -315,6 +334,7 @@ function createWarlockAdapter(options = {}) {
|
|
|
315
334
|
name: "warlock",
|
|
316
335
|
version: coreVersion(),
|
|
317
336
|
host: (root) => warlockHost(root, coreVersion()),
|
|
337
|
+
languages: (root) => readAppLanguages(root),
|
|
318
338
|
async sourceRoots(root) {
|
|
319
339
|
return sourceFolders(root, await mobileApps(root));
|
|
320
340
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/adapter.ts"],"sourcesContent":["/**\n * The Warlock adapter: turns core's inspect report into the book's facts.\n * It never parses app source itself: files come from `collectFiles()`,\n * routes, events and jobs from `inspectApp()` after the `warlock inspect`\n * boot pass, pages from `inspectApp()` (the web page graph, no boot), and\n * mobile apps from their folders.\n *\n * `@warlock.js/core/tooling` is imported inside the methods, never at the\n * top: this module is reached from `warlock.config.ts`.\n */\nimport { readFileSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type {\n InspectFile,\n InspectOptions,\n InspectReport,\n InspectRoute,\n InspectSection,\n} from \"@warlock.js/core/tooling\";\nimport type {\n BookAdapter,\n BookFile,\n BookHost,\n BookMobileApp,\n BookNamedThing,\n BookPage,\n BookRoute,\n BookSite,\n} from \"../contracts/adapter\";\nimport { isCodeFile, isInsideFolder, toPosixPath } from \"../paths\";\nimport { WARLOCK_LOGO_DATA_URI } from \"./logo\";\nimport { collectMobileFacts, type MobileAppOption } from \"./mobile-facts\";\n\n/**\n * Reads the sections of the inspect report that need the app booted\n * (`routes`, `events`, `jobs`) for the project at `root`. The default boots\n * the app once, the `warlock inspect` way (connectors boot, none starts).\n * `warlock mcp` passes its own, which shares the server's boot.\n */\nexport type WarlockInspect = (\n root: string,\n sections: readonly InspectSection[],\n) => Promise<InspectReport>;\n\n/** Options of `createWarlockAdapter()`. */\nexport type WarlockAdapterOptions = {\n /**\n * Mobile apps in the repository: folder, id and routing. Default: every\n * top-level folder with an `app.json` or an `app.config.*` file; it is\n * file-routed when its `package.json` lists `expo-router` (screens come\n * from the files), and code-navigated otherwise (no screens: the agent\n * declares them in `grimoire/apps/<app>/screens/`).\n */\n mobile?: readonly MobileAppOption[];\n /** How the booted sections are read. Default: the `warlock inspect` boot pass, run at most once. Pages never boot. */\n inspect?: WarlockInspect;\n /**\n * Read the route, event and job facts from the registries of the running process instead of booting the app\n * (`inspect` wins when both are set). For code that runs inside `warlock dev`, such as the devtools panel;\n * nothing is booted and no module is loaded twice. Default `false`.\n */\n live?: boolean;\n};\n\n/** The `version` of a `package.json` named `name`, or `null` when the file is not that package's. */\nfunction versionIn(file: string, name: string): string | null {\n try {\n const manifest = JSON.parse(readFileSync(file, \"utf8\")) as {\n name?: unknown;\n version?: unknown;\n };\n\n return manifest.name === name && typeof manifest.version === \"string\" ? manifest.version : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The installed version of a package, read from its `package.json` without\n * going through its `exports` (published `@warlock.js/core` exports neither\n * `./package.json` nor a `require` condition). It resolves the package's\n * entry and walks up to the `package.json` with that name; when the entry\n * cannot be resolved, it looks in each `node_modules` above `from`.\n *\n * @param from Absolute folder to look from.\n * @param resolve Resolves a bare specifier to a file URL or path (`import.meta.resolve`).\n */\nexport function installedVersion(\n name: string,\n from: string,\n resolve: ((specifier: string) => string) | undefined,\n): string | null {\n try {\n const entry = resolve?.(name);\n\n if (entry !== undefined) {\n let folder = path.dirname(entry.startsWith(\"file:\") ? fileURLToPath(entry) : entry);\n\n for (;;) {\n const version = versionIn(path.join(folder, \"package.json\"), name);\n\n if (version !== null) return version;\n\n const parent = path.dirname(folder);\n\n if (parent === folder) break;\n\n folder = parent;\n }\n }\n } catch {\n // Not resolvable from here: look in the node_modules folders below.\n }\n\n for (let folder = from; ; folder = path.dirname(folder)) {\n const version = versionIn(\n path.join(folder, \"node_modules\", ...name.split(\"/\"), \"package.json\"),\n name,\n );\n\n if (version !== null) return version;\n if (path.dirname(folder) === folder) return null;\n }\n}\n\n/** The framework version, for the book manifest (a core upgrade rebuilds the book). */\nfunction coreVersion(): string {\n const resolve =\n typeof import.meta.resolve === \"function\"\n ? (specifier: string) => import.meta.resolve(specifier)\n : undefined;\n\n return (\n installedVersion(\"@warlock.js/core\", path.dirname(fileURLToPath(import.meta.url)), resolve) ??\n \"unknown\"\n );\n}\n\n/** The app's own `name` and `version` from `<root>/package.json`, or `null` when it has no name. */\nexport function appIdentity(root: string): { name: string; version: string | null } | null {\n try {\n const manifest = JSON.parse(readFileSync(path.join(root, \"package.json\"), \"utf8\")) as {\n name?: unknown;\n version?: unknown;\n };\n\n return typeof manifest.name === \"string\" && manifest.name !== \"\"\n ? {\n name: manifest.name,\n version: typeof manifest.version === \"string\" ? manifest.version : null,\n }\n : null;\n } catch {\n return null;\n }\n}\n\n/** The Warlock.js brand (logo and installed version) and the app at `root`, for the view's header and footer. */\nexport function warlockHost(root: string, frameworkVersion: string): BookHost {\n return {\n name: \"Warlock.js\",\n version: frameworkVersion === \"unknown\" ? null : frameworkVersion,\n logo: WARLOCK_LOGO_DATA_URI,\n app: appIdentity(root),\n };\n}\n\n/** Run `work` with `console.log`/`info`/`debug` on stderr, so a boot never mixes with `--json` output. */\nasync function withConsoleOnStderr<T>(work: () => Promise<T>): Promise<T> {\n const { log, info, debug } = console;\n const toStderr = (...args: unknown[]) => console.error(...args);\n\n console.log = toStderr;\n console.info = toStderr;\n console.debug = toStderr;\n\n try {\n return await work();\n } finally {\n console.log = log;\n console.info = info;\n console.debug = debug;\n }\n}\n\n/** The default booted `inspect`: one boot pass, shared by every call. */\nfunction bootedInspect(): WarlockInspect {\n let boot: Promise<unknown> | undefined;\n\n return async (root, sections) => {\n const tooling = await import(\"@warlock.js/core/tooling\");\n\n boot ??= withConsoleOnStderr(() => tooling.bootForInspect(root));\n\n const booted = (await boot) as Awaited<ReturnType<typeof tooling.bootForInspect>>;\n\n if (!booted.context.booted) {\n const failures = booted.context.moduleFailures.map(\n (failure) => `${failure.file}: ${failure.message}`,\n );\n\n throw new Error(\n `the app did not boot${failures.length > 0 ? ` (${failures.join(\"; \")})` : \"\"}. Run warlock doctor to see why.`,\n );\n }\n\n return tooling.inspectApp({ ...tooling.inspectOptionsFromBoot(booted), cwd: root, sections });\n };\n}\n\n/** The slice of `@warlock.js/core/tooling` that {@link liveInspect} reads (a seam for specs). */\nexport type LiveInspectTooling = {\n inspectApp: (options: InspectOptions) => Promise<InspectReport>;\n liveInspectOptions: () => InspectOptions;\n};\n\n/**\n * The `inspect` for code running inside the app's own process (`warlock dev`): reads the live router and the\n * event listeners recorded since dev start. It never boots a connector and never imports the route or event\n * modules again, so the running app is not touched.\n */\nexport function liveInspect(\n load: () => Promise<LiveInspectTooling> = () => import(\"@warlock.js/core/tooling\"),\n): WarlockInspect {\n return async (root, sections) => {\n const tooling = await load();\n\n return tooling.inspectApp({ ...tooling.liveInspectOptions(), cwd: root, sections });\n };\n}\n\n/** `send-receipt.job.ts` → `send-receipt` (the stem without the role suffix). */\nfunction stemOf(file: string, ...suffixes: string[]): string {\n const base = path.posix.basename(file).replace(/\\.(?:d\\.ts|[cm]?[jt]sx?)$/, \"\");\n\n for (const suffix of suffixes) {\n if (base.endsWith(`.${suffix}`)) return base.slice(0, -suffix.length - 1);\n }\n\n return base;\n}\n\n/**\n * The book's role of a file: the framework's role, with CLI command files\n * (`*.command.ts`, or a file directly in `<module>/commands/`) told apart from\n * plain source.\n */\nexport function bookRole(file: Pick<InspectFile, \"file\" | \"role\">): string {\n if (file.role !== \"source\") return file.role;\n\n const stem = path.posix.basename(file.file).replace(/\\.(?:d\\.ts|[cm]?[jt]sx?)$/, \"\");\n const folders = file.file.split(\"/\").slice(0, -1);\n\n return stem.endsWith(\".command\") || (folders.length === 4 && folders[3] === \"commands\")\n ? \"command\"\n : file.role;\n}\n\nfunction toBookFile(file: InspectFile, mobile: readonly BookMobileApp[]): BookFile {\n const docs = file.exportDocs ?? {};\n const app = mobile.find((item) => isInsideFolder(file.file, item.root));\n\n return {\n file: file.file,\n module: file.module,\n type: bookRole(file),\n lines: file.lines ?? 0,\n about: file.about ?? null,\n tags: file.tags ?? {},\n exports: file.exports.map((name) => ({ name, about: docs[name] ?? null })),\n imports: file.imports.map((entry) =>\n entry.typeOnly === true\n ? { specifier: entry.specifier, file: entry.file, typeOnly: true }\n : { specifier: entry.specifier, file: entry.file },\n ),\n importedBy: [...file.importedBy],\n mobileApp: app?.id ?? null,\n };\n}\n\n/** Files by the names they export, built once per `routes()` call. */\ntype ExportIndex = () => ReadonlyMap<string, readonly string[]>;\n\nfunction exportIndex(files: ReadonlyMap<string, BookFile>): ExportIndex {\n let index: Map<string, string[]> | undefined;\n\n return () => {\n if (index) return index;\n\n index = new Map();\n\n for (const file of files.values()) {\n for (const entry of file.exports) {\n const list = index.get(entry.name) ?? [];\n\n list.push(file.file);\n index.set(entry.name, list);\n }\n }\n\n return index;\n };\n}\n\n/** The file that defines a route's handler: the controller's file for a tuple, else the file exporting the handler. */\nfunction handlerFileOf(\n route: InspectRoute,\n files: ReadonlyMap<string, BookFile>,\n pages: readonly BookPage[],\n exporters: ExportIndex,\n): string | null {\n if (route.isPage) {\n return pages.find((page) => page.route === route.path)?.file ?? null;\n }\n\n const exportsName = (file: string | null | undefined, name: string): boolean =>\n file !== null &&\n file !== undefined &&\n files.get(file)?.exports.some((entry) => entry.name === name) === true;\n const imported =\n route.sourceFile === null\n ? []\n : (files.get(route.sourceFile)?.imports ?? []).map((entry) => entry.file);\n const name = route.controller ?? route.handler;\n\n if (!name || name === \"anonymous\") return null;\n\n const fromImports = imported.find((file) => exportsName(file, name));\n\n if (fromImports) return fromImports;\n if (exportsName(route.sourceFile, name)) return route.sourceFile;\n\n // Not imported by the routes file: the one file in the project exporting it, when there is only one.\n const anywhere = [...new Set(exporters().get(name) ?? [])];\n\n return anywhere.length === 1 ? (anywhere[0] ?? null) : null;\n}\n\nfunction toBookRoute(\n route: InspectRoute,\n files: ReadonlyMap<string, BookFile>,\n pages: readonly BookPage[],\n exporters: ExportIndex,\n): BookRoute {\n const controller = route.controller ?? null;\n const action = route.action ?? null;\n const handler =\n controller !== null && action !== null && !route.handler.includes(\".\")\n ? `${controller}.${action}`\n : route.handler;\n\n return {\n method: route.method.toUpperCase(),\n path: route.path,\n name: route.name,\n sourceFile: route.sourceFile === null ? null : toPosixPath(route.sourceFile),\n handler,\n controller,\n action,\n handlerFile: handlerFileOf(route, files, pages, exporters),\n middleware: [...route.middleware],\n auth: { required: route.auth.required, userTypes: [...route.auth.userTypes] },\n isPage: route.isPage,\n description: route.description,\n };\n}\n\nasync function folderNames(dir: string): Promise<string[]> {\n try {\n return (await readdir(dir, { withFileTypes: true }))\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n } catch {\n return [];\n }\n}\n\n/** The site folders of a multi-site app (`src/web/$sites/<id>`), sorted; empty for a single site. */\nfunction siteFolders(root: string): Promise<string[]> {\n return folderNames(path.join(root, \"src\", \"web\", \"$sites\"));\n}\n\n/** `web.sites` from the loaded config, or `undefined` when `src/config/web.ts` is not loaded. */\nasync function webSitesConfig(): Promise<\n Record<string, { basePath?: unknown } | undefined> | undefined\n> {\n const { config } = await import(\"@warlock.js/core\");\n const sites: unknown = config.key(\"web.sites\");\n\n return typeof sites === \"object\" && sites !== null\n ? (sites as Record<string, { basePath?: unknown }>)\n : undefined;\n}\n\n/**\n * Folders of a mobile app that hold native projects, build output or tool\n * caches, never app source. `node_modules` and dot folders are skipped too.\n */\nconst MOBILE_SKIPPED_FOLDERS = new Set([\n \"android\",\n \"ios\",\n \"build\",\n \"dist\",\n \"web-build\",\n \"coverage\",\n \"node_modules\",\n]);\n\n/**\n * The source folders of a mobile app: its top-level folders minus native\n * projects and build output (`android/`, `ios/` with Pods and builds can hold\n * hundreds of megabytes). Code files directly in the app folder (`App.tsx`)\n * are not read: `collectFiles` scans folders only.\n */\nasync function mobileSourceFolders(root: string, app: BookMobileApp): Promise<string[]> {\n return (await folderNames(path.join(root, ...app.root.split(\"/\"))))\n .filter((name) => !name.startsWith(\".\") && !MOBILE_SKIPPED_FOLDERS.has(name))\n .map((name) => `${app.root}/${name}`);\n}\n\n/** The adapter over `inspectApp()`, `collectFiles()` and the mobile app folders. */\nexport function createWarlockAdapter(options: WarlockAdapterOptions = {}): BookAdapter {\n const inspect = options.inspect ?? (options.live === true ? liveInspect() : bootedInspect());\n const mobileOptions = options.mobile === undefined ? {} : { mobile: options.mobile };\n let lastFiles: { root: string; files: BookFile[] } | null = null;\n let lastPages: { root: string; pages: BookPage[] } | null = null;\n\n const mobileApps = (root: string) => collectMobileFacts(root, mobileOptions);\n\n /** `src` and each mobile app's source folders: what `files()` reads and the book fingerprints. */\n async function sourceFolders(root: string, mobile: readonly BookMobileApp[]): Promise<string[]> {\n const folders = await Promise.all(mobile.map((app) => mobileSourceFolders(root, app)));\n\n return [\"src\", ...folders.flat()];\n }\n\n async function files(root: string): Promise<BookFile[]> {\n const { collectFiles } = await import(\"@warlock.js/core/tooling\");\n const mobile = await mobileApps(root);\n const dirs = await sourceFolders(root, mobile);\n const collected = collectFiles(root, [], { dirs })\n .filter((file) => isCodeFile(file.file))\n .map((file) => toBookFile(file, mobile));\n\n lastFiles = { root, files: collected };\n\n return collected;\n }\n\n /** File facts for the routes: the last `files()` answer, else the book's cache, else a new scan. */\n async function currentFiles(root: string): Promise<BookFile[]> {\n if (lastFiles?.root === root) return lastFiles.files;\n\n const { loadBook } = await import(\"../book\");\n const book = await loadBook(root);\n\n return book?.facts.files ?? files(root);\n }\n\n async function pages(root: string): Promise<BookPage[]> {\n // A multi-site app's routes depend on `web.sites` (base paths), which only `src/config/web.ts` holds.\n if ((await siteFolders(root)).length > 0 && (await webSitesConfig()) === undefined) {\n throw new Error(\n \"This app has several sites (src/web/$sites), and their page routes need src/config/web.ts, which is not loaded. Run the command through the warlock CLI, which loads it.\",\n );\n }\n\n // Pages come from the web page graph: files only, never a boot.\n const { inspectApp } = await import(\"@warlock.js/core/tooling\");\n const report = await inspectApp({ cwd: root, sections: [\"pages\"] });\n const found = (report.pages ?? []).map((page): BookPage => ({\n site: page.site ?? \"default\",\n route: page.path,\n name: page.name,\n file: toPosixPath(page.file),\n setupFile: page.setupFile === null ? null : toPosixPath(page.setupFile),\n layouts: page.layouts.map(toPosixPath),\n loaders: page.loaders.map(toPosixPath),\n actions: [...page.actions],\n requires: page.guard === null ? [] : [page.guard],\n reachedFrom: null,\n }));\n\n lastPages = { root, pages: found };\n\n return found;\n }\n\n return {\n name: \"warlock\",\n version: coreVersion(),\n host: (root) => warlockHost(root, coreVersion()),\n async sourceRoots(root) {\n return sourceFolders(root, await mobileApps(root));\n },\n files,\n async routes(root) {\n const report = await inspect(root, [\"routes\"]);\n const known = new Map((await currentFiles(root)).map((file) => [file.file, file]));\n // Pages only name the file of a page route; a page problem is reported by `pages()` itself.\n const sitePages =\n lastPages?.root === root ? lastPages.pages : await pages(root).catch(() => []);\n\n const exporters = exportIndex(known);\n\n return (report.routes ?? []).map((route) => toBookRoute(route, known, sitePages, exporters));\n },\n async named(root) {\n const report = await inspect(root, [\"events\", \"jobs\", \"schedules\"]);\n const known = await currentFiles(root);\n const ofType = (type: string) => known.filter((file) => file.type === type);\n const named: BookNamedThing[] = [];\n\n // `*.mail.ts`, `*.email.ts` and the files of a `mails/` or `emails/` folder are all typed as mails.\n for (const file of ofType(\"mail\")) {\n named.push({\n type: \"mail\",\n name: stemOf(file.file, \"mail\", \"email\"),\n file: file.file,\n });\n }\n\n const jobFiles = ofType(\"job\");\n const jobFileOf = (name: string): string | null =>\n jobFiles.find((item) => {\n const stem = stemOf(item.file, \"job\");\n\n return name === stem || name.endsWith(`.${stem}`) || name.endsWith(`/${stem}`);\n })?.file ?? null;\n const seen = new Set<string>();\n\n // Queue jobs (`defineJob()`) and scheduled tasks are both jobs a flow can name.\n for (const name of [\n ...(report.jobs ?? []).map((job) => job.name),\n ...(report.schedules ?? []).map((schedule) => schedule.name),\n ]) {\n if (seen.has(name)) continue;\n\n seen.add(name);\n named.push({ type: \"job\", name, file: jobFileOf(name) });\n }\n\n // A job file the registries do not list is still a job by its file name.\n for (const file of jobFiles) {\n const name = stemOf(file.file, \"job\");\n\n if (seen.has(name) || [...seen].some((item) => jobFileOf(item) === file.file)) continue;\n\n seen.add(name);\n named.push({ type: \"job\", name, file: file.file });\n }\n\n for (const event of report.events ?? []) {\n const source = event.listeners[0]?.sourceFile;\n\n named.push({\n type: \"event\",\n name: event.event,\n file: source === undefined ? null : toPosixPath(source),\n });\n }\n\n for (const file of known) {\n if (/\\.notification\\.[cm]?[jt]sx?$/.test(file.file)) {\n named.push({\n type: \"notification\",\n name: stemOf(file.file, \"notification\"),\n file: file.file,\n });\n }\n }\n\n return named;\n },\n async sites(root): Promise<BookSite[]> {\n const multi = await siteFolders(root);\n\n if (multi.length > 0) {\n const configured = await webSitesConfig();\n\n return multi.map((id) => {\n const basePath: unknown = configured?.[id]?.basePath;\n\n return {\n id,\n root: `src/web/$sites/${id}`,\n basePath: typeof basePath === \"string\" ? basePath : null,\n };\n });\n }\n\n return (await folderNames(path.join(root, \"src\"))).includes(\"web\")\n ? [{ id: \"default\", root: \"src/web\", basePath: null }]\n : [];\n },\n pages,\n mobile: mobileApps,\n async tests(root) {\n const known = await currentFiles(root);\n const specs = known.filter((file) => file.type === \"spec\").map((file) => file.file);\n const outside: string[] = [];\n\n const walk = async (dir: string, pattern: RegExp): Promise<void> => {\n let entries;\n\n try {\n entries = await readdir(path.join(root, dir), { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n\n const relative = `${dir}/${entry.name}`;\n\n if (entry.isDirectory()) await walk(relative, pattern);\n else if (entry.isFile() && pattern.test(entry.name)) outside.push(relative);\n }\n };\n\n await walk(\"e2e\", /\\.e2e\\.(?:ts|mts|js|mjs)$/);\n await walk(\"tests\", /\\.(?:test|spec)\\.ts$/);\n\n return [...new Set([...specs, ...outside])].sort();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAmEA,SAAS,UAAU,MAAc,MAA6B;CAC5D,IAAI;EACF,MAAM,WAAW,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;EAKtD,OAAO,SAAS,SAAS,QAAQ,OAAO,SAAS,YAAY,WAAW,SAAS,UAAU;CAC7F,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;AAYA,SAAgB,iBACd,MACA,MACA,SACe;CACf,IAAI;EACF,MAAM,QAAQ,UAAU,IAAI;EAE5B,IAAI,UAAU,QAAW;GACvB,IAAI,SAAS,KAAK,QAAQ,MAAM,WAAW,OAAO,IAAI,cAAc,KAAK,IAAI,KAAK;GAElF,SAAS;IACP,MAAM,UAAU,UAAU,KAAK,KAAK,QAAQ,cAAc,GAAG,IAAI;IAEjE,IAAI,YAAY,MAAM,OAAO;IAE7B,MAAM,SAAS,KAAK,QAA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;EACA;EACA,QAAQ;EACR,MAAM,MAAM,MAAM;GAEhB,MAAM,SAAQ,MADM,aAAa,IAAI,EAClB,CAAC,QAAQ,SAAS,KAAK,SAAS,MAAM,CAAC,CAAC,KAAK,SAAS,KAAK,IAAI;GAClF,MAAM,UAAoB,CAAC;GAE3B,MAAM,OAAO,OAAO,KAAa,YAAmC;IAClE,IAAI;IAEJ,IAAI;KACF,UAAU,MAAM,QAAQ,KAAK,KAAK,MAAM,GAAG,GAAG,EAAE,eAAe,KAAK,CAAC;IACvE,QAAQ;KACN;IACF;IAEA,KAAK,MAAM,SAAS,SAAS;KAC3B,IAAI,MAAM,SAAS,kBAAkB,MAAM,KAAK,WAAW,GAAG,GAAG;KAEjE,MAAM,WAAW,GAAG,IAAI,GAAG,MAAM;KAEjC,IAAI,MAAM,YAAY,GAAG,MAAM,KAAK,UAAU,OAAO;UAChD,IAAI,MAAM,OAAO,KAAK,QAAQ,KAAK,MAAM,IAAI,GAAG,QAAQ,KAAK,QAAQ;IAC5E;GACF;GAEA,MAAM,KAAK,OAAO,2BAA2B;GAC7C,MAAM,KAAK,SAAS,sBAAsB;GAE1C,OAAO,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAG,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK;EACnD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"adapter.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/adapter.ts"],"sourcesContent":["/**\n * The Warlock adapter: turns core's inspect report into the book's facts.\n * It never parses app source itself: files come from `collectFiles()`,\n * routes, events and jobs from `inspectApp()` after the `warlock inspect`\n * boot pass, pages from `inspectApp()` (the web page graph, no boot), and\n * mobile apps from their folders.\n *\n * `@warlock.js/core/tooling` is imported inside the methods, never at the\n * top: this module is reached from `warlock.config.ts`.\n */\nimport { readFileSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type {\n InspectFile,\n InspectOptions,\n InspectReport,\n InspectRoute,\n InspectSection,\n} from \"@warlock.js/core/tooling\";\nimport type {\n BookAdapter,\n BookFile,\n BookHost,\n BookMobileApp,\n BookNamedThing,\n BookPage,\n BookRoute,\n BookSite,\n} from \"../contracts/adapter\";\nimport { isCodeFile, isInsideFolder, toPosixPath } from \"../paths\";\nimport { WARLOCK_LOGO_DATA_URI } from \"./logo\";\nimport { collectOffThread } from \"./collect-off-thread\";\nimport { collectMobileFacts, type MobileAppOption } from \"./mobile-facts\";\nimport { readAppLanguages } from \"./languages\";\n\n/**\n * Reads the sections of the inspect report that need the app booted\n * (`routes`, `events`, `jobs`) for the project at `root`. The default boots\n * the app once, the `warlock inspect` way (connectors boot, none starts).\n * `warlock mcp` passes its own, which shares the server's boot.\n */\nexport type WarlockInspect = (\n root: string,\n sections: readonly InspectSection[],\n) => Promise<InspectReport>;\n\n/** Options of `createWarlockAdapter()`. */\nexport type WarlockAdapterOptions = {\n /**\n * Mobile apps in the repository: folder, id and routing. Default: every\n * top-level folder with an `app.json` or an `app.config.*` file; it is\n * file-routed when its `package.json` lists `expo-router` (screens come\n * from the files), and code-navigated otherwise (no screens: the agent\n * declares them in `grimoire/apps/<app>/screens/`).\n */\n mobile?: readonly MobileAppOption[];\n /** How the booted sections are read. Default: the `warlock inspect` boot pass, run at most once. Pages never boot. */\n inspect?: WarlockInspect;\n /**\n * Read the route, event and job facts from the registries of the running process instead of booting the app\n * (`inspect` wins when both are set). For code that runs inside `warlock dev`, such as the devtools panel;\n * nothing is booted and no module is loaded twice. Default `false`.\n */\n live?: boolean;\n};\n\n/** The `version` of a `package.json` named `name`, or `null` when the file is not that package's. */\nfunction versionIn(file: string, name: string): string | null {\n try {\n const manifest = JSON.parse(readFileSync(file, \"utf8\")) as {\n name?: unknown;\n version?: unknown;\n };\n\n return manifest.name === name && typeof manifest.version === \"string\" ? manifest.version : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The installed version of a package, read from its `package.json` without\n * going through its `exports` (published `@warlock.js/core` exports neither\n * `./package.json` nor a `require` condition). It resolves the package's\n * entry and walks up to the `package.json` with that name; when the entry\n * cannot be resolved, it looks in each `node_modules` above `from`.\n *\n * @param from Absolute folder to look from.\n * @param resolve Resolves a bare specifier to a file URL or path (`import.meta.resolve`).\n */\nexport function installedVersion(\n name: string,\n from: string,\n resolve: ((specifier: string) => string) | undefined,\n): string | null {\n try {\n const entry = resolve?.(name);\n\n if (entry !== undefined) {\n let folder = path.dirname(entry.startsWith(\"file:\") ? fileURLToPath(entry) : entry);\n\n for (;;) {\n const version = versionIn(path.join(folder, \"package.json\"), name);\n\n if (version !== null) return version;\n\n const parent = path.dirname(folder);\n\n if (parent === folder) break;\n\n folder = parent;\n }\n }\n } catch {\n // Not resolvable from here: look in the node_modules folders below.\n }\n\n for (let folder = from; ; folder = path.dirname(folder)) {\n const version = versionIn(\n path.join(folder, \"node_modules\", ...name.split(\"/\"), \"package.json\"),\n name,\n );\n\n if (version !== null) return version;\n if (path.dirname(folder) === folder) return null;\n }\n}\n\n/** The framework version, for the book manifest (a core upgrade rebuilds the book). */\nfunction coreVersion(): string {\n const resolve =\n typeof import.meta.resolve === \"function\"\n ? (specifier: string) => import.meta.resolve(specifier)\n : undefined;\n\n return (\n installedVersion(\"@warlock.js/core\", path.dirname(fileURLToPath(import.meta.url)), resolve) ??\n \"unknown\"\n );\n}\n\n/** The app's own `name` and `version` from `<root>/package.json`, or `null` when it has no name. */\nexport function appIdentity(root: string): { name: string; version: string | null } | null {\n try {\n const manifest = JSON.parse(readFileSync(path.join(root, \"package.json\"), \"utf8\")) as {\n name?: unknown;\n version?: unknown;\n };\n\n return typeof manifest.name === \"string\" && manifest.name !== \"\"\n ? {\n name: manifest.name,\n version: typeof manifest.version === \"string\" ? manifest.version : null,\n }\n : null;\n } catch {\n return null;\n }\n}\n\n/** The Warlock.js brand (logo and installed version) and the app at `root`, for the view's header and footer. */\nexport function warlockHost(root: string, frameworkVersion: string): BookHost {\n return {\n name: \"Warlock.js\",\n version: frameworkVersion === \"unknown\" ? null : frameworkVersion,\n logo: WARLOCK_LOGO_DATA_URI,\n app: appIdentity(root),\n };\n}\n\n/** Run `work` with `console.log`/`info`/`debug` on stderr, so a boot never mixes with `--json` output. */\nasync function withConsoleOnStderr<T>(work: () => Promise<T>): Promise<T> {\n const { log, info, debug } = console;\n const toStderr = (...args: unknown[]) => console.error(...args);\n\n console.log = toStderr;\n console.info = toStderr;\n console.debug = toStderr;\n\n try {\n return await work();\n } finally {\n console.log = log;\n console.info = info;\n console.debug = debug;\n }\n}\n\n/** The default booted `inspect`: one boot pass, shared by every call. */\nfunction bootedInspect(): WarlockInspect {\n let boot: Promise<unknown> | undefined;\n\n return async (root, sections) => {\n const tooling = await import(\"@warlock.js/core/tooling\");\n\n boot ??= withConsoleOnStderr(() => tooling.bootForInspect(root));\n\n const booted = (await boot) as Awaited<ReturnType<typeof tooling.bootForInspect>>;\n\n if (!booted.context.booted) {\n const failures = booted.context.moduleFailures.map(\n (failure) => `${failure.file}: ${failure.message}`,\n );\n\n throw new Error(\n `the app did not boot${failures.length > 0 ? ` (${failures.join(\"; \")})` : \"\"}. Run warlock doctor to see why.`,\n );\n }\n\n return tooling.inspectApp({ ...tooling.inspectOptionsFromBoot(booted), cwd: root, sections });\n };\n}\n\n/** The slice of `@warlock.js/core/tooling` that {@link liveInspect} reads (a seam for specs). */\nexport type LiveInspectTooling = {\n inspectApp: (options: InspectOptions) => Promise<InspectReport>;\n liveInspectOptions: () => InspectOptions;\n};\n\n/**\n * The `inspect` for code running inside the app's own process (`warlock dev`): reads the live router and the\n * event listeners recorded since dev start. It never boots a connector and never imports the route or event\n * modules again, so the running app is not touched.\n */\nexport function liveInspect(\n load: () => Promise<LiveInspectTooling> = () => import(\"@warlock.js/core/tooling\"),\n): WarlockInspect {\n return async (root, sections) => {\n const tooling = await load();\n\n return tooling.inspectApp({ ...tooling.liveInspectOptions(), cwd: root, sections });\n };\n}\n\n/** `send-receipt.job.ts` → `send-receipt` (the stem without the role suffix). */\nfunction stemOf(file: string, ...suffixes: string[]): string {\n const base = path.posix.basename(file).replace(/\\.(?:d\\.ts|[cm]?[jt]sx?)$/, \"\");\n\n for (const suffix of suffixes) {\n if (base.endsWith(`.${suffix}`)) return base.slice(0, -suffix.length - 1);\n }\n\n return base;\n}\n\n/**\n * The book's role of a file: the framework's role, with CLI command files\n * (`*.command.ts`, or a file directly in `<module>/commands/`) told apart from\n * plain source.\n */\nexport function bookRole(file: Pick<InspectFile, \"file\" | \"role\">): string {\n if (file.role !== \"source\") return file.role;\n\n const stem = path.posix.basename(file.file).replace(/\\.(?:d\\.ts|[cm]?[jt]sx?)$/, \"\");\n const folders = file.file.split(\"/\").slice(0, -1);\n\n return stem.endsWith(\".command\") || (folders.length === 4 && folders[3] === \"commands\")\n ? \"command\"\n : file.role;\n}\n\nfunction toBookFile(file: InspectFile, mobile: readonly BookMobileApp[]): BookFile {\n const docs = file.exportDocs ?? {};\n const app = mobile.find((item) => isInsideFolder(file.file, item.root));\n\n return {\n file: file.file,\n module: file.module,\n type: bookRole(file),\n lines: file.lines ?? 0,\n about: file.about ?? null,\n tags: file.tags ?? {},\n exports: file.exports.map((name) => ({ name, about: docs[name] ?? null })),\n imports: file.imports.map((entry) =>\n entry.typeOnly === true\n ? { specifier: entry.specifier, file: entry.file, typeOnly: true }\n : { specifier: entry.specifier, file: entry.file },\n ),\n importedBy: [...file.importedBy],\n mobileApp: app?.id ?? null,\n };\n}\n\n/** Files by the names they export, built once per `routes()` call. */\ntype ExportIndex = () => ReadonlyMap<string, readonly string[]>;\n\nfunction exportIndex(files: ReadonlyMap<string, BookFile>): ExportIndex {\n let index: Map<string, string[]> | undefined;\n\n return () => {\n if (index) return index;\n\n index = new Map();\n\n for (const file of files.values()) {\n for (const entry of file.exports) {\n const list = index.get(entry.name) ?? [];\n\n list.push(file.file);\n index.set(entry.name, list);\n }\n }\n\n return index;\n };\n}\n\n/** The file that defines a route's handler: the controller's file for a tuple, else the file exporting the handler. */\nfunction handlerFileOf(\n route: InspectRoute,\n files: ReadonlyMap<string, BookFile>,\n pages: readonly BookPage[],\n exporters: ExportIndex,\n): string | null {\n if (route.isPage) {\n return pages.find((page) => page.route === route.path)?.file ?? null;\n }\n\n const exportsName = (file: string | null | undefined, name: string): boolean =>\n file !== null &&\n file !== undefined &&\n files.get(file)?.exports.some((entry) => entry.name === name) === true;\n const imported =\n route.sourceFile === null\n ? []\n : (files.get(route.sourceFile)?.imports ?? []).map((entry) => entry.file);\n const name = route.controller ?? route.handler;\n\n if (!name || name === \"anonymous\") return null;\n\n const fromImports = imported.find((file) => exportsName(file, name));\n\n if (fromImports) return fromImports;\n if (exportsName(route.sourceFile, name)) return route.sourceFile;\n\n // Not imported by the routes file: the one file in the project exporting it, when there is only one.\n const anywhere = [...new Set(exporters().get(name) ?? [])];\n\n return anywhere.length === 1 ? (anywhere[0] ?? null) : null;\n}\n\nfunction toBookRoute(\n route: InspectRoute,\n files: ReadonlyMap<string, BookFile>,\n pages: readonly BookPage[],\n exporters: ExportIndex,\n): BookRoute {\n const controller = route.controller ?? null;\n const action = route.action ?? null;\n const handler =\n controller !== null && action !== null && !route.handler.includes(\".\")\n ? `${controller}.${action}`\n : route.handler;\n\n return {\n method: route.method.toUpperCase(),\n path: route.path,\n name: route.name,\n sourceFile: route.sourceFile === null ? null : toPosixPath(route.sourceFile),\n handler,\n controller,\n action,\n handlerFile: handlerFileOf(route, files, pages, exporters),\n middleware: [...route.middleware],\n auth: { required: route.auth.required, userTypes: [...route.auth.userTypes] },\n isPage: route.isPage,\n description: route.description,\n };\n}\n\nasync function folderNames(dir: string): Promise<string[]> {\n try {\n return (await readdir(dir, { withFileTypes: true }))\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n } catch {\n return [];\n }\n}\n\n/** The site folders of a multi-site app (`src/web/$sites/<id>`), sorted; empty for a single site. */\nfunction siteFolders(root: string): Promise<string[]> {\n return folderNames(path.join(root, \"src\", \"web\", \"$sites\"));\n}\n\n/** `web.sites` from the loaded config, or `undefined` when `src/config/web.ts` is not loaded. */\nasync function webSitesConfig(): Promise<\n Record<string, { basePath?: unknown } | undefined> | undefined\n> {\n const { config } = await import(\"@warlock.js/core\");\n const sites: unknown = config.key(\"web.sites\");\n\n return typeof sites === \"object\" && sites !== null\n ? (sites as Record<string, { basePath?: unknown }>)\n : undefined;\n}\n\n/**\n * Folders of a mobile app that hold native projects, build output or tool\n * caches, never app source. `node_modules` and dot folders are skipped too.\n */\nconst MOBILE_SKIPPED_FOLDERS = new Set([\n \"android\",\n \"ios\",\n \"build\",\n \"dist\",\n \"web-build\",\n \"coverage\",\n \"node_modules\",\n]);\n\n/**\n * The source folders of a mobile app: its top-level folders minus native\n * projects and build output (`android/`, `ios/` with Pods and builds can hold\n * hundreds of megabytes). Code files directly in the app folder (`App.tsx`)\n * are not folders; {@link mobileTopFiles} lists them.\n */\nasync function mobileSourceFolders(root: string, app: BookMobileApp): Promise<string[]> {\n return (await folderNames(path.join(root, ...app.root.split(\"/\"))))\n .filter((name) => !name.startsWith(\".\") && !MOBILE_SKIPPED_FOLDERS.has(name))\n .map((name) => `${app.root}/${name}`);\n}\n\n/** Code files directly in a mobile app folder (`App.tsx`, `index.ts`), without tool configs and type shims. */\nasync function mobileTopFiles(root: string, app: BookMobileApp): Promise<string[]> {\n try {\n return (await readdir(path.join(root, ...app.root.split(\"/\")), { withFileTypes: true }))\n .filter(\n (entry) =>\n entry.isFile() &&\n !entry.name.startsWith(\".\") &&\n isCodeFile(entry.name) &&\n !entry.name.endsWith(\".d.ts\") &&\n !/\\.config\\.[^.]+$/.test(entry.name),\n )\n .map((entry) => `${app.root}/${entry.name}`)\n .sort();\n } catch {\n return [];\n }\n}\n\n/** The adapter over `inspectApp()`, `collectFiles()` and the mobile app folders. */\nexport function createWarlockAdapter(options: WarlockAdapterOptions = {}): BookAdapter {\n const inspect = options.inspect ?? (options.live === true ? liveInspect() : bootedInspect());\n const mobileOptions = options.mobile === undefined ? {} : { mobile: options.mobile };\n let lastFiles: { root: string; files: BookFile[] } | null = null;\n let lastPages: { root: string; pages: BookPage[] } | null = null;\n\n const mobileApps = (root: string) => collectMobileFacts(root, mobileOptions);\n\n /** `src` and each mobile app's source folders: what `files()` reads and the book fingerprints. */\n async function sourceFolders(root: string, mobile: readonly BookMobileApp[]): Promise<string[]> {\n const folders = await Promise.all(mobile.map((app) => mobileSourceFolders(root, app)));\n\n return [\"src\", ...folders.flat()];\n }\n\n async function files(root: string): Promise<BookFile[]> {\n const { collectFiles } = await import(\"@warlock.js/core/tooling\");\n const mobile = await mobileApps(root);\n const dirs = await sourceFolders(root, mobile);\n const topFiles = (await Promise.all(mobile.map((app) => mobileTopFiles(root, app)))).flat();\n // The scan runs in a worker thread when it can, so a large app's scan never blocks the event loop.\n const scanned =\n (await collectOffThread<InspectFile>({ root, dirs, files: topFiles })) ??\n collectFiles(root, [], { dirs, files: topFiles });\n const collected = scanned\n .filter((file) => isCodeFile(file.file))\n .map((file) => toBookFile(file, mobile));\n\n lastFiles = { root, files: collected };\n\n return collected;\n }\n\n /** File facts for the routes: the last `files()` answer, else the book's cache, else a new scan. */\n async function currentFiles(root: string): Promise<BookFile[]> {\n if (lastFiles?.root === root) return lastFiles.files;\n\n const { loadBook } = await import(\"../book\");\n const book = await loadBook(root);\n\n return book?.facts.files ?? files(root);\n }\n\n async function pages(root: string): Promise<BookPage[]> {\n // A multi-site app's routes depend on `web.sites` (base paths), which only `src/config/web.ts` holds.\n if ((await siteFolders(root)).length > 0 && (await webSitesConfig()) === undefined) {\n throw new Error(\n \"This app has several sites (src/web/$sites), and their page routes need src/config/web.ts, which is not loaded. Run the command through the warlock CLI, which loads it.\",\n );\n }\n\n // Pages come from the web page graph: files only, never a boot.\n const { inspectApp } = await import(\"@warlock.js/core/tooling\");\n const report = await inspectApp({ cwd: root, sections: [\"pages\"] });\n const found = (report.pages ?? []).map((page): BookPage => ({\n site: page.site ?? \"default\",\n route: page.path,\n name: page.name,\n file: toPosixPath(page.file),\n setupFile: page.setupFile === null ? null : toPosixPath(page.setupFile),\n layouts: page.layouts.map(toPosixPath),\n loaders: page.loaders.map(toPosixPath),\n actions: [...page.actions],\n requires: page.guard === null ? [] : [page.guard],\n reachedFrom: null,\n }));\n\n lastPages = { root, pages: found };\n\n return found;\n }\n\n return {\n name: \"warlock\",\n version: coreVersion(),\n host: (root) => warlockHost(root, coreVersion()),\n languages: (root) => readAppLanguages(root),\n async sourceRoots(root) {\n return sourceFolders(root, await mobileApps(root));\n },\n files,\n async routes(root) {\n const report = await inspect(root, [\"routes\"]);\n const known = new Map((await currentFiles(root)).map((file) => [file.file, file]));\n // Pages only name the file of a page route; a page problem is reported by `pages()` itself.\n const sitePages =\n lastPages?.root === root ? lastPages.pages : await pages(root).catch(() => []);\n\n const exporters = exportIndex(known);\n\n return (report.routes ?? []).map((route) => toBookRoute(route, known, sitePages, exporters));\n },\n async named(root) {\n const report = await inspect(root, [\"events\", \"jobs\", \"schedules\"]);\n const known = await currentFiles(root);\n const ofType = (type: string) => known.filter((file) => file.type === type);\n const named: BookNamedThing[] = [];\n\n // `*.mail.ts`, `*.email.ts` and the files of a `mails/` or `emails/` folder are all typed as mails.\n for (const file of ofType(\"mail\")) {\n named.push({\n type: \"mail\",\n name: stemOf(file.file, \"mail\", \"email\"),\n file: file.file,\n });\n }\n\n const jobFiles = ofType(\"job\");\n const jobFileOf = (name: string): string | null =>\n jobFiles.find((item) => {\n const stem = stemOf(item.file, \"job\");\n\n return name === stem || name.endsWith(`.${stem}`) || name.endsWith(`/${stem}`);\n })?.file ?? null;\n const seen = new Set<string>();\n\n // Queue jobs (`defineJob()`) and scheduled tasks are both jobs a flow can name.\n for (const name of [\n ...(report.jobs ?? []).map((job) => job.name),\n ...(report.schedules ?? []).map((schedule) => schedule.name),\n ]) {\n if (seen.has(name)) continue;\n\n seen.add(name);\n named.push({ type: \"job\", name, file: jobFileOf(name) });\n }\n\n // A job file the registries do not list is still a job by its file name.\n for (const file of jobFiles) {\n const name = stemOf(file.file, \"job\");\n\n if (seen.has(name) || [...seen].some((item) => jobFileOf(item) === file.file)) continue;\n\n seen.add(name);\n named.push({ type: \"job\", name, file: file.file });\n }\n\n for (const event of report.events ?? []) {\n const source = event.listeners[0]?.sourceFile;\n\n named.push({\n type: \"event\",\n name: event.event,\n file: source === undefined ? null : toPosixPath(source),\n });\n }\n\n for (const file of known) {\n if (/\\.notification\\.[cm]?[jt]sx?$/.test(file.file)) {\n named.push({\n type: \"notification\",\n name: stemOf(file.file, \"notification\"),\n file: file.file,\n });\n }\n }\n\n return named;\n },\n async sites(root): Promise<BookSite[]> {\n const multi = await siteFolders(root);\n\n if (multi.length > 0) {\n const configured = await webSitesConfig();\n\n return multi.map((id) => {\n const basePath: unknown = configured?.[id]?.basePath;\n\n return {\n id,\n root: `src/web/$sites/${id}`,\n basePath: typeof basePath === \"string\" ? basePath : null,\n };\n });\n }\n\n return (await folderNames(path.join(root, \"src\"))).includes(\"web\")\n ? [{ id: \"default\", root: \"src/web\", basePath: null }]\n : [];\n },\n pages,\n mobile: mobileApps,\n async tests(root) {\n const known = await currentFiles(root);\n const specs = known.filter((file) => file.type === \"spec\").map((file) => file.file);\n const outside: string[] = [];\n\n const walk = async (dir: string, pattern: RegExp): Promise<void> => {\n let entries;\n\n try {\n entries = await readdir(path.join(root, dir), { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n\n const relative = `${dir}/${entry.name}`;\n\n if (entry.isDirectory()) await walk(relative, pattern);\n else if (entry.isFile() && pattern.test(entry.name)) outside.push(relative);\n }\n };\n\n await walk(\"e2e\", /\\.e2e\\.(?:ts|mts|js|mjs)$/);\n await walk(\"tests\", /\\.(?:test|spec)\\.ts$/);\n\n return [...new Set([...specs, ...outside])].sort();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqEA,SAAS,UAAU,MAAc,MAA6B;CA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Aa,IAAI,EAClB,CAAC,QAAQ,SAAS,KAAK,SAAS,MAAM,CAAC,CAAC,KAAK,SAAS,KAAK,IAAI;GAClF,MAAM,UAAoB,CAAC;GAE3B,MAAM,OAAO,OAAO,KAAa,YAAmC;IAClE,IAAI;IAEJ,IAAI;KACF,UAAU,MAAM,QAAQ,KAAK,KAAK,MAAM,GAAG,GAAG,EAAE,eAAe,KAAK,CAAC;IACvE,QAAQ;KACN;IACF;IAEA,KAAK,MAAM,SAAS,SAAS;KAC3B,IAAI,MAAM,SAAS,kBAAkB,MAAM,KAAK,WAAW,GAAG,GAAG;KAEjE,MAAM,WAAW,GAAG,IAAI,GAAG,MAAM;KAEjC,IAAI,MAAM,YAAY,GAAG,MAAM,KAAK,UAAU,OAAO;UAChD,IAAI,MAAM,OAAO,KAAK,QAAQ,KAAK,MAAM,IAAI,GAAG,QAAQ,KAAK,QAAQ;IAC5E;GACF;GAEA,MAAM,KAAK,OAAO,2BAA2B;GAC7C,MAAM,KAAK,SAAS,sBAAsB;GAE1C,OAAO,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAG,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK;EACnD;CACF;AACF"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { GrimoireError } from "../codes/index.mjs";
|
|
2
|
+
import { GRIMOIRE_PATHS } from "../paths/index.mjs";
|
|
3
|
+
import { openGrimoire } from "../workspace/index.mjs";
|
|
4
|
+
import { describeRouteDiff, diffRoutes, readApiSnapshot, routeLines, writeApiSnapshot } from "../guard/api.mjs";
|
|
5
|
+
import { reportError } from "./actions.mjs";
|
|
6
|
+
import "../guard/index.mjs";
|
|
7
|
+
|
|
8
|
+
//#region ../../packages/grimoire/src/warlock/api-command.ts
|
|
9
|
+
/**
|
|
10
|
+
* `warlock grimoire approve api`: write the routes into
|
|
11
|
+
* `grimoire/approved/api.json`, the approved public API. Reads the cached
|
|
12
|
+
* route facts (run `warlock grimoire build` first); never boots the app.
|
|
13
|
+
*/
|
|
14
|
+
/** Approve the current public API. Exit code 0 when written. */
|
|
15
|
+
async function runApproveApi(context, options = {}) {
|
|
16
|
+
const { root, adapter, io } = context;
|
|
17
|
+
try {
|
|
18
|
+
const routes = (await openGrimoire(root, adapter, { routes: "cached" })).book.facts.routes;
|
|
19
|
+
if (routes === null) throw new GrimoireError("GR9006", "The book has no route facts yet, so there is no API to approve. Run warlock grimoire build first.");
|
|
20
|
+
const lines = routeLines(routes);
|
|
21
|
+
const before = await readApiSnapshot(root);
|
|
22
|
+
const diff = diffRoutes(before?.routes ?? [], lines);
|
|
23
|
+
const approved = await writeApiSnapshot(root, lines);
|
|
24
|
+
if (options.json === true) {
|
|
25
|
+
io.out(JSON.stringify({
|
|
26
|
+
file: GRIMOIRE_PATHS.apiSnapshot,
|
|
27
|
+
...approved,
|
|
28
|
+
...diff
|
|
29
|
+
}, null, 2));
|
|
30
|
+
return 0;
|
|
31
|
+
}
|
|
32
|
+
io.out(`approved the public API: ${lines.length} route${lines.length === 1 ? "" : "s"} in ${GRIMOIRE_PATHS.apiSnapshot}${before === null ? "" : diff.added.length + diff.removed.length === 0 ? " (unchanged)" : ` (${describeRouteDiff(diff)})`}`);
|
|
33
|
+
return 0;
|
|
34
|
+
} catch (error) {
|
|
35
|
+
return reportError(io, error);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
//#endregion
|
|
40
|
+
export { runApproveApi };
|
|
41
|
+
//# sourceMappingURL=api-command.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-command.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/api-command.ts"],"sourcesContent":["/**\n * `warlock grimoire approve api`: write the routes into\n * `grimoire/approved/api.json`, the approved public API. Reads the cached\n * route facts (run `warlock grimoire build` first); never boots the app.\n */\nimport { GrimoireError } from \"../codes\";\nimport { GRIMOIRE_PATHS } from \"../paths\";\nimport {\n readApiSnapshot,\n routeLines,\n writeApiSnapshot,\n diffRoutes,\n describeRouteDiff,\n} from \"../guard\";\nimport { openGrimoire } from \"../workspace\";\nimport { reportError, type CommandContext } from \"./actions\";\n\n/** Approve the current public API. Exit code 0 when written. */\nexport async function runApproveApi(\n context: CommandContext,\n options: Record<string, unknown> = {},\n): Promise<number> {\n const { root, adapter, io } = context;\n\n try {\n const snapshot = await openGrimoire(root, adapter, { routes: \"cached\" });\n const routes = snapshot.book.facts.routes;\n\n if (routes === null) {\n throw new GrimoireError(\n \"GR9006\",\n \"The book has no route facts yet, so there is no API to approve. Run warlock grimoire build first.\",\n );\n }\n\n const lines = routeLines(routes);\n const before = await readApiSnapshot(root);\n const diff = diffRoutes(before?.routes ?? [], lines);\n const approved = await writeApiSnapshot(root, lines);\n\n if (options.json === true) {\n io.out(JSON.stringify({ file: GRIMOIRE_PATHS.apiSnapshot, ...approved, ...diff }, null, 2));\n\n return 0;\n }\n\n io.out(\n `approved the public API: ${lines.length} route${lines.length === 1 ? \"\" : \"s\"} in ${GRIMOIRE_PATHS.apiSnapshot}${\n before === null\n ? \"\"\n : diff.added.length + diff.removed.length === 0\n ? \" (unchanged)\"\n : ` (${describeRouteDiff(diff)})`\n }`,\n );\n\n return 0;\n } catch (error) {\n return reportError(io, error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAkBA,eAAsB,cACpB,SACA,UAAmC,CAAC,GACnB;CACjB,MAAM,EAAE,MAAM,SAAS,OAAO;CAE9B,IAAI;EAEF,MAAM,UAAS,MADQ,aAAa,MAAM,SAAS,EAAE,QAAQ,SAAS,CAAC,EAChD,CAAC,KAAK,MAAM;EAEnC,IAAI,WAAW,MACb,MAAM,IAAI,cACR,UACA,mGACF;EAGF,MAAM,QAAQ,WAAW,MAAM;EAC/B,MAAM,SAAS,MAAM,gBAAgB,IAAI;EACzC,MAAM,OAAO,WAAW,QAAQ,UAAU,CAAC,GAAG,KAAK;EACnD,MAAM,WAAW,MAAM,iBAAiB,MAAM,KAAK;EAEnD,IAAI,QAAQ,SAAS,MAAM;GACzB,GAAG,IAAI,KAAK,UAAU;IAAE,MAAM,eAAe;IAAa,GAAG;IAAU,GAAG;GAAK,GAAG,MAAM,CAAC,CAAC;GAE1F,OAAO;EACT;EAEA,GAAG,IACD,4BAA4B,MAAM,OAAO,QAAQ,MAAM,WAAW,IAAI,KAAK,IAAI,MAAM,eAAe,cAClG,WAAW,OACP,KACA,KAAK,MAAM,SAAS,KAAK,QAAQ,WAAW,IAC1C,iBACA,KAAK,kBAAkB,IAAI,EAAE,IAEvC;EAEA,OAAO;CACT,SAAS,OAAO;EACd,OAAO,YAAY,IAAI,KAAK;CAC9B;AACF"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { GrimoireError } from "../codes/index.mjs";
|
|
2
|
+
import { openGrimoire } from "../workspace/index.mjs";
|
|
3
|
+
import { approveItems, rejectItems, selectDrift } from "../shots/approve.mjs";
|
|
4
|
+
import { reportError } from "./actions.mjs";
|
|
5
|
+
|
|
6
|
+
//#region ../../packages/grimoire/src/warlock/approve-command.ts
|
|
7
|
+
/**
|
|
8
|
+
* `warlock grimoire approve <target>` and `reject <target>`: accept or refuse
|
|
9
|
+
* a change since the approved baseline (`grimoire/approved/baseline.json`).
|
|
10
|
+
*/
|
|
11
|
+
function openFor(context) {
|
|
12
|
+
return openGrimoire(context.root, context.adapter, {
|
|
13
|
+
routes: "cached",
|
|
14
|
+
write: false
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
function targetsOf(target, options) {
|
|
18
|
+
if (options.all === true) return ["all"];
|
|
19
|
+
if (typeof target !== "string" || target.trim() === "") throw new GrimoireError("GR9010", "Name what to approve: a change id from the check, a <feature>/<flow>, or --all.");
|
|
20
|
+
return [target.trim()];
|
|
21
|
+
}
|
|
22
|
+
function print(context, done, options, verb) {
|
|
23
|
+
if (options.json === true) {
|
|
24
|
+
context.io.out(JSON.stringify({ done }, null, 2));
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
if (verb === "approved" && done.length === 1 && done[0] === "baseline") {
|
|
28
|
+
context.io.out("created the approved baseline from the current state (grimoire/approved/baseline.json)");
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
for (const id of done) context.io.out(id);
|
|
32
|
+
context.io.out(`${verb} ${done.length}`);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Approve the drift items `target` names: a drift id, a `<feature>/<flow>`
|
|
36
|
+
* (every item of the flow), or every item with `--all`; `--lang` keeps one
|
|
37
|
+
* language's images. `--all` with no baseline creates it from the current
|
|
38
|
+
* state. Exit code 0 when it ran.
|
|
39
|
+
*/
|
|
40
|
+
async function runApprove(context, target, options = {}) {
|
|
41
|
+
try {
|
|
42
|
+
const targets = targetsOf(target, options);
|
|
43
|
+
const snapshot = await openFor(context);
|
|
44
|
+
const language = typeof options.lang === "string" ? options.lang : void 0;
|
|
45
|
+
if (snapshot.shots?.baseline == null) {
|
|
46
|
+
if (options.all !== true) throw new GrimoireError("GR9010", "Nothing is approved yet, so there is no change to name. Approve the current state with --all.");
|
|
47
|
+
print(context, await approveItems(snapshot, [], void 0, { createWhenMissing: true }), options, "approved");
|
|
48
|
+
return 0;
|
|
49
|
+
}
|
|
50
|
+
const items = selectDrift(snapshot, {
|
|
51
|
+
targets,
|
|
52
|
+
...language === void 0 ? {} : { language }
|
|
53
|
+
});
|
|
54
|
+
print(context, await approveItems(snapshot, items), options, "approved");
|
|
55
|
+
return 0;
|
|
56
|
+
} catch (error) {
|
|
57
|
+
return reportError(context.io, error);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** Reject the drift items `target` names (same targets as approve; `--note` records why). */
|
|
61
|
+
async function runReject(context, target, options = {}) {
|
|
62
|
+
try {
|
|
63
|
+
const targets = targetsOf(target, options);
|
|
64
|
+
const snapshot = await openFor(context);
|
|
65
|
+
const language = typeof options.lang === "string" ? options.lang : void 0;
|
|
66
|
+
const note = typeof options.note === "string" && options.note.trim() !== "" ? options.note.trim() : null;
|
|
67
|
+
const items = selectDrift(snapshot, {
|
|
68
|
+
targets,
|
|
69
|
+
...language === void 0 ? {} : { language }
|
|
70
|
+
});
|
|
71
|
+
print(context, await rejectItems(snapshot, items, note), options, "rejected");
|
|
72
|
+
return 0;
|
|
73
|
+
} catch (error) {
|
|
74
|
+
return reportError(context.io, error);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
//#endregion
|
|
79
|
+
export { runApprove, runReject };
|
|
80
|
+
//# sourceMappingURL=approve-command.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"approve-command.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/approve-command.ts"],"sourcesContent":["/**\n * `warlock grimoire approve <target>` and `reject <target>`: accept or refuse\n * a change since the approved baseline (`grimoire/approved/baseline.json`).\n */\nimport { GrimoireError } from \"../codes\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport { approveItems, rejectItems, selectDrift } from \"../shots/approve\";\nimport { openGrimoire } from \"../workspace\";\nimport { reportError, type CommandContext } from \"./actions\";\n\nfunction openFor(context: CommandContext): Promise<GrimoireSnapshot> {\n return openGrimoire(context.root, context.adapter, { routes: \"cached\", write: false });\n}\n\nfunction targetsOf(target: string | undefined, options: Record<string, unknown>): string[] {\n if (options.all === true) return [\"all\"];\n\n if (typeof target !== \"string\" || target.trim() === \"\") {\n throw new GrimoireError(\n \"GR9010\",\n \"Name what to approve: a change id from the check, a <feature>/<flow>, or --all.\",\n );\n }\n\n return [target.trim()];\n}\n\nfunction print(\n context: CommandContext,\n done: readonly string[],\n options: Record<string, unknown>,\n verb: \"approved\" | \"rejected\",\n): void {\n if (options.json === true) {\n context.io.out(JSON.stringify({ done }, null, 2));\n\n return;\n }\n\n // The first approval writes the whole current state as the baseline.\n if (verb === \"approved\" && done.length === 1 && done[0] === \"baseline\") {\n context.io.out(\n \"created the approved baseline from the current state (grimoire/approved/baseline.json)\",\n );\n\n return;\n }\n\n for (const id of done) context.io.out(id);\n\n context.io.out(`${verb} ${done.length}`);\n}\n\n/**\n * Approve the drift items `target` names: a drift id, a `<feature>/<flow>`\n * (every item of the flow), or every item with `--all`; `--lang` keeps one\n * language's images. `--all` with no baseline creates it from the current\n * state. Exit code 0 when it ran.\n */\nexport async function runApprove(\n context: CommandContext,\n target: string | undefined,\n options: Record<string, unknown> = {},\n): Promise<number> {\n try {\n const targets = targetsOf(target, options);\n const snapshot = await openFor(context);\n const language = typeof options.lang === \"string\" ? options.lang : undefined;\n\n if (snapshot.shots?.baseline == null) {\n if (options.all !== true) {\n throw new GrimoireError(\n \"GR9010\",\n \"Nothing is approved yet, so there is no change to name. Approve the current state with --all.\",\n );\n }\n\n print(\n context,\n await approveItems(snapshot, [], undefined, { createWhenMissing: true }),\n options,\n \"approved\",\n );\n\n return 0;\n }\n\n const items = selectDrift(snapshot, {\n targets,\n ...(language === undefined ? {} : { language }),\n });\n\n print(context, await approveItems(snapshot, items), options, \"approved\");\n\n return 0;\n } catch (error) {\n return reportError(context.io, error);\n }\n}\n\n/** Reject the drift items `target` names (same targets as approve; `--note` records why). */\nexport async function runReject(\n context: CommandContext,\n target: string | undefined,\n options: Record<string, unknown> = {},\n): Promise<number> {\n try {\n const targets = targetsOf(target, options);\n const snapshot = await openFor(context);\n const language = typeof options.lang === \"string\" ? options.lang : undefined;\n const note =\n typeof options.note === \"string\" && options.note.trim() !== \"\" ? options.note.trim() : null;\n const items = selectDrift(snapshot, {\n targets,\n ...(language === undefined ? {} : { language }),\n });\n\n print(context, await rejectItems(snapshot, items, note), options, \"rejected\");\n\n return 0;\n } catch (error) {\n return reportError(context.io, error);\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAS,QAAQ,SAAoD;CACnE,OAAO,aAAa,QAAQ,MAAM,QAAQ,SAAS;EAAE,QAAQ;EAAU,OAAO;CAAM,CAAC;AACvF;AAEA,SAAS,UAAU,QAA4B,SAA4C;CACzF,IAAI,QAAQ,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MAAM,UAAU,UAAU,QAAQ,OAAO;EACzC,MAAM,WAAW,MAAM,QAAQ,OAAO;EACtC,MAAM,WAAW,OAAO,QAAQ,SAAS,WAAW,QAAQ,OAAO;EACnE,MAAM,OACJ,OAAO,QAAQ,SAAS,YAAY,QAAQ,KAAK,KAAK,MAAM,KAAK,QAAQ,KAAK,KAAK,IAAI;EACzF,MAAM,QAAQ,YAAY,UAAU;GAClC;GACA,GAAI,aAAa,SAAY,CAAC,IAAI,EAAE,SAAS;EAC/C,CAAC;EAED,MAAM,SAAS,MAAM,YAAY,UAAU,OAAO,IAAI,GAAG,SAAS,UAAU;EAE5E,OAAO;CACT,SAAS,OAAO;EACd,OAAO,YAAY,QAAQ,IAAI,KAAK;CACtC;AACF"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { Worker } from "node:worker_threads";
|
|
2
|
+
|
|
3
|
+
//#region ../../packages/grimoire/src/warlock/collect-off-thread.ts
|
|
4
|
+
/**
|
|
5
|
+
* Runs the source scan (`collectFiles`) in a worker thread, so a large app's scan never blocks the event loop of
|
|
6
|
+
* the process that serves the app. The scan reads and parses every source file synchronously; on thousands of
|
|
7
|
+
* files that is seconds. The worker only reads files; the result comes back as plain data.
|
|
8
|
+
*
|
|
9
|
+
* Returns `null` when the worker cannot run (the tooling entry does not resolve to a plain module a worker can
|
|
10
|
+
* load, or the worker fails); the caller then scans in the current thread, which gives the same answer.
|
|
11
|
+
*/
|
|
12
|
+
/** The worker's body: load the tooling entry, scan, post the files back. */
|
|
13
|
+
const WORKER_SOURCE = `
|
|
14
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
15
|
+
import(workerData.entry)
|
|
16
|
+
.then(({ collectFiles }) => {
|
|
17
|
+
parentPort.postMessage({ files: collectFiles(workerData.root, [], workerData.options) });
|
|
18
|
+
})
|
|
19
|
+
.catch((error) => {
|
|
20
|
+
parentPort.postMessage({ error: String(error && error.message ? error.message : error) });
|
|
21
|
+
});
|
|
22
|
+
`;
|
|
23
|
+
/** Scan in a worker thread; `null` when it could not (scan in the current thread instead). */
|
|
24
|
+
async function collectOffThread(scan) {
|
|
25
|
+
let entry;
|
|
26
|
+
try {
|
|
27
|
+
if (typeof import.meta.resolve !== "function") return null;
|
|
28
|
+
entry = import.meta.resolve("@warlock.js/core/tooling");
|
|
29
|
+
if (/\.[cm]?tsx?$/.test(entry)) return null;
|
|
30
|
+
} catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
return new Promise((resolve) => {
|
|
34
|
+
let worker;
|
|
35
|
+
try {
|
|
36
|
+
worker = new Worker(WORKER_SOURCE, {
|
|
37
|
+
eval: true,
|
|
38
|
+
workerData: {
|
|
39
|
+
entry,
|
|
40
|
+
root: scan.root,
|
|
41
|
+
options: {
|
|
42
|
+
dirs: [...scan.dirs],
|
|
43
|
+
files: [...scan.files]
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
} catch {
|
|
48
|
+
resolve(null);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
let settled = false;
|
|
52
|
+
const finish = (files) => {
|
|
53
|
+
if (settled) return;
|
|
54
|
+
settled = true;
|
|
55
|
+
worker.terminate();
|
|
56
|
+
resolve(files);
|
|
57
|
+
};
|
|
58
|
+
worker.once("message", (message) => finish(message.files ?? null));
|
|
59
|
+
worker.once("error", () => finish(null));
|
|
60
|
+
worker.once("exit", () => finish(null));
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
//#endregion
|
|
65
|
+
export { collectOffThread };
|
|
66
|
+
//# sourceMappingURL=collect-off-thread.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"collect-off-thread.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/collect-off-thread.ts"],"sourcesContent":["/**\n * Runs the source scan (`collectFiles`) in a worker thread, so a large app's scan never blocks the event loop of\n * the process that serves the app. The scan reads and parses every source file synchronously; on thousands of\n * files that is seconds. The worker only reads files; the result comes back as plain data.\n *\n * Returns `null` when the worker cannot run (the tooling entry does not resolve to a plain module a worker can\n * load, or the worker fails); the caller then scans in the current thread, which gives the same answer.\n */\nimport { Worker } from \"node:worker_threads\";\n\n/** The worker's body: load the tooling entry, scan, post the files back. */\nconst WORKER_SOURCE = `\nconst { parentPort, workerData } = require(\"node:worker_threads\");\nimport(workerData.entry)\n .then(({ collectFiles }) => {\n parentPort.postMessage({ files: collectFiles(workerData.root, [], workerData.options) });\n })\n .catch((error) => {\n parentPort.postMessage({ error: String(error && error.message ? error.message : error) });\n });\n`;\n\n/** The scan options the worker passes to `collectFiles`. */\nexport type OffThreadScan = {\n root: string;\n dirs: readonly string[];\n files: readonly string[];\n};\n\n/** Scan in a worker thread; `null` when it could not (scan in the current thread instead). */\nexport async function collectOffThread<File>(scan: OffThreadScan): Promise<File[] | null> {\n let entry: string;\n\n try {\n if (typeof import.meta.resolve !== \"function\") return null;\n\n entry = import.meta.resolve(\"@warlock.js/core/tooling\");\n\n // A worker loads plain JavaScript only: a TypeScript source entry (a checkout of the framework) is scanned in-thread.\n if (/\\.[cm]?tsx?$/.test(entry)) return null;\n } catch {\n return null;\n }\n\n return new Promise((resolve) => {\n let worker: Worker;\n\n try {\n worker = new Worker(WORKER_SOURCE, {\n eval: true,\n workerData: {\n entry,\n root: scan.root,\n options: { dirs: [...scan.dirs], files: [...scan.files] },\n },\n });\n } catch {\n resolve(null);\n\n return;\n }\n\n let settled = false;\n const finish = (files: File[] | null): void => {\n if (settled) return;\n\n settled = true;\n void worker.terminate();\n resolve(files);\n };\n\n worker.once(\"message\", (message: { files?: File[]; error?: string }) =>\n finish(message.files ?? null),\n );\n worker.once(\"error\", () => finish(null));\n worker.once(\"exit\", () => finish(null));\n });\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAM,gBAAgB;;;;;;;;;;;AAmBtB,eAAsB,iBAAuB,MAA6C;CACxF,IAAI;CAEJ,IAAI;EACF,IAAI,OAAO,YAAY,YAAY,YAAY,OAAO;EAEtD,QAAQ,YAAY,QAAQ,0BAA0B;EAGtD,IAAI,eAAe,KAAK,KAAK,GAAG,OAAO;CACzC,QAAQ;EACN,OAAO;CACT;CAEA,OAAO,IAAI,SAAS,YAAY;EAC9B,IAAI;EAEJ,IAAI;GACF,SAAS,IAAI,OAAO,eAAe;IACjC,MAAM;IACN,YAAY;KACV;KACA,MAAM,KAAK;KACX,SAAS;MAAE,MAAM,CAAC,GAAG,KAAK,IAAI;MAAG,OAAO,CAAC,GAAG,KAAK,KAAK;KAAE;IAC1D;GACF,CAAC;EACH,QAAQ;GACN,QAAQ,IAAI;GAEZ;EACF;EAEA,IAAI,UAAU;EACd,MAAM,UAAU,UAA+B;GAC7C,IAAI,SAAS;GAEb,UAAU;GACV,AAAK,OAAO,UAAU;GACtB,QAAQ,KAAK;EACf;EAEA,OAAO,KAAK,YAAY,YACtB,OAAO,QAAQ,SAAS,IAAI,CAC9B;EACA,OAAO,KAAK,eAAe,OAAO,IAAI,CAAC;EACvC,OAAO,KAAK,cAAc,OAAO,IAAI,CAAC;CACxC,CAAC;AACH"}
|