package file→ .shtukbase/packages/keer-ui/actions/kitlib.ts
actions/kitlib.ts
61 lines, 2.7 KB.
- // Shared parts of the keer-ui action and checks. The working directory is the project root.
- // The library lives in .shtukbase/packages/keer-ui/library; `place` copies it into the project folder named by
- // `target:` of /design/keer-ui.md (default src/ui) and writes <target>/.keer-ui.json: the hash of every file it laid.
- import { createHash } from 'node:crypto';
- import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
- import { dirname, join, relative } from 'node:path';
- import { readPage } from '../../collections/checks/lib/pages.ts';
- export const CONFIG = 'design/keer-ui.md';
- export const MANIFEST = '.keer-ui.json';
- export const LIBRARY = join(import.meta.dir, '..', 'library');
- export type Manifest = { version: string; tokens: string; files: Record<string, string> };
- export function sha(text: string): string {
- return createHash('sha256').update(text).digest('hex');
- }
- /** target and tokens paths (relative to the project root) from the config page, with defaults. */
- export function config(root = process.cwd()): { target: string; tokens: string } {
- const page = join(root, CONFIG);
- const fm = existsSync(page) ? readPage(page).fm : {};
- const clean = (v: unknown, d: string) => (typeof v === 'string' && v.trim() ? v.trim().replace(/^\/+|\/+$/g, '') : d);
- return { target: clean(fm.target, 'src/ui'), tokens: clean(fm.tokens, 'design/keer-style/tokens.css') };
- }
- /** Every file under a folder, relative paths with forward slashes. */
- export function files(dir: string, rel = ''): string[] {
- if (!existsSync(join(dir, rel))) return [];
- const out: string[] = [];
- for (const name of readdirSync(join(dir, rel)).sort()) {
- const r = rel ? `${rel}/${name}` : name;
- if (statSync(join(dir, r)).isDirectory()) out.push(...files(dir, r));
- else out.push(r);
- }
- return out;
- }
- /** The text of a library file as it lies in the project: the tokens import points at the project's tokens file. */
- export function render(rel: string, text: string, target: string, tokens: string): string {
- if (!text.includes('{{tokens}}')) return text;
- let path = relative(dirname(join(target, rel)), tokens).split('\\').join('/');
- if (!path.startsWith('.')) path = `./${path}`;
- return text.split('{{tokens}}').join(path);
- }
- export function readManifest(root: string, target: string): Manifest | null {
- const p = join(root, target, MANIFEST);
- if (!existsSync(p)) return null;
- try {
- return JSON.parse(readFileSync(p, 'utf8')) as Manifest;
- } catch {
- return null;
- }
- }
- /** The package version from its package.md (for the manifest). */
- export function version(): string {
- const p = join(import.meta.dir, '..', 'package.md');
- return existsSync(p) ? String(readPage(p).fm.version ?? '') : '';
- }