@anthropic-ai/sdk 0.4.4 → 0.5.1

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.
Files changed (156) hide show
  1. package/_shims/agent.d.ts +9 -0
  2. package/_shims/agent.d.ts.map +1 -0
  3. package/_shims/agent.js +14 -0
  4. package/_shims/agent.js.map +1 -0
  5. package/_shims/agent.mjs +10 -0
  6. package/_shims/agent.mjs.map +1 -0
  7. package/_shims/agent.node.d.ts +7 -0
  8. package/_shims/agent.node.d.ts.map +1 -0
  9. package/_shims/agent.node.js +28 -0
  10. package/_shims/agent.node.js.map +1 -0
  11. package/_shims/agent.node.mjs +16 -0
  12. package/_shims/agent.node.mjs.map +1 -0
  13. package/_shims/fetch.d.ts +52 -0
  14. package/_shims/fetch.js +13 -0
  15. package/_shims/fetch.mjs +15 -0
  16. package/_shims/fetch.node.d.ts +53 -0
  17. package/_shims/fetch.node.js +12 -0
  18. package/_shims/fetch.node.mjs +14 -0
  19. package/_shims/fileFromPath.d.ts +22 -0
  20. package/_shims/fileFromPath.d.ts.map +1 -0
  21. package/_shims/fileFromPath.js +16 -0
  22. package/_shims/fileFromPath.js.map +1 -0
  23. package/_shims/fileFromPath.mjs +12 -0
  24. package/_shims/fileFromPath.mjs.map +1 -0
  25. package/_shims/fileFromPath.node.d.ts +17 -0
  26. package/_shims/fileFromPath.node.d.ts.map +1 -0
  27. package/_shims/fileFromPath.node.js +17 -0
  28. package/_shims/fileFromPath.node.js.map +1 -0
  29. package/_shims/fileFromPath.node.mjs +13 -0
  30. package/_shims/fileFromPath.node.mjs.map +1 -0
  31. package/_shims/formdata.d.ts +43 -0
  32. package/_shims/formdata.js +9 -0
  33. package/_shims/formdata.mjs +11 -0
  34. package/_shims/formdata.node.d.ts +44 -0
  35. package/_shims/formdata.node.js +11 -0
  36. package/_shims/formdata.node.mjs +9 -0
  37. package/_shims/getMultipartRequestOptions.d.ts +10 -0
  38. package/_shims/getMultipartRequestOptions.d.ts.map +1 -0
  39. package/_shims/getMultipartRequestOptions.js +12 -0
  40. package/_shims/getMultipartRequestOptions.js.map +1 -0
  41. package/_shims/getMultipartRequestOptions.mjs +8 -0
  42. package/_shims/getMultipartRequestOptions.mjs.map +1 -0
  43. package/_shims/getMultipartRequestOptions.node.d.ts +10 -0
  44. package/_shims/getMultipartRequestOptions.node.d.ts.map +1 -0
  45. package/_shims/getMultipartRequestOptions.node.js +22 -0
  46. package/_shims/getMultipartRequestOptions.node.js.map +1 -0
  47. package/_shims/getMultipartRequestOptions.node.mjs +18 -0
  48. package/_shims/getMultipartRequestOptions.node.mjs.map +1 -0
  49. package/_shims/node-readable.d.ts +23 -0
  50. package/_shims/node-readable.d.ts.map +1 -0
  51. package/_shims/node-readable.js +11 -0
  52. package/_shims/node-readable.js.map +1 -0
  53. package/_shims/node-readable.mjs +7 -0
  54. package/_shims/node-readable.mjs.map +1 -0
  55. package/_shims/node-readable.node.d.ts +8 -0
  56. package/_shims/node-readable.node.d.ts.map +1 -0
  57. package/_shims/node-readable.node.js +9 -0
  58. package/_shims/node-readable.node.js.map +1 -0
  59. package/_shims/node-readable.node.mjs +5 -0
  60. package/_shims/node-readable.node.mjs.map +1 -0
  61. package/core.d.ts +226 -0
  62. package/core.d.ts.map +1 -0
  63. package/core.js +683 -0
  64. package/core.js.map +1 -0
  65. package/core.mjs +587 -0
  66. package/core.mjs.map +1 -0
  67. package/error.d.ts +48 -0
  68. package/error.d.ts.map +1 -0
  69. package/error.js +126 -0
  70. package/error.js.map +1 -0
  71. package/error.mjs +101 -0
  72. package/error.mjs.map +1 -0
  73. package/index.d.mts +104 -0
  74. package/index.d.ts +104 -0
  75. package/index.d.ts.map +1 -0
  76. package/index.js +177 -0
  77. package/index.js.map +1 -0
  78. package/index.mjs +118 -0
  79. package/index.mjs.map +1 -0
  80. package/package.json +73 -23
  81. package/resource.d.ts +12 -0
  82. package/resource.d.ts.map +1 -0
  83. package/resource.js +17 -0
  84. package/resource.js.map +1 -0
  85. package/resource.mjs +13 -0
  86. package/resource.mjs.map +1 -0
  87. package/resources/completions.d.ts +311 -0
  88. package/resources/completions.d.ts.map +1 -0
  89. package/resources/completions.js +19 -0
  90. package/resources/completions.js.map +1 -0
  91. package/resources/completions.mjs +15 -0
  92. package/resources/completions.mjs.map +1 -0
  93. package/resources/index.d.ts +2 -0
  94. package/resources/index.d.ts.map +1 -0
  95. package/resources/index.js +12 -0
  96. package/resources/index.js.map +1 -0
  97. package/resources/index.mjs +3 -0
  98. package/resources/index.mjs.map +1 -0
  99. package/resources/top-level.d.ts +2 -0
  100. package/resources/top-level.d.ts.map +1 -0
  101. package/resources/top-level.js +4 -0
  102. package/resources/top-level.js.map +1 -0
  103. package/resources/top-level.mjs +3 -0
  104. package/resources/top-level.mjs.map +1 -0
  105. package/src/_shims/agent.node.ts +22 -0
  106. package/src/_shims/agent.ts +12 -0
  107. package/src/_shims/fetch.d.ts +52 -0
  108. package/src/_shims/fetch.js +13 -0
  109. package/src/_shims/fetch.mjs +15 -0
  110. package/src/_shims/fetch.node.d.ts +53 -0
  111. package/src/_shims/fetch.node.js +12 -0
  112. package/src/_shims/fetch.node.mjs +14 -0
  113. package/src/_shims/fileFromPath.node.ts +29 -0
  114. package/src/_shims/fileFromPath.ts +29 -0
  115. package/src/_shims/formdata.d.ts +43 -0
  116. package/src/_shims/formdata.js +9 -0
  117. package/src/_shims/formdata.mjs +11 -0
  118. package/src/_shims/formdata.node.d.ts +44 -0
  119. package/src/_shims/formdata.node.js +11 -0
  120. package/src/_shims/formdata.node.mjs +9 -0
  121. package/src/_shims/getMultipartRequestOptions.node.ts +25 -0
  122. package/src/_shims/getMultipartRequestOptions.ts +14 -0
  123. package/src/_shims/node-readable.node.ts +10 -0
  124. package/src/_shims/node-readable.ts +30 -0
  125. package/src/core.ts +783 -0
  126. package/src/error.ts +115 -0
  127. package/src/index.ts +200 -0
  128. package/src/resource.ts +24 -0
  129. package/src/resources/completions.ts +344 -0
  130. package/src/resources/index.ts +3 -0
  131. package/src/resources/top-level.ts +3 -0
  132. package/src/streaming.ts +220 -0
  133. package/src/uploads.ts +248 -0
  134. package/src/version.ts +1 -0
  135. package/streaming.d.ts +14 -0
  136. package/streaming.d.ts.map +1 -0
  137. package/streaming.js +168 -0
  138. package/streaming.js.map +1 -0
  139. package/streaming.mjs +164 -0
  140. package/streaming.mjs.map +1 -0
  141. package/uploads.d.ts +90 -0
  142. package/uploads.d.ts.map +1 -0
  143. package/uploads.js +207 -0
  144. package/uploads.js.map +1 -0
  145. package/uploads.mjs +174 -0
  146. package/uploads.mjs.map +1 -0
  147. package/version.d.ts +2 -0
  148. package/version.d.ts.map +1 -0
  149. package/version.js +5 -0
  150. package/version.js.map +1 -0
  151. package/version.mjs +2 -0
  152. package/version.mjs.map +1 -0
  153. package/LICENSE +0 -21
  154. package/README.md +0 -34
  155. package/build/src/index.d.ts +0 -39
  156. package/build/src/index.js +0 -116
package/src/core.ts ADDED
@@ -0,0 +1,783 @@
1
+ import * as qs from 'qs';
2
+ import { VERSION } from './version';
3
+ import { Stream } from './streaming';
4
+ import { APIError, APIConnectionError, APIConnectionTimeoutError } from './error';
5
+ import type { Readable } from '@anthropic-ai/sdk/_shims/node-readable';
6
+ import { getDefaultAgent, type Agent } from '@anthropic-ai/sdk/_shims/agent';
7
+ import {
8
+ fetch,
9
+ isPolyfilled as fetchIsPolyfilled,
10
+ type RequestInfo,
11
+ type RequestInit,
12
+ type Response,
13
+ } from '@anthropic-ai/sdk/_shims/fetch';
14
+ import { isMultipartBody } from './uploads';
15
+ export {
16
+ maybeMultipartFormRequestOptions,
17
+ multipartFormRequestOptions,
18
+ createForm,
19
+ type Uploadable,
20
+ } from './uploads';
21
+
22
+ const MAX_RETRIES = 2;
23
+
24
+ type Fetch = (url: RequestInfo, init?: RequestInit) => Promise<Response>;
25
+
26
+ export abstract class APIClient {
27
+ baseURL: string;
28
+ maxRetries: number;
29
+ timeout: number;
30
+ httpAgent: Agent | undefined;
31
+
32
+ private fetch: Fetch;
33
+ protected idempotencyHeader?: string;
34
+
35
+ constructor({
36
+ baseURL,
37
+ maxRetries,
38
+ timeout = 60 * 1000, // 60s
39
+ httpAgent,
40
+ }: {
41
+ baseURL: string;
42
+ maxRetries?: number | undefined;
43
+ timeout: number | undefined;
44
+ httpAgent: Agent | undefined;
45
+ }) {
46
+ this.baseURL = baseURL;
47
+ this.maxRetries = validatePositiveInteger('maxRetries', maxRetries ?? MAX_RETRIES);
48
+ this.timeout = validatePositiveInteger('timeout', timeout);
49
+ this.httpAgent = httpAgent;
50
+
51
+ this.fetch = fetch;
52
+ }
53
+
54
+ protected authHeaders(): Headers {
55
+ return {};
56
+ }
57
+
58
+ /**
59
+ * Override this to add your own default headers, for example:
60
+ *
61
+ * {
62
+ * ...super.defaultHeaders(),
63
+ * Authorization: 'Bearer 123',
64
+ * }
65
+ */
66
+ protected defaultHeaders(): Headers {
67
+ return {
68
+ Accept: 'application/json',
69
+ 'Content-Type': 'application/json',
70
+ 'User-Agent': this.getUserAgent(),
71
+ ...getPlatformHeaders(),
72
+ ...this.authHeaders(),
73
+ };
74
+ }
75
+
76
+ protected abstract defaultQuery(): DefaultQuery | undefined;
77
+
78
+ /**
79
+ * Override this to add your own headers validation:
80
+ */
81
+ protected validateHeaders(headers: Headers, customHeaders: Headers) {}
82
+
83
+ /**
84
+ * Override this to add your own qs.stringify options, for example:
85
+ *
86
+ * {
87
+ * ...super.qsOptions(),
88
+ * strictNullHandling: true,
89
+ * }
90
+ */
91
+ protected qsOptions(): qs.IStringifyOptions | undefined {
92
+ return {};
93
+ }
94
+
95
+ protected defaultIdempotencyKey(): string {
96
+ return `stainless-node-retry-${uuid4()}`;
97
+ }
98
+
99
+ get<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
100
+ return this.request({ method: 'get', path, ...opts });
101
+ }
102
+ post<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
103
+ return this.request({ method: 'post', path, ...opts });
104
+ }
105
+ patch<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
106
+ return this.request({ method: 'patch', path, ...opts });
107
+ }
108
+ put<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
109
+ return this.request({ method: 'put', path, ...opts });
110
+ }
111
+ delete<Req extends {}, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
112
+ return this.request({ method: 'delete', path, ...opts });
113
+ }
114
+
115
+ getAPIList<Item, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(
116
+ path: string,
117
+ Page: new (...args: any[]) => PageClass,
118
+ opts?: RequestOptions<any>,
119
+ ): PagePromise<PageClass> {
120
+ return this.requestAPIList(Page, { method: 'get', path, ...opts });
121
+ }
122
+
123
+ buildRequest<Req extends {}>(
124
+ options: FinalRequestOptions<Req>,
125
+ ): { req: RequestInit; url: string; timeout: number } {
126
+ const { method, path, query, headers: headers = {} } = options;
127
+
128
+ const body =
129
+ isMultipartBody(options.body) ? options.body.body
130
+ : options.body ? JSON.stringify(options.body, null, 2)
131
+ : null;
132
+ const contentLength = typeof body === 'string' ? body.length.toString() : null;
133
+
134
+ const url = this.buildURL(path!, query);
135
+ const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
136
+ const timeout = options.timeout ?? this.timeout;
137
+ validatePositiveInteger('timeout', timeout);
138
+
139
+ if (this.idempotencyHeader && method !== 'get') {
140
+ if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();
141
+ headers[this.idempotencyHeader] = options.idempotencyKey;
142
+ }
143
+
144
+ const reqHeaders: Record<string, string> = {
145
+ ...(contentLength && { 'Content-Length': contentLength }),
146
+ ...this.defaultHeaders(),
147
+ ...headers,
148
+ };
149
+ // let builtin fetch set the Content-Type for multipart bodies
150
+ if (isMultipartBody(options.body) && !fetchIsPolyfilled) {
151
+ delete reqHeaders['Content-Type'];
152
+ }
153
+
154
+ // Strip any headers being explicitly omitted with null
155
+ Object.keys(reqHeaders).forEach((key) => reqHeaders[key] === null && delete reqHeaders[key]);
156
+
157
+ const req: RequestInit = {
158
+ method,
159
+ ...(body && { body: body as any }),
160
+ headers: reqHeaders,
161
+ ...(httpAgent && { agent: httpAgent }),
162
+ };
163
+
164
+ this.validateHeaders(reqHeaders, headers);
165
+
166
+ return { req, url, timeout };
167
+ }
168
+
169
+ /**
170
+ * Used as a callback for mutating the given `RequestInit` object.
171
+ *
172
+ * This is useful for cases where you want to add certain headers based off of
173
+ * the request properties, e.g. `method` or `url`.
174
+ */
175
+ protected async prepareRequest(request: RequestInit, { url }: { url: string }): Promise<void> {}
176
+
177
+ protected makeStatusError(
178
+ status: number | undefined,
179
+ error: Object | undefined,
180
+ message: string | undefined,
181
+ headers: Headers | undefined,
182
+ ) {
183
+ return APIError.generate(status, error, message, headers);
184
+ }
185
+
186
+ async request<Req extends {}, Rsp>(
187
+ options: FinalRequestOptions<Req>,
188
+ retriesRemaining = options.maxRetries ?? this.maxRetries,
189
+ ): Promise<APIResponse<Rsp>> {
190
+ const { req, url, timeout } = this.buildRequest(options);
191
+ await this.prepareRequest(req, { url });
192
+
193
+ this.debug('request', url, options, req.headers);
194
+
195
+ const controller = new AbortController();
196
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
197
+
198
+ if (response instanceof Error) {
199
+ if (retriesRemaining) return this.retryRequest(options, retriesRemaining);
200
+ if (response.name === 'AbortError') throw new APIConnectionTimeoutError();
201
+ throw new APIConnectionError({ cause: response });
202
+ }
203
+
204
+ const responseHeaders = createResponseHeaders(response.headers);
205
+
206
+ if (!response.ok) {
207
+ if (retriesRemaining && this.shouldRetry(response)) {
208
+ return this.retryRequest(options, retriesRemaining, responseHeaders);
209
+ }
210
+
211
+ const errText = await response.text().catch(() => 'Unknown');
212
+ const errJSON = safeJSON(errText);
213
+ const errMessage = errJSON ? undefined : errText;
214
+
215
+ this.debug('response', response.status, url, responseHeaders, errMessage);
216
+
217
+ const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
218
+ throw err;
219
+ }
220
+
221
+ if (options.stream) {
222
+ // Note: there is an invariant here that isn't represented in the type system
223
+ // that if you set `stream: true` the response type must also be `Stream<T>`
224
+ return new Stream<Rsp>(response, controller) as any;
225
+ }
226
+
227
+ const contentType = response.headers.get('content-type');
228
+ if (contentType?.includes('application/json')) {
229
+ const json = await response.json();
230
+
231
+ if (typeof json === 'object' && json != null) {
232
+ /** @deprecated – we expect to change this interface in the near future. */
233
+ Object.defineProperty(json, 'responseHeaders', {
234
+ enumerable: false,
235
+ writable: false,
236
+ value: responseHeaders,
237
+ });
238
+ }
239
+
240
+ this.debug('response', response.status, url, responseHeaders, json);
241
+
242
+ return json as APIResponse<Rsp>;
243
+ }
244
+
245
+ // TODO handle blob, arraybuffer, other content types, etc.
246
+ const text = response.text();
247
+ this.debug('response', response.status, url, responseHeaders, text);
248
+ return text as Promise<any>;
249
+ }
250
+
251
+ requestAPIList<Item = unknown, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(
252
+ Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,
253
+ options: FinalRequestOptions,
254
+ ): PagePromise<PageClass> {
255
+ const requestPromise = this.request(options) as Promise<APIResponse<unknown>>;
256
+ return new PagePromise(this, requestPromise, options, Page);
257
+ }
258
+
259
+ buildURL<Req>(path: string, query: Req | undefined): string {
260
+ const url =
261
+ isAbsoluteURL(path) ?
262
+ new URL(path)
263
+ : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
264
+
265
+ const defaultQuery = this.defaultQuery();
266
+ if (!isEmptyObj(defaultQuery)) {
267
+ query = { ...defaultQuery, ...query } as Req;
268
+ }
269
+
270
+ if (query) {
271
+ url.search = qs.stringify(query, this.qsOptions());
272
+ }
273
+
274
+ return url.toString();
275
+ }
276
+
277
+ async fetchWithTimeout(
278
+ url: RequestInfo,
279
+ init: RequestInit | undefined,
280
+ ms: number,
281
+ controller: AbortController,
282
+ ): Promise<Response> {
283
+ const { signal, ...options } = init || {};
284
+ if (signal) signal.addEventListener('abort', () => controller.abort());
285
+
286
+ const timeout = setTimeout(() => controller.abort(), ms);
287
+
288
+ return this.getRequestClient()
289
+ .fetch(url, { signal: controller.signal as any, ...options })
290
+ .finally(() => {
291
+ clearTimeout(timeout);
292
+ });
293
+ }
294
+
295
+ protected getRequestClient(): RequestClient {
296
+ return { fetch: this.fetch };
297
+ }
298
+
299
+ private shouldRetry(response: Response): boolean {
300
+ // Note this is not a standard header.
301
+ const shouldRetryHeader = response.headers.get('x-should-retry');
302
+
303
+ // If the server explicitly says whether or not to retry, obey.
304
+ if (shouldRetryHeader === 'true') return true;
305
+ if (shouldRetryHeader === 'false') return false;
306
+
307
+ // Retry on lock timeouts.
308
+ if (response.status === 409) return true;
309
+
310
+ // Retry on rate limits.
311
+ if (response.status === 429) return true;
312
+
313
+ // Retry internal errors.
314
+ if (response.status >= 500) return true;
315
+
316
+ return false;
317
+ }
318
+
319
+ private async retryRequest<Req extends {}, Rsp>(
320
+ options: FinalRequestOptions<Req>,
321
+ retriesRemaining: number,
322
+ responseHeaders?: Headers | undefined,
323
+ ): Promise<Rsp> {
324
+ retriesRemaining -= 1;
325
+
326
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
327
+ //
328
+ // TODO: we may want to handle the case where the header is using the http-date syntax: "Retry-After: <http-date>".
329
+ // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax for details.
330
+ const retryAfter = parseInt(responseHeaders?.['retry-after'] || '');
331
+
332
+ const maxRetries = options.maxRetries ?? this.maxRetries;
333
+ const timeout = this.calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) * 1000;
334
+ await sleep(timeout);
335
+
336
+ return this.request(options, retriesRemaining);
337
+ }
338
+
339
+ private calculateRetryTimeoutSeconds(
340
+ retriesRemaining: number,
341
+ retryAfter: number,
342
+ maxRetries: number,
343
+ ): number {
344
+ const initialRetryDelay = 0.5;
345
+ const maxRetryDelay = 2;
346
+
347
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
348
+ // just do what it says.
349
+ if (Number.isInteger(retryAfter) && retryAfter <= 60) {
350
+ return retryAfter;
351
+ }
352
+
353
+ const numRetries = maxRetries - retriesRemaining;
354
+
355
+ // Apply exponential backoff, but not more than the max.
356
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(numRetries - 1, 2), maxRetryDelay);
357
+
358
+ // Apply some jitter, plus-or-minus half a second.
359
+ const jitter = Math.random() - 0.5;
360
+
361
+ return sleepSeconds + jitter;
362
+ }
363
+
364
+ private getUserAgent(): string {
365
+ return `${this.constructor.name}/JS ${VERSION}`;
366
+ }
367
+
368
+ private debug(action: string, ...args: any[]) {
369
+ if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
370
+ console.log(`${this.constructor.name}:DEBUG:${action}`, ...args);
371
+ }
372
+ }
373
+ }
374
+
375
+ export class APIResource {
376
+ protected client: APIClient;
377
+ constructor(client: APIClient) {
378
+ this.client = client;
379
+
380
+ this.get = client.get.bind(client);
381
+ this.post = client.post.bind(client);
382
+ this.patch = client.patch.bind(client);
383
+ this.put = client.put.bind(client);
384
+ this.delete = client.delete.bind(client);
385
+ this.getAPIList = client.getAPIList.bind(client);
386
+ }
387
+
388
+ protected get: APIClient['get'];
389
+ protected post: APIClient['post'];
390
+ protected patch: APIClient['patch'];
391
+ protected put: APIClient['put'];
392
+ protected delete: APIClient['delete'];
393
+ protected getAPIList: APIClient['getAPIList'];
394
+ }
395
+
396
+ export type PageInfo = { url: URL } | { params: Record<string, unknown> | null };
397
+
398
+ export abstract class AbstractPage<Item> implements AsyncIterable<Item> {
399
+ #client: APIClient;
400
+ protected options: FinalRequestOptions;
401
+
402
+ constructor(client: APIClient, response: APIResponse<unknown>, options: FinalRequestOptions) {
403
+ this.#client = client;
404
+ this.options = options;
405
+ }
406
+
407
+ /**
408
+ * @deprecated Use nextPageInfo instead
409
+ */
410
+ abstract nextPageParams(): Partial<Record<string, unknown>> | null;
411
+ abstract nextPageInfo(): PageInfo | null;
412
+
413
+ abstract getPaginatedItems(): Item[];
414
+
415
+ hasNextPage(): boolean {
416
+ const items = this.getPaginatedItems();
417
+ if (!items.length) return false;
418
+ return this.nextPageInfo() != null;
419
+ }
420
+
421
+ async getNextPage(): Promise<AbstractPage<Item>> {
422
+ const nextInfo = this.nextPageInfo();
423
+ if (!nextInfo) {
424
+ throw new Error(
425
+ 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.',
426
+ );
427
+ }
428
+ const nextOptions = { ...this.options };
429
+ if ('params' in nextInfo) {
430
+ nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
431
+ } else if ('url' in nextInfo) {
432
+ const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
433
+ for (const [key, value] of params) {
434
+ nextInfo.url.searchParams.set(key, value);
435
+ }
436
+ nextOptions.query = undefined;
437
+ nextOptions.path = nextInfo.url.toString();
438
+ }
439
+ return await this.#client.requestAPIList(this.constructor as any, nextOptions);
440
+ }
441
+
442
+ async *iterPages() {
443
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
444
+ let page: AbstractPage<Item> = this;
445
+ yield page;
446
+ while (page.hasNextPage()) {
447
+ page = await page.getNextPage();
448
+ yield page;
449
+ }
450
+ }
451
+
452
+ async *[Symbol.asyncIterator]() {
453
+ for await (const page of this.iterPages()) {
454
+ for (const item of page.getPaginatedItems()) {
455
+ yield item;
456
+ }
457
+ }
458
+ }
459
+ }
460
+
461
+ export class PagePromise<
462
+ PageClass extends AbstractPage<Item>,
463
+ Item = ReturnType<PageClass['getPaginatedItems']>[number],
464
+ >
465
+ extends Promise<PageClass>
466
+ implements AsyncIterable<Item>
467
+ {
468
+ /**
469
+ * This subclass of Promise will resolve to an instantiated Page once the request completes.
470
+ */
471
+ constructor(
472
+ client: APIClient,
473
+ requestPromise: Promise<APIResponse<unknown>>,
474
+ options: FinalRequestOptions,
475
+ Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,
476
+ ) {
477
+ super((resolve, reject) =>
478
+ requestPromise.then((response) => resolve(new Page(client, response, options))).catch(reject),
479
+ );
480
+ }
481
+
482
+ /**
483
+ * Enable subclassing Promise.
484
+ * Ref: https://stackoverflow.com/a/60328122
485
+ */
486
+ static get [Symbol.species]() {
487
+ return Promise;
488
+ }
489
+
490
+ /**
491
+ * Allow auto-paginating iteration on an unawaited list call, eg:
492
+ *
493
+ * for await (const item of client.items.list()) {
494
+ * console.log(item)
495
+ * }
496
+ */
497
+ async *[Symbol.asyncIterator]() {
498
+ const page = await this;
499
+ for await (const item of page) {
500
+ yield item;
501
+ }
502
+ }
503
+ }
504
+
505
+ export const createResponseHeaders = (
506
+ headers: Awaited<ReturnType<Fetch>>['headers'],
507
+ ): Record<string, string> => {
508
+ return new Proxy(
509
+ Object.fromEntries(
510
+ // @ts-ignore
511
+ headers.entries(),
512
+ ),
513
+ {
514
+ get(target, name) {
515
+ const key = name.toString();
516
+ return target[key.toLowerCase()] || target[key];
517
+ },
518
+ },
519
+ );
520
+ };
521
+
522
+ type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';
523
+
524
+ export type RequestClient = { fetch: Fetch };
525
+ export type Headers = Record<string, string | null | undefined>;
526
+ export type DefaultQuery = Record<string, string | undefined>;
527
+ export type KeysEnum<T> = { [P in keyof Required<T>]: true };
528
+
529
+ export type RequestOptions<Req extends {} = Record<string, unknown> | Readable> = {
530
+ method?: HTTPMethod;
531
+ path?: string;
532
+ query?: Req | undefined;
533
+ body?: Req | undefined;
534
+ headers?: Headers | undefined;
535
+
536
+ maxRetries?: number;
537
+ stream?: boolean | undefined;
538
+ timeout?: number;
539
+ httpAgent?: Agent;
540
+ idempotencyKey?: string;
541
+ };
542
+
543
+ // This is required so that we can determine if a given object matches the RequestOptions
544
+ // type at runtime. While this requires duplication, it is enforced by the TypeScript
545
+ // compiler such that any missing / extraneous keys will cause an error.
546
+ const requestOptionsKeys: KeysEnum<RequestOptions> = {
547
+ method: true,
548
+ path: true,
549
+ query: true,
550
+ body: true,
551
+ headers: true,
552
+
553
+ maxRetries: true,
554
+ stream: true,
555
+ timeout: true,
556
+ httpAgent: true,
557
+ idempotencyKey: true,
558
+ };
559
+
560
+ export const isRequestOptions = (obj: unknown): obj is RequestOptions => {
561
+ return (
562
+ typeof obj === 'object' &&
563
+ obj !== null &&
564
+ !isEmptyObj(obj) &&
565
+ Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))
566
+ );
567
+ };
568
+
569
+ export type FinalRequestOptions<Req extends {} = Record<string, unknown> | Readable> = RequestOptions<Req> & {
570
+ method: HTTPMethod;
571
+ path: string;
572
+ };
573
+
574
+ export type APIResponse<T> = T & {
575
+ /** @deprecated - we plan to add a different way to access raw response information shortly. */
576
+ responseHeaders: Headers;
577
+ };
578
+
579
+ declare const Deno: any;
580
+ declare const EdgeRuntime: any;
581
+ type Arch = 'x32' | 'x64' | 'arm' | 'arm64' | `other:${string}` | 'unknown';
582
+ type PlatformName =
583
+ | 'MacOS'
584
+ | 'Linux'
585
+ | 'Windows'
586
+ | 'FreeBSD'
587
+ | 'OpenBSD'
588
+ | 'iOS'
589
+ | 'Android'
590
+ | `Other:${string}`
591
+ | 'Unknown';
592
+ type PlatformProperties = {
593
+ 'X-Stainless-Lang': 'js';
594
+ 'X-Stainless-Package-Version': string;
595
+ 'X-Stainless-OS': PlatformName;
596
+ 'X-Stainless-Arch': Arch;
597
+ 'X-Stainless-Runtime': 'node' | 'deno' | 'edge' | 'unknown';
598
+ 'X-Stainless-Runtime-Version': string;
599
+ };
600
+ const getPlatformProperties = (): PlatformProperties => {
601
+ if (typeof Deno !== 'undefined' && Deno.build != null) {
602
+ return {
603
+ 'X-Stainless-Lang': 'js',
604
+ 'X-Stainless-Package-Version': VERSION,
605
+ 'X-Stainless-OS': normalizePlatform(Deno.build.os),
606
+ 'X-Stainless-Arch': normalizeArch(Deno.build.arch),
607
+ 'X-Stainless-Runtime': 'deno',
608
+ 'X-Stainless-Runtime-Version': Deno.version,
609
+ };
610
+ }
611
+ if (typeof EdgeRuntime !== 'undefined') {
612
+ return {
613
+ 'X-Stainless-Lang': 'js',
614
+ 'X-Stainless-Package-Version': VERSION,
615
+ 'X-Stainless-OS': 'Unknown',
616
+ 'X-Stainless-Arch': `other:${EdgeRuntime}`,
617
+ 'X-Stainless-Runtime': 'edge',
618
+ 'X-Stainless-Runtime-Version': process.version,
619
+ };
620
+ }
621
+ // Check if Node.js
622
+ if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {
623
+ return {
624
+ 'X-Stainless-Lang': 'js',
625
+ 'X-Stainless-Package-Version': VERSION,
626
+ 'X-Stainless-OS': normalizePlatform(process.platform),
627
+ 'X-Stainless-Arch': normalizeArch(process.arch),
628
+ 'X-Stainless-Runtime': 'node',
629
+ 'X-Stainless-Runtime-Version': process.version,
630
+ };
631
+ }
632
+ // TODO add support for Cloudflare workers, browsers, etc.
633
+ return {
634
+ 'X-Stainless-Lang': 'js',
635
+ 'X-Stainless-Package-Version': VERSION,
636
+ 'X-Stainless-OS': 'Unknown',
637
+ 'X-Stainless-Arch': 'unknown',
638
+ 'X-Stainless-Runtime': 'unknown',
639
+ 'X-Stainless-Runtime-Version': 'unknown',
640
+ };
641
+ };
642
+
643
+ const normalizeArch = (arch: string): Arch => {
644
+ // Node docs:
645
+ // - https://nodejs.org/api/process.html#processarch
646
+ // Deno docs:
647
+ // - https://doc.deno.land/deno/stable/~/Deno.build
648
+ if (arch === 'x32') return 'x32';
649
+ if (arch === 'x86_64' || arch === 'x64') return 'x64';
650
+ if (arch === 'arm') return 'arm';
651
+ if (arch === 'aarch64' || arch === 'arm64') return 'arm64';
652
+ if (arch) return `other:${arch}`;
653
+ return 'unknown';
654
+ };
655
+
656
+ const normalizePlatform = (platform: string): PlatformName => {
657
+ // Node platforms:
658
+ // - https://nodejs.org/api/process.html#processplatform
659
+ // Deno platforms:
660
+ // - https://doc.deno.land/deno/stable/~/Deno.build
661
+ // - https://github.com/denoland/deno/issues/14799
662
+
663
+ platform = platform.toLowerCase();
664
+
665
+ // NOTE: this iOS check is untested and may not work
666
+ // Node does not work natively on IOS, there is a fork at
667
+ // https://github.com/nodejs-mobile/nodejs-mobile
668
+ // however it is unknown at the time of writing how to detect if it is running
669
+ if (platform.includes('ios')) return 'iOS';
670
+ if (platform === 'android') return 'Android';
671
+ if (platform === 'darwin') return 'MacOS';
672
+ if (platform === 'win32') return 'Windows';
673
+ if (platform === 'freebsd') return 'FreeBSD';
674
+ if (platform === 'openbsd') return 'OpenBSD';
675
+ if (platform === 'linux') return 'Linux';
676
+ if (platform) return `Other:${platform}`;
677
+ return 'Unknown';
678
+ };
679
+
680
+ let _platformHeaders: PlatformProperties;
681
+ const getPlatformHeaders = () => {
682
+ return (_platformHeaders ??= getPlatformProperties());
683
+ };
684
+
685
+ export const safeJSON = (text: string) => {
686
+ try {
687
+ return JSON.parse(text);
688
+ } catch (err) {
689
+ return undefined;
690
+ }
691
+ };
692
+
693
+ // https://stackoverflow.com/a/19709846
694
+ const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i');
695
+ const isAbsoluteURL = (url: string): boolean => {
696
+ return startsWithSchemeRegexp.test(url);
697
+ };
698
+
699
+ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
700
+
701
+ const validatePositiveInteger = (name: string, n: number) => {
702
+ if (!Number.isInteger(n)) {
703
+ throw new Error(`${name} must be an integer`);
704
+ }
705
+ if (n < 0) {
706
+ throw new Error(`${name} must be a positive integer`);
707
+ }
708
+ return n;
709
+ };
710
+
711
+ export const castToError = (err: any): Error => {
712
+ if (err instanceof Error) return err;
713
+ return new Error(err);
714
+ };
715
+
716
+ export const ensurePresent = <T>(value: T | null | undefined): T => {
717
+ if (value == null) throw new Error(`Expected a value to be given but received ${value} instead.`);
718
+ return value;
719
+ };
720
+
721
+ export const coerceInteger = (value: unknown): number => {
722
+ if (typeof value === 'number') return Math.round(value);
723
+ if (typeof value === 'string') return parseInt(value, 10);
724
+
725
+ throw new Error(`Could not coerce ${value} (type: ${typeof value}) into a number`);
726
+ };
727
+
728
+ export const coerceFloat = (value: unknown): number => {
729
+ if (typeof value === 'number') return value;
730
+ if (typeof value === 'string') return parseFloat(value);
731
+
732
+ throw new Error(`Could not coerce ${value} (type: ${typeof value}) into a number`);
733
+ };
734
+
735
+ export const coerceBoolean = (value: unknown): boolean => {
736
+ if (typeof value === 'boolean') return value;
737
+ if (typeof value === 'string') return value === 'true';
738
+ return Boolean(value);
739
+ };
740
+
741
+ // https://stackoverflow.com/a/34491287
742
+ export function isEmptyObj(obj: Object | null | undefined): boolean {
743
+ if (!obj) return true;
744
+ for (const _k in obj) return false;
745
+ return true;
746
+ }
747
+
748
+ // https://eslint.org/docs/latest/rules/no-prototype-builtins
749
+ export function hasOwn(obj: Object, key: string): boolean {
750
+ return Object.prototype.hasOwnProperty.call(obj, key);
751
+ }
752
+
753
+ /**
754
+ * https://stackoverflow.com/a/2117523
755
+ */
756
+ const uuid4 = () => {
757
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
758
+ const r = (Math.random() * 16) | 0;
759
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
760
+ return v.toString(16);
761
+ });
762
+ };
763
+
764
+ export interface HeadersProtocol {
765
+ get: (header: string) => string | null | undefined;
766
+ }
767
+ export type HeadersLike = Record<string, string | string[] | undefined> | HeadersProtocol;
768
+
769
+ export const isHeadersProtocol = (headers: any): headers is HeadersProtocol => {
770
+ return typeof headers?.get === 'function';
771
+ };
772
+
773
+ export const getHeader = (headers: HeadersLike, key: string): string | null | undefined => {
774
+ const lowerKey = key.toLowerCase();
775
+ if (isHeadersProtocol(headers)) return headers.get(key) || headers.get(lowerKey);
776
+ const value = headers[key] || headers[lowerKey];
777
+ if (Array.isArray(value)) {
778
+ if (value.length <= 1) return value[0];
779
+ console.warn(`Received ${value.length} entries for the ${key} header, using the first entry.`);
780
+ return value[0];
781
+ }
782
+ return value;
783
+ };