"use strict";
/**
 * On-disk baseline file — `.dxkit/baselines/<name>.json`.
 *
 * The baseline file is the durable contract between today's scan
 * and tomorrow's guardrail check. It carries:
 *
 *   - Per-finding identities (`BaselineEntry[]`) for cross-run
 *     matching.
 *   - Repo state at capture time (commit SHA, branch) so the
 *     git-aware matcher knows what to diff against.
 *   - Analysis-environment metadata (dxkit version, tool versions,
 *     policy hash, config hashes) so the policy classifier can
 *     reclassify newly-detected findings as `tooling_drift` or
 *     `config_drift` rather than blocking them as regressions.
 *   - The salt-resolution mode used to derive any secret-HMAC
 *     entries, so the matcher knows whether HMAC comparison is
 *     available on the current run.
 *
 * Raw finding payloads (titles, secret values, source excerpts) are
 * NEVER stored. The file is committable to git: a leak surfaces
 * identity fingerprints + locations, but no exploitable content.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_BASELINE_DIR = exports.DEFAULT_BASELINE_NAME = exports.BASELINE_SCHEMA_VERSION = void 0;
exports.pathForBaseline = pathForBaseline;
exports.writeBaselineFile = writeBaselineFile;
exports.readBaselineFile = readBaselineFile;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
/** Banner stamped on every baseline file. Bump when the on-disk
 *  shape changes incompatibly so readers can refuse old / new files
 *  rather than silently mis-parse them. */
exports.BASELINE_SCHEMA_VERSION = 'dxkit-baseline/v1';
/** Default baseline name when the user doesn't pass `--name`. */
exports.DEFAULT_BASELINE_NAME = 'main';
/** Default storage directory. Lives under `.dxkit/` alongside the
 *  generated reports + the salt file. */
exports.DEFAULT_BASELINE_DIR = path.join('.dxkit', 'baselines');
/** Absolute path for a named baseline inside `cwd`. */
function pathForBaseline(cwd, name) {
    return path.join(cwd, exports.DEFAULT_BASELINE_DIR, `${name}.json`);
}
/**
 * Write a baseline file. Creates the parent directory when missing.
 * Pretty-printed JSON for git-friendly diffs.
 */
function writeBaselineFile(filePath, file) {
    fs.mkdirSync(path.dirname(filePath), { recursive: true });
    fs.writeFileSync(filePath, JSON.stringify(file, null, 2) + '\n', 'utf8');
}
/**
 * Identity kinds that this dxkit version no longer recognizes but
 * that older baseline files may contain. Lenient migration: read
 * silently drops these so a 2.5.x baseline still loads on a 2.6+
 * dxkit without forcing a `baseline create --force`. The dropped
 * kind moves to a separate artifact — `license` → `.dxkit/bom.json`,
 * the canonical inventory carried by `vyuh-dxkit bom`.
 */
const RETIRED_KINDS = new Set(['license']);
/**
 * Read + validate a baseline file. Throws when the schema banner is
 * missing or unrecognized — fail fast rather than letting the
 * matcher consume a malformed file and produce wrong verdicts.
 *
 * Retired finding kinds (see `RETIRED_KINDS`) are silently filtered
 * out of `findings` so a baseline written by an older dxkit doesn't
 * crash the matcher when its identity union no longer contains that
 * kind. The original file on disk is not modified — only the in-memory
 * view consumed by the matcher / classifier. A subsequent `baseline
 * create --force` writes a fresh file without the retired entries.
 */
function readBaselineFile(filePath) {
    const raw = fs.readFileSync(filePath, 'utf8');
    let parsed;
    try {
        parsed = JSON.parse(raw);
    }
    catch (err) {
        throw new Error(`baseline file is not valid JSON: ${filePath} (${err.message})`);
    }
    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
        throw new Error(`baseline file root is not an object: ${filePath}`);
    }
    const obj = parsed;
    if (obj.schemaVersion !== exports.BASELINE_SCHEMA_VERSION) {
        throw new Error(`baseline file schemaVersion is ${JSON.stringify(obj.schemaVersion)}; ` +
            `this dxkit understands ${JSON.stringify(exports.BASELINE_SCHEMA_VERSION)} only ` +
            `(${filePath})`);
    }
    const file = parsed;
    const filteredFindings = file.findings.filter((entry) => !RETIRED_KINDS.has(entry.kind));
    if (filteredFindings.length === file.findings.length) {
        return file;
    }
    return { ...file, findings: filteredFindings };
}
//# sourceMappingURL=baseline-file.js.map