import { hasOwnErrorCode } from "./error-codes.js";
export function createBrokenPipeState() {
    return { closed: false };
}
export function createSafeOutputStream(stream, brokenPipe) {
    return {
        write(chunk) {
            if (brokenPipe.closed) {
                return;
            }
            try {
                stream.write(chunk);
            }
            catch (error) {
                if (isBrokenPipeError(error)) {
                    brokenPipe.closed = true;
                    return;
                }
                throw error;
            }
        }
    };
}
export async function withBrokenPipeGuard(streams, brokenPipe, callback) {
    const removeListeners = streams.map((stream) => addBrokenPipeListener(stream, brokenPipe));
    try {
        return await callback();
    }
    finally {
        for (const removeListener of removeListeners) {
            removeListener();
        }
    }
}
export function addBrokenPipeListener(stream, brokenPipe) {
    const onError = (error) => {
        if (isBrokenPipeError(error)) {
            brokenPipe.closed = true;
            return;
        }
        throw error;
    };
    stream.on?.("error", onError);
    return () => {
        stream.off?.("error", onError);
    };
}
function isBrokenPipeError(error) {
    return hasOwnErrorCode(error, "EPIPE");
}
