Download server/compile.js from SSSAssist/Thoth: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/spaces/SSSAssist/Thoth/resolve/main/server/compile.js
- Command line
-
hf download hf://spaces/SSSAssist/Thoth/server/compile.js
-
curl -L -o compile.js https://huggingface.co/spaces/SSSAssist/Thoth/resolve/main/server/compile.js
11.4 kB
| import { spawn, spawnSync } from 'node:child_process'; | |
| import { existsSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs'; | |
| import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'; | |
| import path from 'node:path'; | |
| import { Router } from 'express'; | |
| import { | |
| BIN_DIR, BUILD_DIR, COMPILE_SANDBOX, COMPILE_TIMEOUT_MS, DATA_DIR, KAFES_BIN, TECTONIC_BIN, TECTONIC_CACHE_DIR, TEX_SUPPORT_DIR, | |
| } from './config.js'; | |
| import { db } from './db.js'; | |
| import { withProject } from './store.js'; | |
| import { forwardSearch, inverseSearch, loadSynctex } from './synctex.js'; | |
| import { HttpError, cleanPath } from './util.js'; | |
| const MAX_PARALLEL = 2; | |
| let running = 0; | |
| const waiting = []; | |
| const projectLocks = new Map(); | |
| async function acquireSlot() { | |
| if (running >= MAX_PARALLEL) await new Promise((resolve) => waiting.push(resolve)); | |
| running += 1; | |
| } | |
| function releaseSlot() { | |
| running -= 1; | |
| waiting.shift()?.(); | |
| } | |
| // Kullanıcıya gösterilmeyecek, Tectonic'e özgü gürültü satırları. | |
| const NOISE = /internal consistency problem|Fontconfig error|halted on potentially-recoverable|TeX rerun seems needed|Object @page\.\d+ already defined/; | |
| /** Tectonic çıktısından hata ve uyarıları ayıklar. */ | |
| export function parseProblems(output) { | |
| const problems = []; | |
| for (const line of output.split(/\r?\n/)) { | |
| if (NOISE.test(line)) continue; | |
| const located = line.match(/^(error|warning): (.+?):(\d+): (.*)$/); | |
| if (located) { | |
| problems.push({ | |
| level: located[1], | |
| file: located[2].replace(/\\/g, '/').replace(/^\.\//, ''), | |
| line: Number(located[3]), | |
| message: located[4], | |
| }); | |
| continue; | |
| } | |
| const plain = line.match(/^(error|warning): (.*)$/); | |
| if (plain) problems.push({ level: plain[1], file: null, line: null, message: plain[2] }); | |
| } | |
| return problems; | |
| } | |
| // Derleyiciye sunucunun ortam değişkenleri (API anahtarları vb.) geçirilmez; yalnızca gerekenler verilir. | |
| // Tectonic, biblatex belgelerinde biber'i PATH üzerinden çalıştırır; kurulu araçlar öne alınır. | |
| const ENV_KEEP = /^(PATH|SYSTEMROOT|WINDIR|TEMP|TMP|USERPROFILE|LOCALAPPDATA|APPDATA|PATHEXT|COMSPEC|HOME|LANG|LC_ALL)$/i; | |
| const pathKey = Object.keys(process.env).find((k) => k.toUpperCase() === 'PATH') ?? 'PATH'; | |
| function tectonicEnv(tmpDir) { | |
| const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => ENV_KEEP.test(k))); | |
| env[pathKey] = [BIN_DIR, process.env[pathKey]].filter(Boolean).join(path.delimiter); | |
| env.TECTONIC_CACHE_DIR = TECTONIC_CACHE_DIR; | |
| // Kafeste yalnızca proje klasörüne yazılabilir; geçici dosyalar (ör. biber'in açtığı paket) oraya gider. | |
| if (COMPILE_SANDBOX === 'landlock') Object.assign(env, { TMPDIR: tmpDir, HOME: tmpDir }); | |
| return env; | |
| } | |
| // Kafeste okunabilen sistem klasörleri. Uygulama kodu, veri klasörü ve /proc bunların dışındadır. | |
| const SYSTEM_RO = ['/usr', '/lib', '/lib64', '/bin', '/etc']; | |
| const jailed = (ro, rw, cmd) => [KAFES_BIN, ['--ro', ...ro, '--rw', ...rw, '--', ...cmd]]; | |
| /** Derleme kafesinin durumu; kafes istenmiş ama çalışmıyorsa derleme kapatılır. */ | |
| export const sandbox = checkSandbox(); | |
| function checkSandbox() { | |
| if (COMPILE_SANDBOX === 'none') return { mode: 'none', ok: true, detail: 'Derleme yalıtılmadan çalışıyor.' }; | |
| if (COMPILE_SANDBOX !== 'landlock') return { mode: COMPILE_SANDBOX, ok: false, detail: 'Bilinmeyen COMPILE_SANDBOX değeri.' }; | |
| const probe = spawnSync(KAFES_BIN, ['--dene'], { encoding: 'utf8' }); | |
| if (probe.status !== 0) { | |
| return { mode: 'landlock', ok: false, detail: (probe.stdout || probe.error?.message || 'kafes çalışmadı').trim() }; | |
| } | |
| mkdirSync(TECTONIC_CACHE_DIR, { recursive: true }); | |
| // Öz denetim: kafesteki bir süreç sunucunun ortam değişkenlerini ve veritabanını okuyamamalı, | |
| // veri klasörüne yazamamalı; kendi klasöründe ise çalışabilmeli. | |
| const runs = (cmd, rw = '/dev/null') => { | |
| const [bin, args] = jailed(SYSTEM_RO, [rw], cmd); | |
| return spawnSync(bin, args, { env: { PATH: '/usr/bin:/bin' } }).status === 0; | |
| }; | |
| const leaks = [ | |
| runs(['cat', `/proc/${process.pid}/environ`]) && 'sunucunun ortam değişkenleri okunabiliyor', | |
| runs(['cat', path.join(DATA_DIR, 'thoth.db')]) && 'veritabanı okunabiliyor', | |
| runs(['touch', path.join(DATA_DIR, '.kafes-deneme')]) && 'veri klasörüne yazılabiliyor', | |
| !runs(['touch', path.join(TECTONIC_CACHE_DIR, '.kafes-deneme')], TECTONIC_CACHE_DIR) && 'izin verilen klasöre yazılamıyor', | |
| ].filter(Boolean); | |
| const abi = probe.stdout.trim(); | |
| if (leaks.length) return { mode: 'landlock', ok: false, detail: `${abi}; öz denetim başarısız: ${leaks.join(', ')}` }; | |
| return { mode: 'landlock', ok: true, detail: `${abi}; öz denetim geçti` }; | |
| } | |
| if (!sandbox.ok) console.error(`UYARI: Derleme kafesi çalışmıyor, derleme kapalı: ${sandbox.detail}`); | |
| /** | |
| * Her derlemede proje klasörüne konan destek dosyaları (ör. APA 7 Türkçe yerelleştirmesi). | |
| * Projede aynı adda bir dosya varsa projenin dosyası kullanılır. | |
| */ | |
| export const SUPPORT_FILES = readdirSync(TEX_SUPPORT_DIR).map((name) => ({ | |
| name, | |
| content: readFileSync(path.join(TEX_SUPPORT_DIR, name)), | |
| })); | |
| function runTectonic(args, cwd, base) { | |
| const tmp = path.join(base, 'tmp'); | |
| const [bin, binArgs] = COMPILE_SANDBOX === 'landlock' | |
| ? jailed([...SYSTEM_RO, BIN_DIR, '/dev/urandom'], [base, TECTONIC_CACHE_DIR, '/dev/null'], [TECTONIC_BIN, ...args]) | |
| : [TECTONIC_BIN, args]; | |
| return new Promise((resolve) => { | |
| const child = spawn(bin, binArgs, { cwd, env: tectonicEnv(tmp), windowsHide: true }); | |
| let output = ''; | |
| let timedOut = false; | |
| const timer = setTimeout(() => { | |
| timedOut = true; | |
| child.kill(); | |
| }, COMPILE_TIMEOUT_MS); | |
| child.stdout.on('data', (d) => (output += d)); | |
| child.stderr.on('data', (d) => (output += d)); | |
| child.on('error', (err) => { | |
| clearTimeout(timer); | |
| resolve({ code: -1, output: `${output}\nerror: Derleyici başlatılamadı: ${err.message}` }); | |
| }); | |
| child.on('close', (code) => { | |
| clearTimeout(timer); | |
| if (timedOut) output += `\nerror: Derleme ${Math.round(COMPILE_TIMEOUT_MS / 1000)} saniyelik süre sınırını aştı ve durduruldu.`; | |
| resolve({ code: timedOut ? -1 : code, output }); | |
| }); | |
| }); | |
| } | |
| const pdfPath = (project) => | |
| path.join(BUILD_DIR, project.id, 'out', `${path.basename(project.main_file).replace(/\.[^.]+$/, '')}.pdf`); | |
| async function compileProject(project) { | |
| if (!existsSync(TECTONIC_BIN)) { | |
| throw new HttpError(500, 'LaTeX derleyicisi (Tectonic) kurulu değil. Sunucuda "npm run setup" komutunu çalıştırın.'); | |
| } | |
| if (!sandbox.ok) throw new HttpError(503, `Derleme şu anda kapalı: güvenli derleme ortamı kurulamadı (${sandbox.detail}).`); | |
| const base = path.join(BUILD_DIR, project.id); | |
| const src = path.join(base, 'src'); | |
| const out = path.join(base, 'out'); | |
| await rm(src, { recursive: true, force: true }); | |
| await mkdir(out, { recursive: true }); | |
| await mkdir(path.join(base, 'tmp'), { recursive: true }); | |
| const files = db.prepare('SELECT path, content FROM files WHERE project_id = ?').all(project.id); | |
| for (const f of files) { | |
| const target = path.join(src, ...f.path.split('/')); | |
| await mkdir(path.dirname(target), { recursive: true }); | |
| await writeFile(target, f.content); | |
| } | |
| for (const s of SUPPORT_FILES) { | |
| if (!files.some((f) => f.path === s.name)) await writeFile(path.join(src, s.name), s.content); | |
| } | |
| const started = Date.now(); | |
| // --untrusted: \write18 (kabuk çalıştırma) gibi güvensiz özellikleri kapatır. | |
| const args = ['-X', 'compile', project.main_file, '--outdir', out, '--keep-logs', '--untrusted', '--synctex']; | |
| // Tectonic 0.15, .bbl dosyasının değişip değişmediğini saptayamayıp kaynakçalı belgeleri | |
| // üst sınıra (7 tur) kadar yeniden derliyor. Kaynakça varsa tur sayısı sabitlenir: | |
| // TeX + BibTeX + 2 TeX turu, atıfların ve içindekilerin oturması için yeterlidir. | |
| const usesBibtex = files.some((f) => typeof f.content === 'string' && /\\bibliography\s*\{/.test(f.content)); | |
| if (usesBibtex) args.push('--reruns', '2'); | |
| const { code, output } = await runTectonic(args, src, base); | |
| // Kaynak kopyası derlemeden sonra silinir; projelerin dosyaları diskte açıkta kalmaz. | |
| await rm(src, { recursive: true, force: true }); | |
| const ok = code === 0; | |
| let texLog = ''; | |
| try { | |
| texLog = await readFile(pdfPath(project).replace(/\.pdf$/, '.log'), 'utf8'); | |
| } catch { | |
| // günlük dosyası her zaman oluşmaz | |
| } | |
| return { | |
| ok, | |
| problems: parseProblems(output), | |
| log: output.trim(), | |
| texLog: texLog.slice(-200_000), | |
| durationMs: Date.now() - started, | |
| hasPdf: existsSync(pdfPath(project)), | |
| }; | |
| } | |
| export const compileRouter = Router(); | |
| compileRouter.post('/projects/:id/compile', withProject(), async (req, res) => { | |
| const id = req.project.id; | |
| // Aynı proje için derlemeler sıraya girer; toplamda en fazla MAX_PARALLEL derleme çalışır. | |
| const previous = projectLocks.get(id) ?? Promise.resolve(); | |
| const job = previous.catch(() => {}).then(async () => { | |
| await acquireSlot(); | |
| try { | |
| return await compileProject(req.project); | |
| } finally { | |
| releaseSlot(); | |
| } | |
| }); | |
| projectLocks.set(id, job); | |
| try { | |
| res.json(await job); | |
| } finally { | |
| if (projectLocks.get(id) === job) projectLocks.delete(id); | |
| } | |
| }); | |
| // ---- SyncTeX: kaynak ile PDF arasında gezinme ---- | |
| const synctexCache = new Map(); // proje kimliği -> { mtimeMs, data } | |
| function synctexFor(project) { | |
| const file = pdfPath(project).replace(/\.pdf$/, '.synctex.gz'); | |
| let mtimeMs; | |
| try { | |
| mtimeMs = statSync(file).mtimeMs; | |
| } catch { | |
| throw new HttpError(404, 'Önce belgeyi derleyin.'); | |
| } | |
| const cached = synctexCache.get(project.id); | |
| if (cached?.mtimeMs === mtimeMs) return cached.data; | |
| const data = loadSynctex(file, path.join(BUILD_DIR, project.id, 'src')); | |
| synctexCache.set(project.id, { mtimeMs, data }); | |
| return data; | |
| } | |
| compileRouter.get('/projects/:id/synctex/forward', withProject(), (req, res) => { | |
| const file = cleanPath(req.query.file); | |
| const line = Number(req.query.line); | |
| if (!Number.isInteger(line) || line < 1) throw new HttpError(400, 'Geçersiz satır numarası.'); | |
| const result = forwardSearch(synctexFor(req.project), file, line); | |
| if (!result) throw new HttpError(404, 'Bu satırın PDF\'teki karşılığı bulunamadı. Dosya ana belgeye eklenmemiş ya da henüz derlenmemiş olabilir.'); | |
| res.json(result); | |
| }); | |
| compileRouter.get('/projects/:id/synctex/inverse', withProject(), (req, res) => { | |
| const page = Number(req.query.page); | |
| const x = Number(req.query.x); | |
| const y = Number(req.query.y); | |
| if (!Number.isInteger(page) || page < 1 || !Number.isFinite(x) || !Number.isFinite(y)) { | |
| throw new HttpError(400, 'Geçersiz konum.'); | |
| } | |
| const result = inverseSearch(synctexFor(req.project), page, x, y); | |
| if (!result) throw new HttpError(404, 'Bu noktanın kaynaktaki karşılığı bulunamadı.'); | |
| res.json(result); | |
| }); | |
| compileRouter.get('/projects/:id/pdf', withProject(), (req, res) => { | |
| const file = pdfPath(req.project); | |
| if (!existsSync(file)) throw new HttpError(404, 'Henüz derlenmiş bir PDF yok.'); | |
| if (req.query.indir) res.attachment(`${req.project.title}.pdf`); | |
| res.set('Cache-Control', 'no-store').type('application/pdf').sendFile(file); | |
| }); | |