(config = {})
| 27 | const WebSocket = require('ws'); |
| 28 | const { parse } = require('url'); |
| 29 | function server(config = {}) { |
| 30 | const ROUTES = []; |
| 31 | const WARES = []; |
| 32 | const WS_ROUTES = []; |
| 33 | const wss = new WebSocket.Server({ noServer: true }); |
| 34 | const SERVER = http.createServer((req, res) => { |
| 35 | let u = parse(req.url, true); |
| 36 | req.query = u.query || {}; |
| 37 | req.path = u.pathname; |
| 38 | req.hostname = (req.headers.host || '').split(':')[0].replace(/[^\w.-]/g, ''); |
| 39 | req.ip = (req.socket.remoteAddress || '').replace(/[^\w.:]/g, ''); |
| 40 | res.statusCode = 200; |
| 41 | res.status = (x) => { |
| 42 | res.statusCode = x; |
| 43 | return res; |
| 44 | }; |
| 45 | res.json = (x) => { |
| 46 | res.writeHead(res.statusCode || 200, { 'Content-Type': 'application/json' }); |
| 47 | res.end(JSON.stringify(x)); |
| 48 | }; |
| 49 | res.send = (x) => { |
| 50 | if (x === undefined || x === null) |
| 51 | x = ''; |
| 52 | if (typeof x === 'object') |
| 53 | return res.json(x); |
| 54 | res.writeHead(res.statusCode || 200, { 'Content-Type': 'text/plain' }); |
| 55 | res.end(String(x)); |
| 56 | }; |
| 57 | res.set = (k, v) => { res.setHeader(k, v); return res; }; |
| 58 | let r = matchRoute(req.method.toUpperCase(), req.path); |
| 59 | req.params = r ? r.params : {}; |
| 60 | let fns = [...WARES]; |
| 61 | fns.push(r ? (req, res, next) => r.handler(req, res, next) : (_req, res) => res.status(404).end('404: Not Found')); |
| 62 | let i = 0; |
| 63 | let next = () => { |
| 64 | if (i < fns.length) |
| 65 | fns[i++](req, res, next); |
| 66 | }; |
| 67 | next(); |
| 68 | }); |
| 69 | SERVER.on('upgrade', (req, socket, head) => { |
| 70 | let u = parse(req.url || '', true); |
| 71 | let path = u.pathname; |
| 72 | if (!path || path.includes('..') || /[\0-\x1F\x7F]/.test(path)) { |
| 73 | socket.destroy(); |
| 74 | return; |
| 75 | } |
| 76 | for (let i = 0; i < WS_ROUTES.length; i++) { |
| 77 | let r = WS_ROUTES[i]; |
| 78 | if (r.path === path) { |
| 79 | wss.handleUpgrade(req, socket, head, (ws) => { |
| 80 | ws.req = req; |
| 81 | r.handler(ws, req); |
| 82 | }); |
| 83 | return; |
| 84 | } |
| 85 | } |
| 86 | socket.destroy(); |
no test coverage detected