techtools
Головна / portal / src / catalog.ts

catalog.ts

TypeScript · 129 рядків

1// Каталог документів: перелік ТЗ і досліджень з їхніх README, презентації та індекс ID (WMS-02, TOP-05, R-11…) → посилання.
2// Перебудовується, коли змінюється будь-який .md у doc/ чи research/.
3import { readdir, readFile, stat } from 'node:fs/promises'
4import { join } from 'node:path'
5import { ROOT } from './repo.ts'
6import { slugger } from './slug.ts'
7
8export interface Link { href: string; label: string }
9/** research — R-*, на які посилається документ; open — відкриті питання D-* і Q-* з client-meeting.md, які він згадує. */
10export interface DocEntry { href: string; title: string; summary: string; file: string; research: string[]; open: Link[] }
11/** status — до першої «:» чи «;», short — для бейджа (без пояснень і дат), materials — прототипи й лаби з теми реєстру. */
12/** archived — рядок розділу «Архів» реєстру (файл у research/archive/): зроблено чи замінено, читається як раніше. */
13export interface ResearchEntry { id: string; href: string | null; title: string; status: string; short: string; statusKind: string; date: string; materials: Link[]; archived: boolean }
14export interface Presentation { href: string; title: string; research: string }
15export interface Catalog { docs: DocEntry[]; research: ResearchEntry[]; presentations: Presentation[]; ids: Map<string, string> }
16
17/** Ідентифікатор розділу на початку заголовка: «[feature] TOP-02. …», «F-01. …». */
18const HEADING_ID = /^#{2,4}\s+(?:\[feature\]\s*)?([A-Z]{1,4}-\d{1,3})\./
19const plain = (md: string) => md.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/[*`]/g, '').trim()
20/** Реєстр відкритих питань: розділи «## N. …» і індекс D-* і Q-* → розділ у додатку 2. */
21const OPEN_DOC = 'client-meeting.md'
22const cells = (line: string) => line.trim().replace(/^\||\|$/g, '').split('|').map(c => c.trim())
23
24/** Теки з .md для каталогу: research/archive — досліди в архіві (R-41, 04.12.2026). */
25const DIRS = ['doc', 'research', 'research/archive']
26
27async function mdFiles(dir: string) {
28  return (await readdir(join(ROOT, dir))).filter(f => f.endsWith('.md')).sort()
29}
30
31async function signature() {
32  const parts: string[] = []
33  for (const dir of DIRS) {
34    for (const f of await mdFiles(dir)) parts.push(`${dir}/${f}:${(await stat(join(ROOT, dir, f))).mtimeMs}`)
35  }
36  return parts.join('|')
37}
38
39function statusKind(s: string) {
40  if (/^Підтверджено/.test(s)) return 'ok'
41  if (/^Прийнято|^Узгоджено/.test(s)) return 'accepted'
42  if (/^Закрито|^Замінено|^Видалено/.test(s)) return 'closed'
43  if (/^Заплановано/.test(s)) return 'planned'
44  return 'draft'
45}
46
47async function build(): Promise<Catalog> {
48  const ids = new Map<string, string>()
49
50  const docs: DocEntry[] = []
51  for (const line of (await readFile(join(ROOT, 'doc/README.md'), 'utf8')).split('\n')) {
52    const m = line.match(/^\|\s*\[([^\]]+)\]\(([^)]+\.md)\)\s*\|\s*(.+?)\s*\|\s*$/)
53    if (m && !m[2].startsWith('..')) docs.push({ href: `/doc/${m[2]}`, title: m[1], summary: plain(m[3]), file: m[2], research: [], open: [] })
54  }
55
56  const sections = new Map<string, string>()
57  for (const dir of DIRS) {
58    for (const f of await mdFiles(dir)) {
59      const text = await readFile(join(ROOT, dir, f), 'utf8')
60      const slug = slugger()
61      for (const line of text.split('\n')) {
62        if (!/^#{1,6}\s/.test(line)) continue
63        const anchor = slug(plain(line.replace(/^#+\s+/, '')))
64        const m = line.match(HEADING_ID)
65        if (m && !ids.has(m[1])) ids.set(m[1], `/${dir}/${f}#${anchor}`)
66        const sec = f === OPEN_DOC && line.match(/^##\s+(\d+)\./)
67        if (sec) sections.set(sec[1], `/doc/${f}#${anchor}`)
68      }
69      const r = f.match(/^(R-\d{2})-/)
70      if (r && dir !== 'doc') ids.set(r[1], `/${dir}/${f}`)
71    }
72  }
73
74  const open = new Map<string, string>()
75  for (const line of (await readFile(join(ROOT, 'doc', OPEN_DOC), 'utf8')).split('\n')) {
76    if (!line.startsWith('|')) continue
77    const row = cells(line), sec = sections.get(row[2]?.split(',')[0].trim() ?? '')
78    if (!sec) continue
79    for (const id of (row[0] + ' ' + row[1]).match(/\b[DQ]-\d{2,3}\b/g) ?? []) if (!open.has(id)) open.set(id, sec)
80  }
81  for (const [id, href] of open) if (!ids.has(id)) ids.set(id, href)
82  const byId = (a: string, b: string) => a.localeCompare(b, 'en', { numeric: true })
83  for (const d of docs) {
84    const text = await readFile(join(ROOT, 'doc', d.file), 'utf8').catch(() => '')
85    const refs = d.file === OPEN_DOC ? [...open.keys()] : [...new Set(text.match(/\b[DQ]-\d{2,3}\b/g) ?? [])].filter(id => open.has(id))
86    d.open = refs.sort(byId).map(id => ({ href: open.get(id)!, label: id }))
87    d.research = [...new Set(text.match(/\bR-\d{2}\b/g) ?? [])].sort(byId)
88  }
89
90  const research: ResearchEntry[] = []
91  let archived = false
92  for (const line of (await readFile(join(ROOT, 'research/README.md'), 'utf8')).split('\n')) {
93    if (/^##\s/.test(line)) archived = /^##\s+Архів/.test(line)
94    if (!/^\|\s*\[?R-\d{2}/.test(line)) continue
95    const [idCell, theme, status, date = ''] = cells(line)
96    const link = idCell.match(/\[(R-\d{2})\]\(([^)]+)\)/)
97    const id = link ? link[1] : idCell
98    let title = plain(theme).split(/[:;]/)[0]
99    if (link) {
100      const h1 = (await readFile(join(ROOT, 'research', link[2]), 'utf8').catch(() => '')).match(/^#\s+(.+)$/m)
101      if (h1) title = plain(h1[1]).replace(/^R-\d{2}\.\s*/, '')
102    }
103    const st = plain(status)
104    const short = st.split(/ — |[:;(,]| \d/)[0].trim()
105    const materials = [...theme.matchAll(/\[([^\]]+)\]\(((?:\.\.\/proto|lab)\/[^)]+)\)/g)]
106      .map(m => ({ href: '/' + (m[2].startsWith('lab/') ? 'research/' + m[2] : m[2].slice(3)), label: plain(m[1]).replace(/^(research|proto)\//, '') }))
107      .filter((l, i, all) => all.findIndex(x => x.href === l.href) === i)
108    research.push({ id, href: link ? `/research/${link[2]}` : null, title, status: st.split(/[:;(]/)[0].trim(), short, statusKind: statusKind(st), date: plain(date), materials, archived })
109  }
110
111  const presentations: Presentation[] = []
112  for (const d of (await readdir(join(ROOT, 'research'))).filter(d => /^r-\d{2}-[a-z-]+$/.test(d)).sort()) {
113    const html = await readFile(join(ROOT, 'research', d, 'index.html'), 'utf8').catch(() => '')
114    if (!html) continue
115    const title = html.match(/<title>([^<$]*)<\/title>/)?.[1] ?? d
116    presentations.push({ href: `/research/${d}/`, title: title.replace(/^R-\d{2}\s*·\s*/, ''), research: d.slice(0, 4).toUpperCase() })
117  }
118
119  return { docs, research, presentations, ids }
120}
121
122let cached: { sig: string; catalog: Catalog } | null = null
123
124export async function catalog(): Promise<Catalog> {
125  const sig = await signature()
126  if (cached?.sig !== sig) cached = { sig, catalog: await build() }
127  return cached.catalog
128}
129