"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.readTextFileIfExists = readTextFileIfExists;
exports.pathExists = pathExists;
exports.readTextFileIfExistsSync = readTextFileIfExistsSync;
exports.readJsonFile = readJsonFile;
exports.readJsonFileIfExists = readJsonFileIfExists;
exports.readJsonFileOrNull = readJsonFileOrNull;
exports.readJsonFileOrDefault = readJsonFileOrDefault;
const node_fs_1 = require("node:fs");
const promises_1 = require("node:fs/promises");
const fs_errors_1 = require("./fs-errors");
async function readTextFileIfExists(filePath) {
    try {
        return await (0, promises_1.readFile)(filePath, "utf8");
    }
    catch (error) {
        if ((0, fs_errors_1.isMissingFileError)(error)) {
            return null;
        }
        throw error;
    }
}
async function pathExists(filePath) {
    try {
        await (0, promises_1.access)(filePath);
        return true;
    }
    catch (error) {
        if ((0, fs_errors_1.isMissingFileError)(error)) {
            return false;
        }
        throw error;
    }
}
function readTextFileIfExistsSync(filePath) {
    try {
        return (0, node_fs_1.readFileSync)(filePath, "utf8");
    }
    catch (error) {
        if ((0, fs_errors_1.isMissingFileError)(error)) {
            return null;
        }
        throw error;
    }
}
async function readJsonFile(filePath, parser) {
    const text = await (0, promises_1.readFile)(filePath, "utf8");
    const parsed = JSON.parse(text);
    return parser.parse(parsed);
}
async function readJsonFileIfExists(filePath, parser) {
    try {
        return await readJsonFile(filePath, parser);
    }
    catch (error) {
        if ((0, fs_errors_1.isMissingFileError)(error)) {
            return null;
        }
        throw error;
    }
}
async function readJsonFileOrNull(filePath, parser) {
    try {
        return await readJsonFile(filePath, parser);
    }
    catch (error) {
        if ((0, fs_errors_1.isMissingFileError)(error) || (0, fs_errors_1.isZodParseError)(error)) {
            return null;
        }
        throw error;
    }
}
async function readJsonFileOrDefault(filePath, parser, createDefault) {
    const value = await readJsonFileOrNull(filePath, parser);
    return value ?? createDefault();
}
