ShtukbaseStandard
package file→ .shtukbase/packages/collections/checks/lib/speclib.ts

checks/lib/speclib.ts

216 lines, 9.8 KB.

  1. // The shared part of the checks: a project read from disk (read-only), a rule's result, running a rule.
  2. // Collections are found by the `itemType` of their page, not by path; a relation field is found by the collection
  3. // it leads to; the state category (arriving / working / done / dropped) comes from the phase page of the contour.
  4. // A rule knows only types and the meaning of a link: rename a field or a folder in the schema and the rule follows.
  5. import { existsSync, readFileSync } from 'node:fs';
  6. import { join, resolve } from 'node:path';
  7. import { type Head, type Rec, loadCollection, normPath, normStatus, pystr, schemaProperties, truthy, walk } from './pages.ts';
  8. export * from './pages.ts';
  9. /** Record types the rules work with, by key. Several names in case a type has not settled yet. Packages may add keys. */
  10. export const TYPES: Record<string, string[]> = {
  11. BR: ['BusinessRequirement'], BOBJ: ['BusinessObject'], CAP: ['Capability'], REQ: ['Requirement'],
  12. SURF: ['Surface'], SCEN: ['Scenario'], AUTO: ['ProductAutomation'], INTENT: ['Intent'], REFUSAL: ['Refusal'],
  13. CONCEPT: ['Concept'], CHECK: ['Check'], GOLDEN: ['Golden'], ACTION: ['ProductAction', 'Action'],
  14. AC: ['AcceptanceCriterion'], STAGE: ['Stage'], OBLIGATION: ['Obligation'],
  15. COMPONENT: ['Component', 'SoftwareComponent', 'ArchComponent'],
  16. DESIGN: ['DesignPrimitive', 'DesignComposite', 'DesignBlock', 'DesignScreen'],
  17. };
  18. export const TYPE_LABEL: Record<string, string> = {
  19. BR: 'business requirements', BOBJ: 'business objects', CAP: 'capabilities', REQ: 'requirements', SURF: 'surfaces',
  20. SCEN: 'scenarios', AUTO: 'automations', INTENT: 'intents', REFUSAL: 'refusals', CONCEPT: 'concepts',
  21. CHECK: 'product tests', GOLDEN: 'golden examples', ACTION: 'product actions', AC: 'acceptance criteria',
  22. STAGE: 'deal stages', OBLIGATION: 'deal obligations', COMPONENT: 'components of the Software Architecture layer',
  23. DESIGN: 'components of the Design layer',
  24. };
  25. /** The schema is ambiguous or broken: the run stops with "schema error". */
  26. export class SchemaError extends Error {}
  27. /** Address of a record for a person: the path from the project root without the leading slash. */
  28. export function addr(rid: string): string {
  29. return rid.replace(/^\/+/, '');
  30. }
  31. const rtrim = (s: unknown) => String(s ?? '').replace(/\/+$/, '');
  32. const isMap = (v: unknown): v is Head => !!v && typeof v === 'object' && !Array.isArray(v);
  33. export class Project {
  34. readonly root: string;
  35. private colls: Record<string, string> | null = null;
  36. private allColls: Record<string, string[]> = {};
  37. private recs: Record<string, Rec[]> = {};
  38. private schemas: Record<string, Head> = {};
  39. private cats: Record<string, string> = {};
  40. constructor(root: string) {
  41. this.root = resolve(root);
  42. if (!existsSync(this.root)) throw new Error(`no project folder: ${this.root}`);
  43. }
  44. /** `{itemType: collection path}`. Collection pages are `<layer>.md` and `<layer>/<name>.md`, never deeper. */
  45. collections(): Record<string, string> {
  46. if (this.colls) return this.colls;
  47. const found: Record<string, string> = {};
  48. for (const [rel, files] of walk(this.root, (n, depth) => depth === 0 && !n.startsWith('.') && n !== 'deleted')) {
  49. for (const f of files.filter((x) => x.endsWith('.md'))) {
  50. const path = rel === '.' ? f : rel + '/' + f;
  51. const head = readFileSync(join(this.root, path), 'utf8').slice(0, 4096);
  52. if (!head.startsWith('---') || !/^type:\s*"?Collection"?\s*$/m.test(head)) continue;
  53. const t = /^itemType:\s*"?([A-Za-z]+)"?\s*$/m.exec(head)?.[1];
  54. if (!t || t === 'Collection') continue;
  55. const coll = '/' + path.slice(0, -3);
  56. found[t] ??= coll;
  57. (this.allColls[t] ??= []).push(coll);
  58. }
  59. }
  60. return (this.colls = found);
  61. }
  62. /** Path of the collection of a type key (`TASK`), or null if the project has none. */
  63. coll(key: string): string | null {
  64. for (const name of TYPES[key]) if (name in this.collections()) return this.collections()[name];
  65. return null;
  66. }
  67. /** Records of the collection of a type key; [] if there is no such collection. */
  68. records(key: string): Rec[] {
  69. const c = this.coll(key);
  70. if (c === null) return [];
  71. const folder = c.replace(/^\/+/, '');
  72. return (this.recs[c] ??= loadCollection(this.root, folder.split('/').pop()!, folder));
  73. }
  74. /** `{id: record}` of a type key. */
  75. index(key: string): Record<string, Rec> {
  76. return Object.fromEntries(this.records(key).map((r) => [r.id, r]));
  77. }
  78. /** `properties:` of the collection of a type key; {} if none. */
  79. schema(key: string): Head {
  80. const c = this.coll(key);
  81. if (c === null) return {};
  82. return (this.schemas[c] ??= schemaProperties(this.root, c.replace(/^\/+/, '') + '.md'));
  83. }
  84. /** Why there is no data ("no collection" / "empty"), or null when every collection of the keys exists and has records. */
  85. need(...keys: string[]): string | null {
  86. for (const k of keys) {
  87. const c = this.coll(k);
  88. if (c === null) return `the project has no collection of type ${TYPES[k][0]} (${TYPE_LABEL[k]})`;
  89. if (!this.records(k).length) return `collection ${c} (${TYPE_LABEL[k]}) is empty`;
  90. }
  91. return null;
  92. }
  93. // ------------------------------------------------------------ fields
  94. /** Name of the relation field in the schema of `src` that leads to the collection of `dst`; null if none.
  95. * Several: `hint` if it is one of them, else a SchemaError. */
  96. field(src: string, dst: string, hint?: string | null): string | null {
  97. const props = this.schema(src);
  98. const target = this.coll(dst);
  99. if (!Object.keys(props).length || !target) return null;
  100. const names = Object.entries(props).filter(([, v]) => isMap(v) && v.kind === 'relation' && rtrim(v.collection) === target).map(([k]) => k);
  101. if (hint && names.includes(hint)) return hint;
  102. if (names.length === 1) return names[0];
  103. if (!names.length) return null;
  104. throw new SchemaError(`in the schema ${this.coll(src)} several fields lead to ${names.join(', ')}`);
  105. }
  106. /** First field of the schema of `src` of this kind (`phase`, `select`...). */
  107. fieldOfKind(src: string, kind: string): string | null {
  108. for (const [k, v] of Object.entries(this.schema(src))) if (isMap(v) && v.kind === kind) return k;
  109. return null;
  110. }
  111. /** Short name of a record: the pinned text field (a number) or the file name. */
  112. label(rec: Rec, key: string): string {
  113. const f = Object.entries(this.schema(key)).find(([, v]) => isMap(v) && v.kind === 'text' && v.pinned)?.[0];
  114. const v = f ? rec.fm[f] : null;
  115. return truthy(v) ? pystr(v) : rec.file.slice(0, -3);
  116. }
  117. /** Values of a relation field of a record as project paths `/a/b.md`; a bare name goes into the collection of `dst`. */
  118. links(rec: Rec, field: string | null | undefined, dst: string): string[] {
  119. const v = field ? rec.fm[field] : null;
  120. if (v === null || v === undefined || v === '') return [];
  121. const target = this.coll(dst) || '';
  122. const out: string[] = [];
  123. for (const x of Array.isArray(v) ? v : [v]) {
  124. let s = pystr(x).trim().replace(/^["']+|["']+$/g, '');
  125. const m = /^\[[^\]]*\]\(([^)]+)\)$/.exec(s);
  126. if (m) s = m[1];
  127. if (s && !s.startsWith('/') && !s.includes('/') && target) s = target + '/' + s;
  128. const p = normPath(s, null, rec.id);
  129. if (p && !out.includes(p)) out.push(p);
  130. }
  131. return out;
  132. }
  133. // ------------------------------------------------------------ states
  134. /** State category of a record: arriving / working / done / dropped; '?' if the phase page has none; null if no contour or no state. */
  135. category(rec: Rec, key: string): string | null {
  136. const f = this.fieldOfKind(key, 'phase');
  137. if (!f) return null;
  138. let name = normStatus(rec.fm[f]);
  139. if (!name) return null;
  140. if (name.endsWith('.md')) name = name.slice(0, -3);
  141. const contour = rtrim(this.schema(key)[f].contour);
  142. const ck = contour + '\0' + name;
  143. if (!(ck in this.cats)) {
  144. const path = join(this.root, contour.replace(/^\/+/, ''), name + '.md');
  145. this.cats[ck] = existsSync(path) ? /^category:\s*"?(\w+)/m.exec(readFileSync(path, 'utf8').slice(0, 2048))?.[1] ?? '?' : '?';
  146. }
  147. return this.cats[ck];
  148. }
  149. /** Is the record in scope by its state? Without a contour or a state it counts as live. */
  150. live(rec: Rec, key: string, cats = ['arriving', 'working', 'done']): boolean {
  151. const c = this.category(rec, key);
  152. return c === null || c === '?' || cats.includes(c);
  153. }
  154. }
  155. // ---------------------------------------------------------------- result
  156. export type Hole = { record: string; missing: string; fix: string; code: string; field?: string };
  157. /** The outcome of one rule. */
  158. export class Result {
  159. scopeText: string;
  160. scope: string[] = []; // addresses of the units in scope
  161. holes: Hole[] = [];
  162. nodata: { part: string; reason: string }[] = [];
  163. checked: string[] = [];
  164. error: string | null = null;
  165. info: Record<string, any> = {};
  166. constructor(public rule: { id: string; title: string; scope?: string }) {
  167. this.scopeText = rule.scope ?? '';
  168. }
  169. /** Records a part of the rule; true when there is data and the part is checked. */
  170. part(name: string, reason: string | null): boolean {
  171. if (reason) this.nodata.push({ part: name, reason });
  172. else this.checked.push(name);
  173. return !reason;
  174. }
  175. hole(record: string, missing: string, fix: string, code: string): void {
  176. this.holes.push({ record, missing, fix, code });
  177. }
  178. }
  179. /** A rule is a module with `RULE` and `check(project, result)`. A SchemaError becomes `result.error`. */
  180. export type Rule = { RULE: { id: string; title: string; scope?: string }; check: (p: Project, res: Result) => void };
  181. export function runRule(mod: Rule, project: Project): Result {
  182. const res = new Result(mod.RULE);
  183. try {
  184. mod.check(project, res);
  185. } catch (e) {
  186. if (!(e instanceof SchemaError)) throw e;
  187. res.error = e.message;
  188. }
  189. return res;
  190. }