файл пакета→ .shtukbase/packages/quality/checks/lib/qlib.ts
checks/lib/qlib.ts
122 строки, 5.2 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // The shared part of the checks of the quality packages (quality, risks, testing).
- // On import it adds the record types of the layer "Quality" to the type map of speclib (the collections package),
- // as tasks/checks/lib/worklib.ts does for the layer "Work". Collections are found by the itemType of their page,
- // never by path; a relation field by the collection it leads to. Installed side by side in .shtukbase/packages/:
- // quality -> norms-core -> contours -> frame -> collections.
- import { type Project, type Rec, type Result, SchemaError, TYPES, TYPE_LABEL, addr, pystr } from '../../../collections/checks/lib/speclib.ts';
- export { addr };
- Object.assign(TYPES, {
- RISK: ['SystemRisk', 'Risk'],
- IND: ['Indicator'],
- MEAS: ['Measurement'],
- OUT: ['Outcome'],
- ASM: ['Assumption'],
- DS: ['Dataset'],
- QRUN: ['QualityRun'], // not RUN: that key is the agent run log of agents/lib/factlib.ts (type Run)
- QTEST: ['QualityTest'],
- AGENT: ['ProductAgent', 'Agent'],
- GOAL: ['Goal'],
- DEC: ['Decision'],
- });
- Object.assign(TYPE_LABEL, {
- RISK: 'risks', IND: 'indicators', MEAS: 'measurements', OUT: 'benefit in operation', ASM: 'assumptions', DS: 'datasets',
- QRUN: 'runs', QTEST: 'quality tests', AGENT: 'product agents', GOAL: 'goals', DEC: 'decisions',
- });
- /** Is the field filled: a list with a non-blank item, or a value that is not null, false or blank. */
- export function has(rec: Rec, field: string): boolean {
- const v = rec.fm[field];
- if (Array.isArray(v)) return v.some((x) => x !== null && x !== undefined && pystr(x).trim() !== '');
- if (v instanceof Date) return true;
- return v !== null && v !== undefined && v !== false && pystr(v).trim() !== '';
- }
- /** The fields of the list that are not filled. */
- export function missing(rec: Rec, fields: string[]): string[] {
- return fields.filter((f) => !has(rec, f));
- }
- /** The state of a record: the phase name without the folder and the `.md` end ('' when none). */
- export function state(rec: Rec, field = 'status'): string {
- const v = rec.fm[field];
- const s = v === null || v === undefined ? '' : pystr(v).trim().replace(/^["']|["']$/g, '');
- const last = s.split('/').pop() ?? '';
- return last.endsWith('.md') ? last.slice(0, -3) : last;
- }
- /** A date value as `YYYY-MM-DD`, or null when it is not a date. */
- export function day(v: unknown): string | null {
- if (v instanceof Date) return isNaN(v.getTime()) ? null : v.toISOString().slice(0, 10);
- const m = /^(\d{4}-\d{2}-\d{2})/.exec(pystr(v ?? '').trim());
- return m ? m[1] : null;
- }
- /** Today as `YYYY-MM-DD`; QUALITY_TODAY overrides it (for tests). */
- export function today(): string {
- return day(process.env.QUALITY_TODAY) ?? new Date().toISOString().slice(0, 10);
- }
- /** Days from a to b (both `YYYY-MM-DD`). */
- export function daysBetween(a: string, b: string): number {
- return Math.round((Date.parse(b + 'T00:00:00Z') - Date.parse(a + 'T00:00:00Z')) / 86_400_000);
- }
- /** A number value, or null. */
- export function num(v: unknown): number | null {
- if (typeof v === 'number') return Number.isFinite(v) ? v : null;
- const s = pystr(v ?? '').trim();
- if (!/^-?\d+(\.\d+)?$/.test(s)) return null;
- return Number(s);
- }
- /** Is the record live by its state category: arriving or working (or no contour / unknown phase). */
- export function live(p: Project, rec: Rec, key: string): boolean {
- const c = p.category(rec, key);
- return c === null || c === '?' || c === 'arriving' || c === 'working';
- }
- /** The relation field src → dst by the schema, or the fallback name when the schema has none. */
- export function fld(p: Project, src: string, dst: string, fallback: string): string {
- try {
- return p.field(src, dst, fallback) ?? fallback;
- } catch (e) {
- if (!(e instanceof SchemaError)) throw e;
- return fallback;
- }
- }
- /** Values of a relation field as project paths, even when the target collection is not installed. */
- export function refs(p: Project, rec: Rec, field: string, dst: string): string[] {
- if (p.coll(dst)) return p.links(rec, field, dst);
- const v = rec.fm[field];
- const out: string[] = [];
- for (const x of Array.isArray(v) ? v : v === null || v === undefined || v === '' ? [] : [v]) {
- let s = pystr(x).trim().replace(/^["']+|["']+$/g, '');
- const m = /^\[[^\]]*\]\(([^)]+)\)$/.exec(s);
- if (m) s = m[1];
- if (s) out.push(s.startsWith('/') ? s : '/' + s);
- }
- return out;
- }
- /** One requirement on the fields of the records of a type: when `when` holds, `fields` must be filled. */
- export type FieldRule = { when: (rec: Rec) => boolean; fields: string[]; why: string; fix: string; code: string };
- /** Checks the records of a type key against field rules; the scope is every record a rule applies to. */
- export function checkFields(p: Project, res: Result, key: string, rules: FieldRule[]): void {
- const reason = p.need(key);
- res.part(TYPE_LABEL[key], reason);
- if (reason) return;
- const scope = new Set<string>();
- for (const r of p.records(key)) {
- for (const rule of rules) {
- if (!rule.when(r)) continue;
- scope.add(addr(r.id));
- const gap = missing(r, rule.fields);
- if (gap.length) res.hole(addr(r.id), `${p.label(r, key)}: ${rule.why} — not filled: ${gap.join(', ')}`, rule.fix, rule.code);
- }
- }
- res.scope = [...scope];
- }