Files
deonisiiandClaude Opus 5.5 768daf7c5f Этап 2: общий Markdown-рендер и импорт стартового контента
- packages/md: unified + remark-gfm + remark-directive, свой плагин [[slug]],
  блоки keyfacts/danger/warning/tip/info, чек-листы, шаги, таблицы, фото,
  rehype-sanitize, разбор шпаргалки, терпимый разбор front matter, тесты
- pnpm seed: пространство, разделы, 12 статей, 58 картинок (sharp → WebP
  1600 + 480, без EXIF), исходники как Attachment, администратор, отчёт
- поисковые поля статьи (tsvector с весами, нормализованный и сжатый текст)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 12:15:21 +03:00

258 lines
11 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// pnpm seed: импорт стартового контента из kb-seed/.
// Скрипт идемпотентный: повторный запуск обновляет записи, а не создаёт дубликаты.
//
// Что делает:
// 1. пространство «АСУПП» и разделы по папкам content/NN-slug
// 2. картинки kb-seed/assets → uploads/assets (WebP 1600 + превью 480, без EXIF)
// 3. исходники kb-seed/originals → uploads/originals
// 4. статьи из content/**/*.md (+ Attachment по полю source)
// 5. администратор из ADMIN_EMAIL / ADMIN_PASSWORD
// 6. отчёт: битые [[ссылки]], потерянные картинки и исходники
import fs from 'node:fs/promises';
import path from 'node:path';
import { assetKey, parseFrontMatter } from '@kb/md';
import type { PlaqueColor } from '@kb/shared';
import { prisma } from './db.js';
import { env } from './env.js';
import { rerenderAll } from './services/articles.js';
import { fileSize, storeImage, uploadPath } from './services/images.js';
import { hashPassword } from './services/password.js';
// Код и цвет плашки раздела: как в макете. Для новых папок код берётся из первых букв названия.
const SECTION_STYLE: Record<string, { code: string; color: PlaqueColor }> = {
shpargalka: { code: 'ШП', color: 'yellow' },
'stoyka-vezda': { code: 'ВВ', color: 'yellow' },
'stoyka-shlagbauma': { code: 'ШЛ', color: 'orange' },
'optika-vok': { code: 'ВОК', color: 'blue' },
ostrov: { code: 'ОБ', color: 'green' },
'naves-terminala': { code: 'НТ', color: 'ink' },
};
const IMAGE_EXT = /\.(jpe?g|png|webp|gif|tiff?)$/i;
async function walk(dir: string): Promise<string[]> {
const out: string[] = [];
let entries;
try {
entries = await fs.readdir(dir, { withFileTypes: true });
} catch {
return out;
}
for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
const p = path.join(dir, e.name);
if (e.isDirectory()) out.push(...(await walk(p)));
else out.push(p);
}
return out;
}
const toPosix = (p: string) => p.split(path.sep).join('/');
function fallbackCode(name: string): string {
return name
.split(/[\s/()-]+/)
.filter(Boolean)
.slice(0, 2)
.map((w) => w[0]!.toUpperCase())
.join('');
}
async function importImages(seedDir: string) {
const dir = path.join(seedDir, 'assets');
const files = (await walk(dir)).filter((f) => IMAGE_EXT.test(f));
let converted = 0;
for (const file of files) {
const key = assetKey(`assets/${toPosix(path.relative(dir, file))}`)!;
const rel = `${key}.webp`;
const srcStat = await fs.stat(file);
const existing = await prisma.asset.findUnique({ where: { path: rel } });
const outStat = await fs.stat(uploadPath(rel)).catch(() => null);
// Пропускаем, если уже сконвертировано и исходник с тех пор не менялся
if (existing && outStat && outStat.mtimeMs >= srcStat.mtimeMs) continue;
const img = await storeImage(await fs.readFile(file), key);
const data = { mime: 'image/webp', size: img.size, width: img.width, height: img.height };
await prisma.asset.upsert({ where: { path: rel }, create: { path: rel, ...data }, update: data });
converted++;
}
return { total: files.length, converted };
}
async function importOriginals(seedDir: string) {
const dir = path.join(seedDir, 'originals');
const files = await walk(dir);
for (const file of files) {
const dest = uploadPath(`originals/${toPosix(path.relative(dir, file))}`);
await fs.mkdir(path.dirname(dest), { recursive: true });
await fs.copyFile(file, dest);
}
return files.length;
}
async function main() {
const seedDir = path.resolve(env.SEED_DIR);
const contentDir = path.join(seedDir, 'content');
console.log(`Импорт из ${seedDir}`);
await fs.access(contentDir).catch(() => {
throw new Error(`Не найдена папка ${contentDir}. Проверьте SEED_DIR.`);
});
await fs.mkdir(env.UPLOADS_DIR, { recursive: true });
// 1. Пространство
const space = await prisma.space.upsert({
where: { slug: 'asupp' },
create: { slug: 'asupp', name: 'АСУПП', icon: 'А', order: 0 },
update: {},
});
// 2–3. Файлы
const images = await importImages(seedDir);
const originals = await importOriginals(seedDir);
// 4. Статьи
const admin = await ensureAdmin();
const problems: string[] = [];
const mdFiles = (await walk(contentDir)).filter((f) => f.endsWith('.md'));
let created = 0;
let updated = 0;
for (const file of mdFiles) {
const relFile = toPosix(path.relative(contentDir, file));
const { meta, body } = parseFrontMatter(await fs.readFile(file, 'utf8'));
if (!meta.slug || !meta.title) {
problems.push(`${relFile}: нет slug или title в шапке, статья пропущена`);
continue;
}
// Раздел по папке: «01-stoyka-vezda» → порядок 1, slug stoyka-vezda
const folder = relFile.split('/')[0] ?? '';
const fm = folder.match(/^(\d+)-(.+)$/);
const sectionSlug = fm?.[2] ?? folder;
const sectionName = meta.section ?? sectionSlug;
const style = SECTION_STYLE[sectionSlug] ?? { code: fallbackCode(sectionName), color: 'ink' as PlaqueColor };
const section = await prisma.section.upsert({
where: { slug: sectionSlug },
create: { slug: sectionSlug, spaceId: space.id, name: sectionName, order: Number(fm?.[1] ?? 0), ...style },
// При повторном запуске не затираем то, что админ поменял руками (название, порядок, цвет)
update: {},
});
const bodyMd = body.trim() + '\n';
const data = {
sectionId: section.id,
title: meta.title,
summary: meta.summary ?? '',
tags: meta.tags,
equipment: meta.equipment,
docCode: meta.doc_code ?? null,
pinned: meta.pinned,
order: meta.order ?? 0,
};
const existing = await prisma.article.findUnique({ where: { slug: meta.slug } });
let articleId: string;
if (!existing) {
const art = await prisma.article.create({
data: { ...data, slug: meta.slug, bodyMd, bodyHtml: '', status: 'PUBLISHED', authorId: admin?.id ?? null },
});
await prisma.articleRevision.create({
data: { articleId: art.id, version: 1, title: art.title, bodyMd, authorId: admin?.id ?? null, comment: 'Импорт из kb-seed' },
});
articleId = art.id;
created++;
} else {
const changed = existing.bodyMd !== bodyMd;
const version = changed ? existing.version + 1 : existing.version;
await prisma.article.update({
where: { id: existing.id },
data: { ...data, bodyMd, version, ...(changed ? { updatedAt: new Date() } : {}) },
});
if (changed) {
await prisma.articleRevision.create({
data: { articleId: existing.id, version, title: meta.title, bodyMd, authorId: admin?.id ?? null, comment: 'Обновление из kb-seed' },
});
updated++;
}
articleId = existing.id;
}
// Исходники по полю source
for (const src of meta.source) {
const rel = src.replace(/^\.?\/+/, '');
const size = await fileSize(uploadPath(rel));
if (size === null) {
problems.push(`${meta.slug}: исходник не найден: ${src}`);
continue;
}
const att = { filename: path.posix.basename(rel), size };
await prisma.attachment.upsert({
where: { articleId_path: { articleId, path: rel } },
create: { articleId, path: rel, ...att },
update: att,
});
}
}
// HTML рисуем вторым проходом: к этому моменту известны названия всех статей для [[ссылок]]
const report = await rerenderAll();
for (const r of report) {
for (const slug of r.brokenLinks) problems.push(`${r.slug}: битая ссылка [[${slug}]]`);
}
// Картинки, на которые ссылается текст, но файла нет
const assetPaths = new Set((await prisma.asset.findMany({ select: { path: true } })).map((a) => a.path));
const articles = await prisma.article.findMany({ select: { slug: true, bodyMd: true } });
let imageRefs = 0;
for (const art of articles) {
for (const m of art.bodyMd.matchAll(/!\[[^\]]*\]\(([^)\s]+)/g)) {
const key = assetKey(m[1] ?? '');
if (!key) continue;
imageRefs++;
if (!assetPaths.has(`${key}.webp`)) problems.push(`${art.slug}: картинка не найдена: ${m[1]}`);
}
}
const counts = {
spaces: await prisma.space.count(),
sections: await prisma.section.count(),
articles: await prisma.article.count(),
assets: await prisma.asset.count(),
attachments: await prisma.attachment.count(),
};
console.log('\n===== Отчёт импорта =====');
console.log(`Статей в БД: ${counts.articles} (новых ${created}, обновлено ${updated})`);
console.log(`Разделов: ${counts.sections}, пространств: ${counts.spaces}`);
console.log(`Картинок: ${counts.assets} (в kb-seed ${images.total}, сконвертировано сейчас ${images.converted})`);
console.log(`Ссылок на картинки: ${imageRefs}`);
console.log(`Исходников: ${counts.attachments} привязано к статьям (файлов ${originals})`);
console.log(`[[Ссылок]]: ${report.reduce((n, r) => n + r.brokenLinks.length, 0)} битых`);
console.log(admin ? `Администратор: ${admin.email}` : 'Администратор: не создан (задайте ADMIN_EMAIL и ADMIN_PASSWORD в .env)');
if (problems.length) {
console.log(`\nПроблемы (${problems.length}):`);
for (const p of problems) console.log(` - ${p}`);
process.exitCode = 1;
} else {
console.log('\nПроблем нет: все картинки, исходники и ссылки на месте.');
}
}
async function ensureAdmin() {
if (!env.ADMIN_EMAIL || !env.ADMIN_PASSWORD) return prisma.user.findFirst({ where: { role: 'ADMIN' } });
const email = env.ADMIN_EMAIL.toLowerCase();
const existing = await prisma.user.findUnique({ where: { email } });
// Существующему админу пароль не перезаписываем: он мог его уже сменить
if (existing) return existing;
return prisma.user.create({
data: { email, name: env.ADMIN_NAME, role: 'ADMIN', passwordHash: await hashPassword(env.ADMIN_PASSWORD) },
});
}
main()
.catch((err) => {
console.error(err);
process.exitCode = 1;
})
.finally(() => prisma.$disconnect());