"use strict";
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
Object.defineProperty(exports, "__esModule", { value: true });
exports.toWritableStream = void 0;
const write_all_js_1 = require("./write_all.js");
const _common_js_1 = require("./_common.js");
/**
 * Create a {@linkcode WritableStream} from a {@linkcode Writer}.
 *
 * @example
 * ```ts
 * import { toWritableStream } from "@std/io/to_writable_stream";
 *
 * const file = await Deno.open("./file.txt", { create: true, write: true });
 * await ReadableStream.from("Hello World")
 *   .pipeThrough(new TextEncoderStream())
 *   .pipeTo(toWritableStream(file));
 * ```
 */
function toWritableStream(writer, { autoClose = true } = {}) {
    return new WritableStream({
        async write(chunk, controller) {
            try {
                await (0, write_all_js_1.writeAll)(writer, chunk);
            }
            catch (e) {
                controller.error(e);
                if ((0, _common_js_1.isCloser)(writer) && autoClose) {
                    writer.close();
                }
            }
        },
        close() {
            if ((0, _common_js_1.isCloser)(writer) && autoClose) {
                writer.close();
            }
        },
        abort() {
            if ((0, _common_js_1.isCloser)(writer) && autoClose) {
                writer.close();
            }
        },
    });
}
exports.toWritableStream = toWritableStream;
