openai 4.7.1 → 4.9.0

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