/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { MatterError, TimeoutError } from "#MatterError.js";
import { MaybePromise } from "./Promises.js";
class EndOfStreamError extends MatterError {
  constructor(message = "Unexpected end of stream") {
    super(message);
  }
}
class NoResponseTimeoutError extends TimeoutError {
}
var Stream;
((Stream2) => {
  function from(iterable2) {
    if ("from" in ReadableStream) {
      return ReadableStream.from(iterable2);
    }
    return AnyIterableReadableStream(iterable2);
  }
  Stream2.from = from;
  async function* iterable(stream) {
    if (Symbol.asyncIterator in stream) {
      yield* stream;
      return;
    }
    const reader = stream.getReader();
    try {
      while (true) {
        const next = await reader.read();
        if (next.done) {
          return;
        }
        yield next.value;
      }
    } finally {
      reader.releaseLock();
    }
  }
  Stream2.iterable = iterable;
})(Stream || (Stream = {}));
function AnyIterableReadableStream(iterable) {
  let iterator;
  return new ReadableStream({
    start() {
      if (Symbol.asyncIterator in iterable) {
        iterator = iterable[Symbol.asyncIterator]();
      } else {
        iterator = iterable[Symbol.iterator]();
      }
    },
    async pull(controller) {
      if (!iterator) {
        controller.close();
        return;
      }
      try {
        let next = iterator.next();
        if (MaybePromise.is(next)) {
          next = await next;
        }
        if (next.done) {
          controller.close();
          return;
        }
        controller.enqueue(next.value);
      } catch (e) {
        controller.error(e);
        return;
      }
    },
    async cancel(reason) {
      if (reason) {
        if (iterator?.throw) {
          await iterator.throw(reason);
          return;
        }
        if (iterator?.return) {
          await iterator.return();
        }
        throw reason;
      }
      await iterator?.return?.();
    }
  });
}
export {
  EndOfStreamError,
  NoResponseTimeoutError,
  Stream
};
//# sourceMappingURL=Streams.js.map
