package file→ .shtukbase/packages/live/server/fm.ts
server/fm.ts
105 lines, 4.9 KB.
- // Editing a page's front matter in place: only the fields that change are rewritten, every other line (order,
- // quotes, comments, blank lines) stays as it was. Values are written as YAML that reads back to the same value;
- // the caller gets an error instead of a page that would read back differently.
- import { parseYaml } from '../../collections/checks/lib/pages.ts';
- export type Fields = Record<string, unknown>;
- /** A page split into its front matter lines, the text between the closing `---` and the body, and the body. */
- export type Split = { has: boolean; lines: string[]; gap: string; body: string };
- const OPEN = /^---[ \t]*\r?\n/;
- export function split(text: string): Split {
- const t = text.replace(/^/, '');
- if (!OPEN.test(t)) return { has: false, lines: [], gap: '', body: t };
- const start = t.indexOf('\n') + 1;
- const close = /^---[ \t]*$/m;
- const rest = t.slice(start);
- const m = close.exec(rest);
- if (!m) return { has: false, lines: [], gap: '', body: t };
- const fm = rest.slice(0, m.index).replace(/\r?\n$/, '');
- const after = rest.slice(m.index + m[0].length);
- const gap = /^(\r?\n)*/.exec(after)![0];
- return { has: true, lines: fm === '' ? [] : fm.split(/\r?\n/), gap, body: after.slice(gap.length) };
- }
- export function join(s: Split): string {
- // gap holds the line break that ends the closing `---` and the blank lines before the body
- const head = ['---', ...s.lines, '---'].join('\n');
- const body = s.body.length && !s.body.endsWith('\n') ? s.body + '\n' : s.body;
- return head + (s.gap.includes('\n') ? s.gap : '\n') + body;
- }
- /** Front matter of the page as an object ({} when there is none). Throws on broken YAML. */
- export function fields(s: Split): Fields {
- if (!s.has || !s.lines.length) return {};
- const v = parseYaml(s.lines.join('\n'));
- if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error('the page header is not a set of fields');
- return v as Fields;
- }
- const KEY = /^(?:"([^"]+)"|'([^']+)'|([^\s:#'"-][^:#]*?)):(?:\s|$)/;
- /** [key, first line, last line + 1] of every top-level field. */
- function blocks(lines: string[]): [string, number, number][] {
- const out: [string, number, number][] = [];
- for (let i = 0; i < lines.length; i++) {
- const m = KEY.exec(lines[i]);
- if (!m) continue;
- let j = i + 1;
- // a field goes on while its lines are indented, block list items under it, or blank lines followed by more of it
- while (j < lines.length && (/^[ \t]/.test(lines[j]) || /^- /.test(lines[j]) || lines[j] === '-' || (lines[j].trim() === '' && j + 1 < lines.length && /^[ \t-]/.test(lines[j + 1])))) j++;
- out.push([m[1] ?? m[2] ?? m[3].trim(), i, j]);
- i = j - 1;
- }
- return out;
- }
- const RESERVED = /^(true|false|null|yes|no|on|off|y|n|~|[-+]?(\d[\d_]*)?(\.\d*)?([eE][-+]?\d+)?|0x[0-9a-f]+|0o[0-7]+|[-+]?\.(inf|nan))$/i;
- const PLAIN = /^[\p{L}\p{N}_/][\p{L}\p{N}_\-./ ]*$/u;
- const PLAIN_FLOW = /^[\p{L}\p{N}_/][\p{L}\p{N}_\-./]*$/u;
- function same(a: unknown, b: unknown): boolean {
- return JSON.stringify(a) === JSON.stringify(b);
- }
- /** A scalar or a list/map as one line of YAML. */
- export function yamlValue(v: unknown, flow = false): string {
- if (v === null || v === undefined) return 'null';
- if (typeof v === 'number' || typeof v === 'boolean') return String(v);
- if (typeof v === 'string') {
- const plain = flow ? PLAIN_FLOW : PLAIN;
- if (plain.test(v) && !v.endsWith(' ') && !RESERVED.test(v) && !/^\d{4}-\d{2}-\d{2}/.test(v)) return v;
- return JSON.stringify(v);
- }
- if (Array.isArray(v)) return '[' + v.map((x) => yamlValue(x, true)).join(', ') + ']';
- if (typeof v === 'object') return '{' + Object.entries(v as Fields).map(([k, x]) => `${yamlValue(k, true)}: ${yamlValue(x, true)}`).join(', ') + '}';
- return JSON.stringify(String(v));
- }
- /** Sets fields (null or undefined removes a field) and returns the new front matter lines. Throws when a value
- * would not read back as given. */
- export function setFields(s: Split, set: Fields): Split {
- let lines = [...s.lines];
- for (const [key, value] of Object.entries(set)) {
- if (!/^[\p{L}_][\p{L}\p{N}_\-.]*$/u.test(key)) throw new Error(`field name "${key}" does not fit: letters, digits, _ - .`);
- const b = blocks(lines).find(([k]) => k === key);
- const remove = value === null || value === undefined;
- const line = remove ? [] : [`${key}: ${yamlValue(value)}`];
- if (b) lines.splice(b[1], b[2] - b[1], ...line);
- else if (!remove) lines.push(...line);
- }
- const out = { ...s, has: true, lines };
- const back = fields(out);
- for (const [key, value] of Object.entries(set)) {
- const remove = value === null || value === undefined;
- if (remove ? key in back : !same(back[key], value)) throw new Error(`field "${key}" was not written as given`);
- }
- return out;
- }
- export function setBody(s: Split, body: string): Split {
- const gap = s.has && s.gap.includes('\n') ? s.gap : '\n\n';
- return { ...s, gap, body: body.replace(/^\n+/, '') };
- }