ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/ontology/actions/lib/render_ontology.ts

actions/lib/render_ontology.ts

419 líneas, 20.4 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // Static lens "Ontology and contours": layers, bridges, contours, placement.
  2. //
  3. // Reads from the root: base/ontology.md, <layer>/ontology.md, base/ontology/*.md, base/contours.md,
  4. // <layer>/contours/**/*.md, base/packages.md. Writes <root>/base/ontology/layers.html (static lens,
  5. // lensType schema) with the header and both hashes. Template: templates/ontology.html.
  6. // The old layout (ontology/<id>.md, contours/<layer>-<name>.md, bundles.md at the root; base/bundles.md before
  7. // 2026-11-28) is still read.
  8. //
  9. // What it expects, and what it does when something is missing:
  10. // base/ontology.md tables whose first column is "Layer" list the layers. A heading
  11. // with "meta" over such a table makes the group "Meta", with
  12. // "project" the group "Project"; any other heading is used as is.
  13. // A table with "From" and "To" columns is the bridge list.
  14. // <id>/ontology.md the layer page: description, "Types" section (type names).
  15. // A front-matter list `types:` wins over the section.
  16. // <layer>/contours/*.md one contour per file; phases are the files in <layer>/contours/<name>/.
  17. // base/ontology/placement.md front matter `placement: [{itemType, path, writer, reader}]`
  18. // (or the first table of the body); section skipped if absent.
  19. // Ontology pages not listed in any layers table go to a separate group, so the gap is visible.
  20. import { existsSync, readdirSync, statSync } from 'node:fs';
  21. import { dirname, join, relative, resolve } from 'node:path';
  22. import * as lc from './lenscommon.ts';
  23. import { cmp, e, or, str } from './lenscommon.ts';
  24. import * as mdlite from './mdlite.ts';
  25. type Table = { chain: [number, string][]; header: string[]; rows: string[][] };
  26. const SOURCES = ['base/ontology.md', 'base/ontology/*.md', '*/ontology.md', 'base/contours.md', '*/contours/**/*.md',
  27. 'base/packages.md', 'base/bundles.md'];
  28. // Unicode word characters, as `\w` of Python.
  29. const W = '\\p{L}\\p{N}_';
  30. const LINK = /\[([^\]]+)\]\(([^)\s]+)\)/gu;
  31. const CAT = new Map([['arriving', 'incoming'], ['working', 'in progress'], ['done', 'done'], ['dropped', 'dropped']]);
  32. const isFile = (p: string) => existsSync(p) && statSync(p).isFile();
  33. const isDir = (p: string) => existsSync(p) && statSync(p).isDirectory();
  34. const listdir = (p: string) => readdirSync(p).sort(cmp);
  35. // Everything lives in the layers: the ontology of a layer is <layer>/ontology.md, shared pages are in base/.
  36. // The old layout (ontology/<layer>.md, contours/<layer>-<name>.md at the root) is read until the project is updated.
  37. function first(root: string, ...rels: string[]): string {
  38. return rels.find((rel) => isFile(join(root, rel))) ?? rels[0];
  39. }
  40. const ontRel = (root: string, lid: string) =>
  41. first(root, `${lid}/ontology.md`, `base/ontology/${lid}.md`, `ontology/${lid}.md`);
  42. function ontIds(root: string): string[] {
  43. const ids = new Set<string>();
  44. for (const d of listdir(root)) {
  45. if (!/^[._]/.test(d) && d !== 'base' && isFile(join(root, d, 'ontology.md'))) ids.add(d);
  46. }
  47. for (const folder of ['base/ontology', 'ontology']) {
  48. const full = join(root, folder);
  49. if (isDir(full)) for (const f of listdir(full)) if (f.endsWith('.md') && f !== 'placement.md') ids.add(f.slice(0, -3));
  50. }
  51. return [...ids].sort(cmp);
  52. }
  53. function plain(cell: unknown): string {
  54. return String(cell ?? '').replace(/<br\s*\/?>/g, ' ').replace(LINK, (_, text) => text).replace(/[`*]/g, '').trim();
  55. }
  56. const codeSpans = (cell: string) => [...cell.matchAll(/`([^`]+)`/g)].map((m) => m[1]);
  57. // ---------------------------------------------------------------- md structure
  58. /** Every table with its heading chain, and every heading as [level, text]. */
  59. function structure(body: string): { tables: Table[]; heads: [number, string][] } {
  60. const tables: Table[] = [];
  61. const heads: [number, string][] = [];
  62. let chain: [number, string][] = [];
  63. const lines = body.split('\n');
  64. let i = 0;
  65. let fence = false;
  66. while (i < lines.length) {
  67. const s = lines[i].trim();
  68. if (s.startsWith('```')) fence = !fence;
  69. else if (!fence) {
  70. const m = s.match(new RegExp(`^(#{1,4})\\s+(.*?)\\s*(?:\\{#[${W}-]+\\})?$`, 'u'));
  71. if (m) {
  72. const lvl = m[1].length;
  73. chain = [...chain.filter((c) => c[0] < lvl), [lvl, m[2]]];
  74. heads.push([lvl, m[2]]);
  75. } else if (s.startsWith('|') && i + 1 < lines.length && mdlite.SEP.test(lines[i + 1])) {
  76. let j = i + 2;
  77. while (j < lines.length && lines[j].trim().startsWith('|')) j++;
  78. tables.push({ chain: [...chain], header: mdlite.cells(lines[i]), rows: lines.slice(i + 2, j).map(mdlite.cells) });
  79. i = j;
  80. continue;
  81. }
  82. }
  83. i++;
  84. }
  85. return { tables, heads };
  86. }
  87. function col(header: string[], ...names: string[]): number | null {
  88. const low = header.map((h) => plain(h).toLowerCase());
  89. for (const n of names) {
  90. const k = low.findIndex((h) => h.startsWith(n.toLowerCase()));
  91. if (k !== -1) return k;
  92. }
  93. return null;
  94. }
  95. // ---------------------------------------------------------------- layers
  96. type Layer = { name: string; id: string; question: string; who: string; life: string };
  97. type Group = { label: string; hint: string; layers: Layer[]; orphans?: boolean };
  98. type Bridge = { from: string; to: string; fields: string[] };
  99. function groupLabel(chain: [number, string][]): [string, string] {
  100. const text = chain.length ? chain[chain.length - 1][1] : '';
  101. const low = text.toLowerCase();
  102. if (low.includes('meta')) return ['Meta', text];
  103. if (low.includes('project')) return ['Project', text];
  104. return [text || 'Layers', text];
  105. }
  106. function readLayers(root: string): { groups: Group[]; bridges: Bridge[] } {
  107. const [, body] = lc.page(join(root, first(root, 'base/ontology.md', 'ontology.md')));
  108. const groups: Group[] = [];
  109. const bridges: Bridge[] = [];
  110. const cell = (r: string[], k: number | null) => (k !== null && k < r.length ? plain(r[k]) : '');
  111. for (const { chain, header, rows } of structure(body).tables) {
  112. if (plain(header[0]).toLowerCase() === 'layer') {
  113. const [label, hint] = groupLabel(chain);
  114. const cQ = col(header, 'answers');
  115. const cWho = col(header, 'who changes');
  116. const cLife = col(header, 'how long it lives');
  117. const layers: Layer[] = [];
  118. for (const r of rows) {
  119. const name = plain(r[0]);
  120. if (!name) continue;
  121. let lid: string | undefined;
  122. for (const c of r) {
  123. for (const [, , url] of c.matchAll(LINK)) {
  124. const m = url.match(new RegExp(`^/([${W}-]+)/ontology\\.md$`, 'u'))
  125. ?? url.match(new RegExp(`^/(?:base/)?ontology/([${W}-]+)\\.md$`, 'u'))
  126. ?? url.match(new RegExp(`^/([${W}-]+)\\.md$`, 'u'));
  127. if (m && !lid) lid = m[1];
  128. }
  129. }
  130. layers.push({ name, id: lid || name.toLowerCase().replace(new RegExp(`[^${W}]+`, 'gu'), '-'),
  131. question: cell(r, cQ), who: cell(r, cWho), life: cell(r, cLife) });
  132. }
  133. groups.push({ label, hint, layers });
  134. } else if (col(header, 'from') !== null && col(header, 'to') !== null) {
  135. const cFrom = col(header, 'from') as number;
  136. const cTo = col(header, 'to') as number;
  137. const cF = col(header, 'fields');
  138. for (const r of rows) {
  139. bridges.push({ from: plain(r[cFrom]), to: plain(r[cTo]), fields: cF !== null && cF < r.length ? codeSpans(r[cF]) : [] });
  140. }
  141. }
  142. }
  143. return { groups, bridges };
  144. }
  145. /** Type names from a table: the first name-like column (the prose names of the types). */
  146. function names(header: string[], rows: string[][]): string[] {
  147. for (const want of ['name in text', 'in text', 'collection', 'type']) {
  148. const k = col(header, want);
  149. if (k === null) continue;
  150. const vals = rows.filter((r) => r.length > k && plain(r[k])).map((r) => plain(r[k]));
  151. if (vals.length) return vals;
  152. }
  153. return [];
  154. }
  155. type LayerPage = { title: string; icon: string; description: string; types: unknown[] };
  156. function layerPage(root: string, lid: string): LayerPage | null {
  157. const path = join(root, ontRel(root, lid));
  158. if (!isFile(path)) return null;
  159. const [meta, body] = lc.page(path);
  160. let types: unknown[] | null = Array.isArray(meta.types) ? meta.types : null;
  161. if (types === null) {
  162. const { tables, heads } = structure(body);
  163. types = [];
  164. for (const { chain, header, rows } of tables) {
  165. const top = chain.length ? chain[0][1] : '';
  166. if (chain.length === 1 && /^([0-9]+\.\s*)?Types/.test(top)) {
  167. types = names(header, rows);
  168. break;
  169. }
  170. }
  171. if (!types.length) {
  172. let sec = false;
  173. for (const [lvl, text] of heads) {
  174. if (lvl === 2) sec = /^([0-9]+\.\s*)?Types/.test(text);
  175. else if (lvl === 3 && sec) types.push(text.replace(/[`*]/g, ''));
  176. }
  177. }
  178. if (!types.length) {
  179. for (const { chain, header, rows } of tables) {
  180. if (chain.length === 1 && chain[0][1].startsWith('Words')) {
  181. types = names(header, rows);
  182. break;
  183. }
  184. }
  185. }
  186. }
  187. return { title: str(or(meta.title, lid)), icon: str(or(meta.icon, '')), description: str(or(meta.description, '')), types };
  188. }
  189. function pageTitle(root: string, rel: string): string | null {
  190. const p = join(root, rel);
  191. return isFile(p) ? or(lc.page(p)[0].title, null) : null;
  192. }
  193. // ---------------------------------------------------------------- contours
  194. type Phase = { title: string; category: string; path: string };
  195. type Contour = { name: string; layer: string; file: string; title: string; collection: string; phases: Phase[] };
  196. function readContours(root: string): Contour[] {
  197. const found: [string, string, string][] = []; // layer, name, rel
  198. for (const d of listdir(root)) {
  199. const folder = join(root, d, 'contours');
  200. if (/^[._]/.test(d) || !isDir(folder)) continue;
  201. for (const f of listdir(folder)) if (f.endsWith('.md')) found.push([d, f.slice(0, -3), `${d}/contours/${f}`]);
  202. }
  203. const legacy = join(root, 'contours');
  204. if (isDir(legacy)) {
  205. for (const f of listdir(legacy)) if (f.endsWith('.md')) found.push([f.slice(0, -3).split('-')[0], f.slice(0, -3), `contours/${f}`]);
  206. }
  207. const out: Contour[] = [];
  208. for (const [layer, name, rel] of found) {
  209. const [meta] = lc.page(join(root, rel));
  210. if (meta.type !== 'Contour') continue;
  211. const phases: Phase[] = [];
  212. for (const p of Array.isArray(meta.phases) ? meta.phases.map(String) : []) {
  213. const pfile = join(root, `${p.replace(/^\/+/, '')}.md`);
  214. const pm = isFile(pfile) ? lc.page(pfile)[0] : {};
  215. phases.push({ title: str(or(pm.title, p.split('/').pop())), category: str(or(pm.category, '')), path: p });
  216. }
  217. out.push({ name, layer, file: rel, title: str(or(meta.title, name)), collection: str(or(meta.collection, '')), phases });
  218. }
  219. return out;
  220. }
  221. // ---------------------------------------------------------------- placement
  222. type Placement = { itemType: string; path: string; writer: string; reader: string };
  223. function readPlacement(root: string): Placement[] | null {
  224. const path = join(root, first(root, 'base/ontology/placement.md', 'ontology/placement.md'));
  225. if (!isFile(path)) return null;
  226. const [meta, body] = lc.page(path);
  227. if (Array.isArray(meta.placement) && meta.placement.length) {
  228. const get = (r: Record<string, any>, k: string) => (r[k] === undefined ? '' : str(r[k]));
  229. return meta.placement.filter(lc.isObject).map((r) => ({
  230. itemType: get(r, 'itemType'), path: get(r, 'path'), writer: get(r, 'writer'), reader: get(r, 'reader') }));
  231. }
  232. const { tables } = structure(body);
  233. if (tables.length) {
  234. return tables[0].rows.map((r) => ({ itemType: plain(r[0]), path: r.length > 1 ? plain(r[1]) : '',
  235. writer: r.length > 2 ? plain(r[2]) : '', reader: r.length > 3 ? plain(r[3]) : '' }));
  236. }
  237. return null;
  238. }
  239. function readPackages(root: string): { rows: string[][]; header: string[] } | null {
  240. const path = join(root, first(root, 'base/packages.md', 'base/bundles.md', 'bundles.md'));
  241. if (!isFile(path)) return null;
  242. const [, body] = lc.page(path);
  243. for (const { header, rows } of structure(body).tables) {
  244. if (/^(package|bundle)/.test(plain(header[0]).toLowerCase())) { // "Bundle" in a page written before 2026-11-28
  245. return { rows: rows.map((r) => r.map(plain)), header: header.map(plain) };
  246. }
  247. }
  248. return null;
  249. }
  250. // ---------------------------------------------------------------- html
  251. function render(root: string, out: string): { summary: string; toc: string; content: string } {
  252. const base = dirname(resolve(out));
  253. const href = (rel: string) => relative(base, join(root, rel)).split('\\').join('/');
  254. const { groups, bridges } = readLayers(root);
  255. const contours = readContours(root);
  256. const known = new Set(groups.flatMap((g) => g.layers.map((l) => l.id)));
  257. const extra = ontIds(root).filter((p) => !known.has(p));
  258. if (extra.length) {
  259. groups.push({ label: 'Not in the layers table', hint: '', orphans: true, layers: extra.map((p) => (
  260. { name: layerPage(root, p)?.title || p, id: p, question: '', who: '', life: '' })) });
  261. }
  262. const byLayer = new Map<string, Contour[]>();
  263. for (const c of contours) byLayer.set(c.layer, [...(byLayer.get(c.layer) ?? []), c]);
  264. const layerTitle = (lid: string) => {
  265. for (const g of groups) for (const l of g.layers) if (l.id === lid) return l.name;
  266. return pageTitle(root, ontRel(root, lid)) || pageTitle(root, `${lid}.md`) || lid;
  267. };
  268. const nlayers = groups.filter((g) => !g.orphans).reduce((n, g) => n + g.layers.length, 0);
  269. let ntypes = 0;
  270. const layersHtml: string[] = [];
  271. for (const g of groups) {
  272. const cards: string[] = [];
  273. for (const l of g.layers) {
  274. const lp = layerPage(root, l.id);
  275. if (lp && !g.orphans) ntypes += lp.types.length;
  276. const cs = byLayer.get(l.id) ?? [];
  277. const nph = cs.reduce((n, c) => n + c.phases.length, 0);
  278. const outBr = bridges.filter((b) => b.from.toLowerCase() === l.name.toLowerCase());
  279. const h: string[] = ['<article class="layer">'];
  280. h.push(`<h3 id="layer-${e(l.id)}">${e(`${lp?.icon ?? ''} ${l.name}`).trim()}</h3>`);
  281. const q = l.question || lp?.description || '';
  282. if (q) h.push(`<p class="q">${e(q)}</p>`);
  283. const facts: string[] = [];
  284. if (l.who) facts.push(`<dt>Who changes it</dt><dd>${e(l.who)}</dd>`);
  285. if (l.life) facts.push(`<dt>Lives</dt><dd>${e(l.life)}</dd>`);
  286. if (lp && lp.types.length) {
  287. facts.push(`<dt>Types (${lp.types.length})</dt><dd class="chips">${lp.types.map((t) => `<span class="chip">${e(t)}</span>`).join('')}</dd>`);
  288. }
  289. if (outBr.length) {
  290. const tgt = outBr.flatMap((b) => b.to.split(',').map((t) => t.trim()).filter(Boolean));
  291. facts.push(`<dt>Bridges out</dt><dd>→ ${e([...new Set(tgt)].join(', '))}</dd>`);
  292. }
  293. if (cs.length) facts.push(`<dt>Contours</dt><dd>${cs.length}, phases ${nph}</dd>`);
  294. if (facts.length) h.push(`<dl>${facts.join('')}</dl>`);
  295. if (lp) h.push(`<p class="more"><a href="${e(href(ontRel(root, l.id)))}">Layer page</a></p>`);
  296. else h.push('<p class="more mut">no layer page</p>');
  297. h.push('</article>');
  298. cards.push(h.join('\n'));
  299. }
  300. const note = g.orphans ? '' : ` <span class="count">${g.layers.length}</span>`;
  301. const sub = g.orphans
  302. ? '<p class="mut">These layers have an ontology page, but they are not in the layers table on the page "Project ontology".</p>' : '';
  303. layersHtml.push(`<h3 class="grp">${e(g.label)}${note}</h3>${sub}\n<div class="grid">\n${cards.join('\n')}\n</div>`);
  304. }
  305. const layersSection = groups.length ? layersHtml.join('\n') : '<p class="mut">There is no layers table in ontology.md.</p>';
  306. // bridges
  307. let br = '';
  308. if (bridges.length) {
  309. const rows = bridges.map((b) =>
  310. `<tr><td>${e(b.from)}</td><td>${e(b.to)}</td><td>${b.fields.map((f) => `<code>${e(f)}</code>`).join(' ')}</td></tr>`).join('');
  311. br = '<section><h2 id="bridges">Bridges between layers</h2><div class="tw"><table>'
  312. + `<tr><th>From</th><th>To</th><th>Fields</th></tr>${rows}</table></div></section>`;
  313. }
  314. // contours
  315. let ctr = '';
  316. if (contours.length) {
  317. const order = groups.flatMap((g) => g.layers.map((l) => l.id));
  318. const seen = [...order.filter((lid) => byLayer.has(lid)), ...[...byLayer.keys()].filter((lid) => !order.includes(lid)).sort(cmp)];
  319. const blocks: string[] = [];
  320. for (const lid of seen) {
  321. const cs = byLayer.get(lid) ?? [];
  322. const nph = cs.reduce((n, c) => n + c.phases.length, 0);
  323. const lost = known.has(lid) ? '' : ' <span class="tag">not in the layers table</span>';
  324. const rows = cs.map((c) => {
  325. const chips = c.phases.map((p) =>
  326. `<span class="ph ${e(p.category)}" title="${e(CAT.get(p.category) ?? p.category)}">${e(p.title)}</span>`).join(' <span class="arr">→</span> ');
  327. const coll = c.collection ? `<code>${e(c.collection)}</code>` : '';
  328. 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>`;
  329. }).join('');
  330. blocks.push(`<details open><summary><b>${e(layerTitle(lid))}</b>${lost} <span class="count">contours ${cs.length} · phases ${nph}</span></summary>`
  331. + `<div class="tw"><table><tr><th>Contour</th><th>Phases</th><th>States</th></tr>${rows}</table></div></details>`);
  332. }
  333. const legend = [...CAT].map(([k, v]) => `<span class="ph ${k}">${v}</span>`).join(' ');
  334. ctr = '<section><h2 id="contours">Contours by layer and state</h2>'
  335. + `<p class="mut">The color of a state is its category: ${legend}.</p>${blocks.join('\n')}</section>`;
  336. }
  337. // placement
  338. let pl = '';
  339. const placement = readPlacement(root);
  340. if (placement?.length) {
  341. const rows = placement.map((r) =>
  342. `<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('');
  343. pl = '<section><h2 id="placement">Where things live</h2><div class="tw"><table>'
  344. + `<tr><th>Record type</th><th>Folder</th><th>Who writes</th><th>Who reads</th></tr>${rows}</table></div>`
  345. + `<p class="mut"><a href="${e(href(first(root, 'base/ontology/placement.md', 'ontology/placement.md')))}">The page "Where things live"</a></p></section>`;
  346. }
  347. // packages
  348. let bd = '';
  349. const pk = readPackages(root);
  350. if (pk) {
  351. bd = `<section><h2 id="packages">Packages <span class="count">${pk.rows.length}</span></h2><details><summary>Show the package accounting</summary>`
  352. + `<div class="tw"><table><tr>${pk.header.map((h) => `<th>${e(h)}</th>`).join('')}</tr>`
  353. + `${pk.rows.map((r) => `<tr>${r.map((c) => `<td>${e(c)}</td>`).join('')}</tr>`).join('')}</table></div></details>`
  354. + `<p class="mut"><a href="${e(href(first(root, 'base/packages.md', 'base/bundles.md', 'bundles.md')))}">Packages page</a></p></section>`;
  355. }
  356. const stats: [string, number][] = [['layers', nlayers], ['record types', ntypes], ['bridges', bridges.length],
  357. ['contours', contours.length], ['states', contours.reduce((n, c) => n + c.phases.length, 0)]];
  358. if (extra.length) stats.splice(1, 0, ['layers outside the table', extra.length]);
  359. const summary = stats.map(([l, n]) => `<div class="stat"><b>${n}</b><span>${l}</span></div>`).join('');
  360. const toc = `<nav class="toc"><a href="#layers">Layers</a>${br ? '<a href="#bridges">Bridges</a>' : ''}${ctr ? '<a href="#contours">Contours</a>' : ''}`
  361. + `${pl ? '<a href="#placement">Where things live</a>' : ''}${bd ? '<a href="#packages">Packages</a>' : ''}</nav>`;
  362. const content = `<section><h2 id="layers">Layers</h2>${layersSection}</section>\n${br}\n${ctr}\n${pl}\n${bd}`;
  363. return { summary, toc, content };
  364. }
  365. /** Writes <root>/base/ontology/layers.html (or `out`) and returns its path. */
  366. export function main(root: string, outArg?: string, generator = 'ontology build'): string {
  367. root = resolve(root);
  368. const out = outArg ? resolve(outArg) : join(root, 'base', 'ontology', 'layers.html');
  369. const { summary, toc, content } = render(root, out);
  370. const title = 'Ontology and contours';
  371. const icon = '🧬';
  372. 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.';
  373. const slots: [string, string][] = [['{{icon}}', icon], ['{{title}}', title], ['{{generator}}', e(generator)],
  374. ['{{summary}}', summary], ['{{toc}}', toc], ['{{content}}', content]];
  375. const page = slots.reduce((text, [key, value]) => text.split(key).join(value), lc.template('ontology'));
  376. const meta = { type: 'Lens', title, icon, description: desc, lensType: 'schema', render: 'static', generator,
  377. template: '.shtukbase/packages/ontology/actions/lib/templates/ontology.html' };
  378. lc.build(root, out, meta, SOURCES, page);
  379. return out;
  380. }