@openrouter/sdk 1.5.57 → 1.5.59

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.
package/README.md CHANGED
@@ -70,22 +70,24 @@ import { OpenRouter } from "@openrouter/sdk";
70
70
  const openRouter = new OpenRouter();
71
71
 
72
72
  const result = await openRouter.chat.send({
73
- messages: [
74
- {
75
- role: "user",
76
- content: "Hello, how are you?",
73
+ chatRequest: {
74
+ messages: [
75
+ {
76
+ role: "user",
77
+ content: "Hello, how are you?",
78
+ },
79
+ ],
80
+ model: "openai/gpt-5",
81
+ provider: {
82
+ zdr: true,
83
+ sort: "price",
77
84
  },
78
- ],
79
- model: "openai/gpt-5",
80
- provider: {
81
- zdr: true,
82
- sort: "price",
85
+ stream: true,
83
86
  },
84
- stream: true
85
87
  });
86
88
 
87
89
  for await (const chunk of result) {
88
- console.log(chunk.choices[0].delta.content)
90
+ console.log(chunk.choices[0]?.delta.content);
89
91
  }
90
92
 
91
93
  ```
@@ -8,11 +8,14 @@ import { SDKValidationError } from "../models/errors/sdkvalidationerror.js";
8
8
  import * as operations from "../models/operations/index.js";
9
9
  import { APIPromise } from "../types/async.js";
10
10
  import { Result } from "../types/fp.js";
11
+ import { PageIterator } from "../types/operations.js";
11
12
  /**
12
13
  * List API keys
13
14
  *
14
15
  * @remarks
15
16
  * List all API keys for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.
16
17
  */
17
- export declare function apiKeysList(client: OpenRouterCore, request?: operations.ListRequest | undefined, options?: RequestOptions): APIPromise<Result<operations.ListResponse, errors.BadRequestResponseError | errors.UnauthorizedResponseError | errors.ForbiddenResponseError | errors.NotFoundResponseError | errors.TooManyRequestsResponseError | errors.InternalServerResponseError | OpenRouterError | ResponseValidationError | ConnectionError | RequestAbortedError | RequestTimeoutError | InvalidRequestError | UnexpectedClientError | SDKValidationError>>;
18
+ export declare function apiKeysList(client: OpenRouterCore, request?: operations.ListRequest | undefined, options?: RequestOptions): APIPromise<PageIterator<Result<operations.ListResponse, errors.BadRequestResponseError | errors.UnauthorizedResponseError | errors.ForbiddenResponseError | errors.NotFoundResponseError | errors.TooManyRequestsResponseError | errors.InternalServerResponseError | OpenRouterError | ResponseValidationError | ConnectionError | RequestAbortedError | RequestTimeoutError | InvalidRequestError | UnexpectedClientError | SDKValidationError>, {
19
+ offset: number;
20
+ }>>;
18
21
  //# sourceMappingURL=apiKeysList.d.ts.map
@@ -12,6 +12,7 @@ import { pathToFunc } from "../lib/url.js";
12
12
  import { BadRequestResponseError$inboundSchema as errors_BadRequestResponseError$inboundSchema } from "../models/errors/badrequestresponseerror.js"; import { ForbiddenResponseError$inboundSchema as errors_ForbiddenResponseError$inboundSchema } from "../models/errors/forbiddenresponseerror.js"; import { InternalServerResponseError$inboundSchema as errors_InternalServerResponseError$inboundSchema } from "../models/errors/internalserverresponseerror.js"; import { NotFoundResponseError$inboundSchema as errors_NotFoundResponseError$inboundSchema } from "../models/errors/notfoundresponseerror.js"; import { TooManyRequestsResponseError$inboundSchema as errors_TooManyRequestsResponseError$inboundSchema } from "../models/errors/toomanyrequestsresponseerror.js"; import { UnauthorizedResponseError$inboundSchema as errors_UnauthorizedResponseError$inboundSchema } from "../models/errors/unauthorizedresponseerror.js";
13
13
  import { ListRequest$outboundSchema as operations_ListRequest$outboundSchema, ListResponse$inboundSchema as operations_ListResponse$inboundSchema } from "../models/operations/list.js";
14
14
  import { APIPromise } from "../types/async.js";
15
+ import { createPageIterator, haltIterator, } from "../types/operations.js";
15
16
  /**
16
17
  * List API keys
17
18
  *
@@ -24,7 +25,7 @@ export function apiKeysList(client, request, options) {
24
25
  async function $do(client, request, options) {
25
26
  const parsed = safeParse(request, (value) => operations_ListRequest$outboundSchema.optional().parse(value), "Input validation failed");
26
27
  if (!parsed.ok) {
27
- return [parsed, { status: "invalid" }];
28
+ return [haltIterator(parsed), { status: "invalid" }];
28
29
  }
29
30
  const payload = parsed.value;
30
31
  const body = null;
@@ -78,7 +79,7 @@ async function $do(client, request, options) {
78
79
  timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1,
79
80
  }, options);
80
81
  if (!requestRes.ok) {
81
- return [requestRes, { status: "invalid" }];
82
+ return [haltIterator(requestRes), { status: "invalid" }];
82
83
  }
83
84
  const req = requestRes.value;
84
85
  const doResult = await client._do(req, {
@@ -88,16 +89,41 @@ async function $do(client, request, options) {
88
89
  retryCodes: context.retryCodes,
89
90
  });
90
91
  if (!doResult.ok) {
91
- return [doResult, { status: "request-error", request: req }];
92
+ return [haltIterator(doResult), { status: "request-error", request: req }];
92
93
  }
93
94
  const response = doResult.value;
94
95
  const responseFields = {
95
96
  HttpMeta: { Response: response, Request: req },
96
97
  };
97
- const [result] = await M.match(M.json(200, operations_ListResponse$inboundSchema), M.jsonErr(400, errors_BadRequestResponseError$inboundSchema), M.jsonErr(401, errors_UnauthorizedResponseError$inboundSchema), M.jsonErr(403, errors_ForbiddenResponseError$inboundSchema), M.jsonErr(404, errors_NotFoundResponseError$inboundSchema), M.jsonErr(429, errors_TooManyRequestsResponseError$inboundSchema), M.jsonErr(500, errors_InternalServerResponseError$inboundSchema), M.fail("4XX"), M.fail("5XX"))(response, req, { extraFields: responseFields });
98
+ const [result, raw] = await M.match(M.json(200, operations_ListResponse$inboundSchema, { key: "Result" }), M.jsonErr(400, errors_BadRequestResponseError$inboundSchema), M.jsonErr(401, errors_UnauthorizedResponseError$inboundSchema), M.jsonErr(403, errors_ForbiddenResponseError$inboundSchema), M.jsonErr(404, errors_NotFoundResponseError$inboundSchema), M.jsonErr(429, errors_TooManyRequestsResponseError$inboundSchema), M.jsonErr(500, errors_InternalServerResponseError$inboundSchema), M.fail("4XX"), M.fail("5XX"))(response, req, { extraFields: responseFields });
98
99
  if (!result.ok) {
99
- return [result, { status: "complete", request: req, response }];
100
+ return [haltIterator(result), {
101
+ status: "complete",
102
+ request: req,
103
+ response,
104
+ }];
100
105
  }
101
- return [result, { status: "complete", request: req, response }];
106
+ const nextFunc = (responseData) => {
107
+ const offset = request?.offset ?? 0;
108
+ if (!responseData) {
109
+ return { next: () => null };
110
+ }
111
+ const results = responseData.data;
112
+ if (!Array.isArray(results) || !results.length) {
113
+ return { next: () => null };
114
+ }
115
+ const nextOffset = offset + results.length;
116
+ const nextVal = () => apiKeysList(client, {
117
+ ...request,
118
+ offset: nextOffset,
119
+ }, options);
120
+ return { next: nextVal, "~next": { offset: nextOffset } };
121
+ };
122
+ const page = { ...result, ...nextFunc(raw) };
123
+ return [{ ...page, ...createPageIterator(page, (v) => !v.ok) }, {
124
+ status: "complete",
125
+ request: req,
126
+ response,
127
+ }];
102
128
  }
103
129
  //# sourceMappingURL=apiKeysList.js.map
@@ -1,3 +1,3 @@
1
1
  import type { Hooks } from './types.js';
2
- export declare function initHooks(_hooks: Hooks): void;
2
+ export declare function initHooks(hooks: Hooks): void;
3
3
  //# sourceMappingURL=registration.d.ts.map
@@ -1,11 +1,18 @@
1
+ import { SignalTimeoutHook } from './signal-hooks.js';
1
2
  /*
2
3
  * This file is only ever generated once on the first generation and then is free to be modified.
3
4
  * Any hooks you wish to add should be registered in the initHooks function. Feel free to define them
4
5
  * in this file or in separate files in the hooks folder.
5
6
  */
6
- export function initHooks(_hooks) {
7
+ export function initHooks(hooks) {
7
8
  // Add hooks by calling hooks.register{ClientInit/BeforeCreateRequest/BeforeRequest/AfterSuccess/AfterError}Hook
8
9
  // with an instance of a hook that implements that specific Hook interface
9
10
  // Hooks are registered per SDK instance, and are valid for the lifetime of the SDK instance
11
+ // Compose timeoutMs with caller signals (#1123) and keep aborts working
12
+ // after GC in Node (#1315).
13
+ const signalTimeoutHook = new SignalTimeoutHook();
14
+ hooks.registerSDKInitHook(signalTimeoutHook);
15
+ hooks.registerBeforeCreateRequestHook(signalTimeoutHook);
16
+ hooks.registerBeforeRequestHook(signalTimeoutHook);
10
17
  }
11
18
  //# sourceMappingURL=registration.js.map
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Hooks that fix two gaps in the generated request pipeline without editing
3
+ * generated files:
4
+ *
5
+ * 1. Timeouts and signals compose (#1123). The generated `_createRequest`
6
+ * skips `timeoutMs` whenever the caller passes `signal`. This hook restores
7
+ * the timeout on the hook context so `_do` combines it with the signal and
8
+ * the request aborts on whichever fires first. The timeout covers the whole
9
+ * attempt, including reading a streamed response body, the same as for
10
+ * calls made without a signal.
11
+ *
12
+ * 2. Aborts survive garbage collection in Node (#1315). The generated
13
+ * `HTTPClient` calls `fetch(request)` with only a `Request`. In undici, a
14
+ * `Request`'s signal follows its source signal through a weak reference, so
15
+ * after a GC an abort can stop reaching the network
16
+ * (https://github.com/nodejs/undici/issues/4068). Passing the caller's
17
+ * signal again in the `fetch` init avoids this. The hook links each
18
+ * outgoing `Request` to a signal built directly from the caller's signal
19
+ * and the per-attempt timeout, and a wrapped fetcher passes it as `init`.
20
+ * This part only runs on Node: other runtimes don't have the bug, and Bun
21
+ * mishandles a `Request` combined with an `init` argument.
22
+ */
23
+ import type { SDKOptions } from "../lib/config.js";
24
+ import type { RequestInput } from "../lib/http.js";
25
+ import type { BeforeCreateRequestContext, BeforeCreateRequestHook, BeforeRequestContext, BeforeRequestHook, SDKInitHook } from "./types.js";
26
+ /** True on Node.js, false on Bun, Deno, browsers and other runtimes. */
27
+ export declare function isNodeRuntime(): boolean;
28
+ export type SignalTimeoutHookOptions = {
29
+ /**
30
+ * Whether to apply the abort-after-GC fix (#1315). Defaults to true on
31
+ * Node.js only.
32
+ */
33
+ fixAbortAfterGC?: boolean;
34
+ };
35
+ export declare class SignalTimeoutHook implements SDKInitHook, BeforeCreateRequestHook, BeforeRequestHook {
36
+ #private;
37
+ constructor(options?: SignalTimeoutHookOptions);
38
+ sdkInit(opts: SDKOptions): SDKOptions;
39
+ beforeCreateRequest(hookCtx: BeforeCreateRequestContext, input: RequestInput): RequestInput;
40
+ beforeRequest(hookCtx: BeforeRequestContext, request: Request): Request;
41
+ }
42
+ //# sourceMappingURL=signal-hooks.d.ts.map
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Hooks that fix two gaps in the generated request pipeline without editing
3
+ * generated files:
4
+ *
5
+ * 1. Timeouts and signals compose (#1123). The generated `_createRequest`
6
+ * skips `timeoutMs` whenever the caller passes `signal`. This hook restores
7
+ * the timeout on the hook context so `_do` combines it with the signal and
8
+ * the request aborts on whichever fires first. The timeout covers the whole
9
+ * attempt, including reading a streamed response body, the same as for
10
+ * calls made without a signal.
11
+ *
12
+ * 2. Aborts survive garbage collection in Node (#1315). The generated
13
+ * `HTTPClient` calls `fetch(request)` with only a `Request`. In undici, a
14
+ * `Request`'s signal follows its source signal through a weak reference, so
15
+ * after a GC an abort can stop reaching the network
16
+ * (https://github.com/nodejs/undici/issues/4068). Passing the caller's
17
+ * signal again in the `fetch` init avoids this. The hook links each
18
+ * outgoing `Request` to a signal built directly from the caller's signal
19
+ * and the per-attempt timeout, and a wrapped fetcher passes it as `init`.
20
+ * This part only runs on Node: other runtimes don't have the bug, and Bun
21
+ * mishandles a `Request` combined with an `init` argument.
22
+ */
23
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
24
+ if (kind === "m") throw new TypeError("Private method is not writable");
25
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
26
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
27
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
28
+ };
29
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
30
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
31
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
32
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
33
+ };
34
+ var _SignalTimeoutHook_fixAbortAfterGC;
35
+ import { combineSignals } from "../lib/primitives.js";
36
+ /** The caller's own signal for each in-flight operation. */
37
+ const callerSignals = new WeakMap();
38
+ /** The signal to pass in the `fetch` init for each outgoing request. */
39
+ const fetchSignals = new WeakMap();
40
+ /** HTTP clients whose fetcher and hooks have already been wrapped. */
41
+ const wrappedClients = new WeakSet();
42
+ /** Wrapped version of each user `HTTPClient` beforeRequest hook. */
43
+ const wrappedHooks = new WeakMap();
44
+ /** The user hook each wrapped hook came from. */
45
+ const originalHooks = new WeakMap();
46
+ function isObject(value) {
47
+ return typeof value === "object" && value !== null;
48
+ }
49
+ function hasFetcher(value) {
50
+ return (isObject(value)
51
+ && "fetcher" in value
52
+ && typeof value.fetcher === "function");
53
+ }
54
+ function hasRequestHooks(value) {
55
+ return (isObject(value)
56
+ && "requestHooks" in value
57
+ && Array.isArray(value.requestHooks));
58
+ }
59
+ function isHTTPBeforeRequestHook(value) {
60
+ return typeof value === "function";
61
+ }
62
+ /** True on Node.js, false on Bun, Deno, browsers and other runtimes. */
63
+ export function isNodeRuntime() {
64
+ const proc = Reflect.get(globalThis, "process");
65
+ if (!isObject(proc) || !("versions" in proc) || !isObject(proc.versions)) {
66
+ return false;
67
+ }
68
+ const versions = proc.versions;
69
+ return ("node" in versions
70
+ && typeof versions.node === "string"
71
+ && !("bun" in versions)
72
+ && !("deno" in versions));
73
+ }
74
+ function perRequestTimeoutMs(options) {
75
+ if (isObject(options)
76
+ && "timeoutMs" in options
77
+ && typeof options.timeoutMs === "number") {
78
+ return options.timeoutMs;
79
+ }
80
+ return undefined;
81
+ }
82
+ function resolveTimeoutMs(hookCtx, options) {
83
+ // Mirrors the generated `options?.timeoutMs || client._options.timeoutMs`
84
+ // in each `src/funcs/*` operation. `_createRequest` spreads the per-call
85
+ // RequestOptions into the fetch options, so a per-request `timeoutMs` is
86
+ // visible here. A unit test fails if a regen adds per-operation timeout
87
+ // defaults that this lookup would miss.
88
+ const timeoutMs = perRequestTimeoutMs(options) || hookCtx.options.timeoutMs;
89
+ return timeoutMs != null && timeoutMs > 0 ? timeoutMs : undefined;
90
+ }
91
+ /**
92
+ * Wraps a user `HTTPClient` beforeRequest hook so that a replacement
93
+ * `Request` it returns keeps the fetch signal linked to the original.
94
+ */
95
+ function wrapUserHook(fn) {
96
+ const existing = wrappedHooks.get(fn);
97
+ if (existing) {
98
+ return existing;
99
+ }
100
+ const wrapped = async (req) => {
101
+ const next = await fn(req);
102
+ if (next instanceof Request && next !== req) {
103
+ const signal = fetchSignals.get(req);
104
+ if (signal) {
105
+ // Keep any signal the user's hook set on the new request too.
106
+ fetchSignals.set(next, combineSignals(signal, next.signal) ?? signal);
107
+ }
108
+ }
109
+ return next;
110
+ };
111
+ wrappedHooks.set(fn, wrapped);
112
+ originalHooks.set(wrapped, fn);
113
+ return wrapped;
114
+ }
115
+ /** The user's own hook for a wrapped hook, or the hook itself. */
116
+ function unwrapUserHook(hook) {
117
+ return isHTTPBeforeRequestHook(hook) ? originalHooks.get(hook) ?? hook : hook;
118
+ }
119
+ /**
120
+ * Wraps beforeRequest hooks already on the client, and patches `addHook`,
121
+ * `removeHook` and `clone` so hooks added or removed later are handled the
122
+ * same way.
123
+ */
124
+ function wrapClientHooks(client) {
125
+ if (hasRequestHooks(client)) {
126
+ client.requestHooks = client.requestHooks.map((hook) => isHTTPBeforeRequestHook(hook) ? wrapUserHook(hook) : hook);
127
+ }
128
+ const addHook = Reflect.get(client, "addHook");
129
+ const removeHook = Reflect.get(client, "removeHook");
130
+ const clone = Reflect.get(client, "clone");
131
+ if (typeof addHook !== "function"
132
+ || typeof removeHook !== "function"
133
+ || typeof clone !== "function") {
134
+ return;
135
+ }
136
+ // A clone gets the generated, unpatched `removeHook`, so it must hold the
137
+ // user's own hooks: otherwise removing one by its original function finds
138
+ // nothing and the wrapped hook keeps running. The clone is wrapped again
139
+ // only if it is passed to an SDK.
140
+ Reflect.set(client, "clone", () => {
141
+ const child = Reflect.apply(clone, client, []);
142
+ if (hasRequestHooks(child)) {
143
+ child.requestHooks = child.requestHooks.map(unwrapUserHook);
144
+ }
145
+ return child;
146
+ });
147
+ Reflect.set(client, "addHook", (...args) => {
148
+ const [kind, fn] = args;
149
+ if (kind === "beforeRequest" && isHTTPBeforeRequestHook(fn)) {
150
+ Reflect.apply(addHook, client, [kind, wrapUserHook(fn)]);
151
+ return client;
152
+ }
153
+ Reflect.apply(addHook, client, args);
154
+ return client;
155
+ });
156
+ Reflect.set(client, "removeHook", (...args) => {
157
+ const [kind, fn] = args;
158
+ if (kind === "beforeRequest" && isHTTPBeforeRequestHook(fn)) {
159
+ Reflect.apply(removeHook, client, [kind, wrappedHooks.get(fn) ?? fn]);
160
+ return client;
161
+ }
162
+ Reflect.apply(removeHook, client, args);
163
+ return client;
164
+ });
165
+ }
166
+ export class SignalTimeoutHook {
167
+ constructor(options = {}) {
168
+ _SignalTimeoutHook_fixAbortAfterGC.set(this, void 0);
169
+ __classPrivateFieldSet(this, _SignalTimeoutHook_fixAbortAfterGC, options.fixAbortAfterGC ?? isNodeRuntime(), "f");
170
+ }
171
+ sdkInit(opts) {
172
+ if (!__classPrivateFieldGet(this, _SignalTimeoutHook_fixAbortAfterGC, "f")) {
173
+ return opts;
174
+ }
175
+ const client = opts.httpClient;
176
+ // `fetcher` and `requestHooks` are private fields of the generated
177
+ // HTTPClient. If a future regen renames them, skip the wrap rather than
178
+ // break requests; the unit tests flag that case.
179
+ if (hasFetcher(client) && !wrappedClients.has(client)) {
180
+ const inner = client.fetcher;
181
+ client.fetcher = (input, init) => {
182
+ const signal = input instanceof Request
183
+ ? fetchSignals.get(input)
184
+ : undefined;
185
+ if (signal && init?.signal == null) {
186
+ return inner(input, { ...init, signal });
187
+ }
188
+ return inner(input, init);
189
+ };
190
+ wrapClientHooks(client);
191
+ wrappedClients.add(client);
192
+ }
193
+ return opts;
194
+ }
195
+ beforeCreateRequest(hookCtx, input) {
196
+ const signal = input.options?.signal;
197
+ if (signal) {
198
+ if (__classPrivateFieldGet(this, _SignalTimeoutHook_fixAbortAfterGC, "f")) {
199
+ callerSignals.set(hookCtx, signal);
200
+ }
201
+ if (hookCtx.timeoutMs == null || hookCtx.timeoutMs <= 0) {
202
+ const timeoutMs = resolveTimeoutMs(hookCtx, input.options);
203
+ if (timeoutMs != null) {
204
+ hookCtx.timeoutMs = timeoutMs;
205
+ }
206
+ }
207
+ }
208
+ return input;
209
+ }
210
+ beforeRequest(hookCtx, request) {
211
+ if (!__classPrivateFieldGet(this, _SignalTimeoutHook_fixAbortAfterGC, "f")) {
212
+ return request;
213
+ }
214
+ // Runs once per attempt, so each retry gets a fresh timeout.
215
+ //
216
+ // `_do` has already started an `AbortSignal.timeout` of the same length
217
+ // for this attempt, but it only reaches us through `request.signal`, which
218
+ // is the weakly linked signal that #1315 is about. So we start a second
219
+ // timer and build the fetch signal from strong references only. The fetch
220
+ // uses this one; the `_do` timer is redundant but harmless.
221
+ const timeoutSignal = hookCtx.timeoutMs != null && hookCtx.timeoutMs > 0
222
+ ? AbortSignal.timeout(hookCtx.timeoutMs)
223
+ : undefined;
224
+ const strongSignal = combineSignals(callerSignals.get(hookCtx), timeoutSignal);
225
+ if (!strongSignal) {
226
+ return request;
227
+ }
228
+ // `request.signal` is included so that a signal a later create-request
229
+ // hook put on the request still cancels the fetch, instead of the caller's
230
+ // signal captured above overriding it.
231
+ fetchSignals.set(request, combineSignals(strongSignal, request.signal) ?? strongSignal);
232
+ return request;
233
+ }
234
+ }
235
+ _SignalTimeoutHook_fixAbortAfterGC = new WeakMap();
236
+ //# sourceMappingURL=signal-hooks.js.map
@@ -50,8 +50,8 @@ export declare function serverURLFromOptions(options: SDKOptions): URL | null;
50
50
  export declare const SDK_METADATA: {
51
51
  readonly language: "typescript";
52
52
  readonly openapiDocVersion: "1.0.0";
53
- readonly sdkVersion: "1.5.57";
53
+ readonly sdkVersion: "1.5.59";
54
54
  readonly genVersion: "2.950.13";
55
- readonly userAgent: "speakeasy-sdk/typescript 1.5.57 2.950.13 1.0.0 @openrouter/sdk";
55
+ readonly userAgent: "speakeasy-sdk/typescript 1.5.59 2.950.13 1.0.0 @openrouter/sdk";
56
56
  };
57
57
  //# sourceMappingURL=config.d.ts.map
package/esm/lib/config.js CHANGED
@@ -29,8 +29,8 @@ export function serverURLFromOptions(options) {
29
29
  export const SDK_METADATA = {
30
30
  language: "typescript",
31
31
  openapiDocVersion: "1.0.0",
32
- sdkVersion: "1.5.57",
32
+ sdkVersion: "1.5.59",
33
33
  genVersion: "2.950.13",
34
- userAgent: "speakeasy-sdk/typescript 1.5.57 2.950.13 1.0.0 @openrouter/sdk",
34
+ userAgent: "speakeasy-sdk/typescript 1.5.59 2.950.13 1.0.0 @openrouter/sdk",
35
35
  };
36
36
  //# sourceMappingURL=config.js.map
@@ -64,6 +64,10 @@ export type ChatRequestReasoning = {
64
64
  * Constrains effort on reasoning for reasoning models
65
65
  */
66
66
  effort?: ChatRequestEffort | null | undefined;
67
+ /**
68
+ * Maximum number of tokens the model may spend on reasoning, for models that take a reasoning token budget instead of an effort level. Cannot be combined with `reasoning.effort` or the top-level `reasoning_effort`: a request that sets both is rejected with "Only one of "reasoning.effort" and "reasoning.max_tokens" can be specified".
69
+ */
70
+ maxTokens?: number | null | undefined;
67
71
  summary?: ChatReasoningSummaryVerbosityEnum | null | undefined;
68
72
  };
69
73
  /**
@@ -294,6 +298,7 @@ export declare const ChatRequestEffort$outboundSchema: z.ZodType<string, ChatReq
294
298
  /** @internal */
295
299
  export type ChatRequestReasoning$Outbound = {
296
300
  effort?: string | null | undefined;
301
+ max_tokens?: number | null | undefined;
297
302
  summary?: string | null | undefined;
298
303
  };
299
304
  /** @internal */
@@ -107,8 +107,13 @@ export const ChatRequestEffort$outboundSchema = openEnums.outboundSchema(ChatReq
107
107
  /** @internal */
108
108
  export const ChatRequestReasoning$outboundSchema = z.object({
109
109
  effort: z.nullable(ChatRequestEffort$outboundSchema).optional(),
110
+ maxTokens: z.nullable(z.int()).optional(),
110
111
  summary: z.nullable(ChatReasoningSummaryVerbosityEnum$outboundSchema)
111
112
  .optional(),
113
+ }).transform((v) => {
114
+ return remap$(v, {
115
+ maxTokens: "max_tokens",
116
+ });
112
117
  });
113
118
  export function chatRequestReasoningToJSON(chatRequestReasoning) {
114
119
  return JSON.stringify(ChatRequestReasoning$outboundSchema.parse(chatRequestReasoning));
@@ -1,6 +1,7 @@
1
1
  import * as z from "zod/v4";
2
2
  import * as discriminatedUnionTypes from "../types/discriminatedUnion.js";
3
3
  import { Result as SafeParseResult } from "../types/fp.js";
4
+ import { CostDetails } from "./costdetails.js";
4
5
  import { DecisionsBoxAnswer } from "./decisionsboxanswer.js";
5
6
  import { DecisionsChoiceAnswer } from "./decisionschoiceanswer.js";
6
7
  import { DecisionsNoulAnswer } from "./decisionsnoulanswer.js";
@@ -14,12 +15,23 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js";
14
15
  */
15
16
  export type DecisionsResponseAnswers = DecisionsBoxAnswer | DecisionsChoiceAnswer | DecisionsNoulAnswer | DecisionsRefusalAnswer | DecisionsScoreAnswer | discriminatedUnionTypes.Unknown<"type">;
16
17
  export type DecisionsResponseUsage = {
18
+ /**
19
+ * What OpenRouter charges for the request, in credits. On a BYOK request this is the OpenRouter fee only.
20
+ */
17
21
  cost?: number | undefined;
22
+ /**
23
+ * Breakdown of upstream inference costs
24
+ */
25
+ costDetails?: CostDetails | null | undefined;
18
26
  inputTokens: number;
19
27
  /**
20
28
  * Of `input_tokens`, those the provider served from its prompt cache.
21
29
  */
22
30
  inputTokensDetails?: DecisionsUsageInputTokensDetails | undefined;
31
+ /**
32
+ * Whether a request was made using a Bring Your Own Key configuration
33
+ */
34
+ isByok?: boolean | undefined;
23
35
  outputTokens: number;
24
36
  };
25
37
  export type DecisionsResponse = {
@@ -6,6 +6,7 @@ import * as z from "zod/v4";
6
6
  import { remap as remap$ } from "../lib/primitives.js";
7
7
  import { safeParse } from "../lib/schemas.js";
8
8
  import { discriminatedUnion } from "../types/discriminatedUnion.js";
9
+ import { CostDetails$inboundSchema } from "./costdetails.js";
9
10
  import { DecisionsBoxAnswer$inboundSchema, } from "./decisionsboxanswer.js";
10
11
  import { DecisionsChoiceAnswer$inboundSchema, } from "./decisionschoiceanswer.js";
11
12
  import { DecisionsNoulAnswer$inboundSchema, } from "./decisionsnoulanswer.js";
@@ -27,14 +28,18 @@ export function decisionsResponseAnswersFromJSON(jsonString) {
27
28
  /** @internal */
28
29
  export const DecisionsResponseUsage$inboundSchema = z.object({
29
30
  cost: z.number().optional(),
31
+ cost_details: z.nullable(CostDetails$inboundSchema).optional(),
30
32
  input_tokens: z.int(),
31
33
  input_tokens_details: DecisionsUsageInputTokensDetails$inboundSchema
32
34
  .optional(),
35
+ is_byok: z.boolean().optional(),
33
36
  output_tokens: z.int(),
34
37
  }).transform((v) => {
35
38
  return remap$(v, {
39
+ "cost_details": "costDetails",
36
40
  "input_tokens": "inputTokens",
37
41
  "input_tokens_details": "inputTokensDetails",
42
+ "is_byok": "isByok",
38
43
  "output_tokens": "outputTokens",
39
44
  });
40
45
  });
@@ -156,12 +156,15 @@ export type ListData = {
156
156
  /**
157
157
  * List of API keys
158
158
  */
159
- export type ListResponse = {
159
+ export type ListResponseBody = {
160
160
  /**
161
161
  * List of API keys
162
162
  */
163
163
  data: Array<ListData>;
164
164
  };
165
+ export type ListResponse = {
166
+ result: ListResponseBody;
167
+ };
165
168
  /** @internal */
166
169
  export type ListRequest$Outbound = {
167
170
  "HTTP-Referer"?: string | undefined;
@@ -179,6 +182,9 @@ export declare function listRequestToJSON(listRequest: ListRequest): string;
179
182
  export declare const ListData$inboundSchema: z.ZodType<ListData, unknown>;
180
183
  export declare function listDataFromJSON(jsonString: string): SafeParseResult<ListData, SDKValidationError>;
181
184
  /** @internal */
185
+ export declare const ListResponseBody$inboundSchema: z.ZodType<ListResponseBody, unknown>;
186
+ export declare function listResponseBodyFromJSON(jsonString: string): SafeParseResult<ListResponseBody, SDKValidationError>;
187
+ /** @internal */
182
188
  export declare const ListResponse$inboundSchema: z.ZodType<ListResponse, unknown>;
183
189
  export declare function listResponseFromJSON(jsonString: string): SafeParseResult<ListResponse, SDKValidationError>;
184
190
  //# sourceMappingURL=list.d.ts.map
@@ -75,9 +75,20 @@ export function listDataFromJSON(jsonString) {
75
75
  return safeParse(jsonString, (x) => ListData$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'ListData' from JSON`);
76
76
  }
77
77
  /** @internal */
78
+ export const ListResponseBody$inboundSchema = z.object({
79
+ data: z.array(z.lazy(() => ListData$inboundSchema)),
80
+ });
81
+ export function listResponseBodyFromJSON(jsonString) {
82
+ return safeParse(jsonString, (x) => ListResponseBody$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'ListResponseBody' from JSON`);
83
+ }
84
+ /** @internal */
78
85
  export const ListResponse$inboundSchema = z
79
86
  .object({
80
- data: z.array(z.lazy(() => ListData$inboundSchema)),
87
+ Result: z.lazy(() => ListResponseBody$inboundSchema),
88
+ }).transform((v) => {
89
+ return remap$(v, {
90
+ "Result": "result",
91
+ });
81
92
  });
82
93
  export function listResponseFromJSON(jsonString) {
83
94
  return safeParse(jsonString, (x) => ListResponse$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'ListResponse' from JSON`);
@@ -1,5 +1,6 @@
1
1
  import { ClientSDK, RequestOptions } from "../lib/sdks.js";
2
2
  import * as operations from "../models/operations/index.js";
3
+ import { PageIterator } from "../types/operations.js";
3
4
  export declare class APIKeys extends ClientSDK {
4
5
  /**
5
6
  * Get current API key
@@ -14,7 +15,9 @@ export declare class APIKeys extends ClientSDK {
14
15
  * @remarks
15
16
  * List all API keys for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.
16
17
  */
17
- list(request?: operations.ListRequest | undefined, options?: RequestOptions): Promise<operations.ListResponse>;
18
+ list(request?: operations.ListRequest | undefined, options?: RequestOptions): Promise<PageIterator<operations.ListResponse, {
19
+ offset: number;
20
+ }>>;
18
21
  /**
19
22
  * Create a new API key
20
23
  *
@@ -10,6 +10,7 @@ import { apiKeysList } from "../funcs/apiKeysList.js";
10
10
  import { apiKeysUpdate } from "../funcs/apiKeysUpdate.js";
11
11
  import { ClientSDK } from "../lib/sdks.js";
12
12
  import { unwrapAsync } from "../types/fp.js";
13
+ import { unwrapResultIterator } from "../types/operations.js";
13
14
  export class APIKeys extends ClientSDK {
14
15
  /**
15
16
  * Get current API key
@@ -27,7 +28,7 @@ export class APIKeys extends ClientSDK {
27
28
  * List all API keys for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.
28
29
  */
29
30
  async list(request, options) {
30
- return unwrapAsync(apiKeysList(this, request, options));
31
+ return unwrapResultIterator(apiKeysList(this, request, options));
31
32
  }
32
33
  /**
33
34
  * Create a new API key
package/jsr.json CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  {
4
4
  "name": "@openrouter/sdk",
5
- "version": "1.5.57",
5
+ "version": "1.5.59",
6
6
  "exports": {
7
7
  ".": "./src/index.ts",
8
8
  "./models/errors": "./src/models/errors/index.ts",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openrouter/sdk",
3
- "version": "1.5.57",
3
+ "version": "1.5.59",
4
4
  "author": "OpenRouter",
5
5
  "description": "The OpenRouter TypeScript SDK is a type-safe toolkit for building AI applications with access to 400+ language models through a unified API.",
6
6
  "keywords": [
@@ -73,15 +73,15 @@
73
73
  "lint": "eslint --cache --max-warnings=0 src",
74
74
  "build": "tsc && node scripts/unbarrel-imports.js",
75
75
  "prepublishOnly": "npm run build",
76
- "prepare": "npm run build",
77
- "test:transit": "exit 0",
78
- "test:watch": "vitest --watch --project unit",
76
+ "typecheck": "tsc --noEmit",
79
77
  "typecheck:transit": "exit 0",
80
78
  "compile": "tsc && node scripts/unbarrel-imports.js",
79
+ "prepare": "npm run build",
80
+ "test:transit": "exit 0",
81
+ "postinstall": "node scripts/check-types.js || true",
81
82
  "test": "vitest --run --project unit",
82
83
  "test:e2e": "vitest --run --project e2e",
83
- "typecheck": "tsc --noEmit",
84
- "postinstall": "node scripts/check-types.js || true"
84
+ "test:watch": "vitest --watch --project unit"
85
85
  },
86
86
  "peerDependencies": {
87
87
 
@@ -1,21 +1,29 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * Postinstall script to check if model types are stale.
4
- * Similar to update-browserslist-db, this warns users when their
4
+ * Similar to update-browserslist-db, this warns developers when their
5
5
  * generated types are outdated.
6
6
  *
7
7
  * This script:
8
- * 1. Reads the MODEL_HASH from the generated types file
8
+ * 1. Reads the MODEL_HASH from the generated types source file
9
9
  * 2. Fetches current models from the OpenRouter API
10
10
  * 3. Computes a hash of the current models
11
11
  * 4. Warns to stderr if the hashes don't match
12
12
  *
13
+ * The check runs only in a repository checkout. The published package excludes
14
+ * `src/` (see .npmignore), so installed copies skip it on purpose: the shipped
15
+ * MODEL_HASH goes stale as soon as the model catalog changes, and the fix it
16
+ * would suggest (`npx @openrouter/cli types`) regenerates the source file,
17
+ * which an installed package doesn't have. A warning there could never be
18
+ * cleared.
19
+ *
13
20
  * Exit codes:
14
21
  * - 0: Types are up to date OR check was skipped
15
22
  * - Does NOT fail on stale types (to avoid breaking installs)
16
23
  */
17
24
 
18
25
  import { createHash } from 'node:crypto';
26
+ import { realpathSync } from 'node:fs';
19
27
  import { readFile } from 'node:fs/promises';
20
28
  import { fileURLToPath } from 'node:url';
21
29
  import { dirname, resolve } from 'node:path';
@@ -23,10 +31,18 @@ import { dirname, resolve } from 'node:path';
23
31
  const __filename = fileURLToPath(import.meta.url);
24
32
  const __dirname = dirname(__filename);
25
33
 
26
- const TYPES_FILE_PATH = resolve(__dirname, '../src/types/models.ts');
34
+ /** Generated types source; present only in a repository checkout. */
35
+ export const TYPES_FILE_PATH = resolve(__dirname, '../src/types/models.ts');
27
36
  const API_URL = 'https://openrouter.ai/api/v1/models';
28
37
  const TIMEOUT_MS = 5000;
29
38
 
39
+ export const STALE_TYPES_WARNING =
40
+ '\n' +
41
+ '\x1b[33m' +
42
+ 'OpenRouter model types are outdated.\n' +
43
+ 'Run: npx @openrouter/cli types\n' +
44
+ '\x1b[0m';
45
+
30
46
  /**
31
47
  * Type guard for Node.js errors with error codes
32
48
  * @param {unknown} error
@@ -41,7 +57,7 @@ function isNodeError(error) {
41
57
  * @param {string[]} modelIds
42
58
  * @returns {string}
43
59
  */
44
- function computeHash(modelIds) {
60
+ export function computeHash(modelIds) {
45
61
  const sorted = [...modelIds].sort();
46
62
  const content = sorted.join('\n');
47
63
  const hash = createHash('sha256').update(content).digest('hex');
@@ -53,26 +69,45 @@ function computeHash(modelIds) {
53
69
  * @param {string} content
54
70
  * @returns {string | null}
55
71
  */
56
- function extractHash(content) {
72
+ export function extractHash(content) {
57
73
  const match = content.match(/export const MODEL_HASH = '([a-f0-9]+)'/);
58
- return match ? match[1] : null;
74
+ return match?.[1] ?? null;
59
75
  }
60
76
 
61
77
  /**
62
- * Fetch models from API with timeout
78
+ * Type guard for the /models response shape this script reads
79
+ * @param {unknown} value
80
+ * @returns {value is { data: Array<{ id: string }> }}
81
+ */
82
+ function isModelsResponse(value) {
83
+ return (
84
+ typeof value === 'object' &&
85
+ value !== null &&
86
+ 'data' in value &&
87
+ Array.isArray(value.data) &&
88
+ value.data.every(
89
+ (/** @type {unknown} */ m) =>
90
+ typeof m === 'object' && m !== null && 'id' in m && typeof m.id === 'string',
91
+ )
92
+ );
93
+ }
94
+
95
+ /**
96
+ * Fetch model IDs from the API with timeout
97
+ * @param {typeof fetch} fetchImpl
63
98
  * @returns {Promise<string[]>}
64
99
  */
65
- async function fetchModels() {
100
+ export async function fetchModelIds(fetchImpl) {
66
101
  const controller = new AbortController();
67
102
  const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);
68
103
 
69
104
  try {
70
- const response = await fetch(API_URL, { signal: controller.signal });
105
+ const response = await fetchImpl(API_URL, { signal: controller.signal });
71
106
  if (!response.ok) {
72
107
  throw new Error(`HTTP ${response.status}`);
73
108
  }
74
109
  const data = await response.json();
75
- if (!data?.data || !Array.isArray(data.data)) {
110
+ if (!isModelsResponse(data)) {
76
111
  throw new Error('Invalid API response structure');
77
112
  }
78
113
  return data.data.map((m) => m.id);
@@ -81,47 +116,85 @@ async function fetchModels() {
81
116
  }
82
117
  }
83
118
 
84
- async function main() {
85
- if (process.env.CI) {
86
- return;
87
- }
88
-
89
- if (process.env.OPENROUTER_SKIP_TYPE_CHECK) {
90
- return;
119
+ /**
120
+ * Read the types source file
121
+ * @param {string} path
122
+ * @returns {Promise<string | null>} file content, or null if it doesn't exist
123
+ */
124
+ async function readTypesFile(path) {
125
+ try {
126
+ return await readFile(path, 'utf-8');
127
+ } catch (error) {
128
+ if (isNodeError(error) && error.code === 'ENOENT') {
129
+ return null;
130
+ }
131
+ throw error;
91
132
  }
133
+ }
92
134
 
135
+ /**
136
+ * Compare the generated MODEL_HASH with the live model catalog.
137
+ * Never throws: any failure resolves to 'error' so installs never break.
138
+ * @param {{
139
+ * typesFilePath: string,
140
+ * fetchModelIds: () => Promise<string[]>,
141
+ * warn: (message: string) => void,
142
+ * }} deps
143
+ * @returns {Promise<'skipped' | 'up-to-date' | 'stale' | 'error'>}
144
+ */
145
+ export async function checkTypes(deps) {
93
146
  try {
94
- /** @type {string | null} */
95
- let existingHash;
96
- try {
97
- const content = await readFile(TYPES_FILE_PATH, 'utf-8');
98
- existingHash = extractHash(content);
99
- } catch (error) {
100
- if (isNodeError(error) && error.code === 'ENOENT') {
101
- return;
102
- }
103
- throw error;
147
+ const content = await readTypesFile(deps.typesFilePath);
148
+ // No source file means an installed package; skip on purpose (see header).
149
+ if (content === null) {
150
+ return 'skipped';
104
151
  }
105
152
 
153
+ const existingHash = extractHash(content);
106
154
  if (!existingHash) {
107
- return;
155
+ return 'skipped';
108
156
  }
109
157
 
110
- const modelIds = await fetchModels();
111
- const currentHash = computeHash(modelIds);
112
-
113
- if (existingHash !== currentHash) {
114
- process.stderr.write(
115
- '\n' +
116
- '\x1b[33m' +
117
- 'OpenRouter model types are outdated.\n' +
118
- 'Run: npx @openrouter/cli types\n' +
119
- '\x1b[0m',
120
- );
158
+ const currentHash = computeHash(await deps.fetchModelIds());
159
+ if (existingHash === currentHash) {
160
+ return 'up-to-date';
121
161
  }
162
+
163
+ deps.warn(STALE_TYPES_WARNING);
164
+ return 'stale';
122
165
  } catch {
123
166
  // Silently ignore errors - we don't want to break installs
167
+ return 'error';
168
+ }
169
+ }
170
+
171
+ async function main() {
172
+ if (process.env.CI || process.env.OPENROUTER_SKIP_TYPE_CHECK) {
173
+ return;
174
+ }
175
+
176
+ await checkTypes({
177
+ typesFilePath: TYPES_FILE_PATH,
178
+ fetchModelIds: () => fetchModelIds(fetch),
179
+ warn: (message) => process.stderr.write(message),
180
+ });
181
+ }
182
+
183
+ /**
184
+ * True when this file is run directly (`node scripts/check-types.js`), not
185
+ * imported, so tests can import the exports without triggering a check.
186
+ * @returns {boolean}
187
+ */
188
+ function isRunDirectly() {
189
+ const entry = process.argv[1];
190
+ if (!entry) return false;
191
+ try {
192
+ return realpathSync(entry) === realpathSync(__filename);
193
+ } catch {
194
+ return false;
124
195
  }
125
196
  }
126
197
 
127
- main();
198
+ if (isRunDirectly()) {
199
+ void main();
200
+ }
package/vitest.config.ts CHANGED
@@ -17,6 +17,13 @@ export default defineConfig({
17
17
  typecheck: {
18
18
  enabled: true,
19
19
  },
20
+ // tests/unit/signal-timeout-hooks.test.ts forces a GC to reproduce #1315.
21
+ pool: 'forks',
22
+ poolOptions: {
23
+ forks: {
24
+ execArgv: ['--expose-gc'],
25
+ },
26
+ },
20
27
  projects: [
21
28
  {
22
29
  extends: true,