файл пакета→ .shtukbase/packages/collections/checks/s01_relations.ts
checks/s01_relations.ts
46 строк, 2.7 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // S1. Every value of a `kind: relation` field points to an existing record of the collection named in `collection`.
- // Kinds of findings: broken (no such file), wrong-collection (the file is not in that collection), not-multiple
- // (several values in a single-valued field), bad-value (the value is not a path).
- // A relation without `collection` (polymorphic, like enforcers of rules) is checked for existence only. A relation into
- // a collection the project does not have (a bridge into a layer not installed) sleeps and is not checked: the standard's
- // set had this as the no-collection finding; here it is not one, or any package with a bridge would fail in a project
- // without the second layer.
- import { addr, ctx, empty, hole, iterFields, scopeAll, short, values } from './lib/schemalib.ts';
- import { type Project, type Result, normPath, truthy } from './lib/speclib.ts';
- import { main } from './lib/runner.ts';
- export const RULE = { id: 's01', title: 'Schema: relations lead to existing records of the right collection', scope: 'all records of all collections, kind: relation fields' };
- export function check(p: Project, res: Result): void {
- const c = ctx(p);
- scopeAll(c, res, 'relations');
- if (!res.part('relations', null)) return;
- const files = c.files();
- const colls = new Set(c.collections());
- for (const [coll, name, spec] of iterFields(c, ['relation'])) {
- let target = String(truthy(spec.collection) ? spec.collection : '').trim().replace(/\/+$/, '');
- if (target.endsWith('.md')) target = target.slice(0, -3);
- if (target && !colls.has(target)) continue; // a bridge into a layer the project has not installed sleeps
- for (const r of c.records(coll)) {
- const v = r.fm[name];
- if (empty(v)) continue;
- const a = addr(r.id);
- if (!truthy(spec.multiple) && Array.isArray(v) && v.length > 1)
- hole(res, a, name, 'not-multiple', `${name}: ${v.length} values, but the field is single`, 'keep one value');
- for (const x of values(v)) {
- if (empty(x)) continue;
- if (typeof x === 'object' || typeof x === 'boolean' || typeof x === 'number') {
- hole(res, a, name, 'bad-value', `${name}: not a path, but ${short(x)}`, `replace with the path of a ${target} record: ${target}/…`);
- continue;
- }
- const path = normPath(x, name, r.id);
- if (!path || !files.has(path))
- hole(res, a, name, 'broken', `${name}: ${short(x)} — there is no such record`, 'fix the path or remove the reference');
- else if (target && !path.startsWith(target + '/'))
- hole(res, a, name, 'wrong-collection', `${name}: ${short(x)} is not from ${target}`, `refer to a record of ${target} or fix the schema`);
- }
- }
- }
- }
- if (import.meta.main) main({ RULE, check });