llama-stack-client 0.0.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (416) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +298 -0
  3. package/_shims/MultipartBody.d.ts +9 -0
  4. package/_shims/MultipartBody.d.ts.map +1 -0
  5. package/_shims/MultipartBody.js +16 -0
  6. package/_shims/MultipartBody.js.map +1 -0
  7. package/_shims/MultipartBody.mjs +12 -0
  8. package/_shims/MultipartBody.mjs.map +1 -0
  9. package/_shims/README.md +46 -0
  10. package/_shims/auto/runtime-bun.d.ts +5 -0
  11. package/_shims/auto/runtime-bun.d.ts.map +1 -0
  12. package/_shims/auto/runtime-bun.js +21 -0
  13. package/_shims/auto/runtime-bun.js.map +1 -0
  14. package/_shims/auto/runtime-bun.mjs +2 -0
  15. package/_shims/auto/runtime-bun.mjs.map +1 -0
  16. package/_shims/auto/runtime-node.d.ts +5 -0
  17. package/_shims/auto/runtime-node.d.ts.map +1 -0
  18. package/_shims/auto/runtime-node.js +21 -0
  19. package/_shims/auto/runtime-node.js.map +1 -0
  20. package/_shims/auto/runtime-node.mjs +2 -0
  21. package/_shims/auto/runtime-node.mjs.map +1 -0
  22. package/_shims/auto/runtime.d.ts +5 -0
  23. package/_shims/auto/runtime.d.ts.map +1 -0
  24. package/_shims/auto/runtime.js +21 -0
  25. package/_shims/auto/runtime.js.map +1 -0
  26. package/_shims/auto/runtime.mjs +2 -0
  27. package/_shims/auto/runtime.mjs.map +1 -0
  28. package/_shims/auto/types-node.d.ts +5 -0
  29. package/_shims/auto/types-node.d.ts.map +1 -0
  30. package/_shims/auto/types-node.js +21 -0
  31. package/_shims/auto/types-node.js.map +1 -0
  32. package/_shims/auto/types-node.mjs +2 -0
  33. package/_shims/auto/types-node.mjs.map +1 -0
  34. package/_shims/auto/types.d.ts +101 -0
  35. package/_shims/auto/types.js +3 -0
  36. package/_shims/auto/types.mjs +3 -0
  37. package/_shims/bun-runtime.d.ts +6 -0
  38. package/_shims/bun-runtime.d.ts.map +1 -0
  39. package/_shims/bun-runtime.js +14 -0
  40. package/_shims/bun-runtime.js.map +1 -0
  41. package/_shims/bun-runtime.mjs +10 -0
  42. package/_shims/bun-runtime.mjs.map +1 -0
  43. package/_shims/index.d.ts +81 -0
  44. package/_shims/index.js +13 -0
  45. package/_shims/index.mjs +7 -0
  46. package/_shims/manual-types.d.ts +12 -0
  47. package/_shims/manual-types.js +3 -0
  48. package/_shims/manual-types.mjs +3 -0
  49. package/_shims/node-runtime.d.ts +3 -0
  50. package/_shims/node-runtime.d.ts.map +1 -0
  51. package/_shims/node-runtime.js +89 -0
  52. package/_shims/node-runtime.js.map +1 -0
  53. package/_shims/node-runtime.mjs +56 -0
  54. package/_shims/node-runtime.mjs.map +1 -0
  55. package/_shims/node-types.d.ts +42 -0
  56. package/_shims/node-types.js +3 -0
  57. package/_shims/node-types.mjs +3 -0
  58. package/_shims/registry.d.ts +37 -0
  59. package/_shims/registry.d.ts.map +1 -0
  60. package/_shims/registry.js +41 -0
  61. package/_shims/registry.js.map +1 -0
  62. package/_shims/registry.mjs +37 -0
  63. package/_shims/registry.mjs.map +1 -0
  64. package/_shims/web-runtime.d.ts +5 -0
  65. package/_shims/web-runtime.d.ts.map +1 -0
  66. package/_shims/web-runtime.js +78 -0
  67. package/_shims/web-runtime.js.map +1 -0
  68. package/_shims/web-runtime.mjs +71 -0
  69. package/_shims/web-runtime.mjs.map +1 -0
  70. package/_shims/web-types.d.ts +83 -0
  71. package/_shims/web-types.js +3 -0
  72. package/_shims/web-types.mjs +3 -0
  73. package/core.d.ts +243 -0
  74. package/core.d.ts.map +1 -0
  75. package/core.js +900 -0
  76. package/core.js.map +1 -0
  77. package/core.mjs +869 -0
  78. package/core.mjs.map +1 -0
  79. package/error.d.ts +53 -0
  80. package/error.d.ts.map +1 -0
  81. package/error.js +143 -0
  82. package/error.js.map +1 -0
  83. package/error.mjs +127 -0
  84. package/error.mjs.map +1 -0
  85. package/index.d.mts +215 -0
  86. package/index.d.ts +215 -0
  87. package/index.d.ts.map +1 -0
  88. package/index.js +137 -0
  89. package/index.js.map +1 -0
  90. package/index.mjs +109 -0
  91. package/index.mjs.map +1 -0
  92. package/package.json +102 -0
  93. package/resource.d.ts +6 -0
  94. package/resource.d.ts.map +1 -0
  95. package/resource.js +11 -0
  96. package/resource.js.map +1 -0
  97. package/resource.mjs +7 -0
  98. package/resource.mjs.map +1 -0
  99. package/resources/agents/agents.d.ts +233 -0
  100. package/resources/agents/agents.d.ts.map +1 -0
  101. package/resources/agents/agents.js +73 -0
  102. package/resources/agents/agents.js.map +1 -0
  103. package/resources/agents/agents.mjs +46 -0
  104. package/resources/agents/agents.mjs.map +1 -0
  105. package/resources/agents/index.d.ts +5 -0
  106. package/resources/agents/index.d.ts.map +1 -0
  107. package/resources/agents/index.js +13 -0
  108. package/resources/agents/index.js.map +1 -0
  109. package/resources/agents/index.mjs +6 -0
  110. package/resources/agents/index.mjs.map +1 -0
  111. package/resources/agents/sessions.d.ts +76 -0
  112. package/resources/agents/sessions.d.ts.map +1 -0
  113. package/resources/agents/sessions.js +52 -0
  114. package/resources/agents/sessions.js.map +1 -0
  115. package/resources/agents/sessions.mjs +48 -0
  116. package/resources/agents/sessions.mjs.map +1 -0
  117. package/resources/agents/steps.d.ts +34 -0
  118. package/resources/agents/steps.d.ts.map +1 -0
  119. package/resources/agents/steps.js +24 -0
  120. package/resources/agents/steps.js.map +1 -0
  121. package/resources/agents/steps.mjs +20 -0
  122. package/resources/agents/steps.mjs.map +1 -0
  123. package/resources/agents/turns.d.ts +133 -0
  124. package/resources/agents/turns.d.ts.map +1 -0
  125. package/resources/agents/turns.js +38 -0
  126. package/resources/agents/turns.js.map +1 -0
  127. package/resources/agents/turns.mjs +34 -0
  128. package/resources/agents/turns.mjs.map +1 -0
  129. package/resources/batch-inference.d.ts +99 -0
  130. package/resources/batch-inference.d.ts.map +1 -0
  131. package/resources/batch-inference.js +37 -0
  132. package/resources/batch-inference.js.map +1 -0
  133. package/resources/batch-inference.mjs +33 -0
  134. package/resources/batch-inference.mjs.map +1 -0
  135. package/resources/datasets.d.ts +57 -0
  136. package/resources/datasets.d.ts.map +1 -0
  137. package/resources/datasets.js +52 -0
  138. package/resources/datasets.js.map +1 -0
  139. package/resources/datasets.mjs +48 -0
  140. package/resources/datasets.mjs.map +1 -0
  141. package/resources/evaluate/evaluate.d.ts +29 -0
  142. package/resources/evaluate/evaluate.d.ts.map +1 -0
  143. package/resources/evaluate/evaluate.js +49 -0
  144. package/resources/evaluate/evaluate.js.map +1 -0
  145. package/resources/evaluate/evaluate.mjs +22 -0
  146. package/resources/evaluate/evaluate.mjs.map +1 -0
  147. package/resources/evaluate/index.d.ts +6 -0
  148. package/resources/evaluate/index.d.ts.map +1 -0
  149. package/resources/evaluate/index.js +15 -0
  150. package/resources/evaluate/index.js.map +1 -0
  151. package/resources/evaluate/index.mjs +7 -0
  152. package/resources/evaluate/index.mjs.map +1 -0
  153. package/resources/evaluate/jobs/artifacts.d.ts +22 -0
  154. package/resources/evaluate/jobs/artifacts.d.ts.map +1 -0
  155. package/resources/evaluate/jobs/artifacts.js +24 -0
  156. package/resources/evaluate/jobs/artifacts.js.map +1 -0
  157. package/resources/evaluate/jobs/artifacts.mjs +20 -0
  158. package/resources/evaluate/jobs/artifacts.mjs.map +1 -0
  159. package/resources/evaluate/jobs/index.d.ts +5 -0
  160. package/resources/evaluate/jobs/index.d.ts.map +1 -0
  161. package/resources/evaluate/jobs/index.js +13 -0
  162. package/resources/evaluate/jobs/index.js.map +1 -0
  163. package/resources/evaluate/jobs/index.mjs +6 -0
  164. package/resources/evaluate/jobs/index.mjs.map +1 -0
  165. package/resources/evaluate/jobs/jobs.d.ts +56 -0
  166. package/resources/evaluate/jobs/jobs.d.ts.map +1 -0
  167. package/resources/evaluate/jobs/jobs.js +76 -0
  168. package/resources/evaluate/jobs/jobs.js.map +1 -0
  169. package/resources/evaluate/jobs/jobs.mjs +49 -0
  170. package/resources/evaluate/jobs/jobs.mjs.map +1 -0
  171. package/resources/evaluate/jobs/logs.d.ts +22 -0
  172. package/resources/evaluate/jobs/logs.d.ts.map +1 -0
  173. package/resources/evaluate/jobs/logs.js +24 -0
  174. package/resources/evaluate/jobs/logs.js.map +1 -0
  175. package/resources/evaluate/jobs/logs.mjs +20 -0
  176. package/resources/evaluate/jobs/logs.mjs.map +1 -0
  177. package/resources/evaluate/jobs/status.d.ts +22 -0
  178. package/resources/evaluate/jobs/status.d.ts.map +1 -0
  179. package/resources/evaluate/jobs/status.js +24 -0
  180. package/resources/evaluate/jobs/status.js.map +1 -0
  181. package/resources/evaluate/jobs/status.mjs +20 -0
  182. package/resources/evaluate/jobs/status.mjs.map +1 -0
  183. package/resources/evaluate/question-answering.d.ts +22 -0
  184. package/resources/evaluate/question-answering.d.ts.map +1 -0
  185. package/resources/evaluate/question-answering.js +24 -0
  186. package/resources/evaluate/question-answering.js.map +1 -0
  187. package/resources/evaluate/question-answering.mjs +20 -0
  188. package/resources/evaluate/question-answering.mjs.map +1 -0
  189. package/resources/evaluate/summarization.d.ts +4 -0
  190. package/resources/evaluate/summarization.d.ts.map +1 -0
  191. package/resources/evaluate/summarization.js +9 -0
  192. package/resources/evaluate/summarization.js.map +1 -0
  193. package/resources/evaluate/summarization.mjs +5 -0
  194. package/resources/evaluate/summarization.mjs.map +1 -0
  195. package/resources/evaluate/text-generation.d.ts +4 -0
  196. package/resources/evaluate/text-generation.d.ts.map +1 -0
  197. package/resources/evaluate/text-generation.js +9 -0
  198. package/resources/evaluate/text-generation.js.map +1 -0
  199. package/resources/evaluate/text-generation.mjs +5 -0
  200. package/resources/evaluate/text-generation.mjs.map +1 -0
  201. package/resources/evaluations.d.ts +35 -0
  202. package/resources/evaluations.d.ts.map +1 -0
  203. package/resources/evaluations.js +37 -0
  204. package/resources/evaluations.js.map +1 -0
  205. package/resources/evaluations.mjs +33 -0
  206. package/resources/evaluations.mjs.map +1 -0
  207. package/resources/index.d.ts +17 -0
  208. package/resources/index.d.ts.map +1 -0
  209. package/resources/index.js +50 -0
  210. package/resources/index.js.map +1 -0
  211. package/resources/index.mjs +18 -0
  212. package/resources/index.mjs.map +1 -0
  213. package/resources/inference/embeddings.d.ts +29 -0
  214. package/resources/inference/embeddings.d.ts.map +1 -0
  215. package/resources/inference/embeddings.js +49 -0
  216. package/resources/inference/embeddings.js.map +1 -0
  217. package/resources/inference/embeddings.mjs +22 -0
  218. package/resources/inference/embeddings.mjs.map +1 -0
  219. package/resources/inference/index.d.ts +3 -0
  220. package/resources/inference/index.d.ts.map +1 -0
  221. package/resources/inference/index.js +9 -0
  222. package/resources/inference/index.js.map +1 -0
  223. package/resources/inference/index.mjs +4 -0
  224. package/resources/inference/index.mjs.map +1 -0
  225. package/resources/inference/inference.d.ts +172 -0
  226. package/resources/inference/inference.d.ts.map +1 -0
  227. package/resources/inference/inference.js +67 -0
  228. package/resources/inference/inference.js.map +1 -0
  229. package/resources/inference/inference.mjs +40 -0
  230. package/resources/inference/inference.mjs.map +1 -0
  231. package/resources/memory/documents.d.ts +49 -0
  232. package/resources/memory/documents.d.ts.map +1 -0
  233. package/resources/memory/documents.js +39 -0
  234. package/resources/memory/documents.js.map +1 -0
  235. package/resources/memory/documents.mjs +35 -0
  236. package/resources/memory/documents.mjs.map +1 -0
  237. package/resources/memory/index.d.ts +3 -0
  238. package/resources/memory/index.d.ts.map +1 -0
  239. package/resources/memory/index.js +9 -0
  240. package/resources/memory/index.js.map +1 -0
  241. package/resources/memory/index.mjs +4 -0
  242. package/resources/memory/index.mjs.map +1 -0
  243. package/resources/memory/memory.d.ts +158 -0
  244. package/resources/memory/memory.d.ts.map +1 -0
  245. package/resources/memory/memory.js +137 -0
  246. package/resources/memory/memory.js.map +1 -0
  247. package/resources/memory/memory.mjs +110 -0
  248. package/resources/memory/memory.mjs.map +1 -0
  249. package/resources/memory-banks.d.ts +42 -0
  250. package/resources/memory-banks.d.ts.map +1 -0
  251. package/resources/memory-banks.js +40 -0
  252. package/resources/memory-banks.js.map +1 -0
  253. package/resources/memory-banks.mjs +36 -0
  254. package/resources/memory-banks.mjs.map +1 -0
  255. package/resources/models.d.ts +46 -0
  256. package/resources/models.d.ts.map +1 -0
  257. package/resources/models.js +40 -0
  258. package/resources/models.js.map +1 -0
  259. package/resources/models.mjs +36 -0
  260. package/resources/models.mjs.map +1 -0
  261. package/resources/post-training/index.d.ts +3 -0
  262. package/resources/post-training/index.d.ts.map +1 -0
  263. package/resources/post-training/index.js +9 -0
  264. package/resources/post-training/index.js.map +1 -0
  265. package/resources/post-training/index.mjs +4 -0
  266. package/resources/post-training/index.mjs.map +1 -0
  267. package/resources/post-training/jobs.d.ts +91 -0
  268. package/resources/post-training/jobs.d.ts.map +1 -0
  269. package/resources/post-training/jobs.js +80 -0
  270. package/resources/post-training/jobs.js.map +1 -0
  271. package/resources/post-training/jobs.mjs +76 -0
  272. package/resources/post-training/jobs.mjs.map +1 -0
  273. package/resources/post-training/post-training.d.ts +183 -0
  274. package/resources/post-training/post-training.d.ts.map +1 -0
  275. package/resources/post-training/post-training.js +66 -0
  276. package/resources/post-training/post-training.js.map +1 -0
  277. package/resources/post-training/post-training.mjs +39 -0
  278. package/resources/post-training/post-training.mjs.map +1 -0
  279. package/resources/reward-scoring.d.ts +47 -0
  280. package/resources/reward-scoring.d.ts.map +1 -0
  281. package/resources/reward-scoring.js +24 -0
  282. package/resources/reward-scoring.js.map +1 -0
  283. package/resources/reward-scoring.mjs +20 -0
  284. package/resources/reward-scoring.mjs.map +1 -0
  285. package/resources/safety.d.ts +41 -0
  286. package/resources/safety.d.ts.map +1 -0
  287. package/resources/safety.js +24 -0
  288. package/resources/safety.js.map +1 -0
  289. package/resources/safety.mjs +20 -0
  290. package/resources/safety.mjs.map +1 -0
  291. package/resources/shared.d.ts +42 -0
  292. package/resources/shared.d.ts.map +1 -0
  293. package/resources/shared.js +4 -0
  294. package/resources/shared.js.map +1 -0
  295. package/resources/shared.mjs +3 -0
  296. package/resources/shared.mjs.map +1 -0
  297. package/resources/shields.d.ts +42 -0
  298. package/resources/shields.d.ts.map +1 -0
  299. package/resources/shields.js +40 -0
  300. package/resources/shields.js.map +1 -0
  301. package/resources/shields.mjs +36 -0
  302. package/resources/shields.mjs.map +1 -0
  303. package/resources/synthetic-data-generation.d.ts +36 -0
  304. package/resources/synthetic-data-generation.d.ts.map +1 -0
  305. package/resources/synthetic-data-generation.js +24 -0
  306. package/resources/synthetic-data-generation.js.map +1 -0
  307. package/resources/synthetic-data-generation.mjs +20 -0
  308. package/resources/synthetic-data-generation.mjs.map +1 -0
  309. package/resources/telemetry.d.ts +81 -0
  310. package/resources/telemetry.d.ts.map +1 -0
  311. package/resources/telemetry.js +38 -0
  312. package/resources/telemetry.js.map +1 -0
  313. package/resources/telemetry.mjs +34 -0
  314. package/resources/telemetry.mjs.map +1 -0
  315. package/shims/node.d.ts +30 -0
  316. package/shims/node.d.ts.map +1 -0
  317. package/shims/node.js +31 -0
  318. package/shims/node.js.map +1 -0
  319. package/shims/node.mjs +5 -0
  320. package/shims/node.mjs.map +1 -0
  321. package/shims/web.d.ts +26 -0
  322. package/shims/web.d.ts.map +1 -0
  323. package/shims/web.js +31 -0
  324. package/shims/web.js.map +1 -0
  325. package/shims/web.mjs +5 -0
  326. package/shims/web.mjs.map +1 -0
  327. package/src/_shims/MultipartBody.ts +9 -0
  328. package/src/_shims/README.md +46 -0
  329. package/src/_shims/auto/runtime-bun.ts +4 -0
  330. package/src/_shims/auto/runtime-node.ts +4 -0
  331. package/src/_shims/auto/runtime.ts +4 -0
  332. package/src/_shims/auto/types-node.ts +4 -0
  333. package/src/_shims/auto/types.d.ts +101 -0
  334. package/src/_shims/auto/types.js +3 -0
  335. package/src/_shims/auto/types.mjs +3 -0
  336. package/src/_shims/bun-runtime.ts +14 -0
  337. package/src/_shims/index.d.ts +81 -0
  338. package/src/_shims/index.js +13 -0
  339. package/src/_shims/index.mjs +7 -0
  340. package/src/_shims/manual-types.d.ts +12 -0
  341. package/src/_shims/manual-types.js +3 -0
  342. package/src/_shims/manual-types.mjs +3 -0
  343. package/src/_shims/node-runtime.ts +81 -0
  344. package/src/_shims/node-types.d.ts +42 -0
  345. package/src/_shims/node-types.js +3 -0
  346. package/src/_shims/node-types.mjs +3 -0
  347. package/src/_shims/registry.ts +67 -0
  348. package/src/_shims/web-runtime.ts +103 -0
  349. package/src/_shims/web-types.d.ts +83 -0
  350. package/src/_shims/web-types.js +3 -0
  351. package/src/_shims/web-types.mjs +3 -0
  352. package/src/core.ts +1195 -0
  353. package/src/error.ts +146 -0
  354. package/src/index.ts +298 -0
  355. package/src/lib/.keep +4 -0
  356. package/src/resource.ts +11 -0
  357. package/src/resources/agents/agents.ts +383 -0
  358. package/src/resources/agents/index.ts +33 -0
  359. package/src/resources/agents/sessions.ts +135 -0
  360. package/src/resources/agents/steps.ts +58 -0
  361. package/src/resources/agents/turns.ts +231 -0
  362. package/src/resources/batch-inference.ts +154 -0
  363. package/src/resources/datasets.ts +110 -0
  364. package/src/resources/evaluate/evaluate.ts +35 -0
  365. package/src/resources/evaluate/index.ts +14 -0
  366. package/src/resources/evaluate/jobs/artifacts.ts +42 -0
  367. package/src/resources/evaluate/jobs/index.ts +13 -0
  368. package/src/resources/evaluate/jobs/jobs.ts +99 -0
  369. package/src/resources/evaluate/jobs/logs.ts +42 -0
  370. package/src/resources/evaluate/jobs/status.ts +42 -0
  371. package/src/resources/evaluate/question-answering.ts +42 -0
  372. package/src/resources/evaluate/summarization.ts +5 -0
  373. package/src/resources/evaluate/text-generation.ts +5 -0
  374. package/src/resources/evaluations.ts +73 -0
  375. package/src/resources/index.ts +84 -0
  376. package/src/resources/inference/embeddings.ts +48 -0
  377. package/src/resources/inference/index.ts +15 -0
  378. package/src/resources/inference/inference.ts +268 -0
  379. package/src/resources/memory/documents.ts +92 -0
  380. package/src/resources/memory/index.ts +23 -0
  381. package/src/resources/memory/memory.ts +297 -0
  382. package/src/resources/memory-banks.ts +84 -0
  383. package/src/resources/models.ts +88 -0
  384. package/src/resources/post-training/index.ts +19 -0
  385. package/src/resources/post-training/jobs.ts +192 -0
  386. package/src/resources/post-training/post-training.ts +285 -0
  387. package/src/resources/reward-scoring.ts +82 -0
  388. package/src/resources/safety.ts +66 -0
  389. package/src/resources/shared.ts +75 -0
  390. package/src/resources/shields.ts +84 -0
  391. package/src/resources/synthetic-data-generation.ts +62 -0
  392. package/src/resources/telemetry.ts +150 -0
  393. package/src/shims/node.ts +50 -0
  394. package/src/shims/web.ts +50 -0
  395. package/src/streaming.ts +475 -0
  396. package/src/tsconfig.json +11 -0
  397. package/src/uploads.ts +255 -0
  398. package/src/version.ts +1 -0
  399. package/streaming.d.ts +41 -0
  400. package/streaming.d.ts.map +1 -0
  401. package/streaming.js +403 -0
  402. package/streaming.js.map +1 -0
  403. package/streaming.mjs +396 -0
  404. package/streaming.mjs.map +1 -0
  405. package/uploads.d.ts +75 -0
  406. package/uploads.d.ts.map +1 -0
  407. package/uploads.js +171 -0
  408. package/uploads.js.map +1 -0
  409. package/uploads.mjs +158 -0
  410. package/uploads.mjs.map +1 -0
  411. package/version.d.ts +2 -0
  412. package/version.d.ts.map +1 -0
  413. package/version.js +5 -0
  414. package/version.js.map +1 -0
  415. package/version.mjs +2 -0
  416. package/version.mjs.map +1 -0
package/streaming.mjs ADDED
@@ -0,0 +1,396 @@
1
+ import { ReadableStream } from "./_shims/index.mjs";
2
+ import { LlamaStackClientError } from "./error.mjs";
3
+ export class Stream {
4
+ constructor(iterator, controller) {
5
+ this.iterator = iterator;
6
+ this.controller = controller;
7
+ }
8
+ static fromSSEResponse(response, controller) {
9
+ let consumed = false;
10
+ async function* iterator() {
11
+ if (consumed) {
12
+ throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
13
+ }
14
+ consumed = true;
15
+ let done = false;
16
+ try {
17
+ for await (const sse of _iterSSEMessages(response, controller)) {
18
+ try {
19
+ yield JSON.parse(sse.data);
20
+ }
21
+ catch (e) {
22
+ console.error(`Could not parse message into JSON:`, sse.data);
23
+ console.error(`From chunk:`, sse.raw);
24
+ throw e;
25
+ }
26
+ }
27
+ done = true;
28
+ }
29
+ catch (e) {
30
+ // If the user calls `stream.controller.abort()`, we should exit without throwing.
31
+ if (e instanceof Error && e.name === 'AbortError')
32
+ return;
33
+ throw e;
34
+ }
35
+ finally {
36
+ // If the user `break`s, abort the ongoing request.
37
+ if (!done)
38
+ controller.abort();
39
+ }
40
+ }
41
+ return new Stream(iterator, controller);
42
+ }
43
+ /**
44
+ * Generates a Stream from a newline-separated ReadableStream
45
+ * where each item is a JSON value.
46
+ */
47
+ static fromReadableStream(readableStream, controller) {
48
+ let consumed = false;
49
+ async function* iterLines() {
50
+ const lineDecoder = new LineDecoder();
51
+ const iter = readableStreamAsyncIterable(readableStream);
52
+ for await (const chunk of iter) {
53
+ for (const line of lineDecoder.decode(chunk)) {
54
+ yield line;
55
+ }
56
+ }
57
+ for (const line of lineDecoder.flush()) {
58
+ yield line;
59
+ }
60
+ }
61
+ async function* iterator() {
62
+ if (consumed) {
63
+ throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
64
+ }
65
+ consumed = true;
66
+ let done = false;
67
+ try {
68
+ for await (const line of iterLines()) {
69
+ if (done)
70
+ continue;
71
+ if (line)
72
+ yield JSON.parse(line);
73
+ }
74
+ done = true;
75
+ }
76
+ catch (e) {
77
+ // If the user calls `stream.controller.abort()`, we should exit without throwing.
78
+ if (e instanceof Error && e.name === 'AbortError')
79
+ return;
80
+ throw e;
81
+ }
82
+ finally {
83
+ // If the user `break`s, abort the ongoing request.
84
+ if (!done)
85
+ controller.abort();
86
+ }
87
+ }
88
+ return new Stream(iterator, controller);
89
+ }
90
+ [Symbol.asyncIterator]() {
91
+ return this.iterator();
92
+ }
93
+ /**
94
+ * Splits the stream into two streams which can be
95
+ * independently read from at different speeds.
96
+ */
97
+ tee() {
98
+ const left = [];
99
+ const right = [];
100
+ const iterator = this.iterator();
101
+ const teeIterator = (queue) => {
102
+ return {
103
+ next: () => {
104
+ if (queue.length === 0) {
105
+ const result = iterator.next();
106
+ left.push(result);
107
+ right.push(result);
108
+ }
109
+ return queue.shift();
110
+ },
111
+ };
112
+ };
113
+ return [
114
+ new Stream(() => teeIterator(left), this.controller),
115
+ new Stream(() => teeIterator(right), this.controller),
116
+ ];
117
+ }
118
+ /**
119
+ * Converts this stream to a newline-separated ReadableStream of
120
+ * JSON stringified values in the stream
121
+ * which can be turned back into a Stream with `Stream.fromReadableStream()`.
122
+ */
123
+ toReadableStream() {
124
+ const self = this;
125
+ let iter;
126
+ const encoder = new TextEncoder();
127
+ return new ReadableStream({
128
+ async start() {
129
+ iter = self[Symbol.asyncIterator]();
130
+ },
131
+ async pull(ctrl) {
132
+ try {
133
+ const { value, done } = await iter.next();
134
+ if (done)
135
+ return ctrl.close();
136
+ const bytes = encoder.encode(JSON.stringify(value) + '\n');
137
+ ctrl.enqueue(bytes);
138
+ }
139
+ catch (err) {
140
+ ctrl.error(err);
141
+ }
142
+ },
143
+ async cancel() {
144
+ await iter.return?.();
145
+ },
146
+ });
147
+ }
148
+ }
149
+ export async function* _iterSSEMessages(response, controller) {
150
+ if (!response.body) {
151
+ controller.abort();
152
+ throw new LlamaStackClientError(`Attempted to iterate over a response with no body`);
153
+ }
154
+ const sseDecoder = new SSEDecoder();
155
+ const lineDecoder = new LineDecoder();
156
+ const iter = readableStreamAsyncIterable(response.body);
157
+ for await (const sseChunk of iterSSEChunks(iter)) {
158
+ for (const line of lineDecoder.decode(sseChunk)) {
159
+ const sse = sseDecoder.decode(line);
160
+ if (sse)
161
+ yield sse;
162
+ }
163
+ }
164
+ for (const line of lineDecoder.flush()) {
165
+ const sse = sseDecoder.decode(line);
166
+ if (sse)
167
+ yield sse;
168
+ }
169
+ }
170
+ /**
171
+ * Given an async iterable iterator, iterates over it and yields full
172
+ * SSE chunks, i.e. yields when a double new-line is encountered.
173
+ */
174
+ async function* iterSSEChunks(iterator) {
175
+ let data = new Uint8Array();
176
+ for await (const chunk of iterator) {
177
+ if (chunk == null) {
178
+ continue;
179
+ }
180
+ const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
181
+ : typeof chunk === 'string' ? new TextEncoder().encode(chunk)
182
+ : chunk;
183
+ let newData = new Uint8Array(data.length + binaryChunk.length);
184
+ newData.set(data);
185
+ newData.set(binaryChunk, data.length);
186
+ data = newData;
187
+ let patternIndex;
188
+ while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
189
+ yield data.slice(0, patternIndex);
190
+ data = data.slice(patternIndex);
191
+ }
192
+ }
193
+ if (data.length > 0) {
194
+ yield data;
195
+ }
196
+ }
197
+ function findDoubleNewlineIndex(buffer) {
198
+ // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
199
+ // and returns the index right after the first occurrence of any pattern,
200
+ // or -1 if none of the patterns are found.
201
+ const newline = 0x0a; // \n
202
+ const carriage = 0x0d; // \r
203
+ for (let i = 0; i < buffer.length - 2; i++) {
204
+ if (buffer[i] === newline && buffer[i + 1] === newline) {
205
+ // \n\n
206
+ return i + 2;
207
+ }
208
+ if (buffer[i] === carriage && buffer[i + 1] === carriage) {
209
+ // \r\r
210
+ return i + 2;
211
+ }
212
+ if (buffer[i] === carriage &&
213
+ buffer[i + 1] === newline &&
214
+ i + 3 < buffer.length &&
215
+ buffer[i + 2] === carriage &&
216
+ buffer[i + 3] === newline) {
217
+ // \r\n\r\n
218
+ return i + 4;
219
+ }
220
+ }
221
+ return -1;
222
+ }
223
+ class SSEDecoder {
224
+ constructor() {
225
+ this.event = null;
226
+ this.data = [];
227
+ this.chunks = [];
228
+ }
229
+ decode(line) {
230
+ if (line.endsWith('\r')) {
231
+ line = line.substring(0, line.length - 1);
232
+ }
233
+ if (!line) {
234
+ // empty line and we didn't previously encounter any messages
235
+ if (!this.event && !this.data.length)
236
+ return null;
237
+ const sse = {
238
+ event: this.event,
239
+ data: this.data.join('\n'),
240
+ raw: this.chunks,
241
+ };
242
+ this.event = null;
243
+ this.data = [];
244
+ this.chunks = [];
245
+ return sse;
246
+ }
247
+ this.chunks.push(line);
248
+ if (line.startsWith(':')) {
249
+ return null;
250
+ }
251
+ let [fieldname, _, value] = partition(line, ':');
252
+ if (value.startsWith(' ')) {
253
+ value = value.substring(1);
254
+ }
255
+ if (fieldname === 'event') {
256
+ this.event = value;
257
+ }
258
+ else if (fieldname === 'data') {
259
+ this.data.push(value);
260
+ }
261
+ return null;
262
+ }
263
+ }
264
+ /**
265
+ * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally
266
+ * reading lines from text.
267
+ *
268
+ * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
269
+ */
270
+ class LineDecoder {
271
+ constructor() {
272
+ this.buffer = [];
273
+ this.trailingCR = false;
274
+ }
275
+ decode(chunk) {
276
+ let text = this.decodeText(chunk);
277
+ if (this.trailingCR) {
278
+ text = '\r' + text;
279
+ this.trailingCR = false;
280
+ }
281
+ if (text.endsWith('\r')) {
282
+ this.trailingCR = true;
283
+ text = text.slice(0, -1);
284
+ }
285
+ if (!text) {
286
+ return [];
287
+ }
288
+ const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || '');
289
+ let lines = text.split(LineDecoder.NEWLINE_REGEXP);
290
+ // if there is a trailing new line then the last entry will be an empty
291
+ // string which we don't care about
292
+ if (trailingNewline) {
293
+ lines.pop();
294
+ }
295
+ if (lines.length === 1 && !trailingNewline) {
296
+ this.buffer.push(lines[0]);
297
+ return [];
298
+ }
299
+ if (this.buffer.length > 0) {
300
+ lines = [this.buffer.join('') + lines[0], ...lines.slice(1)];
301
+ this.buffer = [];
302
+ }
303
+ if (!trailingNewline) {
304
+ this.buffer = [lines.pop() || ''];
305
+ }
306
+ return lines;
307
+ }
308
+ decodeText(bytes) {
309
+ if (bytes == null)
310
+ return '';
311
+ if (typeof bytes === 'string')
312
+ return bytes;
313
+ // Node:
314
+ if (typeof Buffer !== 'undefined') {
315
+ if (bytes instanceof Buffer) {
316
+ return bytes.toString();
317
+ }
318
+ if (bytes instanceof Uint8Array) {
319
+ return Buffer.from(bytes).toString();
320
+ }
321
+ throw new LlamaStackClientError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`);
322
+ }
323
+ // Browser
324
+ if (typeof TextDecoder !== 'undefined') {
325
+ if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
326
+ this.textDecoder ?? (this.textDecoder = new TextDecoder('utf8'));
327
+ return this.textDecoder.decode(bytes);
328
+ }
329
+ throw new LlamaStackClientError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
330
+ }
331
+ throw new LlamaStackClientError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`);
332
+ }
333
+ flush() {
334
+ if (!this.buffer.length && !this.trailingCR) {
335
+ return [];
336
+ }
337
+ const lines = [this.buffer.join('')];
338
+ this.buffer = [];
339
+ this.trailingCR = false;
340
+ return lines;
341
+ }
342
+ }
343
+ // prettier-ignore
344
+ LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']);
345
+ LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
346
+ /** This is an internal helper function that's just used for testing */
347
+ export function _decodeChunks(chunks) {
348
+ const decoder = new LineDecoder();
349
+ const lines = [];
350
+ for (const chunk of chunks) {
351
+ lines.push(...decoder.decode(chunk));
352
+ }
353
+ return lines;
354
+ }
355
+ function partition(str, delimiter) {
356
+ const index = str.indexOf(delimiter);
357
+ if (index !== -1) {
358
+ return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
359
+ }
360
+ return [str, '', ''];
361
+ }
362
+ /**
363
+ * Most browsers don't yet have async iterable support for ReadableStream,
364
+ * and Node has a very different way of reading bytes from its "ReadableStream".
365
+ *
366
+ * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
367
+ */
368
+ export function readableStreamAsyncIterable(stream) {
369
+ if (stream[Symbol.asyncIterator])
370
+ return stream;
371
+ const reader = stream.getReader();
372
+ return {
373
+ async next() {
374
+ try {
375
+ const result = await reader.read();
376
+ if (result?.done)
377
+ reader.releaseLock(); // release lock when stream becomes closed
378
+ return result;
379
+ }
380
+ catch (e) {
381
+ reader.releaseLock(); // release lock when stream becomes errored
382
+ throw e;
383
+ }
384
+ },
385
+ async return() {
386
+ const cancelPromise = reader.cancel();
387
+ reader.releaseLock();
388
+ await cancelPromise;
389
+ return { done: true, value: undefined };
390
+ },
391
+ [Symbol.asyncIterator]() {
392
+ return this;
393
+ },
394
+ };
395
+ }
396
+ //# sourceMappingURL=streaming.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streaming.mjs","sourceRoot":"","sources":["src/streaming.ts"],"names":[],"mappings":"OAAO,EAAE,cAAc,EAAiB;OACjC,EAAE,qBAAqB,EAAE;AAUhC,MAAM,OAAO,MAAM;IAGjB,YACU,QAAmC,EAC3C,UAA2B;QADnB,aAAQ,GAAR,QAAQ,CAA2B;QAG3C,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED,MAAM,CAAC,eAAe,CAAO,QAAkB,EAAE,UAA2B;QAC1E,IAAI,QAAQ,GAAG,KAAK,CAAC;QAErB,KAAK,SAAS,CAAC,CAAC,QAAQ;YACtB,IAAI,QAAQ,EAAE;gBACZ,MAAM,IAAI,KAAK,CAAC,0EAA0E,CAAC,CAAC;aAC7F;YACD,QAAQ,GAAG,IAAI,CAAC;YAChB,IAAI,IAAI,GAAG,KAAK,CAAC;YACjB,IAAI;gBACF,IAAI,KAAK,EAAE,MAAM,GAAG,IAAI,gBAAgB,CAAC,QAAQ,EAAE,UAAU,CAAC,EAAE;oBAC9D,IAAI;wBACF,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;qBAC5B;oBAAC,OAAO,CAAC,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AAC,CAAC,EAAE;QAChB,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,SAAS,EAAE,GAAG,CAAC,SAAS,CAAC,KAAK,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;KACtF;IAED,OAAO,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;AACvB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,2BAA2B,CAAI,MAAW;IACxD,IAAI,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC;QAAE,OAAO,MAAM,CAAC;IAEhD,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;IAClC,OAAO;QACL,KAAK,CAAC,IAAI;YACR,IAAI;gBACF,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;gBACnC,IAAI,MAAM,EAAE,IAAI;oBAAE,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC,0CAA0C;gBAClF,OAAO,MAAM,CAAC;aACf;YAAC,OAAO,CAAC,EAAE;gBACV,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC,2CAA2C;gBACjE,MAAM,CAAC,CAAC;aACT;QACH,CAAC;QACD,KAAK,CAAC,MAAM;YACV,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC;YACtC,MAAM,CAAC,WAAW,EAAE,CAAC;YACrB,MAAM,aAAa,CAAC;YACpB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;QAC1C,CAAC;QACD,CAAC,MAAM,CAAC,aAAa,CAAC;YACpB,OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC;AACJ,CAAC"}
package/uploads.d.ts ADDED
@@ -0,0 +1,75 @@
1
+ import { type RequestOptions } from "./core.js";
2
+ import { FormData, type Blob, type FilePropertyBag, type FsReadStream } from "./_shims/index.js";
3
+ import { MultipartBody } from "./_shims/MultipartBody.js";
4
+ export { fileFromPath } from "./_shims/index.js";
5
+ type BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | Uint8Array | DataView;
6
+ export type BlobPart = string | ArrayBuffer | ArrayBufferView | Blob | Uint8Array | DataView;
7
+ /**
8
+ * Typically, this is a native "File" class.
9
+ *
10
+ * We provide the {@link toFile} utility to convert a variety of objects
11
+ * into the File class.
12
+ *
13
+ * For convenience, you can also pass a fetch Response, or in Node,
14
+ * the result of fs.createReadStream().
15
+ */
16
+ export type Uploadable = FileLike | ResponseLike | FsReadStream;
17
+ /**
18
+ * Intended to match web.Blob, node.Blob, node-fetch.Blob, etc.
19
+ */
20
+ export interface BlobLike {
21
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */
22
+ readonly size: number;
23
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */
24
+ readonly type: string;
25
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */
26
+ text(): Promise<string>;
27
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */
28
+ slice(start?: number, end?: number): BlobLike;
29
+ }
30
+ /**
31
+ * Intended to match web.File, node.File, node-fetch.File, etc.
32
+ */
33
+ export interface FileLike extends BlobLike {
34
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */
35
+ readonly lastModified: number;
36
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */
37
+ readonly name: string;
38
+ }
39
+ /**
40
+ * Intended to match web.Response, node.Response, node-fetch.Response, etc.
41
+ */
42
+ export interface ResponseLike {
43
+ url: string;
44
+ blob(): Promise<BlobLike>;
45
+ }
46
+ export declare const isResponseLike: (value: any) => value is ResponseLike;
47
+ export declare const isFileLike: (value: any) => value is FileLike;
48
+ /**
49
+ * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check
50
+ * adds the arrayBuffer() method type because it is available and used at runtime
51
+ */
52
+ export declare const isBlobLike: (value: any) => value is BlobLike & {
53
+ arrayBuffer(): Promise<ArrayBuffer>;
54
+ };
55
+ export declare const isUploadable: (value: any) => value is Uploadable;
56
+ export type ToFileInput = Uploadable | Exclude<BlobLikePart, string> | AsyncIterable<BlobLikePart>;
57
+ /**
58
+ * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats
59
+ * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s
60
+ * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible
61
+ * @param {Object=} options additional properties
62
+ * @param {string=} options.type the MIME type of the content
63
+ * @param {number=} options.lastModified the last modified timestamp
64
+ * @returns a {@link File} with the given properties
65
+ */
66
+ export declare function toFile(value: ToFileInput | PromiseLike<ToFileInput>, name?: string | null | undefined, options?: FilePropertyBag | undefined): Promise<FileLike>;
67
+ export declare const isMultipartBody: (body: any) => body is MultipartBody;
68
+ /**
69
+ * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.
70
+ * Otherwise returns the request as is.
71
+ */
72
+ export declare const maybeMultipartFormRequestOptions: <T = Record<string, unknown>>(opts: RequestOptions<T>) => Promise<RequestOptions<MultipartBody | T>>;
73
+ export declare const multipartFormRequestOptions: <T = Record<string, unknown>>(opts: RequestOptions<T>) => Promise<RequestOptions<MultipartBody | T>>;
74
+ export declare const createForm: <T = Record<string, unknown>>(body: T | undefined) => Promise<FormData>;
75
+ //# sourceMappingURL=uploads.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uploads.d.ts","sourceRoot":"","sources":["src/uploads.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,QAAQ,CAAC;AAC7C,OAAO,EACL,QAAQ,EAER,KAAK,IAAI,EACT,KAAK,eAAe,EAEpB,KAAK,YAAY,EAElB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,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AW,GAAG,UAAU,GAAG,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC,GAAG,aAAa,CAAC,YAAY,CAAC,CAAC;AAEnG;;;;;;;;GAQG;AACH,wBAAsB,MAAM,CAC1B,KAAK,EAAE,WAAW,GAAG,WAAW,CAAC,WAAW,CAAC,EAC7C,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAChC,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,GACpC,OAAO,CAAC,QAAQ,CAAC,CAiCnB;AAmDD,eAAO,MAAM,eAAe,SAAU,GAAG,0BACsD,CAAC;AAEhG;;;GAGG;AACH,eAAO,MAAM,gCAAgC,sGAO5C,CAAC;AAEF,eAAO,MAAM,2BAA2B,sGAKvC,CAAC;AAEF,eAAO,MAAM,UAAU,wDAA6D,QAAQ,QAAQ,CAInG,CAAC"}
package/uploads.js ADDED
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createForm = exports.multipartFormRequestOptions = exports.maybeMultipartFormRequestOptions = exports.isMultipartBody = exports.toFile = exports.isUploadable = exports.isBlobLike = exports.isFileLike = exports.isResponseLike = exports.fileFromPath = void 0;
4
+ const index_1 = require("./_shims/index.js");
5
+ var index_2 = require("./_shims/index.js");
6
+ Object.defineProperty(exports, "fileFromPath", { enumerable: true, get: function () { return index_2.fileFromPath; } });
7
+ const isResponseLike = (value) => value != null &&
8
+ typeof value === 'object' &&
9
+ typeof value.url === 'string' &&
10
+ typeof value.blob === 'function';
11
+ exports.isResponseLike = isResponseLike;
12
+ const isFileLike = (value) => value != null &&
13
+ typeof value === 'object' &&
14
+ typeof value.name === 'string' &&
15
+ typeof value.lastModified === 'number' &&
16
+ (0, exports.isBlobLike)(value);
17
+ exports.isFileLike = isFileLike;
18
+ /**
19
+ * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check
20
+ * adds the arrayBuffer() method type because it is available and used at runtime
21
+ */
22
+ const isBlobLike = (value) => value != null &&
23
+ typeof value === 'object' &&
24
+ typeof value.size === 'number' &&
25
+ typeof value.type === 'string' &&
26
+ typeof value.text === 'function' &&
27
+ typeof value.slice === 'function' &&
28
+ typeof value.arrayBuffer === 'function';
29
+ exports.isBlobLike = isBlobLike;
30
+ const isUploadable = (value) => {
31
+ return (0, exports.isFileLike)(value) || (0, exports.isResponseLike)(value) || (0, index_1.isFsReadStream)(value);
32
+ };
33
+ exports.isUploadable = isUploadable;
34
+ /**
35
+ * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats
36
+ * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s
37
+ * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible
38
+ * @param {Object=} options additional properties
39
+ * @param {string=} options.type the MIME type of the content
40
+ * @param {number=} options.lastModified the last modified timestamp
41
+ * @returns a {@link File} with the given properties
42
+ */
43
+ async function toFile(value, name, options) {
44
+ // If it's a promise, resolve it.
45
+ value = await value;
46
+ // If we've been given a `File` we don't need to do anything
47
+ if ((0, exports.isFileLike)(value)) {
48
+ return value;
49
+ }
50
+ if ((0, exports.isResponseLike)(value)) {
51
+ const blob = await value.blob();
52
+ name || (name = new URL(value.url).pathname.split(/[\\/]/).pop() ?? 'unknown_file');
53
+ // we need to convert the `Blob` into an array buffer because the `Blob` class
54
+ // that `node-fetch` defines is incompatible with the web standard which results
55
+ // in `new File` interpreting it as a string instead of binary data.
56
+ const data = (0, exports.isBlobLike)(blob) ? [(await blob.arrayBuffer())] : [blob];
57
+ return new index_1.File(data, name, options);
58
+ }
59
+ const bits = await getBytes(value);
60
+ name || (name = getName(value) ?? 'unknown_file');
61
+ if (!options?.type) {
62
+ const type = bits[0]?.type;
63
+ if (typeof type === 'string') {
64
+ options = { ...options, type };
65
+ }
66
+ }
67
+ return new index_1.File(bits, name, options);
68
+ }
69
+ exports.toFile = toFile;
70
+ async function getBytes(value) {
71
+ let parts = [];
72
+ if (typeof value === 'string' ||
73
+ ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
74
+ value instanceof ArrayBuffer) {
75
+ parts.push(value);
76
+ }
77
+ else if ((0, exports.isBlobLike)(value)) {
78
+ parts.push(await value.arrayBuffer());
79
+ }
80
+ else if (isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc.
81
+ ) {
82
+ for await (const chunk of value) {
83
+ parts.push(chunk); // TODO, consider validating?
84
+ }
85
+ }
86
+ else {
87
+ throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor
88
+ ?.name}; props: ${propsForError(value)}`);
89
+ }
90
+ return parts;
91
+ }
92
+ function propsForError(value) {
93
+ const props = Object.getOwnPropertyNames(value);
94
+ return `[${props.map((p) => `"${p}"`).join(', ')}]`;
95
+ }
96
+ function getName(value) {
97
+ return (getStringFromMaybeBuffer(value.name) ||
98
+ getStringFromMaybeBuffer(value.filename) ||
99
+ // For fs.ReadStream
100
+ getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop());
101
+ }
102
+ const getStringFromMaybeBuffer = (x) => {
103
+ if (typeof x === 'string')
104
+ return x;
105
+ if (typeof Buffer !== 'undefined' && x instanceof Buffer)
106
+ return String(x);
107
+ return undefined;
108
+ };
109
+ const isAsyncIterableIterator = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';
110
+ const isMultipartBody = (body) => body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody';
111
+ exports.isMultipartBody = isMultipartBody;
112
+ /**
113
+ * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.
114
+ * Otherwise returns the request as is.
115
+ */
116
+ const maybeMultipartFormRequestOptions = async (opts) => {
117
+ if (!hasUploadableValue(opts.body))
118
+ return opts;
119
+ const form = await (0, exports.createForm)(opts.body);
120
+ return (0, index_1.getMultipartRequestOptions)(form, opts);
121
+ };
122
+ exports.maybeMultipartFormRequestOptions = maybeMultipartFormRequestOptions;
123
+ const multipartFormRequestOptions = async (opts) => {
124
+ const form = await (0, exports.createForm)(opts.body);
125
+ return (0, index_1.getMultipartRequestOptions)(form, opts);
126
+ };
127
+ exports.multipartFormRequestOptions = multipartFormRequestOptions;
128
+ const createForm = async (body) => {
129
+ const form = new index_1.FormData();
130
+ await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
131
+ return form;
132
+ };
133
+ exports.createForm = createForm;
134
+ const hasUploadableValue = (value) => {
135
+ if ((0, exports.isUploadable)(value))
136
+ return true;
137
+ if (Array.isArray(value))
138
+ return value.some(hasUploadableValue);
139
+ if (value && typeof value === 'object') {
140
+ for (const k in value) {
141
+ if (hasUploadableValue(value[k]))
142
+ return true;
143
+ }
144
+ }
145
+ return false;
146
+ };
147
+ const addFormValue = async (form, key, value) => {
148
+ if (value === undefined)
149
+ return;
150
+ if (value == null) {
151
+ throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
152
+ }
153
+ // TODO: make nested formats configurable
154
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
155
+ form.append(key, String(value));
156
+ }
157
+ else if ((0, exports.isUploadable)(value)) {
158
+ const file = await toFile(value);
159
+ form.append(key, file);
160
+ }
161
+ else if (Array.isArray(value)) {
162
+ await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry)));
163
+ }
164
+ else if (typeof value === 'object') {
165
+ await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));
166
+ }
167
+ else {
168
+ throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
169
+ }
170
+ };
171
+ //# sourceMappingURL=uploads.js.map