UNPKG

@socketsecurity/lib

Version:

Core utilities and infrastructure for Socket.dev security tools

220 lines (218 loc) 7.55 kB
"use strict"; /* Socket Lib - Built with esbuild */ var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var performance_exports = {}; __export(performance_exports, { clearPerformanceMetrics: () => clearPerformanceMetrics, generatePerformanceReport: () => generatePerformanceReport, getPerformanceMetrics: () => getPerformanceMetrics, getPerformanceSummary: () => getPerformanceSummary, measure: () => measure, measureSync: () => measureSync, perfCheckpoint: () => perfCheckpoint, perfTimer: () => perfTimer, printPerformanceSummary: () => printPerformanceSummary, trackMemory: () => trackMemory }); module.exports = __toCommonJS(performance_exports); var import_debug = require("./debug"); const performanceMetrics = []; function isPerfEnabled() { return process.env["DEBUG"]?.includes("perf") || false; } function perfTimer(operation, metadata) { if (!isPerfEnabled()) { return () => { }; } const start = performance.now(); (0, import_debug.debugLog)(`[perf] [START] ${operation}`); return (additionalMetadata) => { const duration = performance.now() - start; const metric = { operation, // Round to 2 decimals duration: Math.round(duration * 100) / 100, timestamp: Date.now(), metadata: { ...metadata, ...additionalMetadata } }; performanceMetrics.push(metric); (0, import_debug.debugLog)(`[perf] [END] ${operation} - ${metric.duration}ms`); }; } async function measure(operation, fn, metadata) { const stop = perfTimer(operation, metadata); try { const result = await fn(); stop({ success: true }); const metric = performanceMetrics[performanceMetrics.length - 1]; return { result, duration: metric?.duration || 0 }; } catch (e) { stop({ success: false, error: e instanceof Error ? e.message : "Unknown" }); throw e; } } function measureSync(operation, fn, metadata) { const stop = perfTimer(operation, metadata); try { const result = fn(); stop({ success: true }); const metric = performanceMetrics[performanceMetrics.length - 1]; return { result, duration: metric?.duration || 0 }; } catch (e) { stop({ success: false, error: e instanceof Error ? e.message : "Unknown" }); throw e; } } function getPerformanceMetrics() { return [...performanceMetrics]; } function clearPerformanceMetrics() { performanceMetrics.length = 0; (0, import_debug.debugLog)("[perf] Cleared performance metrics"); } function getPerformanceSummary() { const summary = /* @__PURE__ */ Object.create(null); for (const metric of performanceMetrics) { const { duration, operation } = metric; if (!summary[operation]) { summary[operation] = { count: 0, total: 0, min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY }; } const stats = summary[operation]; stats.count++; stats.total += duration; stats.min = Math.min(stats.min, duration); stats.max = Math.max(stats.max, duration); } const result = /* @__PURE__ */ Object.create(null); for (const { 0: operation, 1: stats } of Object.entries(summary)) { result[operation] = { count: stats.count, total: Math.round(stats.total * 100) / 100, avg: Math.round(stats.total / stats.count * 100) / 100, min: Math.round(stats.min * 100) / 100, max: Math.round(stats.max * 100) / 100 }; } return result; } function printPerformanceSummary() { if (!isPerfEnabled() || performanceMetrics.length === 0) { return; } const summary = getPerformanceSummary(); const operations = Object.keys(summary).sort(); (0, import_debug.debugLog)("[perf]\n=== Performance Summary ==="); for (const operation of operations) { const stats = summary[operation]; (0, import_debug.debugLog)( `[perf] ${operation}: ${stats.count} calls, avg ${stats.avg}ms (min ${stats.min}ms, max ${stats.max}ms, total ${stats.total}ms)` ); } (0, import_debug.debugLog)("[perf] =========================\n"); } function perfCheckpoint(checkpoint, metadata) { if (!isPerfEnabled()) { return; } const metric = { operation: `checkpoint:${checkpoint}`, duration: 0, timestamp: Date.now(), ...metadata ? { metadata } : {} }; performanceMetrics.push(metric); (0, import_debug.debugLog)(`[perf] [CHECKPOINT] ${checkpoint}`); } function trackMemory(label) { if (!isPerfEnabled()) { return 0; } const usage = process.memoryUsage(); const heapUsedMB = Math.round(usage.heapUsed / 1024 / 1024 * 100) / 100; (0, import_debug.debugLog)(`[perf] [MEMORY] ${label}: ${heapUsedMB}MB heap used`); const metric = { operation: `checkpoint:memory:${label}`, duration: 0, timestamp: Date.now(), metadata: { heapUsed: heapUsedMB, heapTotal: Math.round(usage.heapTotal / 1024 / 1024 * 100) / 100, external: Math.round(usage.external / 1024 / 1024 * 100) / 100 } }; performanceMetrics.push(metric); return heapUsedMB; } function generatePerformanceReport() { if (!isPerfEnabled() || performanceMetrics.length === 0) { return "(no performance data collected - enable with DEBUG=perf)"; } const summary = getPerformanceSummary(); const operations = Object.keys(summary).sort(); let report = "\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n"; report += "\u2551 Performance Report \u2551\n"; report += "\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\n\n"; for (const operation of operations) { const stats = summary[operation]; report += `${operation}: `; report += ` Calls: ${stats.count} `; report += ` Avg: ${stats.avg}ms `; report += ` Min: ${stats.min}ms `; report += ` Max: ${stats.max}ms `; report += ` Total: ${stats.total}ms `; } const totalDuration = Object.values(summary).reduce( (sum, s) => sum + s.total, 0 ); report += `Total measured time: ${Math.round(totalDuration * 100) / 100}ms `; return report; } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { clearPerformanceMetrics, generatePerformanceReport, getPerformanceMetrics, getPerformanceSummary, measure, measureSync, perfCheckpoint, perfTimer, printPerformanceSummary, trackMemory });