File size: 3,160 Bytes
0d869c0
 
d0ca9fa
 
 
 
 
 
 
 
 
 
0d869c0
d0ca9fa
0d869c0
d0ca9fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d869c0
3e08b05
d0ca9fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d869c0
d0ca9fa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Server for the Mac and the Hugging Face Space: serves public/ and the API.
//   GET /api/check  -> status for the page     POST /api/check -> run a check (NDJSON stream)
// Usage: npm run dev   (reads .env.local)   |   npm run mock   (no API keys needed)
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';

const root = path.dirname(fileURLToPath(import.meta.url));
try { process.loadEnvFile(path.join(root, '.env.local')); } catch {}

const { handleCheck, status } = await import('./lib/pipeline.js');
const PUBLIC = path.join(root, 'public');
const PORT = Number(process.env.PORT) || 3001; // 3000 is taken by Vardrobe
const TYPES = {
  '.html': 'text/html; charset=utf-8',
  '.js': 'text/javascript; charset=utf-8',
  '.css': 'text/css; charset=utf-8',
  '.json': 'application/json',
  '.webmanifest': 'application/manifest+json',
  '.svg': 'image/svg+xml',
  '.png': 'image/png',
  '.ico': 'image/x-icon',
};

const server = http.createServer(async (req, res) => {
  const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
  try {
    if (url.pathname === '/api/check') {
      const ac = new AbortController();
      res.on('close', () => { if (!res.writableEnded) ac.abort(); });
      const chunks = [];
      for await (const c of req) chunks.push(c);
      const headers = new Headers();
      for (const [k, v] of Object.entries(req.headers)) if (v != null) headers.set(k, Array.isArray(v) ? v.join(', ') : v);
      const request = new Request(url, {
        method: req.method,
        headers,
        body: req.method === 'POST' ? Buffer.concat(chunks) : undefined,
        signal: ac.signal,
      });
      let response;
      if (req.method === 'POST') response = await handleCheck(request);
      else if (req.method === 'GET') response = Response.json(await status(request), { headers: { 'cache-control': 'no-store' } });
      else response = new Response('', { status: 405 });
      res.writeHead(response.status, Object.fromEntries(response.headers));
      if (response.body) for await (const chunk of response.body) res.write(chunk);
      res.end();
      return;
    }

    const rel = url.pathname === '/' ? 'index.html' : decodeURIComponent(url.pathname).replace(/^\/+/, '');
    const file = path.normalize(path.join(PUBLIC, rel));
    if (!file.startsWith(PUBLIC + path.sep)) { res.writeHead(403).end(); return; }
    const data = await readFile(file);
    res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream' });
    res.end(data);
  } catch (e) {
    if (!res.headersSent) res.writeHead(e && e.code === 'ENOENT' ? 404 : 500);
    res.end();
  }
});

server.listen(PORT, '0.0.0.0', () => {
  const lan = Object.values(os.networkInterfaces()).flat().find((i) => i && i.family === 'IPv4' && !i.internal);
  console.log(`Sprawdzak: http://localhost:${PORT}` + (lan ? `   (telefon w tej samej sieci Wi-Fi: http://${lan.address}:${PORT})` : ''));
  if (process.env.SPRAWDZAK_MOCK === '1') console.log('Tryb testowy: bez wyszukiwania i bez AI.');
});