@anthropic-ai/sdk 0.6.2 → 0.6.7
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/CHANGELOG.md +109 -0
- package/README.md +16 -6
- package/_shims/MultipartBody.d.ts +9 -0
- package/_shims/MultipartBody.d.ts.map +1 -0
- package/_shims/MultipartBody.js +16 -0
- package/_shims/MultipartBody.js.map +1 -0
- package/_shims/MultipartBody.mjs +12 -0
- package/_shims/MultipartBody.mjs.map +1 -0
- package/_shims/README.md +46 -0
- package/{src/_shims/ReadableStream.node.ts → _shims/auto/runtime-bun.d.ts} +2 -3
- package/_shims/auto/runtime-bun.d.ts.map +1 -0
- package/_shims/auto/runtime-bun.js +21 -0
- package/_shims/auto/runtime-bun.js.map +1 -0
- package/_shims/auto/runtime-bun.mjs +2 -0
- package/_shims/auto/runtime-bun.mjs.map +1 -0
- package/_shims/auto/runtime-node.d.ts +5 -0
- package/_shims/auto/runtime-node.d.ts.map +1 -0
- package/_shims/auto/runtime-node.js +21 -0
- package/_shims/auto/runtime-node.js.map +1 -0
- package/_shims/auto/runtime-node.mjs +2 -0
- package/_shims/auto/runtime-node.mjs.map +1 -0
- package/_shims/auto/runtime.d.ts +5 -0
- package/_shims/auto/runtime.d.ts.map +1 -0
- package/_shims/auto/runtime.js +21 -0
- package/_shims/auto/runtime.js.map +1 -0
- package/_shims/auto/runtime.mjs +2 -0
- package/_shims/auto/runtime.mjs.map +1 -0
- package/_shims/auto/types-node.d.ts +5 -0
- package/_shims/auto/types-node.d.ts.map +1 -0
- package/_shims/auto/types-node.js +21 -0
- package/_shims/auto/types-node.js.map +1 -0
- package/_shims/auto/types-node.mjs +2 -0
- package/_shims/auto/types-node.mjs.map +1 -0
- package/_shims/auto/types.d.ts +101 -0
- package/{src/_shims/ReadableStream.js → _shims/auto/types.js} +0 -2
- package/_shims/{ReadableStream.js → auto/types.mjs} +0 -2
- package/_shims/bun-runtime.d.ts +6 -0
- package/_shims/bun-runtime.d.ts.map +1 -0
- package/_shims/bun-runtime.js +14 -0
- package/_shims/bun-runtime.js.map +1 -0
- package/_shims/bun-runtime.mjs +10 -0
- package/_shims/bun-runtime.mjs.map +1 -0
- package/_shims/index.d.ts +81 -0
- package/_shims/index.js +13 -0
- package/_shims/index.mjs +7 -0
- package/_shims/manual-types.d.ts +12 -0
- package/_shims/manual-types.js +3 -0
- package/_shims/manual-types.mjs +3 -0
- package/_shims/node-runtime.d.ts +3 -0
- package/_shims/node-runtime.d.ts.map +1 -0
- package/_shims/node-runtime.js +89 -0
- package/_shims/node-runtime.js.map +1 -0
- package/_shims/node-runtime.mjs +56 -0
- package/_shims/node-runtime.mjs.map +1 -0
- package/_shims/node-types.d.ts +42 -0
- package/_shims/node-types.js +3 -0
- package/_shims/node-types.mjs +3 -0
- package/_shims/registry.d.ts +37 -0
- package/_shims/registry.d.ts.map +1 -0
- package/_shims/registry.js +41 -0
- package/_shims/registry.js.map +1 -0
- package/_shims/registry.mjs +37 -0
- package/_shims/registry.mjs.map +1 -0
- package/_shims/web-runtime.d.ts +5 -0
- package/_shims/web-runtime.d.ts.map +1 -0
- package/_shims/web-runtime.js +78 -0
- package/_shims/web-runtime.js.map +1 -0
- package/_shims/web-runtime.mjs +71 -0
- package/_shims/web-runtime.mjs.map +1 -0
- package/_shims/web-types.d.ts +83 -0
- package/_shims/web-types.js +3 -0
- package/_shims/web-types.mjs +3 -0
- package/core.d.ts +172 -224
- package/core.d.ts.map +1 -1
- package/core.js +701 -736
- package/core.js.map +1 -1
- package/core.mjs +694 -688
- package/core.mjs.map +1 -1
- package/error.d.ts +32 -32
- package/error.d.ts.map +1 -1
- package/error.js +105 -106
- package/error.js.map +1 -1
- package/error.mjs +101 -91
- package/error.mjs.map +1 -1
- package/index.d.mts +110 -117
- package/index.d.ts +110 -117
- package/index.d.ts.map +1 -1
- package/index.js +107 -159
- package/index.js.map +1 -1
- package/index.mjs +84 -104
- package/index.mjs.map +1 -1
- package/package.json +36 -21
- package/resource.d.ts +10 -10
- package/resource.js +12 -12
- package/resource.mjs +10 -10
- package/resources/completions.d.ts +136 -142
- package/resources/completions.d.ts.map +1 -1
- package/resources/completions.js +9 -14
- package/resources/completions.js.map +1 -1
- package/resources/completions.mjs +6 -11
- package/resources/completions.mjs.map +1 -1
- package/resources/index.d.ts +2 -9
- package/resources/index.d.ts.map +1 -1
- package/resources/index.js +5 -10
- package/resources/index.js.map +1 -1
- package/resources/index.mjs +2 -2
- package/resources/index.mjs.map +1 -1
- package/resources/top-level.d.ts +1 -1
- package/resources/top-level.js +3 -3
- package/resources/top-level.mjs +1 -1
- package/shims/node.d.ts +29 -0
- package/shims/node.d.ts.map +1 -0
- package/shims/node.js +31 -0
- package/shims/node.js.map +1 -0
- package/shims/node.mjs +5 -0
- package/shims/node.mjs.map +1 -0
- package/shims/web.d.ts +26 -0
- package/shims/web.d.ts.map +1 -0
- package/shims/web.js +31 -0
- package/shims/web.js.map +1 -0
- package/shims/web.mjs +5 -0
- package/shims/web.mjs.map +1 -0
- package/src/_shims/MultipartBody.ts +9 -0
- package/src/_shims/README.md +46 -0
- package/src/_shims/auto/runtime-bun.ts +4 -0
- package/src/_shims/auto/runtime-node.ts +4 -0
- package/src/_shims/auto/runtime.ts +4 -0
- package/src/_shims/auto/types-node.ts +4 -0
- package/src/_shims/auto/types.d.ts +101 -0
- package/src/_shims/auto/types.js +3 -0
- package/src/_shims/auto/types.mjs +3 -0
- package/src/_shims/bun-runtime.ts +14 -0
- package/src/_shims/index.d.ts +81 -0
- package/src/_shims/index.js +13 -0
- package/src/_shims/index.mjs +7 -0
- package/src/_shims/manual-types.d.ts +12 -0
- package/src/_shims/manual-types.js +3 -0
- package/src/_shims/manual-types.mjs +3 -0
- package/src/_shims/node-runtime.ts +81 -0
- package/src/_shims/node-types.d.ts +42 -0
- package/src/_shims/node-types.js +3 -0
- package/src/_shims/node-types.mjs +3 -0
- package/src/_shims/registry.ts +67 -0
- package/src/_shims/web-runtime.ts +103 -0
- package/src/_shims/web-types.d.ts +83 -0
- package/src/_shims/web-types.js +3 -0
- package/src/_shims/web-types.mjs +3 -0
- package/src/core.ts +107 -56
- package/src/error.ts +20 -8
- package/src/index.ts +24 -17
- package/src/resources/completions.ts +11 -11
- package/src/resources/index.ts +0 -1
- package/src/shims/node.ts +50 -0
- package/src/shims/web.ts +50 -0
- package/src/streaming.ts +164 -59
- package/src/tsconfig.json +11 -0
- package/src/uploads.ts +11 -15
- package/src/version.ts +1 -1
- package/streaming.d.ts +11 -8
- package/streaming.d.ts.map +1 -1
- package/streaming.js +300 -192
- package/streaming.js.map +1 -1
- package/streaming.mjs +296 -188
- package/streaming.mjs.map +1 -1
- package/uploads.d.ts +23 -39
- package/uploads.d.ts.map +1 -1
- package/uploads.js +111 -157
- package/uploads.js.map +1 -1
- package/uploads.mjs +107 -133
- package/uploads.mjs.map +1 -1
- package/version.d.ts +2 -2
- package/version.js +4 -4
- package/version.mjs +2 -2
- package/_shims/ReadableStream.d.ts +0 -38
- package/_shims/ReadableStream.mjs +0 -7
- package/_shims/ReadableStream.node.d.ts +0 -6
- package/_shims/ReadableStream.node.d.ts.map +0 -1
- package/_shims/ReadableStream.node.js +0 -14
- package/_shims/ReadableStream.node.js.map +0 -1
- package/_shims/ReadableStream.node.mjs +0 -3
- package/_shims/ReadableStream.node.mjs.map +0 -1
- package/_shims/agent.d.ts +0 -9
- package/_shims/agent.d.ts.map +0 -1
- package/_shims/agent.js +0 -14
- package/_shims/agent.js.map +0 -1
- package/_shims/agent.mjs +0 -10
- package/_shims/agent.mjs.map +0 -1
- package/_shims/agent.node.d.ts +0 -7
- package/_shims/agent.node.d.ts.map +0 -1
- package/_shims/agent.node.js +0 -28
- package/_shims/agent.node.js.map +0 -1
- package/_shims/agent.node.mjs +0 -16
- package/_shims/agent.node.mjs.map +0 -1
- package/_shims/fetch.d.ts +0 -60
- package/_shims/fetch.js +0 -13
- package/_shims/fetch.mjs +0 -15
- package/_shims/fetch.node.d.ts +0 -64
- package/_shims/fetch.node.js +0 -12
- package/_shims/fetch.node.mjs +0 -14
- package/_shims/fileFromPath.d.ts +0 -22
- package/_shims/fileFromPath.d.ts.map +0 -1
- package/_shims/fileFromPath.js +0 -16
- package/_shims/fileFromPath.js.map +0 -1
- package/_shims/fileFromPath.mjs +0 -12
- package/_shims/fileFromPath.mjs.map +0 -1
- package/_shims/fileFromPath.node.d.ts +0 -17
- package/_shims/fileFromPath.node.d.ts.map +0 -1
- package/_shims/fileFromPath.node.js +0 -17
- package/_shims/fileFromPath.node.js.map +0 -1
- package/_shims/fileFromPath.node.mjs +0 -13
- package/_shims/fileFromPath.node.mjs.map +0 -1
- package/_shims/formdata.d.ts +0 -43
- package/_shims/formdata.js +0 -17
- package/_shims/formdata.mjs +0 -20
- package/_shims/formdata.node.d.ts +0 -45
- package/_shims/formdata.node.js +0 -11
- package/_shims/formdata.node.mjs +0 -9
- package/_shims/getMultipartRequestOptions.d.ts +0 -10
- package/_shims/getMultipartRequestOptions.d.ts.map +0 -1
- package/_shims/getMultipartRequestOptions.js +0 -12
- package/_shims/getMultipartRequestOptions.js.map +0 -1
- package/_shims/getMultipartRequestOptions.mjs +0 -8
- package/_shims/getMultipartRequestOptions.mjs.map +0 -1
- package/_shims/getMultipartRequestOptions.node.d.ts +0 -10
- package/_shims/getMultipartRequestOptions.node.d.ts.map +0 -1
- package/_shims/getMultipartRequestOptions.node.js +0 -22
- package/_shims/getMultipartRequestOptions.node.js.map +0 -1
- package/_shims/getMultipartRequestOptions.node.mjs +0 -18
- package/_shims/getMultipartRequestOptions.node.mjs.map +0 -1
- package/_shims/node-readable.d.ts +0 -23
- package/_shims/node-readable.d.ts.map +0 -1
- package/_shims/node-readable.js +0 -11
- package/_shims/node-readable.js.map +0 -1
- package/_shims/node-readable.mjs +0 -7
- package/_shims/node-readable.mjs.map +0 -1
- package/_shims/node-readable.node.d.ts +0 -8
- package/_shims/node-readable.node.d.ts.map +0 -1
- package/_shims/node-readable.node.js +0 -9
- package/_shims/node-readable.node.js.map +0 -1
- package/_shims/node-readable.node.mjs +0 -5
- package/_shims/node-readable.node.mjs.map +0 -1
- package/src/_shims/ReadableStream.d.ts +0 -38
- package/src/_shims/ReadableStream.mjs +0 -7
- package/src/_shims/agent.node.ts +0 -22
- package/src/_shims/agent.ts +0 -12
- package/src/_shims/fetch.d.ts +0 -60
- package/src/_shims/fetch.deno.ts +0 -23
- package/src/_shims/fetch.js +0 -13
- package/src/_shims/fetch.mjs +0 -15
- package/src/_shims/fetch.node.d.ts +0 -64
- package/src/_shims/fetch.node.js +0 -12
- package/src/_shims/fetch.node.mjs +0 -14
- package/src/_shims/fileFromPath.node.ts +0 -29
- package/src/_shims/fileFromPath.ts +0 -29
- package/src/_shims/formdata.d.ts +0 -43
- package/src/_shims/formdata.deno.ts +0 -16
- package/src/_shims/formdata.js +0 -17
- package/src/_shims/formdata.mjs +0 -20
- package/src/_shims/formdata.node.d.ts +0 -45
- package/src/_shims/formdata.node.js +0 -11
- package/src/_shims/formdata.node.mjs +0 -9
- package/src/_shims/getMultipartRequestOptions.node.ts +0 -25
- package/src/_shims/getMultipartRequestOptions.ts +0 -14
- package/src/_shims/node-readable.node.ts +0 -10
- package/src/_shims/node-readable.ts +0 -30
package/core.mjs
CHANGED
|
@@ -1,469 +1,452 @@
|
|
|
1
|
-
var __classPrivateFieldSet =
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
if (
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
value
|
|
13
|
-
);
|
|
14
|
-
};
|
|
15
|
-
var __classPrivateFieldGet =
|
|
16
|
-
(this && this.__classPrivateFieldGet) ||
|
|
17
|
-
function (receiver, state, kind, f) {
|
|
18
|
-
if (kind === 'a' && !f) throw new TypeError('Private accessor was defined without a getter');
|
|
19
|
-
if (typeof state === 'function' ? receiver !== state || !f : !state.has(receiver))
|
|
20
|
-
throw new TypeError('Cannot read private member from an object whose class did not declare it');
|
|
21
|
-
return (
|
|
22
|
-
kind === 'm' ? f
|
|
23
|
-
: kind === 'a' ? f.call(receiver)
|
|
24
|
-
: f ? f.value
|
|
25
|
-
: state.get(receiver)
|
|
26
|
-
);
|
|
27
|
-
};
|
|
1
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
2
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
3
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
4
|
+
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");
|
|
5
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
6
|
+
};
|
|
7
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
8
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
9
|
+
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");
|
|
10
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
|
+
};
|
|
28
12
|
var _AbstractPage_client;
|
|
29
|
-
import { VERSION } from
|
|
30
|
-
import { Stream } from
|
|
31
|
-
import { APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError } from
|
|
32
|
-
import { getDefaultAgent } from
|
|
33
|
-
import {
|
|
34
|
-
|
|
35
|
-
export { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm } from './uploads.mjs';
|
|
13
|
+
import { VERSION } from "./version.mjs";
|
|
14
|
+
import { Stream } from "./streaming.mjs";
|
|
15
|
+
import { AnthropicError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, } from "./error.mjs";
|
|
16
|
+
import { kind as shimsKind, getDefaultAgent, fetch, } from "./_shims/index.mjs";
|
|
17
|
+
import { isMultipartBody } from "./uploads.mjs";
|
|
18
|
+
export { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm, } from "./uploads.mjs";
|
|
36
19
|
const MAX_RETRIES = 2;
|
|
37
20
|
async function defaultParseResponse(props) {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
21
|
+
const { response } = props;
|
|
22
|
+
if (props.options.stream) {
|
|
23
|
+
debug('response', response.status, response.url, response.headers, response.body);
|
|
24
|
+
// Note: there is an invariant here that isn't represented in the type system
|
|
25
|
+
// that if you set `stream: true` the response type must also be `Stream<T>`
|
|
26
|
+
return Stream.fromSSEResponse(response, props.controller);
|
|
27
|
+
}
|
|
28
|
+
const contentType = response.headers.get('content-type');
|
|
29
|
+
if (contentType?.includes('application/json')) {
|
|
30
|
+
const json = await response.json();
|
|
31
|
+
debug('response', response.status, response.url, response.headers, json);
|
|
32
|
+
return json;
|
|
33
|
+
}
|
|
34
|
+
// TODO handle blob, arraybuffer, other content types, etc.
|
|
35
|
+
const text = await response.text();
|
|
36
|
+
debug('response', response.status, response.url, response.headers, text);
|
|
37
|
+
return text;
|
|
54
38
|
}
|
|
55
39
|
/**
|
|
56
40
|
* A subclass of `Promise` providing additional helper methods
|
|
57
41
|
* for interacting with the SDK.
|
|
58
42
|
*/
|
|
59
43
|
export class APIPromise extends Promise {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
44
|
+
constructor(responsePromise, parseResponse = defaultParseResponse) {
|
|
45
|
+
super((resolve) => {
|
|
46
|
+
// this is maybe a bit weird but this has to be a no-op to not implicitly
|
|
47
|
+
// parse the response body; instead .then, .catch, .finally are overridden
|
|
48
|
+
// to parse the response
|
|
49
|
+
resolve(null);
|
|
50
|
+
});
|
|
51
|
+
this.responsePromise = responsePromise;
|
|
52
|
+
this.parseResponse = parseResponse;
|
|
53
|
+
}
|
|
54
|
+
_thenUnwrap(transform) {
|
|
55
|
+
return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props)));
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Gets the raw `Response` instance instead of parsing the response
|
|
59
|
+
* data.
|
|
60
|
+
*
|
|
61
|
+
* If you want to parse the response body but still get the `Response`
|
|
62
|
+
* instance, you can use {@link withResponse()}.
|
|
63
|
+
*
|
|
64
|
+
* 👋 Getting the wrong TypeScript type for `Response`?
|
|
65
|
+
* Try setting `"moduleResolution": "NodeNext"` if you can,
|
|
66
|
+
* or add one of these imports before your first `import … from '@anthropic-ai/sdk'`:
|
|
67
|
+
* - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)
|
|
68
|
+
* - `import '@anthropic-ai/sdk/shims/web'` (otherwise)
|
|
69
|
+
*/
|
|
70
|
+
asResponse() {
|
|
71
|
+
return this.responsePromise.then((p) => p.response);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Gets the parsed response data and the raw `Response` instance.
|
|
75
|
+
*
|
|
76
|
+
* If you just want to get the raw `Response` instance without parsing it,
|
|
77
|
+
* you can use {@link asResponse()}.
|
|
78
|
+
*
|
|
79
|
+
*
|
|
80
|
+
* 👋 Getting the wrong TypeScript type for `Response`?
|
|
81
|
+
* Try setting `"moduleResolution": "NodeNext"` if you can,
|
|
82
|
+
* or add one of these imports before your first `import … from '@anthropic-ai/sdk'`:
|
|
83
|
+
* - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)
|
|
84
|
+
* - `import '@anthropic-ai/sdk/shims/web'` (otherwise)
|
|
85
|
+
*/
|
|
86
|
+
async withResponse() {
|
|
87
|
+
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
|
|
88
|
+
return { data, response };
|
|
89
|
+
}
|
|
90
|
+
parse() {
|
|
91
|
+
if (!this.parsedPromise) {
|
|
92
|
+
this.parsedPromise = this.responsePromise.then(this.parseResponse);
|
|
93
|
+
}
|
|
94
|
+
return this.parsedPromise;
|
|
95
|
+
}
|
|
96
|
+
then(onfulfilled, onrejected) {
|
|
97
|
+
return this.parse().then(onfulfilled, onrejected);
|
|
98
|
+
}
|
|
99
|
+
catch(onrejected) {
|
|
100
|
+
return this.parse().catch(onrejected);
|
|
101
|
+
}
|
|
102
|
+
finally(onfinally) {
|
|
103
|
+
return this.parse().finally(onfinally);
|
|
104
|
+
}
|
|
108
105
|
}
|
|
109
106
|
export class APIClient {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
this.baseURL = baseURL;
|
|
118
|
-
this.maxRetries = validatePositiveInteger(
|
|
119
|
-
'maxRetries',
|
|
120
|
-
maxRetries !== null && maxRetries !== void 0 ? maxRetries : MAX_RETRIES,
|
|
121
|
-
);
|
|
122
|
-
this.timeout = validatePositiveInteger('timeout', timeout);
|
|
123
|
-
this.httpAgent = httpAgent;
|
|
124
|
-
this.fetch = overridenFetch !== null && overridenFetch !== void 0 ? overridenFetch : fetch;
|
|
125
|
-
}
|
|
126
|
-
authHeaders(opts) {
|
|
127
|
-
return {};
|
|
128
|
-
}
|
|
129
|
-
/**
|
|
130
|
-
* Override this to add your own default headers, for example:
|
|
131
|
-
*
|
|
132
|
-
* {
|
|
133
|
-
* ...super.defaultHeaders(),
|
|
134
|
-
* Authorization: 'Bearer 123',
|
|
135
|
-
* }
|
|
136
|
-
*/
|
|
137
|
-
defaultHeaders(opts) {
|
|
138
|
-
return {
|
|
139
|
-
Accept: 'application/json',
|
|
140
|
-
'Content-Type': 'application/json',
|
|
141
|
-
'User-Agent': this.getUserAgent(),
|
|
142
|
-
...getPlatformHeaders(),
|
|
143
|
-
...this.authHeaders(opts),
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
/**
|
|
147
|
-
* Override this to add your own headers validation:
|
|
148
|
-
*/
|
|
149
|
-
validateHeaders(headers, customHeaders) {}
|
|
150
|
-
defaultIdempotencyKey() {
|
|
151
|
-
return `stainless-node-retry-${uuid4()}`;
|
|
152
|
-
}
|
|
153
|
-
get(path, opts) {
|
|
154
|
-
return this.methodRequest('get', path, opts);
|
|
155
|
-
}
|
|
156
|
-
post(path, opts) {
|
|
157
|
-
return this.methodRequest('post', path, opts);
|
|
158
|
-
}
|
|
159
|
-
patch(path, opts) {
|
|
160
|
-
return this.methodRequest('patch', path, opts);
|
|
161
|
-
}
|
|
162
|
-
put(path, opts) {
|
|
163
|
-
return this.methodRequest('put', path, opts);
|
|
164
|
-
}
|
|
165
|
-
delete(path, opts) {
|
|
166
|
-
return this.methodRequest('delete', path, opts);
|
|
167
|
-
}
|
|
168
|
-
methodRequest(method, path, opts) {
|
|
169
|
-
return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts })));
|
|
170
|
-
}
|
|
171
|
-
getAPIList(path, Page, opts) {
|
|
172
|
-
return this.requestAPIList(Page, { method: 'get', path, ...opts });
|
|
173
|
-
}
|
|
174
|
-
calculateContentLength(body) {
|
|
175
|
-
if (typeof body === 'string') {
|
|
176
|
-
if (typeof Buffer !== 'undefined') {
|
|
177
|
-
return Buffer.byteLength(body, 'utf8').toString();
|
|
178
|
-
}
|
|
179
|
-
if (typeof TextEncoder !== 'undefined') {
|
|
180
|
-
const encoder = new TextEncoder();
|
|
181
|
-
const encoded = encoder.encode(body);
|
|
182
|
-
return encoded.length.toString();
|
|
183
|
-
}
|
|
107
|
+
constructor({ baseURL, maxRetries, timeout = 600000, // 10 minutes
|
|
108
|
+
httpAgent, fetch: overridenFetch, }) {
|
|
109
|
+
this.baseURL = baseURL;
|
|
110
|
+
this.maxRetries = validatePositiveInteger('maxRetries', maxRetries ?? MAX_RETRIES);
|
|
111
|
+
this.timeout = validatePositiveInteger('timeout', timeout);
|
|
112
|
+
this.httpAgent = httpAgent;
|
|
113
|
+
this.fetch = overridenFetch ?? fetch;
|
|
184
114
|
}
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
}
|
|
324
|
-
return url.toString();
|
|
325
|
-
}
|
|
326
|
-
stringifyQuery(query) {
|
|
327
|
-
return Object.entries(query)
|
|
328
|
-
.filter(([_, value]) => typeof value !== 'undefined')
|
|
329
|
-
.map(([key, value]) => {
|
|
330
|
-
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
331
|
-
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
|
115
|
+
authHeaders(opts) {
|
|
116
|
+
return {};
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Override this to add your own default headers, for example:
|
|
120
|
+
*
|
|
121
|
+
* {
|
|
122
|
+
* ...super.defaultHeaders(),
|
|
123
|
+
* Authorization: 'Bearer 123',
|
|
124
|
+
* }
|
|
125
|
+
*/
|
|
126
|
+
defaultHeaders(opts) {
|
|
127
|
+
return {
|
|
128
|
+
Accept: 'application/json',
|
|
129
|
+
'Content-Type': 'application/json',
|
|
130
|
+
'User-Agent': this.getUserAgent(),
|
|
131
|
+
...getPlatformHeaders(),
|
|
132
|
+
...this.authHeaders(opts),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Override this to add your own headers validation:
|
|
137
|
+
*/
|
|
138
|
+
validateHeaders(headers, customHeaders) { }
|
|
139
|
+
defaultIdempotencyKey() {
|
|
140
|
+
return `stainless-node-retry-${uuid4()}`;
|
|
141
|
+
}
|
|
142
|
+
get(path, opts) {
|
|
143
|
+
return this.methodRequest('get', path, opts);
|
|
144
|
+
}
|
|
145
|
+
post(path, opts) {
|
|
146
|
+
return this.methodRequest('post', path, opts);
|
|
147
|
+
}
|
|
148
|
+
patch(path, opts) {
|
|
149
|
+
return this.methodRequest('patch', path, opts);
|
|
150
|
+
}
|
|
151
|
+
put(path, opts) {
|
|
152
|
+
return this.methodRequest('put', path, opts);
|
|
153
|
+
}
|
|
154
|
+
delete(path, opts) {
|
|
155
|
+
return this.methodRequest('delete', path, opts);
|
|
156
|
+
}
|
|
157
|
+
methodRequest(method, path, opts) {
|
|
158
|
+
return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts })));
|
|
159
|
+
}
|
|
160
|
+
getAPIList(path, Page, opts) {
|
|
161
|
+
return this.requestAPIList(Page, { method: 'get', path, ...opts });
|
|
162
|
+
}
|
|
163
|
+
calculateContentLength(body) {
|
|
164
|
+
if (typeof body === 'string') {
|
|
165
|
+
if (typeof Buffer !== 'undefined') {
|
|
166
|
+
return Buffer.byteLength(body, 'utf8').toString();
|
|
167
|
+
}
|
|
168
|
+
if (typeof TextEncoder !== 'undefined') {
|
|
169
|
+
const encoder = new TextEncoder();
|
|
170
|
+
const encoded = encoder.encode(body);
|
|
171
|
+
return encoded.length.toString();
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
buildRequest(options) {
|
|
177
|
+
const { method, path, query, headers: headers = {} } = options;
|
|
178
|
+
const body = isMultipartBody(options.body) ? options.body.body
|
|
179
|
+
: options.body ? JSON.stringify(options.body, null, 2)
|
|
180
|
+
: null;
|
|
181
|
+
const contentLength = this.calculateContentLength(body);
|
|
182
|
+
const url = this.buildURL(path, query);
|
|
183
|
+
if ('timeout' in options)
|
|
184
|
+
validatePositiveInteger('timeout', options.timeout);
|
|
185
|
+
const timeout = options.timeout ?? this.timeout;
|
|
186
|
+
const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
|
|
187
|
+
const minAgentTimeout = timeout + 1000;
|
|
188
|
+
if (typeof httpAgent?.options?.timeout === 'number' &&
|
|
189
|
+
minAgentTimeout > (httpAgent.options.timeout ?? 0)) {
|
|
190
|
+
// Allow any given request to bump our agent active socket timeout.
|
|
191
|
+
// This may seem strange, but leaking active sockets should be rare and not particularly problematic,
|
|
192
|
+
// and without mutating agent we would need to create more of them.
|
|
193
|
+
// This tradeoff optimizes for performance.
|
|
194
|
+
httpAgent.options.timeout = minAgentTimeout;
|
|
195
|
+
}
|
|
196
|
+
if (this.idempotencyHeader && method !== 'get') {
|
|
197
|
+
if (!options.idempotencyKey)
|
|
198
|
+
options.idempotencyKey = this.defaultIdempotencyKey();
|
|
199
|
+
headers[this.idempotencyHeader] = options.idempotencyKey;
|
|
200
|
+
}
|
|
201
|
+
const reqHeaders = {
|
|
202
|
+
...(contentLength && { 'Content-Length': contentLength }),
|
|
203
|
+
...this.defaultHeaders(options),
|
|
204
|
+
...headers,
|
|
205
|
+
};
|
|
206
|
+
// let builtin fetch set the Content-Type for multipart bodies
|
|
207
|
+
if (isMultipartBody(options.body) && shimsKind !== 'node') {
|
|
208
|
+
delete reqHeaders['Content-Type'];
|
|
209
|
+
}
|
|
210
|
+
// Strip any headers being explicitly omitted with null
|
|
211
|
+
Object.keys(reqHeaders).forEach((key) => reqHeaders[key] === null && delete reqHeaders[key]);
|
|
212
|
+
const req = {
|
|
213
|
+
method,
|
|
214
|
+
...(body && { body: body }),
|
|
215
|
+
headers: reqHeaders,
|
|
216
|
+
...(httpAgent && { agent: httpAgent }),
|
|
217
|
+
// @ts-ignore node-fetch uses a custom AbortSignal type that is
|
|
218
|
+
// not compatible with standard web types
|
|
219
|
+
signal: options.signal ?? null,
|
|
220
|
+
};
|
|
221
|
+
this.validateHeaders(reqHeaders, headers);
|
|
222
|
+
return { req, url, timeout };
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Used as a callback for mutating the given `RequestInit` object.
|
|
226
|
+
*
|
|
227
|
+
* This is useful for cases where you want to add certain headers based off of
|
|
228
|
+
* the request properties, e.g. `method` or `url`.
|
|
229
|
+
*/
|
|
230
|
+
async prepareRequest(request, { url, options }) { }
|
|
231
|
+
parseHeaders(headers) {
|
|
232
|
+
return (!headers ? {}
|
|
233
|
+
: Symbol.iterator in headers ?
|
|
234
|
+
Object.fromEntries(Array.from(headers).map((header) => [...header]))
|
|
235
|
+
: { ...headers });
|
|
236
|
+
}
|
|
237
|
+
makeStatusError(status, error, message, headers) {
|
|
238
|
+
return APIError.generate(status, error, message, headers);
|
|
239
|
+
}
|
|
240
|
+
request(options, remainingRetries = null) {
|
|
241
|
+
return new APIPromise(this.makeRequest(options, remainingRetries));
|
|
242
|
+
}
|
|
243
|
+
async makeRequest(optionsInput, retriesRemaining) {
|
|
244
|
+
const options = await optionsInput;
|
|
245
|
+
if (retriesRemaining == null) {
|
|
246
|
+
retriesRemaining = options.maxRetries ?? this.maxRetries;
|
|
247
|
+
}
|
|
248
|
+
const { req, url, timeout } = this.buildRequest(options);
|
|
249
|
+
await this.prepareRequest(req, { url, options });
|
|
250
|
+
debug('request', url, options, req.headers);
|
|
251
|
+
if (options.signal?.aborted) {
|
|
252
|
+
throw new APIUserAbortError();
|
|
332
253
|
}
|
|
333
|
-
|
|
334
|
-
|
|
254
|
+
const controller = new AbortController();
|
|
255
|
+
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
|
|
256
|
+
if (response instanceof Error) {
|
|
257
|
+
if (options.signal?.aborted) {
|
|
258
|
+
throw new APIUserAbortError();
|
|
259
|
+
}
|
|
260
|
+
if (retriesRemaining) {
|
|
261
|
+
return this.retryRequest(options, retriesRemaining);
|
|
262
|
+
}
|
|
263
|
+
if (response.name === 'AbortError') {
|
|
264
|
+
throw new APIConnectionTimeoutError();
|
|
265
|
+
}
|
|
266
|
+
throw new APIConnectionError({ cause: response });
|
|
335
267
|
}
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
268
|
+
const responseHeaders = createResponseHeaders(response.headers);
|
|
269
|
+
if (!response.ok) {
|
|
270
|
+
if (retriesRemaining && this.shouldRetry(response)) {
|
|
271
|
+
return this.retryRequest(options, retriesRemaining, responseHeaders);
|
|
272
|
+
}
|
|
273
|
+
const errText = await response.text().catch((e) => castToError(e).message);
|
|
274
|
+
const errJSON = safeJSON(errText);
|
|
275
|
+
const errMessage = errJSON ? undefined : errText;
|
|
276
|
+
debug('response', response.status, url, responseHeaders, errMessage);
|
|
277
|
+
const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
|
|
278
|
+
throw err;
|
|
279
|
+
}
|
|
280
|
+
return { response, options, controller };
|
|
281
|
+
}
|
|
282
|
+
requestAPIList(Page, options) {
|
|
283
|
+
const request = this.makeRequest(options, null);
|
|
284
|
+
return new PagePromise(this, request, Page);
|
|
285
|
+
}
|
|
286
|
+
buildURL(path, query) {
|
|
287
|
+
const url = isAbsoluteURL(path) ?
|
|
288
|
+
new URL(path)
|
|
289
|
+
: new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
|
|
290
|
+
const defaultQuery = this.defaultQuery();
|
|
291
|
+
if (!isEmptyObj(defaultQuery)) {
|
|
292
|
+
query = { ...defaultQuery, ...query };
|
|
293
|
+
}
|
|
294
|
+
if (query) {
|
|
295
|
+
url.search = this.stringifyQuery(query);
|
|
296
|
+
}
|
|
297
|
+
return url.toString();
|
|
298
|
+
}
|
|
299
|
+
stringifyQuery(query) {
|
|
300
|
+
return Object.entries(query)
|
|
301
|
+
.filter(([_, value]) => typeof value !== 'undefined')
|
|
302
|
+
.map(([key, value]) => {
|
|
303
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
304
|
+
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
|
305
|
+
}
|
|
306
|
+
if (value === null) {
|
|
307
|
+
return `${encodeURIComponent(key)}=`;
|
|
308
|
+
}
|
|
309
|
+
throw new AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
|
|
310
|
+
})
|
|
311
|
+
.join('&');
|
|
312
|
+
}
|
|
313
|
+
async fetchWithTimeout(url, init, ms, controller) {
|
|
314
|
+
const { signal, ...options } = init || {};
|
|
315
|
+
if (signal)
|
|
316
|
+
signal.addEventListener('abort', () => controller.abort());
|
|
317
|
+
const timeout = setTimeout(() => controller.abort(), ms);
|
|
318
|
+
return (this.getRequestClient()
|
|
319
|
+
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
|
|
320
|
+
.fetch.call(undefined, url, { signal: controller.signal, ...options })
|
|
321
|
+
.finally(() => {
|
|
322
|
+
clearTimeout(timeout);
|
|
323
|
+
}));
|
|
324
|
+
}
|
|
325
|
+
getRequestClient() {
|
|
326
|
+
return { fetch: this.fetch };
|
|
327
|
+
}
|
|
328
|
+
shouldRetry(response) {
|
|
329
|
+
// Note this is not a standard header.
|
|
330
|
+
const shouldRetryHeader = response.headers.get('x-should-retry');
|
|
331
|
+
// If the server explicitly says whether or not to retry, obey.
|
|
332
|
+
if (shouldRetryHeader === 'true')
|
|
333
|
+
return true;
|
|
334
|
+
if (shouldRetryHeader === 'false')
|
|
335
|
+
return false;
|
|
336
|
+
// Retry on request timeouts.
|
|
337
|
+
if (response.status === 408)
|
|
338
|
+
return true;
|
|
339
|
+
// Retry on lock timeouts.
|
|
340
|
+
if (response.status === 409)
|
|
341
|
+
return true;
|
|
342
|
+
// Retry on rate limits.
|
|
343
|
+
if (response.status === 429)
|
|
344
|
+
return true;
|
|
345
|
+
// Retry internal errors.
|
|
346
|
+
if (response.status >= 500)
|
|
347
|
+
return true;
|
|
348
|
+
return false;
|
|
349
|
+
}
|
|
350
|
+
async retryRequest(options, retriesRemaining, responseHeaders) {
|
|
351
|
+
retriesRemaining -= 1;
|
|
352
|
+
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
|
|
353
|
+
let timeoutMillis;
|
|
354
|
+
const retryAfterHeader = responseHeaders?.['retry-after'];
|
|
355
|
+
if (retryAfterHeader) {
|
|
356
|
+
const timeoutSeconds = parseInt(retryAfterHeader);
|
|
357
|
+
if (!Number.isNaN(timeoutSeconds)) {
|
|
358
|
+
timeoutMillis = timeoutSeconds * 1000;
|
|
359
|
+
}
|
|
360
|
+
else {
|
|
361
|
+
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
|
|
365
|
+
// just do what it says, but otherwise calculate a default
|
|
366
|
+
if (!timeoutMillis ||
|
|
367
|
+
!Number.isInteger(timeoutMillis) ||
|
|
368
|
+
timeoutMillis <= 0 ||
|
|
369
|
+
timeoutMillis > 60 * 1000) {
|
|
370
|
+
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
371
|
+
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
|
|
372
|
+
}
|
|
373
|
+
await sleep(timeoutMillis);
|
|
374
|
+
return this.makeRequest(options, retriesRemaining);
|
|
375
|
+
}
|
|
376
|
+
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
|
|
377
|
+
const initialRetryDelay = 0.5;
|
|
378
|
+
const maxRetryDelay = 2;
|
|
379
|
+
const numRetries = maxRetries - retriesRemaining;
|
|
380
|
+
// Apply exponential backoff, but not more than the max.
|
|
381
|
+
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(numRetries - 1, 2), maxRetryDelay);
|
|
382
|
+
// Apply some jitter, plus-or-minus half a second.
|
|
383
|
+
const jitter = Math.random() - 0.5;
|
|
384
|
+
return (sleepSeconds + jitter) * 1000;
|
|
385
|
+
}
|
|
386
|
+
getUserAgent() {
|
|
387
|
+
return `${this.constructor.name}/JS ${VERSION}`;
|
|
388
|
+
}
|
|
403
389
|
}
|
|
404
390
|
export class APIResource {
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
391
|
+
constructor(client) {
|
|
392
|
+
this.client = client;
|
|
393
|
+
this.get = client.get.bind(client);
|
|
394
|
+
this.post = client.post.bind(client);
|
|
395
|
+
this.patch = client.patch.bind(client);
|
|
396
|
+
this.put = client.put.bind(client);
|
|
397
|
+
this.delete = client.delete.bind(client);
|
|
398
|
+
this.getAPIList = client.getAPIList.bind(client);
|
|
399
|
+
}
|
|
414
400
|
}
|
|
415
401
|
export class AbstractPage {
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
}
|
|
402
|
+
constructor(client, response, body, options) {
|
|
403
|
+
_AbstractPage_client.set(this, void 0);
|
|
404
|
+
__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
|
|
405
|
+
this.options = options;
|
|
406
|
+
this.response = response;
|
|
407
|
+
this.body = body;
|
|
408
|
+
}
|
|
409
|
+
hasNextPage() {
|
|
410
|
+
const items = this.getPaginatedItems();
|
|
411
|
+
if (!items.length)
|
|
412
|
+
return false;
|
|
413
|
+
return this.nextPageInfo() != null;
|
|
414
|
+
}
|
|
415
|
+
async getNextPage() {
|
|
416
|
+
const nextInfo = this.nextPageInfo();
|
|
417
|
+
if (!nextInfo) {
|
|
418
|
+
throw new AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
|
|
419
|
+
}
|
|
420
|
+
const nextOptions = { ...this.options };
|
|
421
|
+
if ('params' in nextInfo) {
|
|
422
|
+
nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
|
|
423
|
+
}
|
|
424
|
+
else if ('url' in nextInfo) {
|
|
425
|
+
const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
|
|
426
|
+
for (const [key, value] of params) {
|
|
427
|
+
nextInfo.url.searchParams.set(key, value);
|
|
428
|
+
}
|
|
429
|
+
nextOptions.query = undefined;
|
|
430
|
+
nextOptions.path = nextInfo.url.toString();
|
|
431
|
+
}
|
|
432
|
+
return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
|
|
433
|
+
}
|
|
434
|
+
async *iterPages() {
|
|
435
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
436
|
+
let page = this;
|
|
437
|
+
yield page;
|
|
438
|
+
while (page.hasNextPage()) {
|
|
439
|
+
page = await page.getNextPage();
|
|
440
|
+
yield page;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
|
|
444
|
+
for await (const page of this.iterPages()) {
|
|
445
|
+
for (const item of page.getPaginatedItems()) {
|
|
446
|
+
yield item;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
}
|
|
467
450
|
}
|
|
468
451
|
/**
|
|
469
452
|
* This subclass of Promise will resolve to an instantiated Page once the request completes.
|
|
@@ -475,211 +458,216 @@ export class AbstractPage {
|
|
|
475
458
|
* }
|
|
476
459
|
*/
|
|
477
460
|
export class PagePromise extends APIPromise {
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
yield item;
|
|
495
|
-
}
|
|
496
|
-
}
|
|
461
|
+
constructor(client, request, Page) {
|
|
462
|
+
super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options));
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* Allow auto-paginating iteration on an unawaited list call, eg:
|
|
466
|
+
*
|
|
467
|
+
* for await (const item of client.items.list()) {
|
|
468
|
+
* console.log(item)
|
|
469
|
+
* }
|
|
470
|
+
*/
|
|
471
|
+
async *[Symbol.asyncIterator]() {
|
|
472
|
+
const page = await this;
|
|
473
|
+
for await (const item of page) {
|
|
474
|
+
yield item;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
497
477
|
}
|
|
498
478
|
export const createResponseHeaders = (headers) => {
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
return target[key.toLowerCase()] || target[key];
|
|
508
|
-
},
|
|
509
|
-
},
|
|
510
|
-
);
|
|
479
|
+
return new Proxy(Object.fromEntries(
|
|
480
|
+
// @ts-ignore
|
|
481
|
+
headers.entries()), {
|
|
482
|
+
get(target, name) {
|
|
483
|
+
const key = name.toString();
|
|
484
|
+
return target[key.toLowerCase()] || target[key];
|
|
485
|
+
},
|
|
486
|
+
});
|
|
511
487
|
};
|
|
512
488
|
// This is required so that we can determine if a given object matches the RequestOptions
|
|
513
489
|
// type at runtime. While this requires duplication, it is enforced by the TypeScript
|
|
514
490
|
// compiler such that any missing / extraneous keys will cause an error.
|
|
515
491
|
const requestOptionsKeys = {
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
492
|
+
method: true,
|
|
493
|
+
path: true,
|
|
494
|
+
query: true,
|
|
495
|
+
body: true,
|
|
496
|
+
headers: true,
|
|
497
|
+
maxRetries: true,
|
|
498
|
+
stream: true,
|
|
499
|
+
timeout: true,
|
|
500
|
+
httpAgent: true,
|
|
501
|
+
signal: true,
|
|
502
|
+
idempotencyKey: true,
|
|
527
503
|
};
|
|
528
504
|
export const isRequestOptions = (obj) => {
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))
|
|
534
|
-
);
|
|
505
|
+
return (typeof obj === 'object' &&
|
|
506
|
+
obj !== null &&
|
|
507
|
+
!isEmptyObj(obj) &&
|
|
508
|
+
Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)));
|
|
535
509
|
};
|
|
536
510
|
const getPlatformProperties = () => {
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
511
|
+
if (typeof Deno !== 'undefined' && Deno.build != null) {
|
|
512
|
+
return {
|
|
513
|
+
'X-Stainless-Lang': 'js',
|
|
514
|
+
'X-Stainless-Package-Version': VERSION,
|
|
515
|
+
'X-Stainless-OS': normalizePlatform(Deno.build.os),
|
|
516
|
+
'X-Stainless-Arch': normalizeArch(Deno.build.arch),
|
|
517
|
+
'X-Stainless-Runtime': 'deno',
|
|
518
|
+
'X-Stainless-Runtime-Version': Deno.version,
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
if (typeof EdgeRuntime !== 'undefined') {
|
|
522
|
+
return {
|
|
523
|
+
'X-Stainless-Lang': 'js',
|
|
524
|
+
'X-Stainless-Package-Version': VERSION,
|
|
525
|
+
'X-Stainless-OS': 'Unknown',
|
|
526
|
+
'X-Stainless-Arch': `other:${EdgeRuntime}`,
|
|
527
|
+
'X-Stainless-Runtime': 'edge',
|
|
528
|
+
'X-Stainless-Runtime-Version': process.version,
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
// Check if Node.js
|
|
532
|
+
if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {
|
|
533
|
+
return {
|
|
534
|
+
'X-Stainless-Lang': 'js',
|
|
535
|
+
'X-Stainless-Package-Version': VERSION,
|
|
536
|
+
'X-Stainless-OS': normalizePlatform(process.platform),
|
|
537
|
+
'X-Stainless-Arch': normalizeArch(process.arch),
|
|
538
|
+
'X-Stainless-Runtime': 'node',
|
|
539
|
+
'X-Stainless-Runtime-Version': process.version,
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
const browserInfo = getBrowserInfo();
|
|
543
|
+
if (browserInfo) {
|
|
544
|
+
return {
|
|
545
|
+
'X-Stainless-Lang': 'js',
|
|
546
|
+
'X-Stainless-Package-Version': VERSION,
|
|
547
|
+
'X-Stainless-OS': 'Unknown',
|
|
548
|
+
'X-Stainless-Arch': 'unknown',
|
|
549
|
+
'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
|
|
550
|
+
'X-Stainless-Runtime-Version': browserInfo.version,
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
// TODO add support for Cloudflare workers, etc.
|
|
570
554
|
return {
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
555
|
+
'X-Stainless-Lang': 'js',
|
|
556
|
+
'X-Stainless-Package-Version': VERSION,
|
|
557
|
+
'X-Stainless-OS': 'Unknown',
|
|
558
|
+
'X-Stainless-Arch': 'unknown',
|
|
559
|
+
'X-Stainless-Runtime': 'unknown',
|
|
560
|
+
'X-Stainless-Runtime-Version': 'unknown',
|
|
577
561
|
};
|
|
578
|
-
}
|
|
579
|
-
// TODO add support for Cloudflare workers, etc.
|
|
580
|
-
return {
|
|
581
|
-
'X-Stainless-Lang': 'js',
|
|
582
|
-
'X-Stainless-Package-Version': VERSION,
|
|
583
|
-
'X-Stainless-OS': 'Unknown',
|
|
584
|
-
'X-Stainless-Arch': 'unknown',
|
|
585
|
-
'X-Stainless-Runtime': 'unknown',
|
|
586
|
-
'X-Stainless-Runtime-Version': 'unknown',
|
|
587
|
-
};
|
|
588
562
|
};
|
|
589
563
|
// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
|
|
590
564
|
function getBrowserInfo() {
|
|
591
|
-
|
|
565
|
+
if (typeof navigator === 'undefined' || !navigator) {
|
|
566
|
+
return null;
|
|
567
|
+
}
|
|
568
|
+
// NOTE: The order matters here!
|
|
569
|
+
const browserPatterns = [
|
|
570
|
+
{ key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
571
|
+
{ key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
572
|
+
{ key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
573
|
+
{ key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
574
|
+
{ key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
575
|
+
{ key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
|
|
576
|
+
];
|
|
577
|
+
// Find the FIRST matching browser
|
|
578
|
+
for (const { key, pattern } of browserPatterns) {
|
|
579
|
+
const match = pattern.exec(navigator.userAgent);
|
|
580
|
+
if (match) {
|
|
581
|
+
const major = match[1] || 0;
|
|
582
|
+
const minor = match[2] || 0;
|
|
583
|
+
const patch = match[3] || 0;
|
|
584
|
+
return { browser: key, version: `${major}.${minor}.${patch}` };
|
|
585
|
+
}
|
|
586
|
+
}
|
|
592
587
|
return null;
|
|
593
|
-
}
|
|
594
|
-
// NOTE: The order matters here!
|
|
595
|
-
const browserPatterns = [
|
|
596
|
-
{ key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
597
|
-
{ key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
598
|
-
{ key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
599
|
-
{ key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
600
|
-
{ key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
601
|
-
{ key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
|
|
602
|
-
];
|
|
603
|
-
// Find the FIRST matching browser
|
|
604
|
-
for (const { key, pattern } of browserPatterns) {
|
|
605
|
-
const match = pattern.exec(navigator.userAgent);
|
|
606
|
-
if (match) {
|
|
607
|
-
const major = match[1] || 0;
|
|
608
|
-
const minor = match[2] || 0;
|
|
609
|
-
const patch = match[3] || 0;
|
|
610
|
-
return { browser: key, version: `${major}.${minor}.${patch}` };
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
return null;
|
|
614
588
|
}
|
|
615
589
|
const normalizeArch = (arch) => {
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
590
|
+
// Node docs:
|
|
591
|
+
// - https://nodejs.org/api/process.html#processarch
|
|
592
|
+
// Deno docs:
|
|
593
|
+
// - https://doc.deno.land/deno/stable/~/Deno.build
|
|
594
|
+
if (arch === 'x32')
|
|
595
|
+
return 'x32';
|
|
596
|
+
if (arch === 'x86_64' || arch === 'x64')
|
|
597
|
+
return 'x64';
|
|
598
|
+
if (arch === 'arm')
|
|
599
|
+
return 'arm';
|
|
600
|
+
if (arch === 'aarch64' || arch === 'arm64')
|
|
601
|
+
return 'arm64';
|
|
602
|
+
if (arch)
|
|
603
|
+
return `other:${arch}`;
|
|
604
|
+
return 'unknown';
|
|
626
605
|
};
|
|
627
606
|
const normalizePlatform = (platform) => {
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
607
|
+
// Node platforms:
|
|
608
|
+
// - https://nodejs.org/api/process.html#processplatform
|
|
609
|
+
// Deno platforms:
|
|
610
|
+
// - https://doc.deno.land/deno/stable/~/Deno.build
|
|
611
|
+
// - https://github.com/denoland/deno/issues/14799
|
|
612
|
+
platform = platform.toLowerCase();
|
|
613
|
+
// NOTE: this iOS check is untested and may not work
|
|
614
|
+
// Node does not work natively on IOS, there is a fork at
|
|
615
|
+
// https://github.com/nodejs-mobile/nodejs-mobile
|
|
616
|
+
// however it is unknown at the time of writing how to detect if it is running
|
|
617
|
+
if (platform.includes('ios'))
|
|
618
|
+
return 'iOS';
|
|
619
|
+
if (platform === 'android')
|
|
620
|
+
return 'Android';
|
|
621
|
+
if (platform === 'darwin')
|
|
622
|
+
return 'MacOS';
|
|
623
|
+
if (platform === 'win32')
|
|
624
|
+
return 'Windows';
|
|
625
|
+
if (platform === 'freebsd')
|
|
626
|
+
return 'FreeBSD';
|
|
627
|
+
if (platform === 'openbsd')
|
|
628
|
+
return 'OpenBSD';
|
|
629
|
+
if (platform === 'linux')
|
|
630
|
+
return 'Linux';
|
|
631
|
+
if (platform)
|
|
632
|
+
return `Other:${platform}`;
|
|
633
|
+
return 'Unknown';
|
|
647
634
|
};
|
|
648
635
|
let _platformHeaders;
|
|
649
636
|
const getPlatformHeaders = () => {
|
|
650
|
-
|
|
651
|
-
_platformHeaders
|
|
652
|
-
: (_platformHeaders = getPlatformProperties());
|
|
637
|
+
return (_platformHeaders ?? (_platformHeaders = getPlatformProperties()));
|
|
653
638
|
};
|
|
654
639
|
export const safeJSON = (text) => {
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
640
|
+
try {
|
|
641
|
+
return JSON.parse(text);
|
|
642
|
+
}
|
|
643
|
+
catch (err) {
|
|
644
|
+
return undefined;
|
|
645
|
+
}
|
|
660
646
|
};
|
|
661
647
|
// https://stackoverflow.com/a/19709846
|
|
662
648
|
const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i');
|
|
663
649
|
const isAbsoluteURL = (url) => {
|
|
664
|
-
|
|
650
|
+
return startsWithSchemeRegexp.test(url);
|
|
665
651
|
};
|
|
666
|
-
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
652
|
+
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
667
653
|
const validatePositiveInteger = (name, n) => {
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
654
|
+
if (typeof n !== 'number' || !Number.isInteger(n)) {
|
|
655
|
+
throw new AnthropicError(`${name} must be an integer`);
|
|
656
|
+
}
|
|
657
|
+
if (n < 0) {
|
|
658
|
+
throw new AnthropicError(`${name} must be a positive integer`);
|
|
659
|
+
}
|
|
660
|
+
return n;
|
|
675
661
|
};
|
|
676
662
|
export const castToError = (err) => {
|
|
677
|
-
|
|
678
|
-
|
|
663
|
+
if (err instanceof Error)
|
|
664
|
+
return err;
|
|
665
|
+
return new Error(err);
|
|
679
666
|
};
|
|
680
667
|
export const ensurePresent = (value) => {
|
|
681
|
-
|
|
682
|
-
|
|
668
|
+
if (value == null)
|
|
669
|
+
throw new AnthropicError(`Expected a value to be given but received ${value} instead.`);
|
|
670
|
+
return value;
|
|
683
671
|
};
|
|
684
672
|
/**
|
|
685
673
|
* Read an environment variable.
|
|
@@ -687,112 +675,130 @@ export const ensurePresent = (value) => {
|
|
|
687
675
|
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
|
|
688
676
|
*/
|
|
689
677
|
export const readEnv = (env) => {
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
return (_d = (_c = Deno.env) === null || _c === void 0 ? void 0 : _c.get) === null || _d === void 0 ?
|
|
698
|
-
void 0
|
|
699
|
-
: _d.call(_c, env);
|
|
700
|
-
}
|
|
701
|
-
return undefined;
|
|
678
|
+
if (typeof process !== 'undefined') {
|
|
679
|
+
return process.env?.[env] ?? undefined;
|
|
680
|
+
}
|
|
681
|
+
if (typeof Deno !== 'undefined') {
|
|
682
|
+
return Deno.env?.get?.(env);
|
|
683
|
+
}
|
|
684
|
+
return undefined;
|
|
702
685
|
};
|
|
703
686
|
export const coerceInteger = (value) => {
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
687
|
+
if (typeof value === 'number')
|
|
688
|
+
return Math.round(value);
|
|
689
|
+
if (typeof value === 'string')
|
|
690
|
+
return parseInt(value, 10);
|
|
691
|
+
throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
|
|
707
692
|
};
|
|
708
693
|
export const coerceFloat = (value) => {
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
694
|
+
if (typeof value === 'number')
|
|
695
|
+
return value;
|
|
696
|
+
if (typeof value === 'string')
|
|
697
|
+
return parseFloat(value);
|
|
698
|
+
throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
|
|
712
699
|
};
|
|
713
700
|
export const coerceBoolean = (value) => {
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
701
|
+
if (typeof value === 'boolean')
|
|
702
|
+
return value;
|
|
703
|
+
if (typeof value === 'string')
|
|
704
|
+
return value === 'true';
|
|
705
|
+
return Boolean(value);
|
|
717
706
|
};
|
|
718
707
|
export const maybeCoerceInteger = (value) => {
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
708
|
+
if (value === undefined) {
|
|
709
|
+
return undefined;
|
|
710
|
+
}
|
|
711
|
+
return coerceInteger(value);
|
|
723
712
|
};
|
|
724
713
|
export const maybeCoerceFloat = (value) => {
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
714
|
+
if (value === undefined) {
|
|
715
|
+
return undefined;
|
|
716
|
+
}
|
|
717
|
+
return coerceFloat(value);
|
|
729
718
|
};
|
|
730
719
|
export const maybeCoerceBoolean = (value) => {
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
720
|
+
if (value === undefined) {
|
|
721
|
+
return undefined;
|
|
722
|
+
}
|
|
723
|
+
return coerceBoolean(value);
|
|
735
724
|
};
|
|
736
725
|
// https://stackoverflow.com/a/34491287
|
|
737
726
|
export function isEmptyObj(obj) {
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
727
|
+
if (!obj)
|
|
728
|
+
return true;
|
|
729
|
+
for (const _k in obj)
|
|
730
|
+
return false;
|
|
731
|
+
return true;
|
|
741
732
|
}
|
|
742
733
|
// https://eslint.org/docs/latest/rules/no-prototype-builtins
|
|
743
734
|
export function hasOwn(obj, key) {
|
|
744
|
-
|
|
735
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
745
736
|
}
|
|
746
737
|
export function debug(action, ...args) {
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
738
|
+
if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
|
|
739
|
+
console.log(`Anthropic:DEBUG:${action}`, ...args);
|
|
740
|
+
}
|
|
750
741
|
}
|
|
751
742
|
/**
|
|
752
743
|
* https://stackoverflow.com/a/2117523
|
|
753
744
|
*/
|
|
754
745
|
const uuid4 = () => {
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
746
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
|
747
|
+
const r = (Math.random() * 16) | 0;
|
|
748
|
+
const v = c === 'x' ? r : (r & 0x3) | 0x8;
|
|
749
|
+
return v.toString(16);
|
|
750
|
+
});
|
|
760
751
|
};
|
|
761
752
|
export const isRunningInBrowser = () => {
|
|
762
|
-
|
|
753
|
+
return (
|
|
763
754
|
// @ts-ignore
|
|
764
755
|
typeof window !== 'undefined' &&
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
);
|
|
756
|
+
// @ts-ignore
|
|
757
|
+
typeof window.document !== 'undefined' &&
|
|
758
|
+
// @ts-ignore
|
|
759
|
+
typeof navigator !== 'undefined');
|
|
770
760
|
};
|
|
771
761
|
export const isHeadersProtocol = (headers) => {
|
|
772
|
-
|
|
762
|
+
return typeof headers?.get === 'function';
|
|
773
763
|
};
|
|
774
|
-
export const
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
764
|
+
export const getRequiredHeader = (headers, header) => {
|
|
765
|
+
const lowerCasedHeader = header.toLowerCase();
|
|
766
|
+
if (isHeadersProtocol(headers)) {
|
|
767
|
+
// to deal with the case where the header looks like Stainless-Event-Id
|
|
768
|
+
const intercapsHeader = header[0]?.toUpperCase() +
|
|
769
|
+
header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase());
|
|
770
|
+
for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {
|
|
771
|
+
const value = headers.get(key);
|
|
772
|
+
if (value) {
|
|
773
|
+
return value;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
778
|
+
if (key.toLowerCase() === lowerCasedHeader) {
|
|
779
|
+
if (Array.isArray(value)) {
|
|
780
|
+
if (value.length <= 1)
|
|
781
|
+
return value[0];
|
|
782
|
+
console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);
|
|
783
|
+
return value[0];
|
|
784
|
+
}
|
|
785
|
+
return value;
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
throw new Error(`Could not find ${header} header`);
|
|
784
789
|
};
|
|
785
790
|
/**
|
|
786
791
|
* Encodes a string to Base64 format.
|
|
787
792
|
*/
|
|
788
793
|
export const toBase64 = (str) => {
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
794
|
+
if (!str)
|
|
795
|
+
return '';
|
|
796
|
+
if (typeof Buffer !== 'undefined') {
|
|
797
|
+
return Buffer.from(str).toString('base64');
|
|
798
|
+
}
|
|
799
|
+
if (typeof btoa !== 'undefined') {
|
|
800
|
+
return btoa(str);
|
|
801
|
+
}
|
|
802
|
+
throw new AnthropicError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');
|
|
797
803
|
};
|
|
798
|
-
//# sourceMappingURL=core.mjs.map
|
|
804
|
+
//# sourceMappingURL=core.mjs.map
|