файл пакета→ .shtukbase/packages/design-components/lib/yaml.ts
lib/yaml.ts
41 строка, 2.1 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // A small YAML writer for the front matter of component pages: top-level keys one per line, lists and small maps in
- // flow style, a map of maps (controls) one entry per line. Output is always valid YAML that reads back to the same data
- // (the tests prove it), and it is deterministic: the same data gives the same text, so `fresh` can compare files.
- const RESERVED = new Set(['true', 'false', 'null', 'yes', 'no', 'on', 'off', 'y', 'n', '~']);
- const PLAIN = /^[A-Za-z_/][A-Za-z0-9_\-/.]*$/;
- const KEY = /^[A-Za-z_][A-Za-z0-9_-]*$/;
- export function scalar(v: unknown): string {
- if (v === null || v === undefined) return 'null';
- if (typeof v === 'boolean') return v ? 'true' : 'false';
- if (typeof v === 'number') return Number.isFinite(v) ? String(v) : 'null';
- const s = String(v);
- return PLAIN.test(s) && !RESERVED.has(s.toLowerCase()) ? s : JSON.stringify(s);
- }
- const key = (k: string) => (KEY.test(k) && !RESERVED.has(k.toLowerCase()) ? k : JSON.stringify(k));
- /** A value on one line: `[a, b]`, `{k: v}`, or a scalar. */
- export function flow(v: unknown): string {
- if (Array.isArray(v)) return `[${v.map(flow).join(', ')}]`;
- if (v && typeof v === 'object') {
- const e = Object.entries(v as Record<string, unknown>).filter(([, x]) => x !== undefined);
- return e.length ? `{${e.map(([k, x]) => `${key(k)}: ${flow(x)}`).join(', ')}}` : '{}';
- }
- return scalar(v);
- }
- /** `{a: 1, b: [x]}` → `a: 1\nb: [x]`; a map whose values are maps goes one entry per line under its key. */
- export function emit(data: Record<string, unknown>): string {
- const lines: string[] = [];
- for (const [k, v] of Object.entries(data)) {
- if (v === undefined) continue;
- const nested = v && typeof v === 'object' && !Array.isArray(v) && Object.values(v).length > 0 && Object.values(v).every((x) => x && typeof x === 'object' && !Array.isArray(x));
- if (nested) {
- lines.push(`${key(k)}:`);
- for (const [k2, v2] of Object.entries(v as Record<string, unknown>)) lines.push(` ${key(k2)}: ${flow(v2)}`);
- } else lines.push(`${key(k)}: ${flow(v)}`);
- }
- return lines.join('\n');
- }