import type { MarketClient } from './client.js' import { getAuthToken } from '@drawcall/auth' import { createClient as createV1Client } from './v1/client.js' import { loadConfig } from './config.js' const DEFAULT_BASE_URL = 'https://market.drawcall.ai' export class NotLoggedInError extends Error { constructor() { super('Not logged in. Run `market login` first.') this.name = 'NotLoggedInError' } } export interface CliClientOptions { /** Override the API base URL. Takes precedence over config and defaults. */ baseUrl?: string /** Require authentication. When true, throws NotLoggedInError if no token is available. */ requireAuth?: boolean } export interface CliClient { client: MarketClient baseUrl: string authToken: string | undefined } export async function getCliClient(opts: CliClientOptions = {}): Promise { const authToken = await getAuthToken() const config = await loadConfig() const baseUrl = opts.baseUrl ?? process.env.MARKET_API_URL ?? config?.baseUrl ?? DEFAULT_BASE_URL if (opts.requireAuth && !authToken) { throw new NotLoggedInError() } return { // The v1 client has the same call shapes as the legacy `MarketClient`, so every CLI command // and library consumer of `getCliClient` speaks /api/v1 without a signature change. client: createV1Client({ baseUrl, authToken }), baseUrl, authToken, } }