"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var Faucet_exports = {};
__export(Faucet_exports, {
  Faucet: () => Faucet
});
module.exports = __toCommonJS(Faucet_exports);
class Faucet {
  static {
    __name(this, "Faucet");
  }
  /** Creates a new Faucet. The data starts flowing immediately */
  constructor(readable, writable) {
    this.#readable = readable;
    this.#writable = writable;
    void this.#flow();
  }
  #readable;
  #writable;
  #abort;
  /**
   * Connects a new writable to the faucet.
   * If a writable is already connected, it is replaced.
   */
  connect(writable) {
    this.#writable = writable;
  }
  /**
   * Disconnects the current writable from the faucet.
   */
  disconnect() {
    this.#writable = void 0;
  }
  async #flow() {
    const reader = this.#readable.getReader();
    const abort = new AbortController();
    this.#abort = abort;
    try {
      const abortPromise = new Promise((resolve) => {
        abort.signal.addEventListener("abort", () => {
          resolve();
        });
      });
      while (true) {
        const result = await Promise.race([
          reader.read(),
          abortPromise.then(() => ({ done: true, value: void 0 }))
        ]);
        if (result.done || result.value == void 0)
          break;
        let writer;
        try {
          writer = this.#writable?.getWriter();
          await writer?.write(result.value);
        } catch {
        } finally {
          writer?.releaseLock();
        }
      }
    } finally {
      reader.releaseLock();
    }
  }
  /** Closes the faucet and stops reading data */
  close() {
    this.#abort?.abort();
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  Faucet
});
//# sourceMappingURL=Faucet.js.map
