файл пакета→ .shtukbase/packages/collections/checks/lib/schemalib.ts
checks/lib/schemalib.ts
167 строк, 7.4 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // The shared part of the schema checks (s01–s03 and the checks of other packages that read schemas): collections,
- // their schemas and records are read by the schemas, with no TYPES.
- // A collection is a page with `type: Collection` at most one folder deep (`<layer>.md`, `<layer>/<name>.md`); its
- // records are the `.md` files of the folder of the same name. `only(paths)` narrows reading to the collections where
- // those records lie (the `--files` mode of a caller).
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
- import { join } from 'node:path';
- import { type Head, type Rec, addr, type Project, type Result, loadCollection, pystr, schemaProperties, walk } from './speclib.ts';
- export { addr };
- const SKIP_DIRS = new Set(['deleted', 'lab', 'runs', 'assets', 'node_modules']);
- let ONLY: Set<string> | null = null; // null: all records; else addresses of records without the leading slash
- /** Limits the run to these records (addresses from the project root, no leading slash); null lifts the limit. */
- export function only(paths: Iterable<string> | null): void {
- ONLY = paths === null ? null : new Set(paths);
- }
- /** The current limit (null: none). */
- export const onlyPaths = (): Set<string> | null => ONLY;
- const contexts = new WeakMap<Project, Ctx>();
- /** The schema context of a project: built once per project. */
- export function ctx(p: Project): Ctx {
- let c = contexts.get(p);
- if (!c) contexts.set(p, (c = new Ctx(p.root)));
- return c;
- }
- export class Ctx {
- private _files: Set<string> | null = null;
- private _colls: string[] | null = null;
- private _recs: Record<string, Rec[]> = {};
- private _props: Record<string, Head> = {};
- private _states: Record<string, Set<string> | null> = {};
- constructor(readonly root: string) {}
- /** Paths of all `.md` files of the project, like `/a/b.md` (one walk). In the root folder, `.`/`_` folders and SKIP_DIRS are
- * skipped, unless a SKIP_DIRS folder has its own page beside it (`runs.md`): then it is a collection of the project. */
- files(): Set<string> {
- if (!this._files) {
- this._files = new Set();
- 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')))))))
- for (const f of names) if (f.endsWith('.md')) this._files.add(rel === '.' ? '/' + f : '/' + rel + '/' + f);
- }
- return this._files;
- }
- /** Paths of the collections like `/work/tasks` (by the `type: Collection` header). */
- collections(): string[] {
- if (!this._colls) {
- this._colls = [];
- for (const f of [...this.files()].sort()) {
- if (f.split('/').length - 1 > 2) continue;
- const head = readFileSync(join(this.root, f), 'utf8').slice(0, 4096);
- if (!head.startsWith('---')) continue;
- const end = head.indexOf('\n---', 3);
- if (/^type:\s*["']?Collection["']?\s*$/m.test(head.slice(0, end > 0 ? end : undefined))) this._colls.push(f.slice(0, -3));
- }
- }
- return this._colls;
- }
- /** The collections to read: all, or those where the `only` records lie. */
- wanted(): string[] {
- const cols = this.collections();
- if (!ONLY) return cols;
- const dirs = new Set<string>();
- for (const x of ONLY) {
- dirs.add('/' + x.split('/').slice(0, -1).join('/'));
- if (x.endsWith('.md')) dirs.add('/' + x.slice(0, -3));
- }
- return cols.filter((c) => dirs.has(c));
- }
- /** `properties:` of a collection (`/work/tasks`); {} if none. */
- props(coll: string): Head {
- return (this._props[coll] ??= schemaProperties(this.root, coll.slice(1) + '.md'));
- }
- records(coll: string): Rec[] {
- if (!this._recs[coll]) {
- const folder = coll.slice(1);
- const recs = loadCollection(this.root, folder.split('/').pop()!, folder);
- this._recs[coll] = ONLY ? recs.filter((r) => ONLY!.has(addr(r.id))) : recs;
- }
- return this._recs[coll];
- }
- /** Names of the files in a contour's folder (`/work/states` → `{new, doing, ...}`); null if there is no such folder. */
- states(contour: string | null | undefined): Set<string> | null {
- const c = (contour ?? '').trim().replace(/\/+$/, '');
- if (!(c in this._states)) {
- const d = join(this.root, c.replace(/^\/+/, ''));
- 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;
- }
- return this._states[c];
- }
- }
- // --- values ---------------------------------------------------------------------
- /** Empty value: null, '', [] or {}. */
- export function empty(v: unknown): boolean {
- if (v === null || v === undefined || v === '') return true;
- if (Array.isArray(v)) return v.length === 0;
- return typeof v === 'object' && Object.keys(v).length === 0;
- }
- /** The value as a list (a single value is a list of one). */
- export const values = (v: unknown): any[] => (Array.isArray(v) ? v : [v]);
- /** Names of the `options` of a select field (an option is `{name: ...}` or a plain value). */
- export function optionNames(spec: Head): Set<string> {
- const out = new Set<string>();
- const opts = Array.isArray(spec.options) ? spec.options : [];
- for (const o of opts)
- if (o && typeof o === 'object' && !Array.isArray(o)) {
- if (o.name !== null && o.name !== undefined) out.add(pystr(o.name));
- } else if (o !== null && o !== undefined) out.add(pystr(o));
- return out;
- }
- const DATE_RE = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
- /** An ISO date `YYYY-MM-DD`, optionally with a time. */
- export function isDate(v: unknown): boolean {
- if (v instanceof Date) return true;
- const s = pystr(v).trim();
- if (!DATE_RE.test(s)) return false;
- const [y, m, d] = s.slice(0, 10).split('-').map(Number);
- const t = new Date(Date.UTC(2000, m - 1, d));
- t.setUTCFullYear(y);
- return y >= 1 && t.getUTCFullYear() === y && t.getUTCMonth() === m - 1 && t.getUTCDate() === d;
- }
- export const isNumber = (v: unknown): boolean => typeof v === 'number';
- /** The value as text for a message, cut to `n` characters with «…». */
- export function short(v: unknown, n = 60): string {
- const c = [...pystr(v)];
- return c.length <= n ? c.join('') : c.slice(0, n - 1).join('') + '…';
- }
- /** A finding with a stable key `rule|record|field|code` (`field` in the result, `code` is the kind). */
- export function hole(res: Result, recAddr: string, field: string, kind: string, missing: string, fix: string): void {
- res.hole(recAddr, missing, fix, kind);
- res.holes[res.holes.length - 1].field = field;
- }
- export const holeKey = (ruleId: string, h: { record: string; field?: string; code?: string }): string => `${ruleId}|${h.record}|${h.field ?? ''}|${h.code ?? ''}`;
- /** (collection, field, spec) of the fields of these kinds in all collections that are read. */
- export function* iterFields(c: Ctx, kinds: string[]): Generator<[string, string, Head]> {
- for (const coll of c.wanted())
- for (const [name, spec] of Object.entries(c.props(coll)))
- if (spec && typeof spec === 'object' && kinds.includes((spec as Head).kind)) yield [coll, name, spec as Head];
- }
- /** Sets the scope of a rule to the records of the collections that are read; returns those collections. */
- export function scopeAll(c: Ctx, res: Result, what: string): string[] {
- const cols = c.wanted();
- res.scope = cols.flatMap((coll) => c.records(coll).map((r) => addr(r.id)));
- res.scopeText = `${what}: records of ${cols.length} collections by their schemas`;
- return cols;
- }