/** * BitReport Error Reporter — lightweight Node.js client (CommonJS). * See errorReporter.mjs for full docs. */ 'use strict'; let _token = ''; let _endpoint = 'https://errors.bitreport.pt'; let _disabled = false; const _queue = []; let _flushTimer = null; const BATCH_SIZE = 25; const FLUSH_MS = 5000; const TIMEOUT_MS = 8000; function initReporter(opts) { opts = opts || {}; _token = opts.token || process.env.ERROR_REPORTING_TOKEN || ''; _endpoint = (opts.endpoint || process.env.ERROR_REPORTING_ENDPOINT || 'https://errors.bitreport.pt').replace(/\/$/, ''); _disabled = opts.disabled != null ? opts.disabled : process.env.ERROR_REPORTING_DISABLED === '1'; if (!_disabled && _token) { process.on('uncaughtException', function (err) { reportError(err, { uncaught: true }); setTimeout(function () { throw err; }, 200); }); process.on('unhandledRejection', function (reason) { var e = reason instanceof Error ? reason : new Error(String(reason)); reportError(e, { unhandledRejection: true }); }); } } function reportError(err, context) { if (_disabled || !_token) return; context = context || {}; var msg = (err && err.message) || String(err); var stack = (err && err.stack) || ''; var fileMatch = stack.match(/at\s+.+?\((.+?):(\d+):\d+\)|at\s+(.+?):(\d+):\d+/); var filePath = (fileMatch && (fileMatch[1] || fileMatch[3])) || ''; var lineNumber = parseInt((fileMatch && (fileMatch[2] || fileMatch[4])) || '0', 10); _enqueue({ schema_version: 1, occurred_at: new Date().toISOString(), level: 'error', message: msg, stacktrace: stack, context: Object.assign({ file_path: filePath, line_number: lineNumber || undefined, error_type: (err && err.constructor && err.constructor.name) || 'Error', error_code: (err && err.code) || undefined, }, context), }); } function reportMessage(message, level, context) { if (_disabled || !_token) return; _enqueue({ schema_version: 1, occurred_at: new Date().toISOString(), level: level || 'error', message: message, context: context || {}, }); } async function flush() { if (_flushTimer) { clearTimeout(_flushTimer); _flushTimer = null; } while (_queue.length > 0) { var batch = _queue.splice(0, BATCH_SIZE); await _send(batch); } } function _enqueue(event) { _queue.push(event); if (_queue.length >= BATCH_SIZE) { flush().catch(function () {}); } else if (!_flushTimer) { _flushTimer = setTimeout(function () { _flushTimer = null; flush().catch(function () {}); }, FLUSH_MS); if (_flushTimer.unref) _flushTimer.unref(); } } async function _send(events) { if (!events.length) return; try { var ctrl = new AbortController(); var timer = setTimeout(function () { ctrl.abort(); }, TIMEOUT_MS); await fetch(_endpoint + '/v1/ingest/events', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + _token }, body: JSON.stringify({ events: events }), signal: ctrl.signal, }); clearTimeout(timer); } catch (_) { /* fire-and-forget */ } } module.exports = { initReporter, reportError, reportMessage, flush };