var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __using = (stack, value, async) => {
  if (value != null) {
    if (typeof value !== "object" && typeof value !== "function") __typeError("Object expected");
    var dispose, inner;
    if (async) dispose = value[__knownSymbol("asyncDispose")];
    if (dispose === void 0) {
      dispose = value[__knownSymbol("dispose")];
      if (async) inner = dispose;
    }
    if (typeof dispose !== "function") __typeError("Object not disposable");
    if (inner) dispose = function() {
      try {
        inner.call(this);
      } catch (e) {
        return Promise.reject(e);
      }
    };
    stack.push([async, dispose, value]);
  } else if (async) {
    stack.push([async]);
  }
  return value;
};
var __callDispose = (stack, error, hasError) => {
  var E = typeof SuppressedError === "function" ? SuppressedError : function(e, s, m, _) {
    return _ = Error(m), _.name = "SuppressedError", _.error = e, _.suppressed = s, _;
  };
  var fail = (e) => error = hasError ? new E(e, error, "An error was suppressed during disposal") : (hasError = true, e);
  var next = (it) => {
    while (it = stack.pop()) {
      try {
        var result = it[1] && it[1].call(it[2]);
        if (it[0]) return Promise.resolve(result).then(next, (e) => (fail(e), next()));
      } catch (e) {
        fail(e);
      }
    }
    if (hasError) throw error;
  };
  return next();
};
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { Abort, AppAddress, asJson, Bytes, HttpService, Mutex, Stream } from "@matter/general";
import { StatusResponse, StatusResponseError } from "@matter/types";
import { Api } from "../remote/api/Api.js";
import { ApiPath } from "../remote/api/ApiPath.js";
import { RemoteRequest } from "../remote/api/RemoteRequest.js";
import { RemoteResponse } from "../remote/api/RemoteResponse.js";
import { RemoteInterface } from "../remote/RemoteInterface.js";
const LOG_FACILITY = "WebSocket";
class WebSocketInterface extends RemoteInterface {
  static protocol = "ws";
  #http;
  #mutex = new Mutex(this);
  async start() {
    this.#http = await this.env.get(HttpService).create(this);
    this.#http.ws = this.#handleConnection.bind(this);
  }
  async stop() {
    await super.stop();
    await this.#http?.close();
  }
  /**
   * Handle HTTP connections.
   *
   * Checks path, upgrades to a WebSocket if the path applies, then processes input messages
   */
  async #handleConnection(request, upgrade) {
    var _stack = [];
    try {
      const address = new AppAddress(request.url);
      const path = new ApiPath(address).toString();
      if (path !== this.root.toString()) {
        return;
      }
      const ws = await Abort.race(this.abort, await upgrade());
      if (!ws) {
        return;
      }
      const subtask = __using(_stack, Abort.subtask(this.abort));
      const send = async (local) => {
        await this.#mutex.produce(async () => {
          const message = RemoteResponse(local);
          Api.logResponse(LOG_FACILITY, message);
          const writer = ws.writable.getWriter();
          try {
            await writer.write(asJson(message));
          } finally {
            writer.releaseLock();
          }
        });
      };
      for await (let message of Stream.iterable(ws.readable)) {
        let requestId;
        try {
          message = Bytes.toString(message);
          let parsed;
          try {
            parsed = JSON.parse(message);
          } catch (e) {
            if (e instanceof SyntaxError) {
              throw new StatusResponse.InvalidCommandError(`Request parse error: ${e.message}`);
            }
            throw e;
          }
          requestId = parsed?.id;
          const request2 = RemoteRequest(parsed);
          await this.#handleRequest(request2, subtask, send);
        } catch (error) {
          StatusResponseError.accept(error);
          await send({
            kind: "error",
            id: requestId,
            error
          });
        }
      }
      subtask.abort();
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  async #handleRequest(request, abort, send) {
    const response = await this.#mutex.produce(() => Api.execute(LOG_FACILITY, this.node, request, abort));
    if (response.kind !== "subscription") {
      await send(response);
      return;
    }
    await send({ id: request.id, kind: "ok" });
    this.addWorker(this.#handleSubscription(response.stream, send));
  }
  async #handleSubscription(stream, send) {
    var _stack = [];
    try {
      const _streaming = __using(_stack, this.join("streaming"));
      for await (const update of stream) {
        await send(update.js);
      }
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
}
export {
  WebSocketInterface
};
//# sourceMappingURL=WebSocketInterface.js.map
