fix: editor

This commit is contained in:
2026-04-22 20:20:09 +07:00
parent c828bf7767
commit 994a13da52
8 changed files with 286 additions and 127 deletions
+37 -5
View File
@@ -1,9 +1,20 @@
import puppeteer from 'puppeteer';
import { resolve, basename } from 'path';
import { resolve, basename, dirname } from 'path';
import { existsSync, mkdirSync } from 'fs';
import { fileURLToPath } from 'url';
import { createServer } from 'http';
import { readFile } from 'fs/promises';
import { extname } from 'path';
const OUTPUT_DIR = resolve(fileURLToPath(import.meta.url), '../../../output/pdf');
const __dirname = dirname(fileURLToPath(import.meta.url));
const PROJECT_ROOT = resolve(__dirname, '../..');
const OUTPUT_DIR = resolve(PROJECT_ROOT, 'output/pdf');
const MIME_TYPES = {
'.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
'.webp': 'image/webp', '.svg': 'image/svg+xml', '.json': 'application/json',
};
async function generatePdf(htmlPath) {
const absolutePath = resolve(htmlPath);
@@ -14,13 +25,33 @@ async function generatePdf(htmlPath) {
mkdirSync(OUTPUT_DIR, { recursive: true });
const pdfName = basename(absolutePath, '.html') + '.pdf';
// Strip .output and .template from PDF filename
let pdfName = basename(absolutePath, '.html');
pdfName = pdfName.replace(/\.(output|template)$/, '') + '.pdf';
const pdfPath = resolve(OUTPUT_DIR, pdfName);
const browser = await puppeteer.launch({ headless: true });
// Start temp HTTP server to resolve /assets/ paths correctly
const server = createServer(async (req, res) => {
const filePath = resolve(PROJECT_ROOT, decodeURIComponent(req.url).replace(/^\//, ''));
try {
const data = await readFile(filePath);
const ext = extname(filePath);
res.writeHead(200, { 'Content-Type': MIME_TYPES[ext] || 'application/octet-stream' });
res.end(data);
} catch {
res.writeHead(404);
res.end('Not found');
}
});
await new Promise(r => server.listen(0, '127.0.0.1', r));
const port = server.address().port;
const relPath = absolutePath.replace(PROJECT_ROOT + '/', '');
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] });
const page = await browser.newPage();
await page.goto(`file://${absolutePath}`, { waitUntil: 'networkidle0' });
await page.goto(`http://127.0.0.1:${port}/${relPath}`, { waitUntil: 'networkidle0', timeout: 30000 });
await page.pdf({
path: pdfPath,
@@ -31,6 +62,7 @@ async function generatePdf(htmlPath) {
});
await browser.close();
server.close();
console.log(`PDF generated: ${pdfPath}`);
return pdfPath;
}