"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
var __typeError = (msg) => {
  throw TypeError(msg);
};
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 __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();
};
var MdnsServer_exports = {};
__export(MdnsServer_exports, {
  MdnsServer: () => MdnsServer,
  QUESTION_SUPPRESSION_WINDOW: () => QUESTION_SUPPRESSION_WINDOW
});
module.exports = __toCommonJS(MdnsServer_exports);
var import_general = require("@matter/general");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const logger = import_general.Logger.get("MdnsServer");
const QUESTION_SUPPRESSION_WINDOW = (0, import_general.Millis)(999);
class MdnsServer {
  #lifetime;
  #observers = new import_general.ObserverGroup();
  #recordsGenerator = /* @__PURE__ */ new Map();
  #records = new import_general.AsyncCache(
    "MDNS discovery",
    async (multicastInterface) => {
      const serviceRecords = /* @__PURE__ */ new Map();
      const addrs = await this.network.getIpMac(multicastInterface);
      if (addrs === void 0) {
        return serviceRecords;
      }
      for (const [service, generator] of this.#recordsGenerator) {
        serviceRecords.set(service, generator(multicastInterface, addrs));
      }
      return serviceRecords;
    },
    (0, import_general.Minutes)(15)
  );
  #recordLastSentAsMulticastAnswer = /* @__PURE__ */ new Map();
  #truncatedQueryCache = /* @__PURE__ */ new Map();
  /** RFC 6762 §7.3 - Tracks recently answered queries for duplicate suppression */
  #recentlyAnsweredQueries = /* @__PURE__ */ new Map();
  #socket;
  constructor(socket, lifetime = import_general.Lifetime.process) {
    this.#socket = socket;
    this.#lifetime = lifetime.join("mdns server");
    this.#observers.on(this.#socket.receipt, this.#handleMessage.bind(this));
  }
  get network() {
    return this.#socket.network;
  }
  get supportsIpv4() {
    return this.#socket.supportsIpv4;
  }
  buildDnsRecordKey(record, netInterface, unicastTarget) {
    return `${record.name}-${record.recordClass}-${record.recordType}-${netInterface}-${unicastTarget}`;
  }
  async #handleMessage(incomingMessage) {
    var _stack = [];
    try {
      const _processing = __using(_stack, this.#lifetime.join("processing message"));
      const records = await this.#records.get(incomingMessage.sourceIntf);
      if (records.size === 0) return;
      const message = this.#prepareMessage(incomingMessage);
      if (message === void 0) {
        return;
      }
      const { sourceIntf, sourceIp, transactionId, queries, answers: knownAnswers } = message;
      for (const portRecords of records.values()) {
        let answers = queries.flatMap((query) => this.#queryRecords(query, portRecords));
        if (answers.length === 0) continue;
        let additionalRecords = queries.find(
          (query) => query.recordType !== import_general.DnsRecordType.A && query.recordType !== import_general.DnsRecordType.AAAA
        ) !== void 0 ? portRecords.filter((record) => !answers.includes(record) && record.recordType !== import_general.DnsRecordType.PTR) : [];
        if (knownAnswers.length > 0) {
          for (const knownAnswersRecord of knownAnswers) {
            answers = answers.filter((record) => !(0, import_general.isDeepEqual)(record, knownAnswersRecord, true));
            if (answers.length === 0) break;
          }
          if (answers.length === 0) continue;
          if (additionalRecords.length > 0) {
            for (const knownAnswersRecord of knownAnswers) {
              additionalRecords = additionalRecords.filter(
                (record) => !(0, import_general.isDeepEqual)(record, knownAnswersRecord, true)
              );
            }
          }
        }
        const now = import_general.Time.nowMs;
        let uniCastResponse = queries.filter((query) => !query.uniCastResponse).length === 0;
        const answersTimeSinceLastSent = answers.map((answer) => ({
          timeSinceLastMultiCast: (0, import_general.Millis)(
            now - (this.#recordLastSentAsMulticastAnswer.get(this.buildDnsRecordKey(answer, sourceIntf)) ?? 0)
          ),
          ttl: answer.ttl
        }));
        if (uniCastResponse && answersTimeSinceLastSent.some(({ timeSinceLastMultiCast, ttl }) => timeSinceLastMultiCast > ttl / 4)) {
          uniCastResponse = false;
        }
        if (!uniCastResponse) {
          answers = answers.filter(
            // The last time sent as multicast was more than 900 ms ago
            (_2, index) => answersTimeSinceLastSent[index].timeSinceLastMultiCast >= (0, import_general.Millis)(900)
          );
          if (answers.length === 0) continue;
          if (this.#shouldSuppressResponse(queries, knownAnswers, sourceIntf, answers)) {
            continue;
          }
          answers.forEach(
            (answer) => this.#recordLastSentAsMulticastAnswer.set(this.buildDnsRecordKey(answer, sourceIntf), now)
          );
        }
        this.#socket.send(
          {
            messageType: import_general.DnsMessageType.Response,
            transactionId,
            answers,
            additionalRecords
          },
          sourceIntf,
          uniCastResponse ? sourceIp : void 0
        ).catch((error) => {
          logger.warn(`Failed to send mDNS response to ${sourceIp}`, error);
        });
        await import_general.Time.sleep("MDNS delay", (0, import_general.Millis)(20 + Math.floor(Math.random() * 100)));
      }
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  async #announceRecordsForInterface(netInterface, records) {
    const answers = records.filter(({ recordType }) => recordType === import_general.DnsRecordType.PTR);
    const additionalRecords = records.filter(({ recordType }) => recordType !== import_general.DnsRecordType.PTR);
    await this.#socket.send(
      {
        messageType: import_general.DnsMessageType.Response,
        answers,
        additionalRecords
      },
      netInterface
    );
  }
  async broadcast(...services) {
    var _stack = [];
    try {
      const _broadcasting = __using(_stack, this.#lifetime.join("broadcasting", import_general.Diagnostic.strong((0, import_general.describeList)("and", ...services))));
      await import_general.MatterAggregateError.allSettled(
        (await this.#getMulticastInterfacesForAnnounce()).map(async ({ name: netInterface }) => {
          const records = await this.#records.get(netInterface);
          for (const [service, serviceRecords] of records) {
            if (services.length && !services.includes(service)) continue;
            await this.#announceRecordsForInterface(netInterface, serviceRecords);
            await import_general.Time.sleep("MDNS delay", (0, import_general.Millis)(20 + Math.floor(Math.random() * 100)));
          }
        }),
        "Error announcing MDNS messages"
      ).catch((error) => logger.error(error));
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  async expireAnnouncements(...services) {
    var _stack = [];
    try {
      const _expiring = __using(_stack, this.#lifetime.join("expiring", import_general.Diagnostic.strong((0, import_general.describeList)("and", ...services))));
      await import_general.MatterAggregateError.allSettled(
        this.#records.keys().map(async (netInterface) => {
          const records = await this.#records.get(netInterface);
          for (const [service, serviceRecords] of records) {
            if (services.length && !services.includes(service)) continue;
            serviceRecords.forEach((record) => {
              record.ttl = import_general.Instant;
            });
            await this.#announceRecordsForInterface(netInterface, serviceRecords);
            this.#recordsGenerator.delete(service);
            await import_general.Time.sleep("MDNS delay", (0, import_general.Millis)(20 + Math.floor(Math.random() * 100)));
          }
        }),
        "Error happened when expiring MDNS announcements"
      ).catch((error) => logger.error(error));
      await this.#resetServices();
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  async setRecordsGenerator(service, generator) {
    await this.#records.clear();
    this.#recordLastSentAsMulticastAnswer.clear();
    this.#recentlyAnsweredQueries.clear();
    this.#recordsGenerator.set(service, generator);
  }
  async #resetServices() {
    await this.#records.clear();
    this.#recordLastSentAsMulticastAnswer.clear();
    this.#recentlyAnsweredQueries.clear();
  }
  async close() {
    var _stack = [];
    try {
      const _closing = __using(_stack, this.#lifetime.closing());
      this.#observers.close();
      await this.#records.close();
      for (const { timer } of this.#truncatedQueryCache.values()) {
        timer.stop();
      }
      this.#truncatedQueryCache.clear();
      this.#recordLastSentAsMulticastAnswer.clear();
      this.#recentlyAnsweredQueries.clear();
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  #getMulticastInterfacesForAnnounce() {
    const { netInterface } = this.#socket;
    return netInterface === void 0 ? this.network.getNetInterfaces() : [{ name: netInterface }];
  }
  #queryRecords({ name, recordType }, records) {
    if (recordType === import_general.DnsRecordType.ANY) {
      return records.filter((record) => record.name === name);
    } else {
      return records.filter((record) => record.name === name && record.recordType === recordType);
    }
  }
  /**
   * RFC 6762 §7.3 - Checks if we should suppress a response because another responder
   * has recently answered the same question with answers that cover what we'd send.
   * Also, lazily cleans up expired entries from the cache.
   */
  #shouldSuppressResponse(queries, knownAnswers, sourceIntf, answers) {
    const now = import_general.Time.nowMs;
    for (const [key, entry] of this.#recentlyAnsweredQueries) {
      if (now - entry.timestamp >= QUESTION_SUPPRESSION_WINDOW) {
        this.#recentlyAnsweredQueries.delete(key);
      }
    }
    const queryKey = queries.map((q) => `${q.name}-${q.recordType}`).sort().join("|") + `-${sourceIntf}`;
    const cached = this.#recentlyAnsweredQueries.get(queryKey);
    if (cached && now - cached.timestamp < QUESTION_SUPPRESSION_WINDOW) {
      const answerHashes = answers.map((a) => this.buildDnsRecordKey(a, sourceIntf));
      const allAnswersKnown = answerHashes.every((h) => cached.knownAnswerHashes.has(h));
      if (allAnswersKnown) {
        return true;
      }
    }
    const knownAnswerHashes = /* @__PURE__ */ new Set();
    for (const answer of knownAnswers) {
      knownAnswerHashes.add(this.buildDnsRecordKey(answer, sourceIntf));
    }
    for (const answer of answers) {
      knownAnswerHashes.add(this.buildDnsRecordKey(answer, sourceIntf));
    }
    this.#recentlyAnsweredQueries.set(queryKey, {
      knownAnswerHashes,
      timestamp: now
    });
    return false;
  }
  async #processTruncatedQuery(key) {
    const { message, timer } = this.#truncatedQueryCache.get(key) ?? {};
    this.#truncatedQueryCache.delete(key);
    timer?.stop();
    if (message) {
      if (message.queries.length === 0) {
        return;
      }
      message.messageType &= ~import_general.DnsMessageTypeFlag.TC;
      await this.#handleMessage(message);
    }
  }
  /**
   * Delays processing of truncated messages to allow combining multiple parts or combines them if possible
   */
  #prepareMessage(newMessage) {
    const { messageType, transactionId, sourceIntf, sourceIp } = newMessage;
    if (!import_general.DnsMessageType.isQuery(messageType)) {
      return;
    }
    const key = `${transactionId}-${sourceIntf}-${sourceIp}`;
    const { message: existingMessage, timer } = this.#truncatedQueryCache.get(key) ?? {};
    this.#truncatedQueryCache.delete(key);
    timer?.stop();
    const message = existingMessage ? {
      ...existingMessage,
      queries: [...existingMessage.queries, ...newMessage.queries],
      answers: [...existingMessage.answers, ...newMessage.answers],
      additionalRecords: [...existingMessage.additionalRecords, ...newMessage.additionalRecords],
      messageType: newMessage.messageType
      // Keep TC flag as is from the latest message
    } : newMessage;
    if ((messageType & import_general.DnsMessageTypeFlag.TC) === 0) {
      if (message.queries.length === 0) {
        return;
      }
      return message;
    }
    this.#truncatedQueryCache.set(key, {
      message,
      timer: import_general.Time.getTimer(
        `Truncated MDNS message ${key}`,
        (0, import_general.Millis)(400 + Math.floor(Math.random() * 100)),
        () => this.#processTruncatedQuery(key)
      ).start()
    });
  }
}
//# sourceMappingURL=MdnsServer.js.map
