import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);

// src/capture/buffer.ts
import fs from "fs";
import path from "path";
var EventBuffer = class {
  constructor(bufferDir, sessionId, options = {}) {
    this.bufferDir = bufferDir;
    this.sessionId = sessionId;
    this.filePath = path.join(bufferDir, `${sessionId}.jsonl`);
    this.maxEvents = options.maxEvents ?? 500;
    if (fs.existsSync(this.filePath)) {
      const content = fs.readFileSync(this.filePath, "utf-8").trim();
      this.eventCount = content ? content.split("\n").length : 0;
    }
  }
  filePath;
  maxEvents;
  eventCount = 0;
  append(event) {
    fs.mkdirSync(this.bufferDir, { recursive: true });
    const line = JSON.stringify({
      ...event,
      timestamp: event.timestamp ?? (/* @__PURE__ */ new Date()).toISOString()
    });
    fs.appendFileSync(this.filePath, line + "\n");
    this.eventCount++;
  }
  readAll() {
    if (!fs.existsSync(this.filePath)) return [];
    const content = fs.readFileSync(this.filePath, "utf-8").trim();
    if (!content) return [];
    return content.split("\n").map((line) => JSON.parse(line));
  }
  count() {
    return this.eventCount;
  }
  exists() {
    return fs.existsSync(this.filePath);
  }
  delete() {
    if (fs.existsSync(this.filePath)) {
      fs.unlinkSync(this.filePath);
    }
    this.eventCount = 0;
  }
  isOverflow() {
    return this.eventCount > this.maxEvents;
  }
  getFilePath() {
    return this.filePath;
  }
};
function resolveSessionFromBuffer(bufferDir) {
  try {
    let bestSession;
    let bestMtime = 0;
    for (const file of fs.readdirSync(bufferDir)) {
      if (!file.endsWith(".jsonl")) continue;
      const mtime = fs.statSync(path.join(bufferDir, file)).mtimeMs;
      if (mtime > bestMtime) {
        bestMtime = mtime;
        bestSession = file.replace(".jsonl", "");
      }
    }
    return bestSession;
  } catch {
    return void 0;
  }
}

export {
  EventBuffer,
  resolveSessionFromBuffer
};
//# sourceMappingURL=chunk-HIN3UVOG.js.map