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