@space-df/sdk 0.0.1-dev.3.3 → 0.0.1-dev.5

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 (341) hide show
  1. package/.editorconfig +24 -0
  2. package/.github/pull_request_template.md +25 -0
  3. package/.github/workflows/bump-version.yml +67 -0
  4. package/.github/workflows/publish-package.yml +28 -0
  5. package/.gitignore +11 -0
  6. package/CODE_OF_CONDUCT.md +128 -0
  7. package/CONTRIBUTING.md +89 -0
  8. package/api.doc.md +1537 -0
  9. package/dist/LICENSE +7 -0
  10. package/dist/README.md +382 -0
  11. package/{index.d.mts → dist/index.d.mts} +4 -0
  12. package/{index.d.ts → dist/index.d.ts} +4 -0
  13. package/{index.d.ts.map → dist/index.d.ts.map} +1 -1
  14. package/{index.js → dist/index.js} +4 -0
  15. package/dist/index.js.map +1 -0
  16. package/{index.mjs → dist/index.mjs} +4 -0
  17. package/dist/index.mjs.map +1 -0
  18. package/dist/package.json +101 -0
  19. package/{resources → dist/resources}/auth/auth.d.ts +5 -0
  20. package/dist/resources/auth/auth.d.ts.map +1 -0
  21. package/{resources → dist/resources}/auth/auth.js +3 -0
  22. package/dist/resources/auth/auth.js.map +1 -0
  23. package/{resources → dist/resources}/auth/auth.mjs +3 -0
  24. package/dist/resources/auth/auth.mjs.map +1 -0
  25. package/{resources → dist/resources}/auth/index.d.ts +4 -0
  26. package/{resources → dist/resources}/auth/index.d.ts.map +1 -1
  27. package/{resources → dist/resources}/auth/index.js +4 -0
  28. package/{resources → dist/resources}/auth/index.js.map +1 -1
  29. package/{resources → dist/resources}/auth/index.mjs +4 -0
  30. package/dist/resources/auth/invitation.d.ts +13 -0
  31. package/dist/resources/auth/invitation.d.ts.map +1 -0
  32. package/dist/resources/auth/invitation.js +11 -0
  33. package/dist/resources/auth/invitation.js.map +1 -0
  34. package/dist/resources/auth/invitation.mjs +7 -0
  35. package/dist/resources/auth/invitation.mjs.map +1 -0
  36. package/dist/resources/auth/join-space.d.ts +6 -0
  37. package/dist/resources/auth/join-space.d.ts.map +1 -0
  38. package/dist/resources/auth/join-space.js +11 -0
  39. package/dist/resources/auth/join-space.js.map +1 -0
  40. package/dist/resources/auth/join-space.mjs +7 -0
  41. package/dist/resources/auth/join-space.mjs.map +1 -0
  42. package/dist/resources/auth/presigned-url.d.ts +10 -0
  43. package/dist/resources/auth/presigned-url.d.ts.map +1 -0
  44. package/dist/resources/auth/presigned-url.js +11 -0
  45. package/dist/resources/auth/presigned-url.js.map +1 -0
  46. package/dist/resources/auth/presigned-url.mjs +7 -0
  47. package/dist/resources/auth/presigned-url.mjs.map +1 -0
  48. package/{resources → dist/resources}/auth/space-role-users.d.ts +5 -0
  49. package/dist/resources/auth/space-role-users.d.ts.map +1 -0
  50. package/{resources → dist/resources}/auth/space-role-users.js +16 -0
  51. package/dist/resources/auth/space-role-users.js.map +1 -0
  52. package/{resources → dist/resources}/auth/space-role-users.mjs +16 -0
  53. package/dist/resources/auth/space-role-users.mjs.map +1 -0
  54. package/dist/resources/auth/users.d.ts +19 -0
  55. package/dist/resources/auth/users.d.ts.map +1 -0
  56. package/dist/resources/auth/users.js +17 -0
  57. package/dist/resources/auth/users.js.map +1 -0
  58. package/dist/resources/auth/users.mjs +13 -0
  59. package/dist/resources/auth/users.mjs.map +1 -0
  60. package/dist/src/_shims/MultipartBody.ts +9 -0
  61. package/dist/src/_shims/README.md +46 -0
  62. package/dist/src/_shims/auto/runtime-bun.ts +4 -0
  63. package/dist/src/_shims/auto/runtime-node.ts +4 -0
  64. package/dist/src/_shims/auto/runtime.ts +4 -0
  65. package/dist/src/_shims/auto/types-node.ts +4 -0
  66. package/dist/src/_shims/auto/types.d.ts +101 -0
  67. package/dist/src/_shims/auto/types.js +3 -0
  68. package/dist/src/_shims/auto/types.mjs +3 -0
  69. package/dist/src/_shims/bun-runtime.ts +14 -0
  70. package/dist/src/_shims/index.d.ts +72 -0
  71. package/dist/src/_shims/index.js +13 -0
  72. package/dist/src/_shims/index.mjs +7 -0
  73. package/dist/src/_shims/manual-types.d.ts +12 -0
  74. package/dist/src/_shims/manual-types.js +3 -0
  75. package/dist/src/_shims/manual-types.mjs +3 -0
  76. package/dist/src/_shims/node-runtime.ts +78 -0
  77. package/dist/src/_shims/node-types.d.ts +42 -0
  78. package/dist/src/_shims/node-types.js +3 -0
  79. package/dist/src/_shims/node-types.mjs +3 -0
  80. package/dist/src/_shims/registry.ts +60 -0
  81. package/dist/src/_shims/web-runtime.ts +91 -0
  82. package/dist/src/_shims/web-types.d.ts +83 -0
  83. package/dist/src/_shims/web-types.js +3 -0
  84. package/dist/src/_shims/web-types.mjs +3 -0
  85. package/dist/src/core.ts +1061 -0
  86. package/dist/src/error.ts +134 -0
  87. package/dist/src/index.ts +210 -0
  88. package/dist/src/libs/utils.ts +66 -0
  89. package/dist/src/resource.ts +9 -0
  90. package/dist/src/resources/auth/auth.ts +102 -0
  91. package/dist/src/resources/auth/credentials.ts +12 -0
  92. package/dist/src/resources/auth/index.ts +10 -0
  93. package/dist/src/resources/auth/invitation.ts +17 -0
  94. package/dist/src/resources/auth/join-space.ts +8 -0
  95. package/dist/src/resources/auth/presigned-url.ts +13 -0
  96. package/dist/src/resources/auth/space-policies.ts +55 -0
  97. package/dist/src/resources/auth/space-role-users.ts +64 -0
  98. package/dist/src/resources/auth/space-roles.ts +95 -0
  99. package/dist/src/resources/auth/spaces.ts +118 -0
  100. package/dist/src/resources/auth/users.ts +36 -0
  101. package/dist/src/resources/console/index.ts +1 -0
  102. package/dist/src/resources/console/oauth2.ts +83 -0
  103. package/dist/src/resources/dashboard/dashboards.ts +171 -0
  104. package/dist/src/resources/dashboard/device-states.ts +142 -0
  105. package/dist/src/resources/dashboard/index.ts +2 -0
  106. package/dist/src/resources/index.ts +6 -0
  107. package/dist/src/shims/node.ts +50 -0
  108. package/dist/src/shims/web.ts +50 -0
  109. package/dist/src/types/api.ts +31 -0
  110. package/dist/src/types/jwt.ts +12 -0
  111. package/dist/src/version.ts +1 -0
  112. package/dist/version.d.ts +2 -0
  113. package/dist/version.d.ts.map +1 -0
  114. package/{version.js → dist/version.js} +1 -1
  115. package/dist/version.js.map +1 -0
  116. package/dist/version.mjs +2 -0
  117. package/{version.mjs.map → dist/version.mjs.map} +1 -1
  118. package/eslint.config.mjs +33 -0
  119. package/examples/auth/login.ts +14 -0
  120. package/examples/auth/register.ts +15 -0
  121. package/examples/console/oauth2.ts +15 -0
  122. package/package.json +52 -36
  123. package/scripts/build +56 -0
  124. package/scripts/utils/check-version.cjs +20 -0
  125. package/scripts/utils/fix-index-exports.cjs +8 -0
  126. package/scripts/utils/make-dist-package-json.cjs +21 -0
  127. package/scripts/utils/postprocess-files.cjs +153 -0
  128. package/src/_shims/auto/runtime-deno.ts +4 -0
  129. package/src/_shims/auto/types-deno.ts +4 -0
  130. package/src/_shims/auto/types.d.ts +18 -18
  131. package/src/_shims/index-deno.ts +105 -0
  132. package/src/_shims/index.d.ts +1 -1
  133. package/src/_shims/index.mjs +1 -1
  134. package/src/index.ts +4 -0
  135. package/src/resources/auth/auth.ts +10 -0
  136. package/src/resources/auth/index.ts +4 -0
  137. package/src/resources/auth/invitation.ts +17 -0
  138. package/src/resources/auth/join-space.ts +8 -0
  139. package/src/resources/auth/presigned-url.ts +13 -0
  140. package/src/resources/auth/space-role-users.ts +22 -0
  141. package/src/resources/auth/users.ts +36 -0
  142. package/src/version.ts +1 -1
  143. package/tsc-multi.json +7 -0
  144. package/tsconfig.build.json +18 -0
  145. package/tsconfig.deno.json +20 -0
  146. package/tsconfig.dist-src.json +11 -0
  147. package/tsconfig.json +38 -0
  148. package/index.js.map +0 -1
  149. package/index.mjs.map +0 -1
  150. package/resources/auth/auth.d.ts.map +0 -1
  151. package/resources/auth/auth.js.map +0 -1
  152. package/resources/auth/auth.mjs.map +0 -1
  153. package/resources/auth/space-role-users.d.ts.map +0 -1
  154. package/resources/auth/space-role-users.js.map +0 -1
  155. package/resources/auth/space-role-users.mjs.map +0 -1
  156. package/src/resources/.DS_Store +0 -0
  157. package/version.d.ts +0 -2
  158. package/version.d.ts.map +0 -1
  159. package/version.js.map +0 -1
  160. package/version.mjs +0 -2
  161. package/yarn.lock +0 -268
  162. /package/{_shims → dist/_shims}/MultipartBody.d.ts +0 -0
  163. /package/{_shims → dist/_shims}/MultipartBody.d.ts.map +0 -0
  164. /package/{_shims → dist/_shims}/MultipartBody.js +0 -0
  165. /package/{_shims → dist/_shims}/MultipartBody.js.map +0 -0
  166. /package/{_shims → dist/_shims}/MultipartBody.mjs +0 -0
  167. /package/{_shims → dist/_shims}/MultipartBody.mjs.map +0 -0
  168. /package/{_shims → dist/_shims}/README.md +0 -0
  169. /package/{_shims → dist/_shims}/auto/runtime-bun.d.ts +0 -0
  170. /package/{_shims → dist/_shims}/auto/runtime-bun.d.ts.map +0 -0
  171. /package/{_shims → dist/_shims}/auto/runtime-bun.js +0 -0
  172. /package/{_shims → dist/_shims}/auto/runtime-bun.js.map +0 -0
  173. /package/{_shims → dist/_shims}/auto/runtime-bun.mjs +0 -0
  174. /package/{_shims → dist/_shims}/auto/runtime-bun.mjs.map +0 -0
  175. /package/{_shims → dist/_shims}/auto/runtime-node.d.ts +0 -0
  176. /package/{_shims → dist/_shims}/auto/runtime-node.d.ts.map +0 -0
  177. /package/{_shims → dist/_shims}/auto/runtime-node.js +0 -0
  178. /package/{_shims → dist/_shims}/auto/runtime-node.js.map +0 -0
  179. /package/{_shims → dist/_shims}/auto/runtime-node.mjs +0 -0
  180. /package/{_shims → dist/_shims}/auto/runtime-node.mjs.map +0 -0
  181. /package/{_shims → dist/_shims}/auto/runtime.d.ts +0 -0
  182. /package/{_shims → dist/_shims}/auto/runtime.d.ts.map +0 -0
  183. /package/{_shims → dist/_shims}/auto/runtime.js +0 -0
  184. /package/{_shims → dist/_shims}/auto/runtime.js.map +0 -0
  185. /package/{_shims → dist/_shims}/auto/runtime.mjs +0 -0
  186. /package/{_shims → dist/_shims}/auto/runtime.mjs.map +0 -0
  187. /package/{_shims → dist/_shims}/auto/types-node.d.ts +0 -0
  188. /package/{_shims → dist/_shims}/auto/types-node.d.ts.map +0 -0
  189. /package/{_shims → dist/_shims}/auto/types-node.js +0 -0
  190. /package/{_shims → dist/_shims}/auto/types-node.js.map +0 -0
  191. /package/{_shims → dist/_shims}/auto/types-node.mjs +0 -0
  192. /package/{_shims → dist/_shims}/auto/types-node.mjs.map +0 -0
  193. /package/{_shims → dist/_shims}/auto/types.d.ts +0 -0
  194. /package/{_shims → dist/_shims}/auto/types.js +0 -0
  195. /package/{_shims → dist/_shims}/auto/types.mjs +0 -0
  196. /package/{_shims → dist/_shims}/bun-runtime.d.ts +0 -0
  197. /package/{_shims → dist/_shims}/bun-runtime.d.ts.map +0 -0
  198. /package/{_shims → dist/_shims}/bun-runtime.js +0 -0
  199. /package/{_shims → dist/_shims}/bun-runtime.js.map +0 -0
  200. /package/{_shims → dist/_shims}/bun-runtime.mjs +0 -0
  201. /package/{_shims → dist/_shims}/bun-runtime.mjs.map +0 -0
  202. /package/{_shims → dist/_shims}/index.d.ts +0 -0
  203. /package/{_shims → dist/_shims}/index.js +0 -0
  204. /package/{_shims → dist/_shims}/index.mjs +0 -0
  205. /package/{_shims → dist/_shims}/manual-types.d.ts +0 -0
  206. /package/{_shims → dist/_shims}/manual-types.js +0 -0
  207. /package/{_shims → dist/_shims}/manual-types.mjs +0 -0
  208. /package/{_shims → dist/_shims}/node-runtime.d.ts +0 -0
  209. /package/{_shims → dist/_shims}/node-runtime.d.ts.map +0 -0
  210. /package/{_shims → dist/_shims}/node-runtime.js +0 -0
  211. /package/{_shims → dist/_shims}/node-runtime.js.map +0 -0
  212. /package/{_shims → dist/_shims}/node-runtime.mjs +0 -0
  213. /package/{_shims → dist/_shims}/node-runtime.mjs.map +0 -0
  214. /package/{_shims → dist/_shims}/node-types.d.ts +0 -0
  215. /package/{_shims → dist/_shims}/node-types.js +0 -0
  216. /package/{_shims → dist/_shims}/node-types.mjs +0 -0
  217. /package/{_shims → dist/_shims}/registry.d.ts +0 -0
  218. /package/{_shims → dist/_shims}/registry.d.ts.map +0 -0
  219. /package/{_shims → dist/_shims}/registry.js +0 -0
  220. /package/{_shims → dist/_shims}/registry.js.map +0 -0
  221. /package/{_shims → dist/_shims}/registry.mjs +0 -0
  222. /package/{_shims → dist/_shims}/registry.mjs.map +0 -0
  223. /package/{_shims → dist/_shims}/web-runtime.d.ts +0 -0
  224. /package/{_shims → dist/_shims}/web-runtime.d.ts.map +0 -0
  225. /package/{_shims → dist/_shims}/web-runtime.js +0 -0
  226. /package/{_shims → dist/_shims}/web-runtime.js.map +0 -0
  227. /package/{_shims → dist/_shims}/web-runtime.mjs +0 -0
  228. /package/{_shims → dist/_shims}/web-runtime.mjs.map +0 -0
  229. /package/{_shims → dist/_shims}/web-types.d.ts +0 -0
  230. /package/{_shims → dist/_shims}/web-types.js +0 -0
  231. /package/{_shims → dist/_shims}/web-types.mjs +0 -0
  232. /package/{core.d.ts → dist/core.d.ts} +0 -0
  233. /package/{core.d.ts.map → dist/core.d.ts.map} +0 -0
  234. /package/{core.js → dist/core.js} +0 -0
  235. /package/{core.js.map → dist/core.js.map} +0 -0
  236. /package/{core.mjs → dist/core.mjs} +0 -0
  237. /package/{core.mjs.map → dist/core.mjs.map} +0 -0
  238. /package/{error.d.ts → dist/error.d.ts} +0 -0
  239. /package/{error.d.ts.map → dist/error.d.ts.map} +0 -0
  240. /package/{error.js → dist/error.js} +0 -0
  241. /package/{error.js.map → dist/error.js.map} +0 -0
  242. /package/{error.mjs → dist/error.mjs} +0 -0
  243. /package/{error.mjs.map → dist/error.mjs.map} +0 -0
  244. /package/{libs → dist/libs}/utils.d.ts +0 -0
  245. /package/{libs → dist/libs}/utils.d.ts.map +0 -0
  246. /package/{libs → dist/libs}/utils.js +0 -0
  247. /package/{libs → dist/libs}/utils.js.map +0 -0
  248. /package/{libs → dist/libs}/utils.mjs +0 -0
  249. /package/{libs → dist/libs}/utils.mjs.map +0 -0
  250. /package/{resource.d.ts → dist/resource.d.ts} +0 -0
  251. /package/{resource.d.ts.map → dist/resource.d.ts.map} +0 -0
  252. /package/{resource.js → dist/resource.js} +0 -0
  253. /package/{resource.js.map → dist/resource.js.map} +0 -0
  254. /package/{resource.mjs → dist/resource.mjs} +0 -0
  255. /package/{resource.mjs.map → dist/resource.mjs.map} +0 -0
  256. /package/{resources → dist/resources}/auth/credentials.d.ts +0 -0
  257. /package/{resources → dist/resources}/auth/credentials.d.ts.map +0 -0
  258. /package/{resources → dist/resources}/auth/credentials.js +0 -0
  259. /package/{resources → dist/resources}/auth/credentials.js.map +0 -0
  260. /package/{resources → dist/resources}/auth/credentials.mjs +0 -0
  261. /package/{resources → dist/resources}/auth/credentials.mjs.map +0 -0
  262. /package/{resources → dist/resources}/auth/index.mjs.map +0 -0
  263. /package/{resources → dist/resources}/auth/space-policies.d.ts +0 -0
  264. /package/{resources → dist/resources}/auth/space-policies.d.ts.map +0 -0
  265. /package/{resources → dist/resources}/auth/space-policies.js +0 -0
  266. /package/{resources → dist/resources}/auth/space-policies.js.map +0 -0
  267. /package/{resources → dist/resources}/auth/space-policies.mjs +0 -0
  268. /package/{resources → dist/resources}/auth/space-policies.mjs.map +0 -0
  269. /package/{resources → dist/resources}/auth/space-roles.d.ts +0 -0
  270. /package/{resources → dist/resources}/auth/space-roles.d.ts.map +0 -0
  271. /package/{resources → dist/resources}/auth/space-roles.js +0 -0
  272. /package/{resources → dist/resources}/auth/space-roles.js.map +0 -0
  273. /package/{resources → dist/resources}/auth/space-roles.mjs +0 -0
  274. /package/{resources → dist/resources}/auth/space-roles.mjs.map +0 -0
  275. /package/{resources → dist/resources}/auth/spaces.d.ts +0 -0
  276. /package/{resources → dist/resources}/auth/spaces.d.ts.map +0 -0
  277. /package/{resources → dist/resources}/auth/spaces.js +0 -0
  278. /package/{resources → dist/resources}/auth/spaces.js.map +0 -0
  279. /package/{resources → dist/resources}/auth/spaces.mjs +0 -0
  280. /package/{resources → dist/resources}/auth/spaces.mjs.map +0 -0
  281. /package/{resources → dist/resources}/console/index.d.ts +0 -0
  282. /package/{resources → dist/resources}/console/index.d.ts.map +0 -0
  283. /package/{resources → dist/resources}/console/index.js +0 -0
  284. /package/{resources → dist/resources}/console/index.js.map +0 -0
  285. /package/{resources → dist/resources}/console/index.mjs +0 -0
  286. /package/{resources → dist/resources}/console/index.mjs.map +0 -0
  287. /package/{resources → dist/resources}/console/oauth2.d.ts +0 -0
  288. /package/{resources → dist/resources}/console/oauth2.d.ts.map +0 -0
  289. /package/{resources → dist/resources}/console/oauth2.js +0 -0
  290. /package/{resources → dist/resources}/console/oauth2.js.map +0 -0
  291. /package/{resources → dist/resources}/console/oauth2.mjs +0 -0
  292. /package/{resources → dist/resources}/console/oauth2.mjs.map +0 -0
  293. /package/{resources → dist/resources}/dashboard/dashboards.d.ts +0 -0
  294. /package/{resources → dist/resources}/dashboard/dashboards.d.ts.map +0 -0
  295. /package/{resources → dist/resources}/dashboard/dashboards.js +0 -0
  296. /package/{resources → dist/resources}/dashboard/dashboards.js.map +0 -0
  297. /package/{resources → dist/resources}/dashboard/dashboards.mjs +0 -0
  298. /package/{resources → dist/resources}/dashboard/dashboards.mjs.map +0 -0
  299. /package/{resources → dist/resources}/dashboard/device-states.d.ts +0 -0
  300. /package/{resources → dist/resources}/dashboard/device-states.d.ts.map +0 -0
  301. /package/{resources → dist/resources}/dashboard/device-states.js +0 -0
  302. /package/{resources → dist/resources}/dashboard/device-states.js.map +0 -0
  303. /package/{resources → dist/resources}/dashboard/device-states.mjs +0 -0
  304. /package/{resources → dist/resources}/dashboard/device-states.mjs.map +0 -0
  305. /package/{resources → dist/resources}/dashboard/index.d.ts +0 -0
  306. /package/{resources → dist/resources}/dashboard/index.d.ts.map +0 -0
  307. /package/{resources → dist/resources}/dashboard/index.js +0 -0
  308. /package/{resources → dist/resources}/dashboard/index.js.map +0 -0
  309. /package/{resources → dist/resources}/dashboard/index.mjs +0 -0
  310. /package/{resources → dist/resources}/dashboard/index.mjs.map +0 -0
  311. /package/{resources → dist/resources}/index.d.ts +0 -0
  312. /package/{resources → dist/resources}/index.d.ts.map +0 -0
  313. /package/{resources → dist/resources}/index.js +0 -0
  314. /package/{resources → dist/resources}/index.js.map +0 -0
  315. /package/{resources → dist/resources}/index.mjs +0 -0
  316. /package/{resources → dist/resources}/index.mjs.map +0 -0
  317. /package/{shims → dist/shims}/node.d.ts +0 -0
  318. /package/{shims → dist/shims}/node.d.ts.map +0 -0
  319. /package/{shims → dist/shims}/node.js +0 -0
  320. /package/{shims → dist/shims}/node.js.map +0 -0
  321. /package/{shims → dist/shims}/node.mjs +0 -0
  322. /package/{shims → dist/shims}/node.mjs.map +0 -0
  323. /package/{shims → dist/shims}/web.d.ts +0 -0
  324. /package/{shims → dist/shims}/web.d.ts.map +0 -0
  325. /package/{shims → dist/shims}/web.js +0 -0
  326. /package/{shims → dist/shims}/web.js.map +0 -0
  327. /package/{shims → dist/shims}/web.mjs +0 -0
  328. /package/{shims → dist/shims}/web.mjs.map +0 -0
  329. /package/{src → dist/src}/tsconfig.json +0 -0
  330. /package/{types → dist/types}/api.d.ts +0 -0
  331. /package/{types → dist/types}/api.d.ts.map +0 -0
  332. /package/{types → dist/types}/api.js +0 -0
  333. /package/{types → dist/types}/api.js.map +0 -0
  334. /package/{types → dist/types}/api.mjs +0 -0
  335. /package/{types → dist/types}/api.mjs.map +0 -0
  336. /package/{types → dist/types}/jwt.d.ts +0 -0
  337. /package/{types → dist/types}/jwt.d.ts.map +0 -0
  338. /package/{types → dist/types}/jwt.js +0 -0
  339. /package/{types → dist/types}/jwt.js.map +0 -0
  340. /package/{types → dist/types}/jwt.mjs +0 -0
  341. /package/{types → dist/types}/jwt.mjs.map +0 -0
@@ -0,0 +1,1061 @@
1
+ import { uuid4 } from './libs/utils';
2
+ import { VERSION } from './version';
3
+ import { SpaceDFError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError } from './error';
4
+ import { type Readable, getDefaultAgent, type Agent, fetch, type RequestInfo, type RequestInit, type Response, type HeadersInit } from './_shims/index';
5
+ export { type Response };
6
+
7
+ export type Fetch = (url: RequestInfo, init?: RequestInit) => Promise<Response>;
8
+
9
+ type PromiseOrValue<T> = T | Promise<T>;
10
+
11
+ type APIResponseProps = {
12
+ response: Response;
13
+ options: FinalRequestOptions;
14
+ controller: AbortController;
15
+ };
16
+
17
+ async function defaultParseResponse<T>(props: APIResponseProps): Promise<T> {
18
+ const { response } = props;
19
+ // fetch refuses to read the body when the status code is 204.
20
+ if (response.status === 204) {
21
+ return null as T;
22
+ }
23
+
24
+ if (props.options.__binaryResponse) {
25
+ return response as unknown as T;
26
+ }
27
+
28
+ const contentType = response.headers.get('content-type');
29
+ const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json');
30
+ if (isJSON) {
31
+ const json = await response.json();
32
+
33
+ debug('response', response.status, response.url, response.headers, json);
34
+
35
+ return json as T;
36
+ }
37
+
38
+ const text = await response.text();
39
+ debug('response', response.status, response.url, response.headers, text);
40
+
41
+ // TODO handle blob, arraybuffer, other content types, etc.
42
+ return text as unknown as T;
43
+ }
44
+
45
+ /**
46
+ * A subclass of `Promise` providing additional helper methods
47
+ * for interacting with the SDK.
48
+ */
49
+ export class APIPromise<T> extends Promise<T> {
50
+ private parsedPromise: Promise<T> | undefined;
51
+
52
+ constructor(
53
+ private responsePromise: Promise<APIResponseProps>,
54
+ private parseResponse: (props: APIResponseProps) => PromiseOrValue<T> = defaultParseResponse,
55
+ ) {
56
+ super((resolve) => {
57
+ // this is maybe a bit weird but this has to be a no-op to not implicitly
58
+ // parse the response body; instead .then, .catch, .finally are overridden
59
+ // to parse the response
60
+ resolve(null as any);
61
+ });
62
+ }
63
+
64
+ _thenUnwrap<U>(transform: (data: T) => U): APIPromise<U> {
65
+ return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props)));
66
+ }
67
+
68
+ /**
69
+ * Gets the raw `Response` instance instead of parsing the response
70
+ * data.
71
+ *
72
+ * If you want to parse the response body but still get the `Response`
73
+ * instance, you can use {@link withResponse()}.
74
+ *
75
+ * 👋 Getting the wrong TypeScript type for `Response`?
76
+ * Try setting `"moduleResolution": "NodeNext"` if you can,
77
+ * or add one of these imports before your first `import … from 'spacedf-sdk'`:
78
+ * - `import 'spacedf-sdk/shims/node'` (if you're running on Node)
79
+ * - `import 'spacedf-sdk/shims/web'` (otherwise)
80
+ */
81
+ asResponse(): Promise<Response> {
82
+ return this.responsePromise.then((p) => p.response);
83
+ }
84
+ /**
85
+ * Gets the parsed response data and the raw `Response` instance.
86
+ *
87
+ * If you just want to get the raw `Response` instance without parsing it,
88
+ * you can use {@link asResponse()}.
89
+ *
90
+ *
91
+ * 👋 Getting the wrong TypeScript type for `Response`?
92
+ * Try setting `"moduleResolution": "NodeNext"` if you can,
93
+ * or add one of these imports before your first `import … from 'spacedf-sdk'`:
94
+ * - `import 'spacedf-sdk/shims/node'` (if you're running on Node)
95
+ * - `import 'spacedf-sdk/shims/web'` (otherwise)
96
+ */
97
+ async withResponse(): Promise<{ data: T; response: Response }> {
98
+ const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
99
+ return { data, response };
100
+ }
101
+
102
+ private parse(): Promise<T> {
103
+ if (!this.parsedPromise) {
104
+ this.parsedPromise = this.responsePromise.then(this.parseResponse);
105
+ }
106
+ return this.parsedPromise;
107
+ }
108
+
109
+ override then<TResult1 = T, TResult2 = never>(
110
+ onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
111
+ onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null,
112
+ ): Promise<TResult1 | TResult2> {
113
+ return this.parse().then(onfulfilled, onrejected);
114
+ }
115
+
116
+ override catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult> {
117
+ return this.parse().catch(onrejected);
118
+ }
119
+
120
+ override finally(onfinally?: (() => void) | undefined | null): Promise<T> {
121
+ return this.parse().finally(onfinally);
122
+ }
123
+ }
124
+
125
+ export abstract class APIClient {
126
+ baseURL: string;
127
+ maxRetries: number;
128
+ timeout: number;
129
+ httpAgent: Agent | undefined;
130
+ allowMultiOrgs: boolean;
131
+ APIKey: string | undefined;
132
+
133
+ private fetch: Fetch;
134
+ protected idempotencyHeader?: string;
135
+
136
+ constructor({
137
+ baseURL,
138
+ maxRetries = 2,
139
+ timeout = 60 * 1000, // 1 minute
140
+ httpAgent,
141
+ fetch: overriddenFetch,
142
+ APIKey,
143
+ allowMultiOrgs = false,
144
+ }: {
145
+ baseURL: string;
146
+ maxRetries?: number | undefined;
147
+ timeout: number | undefined;
148
+ httpAgent: Agent | undefined;
149
+ fetch: Fetch | undefined;
150
+ APIKey: string | undefined;
151
+ allowMultiOrgs: boolean;
152
+ }) {
153
+ this.baseURL = baseURL;
154
+ this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);
155
+ this.timeout = validatePositiveInteger('timeout', timeout);
156
+ this.httpAgent = httpAgent;
157
+ this.APIKey = APIKey;
158
+ this.allowMultiOrgs = allowMultiOrgs;
159
+
160
+ this.fetch = overriddenFetch ?? fetch;
161
+ }
162
+
163
+ protected authHeaders(opts: FinalRequestOptions): Headers {
164
+ return {};
165
+ }
166
+
167
+ /**
168
+ * Override this to add your own default headers, for example:
169
+ *
170
+ * {
171
+ * ...super.defaultHeaders(),
172
+ * Authorization: 'Bearer 123',
173
+ * }
174
+ */
175
+ protected defaultHeaders(opts: FinalRequestOptions): Headers {
176
+ return {
177
+ Accept: 'application/json',
178
+ 'Content-Type': 'application/json',
179
+ 'User-Agent': this.getUserAgent(),
180
+ ...getPlatformHeaders(),
181
+ ...this.authHeaders(opts),
182
+ };
183
+ }
184
+
185
+ protected abstract defaultQuery(): DefaultQuery | undefined;
186
+
187
+ /**
188
+ * Override this to add your own headers validation:
189
+ */
190
+ protected validateHeaders(headers: Headers, customHeaders: Headers) {}
191
+
192
+ protected defaultIdempotencyKey(): string {
193
+ return `spacedf-node-retry-${uuid4()}`;
194
+ }
195
+
196
+ get<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
197
+ return this.methodRequest('get', path, opts);
198
+ }
199
+
200
+ post<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
201
+ return this.methodRequest('post', path, opts);
202
+ }
203
+
204
+ patch<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
205
+ return this.methodRequest('patch', path, opts);
206
+ }
207
+
208
+ put<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
209
+ return this.methodRequest('put', path, opts);
210
+ }
211
+
212
+ delete<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
213
+ return this.methodRequest('delete', path, opts);
214
+ }
215
+
216
+ private methodRequest<Req, Rsp>(method: HTTPMethod, path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp> {
217
+ return this.request(
218
+ Promise.resolve(opts).then(async (opts) => {
219
+ const body =
220
+ opts && opts?.body instanceof DataView
221
+ ? opts.body
222
+ : opts?.body instanceof ArrayBuffer
223
+ ? new DataView(opts.body)
224
+ : opts && ArrayBuffer.isView(opts?.body)
225
+ ? new DataView(opts.body.buffer)
226
+ : opts?.body;
227
+ return { method, path, ...opts, body };
228
+ }),
229
+ );
230
+ }
231
+
232
+ getAPIList<Item, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(
233
+ path: string,
234
+ Page: new (...args: any[]) => PageClass,
235
+ opts?: RequestOptions<any>,
236
+ ): PagePromise<PageClass, Item> {
237
+ return this.requestAPIList(Page, { method: 'get', path, ...opts });
238
+ }
239
+
240
+ private calculateContentLength(body: unknown): string | null {
241
+ if (typeof body === 'string') {
242
+ if (typeof Buffer !== 'undefined') {
243
+ return Buffer.byteLength(body, 'utf8').toString();
244
+ }
245
+
246
+ if (typeof TextEncoder !== 'undefined') {
247
+ const encoder = new TextEncoder();
248
+ const encoded = encoder.encode(body);
249
+ return encoded.length.toString();
250
+ }
251
+ } else if (ArrayBuffer.isView(body)) {
252
+ return body.byteLength.toString();
253
+ }
254
+
255
+ return null;
256
+ }
257
+
258
+ buildRequest<Req>(options: FinalRequestOptions<Req>, { retryCount = 0 }: { retryCount?: number } = {}): { req: RequestInit; url: string; timeout: number } {
259
+ const { method, path, query, organization, headers: headers = {} } = options;
260
+
261
+ const body =
262
+ ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string')
263
+ ? options.body
264
+ : options.body
265
+ ? JSON.stringify(options.body, null, 2)
266
+ : null;
267
+ const contentLength = this.calculateContentLength(body);
268
+
269
+ const url = this.buildURL(path!, query, organization);
270
+ if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
271
+ const timeout = options.timeout ?? this.timeout;
272
+ const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
273
+ const minAgentTimeout = timeout + 1000;
274
+ if (typeof (httpAgent as any)?.options?.timeout === 'number' && minAgentTimeout > ((httpAgent as any).options.timeout ?? 0)) {
275
+ // Allow any given request to bump our agent active socket timeout.
276
+ // This may seem strange, but leaking active sockets should be rare and not particularly problematic,
277
+ // and without mutating agent we would need to create more of them.
278
+ // This tradeoff optimizes for performance.
279
+ (httpAgent as any).options.timeout = minAgentTimeout;
280
+ }
281
+
282
+ if (this.idempotencyHeader && method !== 'get') {
283
+ if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();
284
+ headers[this.idempotencyHeader] = options.idempotencyKey;
285
+ }
286
+
287
+ const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount });
288
+
289
+ const req: RequestInit = {
290
+ method,
291
+ ...(body && { body: body as any }),
292
+ headers: reqHeaders,
293
+ ...(httpAgent && { agent: httpAgent }),
294
+ // @ts-ignore node-fetch uses a custom AbortSignal type that is
295
+ // not compatible with standard web types
296
+ signal: options.signal ?? null,
297
+ };
298
+
299
+ return { req, url, timeout };
300
+ }
301
+
302
+ private buildHeaders({
303
+ options,
304
+ headers,
305
+ contentLength,
306
+ retryCount,
307
+ }: {
308
+ options: FinalRequestOptions;
309
+ headers: Record<string, string | null | undefined>;
310
+ contentLength: string | null | undefined;
311
+ retryCount: number;
312
+ }): Record<string, string> {
313
+ const reqHeaders: Record<string, string> = {};
314
+ if (contentLength) {
315
+ reqHeaders['content-length'] = contentLength;
316
+ }
317
+
318
+ const defaultHeaders = this.defaultHeaders(options);
319
+ applyHeadersMut(reqHeaders, defaultHeaders);
320
+ applyHeadersMut(reqHeaders, headers);
321
+
322
+ reqHeaders['x-spacedf-retry-count'] = String(retryCount);
323
+
324
+ this.validateHeaders(reqHeaders, headers);
325
+
326
+ return reqHeaders;
327
+ }
328
+
329
+ /**
330
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
331
+ */
332
+ protected async prepareOptions(options: FinalRequestOptions): Promise<void> {}
333
+
334
+ /**
335
+ * Used as a callback for mutating the given `RequestInit` object.
336
+ *
337
+ * This is useful for cases where you want to add certain headers based off of
338
+ * the request properties, e.g. `method` or `url`.
339
+ */
340
+ protected async prepareRequest(request: RequestInit, { url, options }: { url: string; options: FinalRequestOptions }): Promise<void> {}
341
+
342
+ protected parseHeaders(headers: HeadersInit | null | undefined): Record<string, string> {
343
+ return !headers
344
+ ? {}
345
+ : Symbol.iterator in headers
346
+ ? Object.fromEntries(Array.from(headers as Iterable<string[]>).map((header) => [...header]))
347
+ : { ...headers };
348
+ }
349
+
350
+ protected makeStatusError(status: number | undefined, error: object | undefined, message: string | undefined, headers: Headers | undefined) {
351
+ return APIError.generate(status, error, message, headers);
352
+ }
353
+
354
+ request<Req, Rsp>(options: PromiseOrValue<FinalRequestOptions<Req>>, remainingRetries: number | null = null): APIPromise<Rsp> {
355
+ return new APIPromise(this.makeRequest(options, remainingRetries));
356
+ }
357
+
358
+ private async makeRequest<Req>(optionsInput: PromiseOrValue<FinalRequestOptions<Req>>, retriesRemaining: number | null): Promise<APIResponseProps> {
359
+ const options = await optionsInput;
360
+ const maxRetries = options.maxRetries ?? this.maxRetries;
361
+ if (retriesRemaining == null) {
362
+ retriesRemaining = maxRetries;
363
+ }
364
+
365
+ await this.prepareOptions(options);
366
+
367
+ const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });
368
+
369
+ await this.prepareRequest(req, { url, options });
370
+
371
+ debug('request', url, options, req.headers);
372
+
373
+ if (options.signal?.aborted) {
374
+ throw new APIUserAbortError();
375
+ }
376
+
377
+ const controller = new AbortController();
378
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
379
+
380
+ if (response instanceof Error) {
381
+ if (options.signal?.aborted) {
382
+ throw new APIUserAbortError();
383
+ }
384
+ if (retriesRemaining) {
385
+ return this.retryRequest(options, retriesRemaining);
386
+ }
387
+ if (response.name === 'AbortError') {
388
+ throw new APIConnectionTimeoutError();
389
+ }
390
+ throw new APIConnectionError({ cause: response });
391
+ }
392
+
393
+ const responseHeaders = createResponseHeaders(response.headers);
394
+
395
+ if (!response.ok) {
396
+ if (retriesRemaining && this.shouldRetry(response)) {
397
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
398
+ debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders);
399
+ return this.retryRequest(options, retriesRemaining, responseHeaders);
400
+ }
401
+
402
+ const errText = await response.text().catch((e) => castToError(e).message);
403
+ const errJSON = safeJSON(errText);
404
+ const errMessage = errJSON ? undefined : errText;
405
+ const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;
406
+
407
+ debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);
408
+
409
+ const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
410
+ throw err;
411
+ }
412
+
413
+ return { response, options, controller };
414
+ }
415
+
416
+ requestAPIList<Item = unknown, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(
417
+ Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,
418
+ options: FinalRequestOptions,
419
+ ): PagePromise<PageClass, Item> {
420
+ const request = this.makeRequest(options, null);
421
+ return new PagePromise<PageClass, Item>(this, request, Page);
422
+ }
423
+
424
+ buildURL<Req>(path: string, query: Req | null | undefined, organization: string | undefined): string {
425
+ const baseURL = this.allowMultiOrgs ? toBaseURL(this.baseURL, organization) : this.baseURL;
426
+ const url = isAbsoluteURL(path) ? new URL(path) : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
427
+
428
+ const defaultQuery = this.defaultQuery();
429
+ if (!isEmptyObj(defaultQuery)) {
430
+ query = { ...defaultQuery, ...query } as Req;
431
+ }
432
+
433
+ if (typeof query === 'object' && query && !Array.isArray(query)) {
434
+ url.search = this.stringifyQuery(query as Record<string, unknown>);
435
+ }
436
+
437
+ return url.toString();
438
+ }
439
+
440
+ protected stringifyQuery(query: Record<string, unknown>): string {
441
+ return Object.entries(query)
442
+ .filter(([_, value]) => typeof value !== 'undefined')
443
+ .map(([key, value]) => {
444
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
445
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
446
+ }
447
+ if (value === null) {
448
+ return `${encodeURIComponent(key)}=`;
449
+ }
450
+ throw new SpaceDFError(
451
+ `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.`,
452
+ );
453
+ })
454
+ .join('&');
455
+ }
456
+
457
+ async fetchWithTimeout(url: RequestInfo, init: RequestInit | undefined, ms: number, controller: AbortController): Promise<Response> {
458
+ const { signal, ...options } = init || {};
459
+ if (signal) signal.addEventListener('abort', () => controller.abort());
460
+
461
+ const timeout = setTimeout(() => controller.abort(), ms);
462
+
463
+ return (
464
+ this.getRequestClient()
465
+ // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
466
+ .fetch.call(undefined, url, { signal: controller.signal as any, ...options })
467
+ .finally(() => {
468
+ clearTimeout(timeout);
469
+ })
470
+ );
471
+ }
472
+
473
+ protected getRequestClient(): RequestClient {
474
+ return { fetch: this.fetch };
475
+ }
476
+
477
+ private shouldRetry(response: Response): boolean {
478
+ // Note this is not a standard header.
479
+ const shouldRetryHeader = response.headers.get('x-should-retry');
480
+
481
+ // If the server explicitly says whether or not to retry, obey.
482
+ if (shouldRetryHeader === 'true') return true;
483
+ if (shouldRetryHeader === 'false') return false;
484
+
485
+ // Retry on request timeouts.
486
+ if (response.status === 408) return true;
487
+
488
+ // Retry on lock timeouts.
489
+ if (response.status === 409) return true;
490
+
491
+ // Retry on rate limits.
492
+ if (response.status === 429) return true;
493
+
494
+ // Retry internal errors.
495
+ if (response.status >= 500) return true;
496
+
497
+ return false;
498
+ }
499
+
500
+ private async retryRequest(options: FinalRequestOptions, retriesRemaining: number, responseHeaders?: Headers | undefined): Promise<APIResponseProps> {
501
+ let timeoutMillis: number | undefined;
502
+
503
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
504
+ const retryAfterMillisHeader = responseHeaders?.['retry-after-ms'];
505
+ if (retryAfterMillisHeader) {
506
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
507
+ if (!Number.isNaN(timeoutMs)) {
508
+ timeoutMillis = timeoutMs;
509
+ }
510
+ }
511
+
512
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
513
+ const retryAfterHeader = responseHeaders?.['retry-after'];
514
+ if (retryAfterHeader && !timeoutMillis) {
515
+ const timeoutSeconds = parseFloat(retryAfterHeader);
516
+ if (!Number.isNaN(timeoutSeconds)) {
517
+ timeoutMillis = timeoutSeconds * 1000;
518
+ } else {
519
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
520
+ }
521
+ }
522
+
523
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
524
+ // just do what it says, but otherwise calculate a default
525
+ if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
526
+ const maxRetries = options.maxRetries ?? this.maxRetries;
527
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
528
+ }
529
+ await sleep(timeoutMillis);
530
+
531
+ return this.makeRequest(options, retriesRemaining - 1);
532
+ }
533
+
534
+ private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number {
535
+ const initialRetryDelay = 0.5;
536
+ const maxRetryDelay = 8.0;
537
+
538
+ const numRetries = maxRetries - retriesRemaining;
539
+
540
+ // Apply exponential backoff, but not more than the max.
541
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
542
+
543
+ // Apply some jitter, take up to at most 25 percent of the retry time.
544
+ const jitter = 1 - Math.random() * 0.25;
545
+
546
+ return sleepSeconds * jitter * 1000;
547
+ }
548
+
549
+ private getUserAgent(): string {
550
+ return `${this.constructor.name}/JS ${VERSION}`;
551
+ }
552
+ }
553
+
554
+ export type PageInfo = { url: URL } | { params: Record<string, unknown> | null };
555
+
556
+ export abstract class AbstractPage<Item> implements AsyncIterable<Item> {
557
+ #client: APIClient;
558
+ protected options: FinalRequestOptions;
559
+
560
+ protected response: Response;
561
+ protected body: unknown;
562
+
563
+ constructor(client: APIClient, response: Response, body: unknown, options: FinalRequestOptions) {
564
+ this.#client = client;
565
+ this.options = options;
566
+ this.response = response;
567
+ this.body = body;
568
+ }
569
+
570
+ abstract nextPageInfo(): PageInfo | null;
571
+
572
+ abstract getPaginatedItems(): Item[];
573
+
574
+ hasNextPage(): boolean {
575
+ const items = this.getPaginatedItems();
576
+ if (!items.length) return false;
577
+ return this.nextPageInfo() != null;
578
+ }
579
+
580
+ async getNextPage(): Promise<this> {
581
+ const nextInfo = this.nextPageInfo();
582
+ if (!nextInfo) {
583
+ throw new SpaceDFError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
584
+ }
585
+ const nextOptions = { ...this.options };
586
+ if ('params' in nextInfo && typeof nextOptions.query === 'object') {
587
+ nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
588
+ } else if ('url' in nextInfo) {
589
+ const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
590
+ for (const [key, value] of params) {
591
+ nextInfo.url.searchParams.set(key, value as any);
592
+ }
593
+ nextOptions.query = undefined;
594
+ nextOptions.path = nextInfo.url.toString();
595
+ }
596
+ return await this.#client.requestAPIList(this.constructor as any, nextOptions);
597
+ }
598
+
599
+ async *iterPages() {
600
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
601
+ let page: AbstractPage<Item> = this;
602
+ yield page;
603
+ while (page.hasNextPage()) {
604
+ page = await page.getNextPage();
605
+ yield page;
606
+ }
607
+ }
608
+
609
+ async *[Symbol.asyncIterator]() {
610
+ for await (const page of this.iterPages()) {
611
+ for (const item of page.getPaginatedItems()) {
612
+ yield item;
613
+ }
614
+ }
615
+ }
616
+ }
617
+
618
+ /**
619
+ * This subclass of Promise will resolve to an instantiated Page once the request completes.
620
+ *
621
+ * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
622
+ *
623
+ * for await (const item of client.items.list()) {
624
+ * console.log(item)
625
+ * }
626
+ */
627
+ export class PagePromise<PageClass extends AbstractPage<Item>, Item = ReturnType<PageClass['getPaginatedItems']>[number]>
628
+ extends APIPromise<PageClass>
629
+ implements AsyncIterable<Item>
630
+ {
631
+ constructor(client: APIClient, request: Promise<APIResponseProps>, Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass) {
632
+ super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options));
633
+ }
634
+
635
+ /**
636
+ * Allow auto-paginating iteration on an unawaited list call, eg:
637
+ *
638
+ * for await (const item of client.items.list()) {
639
+ * console.log(item)
640
+ * }
641
+ */
642
+ async *[Symbol.asyncIterator]() {
643
+ const page = await this;
644
+ for await (const item of page) {
645
+ yield item;
646
+ }
647
+ }
648
+ }
649
+
650
+ export const createResponseHeaders = (headers: Awaited<ReturnType<Fetch>>['headers']): Record<string, string> => {
651
+ return new Proxy(
652
+ Object.fromEntries(
653
+ // @ts-ignore
654
+ headers.entries(),
655
+ ),
656
+ {
657
+ get(target, name) {
658
+ const key = name.toString();
659
+ return target[key.toLowerCase()] || target[key];
660
+ },
661
+ },
662
+ );
663
+ };
664
+
665
+ type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';
666
+
667
+ export type RequestClient = { fetch: Fetch };
668
+ export type Headers = Record<string, string | null | undefined>;
669
+ export type DefaultQuery = Record<string, string | undefined>;
670
+ export type KeysEnum<T> = { [P in keyof Required<T>]: true };
671
+
672
+ export type RequestOptions<Req = unknown | Record<string, unknown> | Readable | ArrayBufferView | ArrayBuffer> = {
673
+ method?: HTTPMethod;
674
+ path?: string;
675
+ query?: Req | undefined;
676
+ body?: Req | null | undefined;
677
+ headers?: Headers | undefined;
678
+
679
+ maxRetries?: number;
680
+ stream?: boolean | undefined;
681
+ timeout?: number;
682
+ httpAgent?: Agent;
683
+ signal?: AbortSignal | undefined | null;
684
+ idempotencyKey?: string;
685
+ organization?: string;
686
+ accessToken?: string;
687
+ APIKey?: string;
688
+
689
+ __binaryRequest?: boolean | undefined;
690
+ __binaryResponse?: boolean | undefined;
691
+ };
692
+
693
+ // This is required so that we can determine if a given object matches the RequestOptions
694
+ // type at runtime. While this requires duplication, it is enforced by the TypeScript
695
+ // compiler such that any missing / extraneous keys will cause an error.
696
+ const requestOptionsKeys: KeysEnum<RequestOptions> = {
697
+ method: true,
698
+ path: true,
699
+ query: true,
700
+ body: true,
701
+ headers: true,
702
+
703
+ maxRetries: true,
704
+ stream: true,
705
+ timeout: true,
706
+ httpAgent: true,
707
+ signal: true,
708
+ idempotencyKey: true,
709
+ organization: true,
710
+ accessToken: true,
711
+ APIKey: true,
712
+
713
+ __binaryRequest: true,
714
+ __binaryResponse: true,
715
+ };
716
+
717
+ export const isRequestOptions = (obj: unknown): obj is RequestOptions => {
718
+ return typeof obj === 'object' && obj !== null && !isEmptyObj(obj) && Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k));
719
+ };
720
+
721
+ export type FinalRequestOptions<Req = unknown | Record<string, unknown> | Readable | DataView> = RequestOptions<Req> & {
722
+ method: HTTPMethod;
723
+ path: string;
724
+ };
725
+
726
+ declare const Deno: any;
727
+ declare const EdgeRuntime: any;
728
+ type Arch = 'x32' | 'x64' | 'arm' | 'arm64' | `other:${string}` | 'unknown';
729
+ type PlatformName = 'MacOS' | 'Linux' | 'Windows' | 'FreeBSD' | 'OpenBSD' | 'iOS' | 'Android' | `Other:${string}` | 'Unknown';
730
+ type Browser = 'ie' | 'edge' | 'chrome' | 'firefox' | 'safari';
731
+ type PlatformProperties = {
732
+ 'X-SpaceDF-Lang': 'js';
733
+ 'X-SpaceDF-Package-Version': string;
734
+ 'X-SpaceDF-OS': PlatformName;
735
+ 'X-SpaceDF-Arch': Arch;
736
+ 'X-SpaceDF-Runtime': 'node' | 'deno' | 'edge' | `browser:${Browser}` | 'unknown';
737
+ 'X-SpaceDF-Runtime-Version': string;
738
+ };
739
+ const getPlatformProperties = (): PlatformProperties => {
740
+ if (typeof Deno !== 'undefined' && Deno.build != null) {
741
+ return {
742
+ 'X-SpaceDF-Lang': 'js',
743
+ 'X-SpaceDF-Package-Version': VERSION,
744
+ 'X-SpaceDF-OS': normalizePlatform(Deno.build.os),
745
+ 'X-SpaceDF-Arch': normalizeArch(Deno.build.arch),
746
+ 'X-SpaceDF-Runtime': 'deno',
747
+ 'X-SpaceDF-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',
748
+ };
749
+ }
750
+ if (typeof EdgeRuntime !== 'undefined') {
751
+ return {
752
+ 'X-SpaceDF-Lang': 'js',
753
+ 'X-SpaceDF-Package-Version': VERSION,
754
+ 'X-SpaceDF-OS': 'Unknown',
755
+ 'X-SpaceDF-Arch': `other:${EdgeRuntime}`,
756
+ 'X-SpaceDF-Runtime': 'edge',
757
+ 'X-SpaceDF-Runtime-Version': process.version,
758
+ };
759
+ }
760
+ // Check if Node.js
761
+ if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {
762
+ return {
763
+ 'X-SpaceDF-Lang': 'js',
764
+ 'X-SpaceDF-Package-Version': VERSION,
765
+ 'X-SpaceDF-OS': normalizePlatform(process.platform),
766
+ 'X-SpaceDF-Arch': normalizeArch(process.arch),
767
+ 'X-SpaceDF-Runtime': 'node',
768
+ 'X-SpaceDF-Runtime-Version': process.version,
769
+ };
770
+ }
771
+
772
+ const browserInfo = getBrowserInfo();
773
+ if (browserInfo) {
774
+ return {
775
+ 'X-SpaceDF-Lang': 'js',
776
+ 'X-SpaceDF-Package-Version': VERSION,
777
+ 'X-SpaceDF-OS': 'Unknown',
778
+ 'X-SpaceDF-Arch': 'unknown',
779
+ 'X-SpaceDF-Runtime': `browser:${browserInfo.browser}`,
780
+ 'X-SpaceDF-Runtime-Version': browserInfo.version,
781
+ };
782
+ }
783
+
784
+ // TODO add support for Cloudflare workers, etc.
785
+ return {
786
+ 'X-SpaceDF-Lang': 'js',
787
+ 'X-SpaceDF-Package-Version': VERSION,
788
+ 'X-SpaceDF-OS': 'Unknown',
789
+ 'X-SpaceDF-Arch': 'unknown',
790
+ 'X-SpaceDF-Runtime': 'unknown',
791
+ 'X-SpaceDF-Runtime-Version': 'unknown',
792
+ };
793
+ };
794
+
795
+ type BrowserInfo = {
796
+ browser: Browser;
797
+ version: string;
798
+ };
799
+
800
+ declare const navigator: { userAgent: string } | undefined;
801
+
802
+ // Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
803
+ function getBrowserInfo(): BrowserInfo | null {
804
+ if (typeof navigator === 'undefined' || !navigator) {
805
+ return null;
806
+ }
807
+
808
+ // NOTE: The order matters here!
809
+ const browserPatterns = [
810
+ { key: 'edge' as const, pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
811
+ { key: 'ie' as const, pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
812
+ { key: 'ie' as const, pattern: /Trident(?:.*rv\\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
813
+ { key: 'chrome' as const, pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
814
+ { key: 'firefox' as const, pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
815
+ { key: 'safari' as const, pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
816
+ ];
817
+
818
+ // Find the FIRST matching browser
819
+ for (const { key, pattern } of browserPatterns) {
820
+ const match = pattern.exec(navigator.userAgent);
821
+ if (match) {
822
+ const major = match[1] || 0;
823
+ const minor = match[2] || 0;
824
+ const patch = match[3] || 0;
825
+
826
+ return { browser: key, version: `${major}.${minor}.${patch}` };
827
+ }
828
+ }
829
+
830
+ return null;
831
+ }
832
+
833
+ const normalizeArch = (arch: string): Arch => {
834
+ // Node docs:
835
+ // - https://nodejs.org/api/process.html#processarch
836
+ // Deno docs:
837
+ // - https://doc.deno.land/deno/stable/~/Deno.build
838
+ if (arch === 'x32') return 'x32';
839
+ if (arch === 'x86_64' || arch === 'x64') return 'x64';
840
+ if (arch === 'arm') return 'arm';
841
+ if (arch === 'aarch64' || arch === 'arm64') return 'arm64';
842
+ if (arch) return `other:${arch}`;
843
+ return 'unknown';
844
+ };
845
+
846
+ const normalizePlatform = (platform: string): PlatformName => {
847
+ // Node platforms:
848
+ // - https://nodejs.org/api/process.html#processplatform
849
+ // Deno platforms:
850
+ // - https://doc.deno.land/deno/stable/~/Deno.build
851
+ // - https://github.com/denoland/deno/issues/14799
852
+
853
+ platform = platform.toLowerCase();
854
+
855
+ // NOTE: this iOS check is untested and may not work
856
+ // Node does not work natively on IOS, there is a fork at
857
+ // https://github.com/nodejs-mobile/nodejs-mobile
858
+ // however it is unknown at the time of writing how to detect if it is running
859
+ if (platform.includes('ios')) return 'iOS';
860
+ if (platform === 'android') return 'Android';
861
+ if (platform === 'darwin') return 'MacOS';
862
+ if (platform === 'win32') return 'Windows';
863
+ if (platform === 'freebsd') return 'FreeBSD';
864
+ if (platform === 'openbsd') return 'OpenBSD';
865
+ if (platform === 'linux') return 'Linux';
866
+ if (platform) return `Other:${platform}`;
867
+ return 'Unknown';
868
+ };
869
+
870
+ let _platformHeaders: PlatformProperties;
871
+ const getPlatformHeaders = () => {
872
+ return (_platformHeaders ??= getPlatformProperties());
873
+ };
874
+
875
+ export const safeJSON = (text: string) => {
876
+ try {
877
+ return JSON.parse(text);
878
+ } catch (err) {
879
+ return undefined;
880
+ }
881
+ };
882
+
883
+ // https://stackoverflow.com/a/19709846
884
+ const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i');
885
+ const isAbsoluteURL = (url: string): boolean => {
886
+ return startsWithSchemeRegexp.test(url);
887
+ };
888
+
889
+ const toBaseURL = (url: string, organization: string | undefined) => (organization ? url.replace('//', `//${organization}.`) : url);
890
+
891
+ export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
892
+
893
+ const validatePositiveInteger = (name: string, n: unknown): number => {
894
+ if (typeof n !== 'number' || !Number.isInteger(n)) {
895
+ throw new SpaceDFError(`${name} must be an integer`);
896
+ }
897
+ if (n < 0) {
898
+ throw new SpaceDFError(`${name} must be a positive integer`);
899
+ }
900
+ return n;
901
+ };
902
+
903
+ export const castToError = (err: any): Error => {
904
+ if (err instanceof Error) return err;
905
+ if (typeof err === 'object' && err !== null) {
906
+ try {
907
+ return new Error(JSON.stringify(err));
908
+ } catch {}
909
+ }
910
+ return new Error(err);
911
+ };
912
+
913
+ export const ensurePresent = <T>(value: T | null | undefined): T => {
914
+ if (value == null) throw new SpaceDFError(`Expected a value to be given but received ${value} instead.`);
915
+ return value;
916
+ };
917
+
918
+ /**
919
+ * Read an environment variable.
920
+ *
921
+ * Trims beginning and trailing whitespace.
922
+ *
923
+ * Will return undefined if the environment variable doesn't exist or cannot be accessed.
924
+ */
925
+ export const readEnv = (env: string): string | undefined => {
926
+ if (typeof process !== 'undefined') {
927
+ return process.env?.[env]?.trim() ?? undefined;
928
+ }
929
+ if (typeof Deno !== 'undefined') {
930
+ return Deno.env?.get?.(env)?.trim();
931
+ }
932
+ return undefined;
933
+ };
934
+
935
+ export const coerceInteger = (value: unknown): number => {
936
+ if (typeof value === 'number') return Math.round(value);
937
+ if (typeof value === 'string') return parseInt(value, 10);
938
+
939
+ throw new SpaceDFError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
940
+ };
941
+
942
+ export const coerceFloat = (value: unknown): number => {
943
+ if (typeof value === 'number') return value;
944
+ if (typeof value === 'string') return parseFloat(value);
945
+
946
+ throw new SpaceDFError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
947
+ };
948
+
949
+ export const coerceBoolean = (value: unknown): boolean => {
950
+ if (typeof value === 'boolean') return value;
951
+ if (typeof value === 'string') return value === 'true';
952
+ return Boolean(value);
953
+ };
954
+
955
+ export const maybeCoerceInteger = (value: unknown): number | undefined => {
956
+ if (value === undefined) {
957
+ return undefined;
958
+ }
959
+ return coerceInteger(value);
960
+ };
961
+
962
+ export const maybeCoerceFloat = (value: unknown): number | undefined => {
963
+ if (value === undefined) {
964
+ return undefined;
965
+ }
966
+ return coerceFloat(value);
967
+ };
968
+
969
+ export const maybeCoerceBoolean = (value: unknown): boolean | undefined => {
970
+ if (value === undefined) {
971
+ return undefined;
972
+ }
973
+ return coerceBoolean(value);
974
+ };
975
+
976
+ // https://stackoverflow.com/a/34491287
977
+ export function isEmptyObj(obj: object | null | undefined): boolean {
978
+ if (!obj) return true;
979
+ for (const _k in obj) return false;
980
+ return true;
981
+ }
982
+
983
+ // https://eslint.org/docs/latest/rules/no-prototype-builtins
984
+ export function hasOwn(obj: object, key: string): boolean {
985
+ return Object.prototype.hasOwnProperty.call(obj, key);
986
+ }
987
+
988
+ /**
989
+ * Copies headers from "newHeaders" onto "targetHeaders",
990
+ * using lower-case for all properties,
991
+ * ignoring any keys with undefined values,
992
+ * and deleting any keys with null values.
993
+ */
994
+ function applyHeadersMut(targetHeaders: Headers, newHeaders: Headers): void {
995
+ for (const k in newHeaders) {
996
+ if (!hasOwn(newHeaders, k)) continue;
997
+ const lowerKey = k.toLowerCase();
998
+ if (!lowerKey) continue;
999
+
1000
+ const val = newHeaders[k];
1001
+
1002
+ if (val === null) {
1003
+ delete targetHeaders[lowerKey];
1004
+ } else if (val !== undefined) {
1005
+ targetHeaders[lowerKey] = val;
1006
+ }
1007
+ }
1008
+ }
1009
+
1010
+ export function debug(action: string, ...args: any[]) {
1011
+ if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') {
1012
+ console.log(`SpaceDFSDK:DEBUG:${action}`, ...args);
1013
+ }
1014
+ }
1015
+
1016
+ export const isRunningInBrowser = () => {
1017
+ return (
1018
+ // @ts-ignore
1019
+ typeof window !== 'undefined' &&
1020
+ // @ts-ignore
1021
+ typeof window.document !== 'undefined' &&
1022
+ // @ts-ignore
1023
+ typeof navigator !== 'undefined'
1024
+ );
1025
+ };
1026
+
1027
+ export interface HeadersProtocol {
1028
+ get: (header: string) => string | null | undefined;
1029
+ }
1030
+ export type HeadersLike = Record<string, string | string[] | undefined> | HeadersProtocol;
1031
+
1032
+ export const isHeadersProtocol = (headers: any): headers is HeadersProtocol => {
1033
+ return typeof headers?.get === 'function';
1034
+ };
1035
+
1036
+ export const getRequiredHeader = (headers: HeadersLike, header: string): string => {
1037
+ const lowerCasedHeader = header.toLowerCase();
1038
+ if (isHeadersProtocol(headers)) {
1039
+ // to deal with the case where the header looks like SP-Event-Id
1040
+ const intercapsHeader = header[0]?.toUpperCase() + header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase());
1041
+ for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {
1042
+ const value = headers.get(key);
1043
+ if (value) {
1044
+ return value;
1045
+ }
1046
+ }
1047
+ }
1048
+
1049
+ for (const [key, value] of Object.entries(headers)) {
1050
+ if (key.toLowerCase() === lowerCasedHeader) {
1051
+ if (Array.isArray(value)) {
1052
+ if (value.length <= 1) return value[0];
1053
+ console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);
1054
+ return value[0];
1055
+ }
1056
+ return value;
1057
+ }
1058
+ }
1059
+
1060
+ throw new Error(`Could not find ${header} header`);
1061
+ };