файл пакета→ .shtukbase/packages/ontology/actions/lib/render_ontology.ts
actions/lib/render_ontology.ts
419 строк, 20.4 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // Static lens "Ontology and contours": layers, bridges, contours, placement.
- //
- // Reads from the root: base/ontology.md, <layer>/ontology.md, base/ontology/*.md, base/contours.md,
- // <layer>/contours/**/*.md, base/packages.md. Writes <root>/base/ontology/layers.html (static lens,
- // lensType schema) with the header and both hashes. Template: templates/ontology.html.
- // The old layout (ontology/<id>.md, contours/<layer>-<name>.md, bundles.md at the root; base/bundles.md before
- // 2026-11-28) is still read.
- //
- // What it expects, and what it does when something is missing:
- // base/ontology.md tables whose first column is "Layer" list the layers. A heading
- // with "meta" over such a table makes the group "Meta", with
- // "project" the group "Project"; any other heading is used as is.
- // A table with "From" and "To" columns is the bridge list.
- // <id>/ontology.md the layer page: description, "Types" section (type names).
- // A front-matter list `types:` wins over the section.
- // <layer>/contours/*.md one contour per file; phases are the files in <layer>/contours/<name>/.
- // base/ontology/placement.md front matter `placement: [{itemType, path, writer, reader}]`
- // (or the first table of the body); section skipped if absent.
- // Ontology pages not listed in any layers table go to a separate group, so the gap is visible.
- import { existsSync, readdirSync, statSync } from 'node:fs';
- import { dirname, join, relative, resolve } from 'node:path';
- import * as lc from './lenscommon.ts';
- import { cmp, e, or, str } from './lenscommon.ts';
- import * as mdlite from './mdlite.ts';
- type Table = { chain: [number, string][]; header: string[]; rows: string[][] };
- const SOURCES = ['base/ontology.md', 'base/ontology/*.md', '*/ontology.md', 'base/contours.md', '*/contours/**/*.md',
- 'base/packages.md', 'base/bundles.md'];
- // Unicode word characters, as `\w` of Python.
- const W = '\\p{L}\\p{N}_';
- const LINK = /\[([^\]]+)\]\(([^)\s]+)\)/gu;
- const CAT = new Map([['arriving', 'incoming'], ['working', 'in progress'], ['done', 'done'], ['dropped', 'dropped']]);
- const isFile = (p: string) => existsSync(p) && statSync(p).isFile();
- const isDir = (p: string) => existsSync(p) && statSync(p).isDirectory();
- const listdir = (p: string) => readdirSync(p).sort(cmp);
- // Everything lives in the layers: the ontology of a layer is <layer>/ontology.md, shared pages are in base/.
- // The old layout (ontology/<layer>.md, contours/<layer>-<name>.md at the root) is read until the project is updated.
- function first(root: string, ...rels: string[]): string {
- return rels.find((rel) => isFile(join(root, rel))) ?? rels[0];
- }
- const ontRel = (root: string, lid: string) =>
- first(root, `${lid}/ontology.md`, `base/ontology/${lid}.md`, `ontology/${lid}.md`);
- function ontIds(root: string): string[] {
- const ids = new Set<string>();
- for (const d of listdir(root)) {
- if (!/^[._]/.test(d) && d !== 'base' && isFile(join(root, d, 'ontology.md'))) ids.add(d);
- }
- for (const folder of ['base/ontology', 'ontology']) {
- const full = join(root, folder);
- if (isDir(full)) for (const f of listdir(full)) if (f.endsWith('.md') && f !== 'placement.md') ids.add(f.slice(0, -3));
- }
- return [...ids].sort(cmp);
- }
- function plain(cell: unknown): string {
- return String(cell ?? '').replace(/<br\s*\/?>/g, ' ').replace(LINK, (_, text) => text).replace(/[`*]/g, '').trim();
- }
- const codeSpans = (cell: string) => [...cell.matchAll(/`([^`]+)`/g)].map((m) => m[1]);
- // ---------------------------------------------------------------- md structure
- /** Every table with its heading chain, and every heading as [level, text]. */
- function structure(body: string): { tables: Table[]; heads: [number, string][] } {
- const tables: Table[] = [];
- const heads: [number, string][] = [];
- let chain: [number, string][] = [];
- const lines = body.split('\n');
- let i = 0;
- let fence = false;
- while (i < lines.length) {
- const s = lines[i].trim();
- if (s.startsWith('```')) fence = !fence;
- else if (!fence) {
- const m = s.match(new RegExp(`^(#{1,4})\\s+(.*?)\\s*(?:\\{#[${W}-]+\\})?$`, 'u'));
- if (m) {
- const lvl = m[1].length;
- chain = [...chain.filter((c) => c[0] < lvl), [lvl, m[2]]];
- heads.push([lvl, m[2]]);
- } else if (s.startsWith('|') && i + 1 < lines.length && mdlite.SEP.test(lines[i + 1])) {
- let j = i + 2;
- while (j < lines.length && lines[j].trim().startsWith('|')) j++;
- tables.push({ chain: [...chain], header: mdlite.cells(lines[i]), rows: lines.slice(i + 2, j).map(mdlite.cells) });
- i = j;
- continue;
- }
- }
- i++;
- }
- return { tables, heads };
- }
- function col(header: string[], ...names: string[]): number | null {
- const low = header.map((h) => plain(h).toLowerCase());
- for (const n of names) {
- const k = low.findIndex((h) => h.startsWith(n.toLowerCase()));
- if (k !== -1) return k;
- }
- return null;
- }
- // ---------------------------------------------------------------- layers
- type Layer = { name: string; id: string; question: string; who: string; life: string };
- type Group = { label: string; hint: string; layers: Layer[]; orphans?: boolean };
- type Bridge = { from: string; to: string; fields: string[] };
- function groupLabel(chain: [number, string][]): [string, string] {
- const text = chain.length ? chain[chain.length - 1][1] : '';
- const low = text.toLowerCase();
- if (low.includes('meta')) return ['Meta', text];
- if (low.includes('project')) return ['Project', text];
- return [text || 'Layers', text];
- }
- function readLayers(root: string): { groups: Group[]; bridges: Bridge[] } {
- const [, body] = lc.page(join(root, first(root, 'base/ontology.md', 'ontology.md')));
- const groups: Group[] = [];
- const bridges: Bridge[] = [];
- const cell = (r: string[], k: number | null) => (k !== null && k < r.length ? plain(r[k]) : '');
- for (const { chain, header, rows } of structure(body).tables) {
- if (plain(header[0]).toLowerCase() === 'layer') {
- const [label, hint] = groupLabel(chain);
- const cQ = col(header, 'answers');
- const cWho = col(header, 'who changes');
- const cLife = col(header, 'how long it lives');
- const layers: Layer[] = [];
- for (const r of rows) {
- const name = plain(r[0]);
- if (!name) continue;
- let lid: string | undefined;
- for (const c of r) {
- for (const [, , url] of c.matchAll(LINK)) {
- const m = url.match(new RegExp(`^/([${W}-]+)/ontology\\.md$`, 'u'))
- ?? url.match(new RegExp(`^/(?:base/)?ontology/([${W}-]+)\\.md$`, 'u'))
- ?? url.match(new RegExp(`^/([${W}-]+)\\.md$`, 'u'));
- if (m && !lid) lid = m[1];
- }
- }
- layers.push({ name, id: lid || name.toLowerCase().replace(new RegExp(`[^${W}]+`, 'gu'), '-'),
- question: cell(r, cQ), who: cell(r, cWho), life: cell(r, cLife) });
- }
- groups.push({ label, hint, layers });
- } else if (col(header, 'from') !== null && col(header, 'to') !== null) {
- const cFrom = col(header, 'from') as number;
- const cTo = col(header, 'to') as number;
- const cF = col(header, 'fields');
- for (const r of rows) {
- bridges.push({ from: plain(r[cFrom]), to: plain(r[cTo]), fields: cF !== null && cF < r.length ? codeSpans(r[cF]) : [] });
- }
- }
- }
- return { groups, bridges };
- }
- /** Type names from a table: the first name-like column (the prose names of the types). */
- function names(header: string[], rows: string[][]): string[] {
- for (const want of ['name in text', 'in text', 'collection', 'type']) {
- const k = col(header, want);
- if (k === null) continue;
- const vals = rows.filter((r) => r.length > k && plain(r[k])).map((r) => plain(r[k]));
- if (vals.length) return vals;
- }
- return [];
- }
- type LayerPage = { title: string; icon: string; description: string; types: unknown[] };
- function layerPage(root: string, lid: string): LayerPage | null {
- const path = join(root, ontRel(root, lid));
- if (!isFile(path)) return null;
- const [meta, body] = lc.page(path);
- let types: unknown[] | null = Array.isArray(meta.types) ? meta.types : null;
- if (types === null) {
- const { tables, heads } = structure(body);
- types = [];
- for (const { chain, header, rows } of tables) {
- const top = chain.length ? chain[0][1] : '';
- if (chain.length === 1 && /^([0-9]+\.\s*)?Types/.test(top)) {
- types = names(header, rows);
- break;
- }
- }
- if (!types.length) {
- let sec = false;
- for (const [lvl, text] of heads) {
- if (lvl === 2) sec = /^([0-9]+\.\s*)?Types/.test(text);
- else if (lvl === 3 && sec) types.push(text.replace(/[`*]/g, ''));
- }
- }
- if (!types.length) {
- for (const { chain, header, rows } of tables) {
- if (chain.length === 1 && chain[0][1].startsWith('Words')) {
- types = names(header, rows);
- break;
- }
- }
- }
- }
- return { title: str(or(meta.title, lid)), icon: str(or(meta.icon, '')), description: str(or(meta.description, '')), types };
- }
- function pageTitle(root: string, rel: string): string | null {
- const p = join(root, rel);
- return isFile(p) ? or(lc.page(p)[0].title, null) : null;
- }
- // ---------------------------------------------------------------- contours
- type Phase = { title: string; category: string; path: string };
- type Contour = { name: string; layer: string; file: string; title: string; collection: string; phases: Phase[] };
- function readContours(root: string): Contour[] {
- const found: [string, string, string][] = []; // layer, name, rel
- for (const d of listdir(root)) {
- const folder = join(root, d, 'contours');
- if (/^[._]/.test(d) || !isDir(folder)) continue;
- for (const f of listdir(folder)) if (f.endsWith('.md')) found.push([d, f.slice(0, -3), `${d}/contours/${f}`]);
- }
- const legacy = join(root, 'contours');
- if (isDir(legacy)) {
- for (const f of listdir(legacy)) if (f.endsWith('.md')) found.push([f.slice(0, -3).split('-')[0], f.slice(0, -3), `contours/${f}`]);
- }
- const out: Contour[] = [];
- for (const [layer, name, rel] of found) {
- const [meta] = lc.page(join(root, rel));
- if (meta.type !== 'Contour') continue;
- const phases: Phase[] = [];
- for (const p of Array.isArray(meta.phases) ? meta.phases.map(String) : []) {
- const pfile = join(root, `${p.replace(/^\/+/, '')}.md`);
- const pm = isFile(pfile) ? lc.page(pfile)[0] : {};
- phases.push({ title: str(or(pm.title, p.split('/').pop())), category: str(or(pm.category, '')), path: p });
- }
- out.push({ name, layer, file: rel, title: str(or(meta.title, name)), collection: str(or(meta.collection, '')), phases });
- }
- return out;
- }
- // ---------------------------------------------------------------- placement
- type Placement = { itemType: string; path: string; writer: string; reader: string };
- function readPlacement(root: string): Placement[] | null {
- const path = join(root, first(root, 'base/ontology/placement.md', 'ontology/placement.md'));
- if (!isFile(path)) return null;
- const [meta, body] = lc.page(path);
- if (Array.isArray(meta.placement) && meta.placement.length) {
- const get = (r: Record<string, any>, k: string) => (r[k] === undefined ? '' : str(r[k]));
- return meta.placement.filter(lc.isObject).map((r) => ({
- itemType: get(r, 'itemType'), path: get(r, 'path'), writer: get(r, 'writer'), reader: get(r, 'reader') }));
- }
- const { tables } = structure(body);
- if (tables.length) {
- return tables[0].rows.map((r) => ({ itemType: plain(r[0]), path: r.length > 1 ? plain(r[1]) : '',
- writer: r.length > 2 ? plain(r[2]) : '', reader: r.length > 3 ? plain(r[3]) : '' }));
- }
- return null;
- }
- function readPackages(root: string): { rows: string[][]; header: string[] } | null {
- const path = join(root, first(root, 'base/packages.md', 'base/bundles.md', 'bundles.md'));
- if (!isFile(path)) return null;
- const [, body] = lc.page(path);
- for (const { header, rows } of structure(body).tables) {
- if (/^(package|bundle)/.test(plain(header[0]).toLowerCase())) { // "Bundle" in a page written before 2026-11-28
- return { rows: rows.map((r) => r.map(plain)), header: header.map(plain) };
- }
- }
- return null;
- }
- // ---------------------------------------------------------------- html
- function render(root: string, out: string): { summary: string; toc: string; content: string } {
- const base = dirname(resolve(out));
- const href = (rel: string) => relative(base, join(root, rel)).split('\\').join('/');
- const { groups, bridges } = readLayers(root);
- const contours = readContours(root);
- const known = new Set(groups.flatMap((g) => g.layers.map((l) => l.id)));
- const extra = ontIds(root).filter((p) => !known.has(p));
- if (extra.length) {
- groups.push({ label: 'Not in the layers table', hint: '', orphans: true, layers: extra.map((p) => (
- { name: layerPage(root, p)?.title || p, id: p, question: '', who: '', life: '' })) });
- }
- const byLayer = new Map<string, Contour[]>();
- for (const c of contours) byLayer.set(c.layer, [...(byLayer.get(c.layer) ?? []), c]);
- const layerTitle = (lid: string) => {
- for (const g of groups) for (const l of g.layers) if (l.id === lid) return l.name;
- return pageTitle(root, ontRel(root, lid)) || pageTitle(root, `${lid}.md`) || lid;
- };
- const nlayers = groups.filter((g) => !g.orphans).reduce((n, g) => n + g.layers.length, 0);
- let ntypes = 0;
- const layersHtml: string[] = [];
- for (const g of groups) {
- const cards: string[] = [];
- for (const l of g.layers) {
- const lp = layerPage(root, l.id);
- if (lp && !g.orphans) ntypes += lp.types.length;
- const cs = byLayer.get(l.id) ?? [];
- const nph = cs.reduce((n, c) => n + c.phases.length, 0);
- const outBr = bridges.filter((b) => b.from.toLowerCase() === l.name.toLowerCase());
- const h: string[] = ['<article class="layer">'];
- h.push(`<h3 id="layer-${e(l.id)}">${e(`${lp?.icon ?? ''} ${l.name}`).trim()}</h3>`);
- const q = l.question || lp?.description || '';
- if (q) h.push(`<p class="q">${e(q)}</p>`);
- const facts: string[] = [];
- if (l.who) facts.push(`<dt>Who changes it</dt><dd>${e(l.who)}</dd>`);
- if (l.life) facts.push(`<dt>Lives</dt><dd>${e(l.life)}</dd>`);
- if (lp && lp.types.length) {
- facts.push(`<dt>Types (${lp.types.length})</dt><dd class="chips">${lp.types.map((t) => `<span class="chip">${e(t)}</span>`).join('')}</dd>`);
- }
- if (outBr.length) {
- const tgt = outBr.flatMap((b) => b.to.split(',').map((t) => t.trim()).filter(Boolean));
- facts.push(`<dt>Bridges out</dt><dd>→ ${e([...new Set(tgt)].join(', '))}</dd>`);
- }
- if (cs.length) facts.push(`<dt>Contours</dt><dd>${cs.length}, phases ${nph}</dd>`);
- if (facts.length) h.push(`<dl>${facts.join('')}</dl>`);
- if (lp) h.push(`<p class="more"><a href="${e(href(ontRel(root, l.id)))}">Layer page</a></p>`);
- else h.push('<p class="more mut">no layer page</p>');
- h.push('</article>');
- cards.push(h.join('\n'));
- }
- const note = g.orphans ? '' : ` <span class="count">${g.layers.length}</span>`;
- const sub = g.orphans
- ? '<p class="mut">These layers have an ontology page, but they are not in the layers table on the page "Project ontology".</p>' : '';
- layersHtml.push(`<h3 class="grp">${e(g.label)}${note}</h3>${sub}\n<div class="grid">\n${cards.join('\n')}\n</div>`);
- }
- const layersSection = groups.length ? layersHtml.join('\n') : '<p class="mut">There is no layers table in ontology.md.</p>';
- // bridges
- let br = '';
- if (bridges.length) {
- const rows = bridges.map((b) =>
- `<tr><td>${e(b.from)}</td><td>${e(b.to)}</td><td>${b.fields.map((f) => `<code>${e(f)}</code>`).join(' ')}</td></tr>`).join('');
- br = '<section><h2 id="bridges">Bridges between layers</h2><div class="tw"><table>'
- + `<tr><th>From</th><th>To</th><th>Fields</th></tr>${rows}</table></div></section>`;
- }
- // contours
- let ctr = '';
- if (contours.length) {
- const order = groups.flatMap((g) => g.layers.map((l) => l.id));
- const seen = [...order.filter((lid) => byLayer.has(lid)), ...[...byLayer.keys()].filter((lid) => !order.includes(lid)).sort(cmp)];
- const blocks: string[] = [];
- for (const lid of seen) {
- const cs = byLayer.get(lid) ?? [];
- const nph = cs.reduce((n, c) => n + c.phases.length, 0);
- const lost = known.has(lid) ? '' : ' <span class="tag">not in the layers table</span>';
- const rows = cs.map((c) => {
- const chips = c.phases.map((p) =>
- `<span class="ph ${e(p.category)}" title="${e(CAT.get(p.category) ?? p.category)}">${e(p.title)}</span>`).join(' <span class="arr">→</span> ');
- const coll = c.collection ? `<code>${e(c.collection)}</code>` : '';
- return `<tr><td><a href="${e(href(c.file))}">${e(c.title)}</a><br>${coll}</td><td>${c.phases.length}</td><td class="phs">${chips}</td></tr>`;
- }).join('');
- blocks.push(`<details open><summary><b>${e(layerTitle(lid))}</b>${lost} <span class="count">contours ${cs.length} · phases ${nph}</span></summary>`
- + `<div class="tw"><table><tr><th>Contour</th><th>Phases</th><th>States</th></tr>${rows}</table></div></details>`);
- }
- const legend = [...CAT].map(([k, v]) => `<span class="ph ${k}">${v}</span>`).join(' ');
- ctr = '<section><h2 id="contours">Contours by layer and state</h2>'
- + `<p class="mut">The color of a state is its category: ${legend}.</p>${blocks.join('\n')}</section>`;
- }
- // placement
- let pl = '';
- const placement = readPlacement(root);
- if (placement?.length) {
- const rows = placement.map((r) =>
- `<tr><td>${e(r.itemType)}</td><td><code>${e(r.path)}</code></td><td>${e(r.writer)}</td><td>${e(r.reader)}</td></tr>`).join('');
- pl = '<section><h2 id="placement">Where things live</h2><div class="tw"><table>'
- + `<tr><th>Record type</th><th>Folder</th><th>Who writes</th><th>Who reads</th></tr>${rows}</table></div>`
- + `<p class="mut"><a href="${e(href(first(root, 'base/ontology/placement.md', 'ontology/placement.md')))}">The page "Where things live"</a></p></section>`;
- }
- // packages
- let bd = '';
- const pk = readPackages(root);
- if (pk) {
- bd = `<section><h2 id="packages">Packages <span class="count">${pk.rows.length}</span></h2><details><summary>Show the package accounting</summary>`
- + `<div class="tw"><table><tr>${pk.header.map((h) => `<th>${e(h)}</th>`).join('')}</tr>`
- + `${pk.rows.map((r) => `<tr>${r.map((c) => `<td>${e(c)}</td>`).join('')}</tr>`).join('')}</table></div></details>`
- + `<p class="mut"><a href="${e(href(first(root, 'base/packages.md', 'base/bundles.md', 'bundles.md')))}">Packages page</a></p></section>`;
- }
- const stats: [string, number][] = [['layers', nlayers], ['record types', ntypes], ['bridges', bridges.length],
- ['contours', contours.length], ['states', contours.reduce((n, c) => n + c.phases.length, 0)]];
- if (extra.length) stats.splice(1, 0, ['layers outside the table', extra.length]);
- const summary = stats.map(([l, n]) => `<div class="stat"><b>${n}</b><span>${l}</span></div>`).join('');
- const toc = `<nav class="toc"><a href="#layers">Layers</a>${br ? '<a href="#bridges">Bridges</a>' : ''}${ctr ? '<a href="#contours">Contours</a>' : ''}`
- + `${pl ? '<a href="#placement">Where things live</a>' : ''}${bd ? '<a href="#packages">Packages</a>' : ''}</nav>`;
- const content = `<section><h2 id="layers">Layers</h2>${layersSection}</section>\n${br}\n${ctr}\n${pl}\n${bd}`;
- return { summary, toc, content };
- }
- /** Writes <root>/base/ontology/layers.html (or `out`) and returns its path. */
- export function main(root: string, outArg?: string, generator = 'ontology build'): string {
- root = resolve(root);
- const out = outArg ? resolve(outArg) : join(root, 'base', 'ontology', 'layers.html');
- const { summary, toc, content } = render(root, out);
- const title = 'Ontology and contours';
- const icon = '🧬';
- const desc = 'The layers of the project, their types and bridges, contours by layer and state, where things live. Built from the ontology and the contours of the base.';
- const slots: [string, string][] = [['{{icon}}', icon], ['{{title}}', title], ['{{generator}}', e(generator)],
- ['{{summary}}', summary], ['{{toc}}', toc], ['{{content}}', content]];
- const page = slots.reduce((text, [key, value]) => text.split(key).join(value), lc.template('ontology'));
- const meta = { type: 'Lens', title, icon, description: desc, lensType: 'schema', render: 'static', generator,
- template: '.shtukbase/packages/ontology/actions/lib/templates/ontology.html' };
- lc.build(root, out, meta, SOURCES, page);
- return out;
- }