"use strict";
/* Socket Lib - Built with esbuild */
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var timer_exports = {};
__export(timer_exports, {
  measure: () => measure,
  measureSync: () => measureSync,
  perfCheckpoint: () => perfCheckpoint,
  perfTimer: () => perfTimer,
  trackMemory: () => trackMemory
});
module.exports = __toCommonJS(timer_exports);
var import_node_process = __toESM(require("node:process"));
var import_output = require("../debug/output");
var import_message = require("../errors/message");
var import_date = require("../primordials/date");
var import_math = require("../primordials/math");
var import_internal = require("./_internal");
var import_enabled = require("./enabled");
async function measure(operation, fn, metadata) {
  const stop = perfTimer(operation, metadata);
  try {
    const result = await fn();
    stop({ success: true });
    const metric = import_internal.performanceMetrics[import_internal.performanceMetrics.length - 1];
    return { result, duration: metric?.duration || 0 };
  } catch (e) {
    stop({
      success: false,
      error: (0, import_message.errorMessage)(e)
    });
    throw e;
  }
}
function measureSync(operation, fn, metadata) {
  const stop = perfTimer(operation, metadata);
  try {
    const result = fn();
    stop({ success: true });
    const metric = import_internal.performanceMetrics[import_internal.performanceMetrics.length - 1];
    return { result, duration: metric?.duration || 0 };
  } catch (e) {
    stop({
      success: false,
      error: (0, import_message.errorMessage)(e)
    });
    throw e;
  }
}
function perfCheckpoint(checkpoint, metadata) {
  if (!(0, import_enabled.isPerfEnabled)()) {
    return;
  }
  const metric = {
    operation: `checkpoint:${checkpoint}`,
    duration: 0,
    timestamp: (0, import_date.DateNow)(),
    ...metadata ? { metadata } : {}
  };
  import_internal.performanceMetrics.push(metric);
  (0, import_output.debugLog)(`[perf] [CHECKPOINT] ${checkpoint}`);
}
function perfTimer(operation, metadata) {
  if (!(0, import_enabled.isPerfEnabled)()) {
    return () => {
    };
  }
  const start = performance.now();
  (0, import_output.debugLog)(`[perf] [START] ${operation}`);
  return (additionalMetadata) => {
    const duration = performance.now() - start;
    const metric = {
      operation,
      // Round to 2 decimals
      duration: (0, import_math.MathRound)(duration * 100) / 100,
      timestamp: (0, import_date.DateNow)(),
      metadata: { ...metadata, ...additionalMetadata }
    };
    import_internal.performanceMetrics.push(metric);
    (0, import_output.debugLog)(`[perf] [END] ${operation} - ${metric.duration}ms`);
  };
}
function trackMemory(label) {
  if (!(0, import_enabled.isPerfEnabled)()) {
    return 0;
  }
  const usage = import_node_process.default.memoryUsage();
  const heapUsedMB = (0, import_math.MathRound)(usage.heapUsed / 1024 / 1024 * 100) / 100;
  (0, import_output.debugLog)(`[perf] [MEMORY] ${label}: ${heapUsedMB}MB heap used`);
  const metric = {
    operation: `checkpoint:memory:${label}`,
    duration: 0,
    timestamp: (0, import_date.DateNow)(),
    metadata: {
      heapUsed: heapUsedMB,
      heapTotal: (0, import_math.MathRound)(usage.heapTotal / 1024 / 1024 * 100) / 100,
      external: (0, import_math.MathRound)(usage.external / 1024 / 1024 * 100) / 100
    }
  };
  import_internal.performanceMetrics.push(metric);
  return heapUsedMB;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  measure,
  measureSync,
  perfCheckpoint,
  perfTimer,
  trackMemory
});
