archivo del paquete→ .shtukbase/packages/design-components/lib/header.ts
lib/header.ts
223 líneas, 11.3 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // The component header: one YAML block in the first comment of a component file, `<!---` … `--->` in HTML and
- // `/*---` … `---*/` in TS/TSX/JS (build contract of the wave DSN, section 4; the control schema is section 5).
- // One parser for both; other packages (the HTML and React libraries) import it to test their own headers:
- // import { parseHeader } from '../../design-components/lib/header.ts';
- // Pure: no files are read except by `readHeader`. Bun only, no dependencies (Bun has a YAML parser built in).
- import { readFileSync } from 'node:fs';
- export const LEVELS = ['primitive', 'composite', 'block', 'shell', 'page'] as const;
- export type Level = (typeof LEVELS)[number];
- /** The shadcn registry type of each level (design: "Naming: what comes from shadcn"). */
- export const REGISTRY_TYPES: Record<Level, string> = {
- primitive: 'registry:ui',
- composite: 'registry:component',
- block: 'registry:block',
- shell: 'registry:block',
- page: 'registry:page',
- };
- export const CONTROL_KINDS = ['select', 'segment', 'bool', 'range', 'swatch', 'text'] as const;
- export type ControlKind = (typeof CONTROL_KINDS)[number];
- export type Control = {
- kind: ControlKind;
- label?: string;
- options?: (string | number)[];
- default?: string | number | boolean;
- min?: number;
- max?: number;
- step?: number;
- unit?: string;
- section?: string;
- colors?: unknown;
- };
- export type Header = {
- id: string;
- title: string;
- level: Level;
- description: string;
- uses: string[];
- parts: string[];
- states: string[];
- status: string[];
- controls: Record<string, Control>;
- cssProperties: string[];
- };
- export type Parsed = {
- /** The header as data, or null when the comment is missing or has problems. */
- header: Header | null;
- /** One line per problem, each starting with the `where` label. Empty when `header` is set. */
- problems: string[];
- /** True when the file has a header comment at all (valid or not): the file is a component file. */
- found: boolean;
- /** The YAML text between the markers. */
- raw: string | null;
- /** Where the comment lies in the file: offsets of its first character and of the one after its last. */
- start: number;
- end: number;
- /** `html` for `<!---`, `ts` for `/*---`. */
- lang: 'html' | 'ts' | null;
- };
- const KEBAB = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
- const CONTROL_NAME = /^[a-z][a-z0-9-]*$/;
- const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
- /** `package-card` → `Package card`. */
- export function titleOf(id: string): string {
- const s = id.replace(/-/g, ' ');
- return s.charAt(0).toUpperCase() + s.slice(1);
- }
- /** `package-card` → `PackageCard`. */
- export function pascal(id: string): string {
- return id.split('-').map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('');
- }
- /** The file kind by its name: `html` (the HTML implementation), `react` (TS/TSX/JS/JSX), or null (not a code file). */
- export function kindOf(file: string): 'html' | 'react' | null {
- if (/\.html?$/i.test(file)) return 'html';
- if (/\.(tsx?|jsx?|mjs|mts)$/i.test(file) && !/\.(test|spec|stories|story)\.[a-z]+$/i.test(file) && !/\.d\.ts$/i.test(file)) return 'react';
- return null;
- }
- const PREFIX = /^(?:\s|['"]use (?:client|server)['"];?|\/\/[^\n]*)*/;
- /** Finds the header comment. It must come first in the file: only blanks, a BOM, `'use client'` and `//` lines may precede it. */
- export function findHeader(text: string): { raw: string; start: number; end: number; lang: 'html' | 'ts' } | null {
- const body = text.replace(/^/, '');
- const shift = text.length - body.length;
- const lead = PREFIX.exec(body)![0].length;
- const at = body.slice(lead);
- let open: string, close: string, lang: 'html' | 'ts';
- if (at.startsWith('<!---')) [open, close, lang] = ['<!---', '--->', 'html'];
- else if (at.startsWith('/*---')) [open, close, lang] = ['/*---', '---*/', 'ts'];
- else return null;
- const inner = lead + open.length;
- const stop = body.indexOf(close, inner);
- if (stop < 0) return { raw: body.slice(inner), start: shift + lead, end: text.length, lang };
- return { raw: body.slice(inner, stop), start: shift + lead, end: shift + stop + close.length, lang };
- }
- /** Removes the common indentation (and a leading ` * ` gutter some editors add) so the YAML parses. */
- function dedent(raw: string): string {
- const lines = raw.replace(/\r\n?/g, '\n').split('\n');
- while (lines.length && !lines[0].trim()) lines.shift();
- while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
- const gutter = lines.length > 0 && lines.every((l) => !l.trim() || /^\s*\*(\s|$)/.test(l));
- const body = gutter ? lines.map((l) => l.replace(/^\s*\*\s?/, '')) : lines;
- const indent = Math.min(...body.filter((l) => l.trim()).map((l) => /^ */.exec(l)![0].length));
- return body.map((l) => (Number.isFinite(indent) ? l.slice(Math.min(indent, /^ */.exec(l)![0].length)) : l)).join('\n');
- }
- const strList = (v: unknown, name: string, bad: string[], rule?: RegExp): string[] => {
- if (v === undefined || v === null) return [];
- if (!Array.isArray(v)) { bad.push(`${name} must be a list`); return []; }
- const out: string[] = [];
- for (const x of v) {
- const s = typeof x === 'number' ? String(x) : x;
- if (typeof s !== 'string' || !s.trim()) bad.push(`${name} has an item that is not a word`);
- else if (rule && !rule.test(s)) bad.push(`${name}: "${s}" is not valid here`);
- else out.push(s);
- }
- return out;
- };
- const optStr = (c: Record<string, unknown>, k: string, name: string, bad: string[]) => {
- if (c[k] !== undefined && typeof c[k] !== 'string') bad.push(`${name}.${k} must be text`);
- };
- const optNum = (c: Record<string, unknown>, k: string, name: string, bad: string[]) => {
- if (c[k] !== undefined && (typeof c[k] !== 'number' || !Number.isFinite(c[k]))) bad.push(`${name}.${k} must be a number`);
- };
- /** The control schema of section 5: `{<name>: {kind, label?, options?, default?, min?, max?, step?, unit?, section?, colors?}}`. */
- export function validateControls(controls: unknown, where = 'controls'): string[] {
- const bad: string[] = [];
- if (controls === undefined || controls === null) return bad;
- if (!isObj(controls)) return [`${where} must be a map of controls`];
- for (const [key, c] of Object.entries(controls)) {
- const name = `${where}.${key}`;
- if (!CONTROL_NAME.test(key)) bad.push(`${name}: a control name is lower case with dashes (it becomes data-${key})`);
- if (!isObj(c)) { bad.push(`${name} must be a map with at least "kind"`); continue; }
- if (!CONTROL_KINDS.includes(c.kind as ControlKind)) { bad.push(`${name}.kind "${String(c.kind)}" is not one of ${CONTROL_KINDS.join(', ')}`); continue; }
- for (const k of ['label', 'unit', 'section']) optStr(c, k, name, bad);
- for (const k of ['min', 'max', 'step']) optNum(c, k, name, bad);
- const kind = c.kind as ControlKind;
- const opts = c.options;
- if (kind === 'select' || kind === 'segment' || kind === 'swatch') {
- if (!Array.isArray(opts) || !opts.length) bad.push(`${name}: a ${kind} control needs "options" (a list)`);
- else if (opts.some((o) => typeof o !== 'string' && typeof o !== 'number')) bad.push(`${name}.options must be words, numbers or colours`);
- else {
- if (kind === 'segment' && (opts.length < 2 || opts.length > 4)) bad.push(`${name}: a segment control has 2 to 4 options, not ${opts.length}`);
- if (c.default !== undefined && kind !== 'swatch' && !opts.includes(c.default as string)) bad.push(`${name}.default "${String(c.default)}" is not among the options`);
- }
- } else if (opts !== undefined) bad.push(`${name}: a ${kind} control has no "options"`);
- if (kind === 'bool' && c.default !== undefined && typeof c.default !== 'boolean') bad.push(`${name}.default must be true or false`);
- if (kind === 'text' && c.default !== undefined && typeof c.default !== 'string') bad.push(`${name}.default must be text`);
- if (kind === 'range') {
- if (typeof c.min !== 'number' || typeof c.max !== 'number') bad.push(`${name}: a range control needs "min" and "max"`);
- else if (c.min >= c.max) bad.push(`${name}: "min" must be less than "max"`);
- if (typeof c.step === 'number' && c.step <= 0) bad.push(`${name}.step must be above 0`);
- if (c.default !== undefined) {
- if (typeof c.default !== 'number') bad.push(`${name}.default must be a number`);
- else if (typeof c.min === 'number' && typeof c.max === 'number' && (c.default < c.min || c.default > c.max)) bad.push(`${name}.default is outside min…max`);
- }
- }
- }
- return bad;
- }
- /** Parses the header of a file's text. `where` (a path) starts every problem line. */
- export function parseHeader(text: string, where = 'header'): Parsed {
- const f = findHeader(text);
- const fail = (problems: string[]): Parsed => ({
- header: null, problems: problems.map((p) => `${where}: ${p}`), found: !!f, raw: f?.raw ?? null, start: f?.start ?? -1, end: f?.end ?? -1, lang: f?.lang ?? null,
- });
- if (!f) return fail([]);
- const close = f.lang === 'html' ? '--->' : '---*/';
- if (!text.slice(f.start, f.end).endsWith(close)) return fail([`the header comment is not closed (it must end with ${close})`]);
- let data: unknown;
- // A bare `12-3` is a string to us; Bun's YAML would read the number before the dash.
- const yaml = dedent(f.raw).replace(/^(\s*(?:[\w-]+:\s+)?)(\d+(?:-\d+)+)(\s*)$/gm, '$1"$2"$3');
- try {
- data = Bun.YAML.parse(yaml);
- } catch (e) {
- return fail([`the header is not valid YAML — ${(e as Error).message.split('\n')[0]}`]);
- }
- if (!isObj(data)) return fail(['the header must be a YAML map (id, level, …)']);
- const bad: string[] = [];
- const id = data.id;
- if (typeof id !== 'string' || !KEBAB.test(id)) bad.push(`id "${String(id)}" must be kebab-case (letters, digits, dashes)`);
- if (!LEVELS.includes(data.level as Level)) bad.push(`level "${String(data.level)}" is not one of ${LEVELS.join(', ')}`);
- for (const k of ['title', 'description']) if (data[k] !== undefined && typeof data[k] !== 'string') bad.push(`${k} must be text`);
- const uses = strList(data.uses, 'uses', bad, KEBAB);
- const parts = strList(data.parts, 'parts', bad);
- const states = strList(data.states, 'states', bad);
- const status = strList(data.status, 'status', bad);
- const cssProperties = strList(data.cssProperties, 'cssProperties', bad, /^--[\w-]+$/);
- bad.push(...validateControls(data.controls));
- if (typeof id === 'string' && uses.includes(id)) bad.push('uses itself');
- if (bad.length) return fail(bad);
- const header: Header = {
- id: id as string,
- title: typeof data.title === 'string' && data.title.trim() ? data.title.trim() : titleOf(id as string),
- level: data.level as Level,
- description: typeof data.description === 'string' ? data.description.trim() : '',
- uses, parts, states, status,
- controls: (data.controls ?? {}) as Record<string, Control>,
- cssProperties,
- };
- return { header, problems: [], found: true, raw: f.raw, start: f.start, end: f.end, lang: f.lang };
- }
- /** Reads a file and parses its header. `where` defaults to the path given. */
- export function readHeader(path: string, where = path): Parsed {
- return parseHeader(readFileSync(path, 'utf8'), where);
- }
- /** The text of a file without its header comment (and the blank line after it). */
- export function stripHeader(text: string): string {
- const f = findHeader(text);
- return f ? (text.slice(0, f.start) + text.slice(f.end)).replace(/^\s*\n/, '') : text;
- }