2026-04-05 21:09:33 -05:00
|
|
|
/**
|
|
|
|
|
* Shared CLI utilities.
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
import type { Command } from "commander";
|
2026-04-05 22:44:45 -05:00
|
|
|
import { createTrustGraphSocket, type BaseApi } from "@trustgraph/client";
|
2026-04-05 21:09:33 -05:00
|
|
|
|
|
|
|
|
export interface CliOpts {
|
|
|
|
|
gateway: string;
|
2026-04-05 22:44:45 -05:00
|
|
|
user: string;
|
2026-04-05 21:09:33 -05:00
|
|
|
token?: string;
|
|
|
|
|
flow: string;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function getOpts(cmd: Command): CliOpts {
|
|
|
|
|
// Walk up to root command to get global options
|
|
|
|
|
let root = cmd;
|
2026-05-12 08:06:58 -05:00
|
|
|
while (root.parent !== null) root = root.parent;
|
2026-04-05 21:09:33 -05:00
|
|
|
return root.opts() as CliOpts;
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-05 22:44:45 -05:00
|
|
|
/**
|
|
|
|
|
* Create a BaseApi socket client and wait for the connection to be established.
|
|
|
|
|
* The client auto-connects; we listen for the first "connected/authenticated"
|
|
|
|
|
* state before handing it back to the caller.
|
|
|
|
|
*/
|
|
|
|
|
export async function createSocket(opts: CliOpts): Promise<BaseApi> {
|
|
|
|
|
const socket = createTrustGraphSocket(opts.user, opts.token, opts.gateway);
|
|
|
|
|
|
|
|
|
|
// Wait for the socket to reach an open state
|
|
|
|
|
await new Promise<void>((resolve, reject) => {
|
|
|
|
|
const timeout = setTimeout(() => {
|
|
|
|
|
unsub();
|
|
|
|
|
reject(new Error("Timed out waiting for WebSocket connection"));
|
|
|
|
|
}, 15_000);
|
|
|
|
|
|
|
|
|
|
const unsub = socket.onConnectionStateChange((state) => {
|
|
|
|
|
if (
|
|
|
|
|
state.status === "authenticated" ||
|
|
|
|
|
state.status === "unauthenticated"
|
|
|
|
|
) {
|
|
|
|
|
clearTimeout(timeout);
|
|
|
|
|
unsub();
|
|
|
|
|
resolve();
|
|
|
|
|
} else if (state.status === "failed") {
|
|
|
|
|
clearTimeout(timeout);
|
|
|
|
|
unsub();
|
|
|
|
|
reject(new Error(state.lastError ?? "WebSocket connection failed"));
|
|
|
|
|
}
|
|
|
|
|
});
|
2026-04-05 21:09:33 -05:00
|
|
|
});
|
2026-04-05 22:44:45 -05:00
|
|
|
|
2026-04-05 21:09:33 -05:00
|
|
|
return socket;
|
|
|
|
|
}
|