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

server/fm.ts

105 lines, 4.9 KB.

  1. // Editing a page's front matter in place: only the fields that change are rewritten, every other line (order,
  2. // quotes, comments, blank lines) stays as it was. Values are written as YAML that reads back to the same value;
  3. // the caller gets an error instead of a page that would read back differently.
  4. import { parseYaml } from '../../collections/checks/lib/pages.ts';
  5. export type Fields = Record<string, unknown>;
  6. /** A page split into its front matter lines, the text between the closing `---` and the body, and the body. */
  7. export type Split = { has: boolean; lines: string[]; gap: string; body: string };
  8. const OPEN = /^---[ \t]*\r?\n/;
  9. export function split(text: string): Split {
  10. const t = text.replace(/^/, '');
  11. if (!OPEN.test(t)) return { has: false, lines: [], gap: '', body: t };
  12. const start = t.indexOf('\n') + 1;
  13. const close = /^---[ \t]*$/m;
  14. const rest = t.slice(start);
  15. const m = close.exec(rest);
  16. if (!m) return { has: false, lines: [], gap: '', body: t };
  17. const fm = rest.slice(0, m.index).replace(/\r?\n$/, '');
  18. const after = rest.slice(m.index + m[0].length);
  19. const gap = /^(\r?\n)*/.exec(after)![0];
  20. return { has: true, lines: fm === '' ? [] : fm.split(/\r?\n/), gap, body: after.slice(gap.length) };
  21. }
  22. export function join(s: Split): string {
  23. // gap holds the line break that ends the closing `---` and the blank lines before the body
  24. const head = ['---', ...s.lines, '---'].join('\n');
  25. const body = s.body.length && !s.body.endsWith('\n') ? s.body + '\n' : s.body;
  26. return head + (s.gap.includes('\n') ? s.gap : '\n') + body;
  27. }
  28. /** Front matter of the page as an object ({} when there is none). Throws on broken YAML. */
  29. export function fields(s: Split): Fields {
  30. if (!s.has || !s.lines.length) return {};
  31. const v = parseYaml(s.lines.join('\n'));
  32. if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error('the page header is not a set of fields');
  33. return v as Fields;
  34. }
  35. const KEY = /^(?:"([^"]+)"|'([^']+)'|([^\s:#'"-][^:#]*?)):(?:\s|$)/;
  36. /** [key, first line, last line + 1] of every top-level field. */
  37. function blocks(lines: string[]): [string, number, number][] {
  38. const out: [string, number, number][] = [];
  39. for (let i = 0; i < lines.length; i++) {
  40. const m = KEY.exec(lines[i]);
  41. if (!m) continue;
  42. let j = i + 1;
  43. // a field goes on while its lines are indented, block list items under it, or blank lines followed by more of it
  44. 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++;
  45. out.push([m[1] ?? m[2] ?? m[3].trim(), i, j]);
  46. i = j - 1;
  47. }
  48. return out;
  49. }
  50. 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;
  51. const PLAIN = /^[\p{L}\p{N}_/][\p{L}\p{N}_\-./ ]*$/u;
  52. const PLAIN_FLOW = /^[\p{L}\p{N}_/][\p{L}\p{N}_\-./]*$/u;
  53. function same(a: unknown, b: unknown): boolean {
  54. return JSON.stringify(a) === JSON.stringify(b);
  55. }
  56. /** A scalar or a list/map as one line of YAML. */
  57. export function yamlValue(v: unknown, flow = false): string {
  58. if (v === null || v === undefined) return 'null';
  59. if (typeof v === 'number' || typeof v === 'boolean') return String(v);
  60. if (typeof v === 'string') {
  61. const plain = flow ? PLAIN_FLOW : PLAIN;
  62. if (plain.test(v) && !v.endsWith(' ') && !RESERVED.test(v) && !/^\d{4}-\d{2}-\d{2}/.test(v)) return v;
  63. return JSON.stringify(v);
  64. }
  65. if (Array.isArray(v)) return '[' + v.map((x) => yamlValue(x, true)).join(', ') + ']';
  66. if (typeof v === 'object') return '{' + Object.entries(v as Fields).map(([k, x]) => `${yamlValue(k, true)}: ${yamlValue(x, true)}`).join(', ') + '}';
  67. return JSON.stringify(String(v));
  68. }
  69. /** Sets fields (null or undefined removes a field) and returns the new front matter lines. Throws when a value
  70. * would not read back as given. */
  71. export function setFields(s: Split, set: Fields): Split {
  72. let lines = [...s.lines];
  73. for (const [key, value] of Object.entries(set)) {
  74. if (!/^[\p{L}_][\p{L}\p{N}_\-.]*$/u.test(key)) throw new Error(`field name "${key}" does not fit: letters, digits, _ - .`);
  75. const b = blocks(lines).find(([k]) => k === key);
  76. const remove = value === null || value === undefined;
  77. const line = remove ? [] : [`${key}: ${yamlValue(value)}`];
  78. if (b) lines.splice(b[1], b[2] - b[1], ...line);
  79. else if (!remove) lines.push(...line);
  80. }
  81. const out = { ...s, has: true, lines };
  82. const back = fields(out);
  83. for (const [key, value] of Object.entries(set)) {
  84. const remove = value === null || value === undefined;
  85. if (remove ? key in back : !same(back[key], value)) throw new Error(`field "${key}" was not written as given`);
  86. }
  87. return out;
  88. }
  89. export function setBody(s: Split, body: string): Split {
  90. const gap = s.has && s.gap.includes('\n') ? s.gap : '\n\n';
  91. return { ...s, gap, body: body.replace(/^\n+/, '') };
  92. }