/**
 * Utility for making request-response calls through the gateway.
 *
 * Some handlers (e.g., machines_list) need to forward a request to the gateway
 * and wait for the corresponding response.  This module provides a simple
 * promise-based mechanism backed by a one-time message listener.
 */
const DEFAULT_TIMEOUT_MS = 15_000;
/**
 * Send a request message through the gateway and wait for a response whose
 * `type` matches `expectedResponseType` and `requestId` matches.
 *
 * Rejects if no response arrives within `timeoutMs` (default 15 s).
 */
export function gatewayRequest(client, request, expectedResponseType, timeoutMs = DEFAULT_TIMEOUT_MS) {
    return new Promise((resolve, reject) => {
        const requestId = request.requestId;
        const cleanup = () => {
            client.off("message", listener);
            clearTimeout(timer);
        };
        const listener = (msg) => {
            if (msg.type === "ping")
                return;
            const m = msg;
            if (m.type === expectedResponseType && m.requestId === requestId) {
                cleanup();
                resolve(m);
            }
        };
        const timer = setTimeout(() => {
            cleanup();
            reject(new Error(`Gateway request timed out after ${timeoutMs}ms`));
        }, timeoutMs);
        client.on("message", listener);
        client.send(request);
    });
}
//# sourceMappingURL=gateway-request.js.map