Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.
// Kiểm font lúc chạy: mở cảnh trong Chrome (puppeteer-core, Chrome có sẵn trên máy), seek vài thời điểm,
// gọi window.__fontReport() (engine/runtime/scene.js) để bắt chữ đang hiển thị bằng font hệ thống / thiếu glyph.
// node engine/fontcheck.mjs <sceneDir> [--json]
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { availableFonts, syncLib, parseArgs } from './lib.mjs';
import { CSP } from './sandbox.mjs';
const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css',
'.woff2': 'font/woff2', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg' };
export function findChrome() {
const c = [process.env.CHROME_PATH,
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
path.join(process.env.LOCALAPPDATA || '', 'Google\\Chrome\\Application\\chrome.exe'),
'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser'];
return c.find((p) => p && fs.existsSync(p)) || null;
}
function serve(dir) {
return new Promise((resolve) => {
const srv = http.createServer((req, res) => {
const rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '') || 'index.html';
const file = path.resolve(dir, rel);
if (!file.startsWith(path.resolve(dir) + path.sep) || !fs.existsSync(file) || !fs.statSync(file).isFile()) { res.writeHead(404); return res.end(); }
// CSP qua header (chặn cả WebSocket, thứ request interception của puppeteer không bắt được)
res.writeHead(200, { 'Content-Type': MIME[path.extname(file).toLowerCase()] || 'application/octet-stream', 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff' });
fs.createReadStream(file).pipe(res);
});
srv.listen(0, '127.0.0.1', () => resolve(srv));
});
}
/** Trả {ok, skipped?, issues:[{kind,text,font,weight,why,t}], lines:[…]} */
export async function fontCheck(sceneDir, { log = () => {}, times, readOnly = false } = {}) {
sceneDir = path.resolve(sceneDir);
if (readOnly) { // không ghi gì vào thư mục cảnh (vd cảnh của agent khác): chép ra thư mục tạm
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'fontcheck-'));
fs.cpSync(sceneDir, tmp, { recursive: true, filter: (s) => !/^[\\/](lib|\.hyperframes)([\\/]|$)/.test(path.relative(sceneDir, s) ? '/' + path.relative(sceneDir, s) : '') });
try { return await fontCheck(tmp, { log, times }); } finally { fs.rmSync(tmp, { recursive: true, force: true }); }
}
const chrome = findChrome();
if (!chrome) return { ok: true, skipped: 'không thấy Chrome (đặt CHROME_PATH)', issues: [], lines: [] };
let puppeteer;
try { puppeteer = (await import('puppeteer-core')).default; } catch { return { ok: true, skipped: 'thiếu puppeteer-core', issues: [], lines: [] }; }
syncLib(sceneDir);
const kinds = Object.fromEntries(availableFonts().map((f) => [f.family, f.kind]));
const srv = await serve(sceneDir);
const port = srv.address().port;
// Chromium không mạng: mọi thứ (kể cả 127.0.0.1 cổng khác) đi qua proxy chết, trừ đúng máy chủ cảnh ở trên.
const browser = await puppeteer.launch({ executablePath: chrome, headless: true, args: ['--no-first-run', '--no-default-browser-check', '--disable-extensions',
'--proxy-server=http://127.0.0.1:9', `--proxy-bypass-list=<-loopback>;127.0.0.1:${port}`, '--disable-quic', '--force-webrtc-ip-handling-policy=disable_non_proxied_udp'] });
const issues = [];
const errors = [];
try {
const page = await browser.newPage();
// cỡ khung theo #root của cảnh (9:16 1080×1920, 16:9 1920×1080, 4:3 1440×1080, 3:4 1080×1440)
let vw = 1080; let vh = 1920;
try {
const tag = (fs.readFileSync(path.join(sceneDir, 'index.html'), 'utf8').match(/<div[^>]*id=["']root["'][^>]*>/i) || [''])[0];
const w = Number((tag.match(/data-width=["'](\d+)/) || [])[1]); const h = Number((tag.match(/data-height=["'](\d+)/) || [])[1]);
if (w >= 200 && h >= 200 && w <= 4096 && h <= 4096) { vw = w; vh = h; }
} catch { /* giữ 9:16 */ }
await page.setViewport({ width: vw, height: vh });
page.on('pageerror', (e) => errors.push(String(e.message || e).slice(0, 200)));
// Shader GLSL không biên dịch: Three.js chỉ in console.error, cảnh vẫn chạy nhưng mất hiệu ứng (AUTHORING §10.10).
let shaderErrs = 0;
page.on('console', (m) => {
const txt = m.text();
if (m.type() === 'error' && /Shader Error|WebGLProgram|ERROR: \d+:\d+/i.test(txt) && shaderErrs++ < 3) {
errors.push('SHADER_ERROR (shader không biên dịch, hiệu ứng sẽ mất): ' + txt.replace(/\s+/g, ' ').slice(0, 300));
}
});
// Chỉ cho request tới đúng máy chủ cảnh (không phải 127.0.0.1 bất kỳ: server LumReels cũng nằm ở đó).
const own = `http://127.0.0.1:${port}/`;
await page.setRequestInterception(true);
page.on('request', (r) => (r.url().startsWith(own) || /^(data|blob):/.test(r.url()) ? r.continue() : r.abort()));
await page.goto(`${own}index.html`, { waitUntil: 'load', timeout: 30000 });
await page.waitForFunction('window.__scene && window.__fontReport', { timeout: 20000 });
await page.evaluate('window.__scene.ready');
const D = await page.evaluate('window.__scene.duration');
const ts = times || [0, D * 0.25, D * 0.5, D * 0.75, Math.max(0, D - 0.05)];
const seen = new Set();
for (const t of ts) {
await page.evaluate((x) => window.__scene.seek(x), t);
await page.evaluate('document.fonts.ready');
const rep = await page.evaluate('window.__fontReport()');
for (const i of rep) {
const key = `${i.kind}|${i.text}|${i.font}|${i.weight}`;
if (seen.has(key)) continue;
seen.add(key);
issues.push({ ...i, t: +t.toFixed(2) });
}
// Số in bằng font script/viết tay: khó đọc (luật AUTHORING §5).
const digits = await page.evaluate(() => {
const out = [];
document.querySelectorAll('body *').forEach((el) => {
const own = Array.from(el.childNodes).filter((n) => n.nodeType === 3).map((n) => n.nodeValue).join('').trim();
if (!/\d/.test(own)) return;
const cs = getComputedStyle(el);
if (cs.display === 'none' || cs.visibility === 'hidden' || Number(cs.opacity) === 0) return;
out.push({ text: own.slice(0, 40), font: cs.fontFamily.split(',')[0].trim().replace(/^["']|["']$/g, '') });
});
return out;
});
for (const d of digits) {
if (!['script', 'hand'].includes(kinds[d.font])) continue;
const key = `FONT_DIGITS|${d.text}|${d.font}`;
if (seen.has(key)) continue;
seen.add(key);
issues.push({ kind: 'FONT_DIGITS', text: d.text, font: d.font, why: 'con số dùng font script/viết tay — khó đọc, đổi sang sans/mono', t: +t.toFixed(2) });
}
}
} catch (e) {
errors.push('fontcheck: ' + String(e.message || e).slice(0, 200));
} finally {
await browser.close().catch(() => {});
srv.close();
}
const lines = issues.map((i) => `${i.kind}: "${i.text}" ${i.font} ${i.weight || ''}${i.why ? ' — ' + i.why : ''} (t=${i.t}s)`.replace(/\s+—/, ' —'));
for (const l of lines) log(l);
for (const e of errors) log('CẢNH BÁO ' + e);
return { ok: !issues.some((i) => i.kind === 'FONT_OUTSIDE' || i.kind === 'FONT_FALLBACK'), issues, lines, errors };
}
if (path.resolve(process.argv[1] || '') === fileURLToPath(import.meta.url)) {
const { pos, opt } = parseArgs(process.argv.slice(2));
if (!pos[0]) { console.error('Dùng: node engine/fontcheck.mjs <sceneDir> [--json] [--readonly]'); process.exit(2); }
const r = await fontCheck(pos[0], { log: opt.json ? () => {} : (l) => console.log(l), readOnly: !!opt.readonly });
if (opt.json) console.log(JSON.stringify(r, null, 2));
else console.log(r.skipped ? `BỎ QUA: ${r.skipped}` : r.issues.length ? `${r.issues.length} vấn đề font` : 'FONT OK');
process.exit(r.ok ? 0 : 1);
}