// Small pure helpers shared by the server modules. No state, no I/O. import { isIP } from 'node:net'; import { TaperError } from './events.js'; import { paddedJson } from './padding.js'; export const now = () => Date.now(); export const b64url = (buf) => buf.toString('base64url'); // This machine (a host name, or a URL's hostname with IPv6 in brackets). export const isLoopback = (host) => host === 'localhost' || host === '[::1]' || host === '::1' || (isIP(host) === 4 && host.startsWith('127.')); // Remove the entries of `map` for which `expired(value, key)`, calling `then(key)` // for each. Returns how many went. export function dropWhere(map, expired, then = () => {}) { let n = 0; for (const [k, v] of map) if (expired(v, k)) { map.delete(k); then(k); n++; } return n; } // A failed request's error: a TaperError says what went wrong, anything else is logged and stays internal. export function errorBody(err, method) { if (err instanceof TaperError) return { errcode: err.errcode, error: err.message, ...err.extra }; console.error('internal error in', method, err); return { errcode: 'T_UNKNOWN', error: 'Internal server error' }; } // A JSON frame (padded) or a binary one, if the socket is still open. export function send(ws, frame) { if (ws?.readyState === ws?.OPEN) ws.send(Buffer.isBuffer(frame) ? frame : paddedJson(frame)); }