/01..07.md`. Supports built-in sidebar navigation, copyable code
* blocks, language switching, and clean print-to-PDF styling with zero external dependencies.
*/
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
interface Chapter {
readonly slug: string;
readonly title: string;
readonly html: string;
}
export function buildOfflineModDocs(docsRoot: string, outputDir: string): { readonly zh: string; readonly en: string } {
mkdirSync(outputDir, { recursive: true });
const zhPath = join(outputDir, 'zh-CN.html');
const enPath = join(outputDir, 'en.html');
writeFileSync(zhPath, renderHandbook(docsRoot, 'zh-CN'), 'utf8');
writeFileSync(enPath, renderHandbook(docsRoot, 'en'), 'utf8');
return { zh: zhPath, en: enPath };
}
function renderHandbook(docsRoot: string, lang: 'zh-CN' | 'en'): string {
const dir = join(docsRoot, lang);
const files = readdirSync(dir)
.filter((name) => name.endsWith('.md'))
.sort((a, b) => a.localeCompare(b));
const chapters: Chapter[] = files.map((file) => {
const markdown = readFileSync(join(dir, file), 'utf8');
const titleMatch = /^#\s+(.+)$/m.exec(markdown);
const title = titleMatch ? titleMatch[1]!.trim() : file.replace(/\.md$/, '');
const slug = file.replace(/\.md$/, '');
return { slug, title, html: renderMarkdown(markdown) };
});
const isZh = lang === 'zh-CN';
const pageTitle = isZh ? 'WTOffline 模组开发手册(离线版)' : 'WTOffline Mod Development Handbook (Offline)';
const subtitle = isZh ? 'API 0.1-experimental · 实验期随时可能变动' : 'API 0.1-experimental · Subject to breaking changes';
const switchHref = isZh ? 'en.html' : 'zh-CN.html';
const switchLabel = isZh ? 'English' : '简体中文';
const printLabel = isZh ? '打印 / 另存为 PDF' : 'Print / Save as PDF';
const copyLabel = isZh ? '复制' : 'Copy';
const copiedLabel = isZh ? '已复制' : 'Copied';
const navLinks = chapters
.map((ch) => `${escapeHtml(ch.title)}`)
.join('\n');
const sections = chapters
.map((ch) => `${ch.html}`)
.join('\n
\n');
return `
${escapeHtml(pageTitle)}
${sections}
`;
}
function renderMarkdown(source: string): string {
const lines = source.replace(/\r\n/g, '\n').split('\n');
const out: string[] = [];
let i = 0;
while (i < lines.length) {
const line = lines[i]!;
if (line.trim() === '') {
i += 1;
continue;
}
// Fenced code block.
const fence = /^```([A-Za-z0-9_-]*)/.exec(line);
if (fence) {
const codeLines: string[] = [];
i += 1;
while (i < lines.length && !lines[i]!.startsWith('```')) {
codeLines.push(lines[i]!);
i += 1;
}
if (i < lines.length) i += 1;
out.push(`${escapeHtml(codeLines.join('\n'))}
`);
continue;
}
// Horizontal rule.
if (/^---+$/.test(line.trim())) {
out.push('
');
i += 1;
continue;
}
// Headings.
const heading = /^(#{1,4})\s+(.+)$/.exec(line);
if (heading) {
const level = heading[1]!.length;
out.push(`${renderInline(heading[2]!)}`);
i += 1;
continue;
}
// Blockquote.
if (line.startsWith('>')) {
const quoteLines: string[] = [];
while (i < lines.length && lines[i]!.startsWith('>')) {
quoteLines.push(lines[i]!.replace(/^>\s?/, ''));
i += 1;
}
out.push(`${quoteLines.map(renderInline).join('
')}
`);
continue;
}
// GFM table.
if (line.includes('|') && i + 1 < lines.length && /^\s*\|?[\s:-]+\|[\s|:-]*$/.test(lines[i + 1]!)) {
const headers = splitTableRow(line);
i += 2;
const rows: string[][] = [];
while (i < lines.length && lines[i]!.includes('|') && lines[i]!.trim() !== '') {
rows.push(splitTableRow(lines[i]!));
i += 1;
}
const thead = `${headers.map((cell) => `| ${renderInline(cell)} | `).join('')}
`;
const tbody = `${rows.map((row) => `${row.map((cell) => `| ${renderInline(cell)} | `).join('')}
`).join('')}`;
out.push(``);
continue;
}
// Unordered or ordered list.
if (/^\s*[-*]\s+/.test(line) || /^\s*\d+\.\s+/.test(line)) {
const ordered = /^\s*\d+\.\s+/.test(line);
const tag = ordered ? 'ol' : 'ul';
const items: string[] = [];
while (i < lines.length && (ordered ? /^\s*\d+\.\s+/.test(lines[i]!) : /^\s*[-*]\s+/.test(lines[i]!))) {
items.push(lines[i]!.replace(ordered ? /^\s*\d+\.\s+/ : /^\s*[-*]\s+/, ''));
i += 1;
}
out.push(`<${tag}>${items.map((item) => `${renderInline(item)}`).join('')}${tag}>`);
continue;
}
// Paragraph.
const para: string[] = [];
while (
i < lines.length
&& lines[i]!.trim() !== ''
&& !lines[i]!.startsWith('#')
&& !lines[i]!.startsWith('```')
&& !lines[i]!.startsWith('>')
&& !/^---+$/.test(lines[i]!.trim())
&& !/^\s*[-*]\s+/.test(lines[i]!)
&& !/^\s*\d+\.\s+/.test(lines[i]!)
) {
para.push(lines[i]!);
i += 1;
}
out.push(`${para.map(renderInline).join(' ')}
`);
}
return out.join('\n');
}
function splitTableRow(line: string): string[] {
return line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell) => cell.trim());
}
function renderInline(text: string): string {
const tokens: string[] = [];
let work = text.replace(/`([^`]+)`/g, (_m, code: string) => {
const idx = tokens.length;
tokens.push(`${escapeHtml(code)}`);
return `\u0000T${idx}\u0000`;
});
work = escapeHtml(work);
work = work.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1');
work = work.replace(/\*\*([^*]+)\*\*/g, '$1');
work = work.replace(/\u0000T(\d+)\u0000/g, (_m, idx: string) => tokens[Number(idx)] ?? '');
return work;
}
function escapeHtml(text: string): string {
return text
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"');
}
if (process.argv[1] && resolve(process.argv[1]) === resolve(import.meta.filename)) {
const repo = resolve(import.meta.dirname, '..');
const outArgIdx = process.argv.indexOf('--out');
const outDir = outArgIdx >= 0 && process.argv[outArgIdx + 1]
? resolve(process.argv[outArgIdx + 1]!)
: join(repo, 'build', 'mod-dev-docs');
const result = buildOfflineModDocs(join(repo, 'mod-dev-docs'), outDir);
console.log('Generated offline mod docs:', result.zh, result.en);
}