var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : 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-2025 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { NodeActivity } from "#behavior/context/NodeActivity.js";
import { AccessControlServer } from "#behaviors/access-control";
import {
  Crypto,
  Diagnostic,
  Duration,
  InternalError,
  Logger,
  MatterError,
  MaybePromise,
  Millis,
  Observable,
  Seconds
} from "#general";
import { GLOBAL_IDS, Specification } from "#model";
import {
  ExchangeManager,
  InteractionServerMessenger,
  MessageType,
  NodeSession,
  SessionType
} from "#protocol";
import {
  DEFAULT_MAX_PATHS_PER_INVOKE,
  INTERACTION_PROTOCOL_ID,
  ReceivedStatusResponseError,
  Status,
  StatusCode,
  StatusResponseError,
  TlvAny,
  TlvInvokeResponseData,
  TlvInvokeResponseForSend,
  TlvSubscribeResponse
} from "#types";
import { OnlineServerInteraction } from "./OnlineServerInteraction.js";
import { ServerSubscription, ServerSubscriptionConfig } from "./ServerSubscription.js";
const logger = Logger.get("InteractionServer");
function validateReadAttributesPath(path, isGroupSession = false) {
  if (isGroupSession) {
    throw new StatusResponseError("Illegal read request with group session", StatusCode.InvalidAction);
  }
  const { clusterId, attributeId } = path;
  if (clusterId === void 0 && attributeId !== void 0) {
    if (!GLOBAL_IDS.has(attributeId)) {
      throw new StatusResponseError(
        `Illegal read request for wildcard cluster and non global attribute ${attributeId}`,
        StatusCode.InvalidAction
      );
    }
  }
}
function validateReadEventPath(path, isGroupSession = false) {
  const { clusterId, eventId } = path;
  if (clusterId === void 0 && eventId !== void 0) {
    throw new StatusResponseError("Illegal read request with wildcard cluster ID", StatusCode.InvalidAction);
  }
  if (isGroupSession) {
    throw new StatusResponseError("Illegal read request with group session", StatusCode.InvalidAction);
  }
}
function clusterPathToId({ nodeId, endpointId, clusterId }) {
  return `${nodeId}/${endpointId}/${clusterId}`;
}
class InteractionServer {
  id = INTERACTION_PROTOCOL_ID;
  requiresSecureSession = true;
  #context;
  #nextSubscriptionId;
  #isClosing = false;
  #clientHandler;
  #subscriptionConfig;
  #maxPathsPerInvoke;
  #subscriptionEstablishmentStarted = Observable();
  #node;
  #activity;
  #newActivityBlocked = false;
  #aclServer;
  #serverInteraction;
  constructor(node, sessions) {
    this.#nextSubscriptionId = node.env.get(Crypto).randomUint32;
    this.#context = {
      sessions,
      exchangeManager: node.env.get(ExchangeManager)
    };
    this.#subscriptionConfig = ServerSubscriptionConfig.of(node.state.network.subscriptionOptions);
    this.#maxPathsPerInvoke = node.state.basicInformation.maxPathsPerInvoke ?? DEFAULT_MAX_PATHS_PER_INVOKE;
    this.#activity = node.env.get(NodeActivity);
    this.#node = node;
    this.#serverInteraction = new OnlineServerInteraction(node.protocol);
  }
  async [Symbol.asyncDispose]() {
    await this.close();
  }
  blockNewActivity() {
    this.#newActivityBlocked = true;
  }
  get isClosing() {
    return this.#isClosing;
  }
  get maxPathsPerInvoke() {
    return this.#maxPathsPerInvoke;
  }
  get subscriptionEstablishmentStarted() {
    return this.#subscriptionEstablishmentStarted;
  }
  async onNewExchange(exchange, message) {
    var _stack = [];
    try {
      if (this.#newActivityBlocked || this.isClosing) {
        return;
      }
      if (message.payloadHeader.messageType === MessageType.ReportData && this.clientHandler) {
        return this.clientHandler.onNewExchange(exchange, message);
      }
      const activity = __using(_stack, this.#activity.begin(`session#${exchange.session.id.toString(16)}`));
      exchange[NodeActivity.activityKey] = activity;
      return new InteractionServerMessenger(exchange).handleRequest(this).finally(() => delete exchange[NodeActivity.activityKey]);
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  get aclServer() {
    if (this.#aclServer !== void 0) {
      return this.#aclServer;
    }
    const aclServer = this.#node.act((agent) => agent.get(AccessControlServer));
    if (MaybePromise.is(aclServer)) {
      throw new InternalError("AccessControlServer should already be initialized.");
    }
    return this.#aclServer = aclServer;
  }
  get clientHandler() {
    return this.#clientHandler;
  }
  set clientHandler(clientHandler) {
    this.#clientHandler = clientHandler;
  }
  #prepareOnlineContext(exchange, message, fabricFiltered, timed = false) {
    return {
      activity: exchange[NodeActivity.activityKey],
      fabricFiltered,
      timed,
      message,
      exchange,
      node: this.#node
    };
  }
  /**
   * Returns an iterator that yields the data reports and events data for the given read request.
   */
  async *#executeReadInteraction(readRequest, exchange, message) {
    const readContext = this.#prepareOnlineContext(exchange, message, readRequest.isFabricFiltered);
    for await (const chunk of this.#serverInteraction.read(readRequest, readContext)) {
      for (const report of chunk) {
        yield InteractionServerMessenger.convertServerInteractionReport(report);
      }
    }
  }
  async handleReadRequest(exchange, readRequest, message) {
    const {
      attributeRequests,
      eventRequests,
      isFabricFiltered,
      dataVersionFilters,
      eventFilters,
      interactionModelRevision
    } = readRequest;
    logger.debug(() => [
      "Read \xAB",
      exchange.via,
      Diagnostic.asFlags({ fabricFiltered: isFabricFiltered }),
      Diagnostic.dict({
        attributes: `${attributeRequests?.map((path) => this.#node.protocol.inspectPath(path)).join(", ") ?? "none"}${dataVersionFilters?.length ? ` with ${dataVersionFilters?.length} filters` : ""}`,
        events: `${eventRequests?.map((path) => this.#node.protocol.inspectPath(path)).join(", ") ?? "none"}${eventFilters?.length ? `, ${eventFilters?.length} filters` : ""}`
      })
    ]);
    if (interactionModelRevision > Specification.INTERACTION_MODEL_REVISION) {
      logger.debug(
        `Interaction model revision of sender ${interactionModelRevision} is higher than supported ${Specification.INTERACTION_MODEL_REVISION}.`
      );
    }
    if (attributeRequests === void 0 && eventRequests === void 0) {
      return {
        dataReport: {
          interactionModelRevision: Specification.INTERACTION_MODEL_REVISION,
          suppressResponse: true
        }
      };
    }
    if (message.packetHeader.sessionType !== SessionType.Unicast) {
      throw new StatusResponseError(
        "Reads are only allowed on unicast sessions",
        // Means "No groups"
        StatusCode.InvalidAction
      );
    }
    return {
      dataReport: {
        interactionModelRevision: Specification.INTERACTION_MODEL_REVISION,
        suppressResponse: true
      },
      payload: this.#executeReadInteraction(readRequest, exchange, message)
    };
  }
  async handleWriteRequest(exchange, writeRequest, message) {
    const { suppressResponse, timedRequest, writeRequests, interactionModelRevision, moreChunkedMessages } = writeRequest;
    const sessionType = message.packetHeader.sessionType;
    logger.info(() => [
      "Write \xAB",
      exchange.via,
      Diagnostic.asFlags({ suppressResponse, moreChunkedMessages }),
      Diagnostic.weak(writeRequests.map((req) => this.#node.protocol.inspectPath(req.path)).join(", "))
    ]);
    if (moreChunkedMessages && suppressResponse) {
      throw new StatusResponseError(
        "MoreChunkedMessages and SuppressResponse cannot be used together in write messages",
        StatusCode.InvalidAction
      );
    }
    if (interactionModelRevision > Specification.INTERACTION_MODEL_REVISION) {
      logger.debug(
        `Interaction model revision of sender ${interactionModelRevision} is higher than supported ${Specification.INTERACTION_MODEL_REVISION}.`
      );
    }
    const receivedWithinTimedInteraction = exchange.hasActiveTimedInteraction();
    if (receivedWithinTimedInteraction && moreChunkedMessages) {
      throw new StatusResponseError(
        "Write Request action that is part of a Timed Write Interaction SHALL NOT be chunked.",
        StatusCode.InvalidAction
      );
    }
    if (exchange.hasExpiredTimedInteraction()) {
      exchange.clearTimedInteraction();
      throw new StatusResponseError(`Timed request window expired. Decline write request.`, StatusCode.Timeout);
    }
    if (timedRequest !== exchange.hasTimedInteraction()) {
      throw new StatusResponseError(
        `timedRequest flag of write interaction (${timedRequest}) mismatch with expected timed interaction (${receivedWithinTimedInteraction}).`,
        StatusCode.TimedRequestMismatch
      );
    }
    if (receivedWithinTimedInteraction) {
      logger.debug("Write request for timed interaction on", exchange.channel.name);
      exchange.clearTimedInteraction();
      if (sessionType !== SessionType.Unicast) {
        throw new StatusResponseError(
          "Write requests are only allowed on unicast sessions when a timed interaction is running.",
          StatusCode.InvalidAction
        );
      }
    }
    if (sessionType === SessionType.Group && !suppressResponse) {
      throw new StatusResponseError(
        "Write requests are only allowed as group casts when suppressResponse=true.",
        StatusCode.InvalidAction
      );
    }
    const result = await this.#serverInteraction.write(
      writeRequest,
      this.#prepareOnlineContext(
        exchange,
        message,
        true,
        // always fabric filtered
        receivedWithinTimedInteraction
      )
    );
    return {
      writeResponses: result?.map(({ path, status, clusterStatus }) => ({
        path,
        status: { status, clusterStatus }
      })),
      interactionModelRevision: Specification.INTERACTION_MODEL_REVISION
    };
  }
  async handleSubscribeRequest(exchange, request, messenger, message) {
    const {
      minIntervalFloorSeconds,
      maxIntervalCeilingSeconds,
      attributeRequests,
      dataVersionFilters,
      eventRequests,
      eventFilters,
      keepSubscriptions,
      isFabricFiltered,
      interactionModelRevision
    } = request;
    logger.info(() => [
      "Subscribe \xAB",
      exchange.via,
      Diagnostic.asFlags({ fabricFiltered: isFabricFiltered, keepSubscriptions }),
      Diagnostic.dict({
        attributePaths: attributeRequests?.length,
        eventPaths: eventRequests?.length
      })
    ]);
    if (interactionModelRevision > Specification.INTERACTION_MODEL_REVISION) {
      logger.debug(
        `Interaction model revision of sender ${interactionModelRevision} is higher than supported ${Specification.INTERACTION_MODEL_REVISION}.`
      );
    }
    if (message.packetHeader.sessionType !== SessionType.Unicast) {
      throw new StatusResponseError(
        "Subscriptions are only allowed on unicast sessions",
        StatusCode.InvalidAction
      );
    }
    NodeSession.assert(exchange.session, "Subscriptions are only implemented on secure sessions");
    const session = exchange.session;
    const fabric = session.fabric;
    if (fabric !== void 0 && !keepSubscriptions) {
      const clearedCount = await this.#context.sessions.clearSubscriptionsForNode(
        fabric.addressOf(session.peerNodeId),
        true
      );
      if (clearedCount > 0) {
        logger.debug(
          `Cleared ${clearedCount} subscriptions for Subscriber node ${session.peerNodeId} because keepSubscriptions=false`
        );
      }
    }
    if ((!Array.isArray(attributeRequests) || attributeRequests.length === 0) && (!Array.isArray(eventRequests) || eventRequests.length === 0)) {
      throw new StatusResponseError("No attributes or events requested", StatusCode.InvalidAction);
    }
    logger.debug(() => [
      "Subscribe request details \xAB",
      exchange.via,
      Diagnostic.dict({
        attributes: attributeRequests?.length ? attributeRequests?.map((path) => this.#node.protocol.inspectPath(path)).join(", ") : void 0,
        dataVersionFilters: dataVersionFilters?.length ? dataVersionFilters.map(
          ({ path: { nodeId, endpointId, clusterId }, dataVersion }) => `${clusterPathToId({ nodeId, endpointId, clusterId })}=${dataVersion}`
        ).join(", ") : void 0,
        events: eventRequests?.length ? eventRequests.map((path) => this.#node.protocol.inspectPath(path)).join(", ") : void 0,
        eventFilters: eventFilters?.length ? eventFilters.map((filter) => `${filter.nodeId}/${filter.eventMin}`).join(", ") : void 0
      })
    ]);
    attributeRequests?.forEach((path) => validateReadAttributesPath(path));
    eventRequests?.forEach((path) => validateReadEventPath(path));
    if (minIntervalFloorSeconds < 0) {
      throw new StatusResponseError(
        "minIntervalFloorSeconds should be greater or equal to 0",
        StatusCode.InvalidAction
      );
    }
    if (maxIntervalCeilingSeconds < 0) {
      throw new StatusResponseError(
        "maxIntervalCeilingSeconds should be greater or equal to 0",
        StatusCode.InvalidAction
      );
    }
    if (maxIntervalCeilingSeconds < minIntervalFloorSeconds) {
      throw new StatusResponseError(
        "maxIntervalCeilingSeconds should be greater or equal to minIntervalFloorSeconds",
        StatusCode.InvalidAction
      );
    }
    if (this.#nextSubscriptionId === 4294967295) this.#nextSubscriptionId = 0;
    const subscriptionId = this.#nextSubscriptionId++;
    this.#subscriptionEstablishmentStarted.emit(session.peerAddress);
    let subscription;
    try {
      subscription = await this.#establishSubscription(
        subscriptionId,
        request,
        messenger,
        session,
        exchange,
        message
      );
    } catch (error) {
      logger.error(
        `Subscription ${subscriptionId} for Session ${session.id}: Error while sending initial data reports:`,
        error instanceof MatterError ? error.message : error
      );
      if (error instanceof StatusResponseError && !(error instanceof ReceivedStatusResponseError)) {
        logger.info(
          "Status",
          Diagnostic.strong(`${Status[error.code]}(${error.code})`),
          "\xBB",
          exchange.via,
          "Error:",
          Diagnostic.errorMessage(error)
        );
        await messenger.sendStatus(error.code, {
          logContext: {
            for: "I/SubscriptionSeed-Status"
          }
        });
      }
      await messenger.close();
      return;
    }
    const maxInterval = subscription.maxInterval;
    await messenger.send(
      MessageType.SubscribeResponse,
      TlvSubscribeResponse.encode({
        subscriptionId,
        maxInterval: Seconds.of(maxInterval),
        interactionModelRevision: Specification.INTERACTION_MODEL_REVISION
      }),
      {
        logContext: {
          subId: subscriptionId,
          maxInterval
        }
      }
    );
    subscription.activate();
  }
  async #establishSubscription(id, {
    minIntervalFloorSeconds,
    maxIntervalCeilingSeconds,
    attributeRequests,
    dataVersionFilters,
    eventRequests,
    eventFilters,
    isFabricFiltered
  }, messenger, session, exchange, message) {
    const context = {
      session,
      node: this.#node,
      initiateExchange: (address, protocolId) => this.#context.exchangeManager.initiateExchange(address, protocolId)
    };
    const subscription = new ServerSubscription({
      id,
      context,
      criteria: {
        attributeRequests,
        dataVersionFilters,
        eventRequests,
        eventFilters,
        isFabricFiltered
      },
      minIntervalFloor: Seconds(minIntervalFloorSeconds),
      maxIntervalCeiling: Seconds(maxIntervalCeilingSeconds),
      subscriptionOptions: this.#subscriptionConfig
    });
    const readContext = this.#prepareOnlineContext(exchange, message, isFabricFiltered);
    try {
      await subscription.sendInitialReport(messenger, readContext);
    } catch (error) {
      await subscription.close();
      throw error;
    }
    logger.info(
      "Subscribe successful \xBB",
      exchange.via,
      Diagnostic.dict({
        subId: id,
        timing: `${Duration.format(Seconds(minIntervalFloorSeconds))} - ${Duration.format(Seconds(maxIntervalCeilingSeconds))} => ${Duration.format(subscription.maxInterval)}`,
        sendInterval: Duration.format(subscription.sendInterval)
      })
    );
    return subscription;
  }
  async establishFormerSubscription({
    subscriptionId,
    attributeRequests,
    eventRequests,
    isFabricFiltered,
    minIntervalFloor,
    maxIntervalCeiling,
    maxInterval,
    sendInterval
  }, session) {
    const exchange = this.#context.exchangeManager.initiateExchange(session.peerAddress, INTERACTION_PROTOCOL_ID);
    const message = {};
    logger.info(
      `Reestablish subscription \xBB`,
      exchange.via,
      Diagnostic.dict({
        subId: subscriptionId,
        isFabricFiltered,
        maxInterval: Duration.format(maxInterval),
        sendInterval: Duration.format(sendInterval)
      })
    );
    const context = {
      session,
      node: this.#node,
      initiateExchange: (address, protocolId) => this.#context.exchangeManager.initiateExchange(address, protocolId)
    };
    const subscription = new ServerSubscription({
      id: subscriptionId,
      context,
      minIntervalFloor,
      maxIntervalCeiling,
      criteria: {
        attributeRequests,
        eventRequests,
        isFabricFiltered
      },
      subscriptionOptions: this.#subscriptionConfig,
      useAsMaxInterval: maxInterval,
      useAsSendInterval: sendInterval
    });
    const readContext = this.#prepareOnlineContext(exchange, message, isFabricFiltered);
    try {
      await subscription.sendInitialReport(
        new InteractionServerMessenger(exchange),
        readContext,
        true
        // Do not send status responses because we simulate that the subscription is still established
      );
      subscription.activate();
      logger.info(
        `Subscription successfully reestablished \xBB`,
        exchange.via,
        Diagnostic.dict({
          subId: subscriptionId,
          timing: `${Duration.format(minIntervalFloor)} - ${Duration.format(maxIntervalCeiling)} => ${Duration.format(subscription.maxInterval)}`,
          sendInterval: Duration.format(subscription.sendInterval)
        })
      );
    } catch (error) {
      await subscription.close();
      throw error;
    }
    return subscription;
  }
  async handleInvokeRequest(exchange, request, messenger, message) {
    const { invokeRequests, timedRequest, suppressResponse, interactionModelRevision } = request;
    logger.info(() => [
      "Invoke \xAB",
      exchange.via,
      Diagnostic.asFlags({ suppressResponse, timedRequest }),
      Diagnostic.dict({
        invokes: invokeRequests.map(
          ({ commandPath: { endpointId, clusterId, commandId } }) => this.#node.protocol.inspectPath({ endpointId, clusterId, commandId })
        ).join(", ")
      })
    ]);
    if (interactionModelRevision > Specification.INTERACTION_MODEL_REVISION) {
      logger.debug(
        `Interaction model revision of sender ${interactionModelRevision} is higher than supported ${Specification.INTERACTION_MODEL_REVISION}.`
      );
    }
    const receivedWithinTimedInteraction = exchange.hasActiveTimedInteraction();
    if (exchange.hasExpiredTimedInteraction()) {
      exchange.clearTimedInteraction();
      throw new StatusResponseError(`Timed request window expired. Decline invoke request.`, StatusCode.Timeout);
    }
    if (timedRequest !== exchange.hasTimedInteraction()) {
      throw new StatusResponseError(
        `timedRequest flag of invoke interaction (${timedRequest}) mismatch with expected timed interaction (${receivedWithinTimedInteraction}).`,
        StatusCode.TimedRequestMismatch
      );
    }
    if (receivedWithinTimedInteraction) {
      logger.debug("Invoke request for timed interaction on", exchange.channel.name);
      exchange.clearTimedInteraction();
      if (message.packetHeader.sessionType !== SessionType.Unicast) {
        throw new StatusResponseError(
          "Invoke requests are only allowed on unicast sessions when a timed interaction is running.",
          StatusCode.InvalidAction
        );
      }
    }
    if (invokeRequests.length > this.#maxPathsPerInvoke) {
      throw new StatusResponseError(
        `Only ${this.#maxPathsPerInvoke} invoke requests are supported in one message. This message contains ${invokeRequests.length}`,
        StatusCode.InvalidAction
      );
    }
    const isGroupSession = message.packetHeader.sessionType === SessionType.Group;
    const invokeResponseMessage = {
      suppressResponse: false,
      // Deprecated but must be present
      interactionModelRevision: Specification.INTERACTION_MODEL_REVISION,
      invokeResponses: [],
      moreChunkedMessages: invokeRequests.length > 1
      // Assume for now we have multiple responses when having multiple invokes
    };
    const emptyInvokeResponseBytes = TlvInvokeResponseForSend.encode(invokeResponseMessage);
    let messageSize = emptyInvokeResponseBytes.byteLength;
    let invokeResultsProcessed = 0;
    const processResponseResult = async (invokeResponse) => {
      invokeResultsProcessed++;
      if (isGroupSession) {
        return;
      }
      const encodedInvokeResponse = TlvInvokeResponseData.encodeTlv(invokeResponse);
      const invokeResponseBytes = TlvAny.getEncodedByteLength(encodedInvokeResponse);
      if (messageSize + invokeResponseBytes > exchange.maxPayloadSize || invokeResultsProcessed === invokeRequests.length) {
        let lastMessageProcessed = false;
        if (messageSize + invokeResponseBytes <= exchange.maxPayloadSize) {
          invokeResponseMessage.invokeResponses.push(encodedInvokeResponse);
          lastMessageProcessed = true;
        }
        if (invokeResponseMessage.invokeResponses.length > 0) {
          if (invokeRequests.length > 1) {
            logger.debug(
              `${lastMessageProcessed ? "Final " : ""}Invoke response \xBB`,
              Diagnostic.dict({ commands: invokeResponseMessage.invokeResponses.length })
            );
          }
          const moreChunkedMessages = lastMessageProcessed ? void 0 : true;
          await messenger.send(
            MessageType.InvokeResponse,
            TlvInvokeResponseForSend.encode({
              ...invokeResponseMessage,
              moreChunkedMessages
            }),
            {
              logContext: {
                invokeMsgFlags: Diagnostic.asFlags({
                  suppressResponse,
                  moreChunkedMessages
                })
              }
            }
          );
          invokeResponseMessage.invokeResponses = [];
          messageSize = emptyInvokeResponseBytes.byteLength;
        }
        if (!lastMessageProcessed) {
          invokeResultsProcessed--;
          return processResponseResult(invokeResponse);
        }
      } else {
        invokeResponseMessage.invokeResponses.push(encodedInvokeResponse);
        messageSize += invokeResponseBytes;
      }
    };
    for await (const chunk of this.#serverInteraction.invoke(
      request,
      this.#prepareOnlineContext(exchange, message, void 0, receivedWithinTimedInteraction)
    )) {
      if (suppressResponse) {
        throw new InternalError("Received response that should be suppressed for invoke");
      }
      for (const data of chunk) {
        switch (data.kind) {
          case "cmd-response": {
            const { path: commandPath, commandRef, data: commandFields } = data;
            await processResponseResult({
              command: {
                commandPath,
                commandFields,
                commandRef
              }
            });
            break;
          }
          case "cmd-status": {
            const { path, commandRef, status, clusterStatus } = data;
            await processResponseResult({
              status: { commandPath: path, status: { status, clusterStatus }, commandRef }
            });
          }
        }
      }
    }
  }
  handleTimedRequest(exchange, { timeout, interactionModelRevision }) {
    const interval = Millis(timeout);
    logger.debug(() => [
      "Timed request \xAB",
      exchange.via,
      Diagnostic.dict({
        interval: Duration.format(interval)
      })
    ]);
    if (interactionModelRevision > Specification.INTERACTION_MODEL_REVISION) {
      logger.debug(
        `Interaction model revision of sender ${interactionModelRevision} is higher than supported ${Specification.INTERACTION_MODEL_REVISION}.`
      );
    }
    exchange.startTimedInteraction(interval);
  }
  async close() {
    this.#isClosing = true;
  }
}
export {
  InteractionServer
};
//# sourceMappingURL=InteractionServer.js.map
