"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.toReadableStream = void 0;
const _constants_js_1 = require("./_constants.js");
const _common_js_1 = require("./_common.js");
/**
 * Create a {@linkcode ReadableStream} of {@linkcode Uint8Array}s from a
 * {@linkcode Reader}.
 *
 * When the pull algorithm is called on the stream, a chunk from the reader
 * will be read.  When `null` is returned from the reader, the stream will be
 * closed along with the reader (if it is also a `Closer`).
 *
 * @example
 * ```ts
 * import { toReadableStream } from "@std/io/to_readable_stream";
 *
 * const file = await Deno.open("./file.txt", { read: true });
 * const fileStream = toReadableStream(file);
 * ```
 */
function toReadableStream(reader, { autoClose = true, chunkSize = _constants_js_1.DEFAULT_CHUNK_SIZE, strategy, } = {}) {
    return new ReadableStream({
        async pull(controller) {
            const chunk = new Uint8Array(chunkSize);
            try {
                const read = await reader.read(chunk);
                if (read === null) {
                    if ((0, _common_js_1.isCloser)(reader) && autoClose) {
                        reader.close();
                    }
                    controller.close();
                    return;
                }
                controller.enqueue(chunk.subarray(0, read));
            }
            catch (e) {
                controller.error(e);
                if ((0, _common_js_1.isCloser)(reader)) {
                    reader.close();
                }
            }
        },
        cancel() {
            if ((0, _common_js_1.isCloser)(reader) && autoClose) {
                reader.close();
            }
        },
    }, strategy);
}
exports.toReadableStream = toReadableStream;
