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

checks/lib/pages.ts

217 lines, 10.6 KB.

  1. // Reading pages from disk: front matter, paths, collection records. Read-only, Bun only, no dependencies.
  2. // The base of every check of the standard: speclib.ts and schemalib.ts build on it, other packages import it
  3. // from `.shtukbase/packages/collections/checks/lib/pages.ts`.
  4. import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
  5. import { posix } from 'node:path';
  6. /** A page's front matter as data; values are whatever YAML gives (string, number, boolean, null, array, object). */
  7. export type Head = Record<string, any>;
  8. /** A record of a collection: `id` is the project path `/work/tasks/x.md`, `file` the file name, `kind` the caller's label. */
  9. export type Rec = { id: string; kind: string; fm: Head; body: string; title: string; file: string };
  10. export function readText(path: string): string {
  11. return readFileSync(path, 'utf8');
  12. }
  13. /** Python-style `str(v)`: None / True / False, lists and objects as Python prints them (messages stay the same). */
  14. export function pystr(v: unknown, nested = false): string {
  15. if (v === null || v === undefined) return 'None';
  16. if (typeof v === 'boolean') return v ? 'True' : 'False';
  17. if (typeof v === 'string') {
  18. if (!nested) return v;
  19. const q = v.includes("'") && !v.includes('"') ? '"' : "'";
  20. return q + v.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/\t/g, '\\t').replaceAll(q, '\\' + q) + q;
  21. }
  22. if (Array.isArray(v)) return '[' + v.map((x) => pystr(x, true)).join(', ') + ']';
  23. if (typeof v === 'object') return '{' + Object.entries(v).map(([k, x]) => `${pystr(k, true)}: ${pystr(x, true)}`).join(', ') + '}';
  24. return String(v);
  25. }
  26. /** Python truthiness: the empty string, 0, null, false, `[]` and `{}` are false. */
  27. export function truthy(v: unknown): boolean {
  28. if (Array.isArray(v)) return v.length > 0;
  29. if (v && typeof v === 'object') return Object.keys(v).length > 0;
  30. return !!v;
  31. }
  32. /** Splits a page into the front matter text (between the first two `---` lines; '' when there is none) and the body. */
  33. export function splitFrontMatter(text: string): [string, string] {
  34. text = text.replace(/^+/, '');
  35. if (!text.startsWith('---')) return ['', text];
  36. const lines = text.split('\n');
  37. if (lines[0].trim() !== '---') return ['', text];
  38. for (let i = 1; i < lines.length; i++)
  39. if (lines[i].trimEnd() === '---') return [lines.slice(1, i).join('\n'), lines.slice(i + 1).join('\n')];
  40. return ['', text];
  41. }
  42. const asMap = (v: unknown): Head | null => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Head) : null);
  43. /** Bun 1.3 reads a plain `1118-040008` or `12-3` as the number before the dash; YAML means a string. Quote such
  44. * values when they stand alone on a line or in a one-line flow list, so ids that start with digits survive. */
  45. const DIGIT_DASH = /^(\s*(?:-\s+)?(?:[^\s:#'"][^:]*:\s+)?)(\d+(?:-\d+)+)(\s*(?:#.*)?)$/gm;
  46. function quoteDigitDash(text: string): string {
  47. return text
  48. .replace(DIGIT_DASH, '$1"$2"$3')
  49. .replace(/\[[^\]\n'"]*\]/g, (list) => list.replace(/(^\[|,)(\s*)(\d+(?:-\d+)+)(?=\s*[,\]])/g, '$1$2"$3"'));
  50. }
  51. function tryYaml(text: string): Head | null {
  52. try {
  53. return asMap(Bun.YAML.parse(quoteDigitDash(text)));
  54. } catch {
  55. return null;
  56. }
  57. }
  58. /** Front matter text → object. Strict YAML first. Pages written by hand often are not strict (`title: A: b`, a quote
  59. * inside a quoted value, `@name`): then each top-level entry is parsed on its own, and a one-line value that is not
  60. * valid YAML is taken as the plain text it is. An entry that still cannot be read is skipped, so the record lacks that
  61. * field and the checks name it, instead of the whole run failing. */
  62. export function parseYaml(text: string): Head {
  63. const whole = tryYaml(text);
  64. if (whole) return whole;
  65. const out: Head = {};
  66. for (const block of text.split(/\n(?=[^\s#-])/)) {
  67. const part = tryYaml(block);
  68. if (part) Object.assign(out, part);
  69. else {
  70. const m = /^([^\s:#][^:]*?):[ \t]+(.+?)\s*$/.exec(block);
  71. const plain = m && tryYaml(`${m[1]}: ${JSON.stringify(m[2].replace(/^"(.*)"$/s, '$1'))}`);
  72. if (plain) Object.assign(out, plain);
  73. }
  74. }
  75. return out;
  76. }
  77. /** One page: its parsed front matter and its body. */
  78. export function readPage(path: string): { fm: Head; body: string } {
  79. const [head, body] = splitFrontMatter(readText(path));
  80. return { fm: parseYaml(head), body };
  81. }
  82. /** Collapses `..` and `.` and drops a trailing slash (what Python's `os.path.normpath` does). */
  83. function normpath(p: string): string {
  84. const n = posix.normalize(p);
  85. return n.length > 1 && n.endsWith('/') ? n.slice(0, -1) : n;
  86. }
  87. /** Where a bare name in a relation field is looked up, by field name (old, kept for the checks that rely on it). */
  88. const DEFAULT_COLL: Record<string, string> = {
  89. intent: '/product/intents', intents: '/product/intents',
  90. sc: '/product/scenarios', includes: '/product/scenarios', extends: '/product/scenarios',
  91. leadsTo: '/product/scenarios', needs: '/product/scenarios', feeds: '/product/scenarios',
  92. configuredIn: '/product/scenarios',
  93. actor: '/product/roles', notifies: '/product/roles', serves: '/business/roles',
  94. function: '/business/functions', realizes: '/business/requirements',
  95. requirements: '/business/requirements', supports: '/business/steps', roles: '/business/roles',
  96. runs: '/product/actions', calls: '/product/actions',
  97. };
  98. /** Any relation value (path, `[[wikilink]]`, `[text](path)`, bare name) → project path `/a/b.md`, or null. */
  99. export function normPath(v: unknown, prop?: string | null, ownId?: string | null): string | null {
  100. if (v === null || v === undefined) return null;
  101. let s = pystr(v).trim().replace(/^["']+|["']+$/g, '');
  102. s = s.replace(/^\[\[(.*)\]\]$/s, '$1');
  103. const m = /^\[[^\]]*\]\(([^)]+)\)$/.exec(s);
  104. if (m) s = m[1];
  105. s = s.split('#')[0].trim();
  106. if (!s) return null;
  107. if (!s.startsWith('/')) {
  108. if (s.includes('/') && ownId) s = normpath(posix.join(posix.dirname(ownId), s));
  109. else if (prop && Object.hasOwn(DEFAULT_COLL, prop)) s = DEFAULT_COLL[prop] + '/' + s;
  110. else s = '/' + s;
  111. }
  112. return s.endsWith('.md') ? s : s + '.md';
  113. }
  114. /** The state name of a status value: last path part, lower case (`/work/states/Done.md` → `done.md`), or null. */
  115. export function normStatus(v: unknown): string | null {
  116. if (v === null || v === undefined) return null;
  117. const s = pystr(v).trim().replace(/^\/+|\/+$/g, '');
  118. return s.split('/').pop()!.toLowerCase() || null;
  119. }
  120. /** Records of a collection folder (`work/tasks`, relative to the project): its `.md` files in name order. */
  121. export function loadCollection(project: string, kind: string, folder: string): Rec[] {
  122. const d = posix.join(project, folder);
  123. if (!existsSync(d) || !statSync(d).isDirectory()) return [];
  124. const recs: Rec[] = [];
  125. for (const name of readdirSync(d).sort()) {
  126. if (!name.endsWith('.md') || name.startsWith('.')) continue;
  127. const full = posix.join(d, name);
  128. if (!statSync(full, { throwIfNoEntry: false })?.isFile()) continue;
  129. const [head, body] = splitFrontMatter(readText(full));
  130. const fm = parseYaml(head);
  131. const heading = /^\s{0,3}#\s+(.+?)\s*$/m.exec(body)?.[1];
  132. const title = truthy(fm.title) ? fm.title : heading || name.slice(0, -3);
  133. recs.push({ id: '/' + folder + '/' + name, kind, fm, body: body.replace(/^\n+|\n+$/g, ''), title: pystr(title), file: name });
  134. }
  135. return recs;
  136. }
  137. /** `properties:` of a collection page (`work/tasks.md`): `{field: {kind, collection, multiple, ...}}`; {} if none. */
  138. export function schemaProperties(project: string, relFile: string): Head {
  139. const path = posix.join(project, relFile);
  140. if (!existsSync(path)) return {};
  141. const props = parseYaml(splitFrontMatter(readText(path))[0]).properties;
  142. return props && typeof props === 'object' && !Array.isArray(props) ? props : {};
  143. }
  144. /** Folders of matching nested projects and their repo-relative places, returned as absolute paths. */
  145. export function excludedFolders(projectDir: string, root: string, names: readonly string[]): string[] {
  146. const excluded = new Set<string>();
  147. if (!names.length) return [];
  148. const repo = posix.resolve(root);
  149. function visit(dir: string, nested: boolean): void {
  150. const entries = readdirSync(dir, { withFileTypes: true });
  151. if (nested && entries.some((e) => e.name === '.shtukbase' && e.isDirectory())) {
  152. const header = posix.join(dir, 'base', 'packages.md');
  153. const { name, folder } = existsSync(header) ? readPage(header).fm : {};
  154. if ([posix.basename(dir), name, folder].some((value) => names.includes(value))) {
  155. excluded.add(dir);
  156. const index = posix.join(dir, 'index.md');
  157. const places = existsSync(index) ? readPage(index).fm.places : undefined;
  158. if (Array.isArray(places)) {
  159. for (const place of places) {
  160. if (typeof place !== 'string' || !place.trim() || posix.isAbsolute(place)) continue;
  161. const full = posix.resolve(repo, place.trim());
  162. const rel = posix.relative(repo, full);
  163. if (rel !== '..' && !rel.startsWith('../')) excluded.add(full);
  164. }
  165. }
  166. }
  167. }
  168. for (const e of entries) {
  169. if (!e.isDirectory() || ['.git', 'node_modules', '.shtukbase'].includes(e.name)) continue;
  170. if (e.name === 'worktrees' && posix.basename(dir) === '.claude') continue;
  171. visit(posix.join(dir, e.name), true);
  172. }
  173. }
  174. visit(posix.resolve(projectDir), false);
  175. return [...excluded];
  176. }
  177. /** Walks a folder top down like Python's `os.walk` (links to folders are not entered): yields the folder path relative to
  178. * `root` ('.' for the root) and its file names. `enter(name, depth)` says which sub-folders to go into (depth 0 = in the root).
  179. * Skip folders can be absolute or relative to `root`. */
  180. export function* walk(root: string, enter: (name: string, depth: number) => boolean, skip: readonly string[] = []): Generator<[string, string[]]> {
  181. const excluded = skip.map((dir) => posix.resolve(root, dir));
  182. yield* walkFolder(posix.resolve(root), enter, excluded, '.', 0);
  183. }
  184. function* walkFolder(
  185. root: string, enter: (name: string, depth: number) => boolean, excluded: readonly string[], rel: string, depth: number,
  186. ): Generator<[string, string[]]> {
  187. const dir = posix.join(root, rel);
  188. if (excluded.some((folder) => dir === folder || dir.startsWith(posix.join(folder, '/')))) return;
  189. const files: string[] = [];
  190. const dirs: string[] = [];
  191. for (const e of readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
  192. const isDir = e.isDirectory() || (e.isSymbolicLink() && statSync(posix.join(dir, e.name), { throwIfNoEntry: false })?.isDirectory());
  193. if (!isDir) files.push(e.name);
  194. else if (e.isDirectory() && enter(e.name, depth)) dirs.push(e.name);
  195. }
  196. yield [rel, files];
  197. for (const d of dirs) yield* walkFolder(root, enter, excluded, posix.join(rel, d), depth + 1);
  198. }