Skip to content

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.

14.3 KB
Raw Blame
// Dùng chung cho preview.mjs / render.mjs. Engine: HyperFrames (npm "hyperframes") gọi bằng CLI cục bộ.
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { stripSecrets } from './sandbox.mjs';

export const ENGINE = path.dirname(fileURLToPath(import.meta.url));
export const ROOT = path.dirname(ENGINE);
const HF_BIN = path.join(ROOT, 'node_modules', 'hyperframes', 'bin', 'hyperframes.mjs');

// Không telemetry, không tự kiểm tra cập nhật lúc render.
// Khoá render toàn máy của HyperFrames (HYPERFRAMES_RENDER_LOCK) bị kẹt trên Windows khi nhiều tiến trình chạy cùng lúc
// (2026-11-27: 14 tiến trình snapshot chờ mãi, thư mục khoá trống) → tắt nó, thay bằng hàng chờ riêng (acquireSlot) giới hạn
// số HyperFrames chạy song song (LUMREELS_HF_SLOTS, mặc định 3).
export function hfEnv() {
  const env = stripSecrets(process.env); // HyperFrames không cần khoá nào (L2)
  return {
    ...env,
    HYPERFRAMES_NO_TELEMETRY: '1',
    HYPERFRAMES_NO_UPDATE_CHECK: '1',
    HYPERFRAMES_SKIP_SKILLS: '1',
    HYPERFRAMES_RENDER_LOCK: 'off',
    DO_NOT_TRACK: '1',
  };
}
export const HF_ENV = hfEnv();

const SLOT_DIR = path.join(os.tmpdir(), 'lumreels-hf-slots');
const pidAlive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
/** Giành 1 chỗ chạy HyperFrames (dùng chung giữa mọi tiến trình trên máy). Trả hàm nhả chỗ. */
export async function acquireSlot({ max = Number(process.env.LUMREELS_HF_SLOTS) || 3, onWait } = {}) {
  fs.mkdirSync(SLOT_DIR, { recursive: true });
  let warned = false;
  for (;;) {
    for (let i = 0; i < max; i++) {
      const f = path.join(SLOT_DIR, `slot-${i}`);
      try {
        fs.writeFileSync(f, String(process.pid), { flag: 'wx' });
        return () => { try { if (fs.readFileSync(f, 'utf8') === String(process.pid)) fs.rmSync(f); } catch { /* đã nhả */ } };
      } catch {
        try {
          const pid = Number(fs.readFileSync(f, 'utf8'));
          const age = Date.now() - fs.statSync(f).mtimeMs;
          if (!pid || !pidAlive(pid) || age > hfTimeoutMs(600) + 60 * 1000) fs.rmSync(f, { force: true }); // chỗ của tiến trình đã chết / kẹt quá trần render dài nhất
        } catch { /* file vừa bị nhả */ }
      }
    }
    if (!warned && onWait) { onWait(); warned = true; }
    await new Promise((r) => setTimeout(r, 500));
  }
}

/** Chép engine/{vendor,fonts,runtime} vào <scene>/lib để cảnh import offline bằng đường dẫn ./lib/... */
export function syncLib(sceneDir) {
  const lib = path.join(sceneDir, 'lib');
  for (const sub of ['vendor', 'fonts', 'runtime']) {
    fs.cpSync(path.join(ENGINE, sub), path.join(lib, sub), { recursive: true, force: true });
  }
  return lib;
}

// L4: cảnh của mẫu chạy khoá thêm các lỗi này (lớp phụ; lớp chính là CSP + Chromium không mạng, engine/sandbox.mjs).
const RESTRICTED_PATTERNS = [
  [/\bWebSocket\b/, 'WebSocket'], [/\bEventSource\b/, 'EventSource'], [/\bsendBeacon\b/, 'navigator.sendBeacon'],
  [/\bXMLHttpRequest\b/, 'XMLHttpRequest'], [/\bRTCPeerConnection\b/, 'RTCPeerConnection'],
  [/\blocation\s*(?:\.\s*href\s*)?=(?!=)|\blocation\s*\.\s*(?:assign|replace)\s*\(/, 'đổi location'],
  [/\bwindow\s*\.\s*open\s*\(|\bopen\s*\(\s*["'`]/, 'window.open'],
  [/<iframe\b/i, '<iframe'], [/<object\b/i, '<object'], [/<embed\b/i, '<embed'], [/<form\b/i, '<form'],
  [/\bfile:/i, 'file:'], [/\bimportScripts\b/, 'importScripts'], [/\beval\s*\(/, 'eval('], [/\bnew\s+Function\b/, 'new Function'],
  [/\batob\s*\(/, 'atob('], [/\bimport\s*\(/, 'import() động'], [/\bnew\s+(?:Shared)?Worker\b/, 'Worker'],
  [/<meta[^>]+http-equiv\s*=\s*["']?refresh/i, '<meta refresh'], [/<base\b/i, '<base'],
  [/\biframe\b|\bframes\s*\[|\b(?:window|self|top|parent|globalThis)\s*\[\s*\d/i, 'iframe / frames[…]'], [/\bString\s*\.\s*fromCharCode\b/, 'String.fromCharCode'],
  [/\b(?:top|parent|opener)\s*\.\s*location\b/, 'top/parent.location'],
];
/** fetch( với đối số không phải chuỗi './lib/…' → lỗi (cảnh khoá chỉ được đọc tài nguyên engine). */
function badFetches(html) {
  const out = [];
  for (const m of html.matchAll(/\bfetch\s*\(\s*([^)]{0,80})/g)) {
    if (!/^["'`]\.\/lib\/[\w./-]+["'`]/.test(m[1].trim())) out.push(m[0].slice(0, 60));
  }
  return out;
}

/** Kiểm nhanh index.html theo AUTHORING.md. Trả {errors, warnings, meta}. restricted: thêm luật L4 của mẫu chạy khoá. */
/** expect: {width, height} của job (tỉ lệ khung đã chọn) → #root phải đúng cỡ đó. */
export function lintScene(sceneDir, { restricted = false, expect = null } = {}) {
  const errors = [];
  const warnings = [];
  const file = path.join(sceneDir, 'index.html');
  if (!fs.existsSync(file)) return { errors: [`Không thấy ${file}`], warnings, meta: null };
  const html = fs.readFileSync(file, 'utf8');
  const remote = html.match(/(?:src|href)\s*=\s*["']\s*(?:https?:)?\/\/[^"']+/gi) || [];
  const remoteCss = html.match(/@import\s+url\(\s*["']?(?:https?:)?\/\//gi) || [];
  const fetches = html.match(/\bfetch\s*\(\s*["'`]https?:/gi) || [];
  for (const r of [...remote, ...remoteCss, ...fetches]) errors.push(`Gọi mạng lúc render bị cấm: ${r.slice(0, 80)}`);
  if (/Math\.random\s*\(/.test(html)) errors.push('Dùng Math.random() → không tất định. Dùng VideoScene.rng(seed).');
  if (/Date\.now\s*\(|performance\.now\s*\(|new Date\s*\(\s*\)/.test(html)) errors.push('Dùng đồng hồ thật (Date.now/performance.now) → không seek được. Mọi thứ phải là hàm của t.');
  if (/requestAnimationFrame\s*\(/.test(html)) warnings.push('Có requestAnimationFrame: đừng tự chạy vòng lặp animation, chỉ vẽ trong render(t).');
  if (!/VideoScene\.define\s*\(/.test(html)) errors.push('Thiếu VideoScene.define({ duration, fps, render(t) }).');
  if (!/lib\/runtime\/scene\.js/.test(html)) errors.push('Thiếu <script src="./lib/runtime/scene.js">.');
  if (!/lib\/vendor\/gsap\.min\.js/.test(html)) errors.push('Thiếu <script src="./lib/vendor/gsap.min.js"> (cầu nối HyperFrames cần GSAP).');
  const rootTag = html.match(/<div[^>]*id=["']root["'][^>]*>/i);
  let meta = null;
  if (!rootTag) errors.push('Thiếu <div id="root" ...> với data-duration/data-width/data-height.');
  else {
    const attr = (n) => (rootTag[0].match(new RegExp(`data-${n}=["']([^"']+)["']`)) || [])[1];
    meta = { duration: Number(attr('duration')), width: Number(attr('width')), height: Number(attr('height')), fps: Number(attr('fps') || 30) };
    if (!(meta.duration > 0)) errors.push('#root thiếu data-duration (giây).');
    if (!meta.width || !meta.height) errors.push('#root thiếu data-width / data-height.');
    if (!rootTag[0].includes('data-composition-id')) errors.push('#root thiếu data-composition-id="main".');
    if (expect && meta.width && meta.height && (meta.width !== expect.width || meta.height !== expect.height)) {
      errors.push(`Khung ${meta.width}×${meta.height} sai: job này chọn khung ${expect.width}×${expect.height}. Sửa data-width/data-height của #root, kích thước html/body/#root và width/height trong VideoScene.define.`);
    }
    const def = html.match(/VideoScene\.define\s*\(\s*\{[^]*?\bwidth\s*:\s*(\d+)\s*,\s*height\s*:\s*(\d+)/);
    if (def && meta.width && meta.height && (Number(def[1]) !== meta.width || Number(def[2]) !== meta.height)) {
      errors.push(`VideoScene.define width/height (${def[1]}×${def[2]}) không khớp #root (${meta.width}×${meta.height}).`);
    }
  }
  if (restricted) {
    for (const [re, name] of RESTRICTED_PATTERNS) if (re.test(html)) errors.push(`Cảnh chạy khoá không được dùng ${name} (chỉ dùng ./lib, không gọi mạng, không mở trang khác).`);
    for (const f of badFetches(html)) errors.push(`Cảnh chạy khoá chỉ được fetch('./lib/…'): ${f}`);
  }
  const fonts = lintFonts(html);
  errors.push(...fonts.errors);
  warnings.push(...fonts.warnings);
  return { errors, warnings, meta };
}

// ---------- font ----------
const GENERIC_FAMILIES = new Set(['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-sans-serif', 'ui-serif', 'ui-monospace', 'emoji', 'math', 'inherit', 'initial', 'unset', 'revert']);
/** Danh sách font engine có (engine/fonts/fonts.json do setup.mjs sinh). */
export function availableFonts() {
  try { return JSON.parse(fs.readFileSync(path.join(ENGINE, 'fonts', 'fonts.json'), 'utf8')); } catch { return []; }
}
function splitFamilies(list) {
  return list.split(',').map((s) => s.trim().replace(/^["']|["']$/g, '').trim()).filter(Boolean);
}
/** Kiểm tĩnh: mọi font-family khai báo (CSS, style inline, ctx.font, fontFamily trong JS, biến CSS) phải có trong fonts.css. */
export function lintFonts(html) {
  const errors = [];
  const warnings = [];
  const have = new Set(availableFonts().map((f) => f.family.toLowerCase()));
  if (!have.size) return { errors, warnings: ['Chưa có engine/fonts/fonts.json (chạy npm install) — bỏ qua kiểm font'] };
  const used = new Set();
  const add = (list) => { for (const f of splitFamilies(list)) if (!/^var\(/.test(f) && !/[${}]/.test(f)) used.add(f); };
  // CSS: font-family: …; và JS: fontFamily = '…' / style.fontFamily
  for (const m of html.matchAll(/font-family\s*:\s*([^;}{<>\n]+)/gi)) add(m[1]);
  for (const m of html.matchAll(/fontFamily\s*[:=]\s*(["'`])([^"'`]+)\1/g)) add(m[2]);
  // Shorthand / ctx.font: lấy các tên có ngoặc kép, hoặc cụm sau cỡ chữ (… 120px Oswald, sans-serif)
  for (const m of html.matchAll(/(?:\bfont\s*:|\.font\s*=)\s*([^;\n]+)/g)) {
    const v = m[1];
    for (const q of v.matchAll(/(["'])([A-Za-z][A-Za-z0-9 ]*[A-Za-z0-9])\1/g)) {
      if (/\d|\b(px|em)\b/.test(v) && !/^(px|em|rem|pt|bold|normal|italic)$/i.test(q[2])) used.add(q[2].trim());
    }
    const after = v.match(/\d(?:px|em|rem|pt|%)(?:\s*\/\s*[\d.]+\w*)?\s+([A-Za-z][^"'`;]*?)(?:["'`;]|$)/);
    if (after && !/var\(/.test(after[1])) add(after[1]);
  }
  // Biến CSS chứa danh sách font (vd --display: 'Oswald', sans-serif)
  for (const m of html.matchAll(/--[\w-]+\s*:\s*([^;}{]+)/g)) {
    if (/\b(serif|sans-serif|monospace|cursive)\b/.test(m[1]) || /^\s*["'][A-Z]/.test(m[1])) add(m[1]);
  }
  const bad = [...used].filter((f) => !GENERIC_FAMILIES.has(f.toLowerCase()) && !have.has(f.toLowerCase()));
  for (const f of bad) errors.push(`Font ngoài danh sách: "${f}" — không có trong engine/fonts (sẽ rơi về font hệ thống). Xem bảng ánh xạ AUTHORING §4.`);
  if (/₫|&#8363;|&#x20ab;|\\u20ab/i.test(html)) {
    warnings.push('Có ký hiệu "₫": nhiều font vẽ sai hoặc lệch dòng → viết "đ" (vd 3.000.000đ) hoặc "VNĐ" (AUTHORING §5).');
  }
  for (const m of html.matchAll(/font-size\s*:\s*(\d+(?:\.\d+)?)px/g)) {
    if (Number(m[1]) < 28) { warnings.push(`Có font-size ${m[1]}px < 28px: chữ quá nhỏ trên cạnh ngắn 1080 (tối thiểu 28px, chữ chính ≥ 40px).`); break; }
  }
  if (/-webkit-text-stroke/.test(html) && !/paint-order\s*:\s*stroke/.test(html)) {
    warnings.push('Có -webkit-text-stroke mà không có paint-order: stroke fill → viền ăn vào trong nét chữ. Thêm paint-order: stroke fill (AUTHORING §5).');
  }
  return { errors, warnings, used: [...used] };
}

/** Giới hạn 1 lượt HyperFrames theo thời lượng cảnh: 10 phút + 2 phút cho mỗi 8 giây video, trần 3 giờ. */
export function hfTimeoutMs(durationS = 8) {
  return Math.min(180, 10 + 2 * Math.ceil(Math.max(0, Number(durationS) || 8) / 8)) * 60 * 1000;
}
/** data-duration của <sceneDir>/index.html (args[1] của snapshot/render); không đọc được → 8. */
function sceneDuration(sceneDir) {
  try { return Number(/data-duration=["']([\d.]+)["']/.exec(fs.readFileSync(path.join(sceneDir, 'index.html'), 'utf8'))?.[1]) || 8; } catch { return 8; }
}

/** Chạy CLI HyperFrames: chờ chỗ trống (acquireSlot), có giới hạn thời gian (theo thời lượng cảnh, hfTimeoutMs) để không treo vô hạn. */
export async function runHF(args, { cwd, onLine, env, timeoutMs = hfTimeoutMs(sceneDuration(args[1] || cwd || '.')) } = {}) {
  const release = await acquireSlot({ onWait: () => onLine?.('chờ chỗ chạy HyperFrames (đang có nhiều render cùng lúc)…') });
  try {
    return await new Promise((resolve) => {
      const p = spawn(process.execPath, [HF_BIN, ...args], { cwd, env: { ...hfEnv(), ...(env || {}) }, windowsHide: true });
      let out = '';
      const timer = setTimeout(() => { out += `\n[lumreels] HyperFrames quá ${Math.round(timeoutMs / 1000)}s, dừng\n`; p.kill(); }, timeoutMs);
      const feed = (d) => {
        const s = d.toString();
        out += s;
        if (onLine) for (const l of s.split(/\r?\n/)) if (l.trim()) onLine(l);
      };
      p.stdout.on('data', feed);
      p.stderr.on('data', feed);
      p.on('error', (e) => { clearTimeout(timer); resolve({ code: -1, out: out + String(e) }); });
      p.on('close', (code) => { clearTimeout(timer); resolve({ code, out }); });
    });
  } finally {
    release();
  }
}

export function run(cmd, args, opts = {}) {
  return new Promise((resolve) => {
    const { timeoutMs, ...rest } = opts;
    const p = spawn(cmd, args, { windowsHide: true, ...rest });
    let out = '';
    const timer = timeoutMs ? setTimeout(() => { out += `
[quá ${timeoutMs / 1000}s, dừng]`; p.kill('SIGKILL'); }, timeoutMs) : null;
    p.on('close', () => timer && clearTimeout(timer));
    p.stdout?.on('data', (d) => (out += d));
    p.stderr?.on('data', (d) => (out += d));
    p.on('error', (e) => resolve({ code: -1, out: String(e) }));
    p.on('close', (code) => resolve({ code, out }));
  });
}

export function parseArgs(argv) {
  const pos = [];
  const opt = {};
  for (let i = 0; i < argv.length; i++) {
    const a = argv[i];
    if (a.startsWith('-')) {
      const k = a.replace(/^-+/, '');
      const v = argv[i + 1] && !argv[i + 1].startsWith('-') ? argv[++i] : true;
      opt[k] = v;
    } else pos.push(a);
  }
  return { pos, opt };
}

export async function probe(file) {
  const r = await run('ffprobe', ['-v', 'error', '-show_entries', 'stream=codec_name,width,height,r_frame_rate,nb_frames,pix_fmt:format=duration', '-of', 'json', file]);
  try { return JSON.parse(r.out); } catch { return null; }
}