"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.atomicWriteFileSync = atomicWriteFileSync;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const node_crypto_1 = require("node:crypto");
const config_1 = require("../config");
function atomicWriteFileSync(destinationPath, contents, options = {}) {
    const operations = options.operations ?? node_fs_1.default;
    const resolvedDestinationPath = node_path_1.default.resolve(destinationPath);
    const directoryPath = node_path_1.default.dirname(resolvedDestinationPath);
    const destinationStats = operations.statSync(resolvedDestinationPath, { throwIfNoEntry: false });
    if (destinationStats !== undefined && !destinationStats.isFile()) {
        throw new Error(`Atomic write destination '${destinationPath}' is not a regular file.`);
    }
    operations.mkdirSync(directoryPath, { recursive: true });
    const temporaryPath = openTemporaryFile({
        destinationPath: resolvedDestinationPath,
        mode: destinationStats === undefined ? (options.mode ?? config_1.DEFAULT_CREATION_MODE) : destinationStats.mode & 0o777,
        operations,
        temporaryName: options.temporaryName ?? defaultTemporaryName,
        maxAttempts: options.maxTemporaryNameAttempts ?? config_1.DEFAULT_TEMPORARY_NAME_ATTEMPTS,
    });
    let descriptor = temporaryPath.descriptor;
    try {
        const writeOptions = typeof contents === 'string' ? { encoding: options.encoding ?? 'utf8' } : undefined;
        operations.writeFileSync(descriptor, contents, writeOptions);
        flushFile(operations, descriptor);
        operations.closeSync(descriptor);
        descriptor = null;
        operations.renameSync(temporaryPath.path, resolvedDestinationPath);
        flushDirectory(operations, directoryPath);
    }
    catch (error) {
        if (descriptor !== null) {
            try {
                operations.closeSync(descriptor);
            }
            catch {
                // Preserve the operation error that initiated cleanup.
            }
        }
        try {
            operations.rmSync(temporaryPath.path, { force: true });
        }
        catch {
            // Preserve the operation error; a failed cleanup never makes the temp file active.
        }
        throw error;
    }
}
function openTemporaryFile(options) {
    if (!Number.isInteger(options.maxAttempts) || options.maxAttempts < 1) {
        throw new Error('Atomic write temporary-name attempts must be a positive integer.');
    }
    for (let attempt = 0; attempt < options.maxAttempts; attempt += 1) {
        const temporaryPath = options.temporaryName(options.destinationPath, attempt);
        if (node_path_1.default.dirname(temporaryPath) !== node_path_1.default.dirname(options.destinationPath)) {
            throw new Error('Atomic write temporary files must be created beside the destination.');
        }
        try {
            return {
                path: temporaryPath,
                descriptor: options.operations.openSync(temporaryPath, 'wx', options.mode),
            };
        }
        catch (error) {
            if (!isNodeError(error) || error.code !== 'EEXIST') {
                throw error;
            }
        }
    }
    throw new Error(`Unable to allocate an atomic write temporary file for '${options.destinationPath}'.`);
}
function defaultTemporaryName(destinationPath, attempt) {
    const suffix = (0, node_crypto_1.randomBytes)(12).toString('hex');
    return node_path_1.default.join(node_path_1.default.dirname(destinationPath), `.${node_path_1.default.basename(destinationPath)}.${process.pid}.${attempt}.${suffix}.tmp`);
}
function flushFile(operations, descriptor) {
    try {
        operations.fsyncSync(descriptor);
    }
    catch (error) {
        if (!isPortabilityError(error, config_1.FILE_FSYNC_PORTABILITY_ERRORS)) {
            throw error;
        }
    }
}
function flushDirectory(operations, directoryPath) {
    let descriptor = null;
    try {
        descriptor = operations.openSync(directoryPath, 'r');
        operations.fsyncSync(descriptor);
    }
    catch (error) {
        if (!isPortabilityError(error, config_1.DIRECTORY_FSYNC_PORTABILITY_ERRORS)) {
            throw error;
        }
    }
    finally {
        if (descriptor !== null) {
            try {
                operations.closeSync(descriptor);
            }
            catch {
                // Directory descriptor cleanup is best effort after replacement.
            }
        }
    }
}
function isPortabilityError(error, supportedCodes) {
    return isNodeError(error) && typeof error.code === 'string' && supportedCodes.has(error.code);
}
function isNodeError(error) {
    return error instanceof Error && 'code' in error;
}
