/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { Time } from "#time/Time.js";
import { Bytes } from "#util/Bytes.js";
import { Gate } from "#util/Promises.js";
function MockWsConnection() {
  const clientToServer = createPipe();
  const serverToClient = createPipe();
  return {
    client: {
      readable: serverToClient.readable,
      writable: clientToServer.writable
    },
    server: {
      readable: clientToServer.readable,
      writable: serverToClient.writable
    }
  };
}
((MockWsConnection2) => {
  async function send(connection, message) {
    const writer = connection.writable.getWriter();
    try {
      await writer.write(JSON.stringify(message));
    } finally {
      writer.releaseLock();
    }
  }
  MockWsConnection2.send = send;
  async function receive(connection) {
    const reader = connection.readable.getReader();
    try {
      const result = await reader.read();
      if (result.done) {
        throw new Error("Expected message but stream ended");
      }
      return JSON.parse(Bytes.toString(result.value));
    } finally {
      reader.releaseLock();
    }
  }
  MockWsConnection2.receive = receive;
})(MockWsConnection || (MockWsConnection = {}));
function createPipe() {
  const queue = Array();
  const ready = new Gate();
  let isClosed = false;
  let deliveryScheduled = false;
  function scheduleDelivery() {
    if (!deliveryScheduled) {
      deliveryScheduled = true;
      void Time.macrotask.then(() => {
        deliveryScheduled = false;
        ready.open();
      });
    }
  }
  const readable = new ReadableStream({
    async pull(controller) {
      if (!isClosed && !queue.length) {
        await ready;
      }
      const next = queue.shift();
      if (!queue.length && !isClosed) {
        ready.close();
      }
      if (next === void 0) {
        controller.close();
        return;
      }
      controller.enqueue(next);
    },
    cancel() {
      isClosed = true;
      queue.length = 0;
      ready.open();
    }
  });
  const writable = new WritableStream({
    write(chunk) {
      if (isClosed) {
        return;
      }
      queue.push(chunk);
      scheduleDelivery();
    },
    close() {
      isClosed = true;
      scheduleDelivery();
    },
    abort() {
      isClosed = true;
      queue.length = 0;
      ready.open();
    }
  });
  return { readable, writable };
}
export {
  MockWsConnection
};
//# sourceMappingURL=MockWsConnection.js.map
