"use strict";
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2024-2026 Gracker (Chris)
// This file is part of SmartPerfetto. See LICENSE for details.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseProcStatusRssBytes = parseProcStatusRssBytes;
exports.parsePsRssBytes = parsePsRssBytes;
exports.readProcessRssBytes = readProcessRssBytes;
const fs_1 = __importDefault(require("fs"));
const child_process_1 = require("child_process");
function parseProcStatusRssBytes(statusText) {
    const match = statusText.match(/^VmRSS:\s+(\d+)\s+kB\s*$/m);
    if (!match)
        return null;
    const kib = Number.parseInt(match[1], 10);
    return Number.isFinite(kib) ? kib * 1024 : null;
}
function parsePsRssBytes(psOutput) {
    const firstLine = psOutput.trim().split(/\r?\n/).find(Boolean);
    if (!firstLine)
        return null;
    const kib = Number.parseInt(firstLine.trim(), 10);
    return Number.isFinite(kib) ? kib * 1024 : null;
}
function readProcessRssBytes(pid) {
    if (!Number.isInteger(pid) || pid <= 0) {
        return {
            pid,
            rssBytes: null,
            source: 'unavailable',
            error: 'pid must be a positive integer',
        };
    }
    const procStatusPath = `/proc/${pid}/status`;
    if (fs_1.default.existsSync(procStatusPath)) {
        try {
            const parsed = parseProcStatusRssBytes(fs_1.default.readFileSync(procStatusPath, 'utf8'));
            if (parsed !== null) {
                return {
                    pid,
                    rssBytes: parsed,
                    source: 'procfs',
                };
            }
        }
        catch (error) {
            return {
                pid,
                rssBytes: null,
                source: 'unavailable',
                error: error.message,
            };
        }
    }
    const result = (0, child_process_1.spawnSync)('ps', ['-o', 'rss=', '-p', String(pid)], {
        encoding: 'utf8',
        timeout: 2000,
    });
    const parsed = parsePsRssBytes(result.stdout ?? '');
    if (parsed !== null) {
        return {
            pid,
            rssBytes: parsed,
            source: 'ps',
        };
    }
    const stderr = `${result.stderr ?? ''}`.trim();
    return {
        pid,
        rssBytes: null,
        source: 'unavailable',
        ...(stderr ? { error: stderr } : {}),
    };
}
//# sourceMappingURL=processRss.js.map