"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileStreamHasher = void 0;
const fs_1 = require("fs");
const HashCalculator_1 = require("./HashCalculator");
const fileStreamHasher = (hashCtor, fileStream) => new Promise((resolve, reject) => {
    if (!isReadStream(fileStream)) {
        reject(new Error("Unable to calculate hash for non-file streams."));
        return;
    }
    const fileStreamTee = (0, fs_1.createReadStream)(fileStream.path, {
        start: fileStream.start,
        end: fileStream.end,
    });
    const hash = new hashCtor();
    const hashCalculator = new HashCalculator_1.HashCalculator(hash);
    fileStreamTee.pipe(hashCalculator);
    fileStreamTee.on("error", (err) => {
        hashCalculator.end();
        reject(err);
    });
    hashCalculator.on("error", reject);
    hashCalculator.on("finish", function () {
        hash.digest().then(resolve).catch(reject);
    });
});
exports.fileStreamHasher = fileStreamHasher;
const isReadStream = (stream) => typeof stream.path === "string";
