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