@bluehive/sdk 0.1.0-alpha.10

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 (352) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +201 -0
  3. package/README.md +358 -0
  4. package/api-promise.d.mts +2 -0
  5. package/api-promise.d.mts.map +1 -0
  6. package/api-promise.d.ts +2 -0
  7. package/api-promise.d.ts.map +1 -0
  8. package/api-promise.js +6 -0
  9. package/api-promise.js.map +1 -0
  10. package/api-promise.mjs +2 -0
  11. package/api-promise.mjs.map +1 -0
  12. package/client.d.mts +192 -0
  13. package/client.d.mts.map +1 -0
  14. package/client.d.ts +192 -0
  15. package/client.d.ts.map +1 -0
  16. package/client.js +473 -0
  17. package/client.js.map +1 -0
  18. package/client.mjs +469 -0
  19. package/client.mjs.map +1 -0
  20. package/core/api-promise.d.mts +46 -0
  21. package/core/api-promise.d.mts.map +1 -0
  22. package/core/api-promise.d.ts +46 -0
  23. package/core/api-promise.d.ts.map +1 -0
  24. package/core/api-promise.js +74 -0
  25. package/core/api-promise.js.map +1 -0
  26. package/core/api-promise.mjs +70 -0
  27. package/core/api-promise.mjs.map +1 -0
  28. package/core/error.d.mts +46 -0
  29. package/core/error.d.mts.map +1 -0
  30. package/core/error.d.ts +46 -0
  31. package/core/error.d.ts.map +1 -0
  32. package/core/error.js +113 -0
  33. package/core/error.js.map +1 -0
  34. package/core/error.mjs +97 -0
  35. package/core/error.mjs.map +1 -0
  36. package/core/resource.d.mts +6 -0
  37. package/core/resource.d.mts.map +1 -0
  38. package/core/resource.d.ts +6 -0
  39. package/core/resource.d.ts.map +1 -0
  40. package/core/resource.js +11 -0
  41. package/core/resource.js.map +1 -0
  42. package/core/resource.mjs +7 -0
  43. package/core/resource.mjs.map +1 -0
  44. package/core/uploads.d.mts +3 -0
  45. package/core/uploads.d.mts.map +1 -0
  46. package/core/uploads.d.ts +3 -0
  47. package/core/uploads.d.ts.map +1 -0
  48. package/core/uploads.js +6 -0
  49. package/core/uploads.js.map +1 -0
  50. package/core/uploads.mjs +2 -0
  51. package/core/uploads.mjs.map +1 -0
  52. package/error.d.mts +2 -0
  53. package/error.d.mts.map +1 -0
  54. package/error.d.ts +2 -0
  55. package/error.d.ts.map +1 -0
  56. package/error.js +6 -0
  57. package/error.js.map +1 -0
  58. package/error.mjs +2 -0
  59. package/error.mjs.map +1 -0
  60. package/index.d.mts +6 -0
  61. package/index.d.mts.map +1 -0
  62. package/index.d.ts +6 -0
  63. package/index.d.ts.map +1 -0
  64. package/index.js +30 -0
  65. package/index.js.map +1 -0
  66. package/index.mjs +7 -0
  67. package/index.mjs.map +1 -0
  68. package/internal/builtin-types.d.mts +73 -0
  69. package/internal/builtin-types.d.mts.map +1 -0
  70. package/internal/builtin-types.d.ts +73 -0
  71. package/internal/builtin-types.d.ts.map +1 -0
  72. package/internal/builtin-types.js +4 -0
  73. package/internal/builtin-types.js.map +1 -0
  74. package/internal/builtin-types.mjs +3 -0
  75. package/internal/builtin-types.mjs.map +1 -0
  76. package/internal/detect-platform.d.mts +15 -0
  77. package/internal/detect-platform.d.mts.map +1 -0
  78. package/internal/detect-platform.d.ts +15 -0
  79. package/internal/detect-platform.d.ts.map +1 -0
  80. package/internal/detect-platform.js +162 -0
  81. package/internal/detect-platform.js.map +1 -0
  82. package/internal/detect-platform.mjs +157 -0
  83. package/internal/detect-platform.mjs.map +1 -0
  84. package/internal/errors.d.mts +3 -0
  85. package/internal/errors.d.mts.map +1 -0
  86. package/internal/errors.d.ts +3 -0
  87. package/internal/errors.d.ts.map +1 -0
  88. package/internal/errors.js +41 -0
  89. package/internal/errors.js.map +1 -0
  90. package/internal/errors.mjs +36 -0
  91. package/internal/errors.mjs.map +1 -0
  92. package/internal/headers.d.mts +20 -0
  93. package/internal/headers.d.mts.map +1 -0
  94. package/internal/headers.d.ts +20 -0
  95. package/internal/headers.d.ts.map +1 -0
  96. package/internal/headers.js +79 -0
  97. package/internal/headers.js.map +1 -0
  98. package/internal/headers.mjs +74 -0
  99. package/internal/headers.mjs.map +1 -0
  100. package/internal/parse.d.mts +12 -0
  101. package/internal/parse.d.mts.map +1 -0
  102. package/internal/parse.d.ts +12 -0
  103. package/internal/parse.d.ts.map +1 -0
  104. package/internal/parse.js +35 -0
  105. package/internal/parse.js.map +1 -0
  106. package/internal/parse.mjs +32 -0
  107. package/internal/parse.mjs.map +1 -0
  108. package/internal/request-options.d.mts +75 -0
  109. package/internal/request-options.d.mts.map +1 -0
  110. package/internal/request-options.d.ts +75 -0
  111. package/internal/request-options.d.ts.map +1 -0
  112. package/internal/request-options.js +14 -0
  113. package/internal/request-options.js.map +1 -0
  114. package/internal/request-options.mjs +10 -0
  115. package/internal/request-options.mjs.map +1 -0
  116. package/internal/shim-types.d.mts +17 -0
  117. package/internal/shim-types.d.mts.map +1 -0
  118. package/internal/shim-types.d.ts +17 -0
  119. package/internal/shim-types.d.ts.map +1 -0
  120. package/internal/shim-types.js +4 -0
  121. package/internal/shim-types.js.map +1 -0
  122. package/internal/shim-types.mjs +3 -0
  123. package/internal/shim-types.mjs.map +1 -0
  124. package/internal/shims.d.mts +20 -0
  125. package/internal/shims.d.mts.map +1 -0
  126. package/internal/shims.d.ts +20 -0
  127. package/internal/shims.d.ts.map +1 -0
  128. package/internal/shims.js +92 -0
  129. package/internal/shims.js.map +1 -0
  130. package/internal/shims.mjs +85 -0
  131. package/internal/shims.mjs.map +1 -0
  132. package/internal/to-file.d.mts +45 -0
  133. package/internal/to-file.d.mts.map +1 -0
  134. package/internal/to-file.d.ts +45 -0
  135. package/internal/to-file.d.ts.map +1 -0
  136. package/internal/to-file.js +91 -0
  137. package/internal/to-file.js.map +1 -0
  138. package/internal/to-file.mjs +88 -0
  139. package/internal/to-file.mjs.map +1 -0
  140. package/internal/tslib.js +81 -0
  141. package/internal/tslib.mjs +17 -0
  142. package/internal/types.d.mts +69 -0
  143. package/internal/types.d.mts.map +1 -0
  144. package/internal/types.d.ts +69 -0
  145. package/internal/types.d.ts.map +1 -0
  146. package/internal/types.js +4 -0
  147. package/internal/types.js.map +1 -0
  148. package/internal/types.mjs +3 -0
  149. package/internal/types.mjs.map +1 -0
  150. package/internal/uploads.d.mts +42 -0
  151. package/internal/uploads.d.mts.map +1 -0
  152. package/internal/uploads.d.ts +42 -0
  153. package/internal/uploads.d.ts.map +1 -0
  154. package/internal/uploads.js +141 -0
  155. package/internal/uploads.js.map +1 -0
  156. package/internal/uploads.mjs +131 -0
  157. package/internal/uploads.mjs.map +1 -0
  158. package/internal/utils/base64.d.mts +3 -0
  159. package/internal/utils/base64.d.mts.map +1 -0
  160. package/internal/utils/base64.d.ts +3 -0
  161. package/internal/utils/base64.d.ts.map +1 -0
  162. package/internal/utils/base64.js +38 -0
  163. package/internal/utils/base64.js.map +1 -0
  164. package/internal/utils/base64.mjs +33 -0
  165. package/internal/utils/base64.mjs.map +1 -0
  166. package/internal/utils/bytes.d.mts +4 -0
  167. package/internal/utils/bytes.d.mts.map +1 -0
  168. package/internal/utils/bytes.d.ts +4 -0
  169. package/internal/utils/bytes.d.ts.map +1 -0
  170. package/internal/utils/bytes.js +31 -0
  171. package/internal/utils/bytes.js.map +1 -0
  172. package/internal/utils/bytes.mjs +26 -0
  173. package/internal/utils/bytes.mjs.map +1 -0
  174. package/internal/utils/env.d.mts +9 -0
  175. package/internal/utils/env.d.mts.map +1 -0
  176. package/internal/utils/env.d.ts +9 -0
  177. package/internal/utils/env.d.ts.map +1 -0
  178. package/internal/utils/env.js +22 -0
  179. package/internal/utils/env.js.map +1 -0
  180. package/internal/utils/env.mjs +18 -0
  181. package/internal/utils/env.mjs.map +1 -0
  182. package/internal/utils/log.d.mts +37 -0
  183. package/internal/utils/log.d.mts.map +1 -0
  184. package/internal/utils/log.d.ts +37 -0
  185. package/internal/utils/log.d.ts.map +1 -0
  186. package/internal/utils/log.js +85 -0
  187. package/internal/utils/log.js.map +1 -0
  188. package/internal/utils/log.mjs +79 -0
  189. package/internal/utils/log.mjs.map +1 -0
  190. package/internal/utils/path.d.mts +15 -0
  191. package/internal/utils/path.d.mts.map +1 -0
  192. package/internal/utils/path.d.ts +15 -0
  193. package/internal/utils/path.d.ts.map +1 -0
  194. package/internal/utils/path.js +79 -0
  195. package/internal/utils/path.js.map +1 -0
  196. package/internal/utils/path.mjs +74 -0
  197. package/internal/utils/path.mjs.map +1 -0
  198. package/internal/utils/sleep.d.mts +2 -0
  199. package/internal/utils/sleep.d.mts.map +1 -0
  200. package/internal/utils/sleep.d.ts +2 -0
  201. package/internal/utils/sleep.d.ts.map +1 -0
  202. package/internal/utils/sleep.js +7 -0
  203. package/internal/utils/sleep.js.map +1 -0
  204. package/internal/utils/sleep.mjs +3 -0
  205. package/internal/utils/sleep.mjs.map +1 -0
  206. package/internal/utils/uuid.d.mts +5 -0
  207. package/internal/utils/uuid.d.mts.map +1 -0
  208. package/internal/utils/uuid.d.ts +5 -0
  209. package/internal/utils/uuid.d.ts.map +1 -0
  210. package/internal/utils/uuid.js +19 -0
  211. package/internal/utils/uuid.js.map +1 -0
  212. package/internal/utils/uuid.mjs +15 -0
  213. package/internal/utils/uuid.mjs.map +1 -0
  214. package/internal/utils/values.d.mts +18 -0
  215. package/internal/utils/values.d.mts.map +1 -0
  216. package/internal/utils/values.d.ts +18 -0
  217. package/internal/utils/values.d.ts.map +1 -0
  218. package/internal/utils/values.js +112 -0
  219. package/internal/utils/values.js.map +1 -0
  220. package/internal/utils/values.mjs +94 -0
  221. package/internal/utils/values.mjs.map +1 -0
  222. package/internal/utils.d.mts +7 -0
  223. package/internal/utils.d.mts.map +1 -0
  224. package/internal/utils.d.ts +7 -0
  225. package/internal/utils.d.ts.map +1 -0
  226. package/internal/utils.js +11 -0
  227. package/internal/utils.js.map +1 -0
  228. package/internal/utils.mjs +8 -0
  229. package/internal/utils.mjs.map +1 -0
  230. package/package.json +138 -0
  231. package/resource.d.mts +2 -0
  232. package/resource.d.mts.map +1 -0
  233. package/resource.d.ts +2 -0
  234. package/resource.d.ts.map +1 -0
  235. package/resource.js +6 -0
  236. package/resource.js.map +1 -0
  237. package/resource.mjs +2 -0
  238. package/resource.mjs.map +1 -0
  239. package/resources/database.d.mts +54 -0
  240. package/resources/database.d.mts.map +1 -0
  241. package/resources/database.d.ts +54 -0
  242. package/resources/database.d.ts.map +1 -0
  243. package/resources/database.js +15 -0
  244. package/resources/database.js.map +1 -0
  245. package/resources/database.mjs +11 -0
  246. package/resources/database.mjs.map +1 -0
  247. package/resources/fax.d.mts +159 -0
  248. package/resources/fax.d.mts.map +1 -0
  249. package/resources/fax.d.ts +159 -0
  250. package/resources/fax.d.ts.map +1 -0
  251. package/resources/fax.js +28 -0
  252. package/resources/fax.js.map +1 -0
  253. package/resources/fax.mjs +24 -0
  254. package/resources/fax.mjs.map +1 -0
  255. package/resources/health.d.mts +16 -0
  256. package/resources/health.d.mts.map +1 -0
  257. package/resources/health.d.ts +16 -0
  258. package/resources/health.d.ts.map +1 -0
  259. package/resources/health.js +15 -0
  260. package/resources/health.js.map +1 -0
  261. package/resources/health.mjs +11 -0
  262. package/resources/health.mjs.map +1 -0
  263. package/resources/index.d.mts +6 -0
  264. package/resources/index.d.mts.map +1 -0
  265. package/resources/index.d.ts +6 -0
  266. package/resources/index.d.ts.map +1 -0
  267. package/resources/index.js +15 -0
  268. package/resources/index.js.map +1 -0
  269. package/resources/index.mjs +7 -0
  270. package/resources/index.mjs.map +1 -0
  271. package/resources/providers.d.mts +93 -0
  272. package/resources/providers.d.mts.map +1 -0
  273. package/resources/providers.d.ts +93 -0
  274. package/resources/providers.d.ts.map +1 -0
  275. package/resources/providers.js +15 -0
  276. package/resources/providers.js.map +1 -0
  277. package/resources/providers.mjs +11 -0
  278. package/resources/providers.mjs.map +1 -0
  279. package/resources/version.d.mts +16 -0
  280. package/resources/version.d.mts.map +1 -0
  281. package/resources/version.d.ts +16 -0
  282. package/resources/version.d.ts.map +1 -0
  283. package/resources/version.js +15 -0
  284. package/resources/version.js.map +1 -0
  285. package/resources/version.mjs +11 -0
  286. package/resources/version.mjs.map +1 -0
  287. package/resources.d.mts +2 -0
  288. package/resources.d.mts.map +1 -0
  289. package/resources.d.ts +2 -0
  290. package/resources.d.ts.map +1 -0
  291. package/resources.js +5 -0
  292. package/resources.js.map +1 -0
  293. package/resources.mjs +2 -0
  294. package/resources.mjs.map +1 -0
  295. package/src/api-promise.ts +2 -0
  296. package/src/client.ts +760 -0
  297. package/src/core/README.md +3 -0
  298. package/src/core/api-promise.ts +92 -0
  299. package/src/core/error.ts +130 -0
  300. package/src/core/resource.ts +11 -0
  301. package/src/core/uploads.ts +2 -0
  302. package/src/error.ts +2 -0
  303. package/src/index.ts +22 -0
  304. package/src/internal/README.md +3 -0
  305. package/src/internal/builtin-types.ts +93 -0
  306. package/src/internal/detect-platform.ts +196 -0
  307. package/src/internal/errors.ts +33 -0
  308. package/src/internal/headers.ts +97 -0
  309. package/src/internal/parse.ts +50 -0
  310. package/src/internal/request-options.ts +91 -0
  311. package/src/internal/shim-types.ts +26 -0
  312. package/src/internal/shims.ts +107 -0
  313. package/src/internal/to-file.ts +154 -0
  314. package/src/internal/types.ts +95 -0
  315. package/src/internal/uploads.ts +187 -0
  316. package/src/internal/utils/base64.ts +40 -0
  317. package/src/internal/utils/bytes.ts +32 -0
  318. package/src/internal/utils/env.ts +18 -0
  319. package/src/internal/utils/log.ts +126 -0
  320. package/src/internal/utils/path.ts +88 -0
  321. package/src/internal/utils/sleep.ts +3 -0
  322. package/src/internal/utils/uuid.ts +17 -0
  323. package/src/internal/utils/values.ts +105 -0
  324. package/src/internal/utils.ts +8 -0
  325. package/src/lib/.keep +4 -0
  326. package/src/resource.ts +2 -0
  327. package/src/resources/database.ts +67 -0
  328. package/src/resources/fax.ts +215 -0
  329. package/src/resources/health.ts +22 -0
  330. package/src/resources/index.ts +13 -0
  331. package/src/resources/providers.ts +122 -0
  332. package/src/resources/version.ts +22 -0
  333. package/src/resources.ts +1 -0
  334. package/src/tsconfig.json +11 -0
  335. package/src/uploads.ts +2 -0
  336. package/src/version.ts +1 -0
  337. package/uploads.d.mts +2 -0
  338. package/uploads.d.mts.map +1 -0
  339. package/uploads.d.ts +2 -0
  340. package/uploads.d.ts.map +1 -0
  341. package/uploads.js +6 -0
  342. package/uploads.js.map +1 -0
  343. package/uploads.mjs +2 -0
  344. package/uploads.mjs.map +1 -0
  345. package/version.d.mts +2 -0
  346. package/version.d.mts.map +1 -0
  347. package/version.d.ts +2 -0
  348. package/version.d.ts.map +1 -0
  349. package/version.js +5 -0
  350. package/version.js.map +1 -0
  351. package/version.mjs +2 -0
  352. package/version.mjs.map +1 -0
package/client.d.ts ADDED
@@ -0,0 +1,192 @@
1
+ import type { RequestInit, RequestInfo } from "./internal/builtin-types.js";
2
+ import type { PromiseOrValue, MergedRequestInit, FinalizedRequestInit } from "./internal/types.js";
3
+ export type { Logger, LogLevel } from "./internal/utils/log.js";
4
+ import * as Opts from "./internal/request-options.js";
5
+ import * as Errors from "./core/error.js";
6
+ import * as Uploads from "./core/uploads.js";
7
+ import * as API from "./resources/index.js";
8
+ import { APIPromise } from "./core/api-promise.js";
9
+ import { Database, DatabaseCheckHealthResponse } from "./resources/database.js";
10
+ import { Fax, FaxListProvidersResponse, FaxRetrieveStatusResponse, FaxSendParams, FaxSendResponse } from "./resources/fax.js";
11
+ import { Health, HealthCheckResponse } from "./resources/health.js";
12
+ import { ProviderLookupParams, ProviderLookupResponse, Providers } from "./resources/providers.js";
13
+ import { Version, VersionRetrieveResponse } from "./resources/version.js";
14
+ import { type Fetch } from "./internal/builtin-types.js";
15
+ import { HeadersLike, NullableHeaders } from "./internal/headers.js";
16
+ import { FinalRequestOptions, RequestOptions } from "./internal/request-options.js";
17
+ import { type LogLevel, type Logger } from "./internal/utils/log.js";
18
+ export interface ClientOptions {
19
+ /**
20
+ * API key for accessing BlueHive API endpoints. Format: "ApiKey <your-api-key>" or "Bearer <your-api-key>"
21
+ */
22
+ apiKey?: string | undefined;
23
+ /**
24
+ * Override the default base URL for the API, e.g., "https://api.example.com/v2/"
25
+ *
26
+ * Defaults to process.env['BLUE_HIVE_BASE_URL'].
27
+ */
28
+ baseURL?: string | null | undefined;
29
+ /**
30
+ * The maximum amount of time (in milliseconds) that the client should wait for a response
31
+ * from the server before timing out a single request.
32
+ *
33
+ * Note that request timeouts are retried by default, so in a worst-case scenario you may wait
34
+ * much longer than this timeout before the promise succeeds or fails.
35
+ *
36
+ * @unit milliseconds
37
+ */
38
+ timeout?: number | undefined;
39
+ /**
40
+ * Additional `RequestInit` options to be passed to `fetch` calls.
41
+ * Properties will be overridden by per-request `fetchOptions`.
42
+ */
43
+ fetchOptions?: MergedRequestInit | undefined;
44
+ /**
45
+ * Specify a custom `fetch` function implementation.
46
+ *
47
+ * If not provided, we expect that `fetch` is defined globally.
48
+ */
49
+ fetch?: Fetch | undefined;
50
+ /**
51
+ * The maximum number of times that the client will retry a request in case of a
52
+ * temporary failure, like a network error or a 5XX error from the server.
53
+ *
54
+ * @default 2
55
+ */
56
+ maxRetries?: number | undefined;
57
+ /**
58
+ * Default headers to include with every request to the API.
59
+ *
60
+ * These can be removed in individual requests by explicitly setting the
61
+ * header to `null` in request options.
62
+ */
63
+ defaultHeaders?: HeadersLike | undefined;
64
+ /**
65
+ * Default query parameters to include with every request to the API.
66
+ *
67
+ * These can be removed in individual requests by explicitly setting the
68
+ * param to `undefined` in request options.
69
+ */
70
+ defaultQuery?: Record<string, string | undefined> | undefined;
71
+ /**
72
+ * Set the log level.
73
+ *
74
+ * Defaults to process.env['BLUE_HIVE_LOG'] or 'warn' if it isn't set.
75
+ */
76
+ logLevel?: LogLevel | undefined;
77
+ /**
78
+ * Set the logger.
79
+ *
80
+ * Defaults to globalThis.console.
81
+ */
82
+ logger?: Logger | undefined;
83
+ }
84
+ /**
85
+ * API Client for interfacing with the BlueHive API.
86
+ */
87
+ export declare class BlueHive {
88
+ #private;
89
+ apiKey: string;
90
+ baseURL: string;
91
+ maxRetries: number;
92
+ timeout: number;
93
+ logger: Logger | undefined;
94
+ logLevel: LogLevel | undefined;
95
+ fetchOptions: MergedRequestInit | undefined;
96
+ private fetch;
97
+ protected idempotencyHeader?: string;
98
+ private _options;
99
+ /**
100
+ * API Client for interfacing with the BlueHive API.
101
+ *
102
+ * @param {string | undefined} [opts.apiKey=process.env['BLUEHIVE_API_KEY'] ?? undefined]
103
+ * @param {string} [opts.baseURL=process.env['BLUE_HIVE_BASE_URL'] ?? https://api.bluehive.com] - Override the default base URL for the API.
104
+ * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
105
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
106
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
107
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
108
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
109
+ * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
110
+ */
111
+ constructor({ baseURL, apiKey, ...opts }?: ClientOptions);
112
+ /**
113
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
114
+ */
115
+ withOptions(options: Partial<ClientOptions>): this;
116
+ protected defaultQuery(): Record<string, string | undefined> | undefined;
117
+ protected validateHeaders({ values, nulls }: NullableHeaders): void;
118
+ protected authHeaders(opts: FinalRequestOptions): Promise<NullableHeaders | undefined>;
119
+ /**
120
+ * Basic re-implementation of `qs.stringify` for primitive types.
121
+ */
122
+ protected stringifyQuery(query: Record<string, unknown>): string;
123
+ private getUserAgent;
124
+ protected defaultIdempotencyKey(): string;
125
+ protected makeStatusError(status: number, error: Object, message: string | undefined, headers: Headers): Errors.APIError;
126
+ buildURL(path: string, query: Record<string, unknown> | null | undefined, defaultBaseURL?: string | undefined): string;
127
+ /**
128
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
129
+ */
130
+ protected prepareOptions(options: FinalRequestOptions): Promise<void>;
131
+ /**
132
+ * Used as a callback for mutating the given `RequestInit` object.
133
+ *
134
+ * This is useful for cases where you want to add certain headers based off of
135
+ * the request properties, e.g. `method` or `url`.
136
+ */
137
+ protected prepareRequest(request: RequestInit, { url, options }: {
138
+ url: string;
139
+ options: FinalRequestOptions;
140
+ }): Promise<void>;
141
+ get<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp>;
142
+ post<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp>;
143
+ patch<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp>;
144
+ put<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp>;
145
+ delete<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp>;
146
+ private methodRequest;
147
+ request<Rsp>(options: PromiseOrValue<FinalRequestOptions>, remainingRetries?: number | null): APIPromise<Rsp>;
148
+ private makeRequest;
149
+ fetchWithTimeout(url: RequestInfo, init: RequestInit | undefined, ms: number, controller: AbortController): Promise<Response>;
150
+ private shouldRetry;
151
+ private retryRequest;
152
+ private calculateDefaultRetryTimeoutMillis;
153
+ buildRequest(inputOptions: FinalRequestOptions, { retryCount }?: {
154
+ retryCount?: number;
155
+ }): Promise<{
156
+ req: FinalizedRequestInit;
157
+ url: string;
158
+ timeout: number;
159
+ }>;
160
+ private buildHeaders;
161
+ private buildBody;
162
+ static BlueHive: typeof BlueHive;
163
+ static DEFAULT_TIMEOUT: number;
164
+ static BlueHiveError: typeof Errors.BlueHiveError;
165
+ static APIError: typeof Errors.APIError;
166
+ static APIConnectionError: typeof Errors.APIConnectionError;
167
+ static APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError;
168
+ static APIUserAbortError: typeof Errors.APIUserAbortError;
169
+ static NotFoundError: typeof Errors.NotFoundError;
170
+ static ConflictError: typeof Errors.ConflictError;
171
+ static RateLimitError: typeof Errors.RateLimitError;
172
+ static BadRequestError: typeof Errors.BadRequestError;
173
+ static AuthenticationError: typeof Errors.AuthenticationError;
174
+ static InternalServerError: typeof Errors.InternalServerError;
175
+ static PermissionDeniedError: typeof Errors.PermissionDeniedError;
176
+ static UnprocessableEntityError: typeof Errors.UnprocessableEntityError;
177
+ static toFile: typeof Uploads.toFile;
178
+ health: API.Health;
179
+ version: API.Version;
180
+ providers: API.Providers;
181
+ database: API.Database;
182
+ fax: API.Fax;
183
+ }
184
+ export declare namespace BlueHive {
185
+ export type RequestOptions = Opts.RequestOptions;
186
+ export { Health as Health, type HealthCheckResponse as HealthCheckResponse };
187
+ export { Version as Version, type VersionRetrieveResponse as VersionRetrieveResponse };
188
+ export { Providers as Providers, type ProviderLookupResponse as ProviderLookupResponse, type ProviderLookupParams as ProviderLookupParams, };
189
+ export { Database as Database, type DatabaseCheckHealthResponse as DatabaseCheckHealthResponse };
190
+ export { Fax as Fax, type FaxListProvidersResponse as FaxListProvidersResponse, type FaxRetrieveStatusResponse as FaxRetrieveStatusResponse, type FaxSendResponse as FaxSendResponse, type FaxSendParams as FaxSendParams, };
191
+ }
192
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["src/client.ts"],"names":[],"mappings":"OAEO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAY;OAC3C,KAAK,EAAc,cAAc,EAAE,iBAAiB,EAAE,oBAAoB,EAAE;YAIvE,EAAE,MAAM,EAAE,QAAQ,EAAE;OAKzB,KAAK,IAAI;OAET,KAAK,MAAM;OACX,KAAK,OAAO;OACZ,KAAK,GAAG;OACR,EAAE,UAAU,EAAE;OACd,EAAE,QAAQ,EAAE,2BAA2B,EAAE;OACzC,EACL,GAAG,EACH,wBAAwB,EACxB,yBAAyB,EACzB,aAAa,EACb,eAAe,EAChB;OACM,EAAE,MAAM,EAAE,mBAAmB,EAAE;OAC/B,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,SAAS,EAAE;OAC3D,EAAE,OAAO,EAAE,uBAAuB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AAI,oBAAoB,GAClD,CAAC;IAEF,OAAO,EAAE,QAAQ,IAAI,QAAQ,EAAE,KAAK,2BAA2B,IAAI,2BAA2B,EAAE,CAAC;IAEjG,OAAO,EACL,GAAG,IAAI,GAAG,EACV,KAAK,wBAAwB,IAAI,wBAAwB,EACzD,KAAK,yBAAyB,IAAI,yBAAyB,EAC3D,KAAK,eAAe,IAAI,eAAe,EACvC,KAAK,aAAa,IAAI,aAAa,GACpC,CAAC;CACH"}
package/client.js ADDED
@@ -0,0 +1,473 @@
1
+ "use strict";
2
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
3
+ var _BlueHive_instances, _a, _BlueHive_encoder, _BlueHive_baseURLOverridden;
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.BlueHive = void 0;
6
+ const tslib_1 = require("./internal/tslib.js");
7
+ const uuid_1 = require("./internal/utils/uuid.js");
8
+ const values_1 = require("./internal/utils/values.js");
9
+ const sleep_1 = require("./internal/utils/sleep.js");
10
+ const errors_1 = require("./internal/errors.js");
11
+ const detect_platform_1 = require("./internal/detect-platform.js");
12
+ const Shims = tslib_1.__importStar(require("./internal/shims.js"));
13
+ const Opts = tslib_1.__importStar(require("./internal/request-options.js"));
14
+ const version_1 = require("./version.js");
15
+ const Errors = tslib_1.__importStar(require("./core/error.js"));
16
+ const Uploads = tslib_1.__importStar(require("./core/uploads.js"));
17
+ const API = tslib_1.__importStar(require("./resources/index.js"));
18
+ const api_promise_1 = require("./core/api-promise.js");
19
+ const database_1 = require("./resources/database.js");
20
+ const fax_1 = require("./resources/fax.js");
21
+ const health_1 = require("./resources/health.js");
22
+ const providers_1 = require("./resources/providers.js");
23
+ const version_2 = require("./resources/version.js");
24
+ const headers_1 = require("./internal/headers.js");
25
+ const env_1 = require("./internal/utils/env.js");
26
+ const log_1 = require("./internal/utils/log.js");
27
+ const values_2 = require("./internal/utils/values.js");
28
+ /**
29
+ * API Client for interfacing with the BlueHive API.
30
+ */
31
+ class BlueHive {
32
+ /**
33
+ * API Client for interfacing with the BlueHive API.
34
+ *
35
+ * @param {string | undefined} [opts.apiKey=process.env['BLUEHIVE_API_KEY'] ?? undefined]
36
+ * @param {string} [opts.baseURL=process.env['BLUE_HIVE_BASE_URL'] ?? https://api.bluehive.com] - Override the default base URL for the API.
37
+ * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
38
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
39
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
40
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
41
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
42
+ * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
43
+ */
44
+ constructor({ baseURL = (0, env_1.readEnv)('BLUE_HIVE_BASE_URL'), apiKey = (0, env_1.readEnv)('BLUEHIVE_API_KEY'), ...opts } = {}) {
45
+ _BlueHive_instances.add(this);
46
+ _BlueHive_encoder.set(this, void 0);
47
+ this.health = new API.Health(this);
48
+ this.version = new API.Version(this);
49
+ this.providers = new API.Providers(this);
50
+ this.database = new API.Database(this);
51
+ this.fax = new API.Fax(this);
52
+ if (apiKey === undefined) {
53
+ throw new Errors.BlueHiveError("The BLUEHIVE_API_KEY environment variable is missing or empty; either provide it, or instantiate the BlueHive client with an apiKey option, like new BlueHive({ apiKey: 'My API Key' }).");
54
+ }
55
+ const options = {
56
+ apiKey,
57
+ ...opts,
58
+ baseURL: baseURL || `https://api.bluehive.com`,
59
+ };
60
+ this.baseURL = options.baseURL;
61
+ this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
62
+ this.logger = options.logger ?? console;
63
+ const defaultLogLevel = 'warn';
64
+ // Set default logLevel early so that we can log a warning in parseLogLevel.
65
+ this.logLevel = defaultLogLevel;
66
+ this.logLevel =
67
+ (0, log_1.parseLogLevel)(options.logLevel, 'ClientOptions.logLevel', this) ??
68
+ (0, log_1.parseLogLevel)((0, env_1.readEnv)('BLUE_HIVE_LOG'), "process.env['BLUE_HIVE_LOG']", this) ??
69
+ defaultLogLevel;
70
+ this.fetchOptions = options.fetchOptions;
71
+ this.maxRetries = options.maxRetries ?? 2;
72
+ this.fetch = options.fetch ?? Shims.getDefaultFetch();
73
+ tslib_1.__classPrivateFieldSet(this, _BlueHive_encoder, Opts.FallbackEncoder, "f");
74
+ this._options = options;
75
+ this.apiKey = apiKey;
76
+ }
77
+ /**
78
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
79
+ */
80
+ withOptions(options) {
81
+ const client = new this.constructor({
82
+ ...this._options,
83
+ baseURL: this.baseURL,
84
+ maxRetries: this.maxRetries,
85
+ timeout: this.timeout,
86
+ logger: this.logger,
87
+ logLevel: this.logLevel,
88
+ fetch: this.fetch,
89
+ fetchOptions: this.fetchOptions,
90
+ apiKey: this.apiKey,
91
+ ...options,
92
+ });
93
+ return client;
94
+ }
95
+ defaultQuery() {
96
+ return this._options.defaultQuery;
97
+ }
98
+ validateHeaders({ values, nulls }) {
99
+ return;
100
+ }
101
+ async authHeaders(opts) {
102
+ return (0, headers_1.buildHeaders)([{ Authorization: this.apiKey }]);
103
+ }
104
+ /**
105
+ * Basic re-implementation of `qs.stringify` for primitive types.
106
+ */
107
+ stringifyQuery(query) {
108
+ return Object.entries(query)
109
+ .filter(([_, value]) => typeof value !== 'undefined')
110
+ .map(([key, value]) => {
111
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
112
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
113
+ }
114
+ if (value === null) {
115
+ return `${encodeURIComponent(key)}=`;
116
+ }
117
+ throw new Errors.BlueHiveError(`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.`);
118
+ })
119
+ .join('&');
120
+ }
121
+ getUserAgent() {
122
+ return `${this.constructor.name}/JS ${version_1.VERSION}`;
123
+ }
124
+ defaultIdempotencyKey() {
125
+ return `stainless-node-retry-${(0, uuid_1.uuid4)()}`;
126
+ }
127
+ makeStatusError(status, error, message, headers) {
128
+ return Errors.APIError.generate(status, error, message, headers);
129
+ }
130
+ buildURL(path, query, defaultBaseURL) {
131
+ const baseURL = (!tslib_1.__classPrivateFieldGet(this, _BlueHive_instances, "m", _BlueHive_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
132
+ const url = (0, values_1.isAbsoluteURL)(path) ?
133
+ new URL(path)
134
+ : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
135
+ const defaultQuery = this.defaultQuery();
136
+ if (!(0, values_2.isEmptyObj)(defaultQuery)) {
137
+ query = { ...defaultQuery, ...query };
138
+ }
139
+ if (typeof query === 'object' && query && !Array.isArray(query)) {
140
+ url.search = this.stringifyQuery(query);
141
+ }
142
+ return url.toString();
143
+ }
144
+ /**
145
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
146
+ */
147
+ async prepareOptions(options) { }
148
+ /**
149
+ * Used as a callback for mutating the given `RequestInit` object.
150
+ *
151
+ * This is useful for cases where you want to add certain headers based off of
152
+ * the request properties, e.g. `method` or `url`.
153
+ */
154
+ async prepareRequest(request, { url, options }) { }
155
+ get(path, opts) {
156
+ return this.methodRequest('get', path, opts);
157
+ }
158
+ post(path, opts) {
159
+ return this.methodRequest('post', path, opts);
160
+ }
161
+ patch(path, opts) {
162
+ return this.methodRequest('patch', path, opts);
163
+ }
164
+ put(path, opts) {
165
+ return this.methodRequest('put', path, opts);
166
+ }
167
+ delete(path, opts) {
168
+ return this.methodRequest('delete', path, opts);
169
+ }
170
+ methodRequest(method, path, opts) {
171
+ return this.request(Promise.resolve(opts).then((opts) => {
172
+ return { method, path, ...opts };
173
+ }));
174
+ }
175
+ request(options, remainingRetries = null) {
176
+ return new api_promise_1.APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
177
+ }
178
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
179
+ const options = await optionsInput;
180
+ const maxRetries = options.maxRetries ?? this.maxRetries;
181
+ if (retriesRemaining == null) {
182
+ retriesRemaining = maxRetries;
183
+ }
184
+ await this.prepareOptions(options);
185
+ const { req, url, timeout } = await this.buildRequest(options, {
186
+ retryCount: maxRetries - retriesRemaining,
187
+ });
188
+ await this.prepareRequest(req, { url, options });
189
+ /** Not an API request ID, just for correlating local log entries. */
190
+ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
191
+ const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
192
+ const startTime = Date.now();
193
+ (0, log_1.loggerFor)(this).debug(`[${requestLogID}] sending request`, (0, log_1.formatRequestDetails)({
194
+ retryOfRequestLogID,
195
+ method: options.method,
196
+ url,
197
+ options,
198
+ headers: req.headers,
199
+ }));
200
+ if (options.signal?.aborted) {
201
+ throw new Errors.APIUserAbortError();
202
+ }
203
+ const controller = new AbortController();
204
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(errors_1.castToError);
205
+ const headersTime = Date.now();
206
+ if (response instanceof Error) {
207
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
208
+ if (options.signal?.aborted) {
209
+ throw new Errors.APIUserAbortError();
210
+ }
211
+ // detect native connection timeout errors
212
+ // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
213
+ // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
214
+ // others do not provide enough information to distinguish timeouts from other connection errors
215
+ const isTimeout = (0, errors_1.isAbortError)(response) ||
216
+ /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
217
+ if (retriesRemaining) {
218
+ (0, log_1.loggerFor)(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
219
+ (0, log_1.loggerFor)(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, (0, log_1.formatRequestDetails)({
220
+ retryOfRequestLogID,
221
+ url,
222
+ durationMs: headersTime - startTime,
223
+ message: response.message,
224
+ }));
225
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
226
+ }
227
+ (0, log_1.loggerFor)(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
228
+ (0, log_1.loggerFor)(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, (0, log_1.formatRequestDetails)({
229
+ retryOfRequestLogID,
230
+ url,
231
+ durationMs: headersTime - startTime,
232
+ message: response.message,
233
+ }));
234
+ if (isTimeout) {
235
+ throw new Errors.APIConnectionTimeoutError();
236
+ }
237
+ throw new Errors.APIConnectionError({ cause: response });
238
+ }
239
+ const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
240
+ if (!response.ok) {
241
+ const shouldRetry = await this.shouldRetry(response);
242
+ if (retriesRemaining && shouldRetry) {
243
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
244
+ // We don't need the body of this response.
245
+ await Shims.CancelReadableStream(response.body);
246
+ (0, log_1.loggerFor)(this).info(`${responseInfo} - ${retryMessage}`);
247
+ (0, log_1.loggerFor)(this).debug(`[${requestLogID}] response error (${retryMessage})`, (0, log_1.formatRequestDetails)({
248
+ retryOfRequestLogID,
249
+ url: response.url,
250
+ status: response.status,
251
+ headers: response.headers,
252
+ durationMs: headersTime - startTime,
253
+ }));
254
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
255
+ }
256
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
257
+ (0, log_1.loggerFor)(this).info(`${responseInfo} - ${retryMessage}`);
258
+ const errText = await response.text().catch((err) => (0, errors_1.castToError)(err).message);
259
+ const errJSON = (0, values_1.safeJSON)(errText);
260
+ const errMessage = errJSON ? undefined : errText;
261
+ (0, log_1.loggerFor)(this).debug(`[${requestLogID}] response error (${retryMessage})`, (0, log_1.formatRequestDetails)({
262
+ retryOfRequestLogID,
263
+ url: response.url,
264
+ status: response.status,
265
+ headers: response.headers,
266
+ message: errMessage,
267
+ durationMs: Date.now() - startTime,
268
+ }));
269
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
270
+ throw err;
271
+ }
272
+ (0, log_1.loggerFor)(this).info(responseInfo);
273
+ (0, log_1.loggerFor)(this).debug(`[${requestLogID}] response start`, (0, log_1.formatRequestDetails)({
274
+ retryOfRequestLogID,
275
+ url: response.url,
276
+ status: response.status,
277
+ headers: response.headers,
278
+ durationMs: headersTime - startTime,
279
+ }));
280
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
281
+ }
282
+ async fetchWithTimeout(url, init, ms, controller) {
283
+ const { signal, method, ...options } = init || {};
284
+ if (signal)
285
+ signal.addEventListener('abort', () => controller.abort());
286
+ const timeout = setTimeout(() => controller.abort(), ms);
287
+ const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
288
+ (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
289
+ const fetchOptions = {
290
+ signal: controller.signal,
291
+ ...(isReadableBody ? { duplex: 'half' } : {}),
292
+ method: 'GET',
293
+ ...options,
294
+ };
295
+ if (method) {
296
+ // Custom methods like 'patch' need to be uppercased
297
+ // See https://github.com/nodejs/undici/issues/2294
298
+ fetchOptions.method = method.toUpperCase();
299
+ }
300
+ try {
301
+ // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
302
+ return await this.fetch.call(undefined, url, fetchOptions);
303
+ }
304
+ finally {
305
+ clearTimeout(timeout);
306
+ }
307
+ }
308
+ async shouldRetry(response) {
309
+ // Note this is not a standard header.
310
+ const shouldRetryHeader = response.headers.get('x-should-retry');
311
+ // If the server explicitly says whether or not to retry, obey.
312
+ if (shouldRetryHeader === 'true')
313
+ return true;
314
+ if (shouldRetryHeader === 'false')
315
+ return false;
316
+ // Retry on request timeouts.
317
+ if (response.status === 408)
318
+ return true;
319
+ // Retry on lock timeouts.
320
+ if (response.status === 409)
321
+ return true;
322
+ // Retry on rate limits.
323
+ if (response.status === 429)
324
+ return true;
325
+ // Retry internal errors.
326
+ if (response.status >= 500)
327
+ return true;
328
+ return false;
329
+ }
330
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
331
+ let timeoutMillis;
332
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
333
+ const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
334
+ if (retryAfterMillisHeader) {
335
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
336
+ if (!Number.isNaN(timeoutMs)) {
337
+ timeoutMillis = timeoutMs;
338
+ }
339
+ }
340
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
341
+ const retryAfterHeader = responseHeaders?.get('retry-after');
342
+ if (retryAfterHeader && !timeoutMillis) {
343
+ const timeoutSeconds = parseFloat(retryAfterHeader);
344
+ if (!Number.isNaN(timeoutSeconds)) {
345
+ timeoutMillis = timeoutSeconds * 1000;
346
+ }
347
+ else {
348
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
349
+ }
350
+ }
351
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
352
+ // just do what it says, but otherwise calculate a default
353
+ if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
354
+ const maxRetries = options.maxRetries ?? this.maxRetries;
355
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
356
+ }
357
+ await (0, sleep_1.sleep)(timeoutMillis);
358
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
359
+ }
360
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
361
+ const initialRetryDelay = 0.5;
362
+ const maxRetryDelay = 8.0;
363
+ const numRetries = maxRetries - retriesRemaining;
364
+ // Apply exponential backoff, but not more than the max.
365
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
366
+ // Apply some jitter, take up to at most 25 percent of the retry time.
367
+ const jitter = 1 - Math.random() * 0.25;
368
+ return sleepSeconds * jitter * 1000;
369
+ }
370
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
371
+ const options = { ...inputOptions };
372
+ const { method, path, query, defaultBaseURL } = options;
373
+ const url = this.buildURL(path, query, defaultBaseURL);
374
+ if ('timeout' in options)
375
+ (0, values_1.validatePositiveInteger)('timeout', options.timeout);
376
+ options.timeout = options.timeout ?? this.timeout;
377
+ const { bodyHeaders, body } = this.buildBody({ options });
378
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
379
+ const req = {
380
+ method,
381
+ headers: reqHeaders,
382
+ ...(options.signal && { signal: options.signal }),
383
+ ...(globalThis.ReadableStream &&
384
+ body instanceof globalThis.ReadableStream && { duplex: 'half' }),
385
+ ...(body && { body }),
386
+ ...(this.fetchOptions ?? {}),
387
+ ...(options.fetchOptions ?? {}),
388
+ };
389
+ return { req, url, timeout: options.timeout };
390
+ }
391
+ async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
392
+ let idempotencyHeaders = {};
393
+ if (this.idempotencyHeader && method !== 'get') {
394
+ if (!options.idempotencyKey)
395
+ options.idempotencyKey = this.defaultIdempotencyKey();
396
+ idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
397
+ }
398
+ const headers = (0, headers_1.buildHeaders)([
399
+ idempotencyHeaders,
400
+ {
401
+ Accept: 'application/json',
402
+ 'User-Agent': this.getUserAgent(),
403
+ 'X-Stainless-Retry-Count': String(retryCount),
404
+ ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
405
+ ...(0, detect_platform_1.getPlatformHeaders)(),
406
+ },
407
+ await this.authHeaders(options),
408
+ this._options.defaultHeaders,
409
+ bodyHeaders,
410
+ options.headers,
411
+ ]);
412
+ this.validateHeaders(headers);
413
+ return headers.values;
414
+ }
415
+ buildBody({ options: { body, headers: rawHeaders } }) {
416
+ if (!body) {
417
+ return { bodyHeaders: undefined, body: undefined };
418
+ }
419
+ const headers = (0, headers_1.buildHeaders)([rawHeaders]);
420
+ if (
421
+ // Pass raw type verbatim
422
+ ArrayBuffer.isView(body) ||
423
+ body instanceof ArrayBuffer ||
424
+ body instanceof DataView ||
425
+ (typeof body === 'string' &&
426
+ // Preserve legacy string encoding behavior for now
427
+ headers.values.has('content-type')) ||
428
+ // `Blob` is superset of `File`
429
+ body instanceof Blob ||
430
+ // `FormData` -> `multipart/form-data`
431
+ body instanceof FormData ||
432
+ // `URLSearchParams` -> `application/x-www-form-urlencoded`
433
+ body instanceof URLSearchParams ||
434
+ // Send chunked stream (each chunk has own `length`)
435
+ (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
436
+ return { bodyHeaders: undefined, body: body };
437
+ }
438
+ else if (typeof body === 'object' &&
439
+ (Symbol.asyncIterator in body ||
440
+ (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
441
+ return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body) };
442
+ }
443
+ else {
444
+ return tslib_1.__classPrivateFieldGet(this, _BlueHive_encoder, "f").call(this, { body, headers });
445
+ }
446
+ }
447
+ }
448
+ exports.BlueHive = BlueHive;
449
+ _a = BlueHive, _BlueHive_encoder = new WeakMap(), _BlueHive_instances = new WeakSet(), _BlueHive_baseURLOverridden = function _BlueHive_baseURLOverridden() {
450
+ return this.baseURL !== 'https://api.bluehive.com';
451
+ };
452
+ BlueHive.BlueHive = _a;
453
+ BlueHive.DEFAULT_TIMEOUT = 60000; // 1 minute
454
+ BlueHive.BlueHiveError = Errors.BlueHiveError;
455
+ BlueHive.APIError = Errors.APIError;
456
+ BlueHive.APIConnectionError = Errors.APIConnectionError;
457
+ BlueHive.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
458
+ BlueHive.APIUserAbortError = Errors.APIUserAbortError;
459
+ BlueHive.NotFoundError = Errors.NotFoundError;
460
+ BlueHive.ConflictError = Errors.ConflictError;
461
+ BlueHive.RateLimitError = Errors.RateLimitError;
462
+ BlueHive.BadRequestError = Errors.BadRequestError;
463
+ BlueHive.AuthenticationError = Errors.AuthenticationError;
464
+ BlueHive.InternalServerError = Errors.InternalServerError;
465
+ BlueHive.PermissionDeniedError = Errors.PermissionDeniedError;
466
+ BlueHive.UnprocessableEntityError = Errors.UnprocessableEntityError;
467
+ BlueHive.toFile = Uploads.toFile;
468
+ BlueHive.Health = health_1.Health;
469
+ BlueHive.Version = version_2.Version;
470
+ BlueHive.Providers = providers_1.Providers;
471
+ BlueHive.Database = database_1.Database;
472
+ BlueHive.Fax = fax_1.Fax;
473
+ //# sourceMappingURL=client.js.map