@onlist/sdk 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/errors.ts","../src/version.ts","../src/marketplace.ts"],"sourcesContent":["export { Onlist } from \"./client.js\";\nexport type { OnlistOptions } from \"./client.js\";\n\nexport { Marketplace, MarketplaceModels, MarketplaceProviders, MarketplaceRankings } from \"./marketplace.js\";\nexport type { MarketplaceOptions } from \"./marketplace.js\";\n\nexport {\n OnlistError,\n APIError,\n AuthenticationError,\n InsufficientBalanceError,\n NotFoundError,\n RateLimitError,\n ProviderError,\n} from \"./errors.js\";\n\nexport type {\n Pricing,\n Architecture,\n TopProvider,\n Model,\n ProviderOffer,\n ModelDetail,\n ModelListResponse,\n Provider,\n ProviderDetail,\n ProviderListResponse,\n MaxPrice,\n ProviderRouting,\n ModelRanking,\n ModelSeriesPoint,\n ModelRankingsResponse,\n ModelRankingsParams,\n AppRanking,\n AppRankingsResponse,\n AppRankingsParams,\n} from \"./types/index.js\";\n\nexport { VERSION } from \"./version.js\";\n","import OpenAI from \"openai\";\nimport type { ClientOptions } from \"openai\";\nimport { Marketplace } from \"./marketplace.js\";\nimport { VERSION } from \"./version.js\";\n\nconst BASE_URL = \"https://onlist.io/v1\";\nconst MARKETPLACE_BASE_URL = \"https://onlist.io\";\n\n/** Options for creating an Onlist client. */\nexport interface OnlistOptions extends Omit<ClientOptions, \"apiKey\" | \"baseURL\"> {\n /** API key. Falls back to ONLIST_API_KEY then OPENAI_API_KEY env vars. */\n apiKey?: string | null;\n /** Base URL for the API. Defaults to https://onlist.io/v1. */\n baseURL?: string | null;\n /** Maximum retry attempts for marketplace API calls. Defaults to 2. */\n maxRetries?: number;\n}\n\n/** Onlist API client, extending the OpenAI SDK with marketplace features. */\nexport class Onlist extends OpenAI {\n /** Access to marketplace data: models, providers, and rankings. */\n readonly marketplace: Marketplace;\n\n constructor(opts?: OnlistOptions) {\n const apiKey =\n opts?.apiKey ??\n (typeof process !== \"undefined\"\n ? process.env?.ONLIST_API_KEY ?? process.env?.OPENAI_API_KEY\n : undefined) ??\n undefined;\n\n const baseURL = opts?.baseURL ?? BASE_URL;\n\n super({\n ...opts,\n apiKey: apiKey ?? undefined,\n baseURL,\n defaultHeaders: {\n \"User-Agent\": `onlist-js/${VERSION}`,\n \"HTTP-Referer\": \"https://onlist.io\",\n ...opts?.defaultHeaders,\n },\n });\n\n const marketplaceBase = String(baseURL).split(\"/v1\")[0] || MARKETPLACE_BASE_URL;\n\n this.marketplace = new Marketplace({\n apiKey: this.apiKey,\n baseURL: marketplaceBase,\n maxRetries: opts?.maxRetries,\n });\n }\n}\n","/** Base error class for all Onlist SDK errors. */\nexport class OnlistError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"OnlistError\";\n }\n}\n\n/** Error thrown when an API request fails. */\nexport class APIError extends OnlistError {\n readonly status: number;\n readonly type: string | null;\n readonly code: string | null;\n readonly param: string | null;\n readonly body: unknown;\n\n constructor(\n message: string,\n opts: {\n status: number;\n type?: string | null;\n code?: string | null;\n param?: string | null;\n body?: unknown;\n },\n ) {\n super(message);\n this.name = \"APIError\";\n this.status = opts.status;\n this.type = opts.type ?? null;\n this.code = opts.code ?? null;\n this.param = opts.param ?? null;\n this.body = opts.body ?? null;\n }\n}\n\n/** Error thrown when the API key is invalid or missing. */\nexport class AuthenticationError extends APIError {\n constructor(message = \"Invalid API key\", opts?: Partial<ConstructorParameters<typeof APIError>[1]>) {\n super(message, { status: 401, ...opts });\n this.name = \"AuthenticationError\";\n }\n}\n\n/** Error thrown when the account balance is insufficient. */\nexport class InsufficientBalanceError extends APIError {\n constructor(message = \"Insufficient balance\", opts?: Partial<ConstructorParameters<typeof APIError>[1]>) {\n super(message, { status: 402, ...opts });\n this.name = \"InsufficientBalanceError\";\n }\n}\n\n/** Error thrown when the request is rate-limited. */\nexport class RateLimitError extends APIError {\n constructor(message = \"Rate limited\", opts?: Partial<ConstructorParameters<typeof APIError>[1]>) {\n super(message, { status: 429, ...opts });\n this.name = \"RateLimitError\";\n }\n}\n\n/** Error thrown when no matching provider is available. */\nexport class ProviderError extends APIError {\n constructor(message: string, opts: ConstructorParameters<typeof APIError>[1]) {\n super(message, opts);\n this.name = \"ProviderError\";\n }\n}\n\n/** Error thrown when a requested resource is not found. */\nexport class NotFoundError extends APIError {\n constructor(message = \"Not found\", opts?: Partial<ConstructorParameters<typeof APIError>[1]>) {\n super(message, { status: 404, ...opts });\n this.name = \"NotFoundError\";\n }\n}\n\nexport function raiseForStatus(status: number, body: unknown): never {\n let error: Record<string, unknown> = {};\n if (body && typeof body === \"object\" && \"error\" in body) {\n const e = (body as Record<string, unknown>).error;\n error = typeof e === \"object\" && e !== null ? (e as Record<string, unknown>) : {};\n } else if (body && typeof body === \"object\") {\n error = body as Record<string, unknown>;\n }\n\n const message = (typeof error.message === \"string\" ? error.message : String(body)) || \"Unknown error\";\n const type = typeof error.type === \"string\" ? error.type : null;\n const code = typeof error.code === \"string\" ? error.code : null;\n const param = typeof error.param === \"string\" ? error.param : null;\n const opts = { status, type, code, param, body };\n\n if (status === 401) throw new AuthenticationError(message, opts);\n if (status === 402) throw new InsufficientBalanceError(message, opts);\n if (status === 404) throw new NotFoundError(message, opts);\n if (status === 429) throw new RateLimitError(message, opts);\n if (code && code.startsWith(\"no_provider\")) throw new ProviderError(message, opts);\n\n throw new APIError(message, opts);\n}\n","export const VERSION = \"0.2.0\";\n","import { raiseForStatus } from \"./errors.js\";\nimport { VERSION } from \"./version.js\";\nimport type { ModelDetail, ModelListResponse } from \"./types/model.js\";\nimport type { ProviderDetail, ProviderListResponse } from \"./types/provider.js\";\nimport type {\n ModelRankingsResponse,\n ModelRankingsParams,\n AppRankingsResponse,\n AppRankingsParams,\n} from \"./types/rankings.js\";\n\nconst DEFAULT_TIMEOUT = 30_000;\nconst DEFAULT_MAX_RETRIES = 2;\nconst INITIAL_RETRY_DELAY = 500;\nconst MAX_RETRY_DELAY = 8_000;\nconst JITTER_FACTOR = 0.25;\n\n/** Retryable status codes: timeouts, rate limits, and server errors. */\nconst RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]);\n\nfunction encodePath(segment: string): string {\n return segment\n .split(\"/\")\n .map((s) => encodeURIComponent(s))\n .join(\"/\");\n}\n\nasync function parseResponse(response: Response): Promise<unknown> {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n body = await response.text().catch(() => \"\");\n }\n\n if (!response.ok) {\n raiseForStatus(response.status, body);\n }\n\n if (body && typeof body === \"object\" && \"data\" in body && \"success\" in body) {\n return (body as Record<string, unknown>).data;\n }\n return body;\n}\n\n/** Calculates the retry delay with exponential backoff and jitter. */\nfunction retryDelay(attempt: number, retryAfterHeader: string | null): number {\n if (retryAfterHeader) {\n const seconds = Number(retryAfterHeader);\n if (!isNaN(seconds) && seconds > 0) {\n return Math.min(seconds * 1000, MAX_RETRY_DELAY);\n }\n }\n const base = Math.min(INITIAL_RETRY_DELAY * 2 ** attempt, MAX_RETRY_DELAY);\n const jitter = base * JITTER_FACTOR * (2 * Math.random() - 1);\n return Math.max(0, base + jitter);\n}\n\n/** Options for creating a Marketplace client. */\nexport interface MarketplaceOptions {\n apiKey?: string | null;\n baseURL: string;\n timeout?: number;\n /** Maximum retry attempts for failed requests. Defaults to 2. */\n maxRetries?: number;\n}\n\n/** Access to marketplace model data. */\nexport class MarketplaceModels {\n constructor(private readonly _opts: MarketplaceOptions) {}\n\n /** List models in the marketplace catalog. */\n async list(params?: { limit?: number; offset?: number; q?: string }): Promise<ModelListResponse> {\n const search = new URLSearchParams();\n search.set(\"limit\", String(params?.limit ?? 20));\n search.set(\"offset\", String(params?.offset ?? 0));\n if (params?.q) search.set(\"q\", params.q);\n\n const resp = await fetchWithRetry(this._opts, `/api/mkt/models?${search}`);\n return (await parseResponse(resp)) as ModelListResponse;\n }\n\n /** Get detailed info for a specific model, including provider offers. */\n async get(modelId: string): Promise<ModelDetail> {\n const resp = await fetchWithRetry(this._opts, `/api/mkt/models/${encodePath(modelId)}`);\n let data = (await parseResponse(resp)) as Record<string, unknown>;\n if (data && typeof data === \"object\" && \"data\" in data) {\n data = data.data as Record<string, unknown>;\n }\n return data as unknown as ModelDetail;\n }\n}\n\n/** Access to marketplace provider data. */\nexport class MarketplaceProviders {\n constructor(private readonly _opts: MarketplaceOptions) {}\n\n /** List providers on the marketplace. */\n async list(params?: { sort?: string; q?: string }): Promise<ProviderListResponse> {\n const search = new URLSearchParams();\n if (params?.sort) search.set(\"sort\", params.sort);\n if (params?.q) search.set(\"q\", params.q);\n\n const qs = search.toString();\n const resp = await fetchWithRetry(this._opts, `/api/mkt/providers${qs ? `?${qs}` : \"\"}`);\n return (await parseResponse(resp)) as ProviderListResponse;\n }\n\n /** Get detailed info for a specific provider. */\n async get(slug: string): Promise<ProviderDetail> {\n const resp = await fetchWithRetry(this._opts, `/api/mkt/provider/${encodePath(slug)}`);\n let data = (await parseResponse(resp)) as Record<string, unknown>;\n if (data && typeof data === \"object\" && \"data\" in data) {\n data = data.data as Record<string, unknown>;\n }\n return data as unknown as ProviderDetail;\n }\n}\n\n/** Access to marketplace rankings (models and apps). */\nexport class MarketplaceRankings {\n constructor(private readonly _opts: MarketplaceOptions) {}\n\n /** Get the model usage leaderboard and chart series. */\n async models(params?: ModelRankingsParams): Promise<ModelRankingsResponse> {\n const search = new URLSearchParams();\n if (params?.sort) search.set(\"sort\", params.sort);\n if (params?.window) search.set(\"window\", params.window);\n if (params?.limit != null) search.set(\"limit\", String(params.limit));\n if (params?.offset != null) search.set(\"offset\", String(params.offset));\n\n const qs = search.toString();\n const resp = await fetchWithRetry(this._opts, `/api/mkt/rankings/models${qs ? `?${qs}` : \"\"}`);\n return (await parseResponse(resp)) as ModelRankingsResponse;\n }\n\n /** Get the app rankings list. */\n async apps(params?: AppRankingsParams): Promise<AppRankingsResponse> {\n const search = new URLSearchParams();\n if (params?.sort) search.set(\"sort\", params.sort);\n if (params?.window) search.set(\"window\", params.window);\n if (params?.category) search.set(\"category\", params.category);\n if (params?.subcategory) search.set(\"subcategory\", params.subcategory);\n if (params?.page != null) search.set(\"page\", String(params.page));\n if (params?.limit != null) search.set(\"limit\", String(params.limit));\n\n const qs = search.toString();\n const resp = await fetchWithRetry(this._opts, `/api/mkt/apps${qs ? `?${qs}` : \"\"}`);\n return (await parseResponse(resp)) as AppRankingsResponse;\n }\n}\n\n/** Client for the Onlist marketplace public API. */\nexport class Marketplace {\n /** Browse and search models. */\n readonly models: MarketplaceModels;\n /** Browse and search providers. */\n readonly providers: MarketplaceProviders;\n /** Model and app usage rankings. */\n readonly rankings: MarketplaceRankings;\n\n constructor(opts: MarketplaceOptions) {\n this.models = new MarketplaceModels(opts);\n this.providers = new MarketplaceProviders(opts);\n this.rankings = new MarketplaceRankings(opts);\n }\n}\n\nfunction buildFetchInit(opts: MarketplaceOptions, init?: RequestInit): RequestInit {\n const headers: Record<string, string> = {\n \"User-Agent\": `onlist-js/${VERSION}`,\n Accept: \"application/json\",\n ...(init?.headers as Record<string, string>),\n };\n if (opts.apiKey) {\n headers[\"Authorization\"] = `Bearer ${opts.apiKey}`;\n }\n const signal = AbortSignal.timeout(opts.timeout ?? DEFAULT_TIMEOUT);\n return { ...init, headers, signal };\n}\n\nasync function fetchWithRetry(\n opts: MarketplaceOptions,\n path: string,\n init?: RequestInit,\n): Promise<Response> {\n const url = `${opts.baseURL.replace(/\\/$/, \"\")}${path}`;\n const fetchInit = buildFetchInit(opts, init);\n const maxRetries = opts.maxRetries ?? DEFAULT_MAX_RETRIES;\n\n let lastError: unknown;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const response = await fetch(url, fetchInit);\n if (response.ok || !RETRYABLE_STATUSES.has(response.status) || attempt === maxRetries) {\n return response;\n }\n const delay = retryDelay(attempt, response.headers.get(\"Retry-After\"));\n await new Promise((resolve) => setTimeout(resolve, delay));\n } catch (err) {\n lastError = err;\n if (attempt === maxRetries) break;\n const delay = retryDelay(attempt, null);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n throw lastError;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAAmB;;;ACCZ,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,WAAN,cAAuB,YAAY;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,SACA,MAOA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,KAAK;AACnB,SAAK,OAAO,KAAK,QAAQ;AACzB,SAAK,OAAO,KAAK,QAAQ;AACzB,SAAK,QAAQ,KAAK,SAAS;AAC3B,SAAK,OAAO,KAAK,QAAQ;AAAA,EAC3B;AACF;AAGO,IAAM,sBAAN,cAAkC,SAAS;AAAA,EAChD,YAAY,UAAU,mBAAmB,MAA2D;AAClG,UAAM,SAAS,EAAE,QAAQ,KAAK,GAAG,KAAK,CAAC;AACvC,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,2BAAN,cAAuC,SAAS;AAAA,EACrD,YAAY,UAAU,wBAAwB,MAA2D;AACvG,UAAM,SAAS,EAAE,QAAQ,KAAK,GAAG,KAAK,CAAC;AACvC,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,iBAAN,cAA6B,SAAS;AAAA,EAC3C,YAAY,UAAU,gBAAgB,MAA2D;AAC/F,UAAM,SAAS,EAAE,QAAQ,KAAK,GAAG,KAAK,CAAC;AACvC,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,gBAAN,cAA4B,SAAS;AAAA,EAC1C,YAAY,SAAiB,MAAiD;AAC5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AAQ,KAAK,kBAAkB,QAAQ,KAAK,iBAC5C,WACJ;AAEF,UAAM,UAAU,MAAM,WAAW;AAEjC,UAAM;AAAA,MACJ,GAAG;AAAA,MACH,QAAQ,UAAU;AAAA,MAClB;AAAA,MACA,gBAAgB;AAAA,QACd,cAAc,aAAa,OAAO;AAAA,QAClC,gBAAgB;AAAA,QAChB,GAAG,MAAM;AAAA,MACX;AAAA,IACF,CAAC;AAED,UAAM,kBAAkB,OAAO,OAAO,EAAE,MAAM,KAAK,EAAE,CAAC,KAAK;AAE3D,SAAK,cAAc,IAAI,YAAY;AAAA,MACjC,QAAQ,KAAK;AAAA,MACb,SAAS;AAAA,MACT,YAAY,MAAM;AAAA,IACpB,CAAC;AAAA,EACH;AACF;","names":["OpenAI"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/errors.ts","../src/version.ts","../src/http.ts","../src/account.ts","../src/marketplace.ts"],"sourcesContent":["export { Onlist } from \"./client.js\";\nexport type { OnlistOptions } from \"./client.js\";\n\nexport { Marketplace, MarketplaceModels, MarketplaceProviders, MarketplaceRankings } from \"./marketplace.js\";\nexport type { MarketplaceOptions } from \"./marketplace.js\";\n\nexport {\n AccountActivity,\n AccountApiKeys,\n AccountCredits,\n AccountGenerations,\n AccountOAuth,\n exchangeAuthCode,\n generatePkce,\n} from \"./account.js\";\nexport type { AccountOptions } from \"./account.js\";\n\nexport {\n OnlistError,\n APIError,\n AuthenticationError,\n BadRequestError,\n InsufficientBalanceError,\n NotFoundError,\n PermissionDeniedError,\n RateLimitError,\n ProviderError,\n} from \"./errors.js\";\n\nexport type {\n Pricing,\n Architecture,\n TopProvider,\n Model,\n ProviderOffer,\n ModelDetail,\n ModelListResponse,\n Provider,\n ProviderDetail,\n ProviderListResponse,\n MaxPrice,\n ProviderRouting,\n ModelRanking,\n ModelSeriesPoint,\n ModelRankingsResponse,\n ModelRankingsParams,\n AppRanking,\n AppRankingsResponse,\n AppRankingsParams,\n RateLimit,\n APIKey,\n CurrentKey,\n CreatedKey,\n CreateKeyParams,\n UpdateKeyParams,\n ListKeysParams,\n Credits,\n Generation,\n ActivityRow,\n ActivityParams,\n ExchangedKey,\n PkcePair,\n} from \"./types/index.js\";\n\nexport { VERSION } from \"./version.js\";\n","import OpenAI from \"openai\";\nimport type { ClientOptions } from \"openai\";\nimport {\n AccountActivity,\n AccountApiKeys,\n AccountCredits,\n AccountGenerations,\n AccountOAuth,\n} from \"./account.js\";\nimport { Marketplace } from \"./marketplace.js\";\nimport { VERSION } from \"./version.js\";\n\nconst BASE_URL = \"https://onlist.io/v1\";\nconst MARKETPLACE_BASE_URL = \"https://onlist.io\";\n\n/** Options for creating an Onlist client. */\nexport interface OnlistOptions extends Omit<ClientOptions, \"apiKey\" | \"baseURL\"> {\n /** API key. Falls back to ONLIST_API_KEY then OPENAI_API_KEY env vars. */\n apiKey?: string | null;\n /**\n * Management key (`mgmt_...`) for the account API. Falls back to\n * ONLIST_MANAGEMENT_KEY, then to the API key.\n */\n managementKey?: string | null;\n /** Base URL for the API. Defaults to https://onlist.io/v1. */\n baseURL?: string | null;\n /** Maximum retry attempts for marketplace and account API calls. Defaults to 2. */\n maxRetries?: number;\n}\n\n/** Onlist API client, extending the OpenAI SDK with marketplace and account features. */\nexport class Onlist extends OpenAI {\n /** Access to marketplace data: models, providers, and rankings. */\n readonly marketplace: Marketplace;\n /** Account balance. */\n readonly credits: AccountCredits;\n /** Cost and timing for individual calls. */\n readonly generations: AccountGenerations;\n /** Inference key management. */\n readonly apiKeys: AccountApiKeys;\n /** Daily usage rollups. */\n readonly activity: AccountActivity;\n /** Sign in with Onlist — the PKCE code exchange. */\n readonly oauth: AccountOAuth;\n /** The credential the account API is using. */\n readonly managementKey: string | undefined;\n\n constructor(opts?: OnlistOptions) {\n const apiKey =\n opts?.apiKey ??\n (typeof process !== \"undefined\"\n ? process.env?.ONLIST_API_KEY ?? process.env?.OPENAI_API_KEY\n : undefined) ??\n undefined;\n\n const baseURL = opts?.baseURL ?? BASE_URL;\n\n super({\n ...opts,\n apiKey: apiKey ?? undefined,\n baseURL,\n defaultHeaders: {\n \"User-Agent\": `onlist-js/${VERSION}`,\n \"HTTP-Referer\": \"https://onlist.io\",\n ...opts?.defaultHeaders,\n },\n });\n\n const marketplaceBase = String(baseURL).split(\"/v1\")[0] || MARKETPLACE_BASE_URL;\n\n this.marketplace = new Marketplace({\n apiKey: this.apiKey,\n baseURL: marketplaceBase,\n maxRetries: opts?.maxRetries,\n });\n\n // Falls back to the inference key so that a client built the OpenRouter\n // way — one key, one keyhole — still reaches the account endpoints.\n // Whether that key is allowed there is the server's call: the SDK never\n // inspects key prefixes locally, it just surfaces the 403.\n this.managementKey =\n opts?.managementKey ??\n (typeof process !== \"undefined\" ? process.env?.ONLIST_MANAGEMENT_KEY : undefined) ??\n this.apiKey ??\n undefined;\n\n const accountOpts = {\n apiKey: this.managementKey,\n baseURL: marketplaceBase,\n maxRetries: opts?.maxRetries,\n };\n this.credits = new AccountCredits(accountOpts);\n this.generations = new AccountGenerations(accountOpts);\n this.apiKeys = new AccountApiKeys(accountOpts);\n this.activity = new AccountActivity(accountOpts);\n this.oauth = new AccountOAuth(accountOpts);\n }\n}\n","/** Base error class for all Onlist SDK errors. */\nexport class OnlistError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"OnlistError\";\n }\n}\n\n/** Error thrown when an API request fails. */\nexport class APIError extends OnlistError {\n readonly status: number;\n readonly type: string | null;\n readonly code: string | null;\n readonly param: string | null;\n readonly body: unknown;\n\n constructor(\n message: string,\n opts: {\n status: number;\n type?: string | null;\n code?: string | null;\n param?: string | null;\n body?: unknown;\n },\n ) {\n super(message);\n this.name = \"APIError\";\n this.status = opts.status;\n this.type = opts.type ?? null;\n this.code = opts.code ?? null;\n this.param = opts.param ?? null;\n this.body = opts.body ?? null;\n }\n}\n\n/** Error thrown when the API key is invalid or missing. */\nexport class AuthenticationError extends APIError {\n constructor(message = \"Invalid API key\", opts?: Partial<ConstructorParameters<typeof APIError>[1]>) {\n super(message, { status: 401, ...opts });\n this.name = \"AuthenticationError\";\n }\n}\n\n/** Error thrown when the account balance is insufficient. */\nexport class InsufficientBalanceError extends APIError {\n constructor(message = \"Insufficient balance\", opts?: Partial<ConstructorParameters<typeof APIError>[1]>) {\n super(message, { status: 402, ...opts });\n this.name = \"InsufficientBalanceError\";\n }\n}\n\n/** Error thrown when the request is rate-limited. */\nexport class RateLimitError extends APIError {\n constructor(message = \"Rate limited\", opts?: Partial<ConstructorParameters<typeof APIError>[1]>) {\n super(message, { status: 429, ...opts });\n this.name = \"RateLimitError\";\n }\n}\n\n/** Error thrown when no matching provider is available. */\nexport class ProviderError extends APIError {\n constructor(message: string, opts: ConstructorParameters<typeof APIError>[1]) {\n super(message, opts);\n this.name = \"ProviderError\";\n }\n}\n\n/** Error thrown when a requested resource is not found. */\nexport class NotFoundError extends APIError {\n constructor(message = \"Not found\", opts?: Partial<ConstructorParameters<typeof APIError>[1]>) {\n super(message, { status: 404, ...opts });\n this.name = \"NotFoundError\";\n }\n}\n\n/** Error thrown when the request is malformed or its parameters are rejected. */\nexport class BadRequestError extends APIError {\n constructor(message = \"Bad request\", opts?: Partial<ConstructorParameters<typeof APIError>[1]>) {\n super(message, { status: 400, ...opts });\n this.name = \"BadRequestError\";\n }\n}\n\n/**\n * Error thrown when the credential is valid but not allowed here.\n *\n * Most commonly: an inference key (`sk-...`) was used on an endpoint that\n * only accepts a management key (`mgmt_...`). The server's message is passed\n * through unchanged.\n */\nexport class PermissionDeniedError extends APIError {\n constructor(\n message = \"Permission denied\",\n opts?: Partial<ConstructorParameters<typeof APIError>[1]>,\n ) {\n super(message, { status: 403, ...opts });\n this.name = \"PermissionDeniedError\";\n }\n}\n\nexport function raiseForStatus(status: number, body: unknown): never {\n let error: Record<string, unknown> = {};\n if (body && typeof body === \"object\" && \"error\" in body) {\n const e = (body as Record<string, unknown>).error;\n error = typeof e === \"object\" && e !== null ? (e as Record<string, unknown>) : {};\n } else if (body && typeof body === \"object\") {\n error = body as Record<string, unknown>;\n }\n\n const message = (typeof error.message === \"string\" ? error.message : String(body)) || \"Unknown error\";\n const type = typeof error.type === \"string\" ? error.type : null;\n // The account face sends `code` as the HTTP status (an int), the\n // marketplace as a string slug. Only strings survive to `code`.\n const code = typeof error.code === \"string\" ? error.code : null;\n const param = typeof error.param === \"string\" ? error.param : null;\n const opts = { status, type, code, param, body };\n\n if (status === 400) throw new BadRequestError(message, opts);\n if (status === 401) throw new AuthenticationError(message, opts);\n if (status === 402) throw new InsufficientBalanceError(message, opts);\n if (status === 403) throw new PermissionDeniedError(message, opts);\n if (status === 404) throw new NotFoundError(message, opts);\n if (status === 429) throw new RateLimitError(message, opts);\n if (code && code.startsWith(\"no_provider\")) throw new ProviderError(message, opts);\n\n throw new APIError(message, opts);\n}\n","export const VERSION = \"0.3.0\";\n","import { raiseForStatus } from \"./errors.js\";\nimport { VERSION } from \"./version.js\";\n\nexport const DEFAULT_TIMEOUT = 30_000;\nexport const DEFAULT_MAX_RETRIES = 2;\nconst INITIAL_RETRY_DELAY = 500;\nconst MAX_RETRY_DELAY = 8_000;\nconst JITTER_FACTOR = 0.25;\n\n/** Retryable status codes: timeouts, rate limits, and server errors. */\nexport const RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]);\n\n/** Shared options for the REST resources (marketplace and account). */\nexport interface RequestOptions {\n apiKey?: string | null;\n baseURL: string;\n timeout?: number;\n /** Maximum retry attempts for failed requests. Defaults to 2. */\n maxRetries?: number;\n}\n\nexport function encodePath(segment: string): string {\n return segment\n .split(\"/\")\n .map((s) => encodeURIComponent(s))\n .join(\"/\");\n}\n\nexport async function parseResponse(response: Response): Promise<unknown> {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n body = await response.text().catch(() => \"\");\n }\n\n if (!response.ok) {\n raiseForStatus(response.status, body);\n }\n\n // Only the marketplace envelope ({success, data}) is unwrapped here. The\n // account face uses OpenRouter's {data} without `success`, and POST /keys\n // returns {data, key} where the sibling field is the whole point —\n // unwrapping either one would silently drop data.\n if (body && typeof body === \"object\" && \"data\" in body && \"success\" in body) {\n return (body as Record<string, unknown>).data;\n }\n return body;\n}\n\n/** Calculates the retry delay with exponential backoff and jitter. */\nexport function retryDelay(attempt: number, retryAfterHeader: string | null): number {\n if (retryAfterHeader) {\n const seconds = Number(retryAfterHeader);\n if (!isNaN(seconds) && seconds > 0) {\n return Math.min(seconds * 1000, MAX_RETRY_DELAY);\n }\n }\n const base = Math.min(INITIAL_RETRY_DELAY * 2 ** attempt, MAX_RETRY_DELAY);\n const jitter = base * JITTER_FACTOR * (2 * Math.random() - 1);\n return Math.max(0, base + jitter);\n}\n\nexport function buildFetchInit(opts: RequestOptions, init?: RequestInit): RequestInit {\n const headers: Record<string, string> = {\n \"User-Agent\": `onlist-js/${VERSION}`,\n Accept: \"application/json\",\n ...(init?.headers as Record<string, string>),\n };\n if (opts.apiKey) {\n headers[\"Authorization\"] = `Bearer ${opts.apiKey}`;\n }\n const signal = AbortSignal.timeout(opts.timeout ?? DEFAULT_TIMEOUT);\n return { ...init, headers, signal };\n}\n\nexport async function fetchWithRetry(\n opts: RequestOptions,\n path: string,\n init?: RequestInit,\n): Promise<Response> {\n const url = `${opts.baseURL.replace(/\\/$/, \"\")}${path}`;\n const fetchInit = buildFetchInit(opts, init);\n // Only idempotent GETs are replayed. A retried POST /api/v1/keys mints a\n // second key and a retried OAuth exchange burns the authorization code;\n // in both cases the caller ends up worse off than seeing the error.\n const method = (init?.method ?? \"GET\").toUpperCase();\n const maxRetries = method === \"GET\" ? opts.maxRetries ?? DEFAULT_MAX_RETRIES : 0;\n\n let lastError: unknown;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const response = await fetch(url, fetchInit);\n if (response.ok || !RETRYABLE_STATUSES.has(response.status) || attempt === maxRetries) {\n return response;\n }\n const delay = retryDelay(attempt, response.headers.get(\"Retry-After\"));\n await new Promise((resolve) => setTimeout(resolve, delay));\n } catch (err) {\n lastError = err;\n if (attempt === maxRetries) break;\n const delay = retryDelay(attempt, null);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n throw lastError;\n}\n\n/** Serialise a JSON request body with the header fetch needs for it. */\nexport function jsonBody(value: unknown): RequestInit {\n return {\n body: JSON.stringify(value),\n headers: { \"Content-Type\": \"application/json\" },\n };\n}\n","/**\n * Account resources — the OpenRouter-compatible `/api/v1/*` face.\n *\n * Namespaces follow the wire path segments (`credits`, `generations`,\n * `apiKeys`, `activity`) and methods use a fixed verb set\n * (`list`/`get`/`create`/`update`/`delete`). Two departures, both forced:\n * `GET /api/v1/key` has no matching verb so it is `apiKeys.current()`, and\n * `/api/v1/auth/*` would read as client authentication config so the\n * namespace is `oauth`.\n *\n * Most of these endpoints require a **management key** (`mgmt_...`). The SDK\n * does not inspect key prefixes locally — it sends whatever credential it\n * was given and surfaces the server's 403 as `PermissionDeniedError`.\n */\n\nimport {\n encodePath,\n fetchWithRetry,\n jsonBody,\n parseResponse,\n type RequestOptions,\n} from \"./http.js\";\nimport type {\n ActivityParams,\n ActivityRow,\n APIKey,\n CreatedKey,\n CreateKeyParams,\n Credits,\n CurrentKey,\n ExchangedKey,\n Generation,\n ListKeysParams,\n PkcePair,\n UpdateKeyParams,\n} from \"./types/account.js\";\n\n/** Options for creating the account resources. */\nexport type AccountOptions = RequestOptions;\n\n/**\n * Unwrap the OpenRouter `{data: …}` envelope.\n *\n * Only used where the payload is entirely inside `data`. `POST /keys` and\n * `POST /auth/keys` carry fields alongside it and are parsed whole.\n */\nfunction unwrap(body: unknown): unknown {\n if (body && typeof body === \"object\" && \"data\" in body) {\n return (body as Record<string, unknown>).data;\n }\n return body;\n}\n\nfunction base64url(bytes: Uint8Array): string {\n let binary = \"\";\n for (const b of bytes) binary += String.fromCharCode(b);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/**\n * Generate an S256 PKCE `{verifier, challenge}` pair.\n *\n * Send the challenge to `/auth` when starting the browser flow, keep the\n * verifier in memory, and pass it back to `oauth.exchange()`:\n *\n * ```typescript\n * const { verifier, challenge } = await generatePkce();\n * window.location.href =\n * `https://onlist.io/auth?callback_url=${cb}` +\n * `&code_challenge=${challenge}&code_challenge_method=S256`;\n * ```\n */\nexport async function generatePkce(): Promise<PkcePair> {\n const raw = new Uint8Array(32);\n crypto.getRandomValues(raw);\n const verifier = base64url(raw);\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(verifier));\n return { verifier, challenge: base64url(new Uint8Array(digest)) };\n}\n\nconst DEFAULT_BASE_URL = \"https://onlist.io\";\n\n/**\n * Exchange a PKCE authorization code for an inference key, with no client.\n *\n * `client.oauth.exchange()` does the same thing, but constructing an\n * {@link Onlist} requires an API key — and an app running the \"Sign in with\n * Onlist\" flow does not have one yet. That is the entire point of the flow,\n * so it gets a credential-free entry point:\n *\n * ```typescript\n * const { verifier, challenge } = await generatePkce();\n * // ...user approves in the browser, your callback receives ?code=...\n * const result = await exchangeAuthCode(code, { codeVerifier: verifier });\n * const client = new Onlist({ apiKey: result.key });\n * ```\n *\n * Single-use: the code is consumed even when the verifier turns out to be\n * wrong, so a failure means restarting the browser flow.\n */\nexport async function exchangeAuthCode(\n code: string,\n opts?: { codeVerifier?: string; baseURL?: string; timeout?: number },\n): Promise<ExchangedKey> {\n const resource = new AccountOAuth({\n baseURL: opts?.baseURL ?? DEFAULT_BASE_URL,\n timeout: opts?.timeout,\n });\n return resource.exchange(code, opts?.codeVerifier ?? \"\");\n}\n\n/** Account balance. Requires a management key. */\nexport class AccountCredits {\n constructor(private readonly _opts: AccountOptions) {}\n\n /** Get lifetime credits purchased and credits used, in USD. */\n async get(): Promise<Credits> {\n const resp = await fetchWithRetry(this._opts, \"/api/v1/credits\");\n return unwrap(await parseResponse(resp)) as Credits;\n }\n}\n\n/**\n * Per-call cost and timing.\n *\n * Accepts either credential type: an inference key can look up only the\n * calls it made, a management key any call on the account.\n */\nexport class AccountGenerations {\n constructor(private readonly _opts: AccountOptions) {}\n\n /**\n * Look up one call by request ID.\n *\n * @param requestId The value of the `X-Oneapi-Request-Id` response header\n * from the original call.\n */\n async get(requestId: string): Promise<Generation> {\n const search = new URLSearchParams({ id: requestId });\n const resp = await fetchWithRetry(this._opts, `/api/v1/generation?${search}`);\n return unwrap(await parseResponse(resp)) as Generation;\n }\n}\n\n/**\n * Manage inference keys (`sk-...`). Requires a management key.\n *\n * The exception is {@link current}, which answers for whichever credential\n * made the request.\n */\nexport class AccountApiKeys {\n constructor(private readonly _opts: AccountOptions) {}\n\n /** Describe the credential this client is using. */\n async current(): Promise<CurrentKey> {\n const resp = await fetchWithRetry(this._opts, \"/api/v1/key\");\n return unwrap(await parseResponse(resp)) as CurrentKey;\n }\n\n /**\n * List inference keys.\n *\n * Pages are a fixed 100 keys and no total is returned: request\n * `offset += 100` until you get a short page.\n */\n async list(params?: ListKeysParams): Promise<APIKey[]> {\n const search = new URLSearchParams();\n search.set(\"offset\", String(params?.offset ?? 0));\n search.set(\"include_disabled\", String(params?.include_disabled ?? false));\n\n const resp = await fetchWithRetry(this._opts, `/api/v1/keys?${search}`);\n return (unwrap(await parseResponse(resp)) as APIKey[]) ?? [];\n }\n\n /**\n * Create an inference key.\n *\n * The plaintext secret is on `.key` of the result and is never retrievable\n * again.\n *\n * @param name Display name for the key. Required.\n */\n async create(name: string, params?: CreateKeyParams): Promise<CreatedKey> {\n const body: Record<string, unknown> = { name };\n if (params?.limit !== undefined) body.limit = params.limit;\n if (params?.limit_reset !== undefined) body.limit_reset = params.limit_reset;\n if (params?.expires_at !== undefined) body.expires_at = params.expires_at;\n\n const resp = await fetchWithRetry(this._opts, \"/api/v1/keys\", {\n method: \"POST\",\n ...jsonBody(body),\n });\n return (await parseResponse(resp)) as CreatedKey;\n }\n\n /** Get one inference key by its `hash`. */\n async get(hash: string): Promise<APIKey> {\n const resp = await fetchWithRetry(this._opts, `/api/v1/keys/${encodePath(hash)}`);\n return unwrap(await parseResponse(resp)) as APIKey;\n }\n\n /**\n * Update an inference key. Omitted fields are left unchanged.\n *\n * For `limit`, `limit_reset` and `expires_at`, passing `null` clears the\n * value; leaving the field out leaves it alone.\n */\n async update(hash: string, patch: UpdateKeyParams): Promise<APIKey> {\n // `!== undefined` rather than `in`: an explicit `undefined` means the\n // same thing as an absent field, and neither must reach the wire.\n const body: Record<string, unknown> = {};\n if (patch.name !== undefined) body.name = patch.name;\n if (patch.disabled !== undefined) body.disabled = patch.disabled;\n if (patch.limit !== undefined) body.limit = patch.limit;\n if (patch.limit_reset !== undefined) body.limit_reset = patch.limit_reset;\n if (patch.expires_at !== undefined) body.expires_at = patch.expires_at;\n\n const resp = await fetchWithRetry(this._opts, `/api/v1/keys/${encodePath(hash)}`, {\n method: \"PATCH\",\n ...jsonBody(body),\n });\n return unwrap(await parseResponse(resp)) as APIKey;\n }\n\n /** Delete an inference key. Resolves to `true` on success. */\n async delete(hash: string): Promise<boolean> {\n const resp = await fetchWithRetry(this._opts, `/api/v1/keys/${encodePath(hash)}`, {\n method: \"DELETE\",\n });\n const data = unwrap(await parseResponse(resp)) as { deleted?: boolean } | null;\n return Boolean(data?.deleted);\n }\n}\n\n/** Daily usage rollups. Requires a management key. */\nexport class AccountActivity {\n constructor(private readonly _opts: AccountOptions) {}\n\n /**\n * List usage grouped by day, model and provider.\n *\n * Covers the last 30 complete UTC days; today is excluded.\n */\n async list(params?: ActivityParams): Promise<ActivityRow[]> {\n const search = new URLSearchParams();\n if (params?.date) search.set(\"date\", params.date);\n if (params?.api_key_hash) search.set(\"api_key_hash\", params.api_key_hash);\n\n const qs = search.toString();\n const resp = await fetchWithRetry(this._opts, `/api/v1/activity${qs ? `?${qs}` : \"\"}`);\n return (unwrap(await parseResponse(resp)) as ActivityRow[]) ?? [];\n }\n}\n\n/**\n * Sign in with Onlist — the PKCE authorization-code exchange.\n *\n * Only the exchange lives here. The authorization step itself happens in the\n * user's browser at `https://onlist.io/auth`; there is no SDK call for it,\n * because the SDK has no session to authorize with.\n */\nexport class AccountOAuth {\n constructor(private readonly _opts: AccountOptions) {}\n\n /**\n * Exchange an authorization code for a new inference key.\n *\n * Unauthenticated, and single-use: the code is consumed even when the\n * verifier turns out to be wrong, so a failure means restarting the\n * browser flow.\n *\n * @param code The `code` query parameter from the callback URL.\n * @param codeVerifier The verifier from {@link generatePkce}. Required\n * whenever the authorization request carried a challenge.\n */\n async exchange(code: string, codeVerifier = \"\"): Promise<ExchangedKey> {\n const resp = await fetchWithRetry(this._opts, \"/api/v1/auth/keys\", {\n method: \"POST\",\n ...jsonBody({ code, code_verifier: codeVerifier }),\n });\n return (await parseResponse(resp)) as ExchangedKey;\n }\n}\n","import {\n encodePath,\n fetchWithRetry,\n parseResponse,\n type RequestOptions,\n} from \"./http.js\";\nimport type { ModelDetail, ModelListResponse } from \"./types/model.js\";\nimport type { ProviderDetail, ProviderListResponse } from \"./types/provider.js\";\nimport type {\n ModelRankingsResponse,\n ModelRankingsParams,\n AppRankingsResponse,\n AppRankingsParams,\n} from \"./types/rankings.js\";\n\n/** Options for creating a Marketplace client. */\nexport type MarketplaceOptions = RequestOptions;\n\n/** Access to marketplace model data. */\nexport class MarketplaceModels {\n constructor(private readonly _opts: MarketplaceOptions) {}\n\n /** List models in the marketplace catalog. */\n async list(params?: { limit?: number; offset?: number; q?: string }): Promise<ModelListResponse> {\n const search = new URLSearchParams();\n search.set(\"limit\", String(params?.limit ?? 20));\n search.set(\"offset\", String(params?.offset ?? 0));\n if (params?.q) search.set(\"q\", params.q);\n\n const resp = await fetchWithRetry(this._opts, `/api/mkt/models?${search}`);\n return (await parseResponse(resp)) as ModelListResponse;\n }\n\n /** Get detailed info for a specific model, including provider offers. */\n async get(modelId: string): Promise<ModelDetail> {\n const resp = await fetchWithRetry(this._opts, `/api/mkt/models/${encodePath(modelId)}`);\n let data = (await parseResponse(resp)) as Record<string, unknown>;\n if (data && typeof data === \"object\" && \"data\" in data) {\n data = data.data as Record<string, unknown>;\n }\n return data as unknown as ModelDetail;\n }\n}\n\n/** Access to marketplace provider data. */\nexport class MarketplaceProviders {\n constructor(private readonly _opts: MarketplaceOptions) {}\n\n /** List providers on the marketplace. */\n async list(params?: { sort?: string; q?: string }): Promise<ProviderListResponse> {\n const search = new URLSearchParams();\n if (params?.sort) search.set(\"sort\", params.sort);\n if (params?.q) search.set(\"q\", params.q);\n\n const qs = search.toString();\n const resp = await fetchWithRetry(this._opts, `/api/mkt/providers${qs ? `?${qs}` : \"\"}`);\n return (await parseResponse(resp)) as ProviderListResponse;\n }\n\n /** Get detailed info for a specific provider. */\n async get(slug: string): Promise<ProviderDetail> {\n const resp = await fetchWithRetry(this._opts, `/api/mkt/provider/${encodePath(slug)}`);\n let data = (await parseResponse(resp)) as Record<string, unknown>;\n if (data && typeof data === \"object\" && \"data\" in data) {\n data = data.data as Record<string, unknown>;\n }\n return data as unknown as ProviderDetail;\n }\n}\n\n/** Access to marketplace rankings (models and apps). */\nexport class MarketplaceRankings {\n constructor(private readonly _opts: MarketplaceOptions) {}\n\n /** Get the model usage leaderboard and chart series. */\n async models(params?: ModelRankingsParams): Promise<ModelRankingsResponse> {\n const search = new URLSearchParams();\n if (params?.sort) search.set(\"sort\", params.sort);\n if (params?.window) search.set(\"window\", params.window);\n if (params?.limit != null) search.set(\"limit\", String(params.limit));\n if (params?.offset != null) search.set(\"offset\", String(params.offset));\n\n const qs = search.toString();\n const resp = await fetchWithRetry(this._opts, `/api/mkt/rankings/models${qs ? `?${qs}` : \"\"}`);\n return (await parseResponse(resp)) as ModelRankingsResponse;\n }\n\n /** Get the app rankings list. */\n async apps(params?: AppRankingsParams): Promise<AppRankingsResponse> {\n const search = new URLSearchParams();\n if (params?.sort) search.set(\"sort\", params.sort);\n if (params?.window) search.set(\"window\", params.window);\n if (params?.category) search.set(\"category\", params.category);\n if (params?.subcategory) search.set(\"subcategory\", params.subcategory);\n if (params?.page != null) search.set(\"page\", String(params.page));\n if (params?.limit != null) search.set(\"limit\", String(params.limit));\n\n const qs = search.toString();\n const resp = await fetchWithRetry(this._opts, `/api/mkt/apps${qs ? `?${qs}` : \"\"}`);\n return (await parseResponse(resp)) as AppRankingsResponse;\n }\n}\n\n/** Client for the Onlist marketplace public API. */\nexport class Marketplace {\n /** Browse and search models. */\n readonly models: MarketplaceModels;\n /** Browse and search providers. */\n readonly providers: MarketplaceProviders;\n /** Model and app usage rankings. */\n readonly rankings: MarketplaceRankings;\n\n constructor(opts: MarketplaceOptions) {\n this.models = new MarketplaceModels(opts);\n this.providers = new MarketplaceProviders(opts);\n this.rankings = new MarketplaceRankings(opts);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAAmB;;;ACCZ,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,WAAN,cAAuB,YAAY;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,SACA,MAOA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,KAAK;AACnB,SAAK,OAAO,KAAK,QAAQ;AACzB,SAAK,OAAO,KAAK,QAAQ;AACzB,SAAK,QAAQ,KAAK,SAAS;AAC3B,SAAK,OAAO,KAAK,QAAQ;AAAA,EAC3B;AACF;AAGO,IAAM,sBAAN,cAAkC,SAAS;AAAA,EAChD,YAAY,UAAU,mBAAmB,MAA2D;AAClG,UAAM,SAAS,EAAE,QAAQ,KAAK,GAAG,KAAK,CAAC;AACvC,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,2BAAN,cAAuC,SAAS;AAAA,EACrD,YAAY,UAAU,wBAAwB,MAA2D;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@
1
1
  import OpenAI, { ClientOptions } from 'openai';
2
2
 
3
+ /** Shared options for the REST resources (marketplace and account). */
4
+ interface RequestOptions {
5
+ apiKey?: string | null;
6
+ baseURL: string;
7
+ timeout?: number;
8
+ /** Maximum retry attempts for failed requests. Defaults to 2. */
9
+ maxRetries?: number;
10
+ }
11
+
12
+ /**
13
+ * Response types for the account API (`/api/v1/*`).
14
+ *
15
+ * Field names mirror the wire format one-for-one, which is OpenRouter's, so
16
+ * code written against OpenRouter's responses reads the same fields here.
17
+ */
18
+ /**
19
+ * The deprecated per-key rate limit descriptor on {@link CurrentKey}.
20
+ *
21
+ * Onlist has no per-key request-rate limit — only spend budgets — so
22
+ * `requests` is always `-1`. Do not use it to drive client-side throttling.
23
+ */
24
+ interface RateLimit {
25
+ requests: number;
26
+ interval: string;
27
+ note: string;
28
+ }
29
+ /**
30
+ * An inference key (`sk-...`) as returned by the `apiKeys` resource.
31
+ *
32
+ * `limit`, `limit_remaining` and `limit_reset` move together: either all
33
+ * three are set, or all three are `null` (no spend budget). Amounts are USD.
34
+ * `created_at` / `expires_at` are RFC 3339 UTC strings, or `null` for
35
+ * "never".
36
+ */
37
+ interface APIKey {
38
+ hash: string;
39
+ name: string;
40
+ label: string;
41
+ disabled: boolean;
42
+ limit: number | null;
43
+ limit_remaining: number | null;
44
+ limit_reset: string | null;
45
+ include_byok_in_limit: boolean;
46
+ usage: number;
47
+ usage_daily: number;
48
+ usage_weekly: number;
49
+ usage_monthly: number;
50
+ byok_usage: number;
51
+ byok_usage_daily: number;
52
+ byok_usage_weekly: number;
53
+ byok_usage_monthly: number;
54
+ created_at: string | null;
55
+ updated_at: string | null;
56
+ expires_at: string | null;
57
+ external_user: string | null;
58
+ creator_user_id: string | null;
59
+ workspace_id: string | null;
60
+ }
61
+ /**
62
+ * The credential used for the request, from `apiKeys.current()`.
63
+ *
64
+ * Every field is optional because the endpoint answers for both credential
65
+ * types and they carry different information: a management key has no usage
66
+ * and no budget (reporting `0` would read as "an inference key that has
67
+ * never spent"), so those fields are simply absent from its projection.
68
+ * Branch on `is_management_key`.
69
+ */
70
+ interface CurrentKey extends Partial<APIKey> {
71
+ is_free_tier?: boolean;
72
+ is_management_key?: boolean;
73
+ is_provisioning_key?: boolean;
74
+ rate_limit?: RateLimit;
75
+ }
76
+ /**
77
+ * The result of `apiKeys.create()`.
78
+ *
79
+ * `key` is the full secret in plaintext and is returned **only here, only
80
+ * once** — the server keeps a hash. Store it before discarding this object.
81
+ * `data` is the same key object later reads return.
82
+ */
83
+ interface CreatedKey {
84
+ key: string;
85
+ data: APIKey;
86
+ }
87
+ /** Parameters for `apiKeys.create()`. */
88
+ interface CreateKeyParams {
89
+ /** Spend budget in USD. Omit for no budget. */
90
+ limit?: number;
91
+ /** `"daily"`, `"weekly"`, or omitted for a lifetime total. `"monthly"` is rejected. */
92
+ limit_reset?: string;
93
+ /** Expiry as a Unix timestamp. Omit to never expire. */
94
+ expires_at?: number;
95
+ }
96
+ /**
97
+ * Patch for `apiKeys.update()`.
98
+ *
99
+ * Three states: an omitted (or `undefined`) field is left unchanged, and an
100
+ * explicit `null` clears the value. `name` and `disabled` therefore accept
101
+ * no `null` — the server reads `{"name": null}` as an empty name (400) and
102
+ * `{"disabled": null}` as `false`, which would silently re-enable a key you
103
+ * only meant to leave alone.
104
+ */
105
+ interface UpdateKeyParams {
106
+ name?: string;
107
+ disabled?: boolean;
108
+ limit?: number | null;
109
+ limit_reset?: string | null;
110
+ expires_at?: number | null;
111
+ }
112
+ /** Parameters for `apiKeys.list()`. */
113
+ interface ListKeysParams {
114
+ /** Number of keys to skip. Pages are a fixed 100 and no total is returned. */
115
+ offset?: number;
116
+ /** Include disabled keys in the result. */
117
+ include_disabled?: boolean;
118
+ }
119
+ /**
120
+ * Account balance, in USD.
121
+ *
122
+ * Remaining balance is `total_credits - total_usage`: the endpoint reports
123
+ * lifetime totals rather than a single "balance" number, matching
124
+ * OpenRouter.
125
+ */
126
+ interface Credits {
127
+ total_credits: number;
128
+ total_usage: number;
129
+ }
130
+ /**
131
+ * Cost and timing for a single completed call, from `generations.get()`.
132
+ *
133
+ * Fields Onlist has no data for are `null` rather than `0`: `upstream_id`,
134
+ * `http_referer`, `user_agent`, `origin`, `api_type`, `cache_discount` and
135
+ * `native_tokens_reasoning`. For reconciliation, "not measured" and
136
+ * "measured as zero" are different statements.
137
+ *
138
+ * `latency` is time-to-first-token in milliseconds and is `null` for
139
+ * non-streamed calls, which never measure it. `generation_time` is total
140
+ * wall time in milliseconds. `total_cost` and `usage` are the same USD
141
+ * amount under both of OpenRouter's names.
142
+ */
143
+ interface Generation {
144
+ id: string;
145
+ model: string;
146
+ provider_name: string | null;
147
+ streamed: boolean;
148
+ latency: number | null;
149
+ generation_time: number;
150
+ created_at: string | null;
151
+ tokens_prompt: number;
152
+ tokens_completion: number;
153
+ native_tokens_prompt: number;
154
+ native_tokens_completion: number;
155
+ native_tokens_cached: number | null;
156
+ native_tokens_reasoning: number | null;
157
+ total_cost: number;
158
+ usage: number;
159
+ cache_discount: number | null;
160
+ finish_reason: string | null;
161
+ native_finish_reason: string | null;
162
+ is_byok: boolean;
163
+ upstream_id: string | null;
164
+ http_referer: string | null;
165
+ user_agent: string | null;
166
+ origin: string | null;
167
+ api_type: string | null;
168
+ }
169
+ /**
170
+ * One day × model × provider bucket from `activity.list()`.
171
+ *
172
+ * `date` is a `YYYY-MM-DD` UTC day and `usage` is USD. Only complete days
173
+ * appear — today is still accumulating, and this endpoint exists for
174
+ * reconciliation.
175
+ */
176
+ interface ActivityRow {
177
+ date: string;
178
+ model: string;
179
+ model_permaslug: string;
180
+ endpoint_id: string;
181
+ provider_name: string | null;
182
+ usage: number;
183
+ byok_usage_inference: number;
184
+ requests: number;
185
+ prompt_tokens: number;
186
+ completion_tokens: number;
187
+ reasoning_tokens: number;
188
+ }
189
+ /** Parameters for `activity.list()`. */
190
+ interface ActivityParams {
191
+ /** Restrict to one `YYYY-MM-DD` UTC day inside the 30-day window. */
192
+ date?: string;
193
+ /** Restrict to one inference key. A hash from another account yields an empty list. */
194
+ api_key_hash?: string;
195
+ }
196
+ /**
197
+ * The result of `oauth.exchange()`.
198
+ *
199
+ * `key` is a new inference key in plaintext, returned once. `user_id` is
200
+ * always `null` on Onlist: on OpenRouter it carries the calling
201
+ * application's own external user identifier, which Onlist has no concept
202
+ * of.
203
+ */
204
+ interface ExchangedKey {
205
+ key: string;
206
+ user_id: string | null;
207
+ }
208
+ /** An S256 PKCE pair from `generatePkce()`. */
209
+ interface PkcePair {
210
+ /** Kept in memory and passed back to `oauth.exchange()`. */
211
+ verifier: string;
212
+ /** Sent to `/auth` when opening the browser flow. */
213
+ challenge: string;
214
+ }
215
+
216
+ /**
217
+ * Account resources — the OpenRouter-compatible `/api/v1/*` face.
218
+ *
219
+ * Namespaces follow the wire path segments (`credits`, `generations`,
220
+ * `apiKeys`, `activity`) and methods use a fixed verb set
221
+ * (`list`/`get`/`create`/`update`/`delete`). Two departures, both forced:
222
+ * `GET /api/v1/key` has no matching verb so it is `apiKeys.current()`, and
223
+ * `/api/v1/auth/*` would read as client authentication config so the
224
+ * namespace is `oauth`.
225
+ *
226
+ * Most of these endpoints require a **management key** (`mgmt_...`). The SDK
227
+ * does not inspect key prefixes locally — it sends whatever credential it
228
+ * was given and surfaces the server's 403 as `PermissionDeniedError`.
229
+ */
230
+
231
+ /** Options for creating the account resources. */
232
+ type AccountOptions = RequestOptions;
233
+ /**
234
+ * Generate an S256 PKCE `{verifier, challenge}` pair.
235
+ *
236
+ * Send the challenge to `/auth` when starting the browser flow, keep the
237
+ * verifier in memory, and pass it back to `oauth.exchange()`:
238
+ *
239
+ * ```typescript
240
+ * const { verifier, challenge } = await generatePkce();
241
+ * window.location.href =
242
+ * `https://onlist.io/auth?callback_url=${cb}` +
243
+ * `&code_challenge=${challenge}&code_challenge_method=S256`;
244
+ * ```
245
+ */
246
+ declare function generatePkce(): Promise<PkcePair>;
247
+ /**
248
+ * Exchange a PKCE authorization code for an inference key, with no client.
249
+ *
250
+ * `client.oauth.exchange()` does the same thing, but constructing an
251
+ * {@link Onlist} requires an API key — and an app running the "Sign in with
252
+ * Onlist" flow does not have one yet. That is the entire point of the flow,
253
+ * so it gets a credential-free entry point:
254
+ *
255
+ * ```typescript
256
+ * const { verifier, challenge } = await generatePkce();
257
+ * // ...user approves in the browser, your callback receives ?code=...
258
+ * const result = await exchangeAuthCode(code, { codeVerifier: verifier });
259
+ * const client = new Onlist({ apiKey: result.key });
260
+ * ```
261
+ *
262
+ * Single-use: the code is consumed even when the verifier turns out to be
263
+ * wrong, so a failure means restarting the browser flow.
264
+ */
265
+ declare function exchangeAuthCode(code: string, opts?: {
266
+ codeVerifier?: string;
267
+ baseURL?: string;
268
+ timeout?: number;
269
+ }): Promise<ExchangedKey>;
270
+ /** Account balance. Requires a management key. */
271
+ declare class AccountCredits {
272
+ private readonly _opts;
273
+ constructor(_opts: AccountOptions);
274
+ /** Get lifetime credits purchased and credits used, in USD. */
275
+ get(): Promise<Credits>;
276
+ }
277
+ /**
278
+ * Per-call cost and timing.
279
+ *
280
+ * Accepts either credential type: an inference key can look up only the
281
+ * calls it made, a management key any call on the account.
282
+ */
283
+ declare class AccountGenerations {
284
+ private readonly _opts;
285
+ constructor(_opts: AccountOptions);
286
+ /**
287
+ * Look up one call by request ID.
288
+ *
289
+ * @param requestId The value of the `X-Oneapi-Request-Id` response header
290
+ * from the original call.
291
+ */
292
+ get(requestId: string): Promise<Generation>;
293
+ }
294
+ /**
295
+ * Manage inference keys (`sk-...`). Requires a management key.
296
+ *
297
+ * The exception is {@link current}, which answers for whichever credential
298
+ * made the request.
299
+ */
300
+ declare class AccountApiKeys {
301
+ private readonly _opts;
302
+ constructor(_opts: AccountOptions);
303
+ /** Describe the credential this client is using. */
304
+ current(): Promise<CurrentKey>;
305
+ /**
306
+ * List inference keys.
307
+ *
308
+ * Pages are a fixed 100 keys and no total is returned: request
309
+ * `offset += 100` until you get a short page.
310
+ */
311
+ list(params?: ListKeysParams): Promise<APIKey[]>;
312
+ /**
313
+ * Create an inference key.
314
+ *
315
+ * The plaintext secret is on `.key` of the result and is never retrievable
316
+ * again.
317
+ *
318
+ * @param name Display name for the key. Required.
319
+ */
320
+ create(name: string, params?: CreateKeyParams): Promise<CreatedKey>;
321
+ /** Get one inference key by its `hash`. */
322
+ get(hash: string): Promise<APIKey>;
323
+ /**
324
+ * Update an inference key. Omitted fields are left unchanged.
325
+ *
326
+ * For `limit`, `limit_reset` and `expires_at`, passing `null` clears the
327
+ * value; leaving the field out leaves it alone.
328
+ */
329
+ update(hash: string, patch: UpdateKeyParams): Promise<APIKey>;
330
+ /** Delete an inference key. Resolves to `true` on success. */
331
+ delete(hash: string): Promise<boolean>;
332
+ }
333
+ /** Daily usage rollups. Requires a management key. */
334
+ declare class AccountActivity {
335
+ private readonly _opts;
336
+ constructor(_opts: AccountOptions);
337
+ /**
338
+ * List usage grouped by day, model and provider.
339
+ *
340
+ * Covers the last 30 complete UTC days; today is excluded.
341
+ */
342
+ list(params?: ActivityParams): Promise<ActivityRow[]>;
343
+ }
344
+ /**
345
+ * Sign in with Onlist — the PKCE authorization-code exchange.
346
+ *
347
+ * Only the exchange lives here. The authorization step itself happens in the
348
+ * user's browser at `https://onlist.io/auth`; there is no SDK call for it,
349
+ * because the SDK has no session to authorize with.
350
+ */
351
+ declare class AccountOAuth {
352
+ private readonly _opts;
353
+ constructor(_opts: AccountOptions);
354
+ /**
355
+ * Exchange an authorization code for a new inference key.
356
+ *
357
+ * Unauthenticated, and single-use: the code is consumed even when the
358
+ * verifier turns out to be wrong, so a failure means restarting the
359
+ * browser flow.
360
+ *
361
+ * @param code The `code` query parameter from the callback URL.
362
+ * @param codeVerifier The verifier from {@link generatePkce}. Required
363
+ * whenever the authorization request carried a challenge.
364
+ */
365
+ exchange(code: string, codeVerifier?: string): Promise<ExchangedKey>;
366
+ }
367
+
3
368
  /** Model pricing in USD per million tokens. */
4
369
  interface Pricing {
5
370
  prompt: string;
@@ -164,13 +529,7 @@ interface AppRankingsParams {
164
529
  }
165
530
 
166
531
  /** Options for creating a Marketplace client. */
167
- interface MarketplaceOptions {
168
- apiKey?: string | null;
169
- baseURL: string;
170
- timeout?: number;
171
- /** Maximum retry attempts for failed requests. Defaults to 2. */
172
- maxRetries?: number;
173
- }
532
+ type MarketplaceOptions = RequestOptions;
174
533
  /** Access to marketplace model data. */
175
534
  declare class MarketplaceModels {
176
535
  private readonly _opts;
@@ -220,15 +579,32 @@ declare class Marketplace {
220
579
  interface OnlistOptions extends Omit<ClientOptions, "apiKey" | "baseURL"> {
221
580
  /** API key. Falls back to ONLIST_API_KEY then OPENAI_API_KEY env vars. */
222
581
  apiKey?: string | null;
582
+ /**
583
+ * Management key (`mgmt_...`) for the account API. Falls back to
584
+ * ONLIST_MANAGEMENT_KEY, then to the API key.
585
+ */
586
+ managementKey?: string | null;
223
587
  /** Base URL for the API. Defaults to https://onlist.io/v1. */
224
588
  baseURL?: string | null;
225
- /** Maximum retry attempts for marketplace API calls. Defaults to 2. */
589
+ /** Maximum retry attempts for marketplace and account API calls. Defaults to 2. */
226
590
  maxRetries?: number;
227
591
  }
228
- /** Onlist API client, extending the OpenAI SDK with marketplace features. */
592
+ /** Onlist API client, extending the OpenAI SDK with marketplace and account features. */
229
593
  declare class Onlist extends OpenAI {
230
594
  /** Access to marketplace data: models, providers, and rankings. */
231
595
  readonly marketplace: Marketplace;
596
+ /** Account balance. */
597
+ readonly credits: AccountCredits;
598
+ /** Cost and timing for individual calls. */
599
+ readonly generations: AccountGenerations;
600
+ /** Inference key management. */
601
+ readonly apiKeys: AccountApiKeys;
602
+ /** Daily usage rollups. */
603
+ readonly activity: AccountActivity;
604
+ /** Sign in with Onlist — the PKCE code exchange. */
605
+ readonly oauth: AccountOAuth;
606
+ /** The credential the account API is using. */
607
+ readonly managementKey: string | undefined;
232
608
  constructor(opts?: OnlistOptions);
233
609
  }
234
610
 
@@ -271,6 +647,20 @@ declare class ProviderError extends APIError {
271
647
  declare class NotFoundError extends APIError {
272
648
  constructor(message?: string, opts?: Partial<ConstructorParameters<typeof APIError>[1]>);
273
649
  }
650
+ /** Error thrown when the request is malformed or its parameters are rejected. */
651
+ declare class BadRequestError extends APIError {
652
+ constructor(message?: string, opts?: Partial<ConstructorParameters<typeof APIError>[1]>);
653
+ }
654
+ /**
655
+ * Error thrown when the credential is valid but not allowed here.
656
+ *
657
+ * Most commonly: an inference key (`sk-...`) was used on an endpoint that
658
+ * only accepts a management key (`mgmt_...`). The server's message is passed
659
+ * through unchanged.
660
+ */
661
+ declare class PermissionDeniedError extends APIError {
662
+ constructor(message?: string, opts?: Partial<ConstructorParameters<typeof APIError>[1]>);
663
+ }
274
664
 
275
665
  /** Maximum price limits per token type (USD per million tokens). */
276
666
  interface MaxPrice {
@@ -295,6 +685,6 @@ declare module "openai/resources/chat/completions/completions" {
295
685
  }
296
686
  }
297
687
 
298
- declare const VERSION = "0.2.0";
688
+ declare const VERSION = "0.3.0";
299
689
 
300
- export { APIError, type AppRanking, type AppRankingsParams, type AppRankingsResponse, type Architecture, AuthenticationError, InsufficientBalanceError, Marketplace, MarketplaceModels, type MarketplaceOptions, MarketplaceProviders, MarketplaceRankings, type MaxPrice, type Model, type ModelDetail, type ModelListResponse, type ModelRanking, type ModelRankingsParams, type ModelRankingsResponse, type ModelSeriesPoint, NotFoundError, Onlist, OnlistError, type OnlistOptions, type Pricing, type Provider, type ProviderDetail, ProviderError, type ProviderListResponse, type ProviderOffer, type ProviderRouting, RateLimitError, type TopProvider, VERSION };
690
+ export { APIError, type APIKey, AccountActivity, AccountApiKeys, AccountCredits, AccountGenerations, AccountOAuth, type AccountOptions, type ActivityParams, type ActivityRow, type AppRanking, type AppRankingsParams, type AppRankingsResponse, type Architecture, AuthenticationError, BadRequestError, type CreateKeyParams, type CreatedKey, type Credits, type CurrentKey, type ExchangedKey, type Generation, InsufficientBalanceError, type ListKeysParams, Marketplace, MarketplaceModels, type MarketplaceOptions, MarketplaceProviders, MarketplaceRankings, type MaxPrice, type Model, type ModelDetail, type ModelListResponse, type ModelRanking, type ModelRankingsParams, type ModelRankingsResponse, type ModelSeriesPoint, NotFoundError, Onlist, OnlistError, type OnlistOptions, PermissionDeniedError, type PkcePair, type Pricing, type Provider, type ProviderDetail, ProviderError, type ProviderListResponse, type ProviderOffer, type ProviderRouting, type RateLimit, RateLimitError, type TopProvider, type UpdateKeyParams, VERSION, exchangeAuthCode, generatePkce };