UNPKG

unnbound-logger-sdk

Version:

A structured logging library with TypeScript support using Pino. Provides consistent, well-typed logging with automatic logId, workflowId, traceId, and deploymentId tracking across operational contexts.

97 lines (96 loc) 2.63 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateTimestamp = generateTimestamp; exports.getTraceId = getTraceId; exports.clearTraceId = clearTraceId; exports.filterHeaders = filterHeaders; exports.safeJsonParse = safeJsonParse; exports.normalizeIp = normalizeIp; /** * Utility functions for logging */ const uuid_1 = require("uuid"); /** * Generates the current timestamp in ISO format * @returns ISO timestamp string */ function generateTimestamp() { return new Date().toISOString(); } /** * Stores trace IDs by workflow ID for consistent tracking */ const traceIdMap = new Map(); /** * Gets or creates a trace ID for a workflow * @param workflowId - The workflow ID to get a trace ID for * @returns A trace ID associated with the workflow */ function getTraceId(workflowId) { if (!traceIdMap.has(workflowId)) { traceIdMap.set(workflowId, (0, uuid_1.v4)()); } return traceIdMap.get(workflowId); } /** * Clears a trace ID from the map * @param workflowId - The workflow ID to clear */ function clearTraceId(workflowId) { traceIdMap.delete(workflowId); } // --- Header Allow-Listing --- const ALLOWED_HEADERS = new Set([ 'content-type', 'accept', 'user-agent', 'host', 'x-forwarded-for', 'x-request-id', 'content-length', 'cache-control', ]); /** * Filters an object of headers, returning a new object with only the allowed headers. * @param headers The original headers object. * @returns A new object containing only the headers from the allow-list. */ function filterHeaders(headers) { const filtered = {}; for (const key in headers) { if (ALLOWED_HEADERS.has(key.toLowerCase())) { filtered[key] = String(headers[key]); } } return filtered; } /** * Safely parses JSON strings, returning the original data if parsing fails or if it's not a string. * @param data The data to potentially parse as JSON. * @returns Parsed JSON object or the original data. */ function safeJsonParse(data) { if (typeof data === 'string') { try { return JSON.parse(data); } catch { return data; } } return data; } /** * Normalizes IP addresses by removing IPv6 mapping prefix for IPv4 addresses. * @param ip The IP address to normalize. * @returns Normalized IP address string. */ function normalizeIp(ip) { if (!ip) return ip; // Remove IPv4-mapped IPv6 prefix (::ffff:) to get clean IPv4 address if (ip.startsWith('::ffff:')) { return ip.substring(7); } return ip; }