package file→ .shtukbase/packages/live/server/records.ts
server/records.ts
224 lines, 11.8 KB.
- // Collections and records of the project, and the check of a record against its collection's schema and the
- // contour of its phase field. The rules are those of the checks (collections s02/s03, contours c01/c03), applied
- // to one record before it is written, so a bad value never reaches the disk.
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
- import { join } from 'node:path';
- import { empty, isDate, isNumber, optionNames, values } from '../../collections/checks/lib/schemalib.ts';
- import { type Head, pystr, schemaProperties, truthy } from '../../collections/checks/lib/pages.ts';
- import { headOf, norm, phases } from '../../contours/checks/contourlib.ts';
- import { fields, split } from './fm.ts';
- /** A 422 answer: a message in Russian and, when it is about one field, that field. */
- export class Invalid extends Error {
- constructor(readonly errors: { field: string | null; message: string }[]) {
- super(errors.map((e) => e.message).join('; '));
- }
- }
- export class NotFound extends Error {}
- export class Refused extends Error {}
- const SKIP = new Set(['lib', 'deleted', 'node_modules', 'lab', 'runs', 'assets']);
- /** A project path like `/work/tasks/x.md`: no `..`, no dot or underscore steps. Throws when it is not one. */
- export function safePath(p: unknown): string {
- const s = '/' + pystr(p ?? '').trim().replace(/^\/+/, '');
- const steps = s.split('/').slice(1);
- if (s === '/' || steps.some((x) => x === '' || x === '..' || x.startsWith('.'))) throw new Refused(`path "${pystr(p)}" does not fit`);
- return s;
- }
- export type Collection = { path: string; title: string; itemType: string; props: Head; dir: string };
- /** Collections of the project: pages `type: Collection` at most one folder deep; their records are the `.md` files
- * of the folder of the same name. */
- export function collections(root: string): Collection[] {
- const out: Collection[] = [];
- const look = (rel: string) => {
- const d = join(root, rel);
- for (const n of readdirSync(d).sort()) {
- if (n.startsWith('.') || n.startsWith('_') || SKIP.has(n)) continue;
- const f = join(d, n);
- const st = statSync(f, { throwIfNoEntry: false });
- if (!st) continue;
- if (st.isDirectory() && rel === '') look(n);
- else if (st.isFile() && n.endsWith('.md')) {
- const head = readFileSync(f, 'utf8').slice(0, 4096);
- const end = head.indexOf('\n---', 3);
- if (!head.startsWith('---') || !/^type:\s*["']?Collection["']?\s*$/m.test(head.slice(0, end > 0 ? end : undefined))) continue;
- const path = '/' + (rel ? rel + '/' : '') + n.slice(0, -3);
- const h = headOf(root, path + '.md');
- const items = h.items && typeof h.items === 'object' ? (h.items as Head) : {};
- const dir = typeof items.path === 'string' && items.recursive !== true ? norm(items.path) : path;
- out.push({ path, title: pystr(h.title ?? path), itemType: pystr(h.itemType ?? ''), props: schemaProperties(root, path.slice(1) + '.md'), dir });
- }
- }
- };
- look('');
- return out;
- }
- export function collection(root: string, path: unknown): Collection {
- const p = norm(path);
- const c = collections(root).find((x) => x.path === p);
- if (!c) throw new NotFound(`there is no collection ${p || '(empty)'}`);
- return c;
- }
- /** The collection a record path belongs to (its folder), or null. */
- export function collectionOf(root: string, path: string): Collection | null {
- const dir = path.slice(0, path.lastIndexOf('/'));
- return collections(root).find((c) => c.dir === dir) ?? null;
- }
- export function recordPaths(root: string, c: Collection): string[] {
- const d = join(root, c.dir.slice(1));
- if (!existsSync(d)) return [];
- return readdirSync(d).filter((n) => n.endsWith('.md') && !n.startsWith('.')).sort().map((n) => `${c.dir}/${n}`);
- }
- export function readRecord(root: string, path: string): { text: string; fm: Head; body: string } {
- const f = join(root, path.slice(1));
- if (!existsSync(f) || !statSync(f).isFile()) throw new NotFound(`there is no record ${path}`);
- const text = readFileSync(f, 'utf8');
- const s = split(text);
- let fm: Head = {};
- try {
- fm = fields(s);
- } catch {
- fm = {};
- }
- return { text, fm, body: s.body };
- }
- // ---------- the schema ----------
- const label = (spec: Head, name: string) => (spec && spec.label ? `"${pystr(spec.label)}" (${name})` : `"${name}"`);
- /** The contour of a phase field: its phases, the entry phase, and the exits of each phase with their gates. */
- function contourOf(root: string, spec: Head) {
- const contour = norm(spec.contour);
- const have = phases(root, contour);
- const entry = norm(headOf(root, contour + '.md').entry);
- return { contour, have, entry: entry.startsWith(contour + '/') ? entry.slice(contour.length + 1) : '' };
- }
- function exitsOf(phaseHead: Head, contour: string): { to: string; needs: string[] }[] {
- const out: { to: string; needs: string[] }[] = [];
- for (const x of values(truthy(phaseHead.next) ? phaseHead.next : [])) {
- const isObj = x && typeof x === 'object' && !Array.isArray(x);
- const to = norm(isObj ? x.to : x);
- if (!to.startsWith(contour + '/')) continue;
- out.push({ to: to.slice(contour.length + 1), needs: isObj && !empty(x.needs) ? values(x.needs).map(pystr) : [] });
- }
- return out;
- }
- /** Checks a record (its new fields; `old` is null for a new record) against the collection. Returns the fields with
- * the entry phase filled in for a new record; throws Invalid with every problem found. */
- export function validate(root: string, c: Collection, old: Head | null, fm: Head): Head {
- const errs: { field: string | null; message: string }[] = [];
- const out = { ...fm };
- const bad = (field: string | null, message: string) => errs.push({ field, message });
- // only what this write changes is judged: an old problem elsewhere in the record does not block an edit
- const changed = (name: string) => old === null || JSON.stringify(old[name]) !== JSON.stringify(out[name]);
- if (changed('title') && empty(out.title)) bad('title', 'A title is required (title).');
- for (const [name, spec0] of Object.entries(c.props)) {
- if (!spec0 || typeof spec0 !== 'object' || Array.isArray(spec0)) continue;
- const spec = spec0 as Head;
- const kind = pystr(spec.kind ?? '');
- if (kind === 'phase') {
- const { contour, have, entry } = contourOf(root, spec);
- if (!have || !have.size) continue; // the contour is broken: the contours checks say so
- if (old === null && empty(out[name]) && entry) out[name] = entry;
- const v = out[name];
- if (empty(v) || !changed(name)) continue;
- const next = pystr(v);
- const ph = (n: string) => (have.get(n)?.title ? `"${pystr(have.get(n)!.title)}" (${n})` : `"${n}"`);
- if (typeof v === 'object' || !have.has(next)) {
- bad(name, `Field ${label(spec, name)}: the contour ${contour} has no state "${next}". Available: ${[...have.keys()].map(ph).join(', ')}.`);
- continue;
- }
- if (old === null) {
- if (entry && next !== entry) bad(name, `A new record starts in the state ${ph(entry)}, the entry of the contour ${contour}, not in ${ph(next)}.`);
- continue;
- }
- const prev = old[name];
- if (empty(prev) || typeof prev === 'object' || pystr(prev) === next || !have.has(pystr(prev))) continue;
- const from = pystr(prev);
- const ways = exitsOf(have.get(from)!, contour);
- const way = ways.find((w) => w.to === next);
- if (!way && have.get(next)!.fromAnywhere !== true) {
- bad(name, `There is no transition ${ph(from)} → ${ph(next)} in the contour ${contour}. From ${ph(from)} you can go to: ${ways.map((w) => ph(w.to)).join(', ') || 'nowhere (this is the end)'}.`);
- continue;
- }
- for (const need of way ? way.needs : [])
- if (empty(out[need])) bad(need, `To move to ${ph(next)}, fill in the field ${label((c.props[need] as Head) ?? {}, need)}.`);
- continue;
- }
- const v = out[name];
- if (empty(v)) {
- if (spec.required === true && changed(name)) bad(name, `Field ${label(spec, name)} is required.`);
- const when = spec.requiredWhen;
- if (when && typeof when === 'object' && !Array.isArray(when))
- for (const [f, vals] of Object.entries(when)) {
- const cur = out[f];
- if ((changed(name) || changed(f)) && !empty(cur) && values(vals).map(pystr).includes(pystr(cur))) {
- bad(name, `Field ${label(spec, name)} is required when ${f} = ${pystr(cur)}.`);
- break;
- }
- }
- continue;
- }
- if (!['select', 'date', 'number', 'checkbox', 'relation'].includes(kind) || !changed(name)) continue;
- const multiple = truthy(spec.multiple);
- if (Array.isArray(v) && !multiple && v.length !== 1) {
- bad(name, `Field ${label(spec, name)} takes one value, but a list was given.`);
- continue;
- }
- const allowed = kind === 'select' ? optionNames(spec) : new Set<string>();
- for (const x of values(v)) {
- if (kind === 'select' && allowed.size && (typeof x === 'object' || !allowed.has(pystr(x))))
- bad(name, `Field ${label(spec, name)}: "${pystr(x)}" is not an option. Allowed: ${[...allowed].join(', ')}.`);
- else if (kind === 'date' && !isDate(x)) bad(name, `Field ${label(spec, name)}: "${pystr(x)}" is not a date. A date YYYY-MM-DD is needed.`);
- else if (kind === 'number' && !isNumber(x)) bad(name, `Field ${label(spec, name)}: "${pystr(x)}" is not a number.`);
- else if (kind === 'checkbox' && typeof x !== 'boolean') bad(name, `Field ${label(spec, name)}: true or false is needed.`);
- else if (kind === 'relation' && !empty(spec.collection)) {
- const coll = norm(spec.collection);
- const raw = pystr(x).trim().replace(/\.md$/, '');
- const target = (raw.includes('/') ? '/' + raw.replace(/^\/+/, '') : `${coll}/${raw}`) + '.md';
- if (!target.startsWith(coll + '/') || !existsSync(join(root, target.slice(1))))
- bad(name, `Field ${label(spec, name)}: "${pystr(x)}" is not a record of the collection ${coll}.`);
- }
- }
- }
- if (errs.length) throw new Invalid(errs);
- return out;
- }
- // Cyrillic letters are written as code points, so that titles in Russian still get a latin file name.
- const TRANSLIT: Record<string, string> = Object.fromEntries(
- '\u0430:a \u0431:b \u0432:v \u0433:g \u0434:d \u0435:e \u0451:e \u0436:zh \u0437:z \u0438:i \u0439:i \u043a:k \u043b:l \u043c:m \u043d:n \u043e:o \u043f:p \u0440:r \u0441:s \u0442:t \u0443:u \u0444:f \u0445:h \u0446:ts \u0447:ch \u0448:sh \u0449:sch \u044a: \u044b:y \u044c: \u044d:e \u044e:yu \u044f:ya'
- .split(' ').map((p) => p.split(':') as [string, string]),
- );
- /** A file name for a new record from its title: latin letters, digits and dashes, at most 60 characters. */
- export function slug(title: string): string {
- const s = [...title.toLowerCase()].map((ch) => TRANSLIT[ch] ?? ch).join('')
- .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60).replace(/-+$/, '');
- return s || 'record';
- }
- /** The phases of every phase field of a collection, in the contour's order: {field: [{name, title, next}]}. */
- export function phasesOf(root: string, c: Collection): Record<string, { name: string; title: string; next: string[]; entry: boolean }[]> {
- const out: Record<string, { name: string; title: string; next: string[]; entry: boolean }[]> = {};
- for (const [name, spec0] of Object.entries(c.props)) {
- const spec = spec0 as Head;
- if (!spec || typeof spec !== 'object' || spec.kind !== 'phase') continue;
- const { contour, have, entry } = contourOf(root, spec);
- if (!have) continue;
- const order = values(headOf(root, contour + '.md').phases ?? []).map((p) => norm(p)).filter((p) => p.startsWith(contour + '/')).map((p) => p.slice(contour.length + 1));
- const names = [...order.filter((n) => have.has(n)), ...[...have.keys()].filter((n) => !order.includes(n))];
- out[name] = names.map((n) => ({ name: n, title: pystr(have.get(n)!.title ?? n), next: exitsOf(have.get(n)!, contour).map((w) => w.to), entry: n === entry }));
- }
- return out;
- }