/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { ObserverGroup } from "#util/Observable.js";
function discoverNames(names, suffix, signal) {
  const normalizedSuffix = `.${suffix.toLowerCase().replace(/\.local$/, "")}.local`;
  const exactType = suffix.toLowerCase().replace(/\.local$/, "") + ".local";
  const filter = (record) => {
    const lower = record.name.toLowerCase();
    return lower === exactType || lower.endsWith(normalizedSuffix);
  };
  names.filters.add(filter, [exactType]);
  const observers = new ObserverGroup();
  const queue = [];
  let waiting;
  let done = false;
  const push = (name) => {
    if (done) return;
    const lower = name.qname.toLowerCase();
    if (lower.endsWith(normalizedSuffix)) {
      if (waiting) {
        const resolve = waiting;
        waiting = void 0;
        resolve({ value: name, done: false });
      } else {
        queue.push(name);
      }
    }
  };
  const cleanup = () => {
    if (done) return;
    done = true;
    observers.close();
    names.filters.delete(filter);
    signal.removeEventListener("abort", onAbort);
    if (waiting) {
      const resolve = waiting;
      waiting = void 0;
      resolve({ value: void 0, done: true });
    }
  };
  const onAbort = () => cleanup();
  signal.addEventListener("abort", onAbort, { once: true });
  observers.on(names.discovered, push);
  for (const name of names.discoveredNames) {
    push(name);
  }
  if (signal.aborted) {
    cleanup();
  }
  const iterator = {
    next() {
      if (done) {
        return Promise.resolve({ value: void 0, done: true });
      }
      if (queue.length > 0) {
        return Promise.resolve({ value: queue.shift(), done: false });
      }
      return new Promise((resolve) => {
        waiting = resolve;
      });
    },
    return() {
      cleanup();
      return Promise.resolve({ value: void 0, done: true });
    },
    [Symbol.asyncIterator]() {
      return iterator;
    }
  };
  return iterator;
}
export {
  discoverNames
};
//# sourceMappingURL=ServiceDiscovery.js.map
