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