ShtukbaseStandard
файл пакета→ .shtukbase/packages/collections/checks/lib/schemalib.ts

checks/lib/schemalib.ts

167 строк, 7.4 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // The shared part of the schema checks (s01–s03 and the checks of other packages that read schemas): collections,
  2. // their schemas and records are read by the schemas, with no TYPES.
  3. // A collection is a page with `type: Collection` at most one folder deep (`<layer>.md`, `<layer>/<name>.md`); its
  4. // records are the `.md` files of the folder of the same name. `only(paths)` narrows reading to the collections where
  5. // those records lie (the `--files` mode of a caller).
  6. import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
  7. import { join } from 'node:path';
  8. import { type Head, type Rec, addr, type Project, type Result, loadCollection, pystr, schemaProperties, walk } from './speclib.ts';
  9. export { addr };
  10. const SKIP_DIRS = new Set(['deleted', 'lab', 'runs', 'assets', 'node_modules']);
  11. let ONLY: Set<string> | null = null; // null: all records; else addresses of records without the leading slash
  12. /** Limits the run to these records (addresses from the project root, no leading slash); null lifts the limit. */
  13. export function only(paths: Iterable<string> | null): void {
  14. ONLY = paths === null ? null : new Set(paths);
  15. }
  16. /** The current limit (null: none). */
  17. export const onlyPaths = (): Set<string> | null => ONLY;
  18. const contexts = new WeakMap<Project, Ctx>();
  19. /** The schema context of a project: built once per project. */
  20. export function ctx(p: Project): Ctx {
  21. let c = contexts.get(p);
  22. if (!c) contexts.set(p, (c = new Ctx(p.root)));
  23. return c;
  24. }
  25. export class Ctx {
  26. private _files: Set<string> | null = null;
  27. private _colls: string[] | null = null;
  28. private _recs: Record<string, Rec[]> = {};
  29. private _props: Record<string, Head> = {};
  30. private _states: Record<string, Set<string> | null> = {};
  31. constructor(readonly root: string) {}
  32. /** Paths of all `.md` files of the project, like `/a/b.md` (one walk). In the root folder, `.`/`_` folders and SKIP_DIRS are
  33. * skipped, unless a SKIP_DIRS folder has its own page beside it (`runs.md`): then it is a collection of the project. */
  34. files(): Set<string> {
  35. if (!this._files) {
  36. this._files = new Set();
  37. for (const [rel, names] of walk(this.root, (n, depth) => !n.startsWith('.') && (depth > 0 || (!n.startsWith('_') && !(SKIP_DIRS.has(n) && !existsSync(join(this.root, n + '.md')))))))
  38. for (const f of names) if (f.endsWith('.md')) this._files.add(rel === '.' ? '/' + f : '/' + rel + '/' + f);
  39. }
  40. return this._files;
  41. }
  42. /** Paths of the collections like `/work/tasks` (by the `type: Collection` header). */
  43. collections(): string[] {
  44. if (!this._colls) {
  45. this._colls = [];
  46. for (const f of [...this.files()].sort()) {
  47. if (f.split('/').length - 1 > 2) continue;
  48. const head = readFileSync(join(this.root, f), 'utf8').slice(0, 4096);
  49. if (!head.startsWith('---')) continue;
  50. const end = head.indexOf('\n---', 3);
  51. if (/^type:\s*["']?Collection["']?\s*$/m.test(head.slice(0, end > 0 ? end : undefined))) this._colls.push(f.slice(0, -3));
  52. }
  53. }
  54. return this._colls;
  55. }
  56. /** The collections to read: all, or those where the `only` records lie. */
  57. wanted(): string[] {
  58. const cols = this.collections();
  59. if (!ONLY) return cols;
  60. const dirs = new Set<string>();
  61. for (const x of ONLY) {
  62. dirs.add('/' + x.split('/').slice(0, -1).join('/'));
  63. if (x.endsWith('.md')) dirs.add('/' + x.slice(0, -3));
  64. }
  65. return cols.filter((c) => dirs.has(c));
  66. }
  67. /** `properties:` of a collection (`/work/tasks`); {} if none. */
  68. props(coll: string): Head {
  69. return (this._props[coll] ??= schemaProperties(this.root, coll.slice(1) + '.md'));
  70. }
  71. records(coll: string): Rec[] {
  72. if (!this._recs[coll]) {
  73. const folder = coll.slice(1);
  74. const recs = loadCollection(this.root, folder.split('/').pop()!, folder);
  75. this._recs[coll] = ONLY ? recs.filter((r) => ONLY!.has(addr(r.id))) : recs;
  76. }
  77. return this._recs[coll];
  78. }
  79. /** Names of the files in a contour's folder (`/work/states` → `{new, doing, ...}`); null if there is no such folder. */
  80. states(contour: string | null | undefined): Set<string> | null {
  81. const c = (contour ?? '').trim().replace(/\/+$/, '');
  82. if (!(c in this._states)) {
  83. const d = join(this.root, c.replace(/^\/+/, ''));
  84. this._states[c] = c && existsSync(d) && statSync(d).isDirectory() ? new Set(readdirSync(d).filter((f) => f.endsWith('.md')).map((f) => f.slice(0, -3))) : null;
  85. }
  86. return this._states[c];
  87. }
  88. }
  89. // --- values ---------------------------------------------------------------------
  90. /** Empty value: null, '', [] or {}. */
  91. export function empty(v: unknown): boolean {
  92. if (v === null || v === undefined || v === '') return true;
  93. if (Array.isArray(v)) return v.length === 0;
  94. return typeof v === 'object' && Object.keys(v).length === 0;
  95. }
  96. /** The value as a list (a single value is a list of one). */
  97. export const values = (v: unknown): any[] => (Array.isArray(v) ? v : [v]);
  98. /** Names of the `options` of a select field (an option is `{name: ...}` or a plain value). */
  99. export function optionNames(spec: Head): Set<string> {
  100. const out = new Set<string>();
  101. const opts = Array.isArray(spec.options) ? spec.options : [];
  102. for (const o of opts)
  103. if (o && typeof o === 'object' && !Array.isArray(o)) {
  104. if (o.name !== null && o.name !== undefined) out.add(pystr(o.name));
  105. } else if (o !== null && o !== undefined) out.add(pystr(o));
  106. return out;
  107. }
  108. const DATE_RE = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
  109. /** An ISO date `YYYY-MM-DD`, optionally with a time. */
  110. export function isDate(v: unknown): boolean {
  111. if (v instanceof Date) return true;
  112. const s = pystr(v).trim();
  113. if (!DATE_RE.test(s)) return false;
  114. const [y, m, d] = s.slice(0, 10).split('-').map(Number);
  115. const t = new Date(Date.UTC(2000, m - 1, d));
  116. t.setUTCFullYear(y);
  117. return y >= 1 && t.getUTCFullYear() === y && t.getUTCMonth() === m - 1 && t.getUTCDate() === d;
  118. }
  119. export const isNumber = (v: unknown): boolean => typeof v === 'number';
  120. /** The value as text for a message, cut to `n` characters with «…». */
  121. export function short(v: unknown, n = 60): string {
  122. const c = [...pystr(v)];
  123. return c.length <= n ? c.join('') : c.slice(0, n - 1).join('') + '…';
  124. }
  125. /** A finding with a stable key `rule|record|field|code` (`field` in the result, `code` is the kind). */
  126. export function hole(res: Result, recAddr: string, field: string, kind: string, missing: string, fix: string): void {
  127. res.hole(recAddr, missing, fix, kind);
  128. res.holes[res.holes.length - 1].field = field;
  129. }
  130. export const holeKey = (ruleId: string, h: { record: string; field?: string; code?: string }): string => `${ruleId}|${h.record}|${h.field ?? ''}|${h.code ?? ''}`;
  131. /** (collection, field, spec) of the fields of these kinds in all collections that are read. */
  132. export function* iterFields(c: Ctx, kinds: string[]): Generator<[string, string, Head]> {
  133. for (const coll of c.wanted())
  134. for (const [name, spec] of Object.entries(c.props(coll)))
  135. if (spec && typeof spec === 'object' && kinds.includes((spec as Head).kind)) yield [coll, name, spec as Head];
  136. }
  137. /** Sets the scope of a rule to the records of the collections that are read; returns those collections. */
  138. export function scopeAll(c: Ctx, res: Result, what: string): string[] {
  139. const cols = c.wanted();
  140. res.scope = cols.flatMap((coll) => c.records(coll).map((r) => addr(r.id)));
  141. res.scopeText = `${what}: records of ${cols.length} collections by their schemas`;
  142. return cols;
  143. }