web/website/scripts/preview.mjs
2026-11-27 23:43:05 +00:00

3 lines
1.3 KiB
JavaScript

import {createServer} from 'node:http';import {readFileSync,existsSync,statSync} from 'node:fs';import path from 'node:path';import {fileURLToPath} from 'node:url';import {handleFeed} from '../worker/feed-api.mjs';
const web=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../web');const types={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.webp':'image/webp','.svg':'image/svg+xml'};
createServer(async(req,res)=>{try{const url=new URL(req.url,'http://127.0.0.1:8765');if(url.pathname.startsWith('/api/')){const response=await handleFeed(new Request(url,{method:req.method}),{});res.writeHead(response.status,Object.fromEntries(response.headers));res.end(Buffer.from(await response.arrayBuffer()));return}const pathname=decodeURIComponent(url.pathname==='/'?'/index.html':url.pathname);const file=path.resolve(web,'.'+pathname);if(!file.startsWith(web+path.sep)||!existsSync(file)||!statSync(file).isFile()){res.writeHead(404);res.end('Not found');return}res.writeHead(200,{'Content-Type':types[path.extname(file)]||'application/octet-stream'});res.end(readFileSync(file))}catch{res.writeHead(500);res.end('Preview error')}}).listen(8765,'127.0.0.1',()=>console.log('Dune website: http://127.0.0.1:8765'));