Thoth / server /util.js
mfirat007's picture
Upload 46 files
f41aded verified
Raw History Blame Contribute Delete
1.77 kB
export class HttpError extends Error {
constructor(status, message, extra) {
super(message);
this.status = status;
this.extra = extra;
}
}
const TEXT_EXT = new Set([
'tex', 'bib', 'cls', 'sty', 'bst', 'txt', 'md', 'csv', 'tikz', 'ltx', 'def', 'cfg',
'bbx', 'cbx', 'lbx', 'dtx', 'ins', 'clo', 'ldf', 'json', 'yaml', 'yml', 'gitignore', 'latexmkrc',
]);
const MIME = {
png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', svg: 'image/svg+xml',
webp: 'image/webp', pdf: 'application/pdf', eps: 'application/postscript',
};
export function extOf(p) {
const base = p.split('/').pop();
const i = base.lastIndexOf('.');
return i < 0 ? base.toLowerCase() : base.slice(i + 1).toLowerCase();
}
export const isTextPath = (p) => TEXT_EXT.has(extOf(p));
export const mimeOf = (p) => MIME[extOf(p)] || 'application/octet-stream';
/** Proje içi dosya yolunu doğrular ve normalleştirir ("a\\b/./c" -> "a/b/c"). */
export function cleanPath(p) {
if (typeof p !== 'string' || p.length > 200) throw new HttpError(400, 'Geçersiz dosya yolu.');
const parts = p.replace(/\\/g, '/').split('/').map((s) => s.trim()).filter((s) => s && s !== '.');
if (!parts.length || parts.some((s) => s === '..' || /[<>:"|?*\x00-\x1f]/.test(s))) {
throw new HttpError(400, 'Geçersiz dosya yolu.');
}
return parts.join('/');
}
export function requireString(value, name, { min = 1, max = 200 } = {}) {
if (typeof value !== 'string') throw new HttpError(400, `${name} gerekli.`);
const v = value.trim();
if (v.length < min) throw new HttpError(400, min > 1 ? `${name} en az ${min} karakter olmalı.` : `${name} gerekli.`);
if (v.length > max) throw new HttpError(400, `${name} en fazla ${max} karakter olabilir.`);
return v;
}