@anthropic-ai/sdk 0.6.2 → 0.6.8

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 +117 -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 +90 -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 -224
  74. package/core.d.ts.map +1 -1
  75. package/core.js +701 -736
  76. package/core.js.map +1 -1
  77. package/core.mjs +694 -688
  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 -159
  89. package/index.js.map +1 -1
  90. package/index.mjs +84 -104
  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 +83 -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 +107 -56
  149. package/src/error.ts +20 -8
  150. package/src/index.ts +24 -17
  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 +164 -59
  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 -60
  195. package/_shims/fetch.js +0 -13
  196. package/_shims/fetch.mjs +0 -15
  197. package/_shims/fetch.node.d.ts +0 -64
  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 -60
  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 -64
  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,520 +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(opts) {
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(opts) {
187
- return {
188
- Accept: 'application/json',
189
- 'Content-Type': 'application/json',
190
- 'User-Agent': this.getUserAgent(),
191
- ...getPlatformHeaders(),
192
- ...this.authHeaders(opts),
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(options),
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, options }) {}
304
- parseHeaders(headers) {
305
- return (
306
- !headers ? {}
307
- : Symbol.iterator in headers ? Object.fromEntries(Array.from(headers).map((header) => [...header]))
308
- : { ...headers }
309
- );
310
- }
311
- makeStatusError(status, error, message, headers) {
312
- return error_1.APIError.generate(status, error, message, headers);
313
- }
314
- request(options, remainingRetries = null) {
315
- return new APIPromise(this.makeRequest(options, remainingRetries));
316
- }
317
- async makeRequest(optionsInput, retriesRemaining) {
318
- var _a, _b, _c;
319
- const options = await optionsInput;
320
- if (retriesRemaining == null) {
321
- retriesRemaining = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries;
322
- }
323
- const { req, url, timeout } = this.buildRequest(options);
324
- await this.prepareRequest(req, { url, options });
325
- debug('request', url, options, req.headers);
326
- if ((_b = options.signal) === null || _b === void 0 ? void 0 : _b.aborted) {
327
- throw new error_1.APIUserAbortError();
328
- }
329
- const controller = new AbortController();
330
- const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(exports.castToError);
331
- if (response instanceof Error) {
332
- if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) {
333
- throw new error_1.APIUserAbortError();
334
- }
335
- if (retriesRemaining) {
336
- return this.retryRequest(options, retriesRemaining);
337
- }
338
- if (response.name === 'AbortError') {
339
- throw new error_1.APIConnectionTimeoutError();
340
- }
341
- throw new error_1.APIConnectionError({ cause: response });
342
- }
343
- const responseHeaders = (0, exports.createResponseHeaders)(response.headers);
344
- if (!response.ok) {
345
- if (retriesRemaining && this.shouldRetry(response)) {
346
- return this.retryRequest(options, retriesRemaining, responseHeaders);
347
- }
348
- const errText = await response.text().catch(() => 'Unknown');
349
- const errJSON = (0, exports.safeJSON)(errText);
350
- const errMessage = errJSON ? undefined : errText;
351
- debug('response', response.status, url, responseHeaders, errMessage);
352
- const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
353
- throw err;
354
- }
355
- return { response, options, controller };
356
- }
357
- requestAPIList(Page, options) {
358
- const request = this.makeRequest(options, null);
359
- return new PagePromise(this, request, Page);
360
- }
361
- buildURL(path, query) {
362
- const url =
363
- isAbsoluteURL(path) ?
364
- new URL(path)
365
- : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
366
- const defaultQuery = this.defaultQuery();
367
- if (!isEmptyObj(defaultQuery)) {
368
- query = { ...defaultQuery, ...query };
369
- }
370
- if (query) {
371
- url.search = this.stringifyQuery(query);
372
- }
373
- return url.toString();
374
- }
375
- stringifyQuery(query) {
376
- return Object.entries(query)
377
- .filter(([_, value]) => typeof value !== 'undefined')
378
- .map(([key, value]) => {
379
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
380
- 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();
381
260
  }
382
- if (value === null) {
383
- return `${encodeURIComponent(key)}=`;
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 });
384
274
  }
385
- throw new Error(
386
- `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.`,
387
- );
388
- })
389
- .join('&');
390
- }
391
- async fetchWithTimeout(url, init, ms, controller) {
392
- const { signal, ...options } = init || {};
393
- if (signal) signal.addEventListener('abort', () => controller.abort());
394
- const timeout = setTimeout(() => controller.abort(), ms);
395
- return this.getRequestClient()
396
- .fetch(url, { signal: controller.signal, ...options })
397
- .finally(() => {
398
- clearTimeout(timeout);
399
- });
400
- }
401
- getRequestClient() {
402
- return { fetch: this.fetch };
403
- }
404
- shouldRetry(response) {
405
- // Note this is not a standard header.
406
- const shouldRetryHeader = response.headers.get('x-should-retry');
407
- // If the server explicitly says whether or not to retry, obey.
408
- if (shouldRetryHeader === 'true') return true;
409
- if (shouldRetryHeader === 'false') return false;
410
- // Retry on lock timeouts.
411
- if (response.status === 409) return true;
412
- // Retry on rate limits.
413
- if (response.status === 429) return true;
414
- // Retry internal errors.
415
- if (response.status >= 500) return true;
416
- return false;
417
- }
418
- async retryRequest(options, retriesRemaining, responseHeaders) {
419
- var _a;
420
- retriesRemaining -= 1;
421
- // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
422
- //
423
- // TODO: we may want to handle the case where the header is using the http-date syntax: "Retry-After: <http-date>".
424
- // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax for details.
425
- const retryAfter = parseInt(
426
- (responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders['retry-after']) ||
427
- '',
428
- );
429
- const maxRetries = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries;
430
- const timeout = this.calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) * 1000;
431
- await sleep(timeout);
432
- return this.makeRequest(options, retriesRemaining);
433
- }
434
- calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) {
435
- const initialRetryDelay = 0.5;
436
- const maxRetryDelay = 2;
437
- // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
438
- // just do what it says.
439
- if (Number.isInteger(retryAfter) && retryAfter <= 60) {
440
- return retryAfter;
441
- }
442
- const numRetries = maxRetries - retriesRemaining;
443
- // Apply exponential backoff, but not more than the max.
444
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(numRetries - 1, 2), maxRetryDelay);
445
- // Apply some jitter, plus-or-minus half a second.
446
- const jitter = Math.random() - 0.5;
447
- return sleepSeconds + jitter;
448
- }
449
- getUserAgent() {
450
- return `${this.constructor.name}/JS ${version_1.VERSION}`;
451
- }
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;
286
+ }
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
+ }
452
396
  }
453
397
  exports.APIClient = APIClient;
454
398
  class APIResource {
455
- constructor(client) {
456
- this.client = client;
457
- this.get = client.get.bind(client);
458
- this.post = client.post.bind(client);
459
- this.patch = client.patch.bind(client);
460
- this.put = client.put.bind(client);
461
- this.delete = client.delete.bind(client);
462
- this.getAPIList = client.getAPIList.bind(client);
463
- }
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
+ }
464
408
  }
465
409
  exports.APIResource = APIResource;
466
410
  class AbstractPage {
467
- constructor(client, response, body, options) {
468
- _AbstractPage_client.set(this, void 0);
469
- __classPrivateFieldSet(this, _AbstractPage_client, client, 'f');
470
- this.options = options;
471
- this.response = response;
472
- this.body = body;
473
- }
474
- hasNextPage() {
475
- const items = this.getPaginatedItems();
476
- if (!items.length) return false;
477
- return this.nextPageInfo() != null;
478
- }
479
- async getNextPage() {
480
- const nextInfo = this.nextPageInfo();
481
- if (!nextInfo) {
482
- throw new Error(
483
- 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.',
484
- );
485
- }
486
- const nextOptions = { ...this.options };
487
- if ('params' in nextInfo) {
488
- nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
489
- } else if ('url' in nextInfo) {
490
- const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
491
- for (const [key, value] of params) {
492
- nextInfo.url.searchParams.set(key, value);
493
- }
494
- nextOptions.query = undefined;
495
- nextOptions.path = nextInfo.url.toString();
496
- }
497
- return await __classPrivateFieldGet(this, _AbstractPage_client, 'f').requestAPIList(
498
- this.constructor,
499
- nextOptions,
500
- );
501
- }
502
- async *iterPages() {
503
- // eslint-disable-next-line @typescript-eslint/no-this-alias
504
- let page = this;
505
- yield page;
506
- while (page.hasNextPage()) {
507
- page = await page.getNextPage();
508
- yield page;
509
- }
510
- }
511
- async *[((_AbstractPage_client = new WeakMap()), Symbol.asyncIterator)]() {
512
- for await (const page of this.iterPages()) {
513
- for (const item of page.getPaginatedItems()) {
514
- yield item;
515
- }
516
- }
517
- }
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
+ }
518
459
  }
519
460
  exports.AbstractPage = AbstractPage;
520
461
  /**
@@ -527,216 +468,222 @@ exports.AbstractPage = AbstractPage;
527
468
  * }
528
469
  */
529
470
  class PagePromise extends APIPromise {
530
- constructor(client, request, Page) {
531
- super(
532
- request,
533
- async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options),
534
- );
535
- }
536
- /**
537
- * Allow auto-paginating iteration on an unawaited list call, eg:
538
- *
539
- * for await (const item of client.items.list()) {
540
- * console.log(item)
541
- * }
542
- */
543
- async *[Symbol.asyncIterator]() {
544
- const page = await this;
545
- for await (const item of page) {
546
- yield item;
547
- }
548
- }
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
+ }
549
487
  }
550
488
  exports.PagePromise = PagePromise;
551
489
  const createResponseHeaders = (headers) => {
552
- return new Proxy(
553
- Object.fromEntries(
554
- // @ts-ignore
555
- headers.entries(),
556
- ),
557
- {
558
- get(target, name) {
559
- const key = name.toString();
560
- return target[key.toLowerCase()] || target[key];
561
- },
562
- },
563
- );
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
+ });
564
498
  };
565
499
  exports.createResponseHeaders = createResponseHeaders;
566
500
  // This is required so that we can determine if a given object matches the RequestOptions
567
501
  // type at runtime. While this requires duplication, it is enforced by the TypeScript
568
502
  // compiler such that any missing / extraneous keys will cause an error.
569
503
  const requestOptionsKeys = {
570
- method: true,
571
- path: true,
572
- query: true,
573
- body: true,
574
- headers: true,
575
- maxRetries: true,
576
- stream: true,
577
- timeout: true,
578
- httpAgent: true,
579
- signal: true,
580
- 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,
581
515
  };
582
516
  const isRequestOptions = (obj) => {
583
- return (
584
- typeof obj === 'object' &&
585
- obj !== null &&
586
- !isEmptyObj(obj) &&
587
- Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))
588
- );
517
+ return (typeof obj === 'object' &&
518
+ obj !== null &&
519
+ !isEmptyObj(obj) &&
520
+ Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)));
589
521
  };
590
522
  exports.isRequestOptions = isRequestOptions;
591
523
  const getPlatformProperties = () => {
592
- if (typeof Deno !== 'undefined' && Deno.build != null) {
593
- return {
594
- 'X-Stainless-Lang': 'js',
595
- 'X-Stainless-Package-Version': version_1.VERSION,
596
- 'X-Stainless-OS': normalizePlatform(Deno.build.os),
597
- 'X-Stainless-Arch': normalizeArch(Deno.build.arch),
598
- 'X-Stainless-Runtime': 'deno',
599
- 'X-Stainless-Runtime-Version': Deno.version,
600
- };
601
- }
602
- if (typeof EdgeRuntime !== 'undefined') {
603
- return {
604
- 'X-Stainless-Lang': 'js',
605
- 'X-Stainless-Package-Version': version_1.VERSION,
606
- 'X-Stainless-OS': 'Unknown',
607
- 'X-Stainless-Arch': `other:${EdgeRuntime}`,
608
- 'X-Stainless-Runtime': 'edge',
609
- 'X-Stainless-Runtime-Version': process.version,
610
- };
611
- }
612
- // Check if Node.js
613
- if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {
614
- return {
615
- 'X-Stainless-Lang': 'js',
616
- 'X-Stainless-Package-Version': version_1.VERSION,
617
- 'X-Stainless-OS': normalizePlatform(process.platform),
618
- 'X-Stainless-Arch': normalizeArch(process.arch),
619
- 'X-Stainless-Runtime': 'node',
620
- 'X-Stainless-Runtime-Version': process.version,
621
- };
622
- }
623
- const browserInfo = getBrowserInfo();
624
- 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.
625
567
  return {
626
- 'X-Stainless-Lang': 'js',
627
- 'X-Stainless-Package-Version': version_1.VERSION,
628
- 'X-Stainless-OS': 'Unknown',
629
- 'X-Stainless-Arch': 'unknown',
630
- 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
631
- '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',
632
574
  };
633
- }
634
- // TODO add support for Cloudflare workers, etc.
635
- return {
636
- 'X-Stainless-Lang': 'js',
637
- 'X-Stainless-Package-Version': version_1.VERSION,
638
- 'X-Stainless-OS': 'Unknown',
639
- 'X-Stainless-Arch': 'unknown',
640
- 'X-Stainless-Runtime': 'unknown',
641
- 'X-Stainless-Runtime-Version': 'unknown',
642
- };
643
575
  };
644
576
  // Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
645
577
  function getBrowserInfo() {
646
- 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
+ }
647
600
  return null;
648
- }
649
- // NOTE: The order matters here!
650
- const browserPatterns = [
651
- { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
652
- { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
653
- { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
654
- { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
655
- { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
656
- { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
657
- ];
658
- // Find the FIRST matching browser
659
- for (const { key, pattern } of browserPatterns) {
660
- const match = pattern.exec(navigator.userAgent);
661
- if (match) {
662
- const major = match[1] || 0;
663
- const minor = match[2] || 0;
664
- const patch = match[3] || 0;
665
- return { browser: key, version: `${major}.${minor}.${patch}` };
666
- }
667
- }
668
- return null;
669
601
  }
670
602
  const normalizeArch = (arch) => {
671
- // Node docs:
672
- // - https://nodejs.org/api/process.html#processarch
673
- // Deno docs:
674
- // - https://doc.deno.land/deno/stable/~/Deno.build
675
- if (arch === 'x32') return 'x32';
676
- if (arch === 'x86_64' || arch === 'x64') return 'x64';
677
- if (arch === 'arm') return 'arm';
678
- if (arch === 'aarch64' || arch === 'arm64') return 'arm64';
679
- if (arch) return `other:${arch}`;
680
- 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';
681
618
  };
682
619
  const normalizePlatform = (platform) => {
683
- // Node platforms:
684
- // - https://nodejs.org/api/process.html#processplatform
685
- // Deno platforms:
686
- // - https://doc.deno.land/deno/stable/~/Deno.build
687
- // - https://github.com/denoland/deno/issues/14799
688
- platform = platform.toLowerCase();
689
- // NOTE: this iOS check is untested and may not work
690
- // Node does not work natively on IOS, there is a fork at
691
- // https://github.com/nodejs-mobile/nodejs-mobile
692
- // however it is unknown at the time of writing how to detect if it is running
693
- if (platform.includes('ios')) return 'iOS';
694
- if (platform === 'android') return 'Android';
695
- if (platform === 'darwin') return 'MacOS';
696
- if (platform === 'win32') return 'Windows';
697
- if (platform === 'freebsd') return 'FreeBSD';
698
- if (platform === 'openbsd') return 'OpenBSD';
699
- if (platform === 'linux') return 'Linux';
700
- if (platform) return `Other:${platform}`;
701
- 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';
702
647
  };
703
648
  let _platformHeaders;
704
649
  const getPlatformHeaders = () => {
705
- return _platformHeaders !== null && _platformHeaders !== void 0 ?
706
- _platformHeaders
707
- : (_platformHeaders = getPlatformProperties());
650
+ return (_platformHeaders ?? (_platformHeaders = getPlatformProperties()));
708
651
  };
709
652
  const safeJSON = (text) => {
710
- try {
711
- return JSON.parse(text);
712
- } catch (err) {
713
- return undefined;
714
- }
653
+ try {
654
+ return JSON.parse(text);
655
+ }
656
+ catch (err) {
657
+ return undefined;
658
+ }
715
659
  };
716
660
  exports.safeJSON = safeJSON;
717
661
  // https://stackoverflow.com/a/19709846
718
662
  const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i');
719
663
  const isAbsoluteURL = (url) => {
720
- return startsWithSchemeRegexp.test(url);
664
+ return startsWithSchemeRegexp.test(url);
721
665
  };
722
666
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
667
+ exports.sleep = sleep;
723
668
  const validatePositiveInteger = (name, n) => {
724
- if (typeof n !== 'number' || !Number.isInteger(n)) {
725
- throw new Error(`${name} must be an integer`);
726
- }
727
- if (n < 0) {
728
- throw new Error(`${name} must be a positive integer`);
729
- }
730
- 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;
731
676
  };
732
677
  const castToError = (err) => {
733
- if (err instanceof Error) return err;
734
- return new Error(err);
678
+ if (err instanceof Error)
679
+ return err;
680
+ return new Error(err);
735
681
  };
736
682
  exports.castToError = castToError;
737
683
  const ensurePresent = (value) => {
738
- if (value == null) throw new Error(`Expected a value to be given but received ${value} instead.`);
739
- 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;
740
687
  };
741
688
  exports.ensurePresent = ensurePresent;
742
689
  /**
@@ -745,126 +692,144 @@ exports.ensurePresent = ensurePresent;
745
692
  * Will return undefined if the environment variable doesn't exist or cannot be accessed.
746
693
  */
747
694
  const readEnv = (env) => {
748
- var _a, _b, _c, _d;
749
- if (typeof process !== 'undefined') {
750
- return (_b = (_a = process.env) === null || _a === void 0 ? void 0 : _a[env]) !== null && _b !== void 0 ?
751
- _b
752
- : undefined;
753
- }
754
- if (typeof Deno !== 'undefined') {
755
- return (_d = (_c = Deno.env) === null || _c === void 0 ? void 0 : _c.get) === null || _d === void 0 ?
756
- void 0
757
- : _d.call(_c, env);
758
- }
759
- 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;
760
702
  };
761
703
  exports.readEnv = readEnv;
762
704
  const coerceInteger = (value) => {
763
- if (typeof value === 'number') return Math.round(value);
764
- if (typeof value === 'string') return parseInt(value, 10);
765
- 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`);
766
710
  };
767
711
  exports.coerceInteger = coerceInteger;
768
712
  const coerceFloat = (value) => {
769
- if (typeof value === 'number') return value;
770
- if (typeof value === 'string') return parseFloat(value);
771
- 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`);
772
718
  };
773
719
  exports.coerceFloat = coerceFloat;
774
720
  const coerceBoolean = (value) => {
775
- if (typeof value === 'boolean') return value;
776
- if (typeof value === 'string') return value === 'true';
777
- return Boolean(value);
721
+ if (typeof value === 'boolean')
722
+ return value;
723
+ if (typeof value === 'string')
724
+ return value === 'true';
725
+ return Boolean(value);
778
726
  };
779
727
  exports.coerceBoolean = coerceBoolean;
780
728
  const maybeCoerceInteger = (value) => {
781
- if (value === undefined) {
782
- return undefined;
783
- }
784
- return (0, exports.coerceInteger)(value);
729
+ if (value === undefined) {
730
+ return undefined;
731
+ }
732
+ return (0, exports.coerceInteger)(value);
785
733
  };
786
734
  exports.maybeCoerceInteger = maybeCoerceInteger;
787
735
  const maybeCoerceFloat = (value) => {
788
- if (value === undefined) {
789
- return undefined;
790
- }
791
- return (0, exports.coerceFloat)(value);
736
+ if (value === undefined) {
737
+ return undefined;
738
+ }
739
+ return (0, exports.coerceFloat)(value);
792
740
  };
793
741
  exports.maybeCoerceFloat = maybeCoerceFloat;
794
742
  const maybeCoerceBoolean = (value) => {
795
- if (value === undefined) {
796
- return undefined;
797
- }
798
- return (0, exports.coerceBoolean)(value);
743
+ if (value === undefined) {
744
+ return undefined;
745
+ }
746
+ return (0, exports.coerceBoolean)(value);
799
747
  };
800
748
  exports.maybeCoerceBoolean = maybeCoerceBoolean;
801
749
  // https://stackoverflow.com/a/34491287
802
750
  function isEmptyObj(obj) {
803
- if (!obj) return true;
804
- for (const _k in obj) return false;
805
- return true;
751
+ if (!obj)
752
+ return true;
753
+ for (const _k in obj)
754
+ return false;
755
+ return true;
806
756
  }
807
757
  exports.isEmptyObj = isEmptyObj;
808
758
  // https://eslint.org/docs/latest/rules/no-prototype-builtins
809
759
  function hasOwn(obj, key) {
810
- return Object.prototype.hasOwnProperty.call(obj, key);
760
+ return Object.prototype.hasOwnProperty.call(obj, key);
811
761
  }
812
762
  exports.hasOwn = hasOwn;
813
763
  function debug(action, ...args) {
814
- if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
815
- console.log(`Anthropic:DEBUG:${action}`, ...args);
816
- }
764
+ if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') {
765
+ console.log(`Anthropic:DEBUG:${action}`, ...args);
766
+ }
817
767
  }
818
768
  exports.debug = debug;
819
769
  /**
820
770
  * https://stackoverflow.com/a/2117523
821
771
  */
822
772
  const uuid4 = () => {
823
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
824
- const r = (Math.random() * 16) | 0;
825
- const v = c === 'x' ? r : (r & 0x3) | 0x8;
826
- return v.toString(16);
827
- });
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
+ });
828
778
  };
829
779
  const isRunningInBrowser = () => {
830
- return (
780
+ return (
831
781
  // @ts-ignore
832
782
  typeof window !== 'undefined' &&
833
- // @ts-ignore
834
- typeof window.document !== 'undefined' &&
835
- // @ts-ignore
836
- typeof navigator !== 'undefined'
837
- );
783
+ // @ts-ignore
784
+ typeof window.document !== 'undefined' &&
785
+ // @ts-ignore
786
+ typeof navigator !== 'undefined');
838
787
  };
839
788
  exports.isRunningInBrowser = isRunningInBrowser;
840
789
  const isHeadersProtocol = (headers) => {
841
- return typeof (headers === null || headers === void 0 ? void 0 : headers.get) === 'function';
790
+ return typeof headers?.get === 'function';
842
791
  };
843
792
  exports.isHeadersProtocol = isHeadersProtocol;
844
- const getHeader = (headers, key) => {
845
- const lowerKey = key.toLowerCase();
846
- if ((0, exports.isHeadersProtocol)(headers)) return headers.get(key) || headers.get(lowerKey);
847
- const value = headers[key] || headers[lowerKey];
848
- if (Array.isArray(value)) {
849
- if (value.length <= 1) return value[0];
850
- console.warn(`Received ${value.length} entries for the ${key} header, using the first entry.`);
851
- return value[0];
852
- }
853
- 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`);
854
818
  };
855
- exports.getHeader = getHeader;
819
+ exports.getRequiredHeader = getRequiredHeader;
856
820
  /**
857
821
  * Encodes a string to Base64 format.
858
822
  */
859
823
  const toBase64 = (str) => {
860
- if (!str) return '';
861
- if (typeof Buffer !== 'undefined') {
862
- return Buffer.from(str).toString('base64');
863
- }
864
- if (typeof btoa !== 'undefined') {
865
- return btoa(str);
866
- }
867
- 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');
868
833
  };
869
834
  exports.toBase64 = toBase64;
870
- //# sourceMappingURL=core.js.map
835
+ //# sourceMappingURL=core.js.map