/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { Terminal } from "../docker/terminal.js";
import { CommandPipe } from "./command-pipe.js";
const FIFO_PATH = "/command-pipe.fifo";
class ContainerCommandPipe extends CommandPipe {
  #container;
  #deactivate;
  #stopped;
  constructor(container, subject) {
    super(subject, "/command-pipe.fifo");
    this.#container = container;
  }
  async initialize() {
    await this.#container.createPipe(FIFO_PATH);
    this.#stopped = this.#processCommands();
  }
  async installForApp(name) {
    await this.#container.exec(["ln", "-sf", this.filename, ContainerCommandPipe.filenameFor(name)]);
  }
  async close() {
    this.#deactivate?.();
    this.#deactivate = void 0;
    await this.#stopped;
    this.#stopped = void 0;
  }
  async #processCommands() {
    let commands;
    try {
      commands = await this.#container.exec(
        ["bash", "-c", `while true; do cat ${FIFO_PATH}; done`],
        Terminal.StdoutLine
      );
      const deactivated = new Promise((resolve) => {
        this.#deactivate = resolve;
      });
      const iterator = commands[Symbol.asyncIterator]();
      while (true) {
        const command = await Promise.race([
          deactivated,
          iterator.next().then((result) => result.value)
        ]);
        if (command === void 0) {
          break;
        }
        this.onData(command);
      }
      await deactivated;
    } finally {
      if (commands) {
        try {
          await commands.close();
        } catch (e) {
          console.warn(`Error closing command proxy for ${this.filename}:`, e);
        }
      }
      try {
        await this.#container.delete(this.filename, { force: true });
      } catch (e) {
        console.warn(`Error deleting FIFO ${this.filename}:`, e);
      }
    }
  }
}
export {
  ContainerCommandPipe,
  FIFO_PATH
};
//# sourceMappingURL=container-command-pipe.js.map
