ShtukbaseStandard
package file→ .shtukbase/packages/live/server/records.ts

server/records.ts

224 lines, 11.8 KB.

  1. // Collections and records of the project, and the check of a record against its collection's schema and the
  2. // contour of its phase field. The rules are those of the checks (collections s02/s03, contours c01/c03), applied
  3. // to one record before it is written, so a bad value never reaches the disk.
  4. import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
  5. import { join } from 'node:path';
  6. import { empty, isDate, isNumber, optionNames, values } from '../../collections/checks/lib/schemalib.ts';
  7. import { type Head, pystr, schemaProperties, truthy } from '../../collections/checks/lib/pages.ts';
  8. import { headOf, norm, phases } from '../../contours/checks/contourlib.ts';
  9. import { fields, split } from './fm.ts';
  10. /** A 422 answer: a message in Russian and, when it is about one field, that field. */
  11. export class Invalid extends Error {
  12. constructor(readonly errors: { field: string | null; message: string }[]) {
  13. super(errors.map((e) => e.message).join('; '));
  14. }
  15. }
  16. export class NotFound extends Error {}
  17. export class Refused extends Error {}
  18. const SKIP = new Set(['lib', 'deleted', 'node_modules', 'lab', 'runs', 'assets']);
  19. /** A project path like `/work/tasks/x.md`: no `..`, no dot or underscore steps. Throws when it is not one. */
  20. export function safePath(p: unknown): string {
  21. const s = '/' + pystr(p ?? '').trim().replace(/^\/+/, '');
  22. const steps = s.split('/').slice(1);
  23. if (s === '/' || steps.some((x) => x === '' || x === '..' || x.startsWith('.'))) throw new Refused(`path "${pystr(p)}" does not fit`);
  24. return s;
  25. }
  26. export type Collection = { path: string; title: string; itemType: string; props: Head; dir: string };
  27. /** Collections of the project: pages `type: Collection` at most one folder deep; their records are the `.md` files
  28. * of the folder of the same name. */
  29. export function collections(root: string): Collection[] {
  30. const out: Collection[] = [];
  31. const look = (rel: string) => {
  32. const d = join(root, rel);
  33. for (const n of readdirSync(d).sort()) {
  34. if (n.startsWith('.') || n.startsWith('_') || SKIP.has(n)) continue;
  35. const f = join(d, n);
  36. const st = statSync(f, { throwIfNoEntry: false });
  37. if (!st) continue;
  38. if (st.isDirectory() && rel === '') look(n);
  39. else if (st.isFile() && n.endsWith('.md')) {
  40. const head = readFileSync(f, 'utf8').slice(0, 4096);
  41. const end = head.indexOf('\n---', 3);
  42. if (!head.startsWith('---') || !/^type:\s*["']?Collection["']?\s*$/m.test(head.slice(0, end > 0 ? end : undefined))) continue;
  43. const path = '/' + (rel ? rel + '/' : '') + n.slice(0, -3);
  44. const h = headOf(root, path + '.md');
  45. const items = h.items && typeof h.items === 'object' ? (h.items as Head) : {};
  46. const dir = typeof items.path === 'string' && items.recursive !== true ? norm(items.path) : path;
  47. out.push({ path, title: pystr(h.title ?? path), itemType: pystr(h.itemType ?? ''), props: schemaProperties(root, path.slice(1) + '.md'), dir });
  48. }
  49. }
  50. };
  51. look('');
  52. return out;
  53. }
  54. export function collection(root: string, path: unknown): Collection {
  55. const p = norm(path);
  56. const c = collections(root).find((x) => x.path === p);
  57. if (!c) throw new NotFound(`there is no collection ${p || '(empty)'}`);
  58. return c;
  59. }
  60. /** The collection a record path belongs to (its folder), or null. */
  61. export function collectionOf(root: string, path: string): Collection | null {
  62. const dir = path.slice(0, path.lastIndexOf('/'));
  63. return collections(root).find((c) => c.dir === dir) ?? null;
  64. }
  65. export function recordPaths(root: string, c: Collection): string[] {
  66. const d = join(root, c.dir.slice(1));
  67. if (!existsSync(d)) return [];
  68. return readdirSync(d).filter((n) => n.endsWith('.md') && !n.startsWith('.')).sort().map((n) => `${c.dir}/${n}`);
  69. }
  70. export function readRecord(root: string, path: string): { text: string; fm: Head; body: string } {
  71. const f = join(root, path.slice(1));
  72. if (!existsSync(f) || !statSync(f).isFile()) throw new NotFound(`there is no record ${path}`);
  73. const text = readFileSync(f, 'utf8');
  74. const s = split(text);
  75. let fm: Head = {};
  76. try {
  77. fm = fields(s);
  78. } catch {
  79. fm = {};
  80. }
  81. return { text, fm, body: s.body };
  82. }
  83. // ---------- the schema ----------
  84. const label = (spec: Head, name: string) => (spec && spec.label ? `"${pystr(spec.label)}" (${name})` : `"${name}"`);
  85. /** The contour of a phase field: its phases, the entry phase, and the exits of each phase with their gates. */
  86. function contourOf(root: string, spec: Head) {
  87. const contour = norm(spec.contour);
  88. const have = phases(root, contour);
  89. const entry = norm(headOf(root, contour + '.md').entry);
  90. return { contour, have, entry: entry.startsWith(contour + '/') ? entry.slice(contour.length + 1) : '' };
  91. }
  92. function exitsOf(phaseHead: Head, contour: string): { to: string; needs: string[] }[] {
  93. const out: { to: string; needs: string[] }[] = [];
  94. for (const x of values(truthy(phaseHead.next) ? phaseHead.next : [])) {
  95. const isObj = x && typeof x === 'object' && !Array.isArray(x);
  96. const to = norm(isObj ? x.to : x);
  97. if (!to.startsWith(contour + '/')) continue;
  98. out.push({ to: to.slice(contour.length + 1), needs: isObj && !empty(x.needs) ? values(x.needs).map(pystr) : [] });
  99. }
  100. return out;
  101. }
  102. /** Checks a record (its new fields; `old` is null for a new record) against the collection. Returns the fields with
  103. * the entry phase filled in for a new record; throws Invalid with every problem found. */
  104. export function validate(root: string, c: Collection, old: Head | null, fm: Head): Head {
  105. const errs: { field: string | null; message: string }[] = [];
  106. const out = { ...fm };
  107. const bad = (field: string | null, message: string) => errs.push({ field, message });
  108. // only what this write changes is judged: an old problem elsewhere in the record does not block an edit
  109. const changed = (name: string) => old === null || JSON.stringify(old[name]) !== JSON.stringify(out[name]);
  110. if (changed('title') && empty(out.title)) bad('title', 'A title is required (title).');
  111. for (const [name, spec0] of Object.entries(c.props)) {
  112. if (!spec0 || typeof spec0 !== 'object' || Array.isArray(spec0)) continue;
  113. const spec = spec0 as Head;
  114. const kind = pystr(spec.kind ?? '');
  115. if (kind === 'phase') {
  116. const { contour, have, entry } = contourOf(root, spec);
  117. if (!have || !have.size) continue; // the contour is broken: the contours checks say so
  118. if (old === null && empty(out[name]) && entry) out[name] = entry;
  119. const v = out[name];
  120. if (empty(v) || !changed(name)) continue;
  121. const next = pystr(v);
  122. const ph = (n: string) => (have.get(n)?.title ? `"${pystr(have.get(n)!.title)}" (${n})` : `"${n}"`);
  123. if (typeof v === 'object' || !have.has(next)) {
  124. bad(name, `Field ${label(spec, name)}: the contour ${contour} has no state "${next}". Available: ${[...have.keys()].map(ph).join(', ')}.`);
  125. continue;
  126. }
  127. if (old === null) {
  128. 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)}.`);
  129. continue;
  130. }
  131. const prev = old[name];
  132. if (empty(prev) || typeof prev === 'object' || pystr(prev) === next || !have.has(pystr(prev))) continue;
  133. const from = pystr(prev);
  134. const ways = exitsOf(have.get(from)!, contour);
  135. const way = ways.find((w) => w.to === next);
  136. if (!way && have.get(next)!.fromAnywhere !== true) {
  137. 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)'}.`);
  138. continue;
  139. }
  140. for (const need of way ? way.needs : [])
  141. if (empty(out[need])) bad(need, `To move to ${ph(next)}, fill in the field ${label((c.props[need] as Head) ?? {}, need)}.`);
  142. continue;
  143. }
  144. const v = out[name];
  145. if (empty(v)) {
  146. if (spec.required === true && changed(name)) bad(name, `Field ${label(spec, name)} is required.`);
  147. const when = spec.requiredWhen;
  148. if (when && typeof when === 'object' && !Array.isArray(when))
  149. for (const [f, vals] of Object.entries(when)) {
  150. const cur = out[f];
  151. if ((changed(name) || changed(f)) && !empty(cur) && values(vals).map(pystr).includes(pystr(cur))) {
  152. bad(name, `Field ${label(spec, name)} is required when ${f} = ${pystr(cur)}.`);
  153. break;
  154. }
  155. }
  156. continue;
  157. }
  158. if (!['select', 'date', 'number', 'checkbox', 'relation'].includes(kind) || !changed(name)) continue;
  159. const multiple = truthy(spec.multiple);
  160. if (Array.isArray(v) && !multiple && v.length !== 1) {
  161. bad(name, `Field ${label(spec, name)} takes one value, but a list was given.`);
  162. continue;
  163. }
  164. const allowed = kind === 'select' ? optionNames(spec) : new Set<string>();
  165. for (const x of values(v)) {
  166. if (kind === 'select' && allowed.size && (typeof x === 'object' || !allowed.has(pystr(x))))
  167. bad(name, `Field ${label(spec, name)}: "${pystr(x)}" is not an option. Allowed: ${[...allowed].join(', ')}.`);
  168. 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.`);
  169. else if (kind === 'number' && !isNumber(x)) bad(name, `Field ${label(spec, name)}: "${pystr(x)}" is not a number.`);
  170. else if (kind === 'checkbox' && typeof x !== 'boolean') bad(name, `Field ${label(spec, name)}: true or false is needed.`);
  171. else if (kind === 'relation' && !empty(spec.collection)) {
  172. const coll = norm(spec.collection);
  173. const raw = pystr(x).trim().replace(/\.md$/, '');
  174. const target = (raw.includes('/') ? '/' + raw.replace(/^\/+/, '') : `${coll}/${raw}`) + '.md';
  175. if (!target.startsWith(coll + '/') || !existsSync(join(root, target.slice(1))))
  176. bad(name, `Field ${label(spec, name)}: "${pystr(x)}" is not a record of the collection ${coll}.`);
  177. }
  178. }
  179. }
  180. if (errs.length) throw new Invalid(errs);
  181. return out;
  182. }
  183. // Cyrillic letters are written as code points, so that titles in Russian still get a latin file name.
  184. const TRANSLIT: Record<string, string> = Object.fromEntries(
  185. '\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'
  186. .split(' ').map((p) => p.split(':') as [string, string]),
  187. );
  188. /** A file name for a new record from its title: latin letters, digits and dashes, at most 60 characters. */
  189. export function slug(title: string): string {
  190. const s = [...title.toLowerCase()].map((ch) => TRANSLIT[ch] ?? ch).join('')
  191. .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60).replace(/-+$/, '');
  192. return s || 'record';
  193. }
  194. /** The phases of every phase field of a collection, in the contour's order: {field: [{name, title, next}]}. */
  195. export function phasesOf(root: string, c: Collection): Record<string, { name: string; title: string; next: string[]; entry: boolean }[]> {
  196. const out: Record<string, { name: string; title: string; next: string[]; entry: boolean }[]> = {};
  197. for (const [name, spec0] of Object.entries(c.props)) {
  198. const spec = spec0 as Head;
  199. if (!spec || typeof spec !== 'object' || spec.kind !== 'phase') continue;
  200. const { contour, have, entry } = contourOf(root, spec);
  201. if (!have) continue;
  202. const order = values(headOf(root, contour + '.md').phases ?? []).map((p) => norm(p)).filter((p) => p.startsWith(contour + '/')).map((p) => p.slice(contour.length + 1));
  203. const names = [...order.filter((n) => have.has(n)), ...[...have.keys()].filter((n) => !order.includes(n))];
  204. 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 }));
  205. }
  206. return out;
  207. }