server.ts
TypeScript · 94 рядків
1// Портал wms.techtools.top: лендінг, рендер ТЗ (doc/) і досліджень (research/) з переходами, презентації, статус прототипів, сторінка стенда /stand.
2// Запуск: node src/server.ts [--port 4000] [--host 0.0.0.0] (порт за замовчуванням — services.portal.port у stand.config.json)
3import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
4import { readFile, stat } from 'node:fs/promises'
5import { join, extname } from 'node:path'
6import { parseArgs } from 'node:util'
7import { landing } from './landing.ts'
8import { codePage, dirPage, markdownPage } from './render.ts'
9import { ROOT, resolveRepoPath } from './repo.ts'
10import { loadConfig } from '../../scripts/stand.ts'
11import { standJson, standPage, standPost } from './stand.ts'
12import { checkStatus } from './status.ts'
13import { handleComments } from './comments/routes.ts'
14import { ensureDefaultAdmin } from './comments/auth.ts'
15import { privateFile } from './comments/git.ts'
16
17const ASSETS = join(import.meta.dirname, '..', 'assets')
18
19const MIME: Record<string, string> = {
20 '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
21 '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg',
22 '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.pdf': 'application/pdf', '.ico': 'image/x-icon',
23 '.txt': 'text/plain; charset=utf-8', '.csv': 'text/plain; charset=utf-8',
24}
25/** Текстові файли, які показуються сторінкою з кодом. */
26const CODE = new Set(['.ts', '.js', '.mjs', '.cjs', '.log', '.vue', '.sql', '.json', '.yaml', '.yml', '.txt', '.css', '.csv', '.sh', '.ps1', '.toml'])
27
28function send(res: ServerResponse, status: number, body: string | Buffer, type = 'text/html; charset=utf-8') {
29 res.writeHead(status, { 'content-type': type, 'cache-control': 'no-cache' })
30 res.end(body)
31}
32
33async function handle(req: IncomingMessage, res: ServerResponse) {
34 const url = new URL(req.url ?? '/', 'http://portal')
35 const path = decodeURIComponent(url.pathname)
36
37 if (path === '/') return send(res, 200, await landing())
38 if (await handleComments(req, res, url)) return
39 // приватні документи (private/, лише на цій машині) — за тими самими адресами, що й документи проєкту
40 const own = privateFile(path.slice(1))
41 if (own) {
42 const md = await readFile(own, 'utf8')
43 return url.searchParams.has('raw') ? send(res, 200, md, MIME['.txt']) : send(res, 200, await markdownPage(path.slice(1), md))
44 }
45 if (path === '/api/status') return send(res, 200, JSON.stringify(await checkStatus()), MIME['.json'])
46 if (path === '/api/stand') return send(res, 200, JSON.stringify(await standJson(), null, 2), MIME['.json'])
47 if (path === '/stand' && req.method === 'POST') {
48 const r = await standPost(req)
49 send(res, r.status, r.html)
50 return r.after?.()
51 }
52 if (path === '/stand') return send(res, 200, await standPage())
53 if (path.startsWith('/assets/')) {
54 const name = path.slice('/assets/'.length)
55 if (!/^[\w.-]+$/.test(name)) return send(res, 404, 'Not found', MIME['.txt'])
56 try { return send(res, 200, await readFile(join(ASSETS, name)), MIME[extname(name)] ?? 'application/octet-stream') }
57 catch { return send(res, 404, 'Not found', MIME['.txt']) }
58 }
59
60 const file = resolveRepoPath(path)
61 if (!file) return send(res, 404, await markdownPage(null, '# Не знайдено\n\nТакого документа немає або він не публікується порталом.\n\n[На головну](/)'))
62 const info = await stat(file.abs).catch(() => null)
63 if (!info) return send(res, 404, await markdownPage(null, `# Не знайдено\n\n\`${file.rel}\` відсутній у репозиторії.\n\n[На головну](/)`))
64
65 if (info.isDirectory()) {
66 if (!path.endsWith('/')) { res.writeHead(301, { location: url.pathname + '/' + url.search }); return res.end() }
67 return send(res, 200, await dirPage(file.rel, file.abs))
68 }
69 const ext = extname(file.abs).toLowerCase()
70 // сирий текст — завжди текстом, щоб HTML прототипу не відкривався сторінкою з битими шляхами
71 if (url.searchParams.has('raw')) return send(res, 200, await readFile(file.abs), ext === '.html' ? MIME['.txt'] : MIME[ext] ?? MIME['.txt'])
72 if (ext === '.html' && file.servesHtml) return send(res, 200, await readFile(file.abs), MIME[ext])
73 if (ext === '.md') return send(res, 200, await markdownPage(file.rel, await readFile(file.abs, 'utf8')))
74 if (CODE.has(ext) || ext === '.html') {
75 if (info.size > 2_000_000) return send(res, 200, await readFile(file.abs), MIME['.txt'])
76 return send(res, 200, await codePage(file.rel, await readFile(file.abs, 'utf8')))
77 }
78 if (MIME[ext]) return send(res, 200, await readFile(file.abs), MIME[ext])
79 return send(res, 404, 'Not found', MIME['.txt'])
80}
81
82if (import.meta.main) {
83 const { values } = parseArgs({ options: { port: { type: 'string' }, host: { type: 'string' } } })
84 const port = Number(values.port ?? process.env.PORT ?? loadConfig().services.portal.port)
85 const host = values.host ?? '0.0.0.0'
86 createServer((req, res) => {
87 handle(req, res).catch(e => { console.error(e); if (!res.headersSent) send(res, 500, 'Internal error', MIME['.txt']); else res.end() })
88 }).listen(port, host, async () => {
89 console.log(`portal: http://localhost:${port} — слухає ${host} (репозиторій ${ROOT})`)
90 const admin = ensureDefaultAdmin()
91 if (admin) console.log(`portal: створено адміністратора «${admin}» з stand.config.json (portalAdmin)`)
92 })
93}
94