@arcgis/ai-components 5.1.0-next.7 → 5.1.0-next.71

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 (525) hide show
  1. package/dist/cdn/24MYCR6F.js +3 -0
  2. package/dist/cdn/276ERLGQ.js +2 -0
  3. package/dist/cdn/2MLMI2OK.js +2 -0
  4. package/dist/cdn/3D2FSGMT.js +75 -0
  5. package/dist/cdn/3M7XAZRH.js +2 -0
  6. package/dist/cdn/{ZYQ6U2YH.js → 5PT7ZFXF.js} +46 -6
  7. package/dist/cdn/7CRP5WU6.js +2 -0
  8. package/dist/cdn/{LTBEINKG.js → ABCHVJTB.js} +13 -1
  9. package/dist/cdn/B4DEC7PH.js +2 -0
  10. package/dist/cdn/B66A2V6H.js +2 -0
  11. package/dist/cdn/BUO7QQDY.js +2 -0
  12. package/dist/cdn/C5BYUKXO.js +72 -0
  13. package/dist/cdn/DR56NDCW.js +2 -0
  14. package/dist/cdn/{62K6RJZZ.js → ESTSYVJP.js} +15 -2
  15. package/dist/cdn/FEBQMS6F.js +2 -0
  16. package/dist/cdn/GY6V3KIF.js +2 -0
  17. package/dist/cdn/IHZ6MKIF.js +2 -0
  18. package/dist/cdn/IR3YHQ5A.js +225 -0
  19. package/dist/cdn/JG7SOQYZ.js +2 -0
  20. package/dist/cdn/{UY4FI7AP.js → KADK7ZYA.js} +1 -1
  21. package/dist/cdn/KVH3PDVW.js +2 -0
  22. package/dist/cdn/KWBMH7LU.js +61 -0
  23. package/dist/cdn/L7YTPHKQ.js +349 -0
  24. package/dist/cdn/MZBTKGRF.js +2 -0
  25. package/dist/cdn/MZJGADGH.js +122 -0
  26. package/dist/cdn/OLR6WPCR.js +2 -0
  27. package/dist/cdn/OQNCJHHX.js +2 -0
  28. package/dist/cdn/RFTAJAJW.js +2 -0
  29. package/dist/cdn/RMM7LKZF.js +3 -0
  30. package/dist/cdn/SGGBOB5K.js +4 -0
  31. package/dist/cdn/SN2JIWIP.js +2 -0
  32. package/dist/cdn/TD3EJQQF.js +2 -0
  33. package/dist/cdn/WH52UBDS.js +2 -0
  34. package/dist/cdn/WPWVMXUE.js +2 -0
  35. package/dist/cdn/Y4YK5Q2F.js +2 -0
  36. package/dist/cdn/{WBSNYWJJ.js → YGW7TUNX.js} +1 -1
  37. package/dist/cdn/ZDEYVBH7.js +44 -0
  38. package/dist/cdn/assets/assistant/t9n/messages.ar.json +1 -1
  39. package/dist/cdn/assets/assistant/t9n/messages.bg.json +1 -1
  40. package/dist/cdn/assets/assistant/t9n/messages.bs.json +1 -1
  41. package/dist/cdn/assets/assistant/t9n/messages.ca.json +1 -1
  42. package/dist/cdn/assets/assistant/t9n/messages.cs.json +1 -1
  43. package/dist/cdn/assets/assistant/t9n/messages.da.json +1 -1
  44. package/dist/cdn/assets/assistant/t9n/messages.de.json +1 -1
  45. package/dist/cdn/assets/assistant/t9n/messages.el.json +1 -1
  46. package/dist/cdn/assets/assistant/t9n/messages.en.json +1 -1
  47. package/dist/cdn/assets/assistant/t9n/messages.es.json +1 -1
  48. package/dist/cdn/assets/assistant/t9n/messages.et.json +1 -1
  49. package/dist/cdn/assets/assistant/t9n/messages.fi.json +1 -1
  50. package/dist/cdn/assets/assistant/t9n/messages.fr.json +1 -1
  51. package/dist/cdn/assets/assistant/t9n/messages.he.json +1 -1
  52. package/dist/cdn/assets/assistant/t9n/messages.hr.json +1 -1
  53. package/dist/cdn/assets/assistant/t9n/messages.hu.json +1 -1
  54. package/dist/cdn/assets/assistant/t9n/messages.id.json +1 -1
  55. package/dist/cdn/assets/assistant/t9n/messages.it.json +1 -1
  56. package/dist/cdn/assets/assistant/t9n/messages.ja.json +1 -1
  57. package/dist/cdn/assets/assistant/t9n/messages.ko.json +1 -1
  58. package/dist/cdn/assets/assistant/t9n/messages.lt.json +1 -1
  59. package/dist/cdn/assets/assistant/t9n/messages.lv.json +1 -1
  60. package/dist/cdn/assets/assistant/t9n/messages.nl.json +1 -1
  61. package/dist/cdn/assets/assistant/t9n/messages.no.json +1 -1
  62. package/dist/cdn/assets/assistant/t9n/messages.pl.json +1 -1
  63. package/dist/cdn/assets/assistant/t9n/messages.pt-BR.json +1 -1
  64. package/dist/cdn/assets/assistant/t9n/messages.pt-PT.json +1 -1
  65. package/dist/cdn/assets/assistant/t9n/messages.ro.json +1 -1
  66. package/dist/cdn/assets/assistant/t9n/messages.ru.json +1 -1
  67. package/dist/cdn/assets/assistant/t9n/messages.sk.json +1 -1
  68. package/dist/cdn/assets/assistant/t9n/messages.sl.json +1 -1
  69. package/dist/cdn/assets/assistant/t9n/messages.sr.json +1 -1
  70. package/dist/cdn/assets/assistant/t9n/messages.sv.json +1 -1
  71. package/dist/cdn/assets/assistant/t9n/messages.th.json +1 -1
  72. package/dist/cdn/assets/assistant/t9n/messages.tr.json +1 -1
  73. package/dist/cdn/assets/assistant/t9n/messages.uk.json +1 -1
  74. package/dist/cdn/assets/assistant/t9n/messages.vi.json +1 -1
  75. package/dist/cdn/assets/assistant/t9n/messages.zh-CN.json +1 -1
  76. package/dist/cdn/assets/assistant/t9n/messages.zh-HK.json +1 -1
  77. package/dist/cdn/assets/assistant/t9n/messages.zh-TW.json +1 -1
  78. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.ar.json +1 -1
  79. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.bg.json +1 -1
  80. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.bs.json +1 -1
  81. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.ca.json +1 -1
  82. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.cs.json +1 -1
  83. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.da.json +1 -1
  84. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.de.json +1 -1
  85. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.el.json +1 -1
  86. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.en.json +1 -1
  87. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.es.json +1 -1
  88. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.et.json +1 -1
  89. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.fi.json +1 -1
  90. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.fr.json +1 -1
  91. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.he.json +1 -1
  92. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.hr.json +1 -1
  93. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.hu.json +1 -1
  94. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.id.json +1 -1
  95. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.it.json +1 -1
  96. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.ja.json +1 -1
  97. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.ko.json +1 -1
  98. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.lt.json +1 -1
  99. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.lv.json +1 -1
  100. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.nl.json +1 -1
  101. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.no.json +1 -1
  102. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.pl.json +1 -1
  103. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.pt-BR.json +1 -1
  104. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.pt-PT.json +1 -1
  105. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.ro.json +1 -1
  106. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.ru.json +1 -1
  107. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.sk.json +1 -1
  108. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.sl.json +1 -1
  109. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.sr.json +1 -1
  110. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.sv.json +1 -1
  111. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.th.json +1 -1
  112. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.tr.json +1 -1
  113. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.uk.json +1 -1
  114. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.vi.json +1 -1
  115. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.zh-CN.json +1 -1
  116. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.zh-HK.json +1 -1
  117. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.zh-TW.json +1 -1
  118. package/dist/cdn/assets/assistant-interrupt/t9n/messages.ar.json +1 -1
  119. package/dist/cdn/assets/assistant-interrupt/t9n/messages.bg.json +1 -1
  120. package/dist/cdn/assets/assistant-interrupt/t9n/messages.bs.json +1 -1
  121. package/dist/cdn/assets/assistant-interrupt/t9n/messages.ca.json +1 -1
  122. package/dist/cdn/assets/assistant-interrupt/t9n/messages.cs.json +1 -1
  123. package/dist/cdn/assets/assistant-interrupt/t9n/messages.da.json +1 -1
  124. package/dist/cdn/assets/assistant-interrupt/t9n/messages.de.json +1 -1
  125. package/dist/cdn/assets/assistant-interrupt/t9n/messages.el.json +1 -1
  126. package/dist/cdn/assets/assistant-interrupt/t9n/messages.es.json +1 -1
  127. package/dist/cdn/assets/assistant-interrupt/t9n/messages.et.json +1 -1
  128. package/dist/cdn/assets/assistant-interrupt/t9n/messages.fi.json +1 -1
  129. package/dist/cdn/assets/assistant-interrupt/t9n/messages.fr.json +1 -1
  130. package/dist/cdn/assets/assistant-interrupt/t9n/messages.he.json +1 -1
  131. package/dist/cdn/assets/assistant-interrupt/t9n/messages.hr.json +1 -1
  132. package/dist/cdn/assets/assistant-interrupt/t9n/messages.hu.json +1 -1
  133. package/dist/cdn/assets/assistant-interrupt/t9n/messages.id.json +1 -1
  134. package/dist/cdn/assets/assistant-interrupt/t9n/messages.it.json +1 -1
  135. package/dist/cdn/assets/assistant-interrupt/t9n/messages.ja.json +1 -1
  136. package/dist/cdn/assets/assistant-interrupt/t9n/messages.ko.json +1 -1
  137. package/dist/cdn/assets/assistant-interrupt/t9n/messages.lt.json +1 -1
  138. package/dist/cdn/assets/assistant-interrupt/t9n/messages.lv.json +1 -1
  139. package/dist/cdn/assets/assistant-interrupt/t9n/messages.nl.json +1 -1
  140. package/dist/cdn/assets/assistant-interrupt/t9n/messages.no.json +1 -1
  141. package/dist/cdn/assets/assistant-interrupt/t9n/messages.pl.json +1 -1
  142. package/dist/cdn/assets/assistant-interrupt/t9n/messages.pt-BR.json +1 -1
  143. package/dist/cdn/assets/assistant-interrupt/t9n/messages.pt-PT.json +1 -1
  144. package/dist/cdn/assets/assistant-interrupt/t9n/messages.ro.json +1 -1
  145. package/dist/cdn/assets/assistant-interrupt/t9n/messages.ru.json +1 -1
  146. package/dist/cdn/assets/assistant-interrupt/t9n/messages.sk.json +1 -1
  147. package/dist/cdn/assets/assistant-interrupt/t9n/messages.sl.json +1 -1
  148. package/dist/cdn/assets/assistant-interrupt/t9n/messages.sr.json +1 -1
  149. package/dist/cdn/assets/assistant-interrupt/t9n/messages.sv.json +1 -1
  150. package/dist/cdn/assets/assistant-interrupt/t9n/messages.th.json +1 -1
  151. package/dist/cdn/assets/assistant-interrupt/t9n/messages.tr.json +1 -1
  152. package/dist/cdn/assets/assistant-interrupt/t9n/messages.uk.json +1 -1
  153. package/dist/cdn/assets/assistant-interrupt/t9n/messages.vi.json +1 -1
  154. package/dist/cdn/assets/assistant-interrupt/t9n/messages.zh-CN.json +1 -1
  155. package/dist/cdn/assets/assistant-interrupt/t9n/messages.zh-HK.json +1 -1
  156. package/dist/cdn/assets/assistant-interrupt/t9n/messages.zh-TW.json +1 -1
  157. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.ar.json +1 -0
  158. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.bg.json +1 -0
  159. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.bs.json +1 -0
  160. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.ca.json +1 -0
  161. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.cs.json +1 -0
  162. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.da.json +1 -0
  163. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.de.json +1 -0
  164. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.el.json +1 -0
  165. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.en.json +1 -0
  166. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.es.json +1 -0
  167. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.et.json +1 -0
  168. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.fi.json +1 -0
  169. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.fr.json +1 -0
  170. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.he.json +1 -0
  171. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.hr.json +1 -0
  172. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.hu.json +1 -0
  173. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.id.json +1 -0
  174. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.it.json +1 -0
  175. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.ja.json +1 -0
  176. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.ko.json +1 -0
  177. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.lt.json +1 -0
  178. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.lv.json +1 -0
  179. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.nl.json +1 -0
  180. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.no.json +1 -0
  181. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.pl.json +1 -0
  182. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.pt-BR.json +1 -0
  183. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.pt-PT.json +1 -0
  184. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.ro.json +1 -0
  185. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.ru.json +1 -0
  186. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.sk.json +1 -0
  187. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.sl.json +1 -0
  188. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.sr.json +1 -0
  189. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.sv.json +1 -0
  190. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.th.json +1 -0
  191. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.tr.json +1 -0
  192. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.uk.json +1 -0
  193. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.vi.json +1 -0
  194. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.zh-CN.json +1 -0
  195. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.zh-HK.json +1 -0
  196. package/dist/cdn/assets/assistant-message-feedback/t9n/messages.zh-TW.json +1 -0
  197. package/dist/cdn/assets/assistant-message-footer/t9n/messages.ar.json +1 -0
  198. package/dist/cdn/assets/assistant-message-footer/t9n/messages.bg.json +1 -0
  199. package/dist/cdn/assets/assistant-message-footer/t9n/messages.bs.json +1 -0
  200. package/dist/cdn/assets/assistant-message-footer/t9n/messages.ca.json +1 -0
  201. package/dist/cdn/assets/assistant-message-footer/t9n/messages.cs.json +1 -0
  202. package/dist/cdn/assets/assistant-message-footer/t9n/messages.da.json +1 -0
  203. package/dist/cdn/assets/assistant-message-footer/t9n/messages.de.json +1 -0
  204. package/dist/cdn/assets/assistant-message-footer/t9n/messages.el.json +1 -0
  205. package/dist/cdn/assets/assistant-message-footer/t9n/messages.en.json +1 -0
  206. package/dist/cdn/assets/assistant-message-footer/t9n/messages.es.json +1 -0
  207. package/dist/cdn/assets/assistant-message-footer/t9n/messages.et.json +1 -0
  208. package/dist/cdn/assets/assistant-message-footer/t9n/messages.fi.json +1 -0
  209. package/dist/cdn/assets/assistant-message-footer/t9n/messages.fr.json +1 -0
  210. package/dist/cdn/assets/assistant-message-footer/t9n/messages.he.json +1 -0
  211. package/dist/cdn/assets/assistant-message-footer/t9n/messages.hr.json +1 -0
  212. package/dist/cdn/assets/assistant-message-footer/t9n/messages.hu.json +1 -0
  213. package/dist/cdn/assets/assistant-message-footer/t9n/messages.id.json +1 -0
  214. package/dist/cdn/assets/assistant-message-footer/t9n/messages.it.json +1 -0
  215. package/dist/cdn/assets/assistant-message-footer/t9n/messages.ja.json +1 -0
  216. package/dist/cdn/assets/assistant-message-footer/t9n/messages.ko.json +1 -0
  217. package/dist/cdn/assets/assistant-message-footer/t9n/messages.lt.json +1 -0
  218. package/dist/cdn/assets/assistant-message-footer/t9n/messages.lv.json +1 -0
  219. package/dist/cdn/assets/assistant-message-footer/t9n/messages.nl.json +1 -0
  220. package/dist/cdn/assets/assistant-message-footer/t9n/messages.no.json +1 -0
  221. package/dist/cdn/assets/assistant-message-footer/t9n/messages.pl.json +1 -0
  222. package/dist/cdn/assets/assistant-message-footer/t9n/messages.pt-BR.json +1 -0
  223. package/dist/cdn/assets/assistant-message-footer/t9n/messages.pt-PT.json +1 -0
  224. package/dist/cdn/assets/assistant-message-footer/t9n/messages.ro.json +1 -0
  225. package/dist/cdn/assets/assistant-message-footer/t9n/messages.ru.json +1 -0
  226. package/dist/cdn/assets/assistant-message-footer/t9n/messages.sk.json +1 -0
  227. package/dist/cdn/assets/assistant-message-footer/t9n/messages.sl.json +1 -0
  228. package/dist/cdn/assets/assistant-message-footer/t9n/messages.sr.json +1 -0
  229. package/dist/cdn/assets/assistant-message-footer/t9n/messages.sv.json +1 -0
  230. package/dist/cdn/assets/assistant-message-footer/t9n/messages.th.json +1 -0
  231. package/dist/cdn/assets/assistant-message-footer/t9n/messages.tr.json +1 -0
  232. package/dist/cdn/assets/assistant-message-footer/t9n/messages.uk.json +1 -0
  233. package/dist/cdn/assets/assistant-message-footer/t9n/messages.vi.json +1 -0
  234. package/dist/cdn/assets/assistant-message-footer/t9n/messages.zh-CN.json +1 -0
  235. package/dist/cdn/assets/assistant-message-footer/t9n/messages.zh-HK.json +1 -0
  236. package/dist/cdn/assets/assistant-message-footer/t9n/messages.zh-TW.json +1 -0
  237. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.ar.json +1 -0
  238. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.bg.json +1 -0
  239. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.bs.json +1 -0
  240. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.ca.json +1 -0
  241. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.cs.json +1 -0
  242. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.da.json +1 -0
  243. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.de.json +1 -0
  244. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.el.json +1 -0
  245. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.en.json +1 -0
  246. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.es.json +1 -0
  247. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.et.json +1 -0
  248. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.fi.json +1 -0
  249. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.fr.json +1 -0
  250. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.he.json +1 -0
  251. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.hr.json +1 -0
  252. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.hu.json +1 -0
  253. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.id.json +1 -0
  254. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.it.json +1 -0
  255. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.ja.json +1 -0
  256. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.ko.json +1 -0
  257. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.lt.json +1 -0
  258. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.lv.json +1 -0
  259. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.nl.json +1 -0
  260. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.no.json +1 -0
  261. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.pl.json +1 -0
  262. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.pt-BR.json +1 -0
  263. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.pt-PT.json +1 -0
  264. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.ro.json +1 -0
  265. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.ru.json +1 -0
  266. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.sk.json +1 -0
  267. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.sl.json +1 -0
  268. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.sr.json +1 -0
  269. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.sv.json +1 -0
  270. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.th.json +1 -0
  271. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.tr.json +1 -0
  272. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.uk.json +1 -0
  273. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.vi.json +1 -0
  274. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.zh-CN.json +1 -0
  275. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.zh-HK.json +1 -0
  276. package/dist/cdn/assets/assistant-message-read-aloud/t9n/messages.zh-TW.json +1 -0
  277. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.ar.json +1 -0
  278. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.bg.json +1 -0
  279. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.bs.json +1 -0
  280. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.ca.json +1 -0
  281. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.cs.json +1 -0
  282. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.da.json +1 -0
  283. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.de.json +1 -0
  284. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.el.json +1 -0
  285. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.en.json +1 -0
  286. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.es.json +1 -0
  287. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.et.json +1 -0
  288. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.fi.json +1 -0
  289. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.fr.json +1 -0
  290. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.he.json +1 -0
  291. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.hr.json +1 -0
  292. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.hu.json +1 -0
  293. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.id.json +1 -0
  294. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.it.json +1 -0
  295. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.ja.json +1 -0
  296. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.ko.json +1 -0
  297. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.lt.json +1 -0
  298. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.lv.json +1 -0
  299. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.nl.json +1 -0
  300. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.no.json +1 -0
  301. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.pl.json +1 -0
  302. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.pt-BR.json +1 -0
  303. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.pt-PT.json +1 -0
  304. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.ro.json +1 -0
  305. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.ru.json +1 -0
  306. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.sk.json +1 -0
  307. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.sl.json +1 -0
  308. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.sr.json +1 -0
  309. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.sv.json +1 -0
  310. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.th.json +1 -0
  311. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.tr.json +1 -0
  312. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.uk.json +1 -0
  313. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.vi.json +1 -0
  314. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.zh-CN.json +1 -0
  315. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.zh-HK.json +1 -0
  316. package/dist/cdn/assets/assistant-suggested-prompts/t9n/messages.zh-TW.json +1 -0
  317. package/dist/cdn/index.js +1 -1
  318. package/dist/cdn/main.css +1 -1
  319. package/dist/chunks/converterUtils.js +117 -0
  320. package/dist/chunks/utils.js +16 -14
  321. package/dist/chunks/utils2.js +8 -3
  322. package/dist/components/arcgis-assistant/customElement.d.ts +342 -27
  323. package/dist/components/arcgis-assistant/customElement.js +216 -147
  324. package/dist/components/arcgis-assistant/index.js +9 -2
  325. package/dist/components/arcgis-assistant/types.d.ts +136 -0
  326. package/dist/components/arcgis-assistant-agent/customElement.d.ts +22 -8
  327. package/dist/components/arcgis-assistant-agent/customElement.js +7 -7
  328. package/dist/components/arcgis-assistant-chat/customElement.d.ts +2 -9
  329. package/dist/components/arcgis-assistant-chat/customElement.js +13 -13
  330. package/dist/components/arcgis-assistant-chat/index.js +0 -1
  331. package/dist/components/arcgis-assistant-chat-entry/customElement.d.ts +15 -12
  332. package/dist/components/arcgis-assistant-chat-entry/customElement.js +59 -25
  333. package/dist/components/arcgis-assistant-chat-entry/index.js +1 -2
  334. package/dist/components/arcgis-assistant-data-exploration-agent/customElement.d.ts +73 -6
  335. package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +5 -5
  336. package/dist/components/arcgis-assistant-help-agent/customElement.d.ts +73 -0
  337. package/dist/components/arcgis-assistant-help-agent/customElement.js +26 -0
  338. package/dist/components/arcgis-assistant-interrupt/customElement.d.ts +1 -1
  339. package/dist/components/arcgis-assistant-interrupt/customElement.js +8 -8
  340. package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +6 -6
  341. package/dist/components/arcgis-assistant-message/customElement.d.ts +18 -0
  342. package/dist/components/arcgis-assistant-message/customElement.js +29 -0
  343. package/dist/components/arcgis-assistant-message/index.d.ts +1 -0
  344. package/dist/components/arcgis-assistant-message/index.js +4 -0
  345. package/dist/components/arcgis-assistant-message-block/customElement.d.ts +8 -0
  346. package/dist/components/arcgis-assistant-message-block/customElement.js +29 -0
  347. package/dist/components/arcgis-assistant-message-block/index.js +2 -0
  348. package/dist/components/arcgis-assistant-message-content/customElement.d.ts +12 -0
  349. package/dist/components/arcgis-assistant-message-content/customElement.js +62 -0
  350. package/dist/components/arcgis-assistant-message-content/index.js +4 -0
  351. package/dist/components/arcgis-assistant-message-feedback/customElement.d.ts +23 -0
  352. package/dist/components/arcgis-assistant-message-feedback/customElement.js +36 -0
  353. package/dist/components/arcgis-assistant-message-feedback/index.js +3 -0
  354. package/dist/components/arcgis-assistant-message-footer/customElement.d.ts +25 -0
  355. package/dist/components/arcgis-assistant-message-footer/customElement.js +62 -0
  356. package/dist/components/arcgis-assistant-message-footer/index.js +6 -0
  357. package/dist/components/arcgis-assistant-message-loading/customElement.d.ts +10 -0
  358. package/dist/components/arcgis-assistant-message-loading/customElement.js +23 -0
  359. package/dist/components/arcgis-assistant-message-loading/index.js +4 -0
  360. package/dist/components/arcgis-assistant-message-log/customElement.d.ts +11 -0
  361. package/dist/components/arcgis-assistant-message-log/customElement.js +29 -0
  362. package/dist/components/arcgis-assistant-message-log/index.d.ts +1 -0
  363. package/dist/components/arcgis-assistant-message-log/index.js +3 -0
  364. package/dist/components/arcgis-assistant-message-read-aloud/customElement.d.ts +19 -0
  365. package/dist/components/arcgis-assistant-message-read-aloud/customElement.js +104 -0
  366. package/dist/components/arcgis-assistant-message-read-aloud/index.d.ts +1 -0
  367. package/dist/components/arcgis-assistant-message-read-aloud/index.js +3 -0
  368. package/dist/components/arcgis-assistant-message-text/customElement.d.ts +7 -0
  369. package/dist/components/arcgis-assistant-message-text/customElement.js +22 -0
  370. package/dist/components/arcgis-assistant-message-text/index.d.ts +1 -0
  371. package/dist/components/arcgis-assistant-message-text/index.js +1 -0
  372. package/dist/components/arcgis-assistant-navigation-agent/customElement.d.ts +53 -6
  373. package/dist/components/arcgis-assistant-navigation-agent/customElement.js +5 -5
  374. package/dist/components/arcgis-assistant-speech-input/customElement.d.ts +31 -0
  375. package/dist/components/arcgis-assistant-speech-input/customElement.js +488 -0
  376. package/dist/components/arcgis-assistant-speech-input/index.d.ts +1 -0
  377. package/dist/components/arcgis-assistant-speech-input/index.js +2 -0
  378. package/dist/components/arcgis-assistant-speech-input/support/types.d.ts +20 -0
  379. package/dist/components/arcgis-assistant-suggested-prompts/customElement.d.ts +16 -0
  380. package/dist/components/arcgis-assistant-suggested-prompts/customElement.js +27 -0
  381. package/dist/components/arcgis-assistant-suggested-prompts/index.d.ts +1 -0
  382. package/dist/components/arcgis-assistant-suggested-prompts/index.js +3 -0
  383. package/dist/components/arcgis-assistant-user-message/customElement.d.ts +10 -0
  384. package/dist/components/arcgis-assistant-user-message/customElement.js +23 -0
  385. package/dist/components/arcgis-assistant-user-message/index.d.ts +1 -0
  386. package/dist/components/arcgis-assistant-user-message/index.js +2 -0
  387. package/dist/docs/api.json +1 -1
  388. package/dist/docs/docs.json +1 -1
  389. package/dist/docs/vscode.html-custom-data.json +1 -1
  390. package/dist/docs/web-types.json +1 -1
  391. package/dist/index.d.ts +78 -22
  392. package/dist/loader.js +19 -11
  393. package/dist/types/lumina.d.ts +83 -26
  394. package/dist/types/preact.d.ts +96 -31
  395. package/dist/types/react.d.ts +109 -36
  396. package/dist/types/stencil.d.ts +83 -26
  397. package/dist/utils/index.d.ts +305 -0
  398. package/dist/utils/index.js +13 -0
  399. package/package.json +15 -8
  400. package/dist/cdn/26V7SXDR.js +0 -4
  401. package/dist/cdn/2PLHSU7P.js +0 -271
  402. package/dist/cdn/4Y73V2HU.js +0 -2
  403. package/dist/cdn/6T2EIYO4.js +0 -59
  404. package/dist/cdn/AIAY4NON.js +0 -245
  405. package/dist/cdn/CN6VFVA2.js +0 -19
  406. package/dist/cdn/GCFT45CD.js +0 -2
  407. package/dist/cdn/GN2HYJJX.js +0 -4
  408. package/dist/cdn/HN2HMAMX.js +0 -28
  409. package/dist/cdn/I22GHLAO.js +0 -2
  410. package/dist/cdn/IFSNQY7L.js +0 -2
  411. package/dist/cdn/IFWK7P7O.js +0 -2
  412. package/dist/cdn/J35M7O4J.js +0 -2
  413. package/dist/cdn/JABDBJPC.js +0 -2
  414. package/dist/cdn/KJZARHAM.js +0 -2
  415. package/dist/cdn/M672SFG6.js +0 -2
  416. package/dist/cdn/M7XUI5KY.js +0 -77
  417. package/dist/cdn/NKNUZCLA.js +0 -17
  418. package/dist/cdn/Q674OE2M.js +0 -2
  419. package/dist/cdn/SOWNHB7F.js +0 -30
  420. package/dist/cdn/VUHDKXFM.js +0 -2
  421. package/dist/cdn/X7WF7TCS.js +0 -2
  422. package/dist/cdn/XGVAPO3I.js +0 -2
  423. package/dist/cdn/XVUE27HC.js +0 -2
  424. package/dist/cdn/Y7UZYXEV.js +0 -2
  425. package/dist/cdn/ZF7JAW4Z.js +0 -2
  426. package/dist/cdn/assets/assistant-chat-card/t9n/messages.ar.json +0 -1
  427. package/dist/cdn/assets/assistant-chat-card/t9n/messages.bg.json +0 -1
  428. package/dist/cdn/assets/assistant-chat-card/t9n/messages.bs.json +0 -1
  429. package/dist/cdn/assets/assistant-chat-card/t9n/messages.ca.json +0 -1
  430. package/dist/cdn/assets/assistant-chat-card/t9n/messages.cs.json +0 -1
  431. package/dist/cdn/assets/assistant-chat-card/t9n/messages.da.json +0 -1
  432. package/dist/cdn/assets/assistant-chat-card/t9n/messages.de.json +0 -1
  433. package/dist/cdn/assets/assistant-chat-card/t9n/messages.el.json +0 -1
  434. package/dist/cdn/assets/assistant-chat-card/t9n/messages.en.json +0 -1
  435. package/dist/cdn/assets/assistant-chat-card/t9n/messages.es.json +0 -1
  436. package/dist/cdn/assets/assistant-chat-card/t9n/messages.et.json +0 -1
  437. package/dist/cdn/assets/assistant-chat-card/t9n/messages.fi.json +0 -1
  438. package/dist/cdn/assets/assistant-chat-card/t9n/messages.fr.json +0 -1
  439. package/dist/cdn/assets/assistant-chat-card/t9n/messages.he.json +0 -1
  440. package/dist/cdn/assets/assistant-chat-card/t9n/messages.hr.json +0 -1
  441. package/dist/cdn/assets/assistant-chat-card/t9n/messages.hu.json +0 -1
  442. package/dist/cdn/assets/assistant-chat-card/t9n/messages.id.json +0 -1
  443. package/dist/cdn/assets/assistant-chat-card/t9n/messages.it.json +0 -1
  444. package/dist/cdn/assets/assistant-chat-card/t9n/messages.ja.json +0 -1
  445. package/dist/cdn/assets/assistant-chat-card/t9n/messages.ko.json +0 -1
  446. package/dist/cdn/assets/assistant-chat-card/t9n/messages.lt.json +0 -1
  447. package/dist/cdn/assets/assistant-chat-card/t9n/messages.lv.json +0 -1
  448. package/dist/cdn/assets/assistant-chat-card/t9n/messages.nl.json +0 -1
  449. package/dist/cdn/assets/assistant-chat-card/t9n/messages.no.json +0 -1
  450. package/dist/cdn/assets/assistant-chat-card/t9n/messages.pl.json +0 -1
  451. package/dist/cdn/assets/assistant-chat-card/t9n/messages.pt-BR.json +0 -1
  452. package/dist/cdn/assets/assistant-chat-card/t9n/messages.pt-PT.json +0 -1
  453. package/dist/cdn/assets/assistant-chat-card/t9n/messages.ro.json +0 -1
  454. package/dist/cdn/assets/assistant-chat-card/t9n/messages.ru.json +0 -1
  455. package/dist/cdn/assets/assistant-chat-card/t9n/messages.sk.json +0 -1
  456. package/dist/cdn/assets/assistant-chat-card/t9n/messages.sl.json +0 -1
  457. package/dist/cdn/assets/assistant-chat-card/t9n/messages.sr.json +0 -1
  458. package/dist/cdn/assets/assistant-chat-card/t9n/messages.sv.json +0 -1
  459. package/dist/cdn/assets/assistant-chat-card/t9n/messages.th.json +0 -1
  460. package/dist/cdn/assets/assistant-chat-card/t9n/messages.tr.json +0 -1
  461. package/dist/cdn/assets/assistant-chat-card/t9n/messages.uk.json +0 -1
  462. package/dist/cdn/assets/assistant-chat-card/t9n/messages.vi.json +0 -1
  463. package/dist/cdn/assets/assistant-chat-card/t9n/messages.zh-CN.json +0 -1
  464. package/dist/cdn/assets/assistant-chat-card/t9n/messages.zh-HK.json +0 -1
  465. package/dist/cdn/assets/assistant-chat-card/t9n/messages.zh-TW.json +0 -1
  466. package/dist/cdn/assets/assistant-shell/t9n/messages.ar.json +0 -1
  467. package/dist/cdn/assets/assistant-shell/t9n/messages.bg.json +0 -1
  468. package/dist/cdn/assets/assistant-shell/t9n/messages.bs.json +0 -1
  469. package/dist/cdn/assets/assistant-shell/t9n/messages.ca.json +0 -1
  470. package/dist/cdn/assets/assistant-shell/t9n/messages.cs.json +0 -1
  471. package/dist/cdn/assets/assistant-shell/t9n/messages.da.json +0 -1
  472. package/dist/cdn/assets/assistant-shell/t9n/messages.de.json +0 -1
  473. package/dist/cdn/assets/assistant-shell/t9n/messages.el.json +0 -1
  474. package/dist/cdn/assets/assistant-shell/t9n/messages.en.json +0 -1
  475. package/dist/cdn/assets/assistant-shell/t9n/messages.es.json +0 -1
  476. package/dist/cdn/assets/assistant-shell/t9n/messages.et.json +0 -1
  477. package/dist/cdn/assets/assistant-shell/t9n/messages.fi.json +0 -1
  478. package/dist/cdn/assets/assistant-shell/t9n/messages.fr.json +0 -1
  479. package/dist/cdn/assets/assistant-shell/t9n/messages.he.json +0 -1
  480. package/dist/cdn/assets/assistant-shell/t9n/messages.hr.json +0 -1
  481. package/dist/cdn/assets/assistant-shell/t9n/messages.hu.json +0 -1
  482. package/dist/cdn/assets/assistant-shell/t9n/messages.id.json +0 -1
  483. package/dist/cdn/assets/assistant-shell/t9n/messages.it.json +0 -1
  484. package/dist/cdn/assets/assistant-shell/t9n/messages.ja.json +0 -1
  485. package/dist/cdn/assets/assistant-shell/t9n/messages.ko.json +0 -1
  486. package/dist/cdn/assets/assistant-shell/t9n/messages.lt.json +0 -1
  487. package/dist/cdn/assets/assistant-shell/t9n/messages.lv.json +0 -1
  488. package/dist/cdn/assets/assistant-shell/t9n/messages.nl.json +0 -1
  489. package/dist/cdn/assets/assistant-shell/t9n/messages.no.json +0 -1
  490. package/dist/cdn/assets/assistant-shell/t9n/messages.pl.json +0 -1
  491. package/dist/cdn/assets/assistant-shell/t9n/messages.pt-BR.json +0 -1
  492. package/dist/cdn/assets/assistant-shell/t9n/messages.pt-PT.json +0 -1
  493. package/dist/cdn/assets/assistant-shell/t9n/messages.ro.json +0 -1
  494. package/dist/cdn/assets/assistant-shell/t9n/messages.ru.json +0 -1
  495. package/dist/cdn/assets/assistant-shell/t9n/messages.sk.json +0 -1
  496. package/dist/cdn/assets/assistant-shell/t9n/messages.sl.json +0 -1
  497. package/dist/cdn/assets/assistant-shell/t9n/messages.sr.json +0 -1
  498. package/dist/cdn/assets/assistant-shell/t9n/messages.sv.json +0 -1
  499. package/dist/cdn/assets/assistant-shell/t9n/messages.th.json +0 -1
  500. package/dist/cdn/assets/assistant-shell/t9n/messages.tr.json +0 -1
  501. package/dist/cdn/assets/assistant-shell/t9n/messages.uk.json +0 -1
  502. package/dist/cdn/assets/assistant-shell/t9n/messages.vi.json +0 -1
  503. package/dist/cdn/assets/assistant-shell/t9n/messages.zh-CN.json +0 -1
  504. package/dist/cdn/assets/assistant-shell/t9n/messages.zh-HK.json +0 -1
  505. package/dist/cdn/assets/assistant-shell/t9n/messages.zh-TW.json +0 -1
  506. package/dist/components/arcgis-assistant-chat-card/customElement.d.ts +0 -32
  507. package/dist/components/arcgis-assistant-chat-card/customElement.js +0 -53
  508. package/dist/components/arcgis-assistant-chat-card/index.js +0 -6
  509. package/dist/components/arcgis-assistant-chat-card-content/customElement.d.ts +0 -12
  510. package/dist/components/arcgis-assistant-chat-card-content/customElement.js +0 -40
  511. package/dist/components/arcgis-assistant-chat-card-content/index.js +0 -2
  512. package/dist/components/arcgis-assistant-layer-filter-agent/customElement.d.ts +0 -8
  513. package/dist/components/arcgis-assistant-layer-filter-agent/customElement.js +0 -26
  514. package/dist/components/arcgis-assistant-layer-query-agent/customElement.d.ts +0 -8
  515. package/dist/components/arcgis-assistant-layer-query-agent/customElement.js +0 -26
  516. package/dist/components/arcgis-assistant-shell/customElement.d.ts +0 -37
  517. package/dist/components/arcgis-assistant-shell/customElement.js +0 -27
  518. package/dist/components/arcgis-assistant-shell/index.js +0 -6
  519. /package/dist/components/{arcgis-assistant-chat-card-content → arcgis-assistant-help-agent}/index.d.ts +0 -0
  520. /package/dist/components/{arcgis-assistant-layer-filter-agent → arcgis-assistant-help-agent}/index.js +0 -0
  521. /package/dist/components/{arcgis-assistant-chat-card → arcgis-assistant-message-block}/index.d.ts +0 -0
  522. /package/dist/components/{arcgis-assistant-layer-filter-agent → arcgis-assistant-message-content}/index.d.ts +0 -0
  523. /package/dist/components/{arcgis-assistant-layer-query-agent → arcgis-assistant-message-feedback}/index.d.ts +0 -0
  524. /package/dist/components/{arcgis-assistant-shell → arcgis-assistant-message-footer}/index.d.ts +0 -0
  525. /package/dist/components/{arcgis-assistant-layer-query-agent/index.js → arcgis-assistant-message-loading/index.d.ts} +0 -0
@@ -1,271 +0,0 @@
1
- /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{a as ae,b as $s,c as Cs}from"./CFDTXKJ6.js";export default $arcgis.t(([GE,KE,_q,xz])=>{var lk=ae((tW,uk)=>{"use strict";uk.exports=function(e,t){if(typeof e!="string")throw new TypeError("Expected a string");return t=typeof t>"u"?"_":t,e.replace(/([a-z\d])([A-Z])/g,"$1"+t+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+t+"$2").toLowerCase()}});var _k=ae((rW,V_)=>{"use strict";var Wz=/[\p{Lu}]/u,Jz=/[\p{Ll}]/u,pk=/^[\p{Lu}](?![\p{Lu}])/gu,mk=/([\p{Alpha}\p{N}_]|$)/u,hk=/[_.\- ]+/,Xz=new RegExp("^"+hk.source),dk=new RegExp(hk.source+mk.source,"gu"),fk=new RegExp("\\d+"+mk.source,"gu"),Yz=(e,t,r)=>{let n=!1,i=!1,s=!1;for(let o=0;o<e.length;o++){let a=e[o];n&&Wz.test(a)?(e=e.slice(0,o)+"-"+e.slice(o),n=!1,s=i,i=!0,o++):i&&s&&Jz.test(a)?(e=e.slice(0,o-1)+"-"+e.slice(o-1),s=i,i=!1,n=!0):(n=t(a)===a&&r(a)!==a,s=i,i=r(a)===a&&t(a)!==a)}return e},Qz=(e,t)=>(pk.lastIndex=0,e.replace(pk,r=>t(r))),eL=(e,t)=>(dk.lastIndex=0,fk.lastIndex=0,e.replace(dk,(r,n)=>t(n)).replace(fk,r=>t(r))),gk=(e,t)=>{if(!(typeof e=="string"||Array.isArray(e)))throw new TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},Array.isArray(e)?e=e.map(s=>s.trim()).filter(s=>s.length).join("-"):e=e.trim(),e.length===0)return"";let r=t.locale===!1?s=>s.toLowerCase():s=>s.toLocaleLowerCase(t.locale),n=t.locale===!1?s=>s.toUpperCase():s=>s.toLocaleUpperCase(t.locale);return e.length===1?t.pascalCase?n(e):r(e):(e!==r(e)&&(e=Yz(e,r,n)),e=e.replace(Xz,""),t.preserveConsecutiveUppercase?e=Qz(e,r):e=r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),eL(e,n))};V_.exports=gk;V_.exports.default=gk});var OA=ae((I8,wy)=>{"use strict";var DL=Object.prototype.hasOwnProperty,lr="~";function gl(){}Object.create&&(gl.prototype=Object.create(null),new gl().__proto__||(lr=!1));function zL(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function TA(e,t,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var s=new zL(r,n||e,i),o=lr?lr+t:t;return e._events[o]?e._events[o].fn?e._events[o]=[e._events[o],s]:e._events[o].push(s):(e._events[o]=s,e._eventsCount++),e}function bf(e,t){--e._eventsCount===0?e._events=new gl:delete e._events[t]}function Jt(){this._events=new gl,this._eventsCount=0}Jt.prototype.eventNames=function(){var t=[],r,n;if(this._eventsCount===0)return t;for(n in r=this._events)DL.call(r,n)&&t.push(lr?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(r)):t};Jt.prototype.listeners=function(t){var r=lr?lr+t:t,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o};Jt.prototype.listenerCount=function(t){var r=lr?lr+t:t,n=this._events[r];return n?n.fn?1:n.length:0};Jt.prototype.emit=function(t,r,n,i,s,o){var a=lr?lr+t:t;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,p;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,i),!0;case 5:return c.fn.call(c.context,r,n,i,s),!0;case 6:return c.fn.call(c.context,r,n,i,s,o),!0}for(p=1,l=new Array(u-1);p<u;p++)l[p-1]=arguments[p];c.fn.apply(c.context,l)}else{var f=c.length,d;for(p=0;p<f;p++)switch(c[p].once&&this.removeListener(t,c[p].fn,void 0,!0),u){case 1:c[p].fn.call(c[p].context);break;case 2:c[p].fn.call(c[p].context,r);break;case 3:c[p].fn.call(c[p].context,r,n);break;case 4:c[p].fn.call(c[p].context,r,n,i);break;default:if(!l)for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];c[p].fn.apply(c[p].context,l)}}return!0};Jt.prototype.on=function(t,r,n){return TA(this,t,r,n,!1)};Jt.prototype.once=function(t,r,n){return TA(this,t,r,n,!0)};Jt.prototype.removeListener=function(t,r,n,i){var s=lr?lr+t:t;if(!this._events[s])return this;if(!r)return bf(this,s),this;var o=this._events[s];if(o.fn)o.fn===r&&(!i||o.once)&&(!n||o.context===n)&&bf(this,s);else{for(var a=0,c=[],u=o.length;a<u;a++)(o[a].fn!==r||i&&!o[a].once||n&&o[a].context!==n)&&c.push(o[a]);c.length?this._events[s]=c.length===1?c[0]:c:bf(this,s)}return this};Jt.prototype.removeAllListeners=function(t){var r;return t?(r=lr?lr+t:t,this._events[r]&&bf(this,r)):(this._events=new gl,this._eventsCount=0),this};Jt.prototype.off=Jt.prototype.removeListener;Jt.prototype.addListener=Jt.prototype.on;Jt.prefixed=lr;Jt.EventEmitter=Jt;typeof wy<"u"&&(wy.exports=Jt)});var CA=ae((S8,$A)=>{"use strict";$A.exports=(e,t)=>(t=t||(()=>{}),e.then(r=>new Promise(n=>{n(t())}).then(()=>r),r=>new Promise(n=>{n(t())}).then(()=>{throw r})))});var NA=ae((E8,xf)=>{"use strict";var LL=CA(),wf=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},PA=(e,t,r)=>new Promise((n,i)=>{if(typeof t!="number"||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0){n(e);return}let s=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(c){i(c)}return}let o=typeof r=="string"?r:`Promise timed out after ${t} milliseconds`,a=r instanceof Error?r:new wf(o);typeof e.cancel=="function"&&e.cancel(),i(a)},t);LL(e.then(n,i),()=>{clearTimeout(s)})});xf.exports=PA;xf.exports.default=PA;xf.exports.TimeoutError=wf});var RA=ae(xy=>{"use strict";Object.defineProperty(xy,"__esModule",{value:!0});function UL(e,t,r){let n=0,i=e.length;for(;i>0;){let s=i/2|0,o=n+s;r(e[o],t)<=0?(n=++o,i-=s+1):i=s}return n}xy.default=UL});var MA=ae(Sy=>{"use strict";Object.defineProperty(Sy,"__esModule",{value:!0});var FL=RA(),Iy=class{constructor(){this._queue=[]}enqueue(t,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:t};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let i=FL.default(this._queue,n,(s,o)=>o.priority-s.priority);this._queue.splice(i,0,n)}dequeue(){let t=this._queue.shift();return t?.run}filter(t){return this._queue.filter(r=>r.priority===t.priority).map(r=>r.run)}get size(){return this._queue.length}};Sy.default=Iy});var Sf=ae(ky=>{"use strict";Object.defineProperty(ky,"__esModule",{value:!0});var BL=OA(),jA=NA(),VL=MA(),If=()=>{},ZL=new jA.TimeoutError,Ey=class extends BL{constructor(t){var r,n,i,s;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=If,this._resolveIdle=If,t=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:VL.default},t),!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=t.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(i=t.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof t.interval})`);this._carryoverConcurrencyCount=t.carryoverConcurrencyCount,this._isIntervalIgnored=t.intervalCap===1/0||t.interval===0,this._intervalCap=t.intervalCap,this._interval=t.interval,this._queue=new t.queueClass,this._queueClass=t.queueClass,this.concurrency=t.concurrency,this._timeout=t.timeout,this._throwOnTimeout=t.throwOnTimeout===!0,this._isPaused=t.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=If,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=If,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let t=Date.now();if(this._intervalId===void 0){let r=this._intervalEnd-t;if(r<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},r)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let t=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),t&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this._concurrency=t,this._processQueue()}async add(t,r={}){return new Promise((n,i)=>{let s=async()=>{this._pendingCount++,this._intervalCount++;try{let o=this._timeout===void 0&&r.timeout===void 0?t():jA.default(Promise.resolve(t()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&i(ZL)});n(await o)}catch(o){i(o)}this._next()};this._queue.enqueue(s,r),this._tryToStartAnother(),this.emit("add")})}async addAll(t,r){return Promise.all(t.map(async n=>this.add(n,r)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(t=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),t()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(t=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),t()}})}get size(){return this._queue.size}sizeBy(t){return this._queue.filter(t).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(t){this._timeout=t}};ky.default=Ey});var yl=ae((P8,DA)=>{"use strict";var KL="2.0.0",qL=Number.MAX_SAFE_INTEGER||9007199254740991,HL=16,WL=250,JL=["major","premajor","minor","preminor","patch","prepatch","prerelease"];DA.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:HL,MAX_SAFE_BUILD_LENGTH:WL,MAX_SAFE_INTEGER:qL,RELEASE_TYPES:JL,SEMVER_SPEC_VERSION:KL,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var vl=ae((N8,zA)=>{"use strict";var XL=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};zA.exports=XL});var dc=ae((ri,LA)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Oy,MAX_SAFE_BUILD_LENGTH:YL,MAX_LENGTH:QL}=yl(),eU=vl();ri=LA.exports={};var tU=ri.re=[],rU=ri.safeRe=[],Y=ri.src=[],nU=ri.safeSrc=[],Q=ri.t={},iU=0,$y="[a-zA-Z0-9-]",sU=[["\\s",1],["\\d",QL],[$y,YL]],oU=e=>{for(let[t,r]of sU)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},we=(e,t,r)=>{let n=oU(t),i=iU++;eU(e,i,t),Q[e]=i,Y[i]=t,nU[i]=n,tU[i]=new RegExp(t,r?"g":void 0),rU[i]=new RegExp(n,r?"g":void 0)};we("NUMERICIDENTIFIER","0|[1-9]\\d*");we("NUMERICIDENTIFIERLOOSE","\\d+");we("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${$y}*`);we("MAINVERSION",`(${Y[Q.NUMERICIDENTIFIER]})\\.(${Y[Q.NUMERICIDENTIFIER]})\\.(${Y[Q.NUMERICIDENTIFIER]})`);we("MAINVERSIONLOOSE",`(${Y[Q.NUMERICIDENTIFIERLOOSE]})\\.(${Y[Q.NUMERICIDENTIFIERLOOSE]})\\.(${Y[Q.NUMERICIDENTIFIERLOOSE]})`);we("PRERELEASEIDENTIFIER",`(?:${Y[Q.NONNUMERICIDENTIFIER]}|${Y[Q.NUMERICIDENTIFIER]})`);we("PRERELEASEIDENTIFIERLOOSE",`(?:${Y[Q.NONNUMERICIDENTIFIER]}|${Y[Q.NUMERICIDENTIFIERLOOSE]})`);we("PRERELEASE",`(?:-(${Y[Q.PRERELEASEIDENTIFIER]}(?:\\.${Y[Q.PRERELEASEIDENTIFIER]})*))`);we("PRERELEASELOOSE",`(?:-?(${Y[Q.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${Y[Q.PRERELEASEIDENTIFIERLOOSE]})*))`);we("BUILDIDENTIFIER",`${$y}+`);we("BUILD",`(?:\\+(${Y[Q.BUILDIDENTIFIER]}(?:\\.${Y[Q.BUILDIDENTIFIER]})*))`);we("FULLPLAIN",`v?${Y[Q.MAINVERSION]}${Y[Q.PRERELEASE]}?${Y[Q.BUILD]}?`);we("FULL",`^${Y[Q.FULLPLAIN]}$`);we("LOOSEPLAIN",`[v=\\s]*${Y[Q.MAINVERSIONLOOSE]}${Y[Q.PRERELEASELOOSE]}?${Y[Q.BUILD]}?`);we("LOOSE",`^${Y[Q.LOOSEPLAIN]}$`);we("GTLT","((?:<|>)?=?)");we("XRANGEIDENTIFIERLOOSE",`${Y[Q.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);we("XRANGEIDENTIFIER",`${Y[Q.NUMERICIDENTIFIER]}|x|X|\\*`);we("XRANGEPLAIN",`[v=\\s]*(${Y[Q.XRANGEIDENTIFIER]})(?:\\.(${Y[Q.XRANGEIDENTIFIER]})(?:\\.(${Y[Q.XRANGEIDENTIFIER]})(?:${Y[Q.PRERELEASE]})?${Y[Q.BUILD]}?)?)?`);we("XRANGEPLAINLOOSE",`[v=\\s]*(${Y[Q.XRANGEIDENTIFIERLOOSE]})(?:\\.(${Y[Q.XRANGEIDENTIFIERLOOSE]})(?:\\.(${Y[Q.XRANGEIDENTIFIERLOOSE]})(?:${Y[Q.PRERELEASELOOSE]})?${Y[Q.BUILD]}?)?)?`);we("XRANGE",`^${Y[Q.GTLT]}\\s*${Y[Q.XRANGEPLAIN]}$`);we("XRANGELOOSE",`^${Y[Q.GTLT]}\\s*${Y[Q.XRANGEPLAINLOOSE]}$`);we("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Oy}})(?:\\.(\\d{1,${Oy}}))?(?:\\.(\\d{1,${Oy}}))?`);we("COERCE",`${Y[Q.COERCEPLAIN]}(?:$|[^\\d])`);we("COERCEFULL",Y[Q.COERCEPLAIN]+`(?:${Y[Q.PRERELEASE]})?(?:${Y[Q.BUILD]})?(?:$|[^\\d])`);we("COERCERTL",Y[Q.COERCE],!0);we("COERCERTLFULL",Y[Q.COERCEFULL],!0);we("LONETILDE","(?:~>?)");we("TILDETRIM",`(\\s*)${Y[Q.LONETILDE]}\\s+`,!0);ri.tildeTrimReplace="$1~";we("TILDE",`^${Y[Q.LONETILDE]}${Y[Q.XRANGEPLAIN]}$`);we("TILDELOOSE",`^${Y[Q.LONETILDE]}${Y[Q.XRANGEPLAINLOOSE]}$`);we("LONECARET","(?:\\^)");we("CARETTRIM",`(\\s*)${Y[Q.LONECARET]}\\s+`,!0);ri.caretTrimReplace="$1^";we("CARET",`^${Y[Q.LONECARET]}${Y[Q.XRANGEPLAIN]}$`);we("CARETLOOSE",`^${Y[Q.LONECARET]}${Y[Q.XRANGEPLAINLOOSE]}$`);we("COMPARATORLOOSE",`^${Y[Q.GTLT]}\\s*(${Y[Q.LOOSEPLAIN]})$|^$`);we("COMPARATOR",`^${Y[Q.GTLT]}\\s*(${Y[Q.FULLPLAIN]})$|^$`);we("COMPARATORTRIM",`(\\s*)${Y[Q.GTLT]}\\s*(${Y[Q.LOOSEPLAIN]}|${Y[Q.XRANGEPLAIN]})`,!0);ri.comparatorTrimReplace="$1$2$3";we("HYPHENRANGE",`^\\s*(${Y[Q.XRANGEPLAIN]})\\s+-\\s+(${Y[Q.XRANGEPLAIN]})\\s*$`);we("HYPHENRANGELOOSE",`^\\s*(${Y[Q.XRANGEPLAINLOOSE]})\\s+-\\s+(${Y[Q.XRANGEPLAINLOOSE]})\\s*$`);we("STAR","(<|>)?=?\\s*\\*");we("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");we("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var kf=ae((R8,UA)=>{"use strict";var aU=Object.freeze({loose:!0}),cU=Object.freeze({}),uU=e=>e?typeof e!="object"?aU:e:cU;UA.exports=uU});var Cy=ae((M8,VA)=>{"use strict";var FA=/^[0-9]+$/,BA=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=FA.test(e),n=FA.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1},lU=(e,t)=>BA(t,e);VA.exports={compareIdentifiers:BA,rcompareIdentifiers:lU}});var Xt=ae((j8,GA)=>{"use strict";var Af=vl(),{MAX_LENGTH:ZA,MAX_SAFE_INTEGER:Tf}=yl(),{safeRe:Of,t:$f}=dc(),pU=kf(),{compareIdentifiers:Py}=Cy(),Ny=class e{constructor(t,r){if(r=pU(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>ZA)throw new TypeError(`version is longer than ${ZA} characters`);Af("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?Of[$f.LOOSE]:Of[$f.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Tf||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Tf||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Tf||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let s=+i;if(s>=0&&s<Tf)return s}return i}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(Af("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if(typeof t=="string"&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],i=t.prerelease[r];if(Af("prerelease compare",r,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return Py(n,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],i=t.build[r];if(Af("build compare",r,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return Py(n,i)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let i=`-${r}`.match(this.options.loose?Of[$f.PRERELEASELOOSE]:Of[$f.PRERELEASE]);if(!i||i[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(r){let s=[r,i];n===!1&&(s=[r]),Py(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};GA.exports=Ny});var jo=ae((D8,qA)=>{"use strict";var KA=Xt(),dU=(e,t,r=!1)=>{if(e instanceof KA)return e;try{return new KA(e,t)}catch(n){if(!r)return null;throw n}};qA.exports=dU});var WA=ae((z8,HA)=>{"use strict";var fU=jo(),mU=(e,t)=>{let r=fU(e,t);return r?r.version:null};HA.exports=mU});var XA=ae((L8,JA)=>{"use strict";var hU=jo(),gU=(e,t)=>{let r=hU(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};JA.exports=gU});var eT=ae((U8,QA)=>{"use strict";var YA=Xt(),_U=(e,t,r,n,i)=>{typeof r=="string"&&(i=n,n=r,r=void 0);try{return new YA(e instanceof YA?e.version:e,r).inc(t,n,i).version}catch{return null}};QA.exports=_U});var nT=ae((F8,rT)=>{"use strict";var tT=jo(),yU=(e,t)=>{let r=tT(e,null,!0),n=tT(t,null,!0),i=r.compare(n);if(i===0)return null;let s=i>0,o=s?r:n,a=s?n:r,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let l=c?"pre":"";return r.major!==n.major?l+"major":r.minor!==n.minor?l+"minor":r.patch!==n.patch?l+"patch":"prerelease"};rT.exports=yU});var sT=ae((B8,iT)=>{"use strict";var vU=Xt(),bU=(e,t)=>new vU(e,t).major;iT.exports=bU});var aT=ae((V8,oT)=>{"use strict";var wU=Xt(),xU=(e,t)=>new wU(e,t).minor;oT.exports=xU});var uT=ae((Z8,cT)=>{"use strict";var IU=Xt(),SU=(e,t)=>new IU(e,t).patch;cT.exports=SU});var pT=ae((G8,lT)=>{"use strict";var EU=jo(),kU=(e,t)=>{let r=EU(e,t);return r&&r.prerelease.length?r.prerelease:null};lT.exports=kU});var on=ae((K8,fT)=>{"use strict";var dT=Xt(),AU=(e,t,r)=>new dT(e,r).compare(new dT(t,r));fT.exports=AU});var hT=ae((q8,mT)=>{"use strict";var TU=on(),OU=(e,t,r)=>TU(t,e,r);mT.exports=OU});var _T=ae((H8,gT)=>{"use strict";var $U=on(),CU=(e,t)=>$U(e,t,!0);gT.exports=CU});var Cf=ae((W8,vT)=>{"use strict";var yT=Xt(),PU=(e,t,r)=>{let n=new yT(e,r),i=new yT(t,r);return n.compare(i)||n.compareBuild(i)};vT.exports=PU});var wT=ae((J8,bT)=>{"use strict";var NU=Cf(),RU=(e,t)=>e.sort((r,n)=>NU(r,n,t));bT.exports=RU});var IT=ae((X8,xT)=>{"use strict";var MU=Cf(),jU=(e,t)=>e.sort((r,n)=>MU(n,r,t));xT.exports=jU});var bl=ae((Y8,ST)=>{"use strict";var DU=on(),zU=(e,t,r)=>DU(e,t,r)>0;ST.exports=zU});var Pf=ae((Q8,ET)=>{"use strict";var LU=on(),UU=(e,t,r)=>LU(e,t,r)<0;ET.exports=UU});var Ry=ae((eJ,kT)=>{"use strict";var FU=on(),BU=(e,t,r)=>FU(e,t,r)===0;kT.exports=BU});var My=ae((tJ,AT)=>{"use strict";var VU=on(),ZU=(e,t,r)=>VU(e,t,r)!==0;AT.exports=ZU});var Nf=ae((rJ,TT)=>{"use strict";var GU=on(),KU=(e,t,r)=>GU(e,t,r)>=0;TT.exports=KU});var Rf=ae((nJ,OT)=>{"use strict";var qU=on(),HU=(e,t,r)=>qU(e,t,r)<=0;OT.exports=HU});var jy=ae((iJ,$T)=>{"use strict";var WU=Ry(),JU=My(),XU=bl(),YU=Nf(),QU=Pf(),e4=Rf(),t4=(e,t,r,n)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return WU(e,r,n);case"!=":return JU(e,r,n);case">":return XU(e,r,n);case">=":return YU(e,r,n);case"<":return QU(e,r,n);case"<=":return e4(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};$T.exports=t4});var PT=ae((sJ,CT)=>{"use strict";var r4=Xt(),n4=jo(),{safeRe:Mf,t:jf}=dc(),i4=(e,t)=>{if(e instanceof r4)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?Mf[jf.COERCEFULL]:Mf[jf.COERCE]);else{let c=t.includePrerelease?Mf[jf.COERCERTLFULL]:Mf[jf.COERCERTL],u;for(;(u=c.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),c.lastIndex=u.index+u[1].length+u[2].length;c.lastIndex=-1}if(r===null)return null;let n=r[2],i=r[3]||"0",s=r[4]||"0",o=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return n4(`${n}.${i}.${s}${o}${a}`,t)};CT.exports=i4});var RT=ae((oJ,NT)=>{"use strict";var Dy=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(t,r)}return this}};NT.exports=Dy});var an=ae((aJ,zT)=>{"use strict";var s4=/\s+/g,zy=class e{constructor(t,r){if(r=a4(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof Ly)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(s4," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(i=>!jT(i[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&m4(i[0])){this.set=[i];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){t>0&&(this.formatted+="||");let r=this.set[t];for(let n=0;n<r.length;n++)n>0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let n=((this.options.includePrerelease&&d4)|(this.options.loose&&f4))+":"+t,i=MT.get(n);if(i)return i;let s=this.options.loose,o=s?pr[Yt.HYPHENRANGELOOSE]:pr[Yt.HYPHENRANGE];t=t.replace(o,S4(this.options.includePrerelease)),rt("hyphen replace",t),t=t.replace(pr[Yt.COMPARATORTRIM],u4),rt("comparator trim",t),t=t.replace(pr[Yt.TILDETRIM],l4),rt("tilde trim",t),t=t.replace(pr[Yt.CARETTRIM],p4),rt("caret trim",t);let a=t.split(" ").map(p=>h4(p,this.options)).join(" ").split(/\s+/).map(p=>I4(p,this.options));s&&(a=a.filter(p=>(rt("loose invalid filter",p,this.options),!!p.match(pr[Yt.COMPARATORLOOSE])))),rt("range list",a);let c=new Map,u=a.map(p=>new Ly(p,this.options));for(let p of u){if(jT(p))return[p];c.set(p.value,p)}c.size>1&&c.has("")&&c.delete("");let l=[...c.values()];return MT.set(n,l),l}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>DT(n,r)&&t.set.some(i=>DT(i,r)&&n.every(s=>i.every(o=>s.intersects(o,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new c4(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(E4(this.set[r],t,this.options))return!0;return!1}};zT.exports=zy;var o4=RT(),MT=new o4,a4=kf(),Ly=wl(),rt=vl(),c4=Xt(),{safeRe:pr,t:Yt,comparatorTrimReplace:u4,tildeTrimReplace:l4,caretTrimReplace:p4}=dc(),{FLAG_INCLUDE_PRERELEASE:d4,FLAG_LOOSE:f4}=yl(),jT=e=>e.value==="<0.0.0-0",m4=e=>e.value==="",DT=(e,t)=>{let r=!0,n=e.slice(),i=n.pop();for(;r&&n.length;)r=n.every(s=>i.intersects(s,t)),i=n.pop();return r},h4=(e,t)=>(e=e.replace(pr[Yt.BUILD],""),rt("comp",e,t),e=y4(e,t),rt("caret",e),e=g4(e,t),rt("tildes",e),e=b4(e,t),rt("xrange",e),e=x4(e,t),rt("stars",e),e),dr=e=>!e||e.toLowerCase()==="x"||e==="*",g4=(e,t)=>e.trim().split(/\s+/).map(r=>_4(r,t)).join(" "),_4=(e,t)=>{let r=t.loose?pr[Yt.TILDELOOSE]:pr[Yt.TILDE];return e.replace(r,(n,i,s,o,a)=>{rt("tilde",e,n,i,s,o,a);let c;return dr(i)?c="":dr(s)?c=`>=${i}.0.0 <${+i+1}.0.0-0`:dr(o)?c=`>=${i}.${s}.0 <${i}.${+s+1}.0-0`:a?(rt("replaceTilde pr",a),c=`>=${i}.${s}.${o}-${a} <${i}.${+s+1}.0-0`):c=`>=${i}.${s}.${o} <${i}.${+s+1}.0-0`,rt("tilde return",c),c})},y4=(e,t)=>e.trim().split(/\s+/).map(r=>v4(r,t)).join(" "),v4=(e,t)=>{rt("caret",e,t);let r=t.loose?pr[Yt.CARETLOOSE]:pr[Yt.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(i,s,o,a,c)=>{rt("caret",e,i,s,o,a,c);let u;return dr(s)?u="":dr(o)?u=`>=${s}.0.0${n} <${+s+1}.0.0-0`:dr(a)?s==="0"?u=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:c?(rt("replaceCaret pr",c),s==="0"?o==="0"?u=`>=${s}.${o}.${a}-${c} <${s}.${o}.${+a+1}-0`:u=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${a}-${c} <${+s+1}.0.0-0`):(rt("no pr"),s==="0"?o==="0"?u=`>=${s}.${o}.${a}${n} <${s}.${o}.${+a+1}-0`:u=`>=${s}.${o}.${a}${n} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),rt("caret return",u),u})},b4=(e,t)=>(rt("replaceXRanges",e,t),e.split(/\s+/).map(r=>w4(r,t)).join(" ")),w4=(e,t)=>{e=e.trim();let r=t.loose?pr[Yt.XRANGELOOSE]:pr[Yt.XRANGE];return e.replace(r,(n,i,s,o,a,c)=>{rt("xRange",e,n,i,s,o,a,c);let u=dr(s),l=u||dr(o),p=l||dr(a),f=p;return i==="="&&f&&(i=""),c=t.includePrerelease?"-0":"",u?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&f?(l&&(o=0),a=0,i===">"?(i=">=",l?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",l?s=+s+1:o=+o+1),i==="<"&&(c="-0"),n=`${i+s}.${o}.${a}${c}`):l?n=`>=${s}.0.0${c} <${+s+1}.0.0-0`:p&&(n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),rt("xRange return",n),n})},x4=(e,t)=>(rt("replaceStars",e,t),e.trim().replace(pr[Yt.STAR],"")),I4=(e,t)=>(rt("replaceGTE0",e,t),e.trim().replace(pr[t.includePrerelease?Yt.GTE0PRE:Yt.GTE0],"")),S4=e=>(t,r,n,i,s,o,a,c,u,l,p,f)=>(dr(n)?r="":dr(i)?r=`>=${n}.0.0${e?"-0":""}`:dr(s)?r=`>=${n}.${i}.0${e?"-0":""}`:o?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,dr(u)?c="":dr(l)?c=`<${+u+1}.0.0-0`:dr(p)?c=`<${u}.${+l+1}.0-0`:f?c=`<=${u}.${l}.${p}-${f}`:e?c=`<${u}.${l}.${+p+1}-0`:c=`<=${c}`,`${r} ${c}`.trim()),E4=(e,t,r)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let n=0;n<e.length;n++)if(rt(e[n].semver),e[n].semver!==Ly.ANY&&e[n].semver.prerelease.length>0){let i=e[n].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}return!1}return!0}});var wl=ae((cJ,ZT)=>{"use strict";var xl=Symbol("SemVer ANY"),By=class e{static get ANY(){return xl}constructor(t,r){if(r=LT(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Fy("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===xl?this.value="":this.value=this.operator+this.semver.version,Fy("comp",this)}parse(t){let r=this.options.loose?UT[FT.COMPARATORLOOSE]:UT[FT.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new BT(n[2],this.options.loose):this.semver=xl}toString(){return this.value}test(t){if(Fy("Comparator.test",t,this.options.loose),this.semver===xl||t===xl)return!0;if(typeof t=="string")try{t=new BT(t,this.options)}catch{return!1}return Uy(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new VT(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new VT(this.value,r).test(t.semver):(r=LT(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||Uy(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||Uy(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};ZT.exports=By;var LT=kf(),{safeRe:UT,t:FT}=dc(),Uy=jy(),Fy=vl(),BT=Xt(),VT=an()});var Il=ae((uJ,GT)=>{"use strict";var k4=an(),A4=(e,t,r)=>{try{t=new k4(t,r)}catch{return!1}return t.test(e)};GT.exports=A4});var qT=ae((lJ,KT)=>{"use strict";var T4=an(),O4=(e,t)=>new T4(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));KT.exports=O4});var WT=ae((pJ,HT)=>{"use strict";var $4=Xt(),C4=an(),P4=(e,t,r)=>{let n=null,i=null,s=null;try{s=new C4(t,r)}catch{return null}return e.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new $4(n,r))}),n};HT.exports=P4});var XT=ae((dJ,JT)=>{"use strict";var N4=Xt(),R4=an(),M4=(e,t,r)=>{let n=null,i=null,s=null;try{s=new R4(t,r)}catch{return null}return e.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new N4(n,r))}),n};JT.exports=M4});var eO=ae((fJ,QT)=>{"use strict";var Vy=Xt(),j4=an(),YT=bl(),D4=(e,t)=>{e=new j4(e,t);let r=new Vy("0.0.0");if(e.test(r)||(r=new Vy("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n<e.set.length;++n){let i=e.set[n],s=null;i.forEach(o=>{let a=new Vy(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||YT(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!r||YT(r,s))&&(r=s)}return r&&e.test(r)?r:null};QT.exports=D4});var rO=ae((mJ,tO)=>{"use strict";var z4=an(),L4=(e,t)=>{try{return new z4(e,t).range||"*"}catch{return null}};tO.exports=L4});var Df=ae((hJ,oO)=>{"use strict";var U4=Xt(),sO=wl(),{ANY:F4}=sO,B4=an(),V4=Il(),nO=bl(),iO=Pf(),Z4=Rf(),G4=Nf(),K4=(e,t,r,n)=>{e=new U4(e,n),t=new B4(t,n);let i,s,o,a,c;switch(r){case">":i=nO,s=Z4,o=iO,a=">",c=">=";break;case"<":i=iO,s=G4,o=nO,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(V4(e,t,n))return!1;for(let u=0;u<t.set.length;++u){let l=t.set[u],p=null,f=null;if(l.forEach(d=>{d.semver===F4&&(d=new sO(">=0.0.0")),p=p||d,f=f||d,i(d.semver,p.semver,n)?p=d:o(d.semver,f.semver,n)&&(f=d)}),p.operator===a||p.operator===c||(!f.operator||f.operator===a)&&s(e,f.semver))return!1;if(f.operator===c&&o(e,f.semver))return!1}return!0};oO.exports=K4});var cO=ae((gJ,aO)=>{"use strict";var q4=Df(),H4=(e,t,r)=>q4(e,t,">",r);aO.exports=H4});var lO=ae((_J,uO)=>{"use strict";var W4=Df(),J4=(e,t,r)=>W4(e,t,"<",r);uO.exports=J4});var fO=ae((yJ,dO)=>{"use strict";var pO=an(),X4=(e,t,r)=>(e=new pO(e,r),t=new pO(t,r),e.intersects(t,r));dO.exports=X4});var hO=ae((vJ,mO)=>{"use strict";var Y4=Il(),Q4=on();mO.exports=(e,t,r)=>{let n=[],i=null,s=null,o=e.sort((l,p)=>Q4(l,p,r));for(let l of o)Y4(l,t,r)?(s=l,i||(i=l)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[l,p]of n)l===p?a.push(l):!p&&l===o[0]?a.push("*"):p?l===o[0]?a.push(`<=${p}`):a.push(`${l} - ${p}`):a.push(`>=${l}`);let c=a.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return c.length<u.length?c:t}});var wO=ae((bJ,bO)=>{"use strict";var gO=an(),Gy=wl(),{ANY:Zy}=Gy,Sl=Il(),Ky=on(),e2=(e,t,r={})=>{if(e===t)return!0;e=new gO(e,r),t=new gO(t,r);let n=!1;e:for(let i of e.set){for(let s of t.set){let o=r2(i,s,r);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},t2=[new Gy(">=0.0.0-0")],_O=[new Gy(">=0.0.0")],r2=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Zy){if(t.length===1&&t[0].semver===Zy)return!0;r.includePrerelease?e=t2:e=_O}if(t.length===1&&t[0].semver===Zy){if(r.includePrerelease)return!0;t=_O}let n=new Set,i,s;for(let d of e)d.operator===">"||d.operator===">="?i=yO(i,d,r):d.operator==="<"||d.operator==="<="?s=vO(s,d,r):n.add(d.semver);if(n.size>1)return null;let o;if(i&&s){if(o=Ky(i.semver,s.semver,r),o>0)return null;if(o===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let d of n){if(i&&!Sl(d,String(i),r)||s&&!Sl(d,String(s),r))return null;for(let m of t)if(!Sl(d,String(m),r))return!1;return!0}let a,c,u,l,p=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=i&&!r.includePrerelease&&i.semver.prerelease.length?i.semver:!1;p&&p.prerelease.length===1&&s.operator==="<"&&p.prerelease[0]===0&&(p=!1);for(let d of t){if(l=l||d.operator===">"||d.operator===">=",u=u||d.operator==="<"||d.operator==="<=",i){if(f&&d.semver.prerelease&&d.semver.prerelease.length&&d.semver.major===f.major&&d.semver.minor===f.minor&&d.semver.patch===f.patch&&(f=!1),d.operator===">"||d.operator===">="){if(a=yO(i,d,r),a===d&&a!==i)return!1}else if(i.operator===">="&&!Sl(i.semver,String(d),r))return!1}if(s){if(p&&d.semver.prerelease&&d.semver.prerelease.length&&d.semver.major===p.major&&d.semver.minor===p.minor&&d.semver.patch===p.patch&&(p=!1),d.operator==="<"||d.operator==="<="){if(c=vO(s,d,r),c===d&&c!==s)return!1}else if(s.operator==="<="&&!Sl(s.semver,String(d),r))return!1}if(!d.operator&&(s||i)&&o!==0)return!1}return!(i&&u&&!s&&o!==0||s&&l&&!i&&o!==0||f||p)},yO=(e,t,r)=>{if(!e)return t;let n=Ky(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},vO=(e,t,r)=>{if(!e)return t;let n=Ky(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};bO.exports=e2});var EO=ae((wJ,SO)=>{"use strict";var qy=dc(),xO=yl(),n2=Xt(),IO=Cy(),i2=jo(),s2=WA(),o2=XA(),a2=eT(),c2=nT(),u2=sT(),l2=aT(),p2=uT(),d2=pT(),f2=on(),m2=hT(),h2=_T(),g2=Cf(),_2=wT(),y2=IT(),v2=bl(),b2=Pf(),w2=Ry(),x2=My(),I2=Nf(),S2=Rf(),E2=jy(),k2=PT(),A2=wl(),T2=an(),O2=Il(),$2=qT(),C2=WT(),P2=XT(),N2=eO(),R2=rO(),M2=Df(),j2=cO(),D2=lO(),z2=fO(),L2=hO(),U2=wO();SO.exports={parse:i2,valid:s2,clean:o2,inc:a2,diff:c2,major:u2,minor:l2,patch:p2,prerelease:d2,compare:f2,rcompare:m2,compareLoose:h2,compareBuild:g2,sort:_2,rsort:y2,gt:v2,lt:b2,eq:w2,neq:x2,gte:I2,lte:S2,cmp:E2,coerce:k2,Comparator:A2,Range:T2,satisfies:O2,toComparators:$2,maxSatisfying:C2,minSatisfying:P2,minVersion:N2,validRange:R2,outside:M2,gtr:j2,ltr:D2,intersects:z2,simplifyRange:L2,subset:U2,SemVer:n2,re:qy.re,src:qy.src,tokens:qy.t,SEMVER_SPEC_VERSION:xO.SEMVER_SPEC_VERSION,RELEASE_TYPES:xO.RELEASE_TYPES,compareIdentifiers:IO.compareIdentifiers,rcompareIdentifiers:IO.rcompareIdentifiers}});var GO=ae((d7,ZO)=>{"use strict";var BO=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,VO=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`;function uF(){let e=new Map,t={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(let[r,n]of Object.entries(t)){for(let[i,s]of Object.entries(n))t[i]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[i]=t[i],e.set(s[0],s[1]);Object.defineProperty(t,r,{value:n,enumerable:!1})}return Object.defineProperty(t,"codes",{value:e,enumerable:!1}),t.color.close="\x1B[39m",t.bgColor.close="\x1B[49m",t.color.ansi256=BO(),t.color.ansi16m=VO(),t.bgColor.ansi256=BO(10),t.bgColor.ansi16m=VO(10),Object.defineProperties(t,{rgbToAnsi256:{value:(r,n,i)=>r===n&&n===i?r<8?16:r>248?231:Math.round((r-8)/247*24)+232:16+36*Math.round(r/255*5)+6*Math.round(n/255*5)+Math.round(i/255*5),enumerable:!1},hexToRgb:{value:r=>{let n=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(r.toString(16));if(!n)return[0,0,0];let{colorString:i}=n.groups;i.length===3&&(i=i.split("").map(o=>o+o).join(""));let s=Number.parseInt(i,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:r=>t.rgbToAnsi256(...t.hexToRgb(r)),enumerable:!1}}),t}Object.defineProperty(ZO,"exports",{enumerable:!0,get:uF})});var VN=ae(Ih=>{"use strict";Ih.byteLength=BZ;Ih.toByteArray=ZZ;Ih.fromByteArray=qZ;var hi=[],_n=[],FZ=typeof Uint8Array<"u"?Uint8Array:Array,k0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(ya=0,FN=k0.length;ya<FN;++ya)hi[ya]=k0[ya],_n[k0.charCodeAt(ya)]=ya;var ya,FN;_n[45]=62;_n[95]=63;function BN(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function BZ(e){var t=BN(e),r=t[0],n=t[1];return(r+n)*3/4-n}function VZ(e,t,r){return(t+r)*3/4-r}function ZZ(e){var t,r=BN(e),n=r[0],i=r[1],s=new FZ(VZ(e,n,i)),o=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)t=_n[e.charCodeAt(c)]<<18|_n[e.charCodeAt(c+1)]<<12|_n[e.charCodeAt(c+2)]<<6|_n[e.charCodeAt(c+3)],s[o++]=t>>16&255,s[o++]=t>>8&255,s[o++]=t&255;return i===2&&(t=_n[e.charCodeAt(c)]<<2|_n[e.charCodeAt(c+1)]>>4,s[o++]=t&255),i===1&&(t=_n[e.charCodeAt(c)]<<10|_n[e.charCodeAt(c+1)]<<4|_n[e.charCodeAt(c+2)]>>2,s[o++]=t>>8&255,s[o++]=t&255),s}function GZ(e){return hi[e>>18&63]+hi[e>>12&63]+hi[e>>6&63]+hi[e&63]}function KZ(e,t,r){for(var n,i=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),i.push(GZ(n));return i.join("")}function qZ(e){for(var t,r=e.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(KZ(e,o,o+s>a?a:o+s));return n===1?(t=e[r-1],i.push(hi[t>>2]+hi[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(hi[t>>10]+hi[t>>4&63]+hi[t<<2&63]+"=")),i.join("")}});var Pi=class extends Error{lc_error_code;constructor(e,t){let r=e??"";t?.lc_error_code&&(r=`${r}
3
-
4
- Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/
5
- `),super(r),this.lc_error_code=t?.lc_error_code}},A_=class extends Pi{get is_bubble_up(){return!0}},T_=class extends Pi{constructor(e,t){super(e,t),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},$o=class extends Pi{constructor(e,t){super(e,t),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},Ni=class extends A_{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name="GraphInterrupt",this.interrupts=e??[]}static get unminifiable_name(){return"GraphInterrupt"}},Vd=class extends Ni{constructor(e,t){super([{value:e}],t),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},Zd=class extends A_{command;constructor(e){super(),this.name="ParentCommand",this.command=e}static get unminifiable_name(){return"ParentCommand"}};function O_(e){return e!==void 0&&e.name===Zd.unminifiable_name}function Co(e){return e!==void 0&&e.is_bubble_up===!0}function Ri(e){return e!==void 0&&[Ni.unminifiable_name,Vd.unminifiable_name].includes(e.name)}var Gd=class extends Pi{constructor(e,t){super(e,t),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},Ve=class extends Pi{constructor(e,t){super(e,t),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},De=class extends Pi{constructor(e,t){super(e,t),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}};var $_=class extends Pi{constructor(e,t){super(e,t),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};var ol=class extends Pi{constructor(e,t){super(e,t),this.name="StateGraphInputError",this.message="Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema."}static get unminifiable_name(){return"StateGraphInputError"}};var QE=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Oz(e){return typeof e=="string"&&QE.test(e)}var En=Oz;function $z(e){if(!En(e))throw TypeError("Invalid UUID");var t,r=new Uint8Array(16);return r[0]=(t=parseInt(e.slice(0,8),16))>>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=t&255,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=t&255,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=t&255,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=t&255,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=t&255,r}var Kd=$z;var Vt=[];for(qd=0;qd<256;++qd)Vt.push((qd+256).toString(16).slice(1));var qd;function rn(e,t=0){return(Vt[e[t+0]]+Vt[e[t+1]]+Vt[e[t+2]]+Vt[e[t+3]]+"-"+Vt[e[t+4]]+Vt[e[t+5]]+"-"+Vt[e[t+6]]+Vt[e[t+7]]+"-"+Vt[e[t+8]]+Vt[e[t+9]]+"-"+Vt[e[t+10]]+Vt[e[t+11]]+Vt[e[t+12]]+Vt[e[t+13]]+Vt[e[t+14]]+Vt[e[t+15]]).toLowerCase()}var Hd,Cz=new Uint8Array(16);function Po(){if(!Hd&&(Hd=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Hd))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Hd(Cz)}var C_,Wd,P_=0,N_=0;function Pz(e,t,r){var n=t&&r||0,i=t||new Array(16);e=e||{};var s=e.node,o=e.clockseq;if(e._v6||(s||(s=C_),o==null&&(o=Wd)),s==null||o==null){var a=e.random||(e.rng||Po)();s==null&&(s=[a[0],a[1],a[2],a[3],a[4],a[5]],!C_&&!e._v6&&(s[0]|=1,C_=s)),o==null&&(o=(a[6]<<8|a[7])&16383,Wd===void 0&&!e._v6&&(Wd=o))}var c=e.msecs!==void 0?e.msecs:Date.now(),u=e.nsecs!==void 0?e.nsecs:N_+1,l=c-P_+(u-N_)/1e4;if(l<0&&e.clockseq===void 0&&(o=o+1&16383),(l<0||c>P_)&&e.nsecs===void 0&&(u=0),u>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");P_=c,N_=u,Wd=o,c+=122192928e5;var p=((c&268435455)*1e4+u)%4294967296;i[n++]=p>>>24&255,i[n++]=p>>>16&255,i[n++]=p>>>8&255,i[n++]=p&255;var f=c/4294967296*1e4&268435455;i[n++]=f>>>8&255,i[n++]=f&255,i[n++]=f>>>24&15|16,i[n++]=f>>>16&255,i[n++]=o>>>8|128,i[n++]=o&255;for(var d=0;d<6;++d)i[n+d]=s[d];return t||rn(i)}var ek=Pz;function R_(e){var t=typeof e=="string"?Kd(e):e,r=Nz(t);return typeof e=="string"?rn(r):r}function Nz(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function Rz(e){e=unescape(encodeURIComponent(e));for(var t=[],r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t}var Mz="6ba7b810-9dad-11d1-80b4-00c04fd430c8",jz="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function M_(e,t,r){function n(i,s,o,a){var c;if(typeof i=="string"&&(i=Rz(i)),typeof s=="string"&&(s=Kd(s)),((c=s)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var u=new Uint8Array(16+i.length);if(u.set(s),u.set(i,s.length),u=r(u),u[6]=u[6]&15|t,u[8]=u[8]&63|128,o){a=a||0;for(var l=0;l<16;++l)o[a+l]=u[l];return o}return rn(u)}try{n.name=e}catch{}return n.DNS=Mz,n.URL=jz,n}var Dz=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),j_={randomUUID:Dz};function zz(e,t,r){if(j_.randomUUID&&!t&&!e)return j_.randomUUID();e=e||{};var n=e.random||(e.rng||Po)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(var i=0;i<16;++i)t[r+i]=n[i];return t}return rn(n)}var Ar=zz;function Lz(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:return t^r^n;case 2:return t&r^t&n^r&n;case 3:return t^r^n}}function D_(e,t){return e<<t|e>>>32-t}function Uz(e){var t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof e=="string"){var n=unescape(encodeURIComponent(e));e=[];for(var i=0;i<n.length;++i)e.push(n.charCodeAt(i))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);for(var s=e.length/4+2,o=Math.ceil(s/16),a=new Array(o),c=0;c<o;++c){for(var u=new Uint32Array(16),l=0;l<16;++l)u[l]=e[c*64+l*4]<<24|e[c*64+l*4+1]<<16|e[c*64+l*4+2]<<8|e[c*64+l*4+3];a[c]=u}a[o-1][14]=(e.length-1)*8/Math.pow(2,32),a[o-1][14]=Math.floor(a[o-1][14]),a[o-1][15]=(e.length-1)*8&4294967295;for(var p=0;p<o;++p){for(var f=new Uint32Array(80),d=0;d<16;++d)f[d]=a[p][d];for(var m=16;m<80;++m)f[m]=D_(f[m-3]^f[m-8]^f[m-14]^f[m-16],1);for(var h=r[0],b=r[1],_=r[2],y=r[3],x=r[4],I=0;I<80;++I){var A=Math.floor(I/20),j=D_(h,5)+Lz(A,b,_,y)+x+t[A]+f[I]>>>0;x=y,y=_,_=D_(b,30)>>>0,b=h,h=j}r[0]=r[0]+h>>>0,r[1]=r[1]+b>>>0,r[2]=r[2]+_>>>0,r[3]=r[3]+y>>>0,r[4]=r[4]+x>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,r[0]&255,r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,r[1]&255,r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,r[2]&255,r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,r[3]&255,r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,r[4]&255]}var tk=Uz;var Fz=M_("v5",80,tk),nn=Fz;function rk(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function nk(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?rk(Object(r),!0).forEach(function(n){Bz(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):rk(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Bz(e,t,r){return(t=Vz(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Vz(e){var t=Zz(e,"string");return typeof t=="symbol"?t:t+""}function Zz(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Jd(e={},t,r=0){var n=ek(nk(nk({},e),{},{_v6:!0}),new Uint8Array(16));if(n=R_(n),t){for(var i=0;i<16;i++)t[r+i]=n[i];return t}return rn(n)}var ik=null,sk=null,kn=0;function Gz(e,t,r){e=e||{};var n=t&&r||0,i=t||new Uint8Array(16),s=e.random||(e.rng||Po)(),o=e.msecs!==void 0?e.msecs:Date.now(),a=e.seq!==void 0?e.seq:null,c=sk,u=ik;return o>kn&&e.msecs===void 0&&(kn=o,a!==null&&(c=null,u=null)),a!==null&&(a>2147483647&&(a=2147483647),c=a>>>19&4095,u=a&524287),(c===null||u===null)&&(c=s[6]&127,c=c<<8|s[7],u=s[8]&63,u=u<<8|s[9],u=u<<5|s[10]>>>3),o+1e4>kn&&a===null?++u>524287&&(u=0,++c>4095&&(c=0,kn++)):kn=o,sk=c,ik=u,i[n++]=kn/1099511627776&255,i[n++]=kn/4294967296&255,i[n++]=kn/16777216&255,i[n++]=kn/65536&255,i[n++]=kn/256&255,i[n++]=kn&255,i[n++]=c>>>4&15|112,i[n++]=c&255,i[n++]=u>>>13&63|128,i[n++]=u>>>5&255,i[n++]=u<<3&255|s[10]&7,i[n++]=s[11],i[n++]=s[12],i[n++]=s[13],i[n++]=s[14],i[n++]=s[15],t||rn(i)}var sn=Gz;function al(e){return Jd({clockseq:e})}function Mi(e,t){let r=t.replace(/-/g,"").match(/.{2}/g).map(n=>parseInt(n,16));return nn(e,new Uint8Array(r))}var cl="__pregel_tasks",z_="__error__",No="__scheduled__",L_="__interrupt__",U_="__resume__";var ak="[...]",Kz="[Circular]",Xd=[],ac=[];function qz(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function ck(e,t,r,n){typeof n>"u"&&(n=qz()),B_(e,"",0,[],void 0,0,n);var i;try{ac.length===0?i=JSON.stringify(e,t,r):i=JSON.stringify(e,Hz(t),r)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Xd.length!==0;){var s=Xd.pop();s.length===4?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return i}function F_(e,t,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:e}),Xd.push([n,r,t,i])):ac.push([t,r,e]):(n[r]=e,Xd.push([n,r,t]))}function B_(e,t,r,n,i,s,o){s+=1;var a;if(typeof e=="object"&&e!==null){for(a=0;a<n.length;a++)if(n[a]===e){F_(Kz,e,t,i);return}if(typeof o.depthLimit<"u"&&s>o.depthLimit){F_(ak,e,t,i);return}if(typeof o.edgesLimit<"u"&&r+1>o.edgesLimit){F_(ak,e,t,i);return}if(n.push(e),Array.isArray(e))for(a=0;a<e.length;a++)B_(e[a],a,a,n,e,s,o);else{var c=Object.keys(e);for(a=0;a<c.length;a++){var u=c[a];B_(e[u],u,a,n,e,s,o)}}n.pop()}}function Hz(e){return e=typeof e<"u"?e:function(t,r){return r},function(t,r){if(ac.length>0)for(var n=0;n<ac.length;n++){var i=ac[n];if(i[1]===t&&i[0]===r){r=i[2],ac.splice(n,1);break}}return e.call(this,t,r)}}var yk=Cs(lk(),1),vk=Cs(_k(),1);function bk(e,t){return t?.[e]||(0,yk.default)(e)}function wk(e,t){return t?.[e]||(0,vk.default)(e)}function Yd(e,t,r){let n={};for(let i in e)Object.hasOwn(e,i)&&(n[t(i,r)]=e[i]);return n}var tf="__lc_escaped__";function tL(e){return"lc"in e||Object.keys(e).length===1&&tf in e}function rL(e){return{[tf]:e}}function Z_(e){return Object.keys(e).length===1&&tf in e}function nL(e){return e!==null&&typeof e=="object"&&"lc_serializable"in e&&typeof e.toJSON=="function"}function iL(e){let t;return e!==null&&typeof e=="object"?"lc_id"in e&&Array.isArray(e.lc_id)?t=e.lc_id:t=[e.constructor?.name??"Object"]:t=[typeof e],{lc:1,type:"not_implemented",id:t}}function Qd(e,t=new WeakSet){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){if(t.has(e))return iL(e);if(nL(e))return e;t.add(e);let r=e;if(tL(r))return t.delete(e),rL(r);let n={};for(let[i,s]of Object.entries(r))n[i]=Qd(s,t);return t.delete(e),n}return Array.isArray(e)?e.map(r=>Qd(r,t)):e}function ef(e){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(Z_(t))return t[tf];let r={};for(let[n,i]of Object.entries(t))r[n]=ef(i);return r}return Array.isArray(e)?e.map(t=>ef(t)):e}var sL=Object.defineProperty,M=(e,t)=>{for(var r in t)sL(e,r,{get:t[r],enumerable:!0})};var G_={};M(G_,{Serializable:()=>vt,get_lc_unique_name:()=>cc});function xk(e){return Array.isArray(e)?[...e]:{...e}}function oL(e,t){let r=xk(e);for(let[n,i]of Object.entries(t)){let[s,...o]=n.split(".").reverse(),a=r;for(let c of o.reverse()){if(a[c]===void 0)break;a[c]=xk(a[c]),a=a[c]}a[s]!==void 0&&(a[s]={lc:1,type:"secret",id:[i]})}return r}function cc(e){let t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var vt=class Ik{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,cc(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof Ik||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let t={},r={},n=Object.keys(this.lc_kwargs).reduce((c,u)=>(c[u]=u in this?this[u]:this.lc_kwargs[u],c),{});for(let c=Object.getPrototypeOf(this);c;c=Object.getPrototypeOf(c))Object.assign(t,Reflect.get(c,"lc_aliases",this)),Object.assign(r,Reflect.get(c,"lc_secrets",this)),Object.assign(n,Reflect.get(c,"lc_attributes",this));Object.keys(r).forEach(c=>{let u=this,l=n,[p,...f]=c.split(".").reverse();for(let d of f.reverse()){if(!(d in u)||u[d]===void 0)return;(!(d in l)||l[d]===void 0)&&(typeof u[d]=="object"&&u[d]!=null?l[d]={}:Array.isArray(u[d])&&(l[d]=[])),u=u[d],l=l[d]}p in u&&u[p]!==void 0&&(l[p]=l[p]||u[p])});let i={},s=new WeakSet;s.add(this);for(let[c,u]of Object.entries(n))i[c]=Qd(u,s);let o=Object.keys(r).length?oL(i,r):i,a=Yd(o,bk,t);return{lc:1,type:"constructor",id:this.lc_id,kwargs:a}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};var q_={};M(q_,{getEnv:()=>nf,getEnvironmentVariable:()=>Je,getRuntimeEnvironment:()=>H_,isBrowser:()=>Sk,isDeno:()=>rf,isJsDom:()=>kk,isNode:()=>Ak,isWebWorker:()=>Ek});var Sk=()=>typeof window<"u"&&typeof window.document<"u",Ek=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",kk=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),rf=()=>typeof Deno<"u",Ak=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!rf(),nf=()=>{let e;return Sk()?e="browser":Ak()?e="node":Ek()?e="webworker":kk()?e="jsdom":rf()?e="deno":e="other",e},K_;function H_(){return K_===void 0&&(K_={library:"langchain-js",runtime:nf()}),K_}function Je(e){try{return typeof process<"u"?process.env?.[e]:rf()?Deno?.env.get(e):void 0}catch{return}}var Tk=[];var Ok={};function Tr(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function uc(e){return Tr(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function lc(e){return Tr(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function $k(e){return Tr(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function sf(e){return Tr(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function of(e){if(Tr(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function ul(e){let t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);let r=t[0].trim(),n=t[1].trim();if(r===""||n==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);let i={};for(let s of e.split(";").slice(1)){let o=s.split("=");if(o.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);let a=o[0].trim(),c=o[1].trim();if(a==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);i[a]=c}return{type:r,subtype:n,parameters:i}}function Ps({dataUrl:e,asTypedArray:t=!1}){let r=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let i=t?Uint8Array.from(atob(r[2]),s=>s.charCodeAt(0)):r[2];return{mime_type:n,data:i}}}function pc(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function re(e,t){return le(e)&&e.type===t}function le(e){return typeof e=="object"&&e!==null}function qt(e){return Array.isArray(e)}function z(e){return typeof e=="string"}function Ur(e){return typeof e=="number"}function af(e){return e instanceof Uint8Array}function W_(e){try{return JSON.parse(e)}catch{return}}var ji=e=>e();function aL(e){if(e.type==="char_location"&&z(e.document_title)&&Ur(e.start_char_index)&&Ur(e.end_char_index)&&z(e.cited_text)){let{document_title:t,start_char_index:r,end_char_index:n,cited_text:i,...s}=e;return{...s,type:"citation",source:"char",title:t??void 0,startIndex:r,endIndex:n,citedText:i}}if(e.type==="page_location"&&z(e.document_title)&&Ur(e.start_page_number)&&Ur(e.end_page_number)&&z(e.cited_text)){let{document_title:t,start_page_number:r,end_page_number:n,cited_text:i,...s}=e;return{...s,type:"citation",source:"page",title:t??void 0,startIndex:r,endIndex:n,citedText:i}}if(e.type==="content_block_location"&&z(e.document_title)&&Ur(e.start_block_index)&&Ur(e.end_block_index)&&z(e.cited_text)){let{document_title:t,start_block_index:r,end_block_index:n,cited_text:i,...s}=e;return{...s,type:"citation",source:"block",title:t??void 0,startIndex:r,endIndex:n,citedText:i}}if(e.type==="web_search_result_location"&&z(e.url)&&z(e.title)&&z(e.encrypted_index)&&z(e.cited_text)){let{url:t,title:r,encrypted_index:n,cited_text:i,...s}=e;return{...s,type:"citation",source:"url",url:t,title:r,startIndex:Number(n),endIndex:Number(n),citedText:i}}if(e.type==="search_result_location"&&z(e.source)&&z(e.title)&&Ur(e.start_block_index)&&Ur(e.end_block_index)&&z(e.cited_text)){let{source:t,title:r,start_block_index:n,end_block_index:i,cited_text:s,...o}=e;return{...o,type:"citation",source:"search",url:t,title:r??void 0,startIndex:n,endIndex:i,citedText:s}}}function Pk(e){if(re(e,"document")&&le(e.source)&&"type"in e.source){if(e.source.type==="base64"&&z(e.source.media_type)&&z(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&z(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&z(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&z(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(re(e,"image")&&le(e.source)&&"type"in e.source){if(e.source.type==="base64"&&z(e.source.media_type)&&z(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&z(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&z(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function Nk(e){function*t(){for(let r of e){let n=Pk(r);n?yield n:yield r}}return Array.from(t())}function Ck(e){function*t(){let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r){if(re(n,"text")&&z(n.text)){let{text:i,citations:s,...o}=n;if(qt(s)&&s.length){let a=s.reduce((c,u)=>{let l=aL(u);return l?[...c,l]:c},[]);yield{...o,type:"text",text:i,annotations:a};continue}else{yield{...o,type:"text",text:i};continue}}else if(re(n,"thinking")&&z(n.thinking)){let{thinking:i,signature:s,...o}=n;yield{...o,type:"reasoning",reasoning:i,signature:s};continue}else if(re(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(re(n,"tool_use")&&z(n.name)&&z(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(re(n,"input_json_delta")){if(cL(e)&&e.tool_call_chunks?.length){let i=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:i.id,name:i.name,args:i.args,index:i.index};continue}}else if(re(n,"server_tool_use")&&z(n.name)&&z(n.id)){let{name:i,id:s}=n;if(i==="web_search"){let o=ji(()=>{if(typeof n.input=="string")return n.input;if(le(n.input)&&z(n.input.query))return n.input.query;if(z(n.partial_json)){let a=W_(n.partial_json);if(a?.query)return a.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:o}};continue}else if(n.name==="code_execution"){let o=ji(()=>{if(typeof n.input=="string")return n.input;if(le(n.input)&&z(n.input.code))return n.input.code;if(z(n.partial_json)){let a=W_(n.partial_json);if(a?.code)return a.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:o}};continue}}else if(re(n,"web_search_tool_result")&&z(n.tool_use_id)&&qt(n.content)){let{content:i,tool_use_id:s}=n,o=i.reduce((a,c)=>re(c,"web_search_result")?[...a,c.url]:a,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:o}};continue}else if(re(n,"code_execution_tool_result")&&z(n.tool_use_id)&&le(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(re(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(re(n,"mcp_tool_result")&&z(n.tool_use_id)&&le(n.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(re(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(re(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(re(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{let i=Pk(n);if(i){yield i;continue}}yield{type:"non_standard",value:n}}}return Array.from(t())}var Rk={translateContent:Ck,translateContentChunk:Ck};function cL(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function uL(e){return uc(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:lc(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:sf(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Mk(e){return e.map(uL)}function jk(e){return!!(re(e,"image_url")&&le(e.image_url)||re(e,"input_audio")&&le(e.input_audio)||re(e,"file")&&le(e.file))}function Dk(e){if(re(e,"image_url")&&le(e.image_url)&&z(e.image_url.url)){let t=Ps({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(re(e,"input_audio")&&le(e.input_audio)&&z(e.input_audio.data)&&z(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(re(e,"file")&&le(e.file)&&z(e.file.data)){let t=Ps({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(z(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function lL(e){let t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...cf(e.content));for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function pL(e){let t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...cf(e.content));for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function cf(e){let t=[];for(let r of e)jk(r)?t.push(Dk(r)):t.push(r);return t}function dL(e){if(e.type==="url_citation"){let{url:t,title:r,start_index:n,end_index:i}=e;return{type:"citation",url:t,title:r,startIndex:n,endIndex:i}}if(e.type==="file_citation"){let{file_id:t,filename:r,index:n}=e;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:t}}return e}function zk(e){function*t(){le(e.additional_kwargs?.reasoning)&&qt(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((i,s)=>le(s)&&z(s.text)?`${i}${s.text}`:i,"")});let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r)if(re(n,"text")){let{text:i,annotations:s,...o}=n;Array.isArray(s)?yield{...o,type:"text",text:String(i),annotations:s.map(dL)}:yield{...o,type:"text",text:String(i)}}for(let n of e.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(le(e.additional_kwargs)&&qt(e.additional_kwargs.tool_outputs))for(let n of e.additional_kwargs.tool_outputs){if(re(n,"web_search_call")){yield{id:n.id,type:"server_tool_call",name:"web_search",args:{query:n.query}};continue}else if(re(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{query:n.query}};continue}else if(re(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(re(n,"code_interpreter_call")){if(z(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),qt(n.outputs)){let i=ji(()=>{if(n.status!=="in_progress"){if(n.status==="completed")return 0;if(n.status==="incomplete")return 127;if(n.status!=="interpreting"&&n.status==="failed")return 1}});for(let s of n.outputs)if(re(s,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:i??0,stderr:[0,void 0].includes(i)?void 0:String(s.logs),stdout:[0,void 0].includes(i)?String(s.logs):void 0}};continue}}continue}else if(re(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(re(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(re(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(re(n,"image_generation_call")){z(n.result)&&(yield{type:"image",mimeType:"image/png",data:n.result,id:z(n.id)?n.id:void 0,metadata:{status:z(n.status)?n.status:void 0}}),yield{type:"non_standard",value:n};continue}le(n)&&(yield{type:"non_standard",value:n})}}return Array.from(t())}function fL(e){function*t(){yield*zk(e);for(let r of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return Array.from(t())}var Lk={translateContent:e=>typeof e.content=="string"?lL(e):zk(e),translateContentChunk:e=>typeof e.content=="string"?pL(e):fL(e)};function uf(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function Uk(e,t="pretty"){return t==="pretty"?mL(e):JSON.stringify(e)}function mL(e){let t=[],r=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),i="=".repeat(n),s=r.length%2===0?i:`${i}=`;if(t.push(`${i}${r}${s}`),e.type==="ai"){let o=e;if(o.tool_calls&&o.tool_calls.length>0){t.push("Tool Calls:");for(let a of o.tool_calls){t.push(` ${a.name} (${a.id})`),t.push(` Call ID: ${a.id}`),t.push(" Args:");for(let[c,u]of Object.entries(a.args))t.push(` ${c}: ${typeof u=="object"?JSON.stringify(u):u}`)}}}if(e.type==="tool"){let o=e;o.name&&t.push(`Name: ${o.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
6
- `)}var J_=Symbol.for("langchain.message");function Ht(e,t){return typeof e=="string"?e===""?t:typeof t=="string"?e+t:Array.isArray(t)&&t.length===0?e:Array.isArray(t)&&t.some(r=>Tr(r))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?Ro(e,t)??[...e,...t]:t===""?e:Array.isArray(e)&&e.some(r=>Tr(r))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function lf(e,t){return e==="error"||t==="error"?"error":"success"}function hL(e,t){function r(n,i){if(typeof n!="object"||n===null||n===void 0)return n;if(i>=t)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(o=>r(o,i+1));let s={};for(let o of Object.keys(n))s[o]=r(n[o],i+1);return s}return JSON.stringify(r(e,0),null,2)}var bt=class extends vt{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[J_]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){let t=typeof e=="string"||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):t.content!==void 0?(this.content=t.content??[],this.response_metadata=t.response_metadata):(this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){let e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[Mk,cf,Nk].reduce((n,i)=>i(n),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&J_ in e&&e[J_]===!0&&uf(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;let t=hL(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return Uk(this,e)}};function Fk(e){return Array.isArray(e)&&e.every(t=>typeof t.index=="number")}var X_=["index","created","timestamp"];function st(e,t,r){let n=r?.ignoreKeys??X_;if(e==null&&t==null)return;if(e==null||t==null)return e??t;let i={...e};for(let[s,o]of Object.entries(t))if(i[s]==null)i[s]=o;else{if(o==null)continue;if(typeof i[s]!=typeof o||Array.isArray(i[s])!==Array.isArray(o))throw new Error(`field[${s}] already exists in the message chunk, but with a different type.`);if(typeof i[s]=="string"){if(s==="type")continue;if(["id","name","output_version","model_provider"].includes(s))o&&(i[s]=o);else{if(n.includes(s))continue;i[s]+=o}}else if(typeof i[s]=="number"){if(n.includes(s))continue;i[s]=i[s]+o}else if(typeof i[s]=="object"&&!Array.isArray(i[s]))i[s]=st(i[s],o,r);else if(Array.isArray(i[s]))i[s]=Ro(i[s],o,r);else{if(i[s]===o)continue;console.warn(`field[${s}] already exists in this message chunk and value has unsupported type.`)}}return i}function Ro(e,t,r){if(!(e==null&&t==null)){if(e==null||t==null)return e||t;{let n=[...e];for(let i of t)if(typeof i=="object"&&i!==null&&"index"in i&&typeof i.index=="number"){let s=n.findIndex(o=>{let a=typeof o=="object",c="index"in o&&o.index===i.index,u="id"in o&&"id"in i&&o?.id===i?.id,l=!("id"in o)||!o?.id||!("id"in i)||!i?.id;return a&&c&&(u||l)});s!==-1&&typeof n[s]=="object"&&n[s]!==null?n[s]=st(n[s],i,r):n.push(i)}else{if(typeof i=="object"&&i!==null&&"text"in i&&i.text==="")continue;n.push(i)}return n}}}function pf(e,t,r){if(!(e==null&&t==null)){if(e==null||t==null)return e??t;if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.
7
- Left ${typeof e}
8
- Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return Ro(e,t,r);if(typeof e=="object"&&typeof t=="object")return st(e,t,r);if(e===t)return e;throw new Error(`Can not merge objects of different types.
9
- Left ${e}
10
- Right ${t}`)}}var ur=class Bk extends bt{static isInstance(t){if(!super.isInstance(t))return!1;let r=Object.getPrototypeOf(t);for(;r!==null;){if(r===Bk.prototype)return!0;r=Object.getPrototypeOf(r)}return!1}};function df(e){return typeof e.role=="string"}function ot(e){return typeof e?._getType=="function"}function Di(e){return ur.isInstance(e)}var Y_={};M(Y_,{ToolMessage:()=>Wt,ToolMessageChunk:()=>Ns,defaultToolCallParser:()=>pl,isDirectToolOutput:()=>ll,isToolMessage:()=>Mo,isToolMessageChunk:()=>Q_});function ll(e){return e!=null&&typeof e=="object"&&"lc_direct_tool_output"in e&&e.lc_direct_tool_output===!0}var Wt=class extends bt{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(e,t,r){let n=typeof e=="string"||Array.isArray(e)?{content:e,name:r,tool_call_id:t}:e;super(n),this.tool_call_id=n.tool_call_id,this.artifact=n.artifact,this.status=n.status,this.metadata=n.metadata}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Ns=class extends ur{type="tool";tool_call_id;status;artifact;constructor(e){super(e),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){let t=this.constructor;return new t({content:Ht(this.content,e.content),additional_kwargs:st(this.additional_kwargs,e.additional_kwargs),response_metadata:st(this.response_metadata,e.response_metadata),artifact:pf(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:lf(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function pl(e){let t=[],r=[];for(let n of e)if(n.function){let i=n.function.name;try{let s=JSON.parse(n.function.arguments);t.push({name:i||"",args:s||{},id:n.id})}catch{r.push({name:i,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[t,r]}function Mo(e){return typeof e=="object"&&e!==null&&"getType"in e&&typeof e.getType=="function"&&e.getType()==="tool"}function Q_(e){return e._getType()==="tool"}var ey={};M(ey,{BaseCallbackHandler:()=>zi,callbackHandlerPrefersStreaming:()=>dl,isBaseCallbackHandler:()=>ty});var gL=class{};function dl(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}var zi=class extends gL{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,cc(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Je("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(e){super(),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return vt.prototype.toJSON.call(this)}toJSONNotImplemented(){return vt.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends zi{name=sn();constructor(){super(),Object.assign(this,e)}}return new t}},ty=e=>{let t=e;return t!==void 0&&typeof t.copy=="function"&&typeof t.name=="string"&&typeof t.awaitHandlers=="boolean"};var Vk="gen_ai.operation.name",Zk="gen_ai.system",ry="gen_ai.request.model",Gk="gen_ai.response.model",ny="gen_ai.usage.input_tokens",iy="gen_ai.usage.output_tokens",sy="gen_ai.usage.total_tokens",Kk="gen_ai.request.max_tokens",qk="gen_ai.request.temperature",Hk="gen_ai.request.top_p",Wk="gen_ai.request.frequency_penalty",Jk="gen_ai.request.presence_penalty",Xk="gen_ai.response.finish_reasons",Yk="gen_ai.prompt",Qk="gen_ai.completion",eA="gen_ai.request.extra_query",tA="gen_ai.request.extra_body",rA="gen_ai.serialized.name",nA="gen_ai.serialized.signature",iA="gen_ai.serialized.doc",sA="gen_ai.response.id",oA="gen_ai.response.service_tier",aA="gen_ai.response.system_fingerprint",cA="gen_ai.usage.input_token_details",uA="gen_ai.usage.output_token_details",lA="langsmith.trace.session_id",pA="langsmith.trace.session_name",dA="langsmith.span.kind",fA="langsmith.trace.name",mA="langsmith.metadata",oy="langsmith.span.tags";var hA="langsmith.request.streaming",gA="langsmith.request.headers";var yL=(...e)=>fetch(...e),_A=Symbol.for("ls:fetch_implementation");var yA=()=>{let e=globalThis[_A];return e?typeof e=="function"&&"Headers"in e&&"Request"in e&&"Response"in e:!1},vA=e=>async(...t)=>{if(e||wt("DEBUG")==="true"){let[n,i]=t;console.log(`\u2192 ${i?.method||"GET"} ${n}`)}let r=await(globalThis[_A]??yL)(...t);return(e||wt("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r};var fl=()=>wt("PROJECT")??Fr("LANGCHAIN_SESSION")??"default";var bA={};function ml(e){bA[e]||(console.warn(e),bA[e]=!0)}var vL=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function be(e,t){if(!vL.test(e)){let r=t!==void 0?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`;throw new Error(r)}return e}function ff(e){let t=typeof e=="string"?Date.parse(e):e;return sn({msecs:t,seq:0})}function wA(e,t){throw new Error("dump() is not supported in browser environments.")}function xA(e){throw new Error("load() is not supported in browser environments.")}function bL(e,t){return t===null?!1:Date.now()-e.createdAt>t*1e3}var hl=class{constructor(t={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchFunc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.maxSize=t.maxSize??100,this.ttlSeconds=t.ttlSeconds??3600,this.refreshIntervalSeconds=t.refreshIntervalSeconds??60,this.fetchFunc=t.fetchFunc,this.fetchFunc&&this.ttlSeconds!==null&&this.startRefreshLoop()}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let t=this.totalRequests;return t>0?this._metrics.hits/t:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(t){let r=this.cache.get(t);if(!r){this._metrics.misses+=1;return}return this.cache.delete(t),this.cache.set(t,r),this._metrics.hits+=1,r.value}set(t,r){if(!this.cache.has(t)&&this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}let n={value:r,createdAt:Date.now()};this.cache.delete(t),this.cache.set(t,n)}invalidate(t){this.cache.delete(t)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(t){let r={};for(let[n,i]of this.cache.entries())r[n]=i.value;wA(t,r)}load(t){let r=xA(t);if(!r)return 0;let n=0,i=Date.now();for(let[s,o]of Object.entries(r)){if(this.cache.size>=this.maxSize)break;let a={value:o,createdAt:i};this.cache.set(s,a),n+=1}return n}startRefreshLoop(){this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(t=>{console.warn("Unexpected error in cache refresh loop:",t)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref()}getStaleKeys(){let t=[];for(let[r,n]of this.cache.entries())bL(n,this.ttlSeconds)&&t.push(r);return t}async refreshStaleEntries(){if(!this.fetchFunc)return;let t=this.getStaleKeys();if(t.length!==0)for(let r of t)try{let n=await this.fetchFunc(r);this.set(r,n),this._metrics.refreshes+=1}catch(n){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${r}:`,n)}}};var mf="0.4.8";var ti,wL=()=>typeof window<"u"&&typeof window.document<"u",xL=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",IL=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),IA=()=>typeof Deno<"u",SL=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!IA(),uy=()=>ti||(typeof Bun<"u"?ti="bun":wL()?ti="browser":SL()?ti="node":xL()?ti="webworker":IL()?ti="jsdom":IA()?ti="deno":ti="other",ti),ay;function hf(){if(ay===void 0){let e=uy(),t=kL();ay={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:mf,...t}}return ay}function ly(){let e=EL(),t={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[n,i]of Object.entries(e))typeof i=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?t.revision_id=i:t[n]=i);return t}function EL(){let e={};try{if(typeof process<"u"&&process.env)for(let[t,r]of Object.entries(process.env))(t.startsWith("LANGCHAIN_")||t.startsWith("LANGSMITH_"))&&r!=null&&((t.toLowerCase().includes("key")||t.toLowerCase().includes("secret")||t.toLowerCase().includes("token"))&&typeof r=="string"?e[t]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):e[t]=r)}catch{}return e}function Fr(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function wt(e){return Fr(`LANGSMITH_${e}`)||Fr(`LANGCHAIN_${e}`)}var cy;function kL(){if(cy!==void 0)return cy;let e=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],t={};for(let r of e){let n=Fr(r);n!==void 0&&(t[r]=n)}return cy=t,t}function gf(){return Fr("OTEL_ENABLED")==="true"||wt("OTEL_ENABLED")==="true"}var fy=class{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(t,...r){!this.hasWarned&&gf()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(r.length===1&&typeof r[0]=="function"?n=r[0]:r.length===2&&typeof r[1]=="function"?n=r[1]:r.length===3&&typeof r[2]=="function"&&(n=r[2]),typeof n=="function")return n()}},my=class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new fy})}getTracer(t,r){return this.mockTracer}getActiveSpan(){}setSpan(t,r){return t}getSpan(t){}setSpanContext(t,r){return t}getTracerProvider(){}setGlobalTracerProvider(t){return!1}},hy=class{active(){return{}}with(t,r){return r()}},py=Symbol.for("ls:otel_trace"),dy=Symbol.for("ls:otel_context"),SA=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),AL=new my,TL=new hy,gy=class{getTraceInstance(){return globalThis[py]??AL}getContextInstance(){return globalThis[dy]??TL}initializeGlobalInstances(t){globalThis[py]===void 0&&(globalThis[py]=t.trace),globalThis[dy]===void 0&&(globalThis[dy]=t.context)}setDefaultOTLPTracerComponents(t){globalThis[SA]=t}getDefaultOTLPTracerComponents(){return globalThis[SA]??void 0}},_y=new gy;function _f(){return _y.getTraceInstance()}function EA(){return _y.getContextInstance()}function kA(){return _y.getDefaultOTLPTracerComponents()}var OL={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function $L(e){return OL[e]||e}var yf=class{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(t,r){for(let n of t)try{if(!n.run)continue;if(n.operation==="post"){let i=this.createSpanForRun(n,n.run,r.get(n.id));i&&!n.run.end_time&&this.spans.set(n.id,i)}else this.updateSpanForRun(n,n.run)}catch(i){console.error(`Error processing operation ${n.id}:`,i)}}createSpanForRun(t,r,n){let i=n&&_f().getSpan(n);if(i)try{return this.finishSpanSetup(i,r,t)}catch(s){console.error(`Failed to create span for run ${t.id}:`,s);return}}finishSpanSetup(t,r,n){return this.setSpanAttributes(t,r,n),r.error?(t.setStatus({code:2}),t.recordException(new Error(r.error))):t.setStatus({code:1}),r.end_time&&t.end(new Date(r.end_time)),t}updateSpanForRun(t,r){try{let n=this.spans.get(t.id);if(!n){console.debug(`No span found for run ${t.id} during update`);return}this.setSpanAttributes(n,r,t),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});let i=r.end_time;i&&(n.end(new Date(i)),this.spans.delete(t.id))}catch(n){console.error(`Failed to update span for run ${t.id}:`,n)}}extractModelName(t){if(t.extra?.metadata){let r=t.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){let n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(t,r,n){if("run_type"in r&&r.run_type){t.setAttribute(dA,r.run_type);let a=$L(r.run_type||"chain");t.setAttribute(Vk,a)}"name"in r&&r.name&&t.setAttribute(fA,r.name),"session_id"in r&&r.session_id&&t.setAttribute(lA,r.session_id),"session_name"in r&&r.session_name&&t.setAttribute(pA,r.session_name),this.setGenAiSystem(t,r);let i=this.extractModelName(r);i&&t.setAttribute(ry,i),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&t.setAttribute(ny,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&t.setAttribute(iy,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&t.setAttribute(sy,r.total_tokens),this.setInvocationParameters(t,r);let s=r.extra?.metadata||{};for(let[a,c]of Object.entries(s))c!=null&&t.setAttribute(`${mA}.${a}`,String(c));let o=r.tags;if(o&&Array.isArray(o)?t.setAttribute(oy,o.join(", ")):o&&t.setAttribute(oy,String(o)),"serialized"in r&&typeof r.serialized=="object"){let a=r.serialized;a.name&&t.setAttribute(rA,String(a.name)),a.signature&&t.setAttribute(nA,String(a.signature)),a.doc&&t.setAttribute(iA,String(a.doc))}this.setIOAttributes(t,n)}setGenAiSystem(t,r){let n="langchain",i=this.extractModelName(r);if(i){let s=i.toLowerCase();s.includes("anthropic")||s.startsWith("claude")?n="anthropic":s.includes("bedrock")?n="aws.bedrock":s.includes("azure")&&s.includes("openai")?n="az.ai.openai":s.includes("azure")&&s.includes("inference")?n="az.ai.inference":s.includes("cohere")?n="cohere":s.includes("deepseek")?n="deepseek":s.includes("gemini")?n="gemini":s.includes("groq")?n="groq":s.includes("watson")||s.includes("ibm")?n="ibm.watsonx.ai":s.includes("mistral")?n="mistral_ai":s.includes("gpt")||s.includes("openai")?n="openai":s.includes("perplexity")||s.includes("sonar")?n="perplexity":s.includes("vertex")?n="vertex_ai":(s.includes("xai")||s.includes("grok"))&&(n="xai")}t.setAttribute(Zk,n)}setInvocationParameters(t,r){if(!r.extra?.metadata?.invocation_params)return;let n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&t.setAttribute(Kk,n.max_tokens),n.temperature!==void 0&&t.setAttribute(qk,n.temperature),n.top_p!==void 0&&t.setAttribute(Hk,n.top_p),n.frequency_penalty!==void 0&&t.setAttribute(Wk,n.frequency_penalty),n.presence_penalty!==void 0&&t.setAttribute(Jk,n.presence_penalty)}setIOAttributes(t,r){if(r.run.inputs)try{let n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&t.setAttribute(ry,n.model),n.stream!==void 0&&t.setAttribute(hA,n.stream),n.extra_headers&&t.setAttribute(gA,JSON.stringify(n.extra_headers)),n.extra_query&&t.setAttribute(eA,JSON.stringify(n.extra_query)),n.extra_body&&t.setAttribute(tA,JSON.stringify(n.extra_body))),t.setAttribute(Yk,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{let n=r.run.outputs,i=this.getUnifiedRunTokens(n);if(i&&(t.setAttribute(ny,i[0]),t.setAttribute(iy,i[1]),t.setAttribute(sy,i[0]+i[1])),n&&typeof n=="object"){if(n.model&&t.setAttribute(Gk,String(n.model)),n.id&&t.setAttribute(sA,n.id),n.choices&&Array.isArray(n.choices)){let s=n.choices.map(o=>o.finish_reason).filter(o=>o).map(String);s.length>0&&t.setAttribute(Xk,s.join(", "))}if(n.service_tier&&t.setAttribute(oA,n.service_tier),n.system_fingerprint&&t.setAttribute(aA,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let s=n.usage_metadata;s.input_token_details&&t.setAttribute(cA,JSON.stringify(s.input_token_details)),s.output_token_details&&t.setAttribute(uA,JSON.stringify(s.output_token_details))}}t.setAttribute(Qk,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(t){if(!t)return null;let r=this.extractUnifiedRunTokens(t.usage_metadata);if(r)return r;let n=Object.keys(t);for(let o of n){let a=t[o];if(!(!a||typeof a!="object")&&(r=this.extractUnifiedRunTokens(a.usage_metadata),r||a.lc===1&&a.kwargs&&typeof a.kwargs=="object"&&(r=this.extractUnifiedRunTokens(a.kwargs.usage_metadata),r)))return r}let i=t.generations||[];if(!Array.isArray(i))return null;let s=Array.isArray(i[0])?i.flat():i;for(let o of s)if(typeof o=="object"&&o.message&&typeof o.message=="object"&&o.message.kwargs&&typeof o.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(o.message.kwargs.usage_metadata),r))return r;return null}extractUnifiedRunTokens(t){return!t||typeof t!="object"||typeof t.input_tokens!="number"||typeof t.output_tokens!="number"?null:[t.input_tokens,t.output_tokens]}};var CL=Object.prototype.toString,PL=e=>CL.call(e)==="[object Error]",NL=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function yy(e){if(!(e&&PL(e)&&e.name==="TypeError"&&typeof e.message=="string"))return!1;let{message:r,stack:n}=e;return r==="Load failed"?n===void 0||"__sentry_captured__"in e:r.startsWith("error sending request for url")?!0:NL.has(r)}function RL(e){if(typeof e=="number"){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function vf(e,t,{min:r=0,allowInfinity:n=!1}={}){if(t!==void 0){if(typeof t!="number"||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<r)throw new TypeError(`Expected \`${e}\` to be \u2265 ${r}.`)}}var vy=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}};function ML(e,t){let r=Math.max(1,e+1),n=t.randomize?Math.random()+1:1,i=Math.round(n*t.minTimeout*t.factor**(r-1));return i=Math.min(i,t.maxTimeout),i}function AA(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function jL({error:e,attemptNumber:t,retriesConsumed:r,startTime:n,options:i}){let s=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(s instanceof vy)throw s.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,a=i.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:s,attemptNumber:t,retriesLeft:o,retriesConsumed:r});if(await i.onFailedAttempt(c),AA(n,a)<=0)throw s;let u=await i.shouldConsumeRetry(c),l=AA(n,a);if(l<=0||o<=0)throw s;if(s instanceof TypeError&&!yy(s)){if(u)throw s;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw s;if(!u)return i.signal?.throwIfAborted(),!1;let p=ML(r,i),f=Math.min(p,l);return f>0&&await new Promise((d,m)=>{let h=()=>{clearTimeout(b),i.signal?.removeEventListener("abort",h),m(i.signal.reason)},b=setTimeout(()=>{i.signal?.removeEventListener("abort",h),d()},f);i.unref&&b.unref?.(),i.signal?.addEventListener("abort",h,{once:!0})}),i.signal?.throwIfAborted(),!0}async function by(e,t={}){if(t={...t},RL(t.retries),Object.hasOwn(t,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=Number.POSITIVE_INFINITY,t.maxRetryTime??=Number.POSITIVE_INFINITY,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,vf("factor",t.factor,{min:0,allowInfinity:!1}),vf("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),vf("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),vf("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let r=0,n=0,i=performance.now();for(;!Number.isFinite(t.retries)||n<=t.retries;){r++;try{t.signal?.throwIfAborted();let s=await e(r);return t.signal?.throwIfAborted(),s}catch(s){await jL({error:s,attemptNumber:r,retriesConsumed:n,startTime:i,options:t})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Ef=Cs(Sf(),1),GL=[408,425,429,500,502,503,504],_l=class{constructor(t){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.maxQueueSizeBytes=t.maxQueueSizeBytes,"default"in Ef.default?this.queue=new Ef.default.default({concurrency:this.maxConcurrency}):this.queue=new Ef.default({concurrency:this.maxConcurrency}),this.onFailedResponseHook=t?.onFailedResponseHook}call(t,...r){return this.callWithOptions({},t,...r)}callWithOptions(t,r,...n){let i=t.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&i>0&&this.queueSizeBytes+i>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${i} bytes.`));i>0&&(this.queueSizeBytes+=i);let s=this.onFailedResponseHook,o=this.queue.add(()=>by(()=>r(...n).catch(a=>{throw a instanceof Error?a:new Error(a)}),{async onFailedAttempt({error:a}){if(typeof a!="object"||a==null)throw a;let c="message"in a&&typeof a.message=="string"?a.message:void 0;if(c?.startsWith("Cancel")||c?.startsWith("TimeoutError")||c?.startsWith("AbortError")||"name"in a&&a.name==="TimeoutError"||"code"in a&&a.code==="ECONNABORTED")throw a;let u="response"in a?a.response:void 0;if(s&&await s(u))return;let l=u?.status??("status"in a?a.status:void 0);if(l!=null&&(typeof l=="number"||typeof l=="string")&&!GL.includes(+l))throw a},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return i>0&&(o=o.finally(()=>{this.queueSizeBytes-=i})),t.signal?Promise.race([o,new Promise((a,c)=>{t.signal?.addEventListener("abort",()=>{c(new Error("AbortError"))})})]):o}};function Ay(e){return typeof e?._getType=="function"}function Ty(e){let t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}var F2=Cs(EO(),1);function Ui(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(`Invalid identifier format: ${e}`);let[t,r]=e.split(":"),n=r||"latest";if(t.includes("/")){let[i,s]=t.split("/",2);if(!i||!s)throw new Error(`Invalid identifier format: ${e}`);return[i,s,n]}else{if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,n]}}var Hy=class extends Error{constructor(t){super(t),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}},Wy=class extends Error{constructor(t){super(t),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}};function Jy(e){return e!=null&&typeof e=="object"&&"name"in e&&e?.name==="LangSmithNotFoundError"}async function ie(e,t,r){let n;if(e.ok){r&&(n=await e.text());return}if(e.status===403)try{(await e.json())?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{let a=new Error(`${e.status} ${e.statusText}`);throw a.status=e?.status,a}if(n===void 0)try{n=await e.text()}catch{n=""}let i=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${n}`;if(e.status===404)throw new Wy(i);if(e.status===409)throw new Hy(i);let s=new Error(i);throw s.status=e.status,s}var kO="ERR_CONFLICTING_ENDPOINTS",zf=class extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:kO}),this.name="ConflictingEndpointsError"}};function AO(e){return typeof e=="object"&&e!==null&&e.code===kO}var TO="[...]",B2={result:"[Circular]"},Uf=[],fc=[],V2=new TextEncoder;function Z2(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Lf(e){return V2.encode(e)}function OO(e){if(e&&typeof e=="object"&&e!==null){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if(typeof e=="bigint")return e.toString();return e}function G2(e){return function(t,r){if(e){let n=e.call(this,t,r);if(n!==void 0)return n}return OO(r)}}function Or(e,t,r,n,i){try{let s=JSON.stringify(e,G2(r),n);return Lf(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`
11
- Context: ${t}`:""}`),Lf("[Unserializable]");wt("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?`
12
- Context: ${t}`:""}`),typeof i>"u"&&(i=Z2()),Yy(e,"",0,[],void 0,0,i);let o;try{fc.length===0?o=JSON.stringify(e,r,n):o=JSON.stringify(e,K2(r),n)}catch{return Lf("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Uf.length!==0;){let a=Uf.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return Lf(o)}}function Xy(e,t,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:e}),Uf.push([n,r,t,i])):fc.push([t,r,e]):(n[r]=e,Uf.push([n,r,t]))}function Yy(e,t,r,n,i,s,o){s+=1;var a;if(typeof e=="object"&&e!==null){for(a=0;a<n.length;a++)if(n[a]===e){Xy(B2,e,t,i);return}if(typeof o.depthLimit<"u"&&s>o.depthLimit){Xy(TO,e,t,i);return}if(typeof o.edgesLimit<"u"&&r+1>o.edgesLimit){Xy(TO,e,t,i);return}if(n.push(e),Array.isArray(e))for(a=0;a<e.length;a++)Yy(e[a],a,a,n,e,s,o);else{e=OO(e);var c=Object.keys(e);for(a=0;a<c.length;a++){var u=c[a];Yy(e[u],u,a,n,e,s,o)}}n.pop()}}function K2(e){return e=typeof e<"u"?e:function(t,r){return r},function(t,r){if(fc.length>0)for(var n=0;n<fc.length;n++){var i=fc[n];if(i[1]===t&&i[0]===r){r=i[2],fc.splice(n,1);break}}return e.call(this,t,r)}}function $O(e,t,r){if(r)return e;let n=hf(),i=t??ly(),s=e.extra??{},o=s.metadata;return e.extra={...s,runtime:{...n,...s?.runtime},metadata:{...i,...i.revision_id||"revision_id"in e&&e.revision_id?{revision_id:("revision_id"in e?e.revision_id:void 0)??i.revision_id}:{},...o}},e}var q2=e=>{let t=e?.toString()??wt("TRACING_SAMPLING_RATE");if(t===void 0)return;let r=parseFloat(t);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},H2=e=>{let r=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};async function W2(e){let t=[];for await(let r of e)t.push(r);return t}function Ff(e){if(e!==void 0)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}var J2=async e=>{if(e?.status===429){let t=parseInt(e.headers.get("retry-after")??"10",10)*1e3;if(t>0)return await new Promise(r=>setTimeout(r,t)),!0}return!1};function CO(e){return typeof e=="number"?Number(e.toFixed(4)):e}var X2=24*1024*1024,RO=1024*1024*1024,Y2=1e4,Q2=100,PO="https://api.smith.langchain.com",Qy=class{constructor(t){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=t??RO}peek(){return this.items[0]}push(t){let r,n=new Promise(s=>{r=s}),i=Or(t.item,`Serializing run with id: ${t.item.id}`).length;return this.sizeBytes+i>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${t.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${i} bytes.`),r(),n):(this.items.push({action:t.action,payload:t.item,otelContext:t.otelContext,apiKey:t.apiKey,apiUrl:t.apiUrl,itemPromiseResolve:r,itemPromise:n,size:i}),this.sizeBytes+=i,n)}pop({upToSizeBytes:t,upToSize:r}){if(t<1)throw new Error("Number of bytes to pop off may not be less than 1.");let n=[],i=0;for(;i+(this.peek()?.size??0)<t&&this.items.length>0&&n.length<r;){let s=this.items.shift();s&&(n.push(s),i+=s.size,this.sizeBytes-=s.size)}if(n.length===0&&this.items.length>0){let s=this.items.shift();n.push(s),i+=s.size,this.sizeBytes-=s.size}return[n.map(s=>({action:s.action,item:s.payload,otelContext:s.otelContext,apiKey:s.apiKey,apiUrl:s.apiUrl,size:s.size})),()=>n.forEach(s=>s.itemPromiseResolve())]}},Li=class e{get _fetch(){return this.fetchImplementation||vA(this.debug)}constructor(t={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Fr("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:wt("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Fr("LANGSMITH_DEBUG")==="true"});let r=e.getDefaultClientConfig();if(this.tracingSampleRate=q2(t.tracingSamplingRate),this.apiUrl=Ff(t.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=Ff(t.apiKey??r.apiKey),this.webUrl=Ff(t.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Ff(t.workspaceId??wt("WORKSPACE_ID")),this.timeout_ms=t.timeout_ms??9e4,this.caller=new _l({...t.callerOptions??{},maxRetries:4,debug:t.debug??this.debug}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=t.debug??this.debug,this.fetchImplementation=t.fetchImplementation;let n=t.maxIngestMemoryBytes??RO;this.batchIngestCaller=new _l({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:n,...t.callerOptions??{},onFailedResponseHook:J2,debug:t.debug??this.debug}),this.hideInputs=t.hideInputs??t.anonymizer??r.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??r.hideOutputs,this.omitTracedRuntimeInfo=t.omitTracedRuntimeInfo??!1,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new Qy(n),this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.batchSizeLimit=t.batchSizeLimit,this.fetchOptions=t.fetchOptions||{},this.manualFlushMode=t.manualFlushMode??this.manualFlushMode,gf()&&(this.langSmithToOTELTranslator=new yf),this.cachedLSEnvVarsForMetadata=ly(),t.cache===!0?this._cache=new hl:t.cache&&typeof t.cache=="object"?this._cache=t.cache:this._cache=void 0}static getDefaultClientConfig(){let t=wt("API_KEY"),r=wt("ENDPOINT")??PO,n=wt("HIDE_INPUTS")==="true",i=wt("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:t,webUrl:void 0,hideInputs:n,hideOutputs:i}}getHostUrl(){return this.webUrl?this.webUrl:H2(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){let t={"User-Agent":`langsmith-js/${mf}`};return this.apiKey&&(t["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(t["x-tenant-id"]=this.workspaceId),t}_getPlatformEndpointPath(t){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${t}`:`/platform/${t}`}async processInputs(t){return this.hideInputs===!1?t:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(t):t}async processOutputs(t){return this.hideOutputs===!1?t:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(t):t}async prepareRunCreateOrUpdateInputs(t){let r={...t};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),r}async _getResponse(t,r){let n=r?.toString()??"",i=`${this.apiUrl}${t}?${n}`;return await this.caller.call(async()=>{let o=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(o,`fetch ${t}`),o})}async _get(t,r){return(await this._getResponse(t,r)).json()}async*_getPaginated(t,r=new URLSearchParams,n){let i=Number(r.get("offset"))||0,s=Number(r.get("limit"))||100;for(;;){r.set("offset",String(i)),r.set("limit",String(s));let o=`${this.apiUrl}${t}?${r}`,a=await this.caller.call(async()=>{let u=await this._fetch(o,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(u,`fetch ${t}`),u}),c=n?n(await a.json()):await a.json();if(c.length===0||(yield c,c.length<s))break;i+=c.length}}async*_getCursorPaginatedList(t,r=null,n="POST",i="runs"){let s=r?{...r}:{};for(;;){let o=JSON.stringify(s),c=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}${t}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(l,`fetch ${t}`),l})).json();if(!c||!c[i])break;yield c[i];let u=c.cursors;if(!u||!u.next)break;s.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(t,r=!1){if(this.tracingSampleRate===void 0)return t;if(r){let n=[];for(let i of t)this.filteredPostUuids.has(i.trace_id)?i.id===i.trace_id&&this.filteredPostUuids.delete(i.trace_id):n.push(i);return n}else{let n=[];for(let i of t){let s=i.trace_id??i.id;this.filteredPostUuids.has(s)||(i.id===s?this._shouldSample()?n.push(i):this.filteredPostUuids.add(s):n.push(i))}return n}}async _getBatchSizeLimitBytes(){let t=await this._ensureServerInfo();return this.batchSizeBytesLimit??t?.batch_ingest_config?.size_limit_bytes??X2}async _getBatchSizeLimit(){let t=await this._ensureServerInfo();return this.batchSizeLimit??t?.batch_ingest_config?.size_limit??Q2}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:r}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[i,s]=this.autoBatchQueue.pop({upToSizeBytes:t,upToSize:r});if(!i.length){s();break}let o=i.reduce((u,l)=>{let p=l.apiUrl??this.apiUrl,f=l.apiKey??this.apiKey,m=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${p}|${f}`;return u[m]||(u[m]=[]),u[m].push(l),u},{}),a=[];for(let[u,l]of Object.entries(o)){let p=this._processBatch(l,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});a.push(p)}let c=Promise.all(a).finally(s);n.push(c)}return Promise.all(n)}async _processBatch(t,r){if(!t.length)return;let n=t.reduce((i,s)=>i+(s.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(t);else{let i={runCreates:t.filter(a=>a.action==="create").map(a=>a.item),runUpdates:t.filter(a=>a.action==="update").map(a=>a.item)},s=await this._ensureServerInfo();if(!this._multipartDisabled&&(s?.batch_ingest_config?.use_multipart_endpoint??!0)){let a=!this._runCompressionDisabled&&s?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(i,{...r,useGzip:a,sizeBytes:n})}catch(c){if(Jy(c))this._multipartDisabled=!0,await this.batchIngestRuns(i,{...r,sizeBytes:n});else throw c}}else await this.batchIngestRuns(i,{...r,sizeBytes:n})}}catch(i){console.error("Error exporting batch:",i)}}_sendBatchToOTELTranslator(t){if(this.langSmithToOTELTranslator!==void 0){let r=new Map,n=[];for(let i of t)i.item.id&&i.otelContext&&(r.set(i.item.id,i.otelContext),i.action==="create"?n.push({operation:"post",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}):n.push({operation:"patch",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(t){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,t.item=$O(t.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let r=this.autoBatchQueue.push(t);if(this.manualFlushMode)return r;let n=await this._getBatchSizeLimitBytes(),i=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>i)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i})},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){let r=await(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(Y2),...this.fetchOptions});return await ie(n,"get server info"),n})).json();return this.debug&&console.log(`
13
- === LangSmith Server Configuration ===
14
- `+JSON.stringify(r,null,2)+`
15
- `),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(t){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${t.status??"Unspecified status code"} ${t.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(t=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),t))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let t=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:r})}_cloneCurrentOTELContext(){let t=_f(),r=EA();if(this.langSmithToOTELTranslator!==void 0){let n=t.getActiveSpan();if(n)return t.setSpan(r.active(),n)}}async createRun(t,r){if(!this._filterForSampling([t]).length)return;let n={...this.headers,"Content-Type":"application/json"},i=t.project_name;delete t.project_name;let s=await this.prepareRunCreateOrUpdateInputs({session_name:i,...t,start_time:t.start_time??Date.now()});if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){let c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:s,otelContext:c,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}let o=$O(s,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);let a=Or(o,`Creating run with id: ${o.id}`);await this.caller.call(async()=>{let c=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await ie(c,"create run",!0),c})}async batchIngestRuns({runCreates:t,runUpdates:r},n){if(t===void 0&&r===void 0)return;let i=await Promise.all(t?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),s=await Promise.all(r?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(i.length>0&&s.length>0){let c=i.reduce((l,p)=>(p.id&&(l[p.id]=p),l),{}),u=[];for(let l of s)l.id!==void 0&&c[l.id]?c[l.id]={...c[l.id],...l}:u.push(l);i=Object.values(c),s=u}let o={post:i,patch:s};if(!o.post.length&&!o.patch.length)return;let a={post:[],patch:[]};for(let c of["post","patch"]){let u=c,l=o[u].reverse(),p=l.pop();for(;p!==void 0;)a[u].push(p),p=l.pop()}if(a.post.length>0||a.patch.length>0){let c=a.post.map(u=>u.id).concat(a.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(Or(a,`Ingesting runs with ids: ${c}`),n)}}async _postBatchIngestRuns(t,r){let n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let i=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await ie(i,"batch create run",!0),i})}async multipartIngestRuns({runCreates:t,runUpdates:r},n){if(t===void 0&&r===void 0)return;let i={},s=[];for(let p of t??[]){let f=await this.prepareRunCreateOrUpdateInputs(p);f.id!==void 0&&f.attachments!==void 0&&(i[f.id]=f.attachments),delete f.attachments,s.push(f)}let o=[];for(let p of r??[])o.push(await this.prepareRunCreateOrUpdateInputs(p));if(s.find(p=>p.trace_id===void 0||p.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(o.find(p=>p.trace_id===void 0||p.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(s.length>0&&o.length>0){let p=s.reduce((d,m)=>(m.id&&(d[m.id]=m),d),{}),f=[];for(let d of o)d.id!==void 0&&p[d.id]?p[d.id]={...p[d.id],...d}:f.push(d);s=Object.values(p),o=f}if(s.length===0&&o.length===0)return;let u=[],l=[];for(let[p,f]of[["post",s],["patch",o]])for(let d of f){let{inputs:m,outputs:h,events:b,extra:_,error:y,serialized:x,attachments:I,...A}=d,j={inputs:m,outputs:h,events:b,extra:_,error:y,serialized:x},O=Or(A,`Serializing for multipart ingestion of run with id: ${A.id}`);l.push({name:`${p}.${A.id}`,payload:new Blob([O],{type:`application/json; length=${O.length}`})});for(let[w,U]of Object.entries(j)){if(U===void 0)continue;let P=Or(U,`Serializing ${w} for multipart ingestion of run with id: ${A.id}`);l.push({name:`${p}.${A.id}.${w}`,payload:new Blob([P],{type:`application/json; length=${P.length}`})})}if(A.id!==void 0){let w=i[A.id];if(w){delete i[A.id];for(let[U,P]of Object.entries(w)){let V,Oe;if(Array.isArray(P)?[V,Oe]=P:(V=P.mimeType,Oe=P.data),U.includes(".")){console.warn(`Skipping attachment '${U}' for run ${A.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${A.id}.${U}`,payload:new Blob([Oe],{type:`${V}; length=${Oe.byteLength}`})})}}}u.push(`trace=${A.trace_id},id=${A.id}`)}await this._sendMultipartRequest(l,u.join("; "),n)}async _createNodeFetchBody(t,r){let n=[];for(let o of t)n.push(new Blob([`--${r}\r
16
- `])),n.push(new Blob([`Content-Disposition: form-data; name="${o.name}"\r
17
- `,`Content-Type: ${o.payload.type}\r
18
- \r
19
- `])),n.push(o.payload),n.push(new Blob([`\r
20
- `]));return n.push(new Blob([`--${r}--\r
21
- `])),await new Blob(n).arrayBuffer()}async _createMultipartStream(t,r){let n=new TextEncoder;return new ReadableStream({async start(s){let o=async a=>{typeof a=="string"?s.enqueue(n.encode(a)):s.enqueue(a)};for(let a of t){await o(`--${r}\r
22
- `),await o(`Content-Disposition: form-data; name="${a.name}"\r
23
- `),await o(`Content-Type: ${a.payload.type}\r
24
- \r
25
- `);let u=a.payload.stream().getReader();try{let l;for(;!(l=await u.read()).done;)s.enqueue(l.value)}finally{u.releaseLock()}await o(`\r
26
- `)}await o(`--${r}--\r
27
- `),s.close()}})}async _sendMultipartRequest(t,r,n){let i="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=yA(),o=()=>this._createNodeFetchBody(t,i),a=()=>this._createMultipartStream(t,i),c=async u=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let l=await u(),p={...this.headers,"Content-Type":`multipart/form-data; boundary=${i}`};n?.apiKey!==void 0&&(p["x-api-key"]=n.apiKey);let f=l;n?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(f=l.pipeThrough(new CompressionStream("gzip")),p["Content-Encoding"]="gzip");let d=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:p,body:f,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(d,"Failed to send multipart request",!0),d});try{let u,l=!1;!s&&!this.multipartStreamingDisabled&&uy()!=="bun"?(l=!0,u=await c(a)):u=await c(o),(!this.multipartStreamingDisabled||l)&&u.status===422&&(n?.apiUrl??this.apiUrl)!==PO&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,u=await c(o))}catch(u){if(Jy(u))throw u;console.warn(`${u.message.trim()}
28
-
29
- Context: ${r}`)}}async updateRun(t,r,n){be(t),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));let i={...r,id:t};if(!this._filterForSampling([i],!0).length)return;if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let a=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&i.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:i,otelContext:a,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:i,otelContext:a,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let s={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(s["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(s["x-tenant-id"]=n.workspaceId);let o=Or(r,`Serializing payload to update run with id: ${t}`);await this.caller.call(async()=>{let a=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${t}`,{method:"PATCH",headers:s,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(a,"update run",!0),a})}async readRun(t,{loadChildRuns:r}={loadChildRuns:!1}){be(t);let n=await this._get(`/runs/${t}`);return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:t,run:r,projectOpts:n}){if(r!==void 0){let i;r.session_id?i=r.session_id:n?.projectName?i=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?i=n?.projectId:i=(await this.readProject({projectName:wt("PROJECT")||"default"})).id;let s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${i}/r/${r.id}?poll=true`}else if(t!==void 0){let i=await this.readRun(t);if(!i.app_path)throw new Error(`Run ${t} has no app_path`);return`${this.getHostUrl()}${i.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(t){let r=await W2(this.listRuns({isRoot:!1,projectId:t.session_id,traceId:t.trace_id})),n={},i={};r.sort((s,o)=>(s?.dotted_order??"").localeCompare(o?.dotted_order??""));for(let s of r){if(s.parent_run_id===null||s.parent_run_id===void 0)throw new Error(`Child run ${s.id} has no parent`);s.dotted_order?.startsWith(t.dotted_order??"")&&s.id!==t.id&&(s.parent_run_id in n||(n[s.parent_run_id]=[]),n[s.parent_run_id].push(s),i[s.id]=s)}t.child_runs=n[t.id]||[];for(let s in n)s!==t.id&&(i[s].child_runs=n[s]);return t}async*listRuns(t){let{projectId:r,projectName:n,parentRunId:i,traceId:s,referenceExampleId:o,startTime:a,executionOrder:c,isRoot:u,runType:l,error:p,id:f,query:d,filter:m,traceFilter:h,treeFilter:b,limit:_,select:y,order:x}=t,I=[];if(r&&(I=Array.isArray(r)?r:[r]),n){let w=Array.isArray(n)?n:[n],U=await Promise.all(w.map(P=>this.readProject({projectName:P}).then(V=>V.id)));I.push(...U)}let A=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],j={session:I.length?I:null,run_type:l,reference_example:o,query:d,filter:m,trace_filter:h,tree_filter:b,execution_order:c,parent_run:i,start_time:a?a.toISOString():null,error:p,id:f,limit:_,trace:s,select:y||A,is_root:u,order:x};j.select.includes("child_run_ids")&&ml("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let O=0;for await(let w of this._getCursorPaginatedList("/runs/query",j))if(_){if(O>=_)break;if(w.length+O>_){yield*w.slice(0,_-O);break}O+=w.length,yield*w}else yield*w}async*listGroupRuns(t){let{projectId:r,projectName:n,groupBy:i,filter:s,startTime:o,endTime:a,limit:c,offset:u}=t,p={session_id:r||(await this.readProject({projectName:n})).id,group_by:i,filter:s,start_time:o?o.toISOString():null,end_time:a?a.toISOString():null,limit:Number(c)||100},f=Number(u)||0,d="/runs/group",m=`${this.apiUrl}${d}`;for(;;){let h={...p,offset:f},b=Object.fromEntries(Object.entries(h).filter(([j,O])=>O!==void 0)),_=JSON.stringify(b),x=await(await this.caller.call(async()=>{let j=await this._fetch(m,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await ie(j,`Failed to fetch ${d}`),j})).json(),{groups:I,total:A}=x;if(I.length===0)break;for(let j of I)yield j;if(f+=I.length,f>=A)break}}async getRunStats({id:t,trace:r,parentRun:n,runType:i,projectNames:s,projectIds:o,referenceExampleIds:a,startTime:c,endTime:u,error:l,query:p,filter:f,traceFilter:d,treeFilter:m,isRoot:h,dataSourceType:b}){let _=o||[];s&&(_=[...o||[],...await Promise.all(s.map(O=>this.readProject({projectName:O}).then(w=>w.id)))]);let x=Object.fromEntries(Object.entries({id:t,trace:r,parent_run:n,run_type:i,session:_,reference_example:a,start_time:c,end_time:u,error:l,query:p,filter:f,trace_filter:d,tree_filter:m,is_root:h,data_source_type:b}).filter(([O,w])=>w!==void 0)),I=JSON.stringify(x);return await(await this.caller.call(async()=>{let O=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:I});return await ie(O,"get run stats"),O})).json()}async shareRun(t,{shareId:r}={}){let n={run_id:t,share_token:r||Ar()};be(t);let i=JSON.stringify(n),o=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await ie(a,"share run"),a})).json();if(o===null||!("share_token"in o))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${o.share_token}/r`}async unshareRun(t){be(t),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(r,"unshare run",!0),r})}async readRunSharedLink(t){be(t);let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(i,"read run shared link"),i})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(t,{runIds:r}={}){let n=new URLSearchParams({share_token:t});if(r!==void 0)for(let o of r)n.append("id",o);return be(t),await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/public/${t}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(o,"list shared runs"),o})).json()}async readDatasetSharedSchema(t,r){if(!t&&!r)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:r})).id),be(t);let i=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(s,"read dataset shared schema"),s})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async shareDataset(t,r){if(!t&&!r)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:r})).id);let n={dataset_id:t};be(t);let i=JSON.stringify(n),o=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await ie(a,"share dataset"),a})).json();return o.url=`${this.getHostUrl()}/public/${o.share_token}/d`,o}async unshareDataset(t){be(t),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(r,"unshare dataset",!0),r})}async readSharedDataset(t){return be(t),await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/public/${t}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(i,"read shared dataset"),i})).json()}async listSharedExamples(t,r){let n={};r?.exampleIds&&(n.id=r.exampleIds);let i=new URLSearchParams;Object.entries(n).forEach(([a,c])=>{Array.isArray(c)?c.forEach(u=>i.append(a,u)):i.append(a,c)});let s=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/public/${t}/examples?${i.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(a,"list shared examples"),a}),o=await s.json();if(!s.ok)throw"detail"in o?new Error(`Failed to list shared examples.
30
- Status: ${s.status}
31
- Message: ${Array.isArray(o.detail)?o.detail.join(`
32
- `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`);return o.map(a=>({...a,_hostUrl:this.getHostUrl()}))}async createProject({projectName:t,description:r=null,metadata:n=null,upsert:i=!1,projectExtra:s=null,referenceDatasetId:o=null}){let a=i?"?upsert=true":"",c=`${this.apiUrl}/sessions${a}`,u=s||{};n&&(u.metadata=n);let l={name:t,extra:u,description:r};o!==null&&(l.reference_dataset_id=o);let p=JSON.stringify(l);return await(await this.caller.call(async()=>{let m=await this._fetch(c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:p});return await ie(m,"create project"),m})).json()}async updateProject(t,{name:r=null,description:n=null,metadata:i=null,projectExtra:s=null,endTime:o=null}){let a=`${this.apiUrl}/sessions/${t}`,c=s;i&&(c={...c||{},metadata:i});let u=JSON.stringify({name:r,extra:c,description:n,end_time:o?new Date(o).toISOString():null});return await(await this.caller.call(async()=>{let f=await this._fetch(a,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await ie(f,"update project"),f})).json()}async hasProject({projectId:t,projectName:r}){let n="/sessions",i=new URLSearchParams;if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)be(t),n+=`/${t}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");let s=await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${n}?${i}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(o,"has project"),o});try{let o=await s.json();return s.ok?Array.isArray(o)?o.length>0:!0:!1}catch{return!1}}async readProject({projectId:t,projectName:r,includeStats:n}){let i="/sessions",s=new URLSearchParams;if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)be(t),i+=`/${t}`;else if(r!==void 0)s.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&s.append("include_stats",n.toString());let o=await this._get(i,s),a;if(Array.isArray(o)){if(o.length===0)throw new Error(`Project[id=${t}, name=${r}] not found`);a=o[0]}else a=o;return a}async getProjectUrl({projectId:t,projectName:r}){if(t===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:t,projectName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${n.id}`}async getDatasetUrl({datasetId:t,datasetName:r}){if(t===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:t,datasetName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let t=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",t))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:t,name:r,nameContains:n,referenceDatasetId:i,referenceDatasetName:s,includeStats:o,datasetVersion:a,referenceFree:c,metadata:u}={}){let l=new URLSearchParams;if(t!==void 0)for(let p of t)l.append("id",p);if(r!==void 0&&l.append("name",r),n!==void 0&&l.append("name_contains",n),i!==void 0)l.append("reference_dataset",i);else if(s!==void 0){let p=await this.readDataset({datasetName:s});l.append("reference_dataset",p.id)}o!==void 0&&l.append("include_stats",o.toString()),a!==void 0&&l.append("dataset_version",a),c!==void 0&&l.append("reference_free",c.toString()),u!==void 0&&l.append("metadata",JSON.stringify(u));for await(let p of this._getPaginated("/sessions",l))yield*p}async deleteProject({projectId:t,projectName:r}){let n;if(t===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");t===void 0?n=(await this.readProject({projectName:r})).id:n=t,be(n),await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(i,`delete session ${n} (${r})`,!0),i})}async uploadCsv({csvFile:t,fileName:r,inputKeys:n,outputKeys:i,description:s,dataType:o,name:a}){let c=`${this.apiUrl}/datasets/upload`,u=new FormData,l=new Blob([t],{type:"text/csv"});return u.append("file",l,r),n.forEach(d=>{u.append("input_keys",d)}),i.forEach(d=>{u.append("output_keys",d)}),s&&u.append("description",s),o&&u.append("data_type",o),a&&u.append("name",a),await(await this.caller.call(async()=>{let d=await this._fetch(c,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await ie(d,"upload CSV"),d})).json()}async createDataset(t,{description:r,dataType:n,inputsSchema:i,outputsSchema:s,metadata:o}={}){let a={name:t,description:r,extra:o?{metadata:o}:void 0};n&&(a.data_type=n),i&&(a.inputs_schema_definition=i),s&&(a.outputs_schema_definition=s);let c=JSON.stringify(a);return await(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await ie(p,"create dataset"),p})).json()}async readDataset({datasetId:t,datasetName:r}){let n="/datasets",i=new URLSearchParams({limit:"1"});if(t&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(t)be(t),n+=`/${t}`;else if(r)i.append("name",r);else throw new Error("Must provide datasetName or datasetId");let s=await this._get(n,i),o;if(Array.isArray(s)){if(s.length===0)throw new Error(`Dataset[id=${t}, name=${r}] not found`);o=s[0]}else o=s;return o}async hasDataset({datasetId:t,datasetName:r}){try{return await this.readDataset({datasetId:t,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:t,datasetName:r,fromVersion:n,toVersion:i}){let s=t;if(s===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:r})).id);let o=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof i=="string"?i:i.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,o)}async readDatasetOpenaiFinetuning({datasetId:t,datasetName:r}){let n="/datasets";if(t===void 0)if(r!==void 0)t=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${t}/openai_ft`)).text()).trim().split(`
33
- `).map(a=>JSON.parse(a))}async*listDatasets({limit:t=100,offset:r=0,datasetIds:n,datasetName:i,datasetNameContains:s,metadata:o}={}){let a="/datasets",c=new URLSearchParams({limit:t.toString(),offset:r.toString()});if(n!==void 0)for(let u of n)c.append("id",u);i!==void 0&&c.append("name",i),s!==void 0&&c.append("name_contains",s),o!==void 0&&c.append("metadata",JSON.stringify(o));for await(let u of this._getPaginated(a,c))yield*u}async updateDataset(t){let{datasetId:r,datasetName:n,...i}=t;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let s=r??(await this.readDataset({datasetName:n})).id;be(s);let o=JSON.stringify(i);return await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(c,"update dataset"),c})).json()}async updateDatasetTag(t){let{datasetId:r,datasetName:n,asOf:i,tag:s}=t;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let o=r??(await this.readDataset({datasetName:n})).id;be(o);let a=JSON.stringify({as_of:typeof i=="string"?i:i.toISOString(),tag:s});await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${o}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await ie(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:t,datasetName:r}){let n="/datasets",i=t;if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(i=(await this.readDataset({datasetName:r})).id),i!==void 0)be(i),n+=`/${i}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let s=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(s,`delete ${n}`,!0),s})}async indexDataset({datasetId:t,datasetName:r,tag:n}){let i=t;if(!i&&!r)throw new Error("Must provide either datasetName or datasetId");if(i&&r)throw new Error("Must provide either datasetName or datasetId, not both");i||(i=(await this.readDataset({datasetName:r})).id),be(i);let o=JSON.stringify({tag:n});await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${i}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(c,"index dataset"),c})).json()}async similarExamples(t,r,n,{filter:i}={}){let s={limit:n,inputs:t};i!==void 0&&(s.filter=i),be(r);let o=JSON.stringify(s);return(await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:o});return await ie(u,"fetch similar examples"),u})).json()).examples}async createExample(t,r,n){if(NO(t)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let i=r?n?.datasetId:t.dataset_id,s=r?n?.datasetName:t.dataset_name;if(i===void 0&&s===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&s!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:s})).id);let o=(r?n?.createdAt:t.created_at)||new Date,a;NO(t)?a=t:a={inputs:t,outputs:r,created_at:o?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let c=await this._uploadExamplesMultipart(i,[a]);return await this.readExample(c.example_ids?.[0]??Ar())}async createExamples(t){if(Array.isArray(t)){if(t.length===0)return[];let y=t,x=y[0].dataset_id,I=y[0].dataset_name;if(x===void 0&&I===void 0)throw new Error("Must provide either datasetName or datasetId");if(x!==void 0&&I!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");x===void 0&&(x=(await this.readDataset({datasetName:I})).id);let A=await this._uploadExamplesMultipart(x,y);return await Promise.all(A.example_ids.map(O=>this.readExample(O)))}let{inputs:r,outputs:n,metadata:i,splits:s,sourceRunIds:o,useSourceRunIOs:a,useSourceRunAttachments:c,attachments:u,exampleIds:l,datasetId:p,datasetName:f}=t;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let d=p,m=f;if(d===void 0&&m===void 0)throw new Error("Must provide either datasetName or datasetId");if(d!==void 0&&m!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");d===void 0&&(d=(await this.readDataset({datasetName:m})).id);let h=r.map((y,x)=>({dataset_id:d,inputs:y,outputs:n?.[x],metadata:i?.[x],split:s?.[x],id:l?.[x],attachments:u?.[x],source_run_id:o?.[x],use_source_run_io:a?.[x],use_source_run_attachments:c?.[x]})),b=await this._uploadExamplesMultipart(d,h);return await Promise.all(b.example_ids.map(y=>this.readExample(y)))}async createLLMExample(t,r,n){return this.createExample({input:t},{output:r},n)}async createChatExample(t,r,n){let i=t.map(o=>Ay(o)?Ty(o):o),s=Ay(r)?Ty(r):r;return this.createExample({input:i},{output:s},n)}async readExample(t){be(t);let r=`/examples/${t}`,n=await this._get(r),{attachment_urls:i,...s}=n,o=s;return i&&(o.attachments=Object.entries(i).reduce((a,[c,u])=>(a[c.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},a),{})),o}async*listExamples({datasetId:t,datasetName:r,exampleIds:n,asOf:i,splits:s,inlineS3Urls:o,metadata:a,limit:c,offset:u,filter:l,includeAttachments:p}={}){let f;if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0)f=t;else if(r!==void 0)f=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");let d=new URLSearchParams({dataset:f}),m=i?typeof i=="string"?i:i?.toISOString():void 0;m&&d.append("as_of",m);let h=o??!0;if(d.append("inline_s3_urls",h.toString()),n!==void 0)for(let _ of n)d.append("id",_);if(s!==void 0)for(let _ of s)d.append("splits",_);if(a!==void 0){let _=JSON.stringify(a);d.append("metadata",_)}c!==void 0&&d.append("limit",c.toString()),u!==void 0&&d.append("offset",u.toString()),l!==void 0&&d.append("filter",l),p===!0&&["attachment_urls","outputs","metadata"].forEach(_=>d.append("select",_));let b=0;for await(let _ of this._getPaginated("/examples",d)){for(let y of _){let{attachment_urls:x,...I}=y,A=I;x&&(A.attachments=Object.entries(x).reduce((j,[O,w])=>(j[O.slice(11)]={presigned_url:w.presigned_url,mime_type:w.mime_type||void 0},j),{})),yield A,b++}if(c!==void 0&&b>=c)break}}async deleteExample(t){be(t);let r=`/examples/${t}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(n,`delete ${r}`,!0),n})}async deleteExamples(t,r){if(t.forEach(n=>be(n)),r?.hardDelete){let n=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${n}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({example_ids:t,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(i,"hard delete examples",!0),i})}else{let n=new URLSearchParams;t.forEach(i=>n.append("example_ids",i)),await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/examples?${n.toString()}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(i,"delete examples",!0),i})}}async updateExample(t,r){let n;r?n=t:n=t.id,be(n);let i;r?i={id:n,...r}:i=t;let s;return i.dataset_id!==void 0?s=i.dataset_id:s=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(s,[i])}async updateExamples(t){let r;return t[0].dataset_id===void 0?r=(await this.readExample(t[0].id)).dataset_id:r=t[0].dataset_id,this._updateExamplesMultipart(r,t)}async readDatasetVersion({datasetId:t,datasetName:r,asOf:n,tag:i}){let s;if(t?s=t:s=(await this.readDataset({datasetName:r})).id,be(s),n&&i||!n&&!i)throw new Error("Exactly one of asOf and tag must be specified.");let o=new URLSearchParams;return n!==void 0&&o.append("as_of",typeof n=="string"?n:n.toISOString()),i!==void 0&&o.append("tag",i),await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${s}/version?${o.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:t,datasetName:r,asOf:n}){let i;if(t===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?i=(await this.readDataset({datasetName:r})).id:i=t,be(i);let s=new URLSearchParams,o=n?typeof n=="string"?n:n?.toISOString():void 0;return o&&s.append("as_of",o),await this._get(`/datasets/${i}/splits`,s)}async updateDatasetSplits({datasetId:t,datasetName:r,splitName:n,exampleIds:i,remove:s=!1}){let o;if(t===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?o=(await this.readDataset({datasetName:r})).id:o=t,be(o);let a={split_name:n,examples:i.map(u=>(be(u),u)),remove:s},c=JSON.stringify(a);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${o}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await ie(u,"update dataset splits",!0),u})}async createFeedback(t,r,{score:n,value:i,correction:s,comment:o,sourceInfo:a,feedbackSourceType:c="api",sourceRunId:u,feedbackId:l,feedbackConfig:p,projectId:f,comparativeExperimentId:d}){if(!t&&!f)throw new Error("One of runId or projectId must be provided");if(t&&f)throw new Error("Only one of runId or projectId can be provided");let m={type:c??"api",metadata:a??{}};u!==void 0&&m?.metadata!==void 0&&!m.metadata.__run&&(m.metadata.__run={run_id:u}),m?.metadata!==void 0&&m.metadata.__run?.run_id!==void 0&&be(m.metadata.__run.run_id);let h={id:l??Ar(),run_id:t,key:r,score:CO(n),value:i,correction:s,comment:o,feedback_source:m,comparative_experiment_id:d,feedbackConfig:p,session_id:f},b=JSON.stringify(h),_=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let y=await this._fetch(_,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:b});return await ie(y,"create feedback",!0),y}),h}async updateFeedback(t,{score:r,value:n,correction:i,comment:s}){let o={};r!=null&&(o.score=CO(r)),n!=null&&(o.value=n),i!=null&&(o.correction=i),s!=null&&(o.comment=s),be(t);let a=JSON.stringify(o);await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback/${t}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await ie(c,"update feedback",!0),c})}async readFeedback(t){be(t);let r=`/feedback/${t}`;return await this._get(r)}async deleteFeedback(t){be(t);let r=`/feedback/${t}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:t,feedbackKeys:r,feedbackSourceTypes:n}={}){let i=new URLSearchParams;if(t)for(let s of t)be(s),i.append("run",s);if(r)for(let s of r)i.append("key",s);if(n)for(let s of n)i.append("source",s);for await(let s of this._getPaginated("/feedback",i))yield*s}async createPresignedFeedbackToken(t,r,{expiration:n,feedbackConfig:i}={}){let s={run_id:t,feedback_key:r,feedback_config:i};n?typeof n=="string"?s.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(s.expires_in=n):s.expires_in={hours:3};let o=JSON.stringify(s);return await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:t,experimentIds:r,referenceDatasetId:n,createdAt:i,description:s,metadata:o,id:a}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");let c={id:a,name:t,experiment_ids:r,reference_dataset_id:n,description:s,created_at:(i??new Date)?.toISOString(),extra:{}};o&&(c.extra.metadata=o);let u=JSON.stringify(c);return(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await ie(p,"create comparative experiment"),p})).json()}async*listPresignedFeedbackTokens(t){be(t);let r=new URLSearchParams({run_id:t});for await(let n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(t){let r;return"results"in t?r=t.results:Array.isArray(t)?r=t:r=[t],r}async _logEvaluationFeedback(t,r,n){let i=this._selectEvalResults(t),s=[];for(let o of i){let a=n||{};o.evaluatorInfo&&(a={...o.evaluatorInfo,...a});let c=null;o.targetRunId?c=o.targetRunId:r&&(c=r.id),s.push(await this.createFeedback(c,o.key,{score:o.score,value:o.value,comment:o.comment,correction:o.correction,sourceInfo:a,sourceRunId:o.sourceRunId,feedbackConfig:o.feedbackConfig,feedbackSourceType:"model"}))}return[i,s]}async logEvaluationFeedback(t,r,n){let[i]=await this._logEvaluationFeedback(t,r,n);return i}async*listAnnotationQueues(t={}){let{queueIds:r,name:n,nameContains:i,limit:s}=t,o=new URLSearchParams;r&&r.forEach((c,u)=>{be(c,`queueIds[${u}]`),o.append("ids",c)}),n&&o.append("name",n),i&&o.append("name_contains",i),o.append("limit",(s!==void 0?Math.min(s,100):100).toString());let a=0;for await(let c of this._getPaginated("/annotation-queues",o))if(yield*c,a++,s!==void 0&&a>=s)break}async createAnnotationQueue(t){let{name:r,description:n,queueId:i,rubricInstructions:s}=t,o={name:r,description:n,id:i||Ar(),rubric_instructions:s},a=JSON.stringify(Object.fromEntries(Object.entries(o).filter(([u,l])=>l!==void 0)));return(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await ie(u,"create annotation queue"),u})).json()}async readAnnotationQueue(t){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${be(t,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(t,r){let{name:n,description:i,rubricInstructions:s}=r,o=JSON.stringify({name:n,description:i,rubric_instructions:s});await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/annotation-queues/${be(t,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(a,"update annotation queue",!0),a})}async deleteAnnotationQueue(t){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${be(t,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(t,r){let n=JSON.stringify(r.map((i,s)=>be(i,`runIds[${s}]`).toString()));await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/annotation-queues/${be(t,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await ie(i,"add runs to annotation queue",!0),i})}async getRunFromAnnotationQueue(t,r){let n=`/annotation-queues/${be(t,"queueId")}/run`;return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(s,"get run from annotation queue"),s})).json()}async deleteRunFromAnnotationQueue(t,r){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${be(t,"queueId")}/runs/${be(r,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(t){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${be(t,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(t){let r=await this._getSettings();return t=="-"||r.tenant_handle===t}async _ownerConflictError(t,r){let n=await this._getSettings();return new Error(`Cannot ${t} for another tenant.
34
-
35
- Current tenant: ${n.tenant_handle}
36
-
37
- Requested tenant: ${r}`)}async _getLatestCommitHash(t){let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/commits/${t}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(i,"get latest commit hash"),i})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(t,r){let[n,i,s]=Ui(t),o=JSON.stringify({like:r});return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/likes/${n}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(c,`${r?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(t){let[r,n,i]=Ui(t);if(await this._currentTenantIsOwner(r)){let s=await this._getSettings();return i!=="latest"?`${this.getHostUrl()}/prompts/${n}/${i.substring(0,8)}?organizationId=${s.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${s.id}`}else return i!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${i.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}async promptExists(t){return!!await this.getPrompt(t)}async likePrompt(t){return this._likeOrUnlikePrompt(t,!0)}async unlikePrompt(t){return this._likeOrUnlikePrompt(t,!1)}async*listCommits(t){for await(let r of this._getPaginated(`/commits/${t}/`,new URLSearchParams,n=>n.commits))yield*r}async*listPrompts(t){let r=new URLSearchParams;r.append("sort_field",t?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!t?.isArchived).toString()),t?.isPublic!==void 0&&r.append("is_public",t.isPublic.toString()),t?.query&&r.append("query",t.query);for await(let n of this._getPaginated("/repos",r,i=>i.repos))yield*n}async getPrompt(t){let[r,n,i]=Ui(t),o=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return a?.status===404?null:(await ie(a,"get prompt"),a)}))?.json();return o?.repo?o.repo:null}async createPrompt(t,r){let n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
38
-
39
- creating a LangChain Hub handle.
40
- You can add a handle by creating a public prompt at:
41
-
42
- https://smith.langchain.com/prompts`);let[i,s,o]=Ui(t);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError("create a prompt",i);let a={repo_handle:s,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},c=JSON.stringify(a),u=await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await ie(p,"create prompt"),p}),{repo:l}=await u.json();return l}async createCommit(t,r,n){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[i,s,o]=Ui(t),a=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${i}/${s}`):n?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(r)),parent_commit:a},u=JSON.stringify(c),p=await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/commits/${i}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await ie(f,"create commit"),f})).json();return this._getPromptUrl(`${i}/${s}${p.commit_hash?`:${p.commit_hash}`:""}`)}async updateExamplesMultipart(t,r=[]){return this._updateExamplesMultipart(t,r)}async _updateExamplesMultipart(t,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let o of r){let a=o.id,c={...o.metadata&&{metadata:o.metadata},...o.split&&{split:o.split}},u=Or(c,`Serializing body for example with id: ${a}`),l=new Blob([u],{type:"application/json"});if(n.append(a,l),o.inputs){let p=Or(o.inputs,`Serializing inputs for example with id: ${a}`),f=new Blob([p],{type:"application/json"});n.append(`${a}.inputs`,f)}if(o.outputs){let p=Or(o.outputs,`Serializing outputs whle updating example with id: ${a}`),f=new Blob([p],{type:"application/json"});n.append(`${a}.outputs`,f)}if(o.attachments)for(let[p,f]of Object.entries(o.attachments)){let d,m;Array.isArray(f)?[d,m]=f:(d=f.mimeType,m=f.data);let h=new Blob([m],{type:`${d}; length=${m.byteLength}`});n.append(`${a}.attachment.${p}`,h)}if(o.attachments_operations){let p=Or(o.attachments_operations,`Serializing attachments while updating example with id: ${a}`),f=new Blob([p],{type:"application/json"});n.append(`${a}.attachments_operations`,f)}}let i=t??r[0]?.dataset_id;return(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${i}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await ie(o,"update examples"),o})).json()}async uploadExamplesMultipart(t,r=[]){return this._uploadExamplesMultipart(t,r)}async _uploadExamplesMultipart(t,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let s of r){let o=(s.id??Ar()).toString(),a={created_at:s.created_at,...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split},...s.source_run_id&&{source_run_id:s.source_run_id},...s.use_source_run_io&&{use_source_run_io:s.use_source_run_io},...s.use_source_run_attachments&&{use_source_run_attachments:s.use_source_run_attachments}},c=Or(a,`Serializing body for uploaded example with id: ${o}`),u=new Blob([c],{type:"application/json"});if(n.append(o,u),s.inputs){let l=Or(s.inputs,`Serializing inputs for uploaded example with id: ${o}`),p=new Blob([l],{type:"application/json"});n.append(`${o}.inputs`,p)}if(s.outputs){let l=Or(s.outputs,`Serializing outputs for uploaded example with id: ${o}`),p=new Blob([l],{type:"application/json"});n.append(`${o}.outputs`,p)}if(s.attachments)for(let[l,p]of Object.entries(s.attachments)){let f,d;Array.isArray(p)?[f,d]=p:(f=p.mimeType,d=p.data);let m=new Blob([d],{type:`${f}; length=${d.byteLength}`});n.append(`${o}.attachment.${l}`,m)}}return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${t}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await ie(s,"upload examples"),s})).json()}async updatePrompt(t,r){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[n,i]=Ui(t);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let s={};if(r?.description!==void 0&&(s.description=r.description),r?.readme!==void 0&&(s.readme=r.readme),r?.tags!==void 0&&(s.tags=r.tags),r?.isPublic!==void 0&&(s.is_public=r.isPublic),r?.isArchived!==void 0&&(s.is_archived=r.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");let o=JSON.stringify(s);return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/repos/${n}/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(c,"update prompt"),c})).json()}async deletePrompt(t){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[r,n,i]=Ui(t);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(o,"delete prompt"),o})).json()}_getPromptCacheKey(t,r){return`${t}${r?":with_model":""}`}async _fetchPromptFromApi(t,r){let[n,i,s]=Ui(t),a=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/commits/${n}/${i}/${s}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(c,"pull prompt commit"),c})).json();return{owner:n,repo:i,commit_hash:a.commit_hash,manifest:a.manifest,examples:a.examples}}async pullPromptCommit(t,r){if(!r?.skipCache&&this._cache){let n=this._getPromptCacheKey(t,r?.includeModel),i=this._cache.get(n);if(i)return i;let s=await this._fetchPromptFromApi(t,r);return this._cache.set(n,s),s}return this._fetchPromptFromApi(t,r)}async _pullPrompt(t,r){let n=await this.pullPromptCommit(t,{includeModel:r?.includeModel,skipCache:r?.skipCache});return JSON.stringify(n.manifest)}async pushPrompt(t,r){return await this.promptExists(t)?r&&Object.keys(r).some(i=>i!=="object")&&await this.updatePrompt(t,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(t,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(t,r?.object,{parentCommitHash:r?.parentCommitHash}):await this._getPromptUrl(t)}async clonePublicDataset(t,r={}){let{sourceApiUrl:n=this.apiUrl,datasetName:i}=r,[s,o]=this.parseTokenOrUrl(t,n),a=new e({apiUrl:s,apiKey:"placeholder"}),c=await a.readSharedDataset(o),u=i||c.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}let l=await a.listSharedExamples(o),p=await this.createDataset(u,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map(f=>f.inputs),outputs:l.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:p.id})}catch(f){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),f}}parseTokenOrUrl(t,r,n=2,i="dataset"){try{return be(t),[r,t]}catch{}try{let o=new URL(t).pathname.split("/").filter(a=>a!=="");if(o.length>=n){let a=o[o.length-n];return[r,a]}else throw new Error(`Invalid public ${i} URL: ${t}`)}catch{throw new Error(`Invalid public ${i} URL or token: ${t}`)}}get cache(){return this._cache}cleanup(){this._cache&&this._cache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await new Promise(t=>setTimeout(t,1)),await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:t})=>t),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await kA()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}};function NO(e){return"dataset_id"in e||"dataset_name"in e}var MO=e=>e!==void 0?e:!!["TRACING_V2","TRACING"].find(r=>wt(r)==="true");var ni=Symbol.for("lc:context_variables"),BJ=Symbol.for("lc:child_run_end_promises"),Bf=Symbol.for("langsmith:replica_trace_roots");function ev(e,t){if(ni in e)return e[ni][t]}function jO(e,t,r){let n=ni in e?e[ni]:{};n[t]=r,e[ni]=n}var El=36,kl="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function DO(e){let r=Object.keys(e).sort().map(n=>`${n}:${e[n]??""}`).join("|");return nn(r,kl)}function eF(e){return e.replace(/[-:.]/g,"")}function LO(e,t=1){let r=t.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(e).toISOString().slice(0,-1)}${r}Z`}function tv(e,t,r=1){let n=LO(e,r);return{dottedOrder:eF(n)+t,microsecondPrecisionDatestring:n}}var tF=new Set(["projectName","updates","reroot"]);function rF(e){let t={};for(let r of Object.keys(e))tF.has(r)&&(t[r]=e[r]);return t}var Vf=class e{constructor(t,r,n,i){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=t,this.tags=r,this.project_name=n,this.replicas=i}static fromHeader(t){let r=t.split(","),n={},i=[],s,o;for(let a of r){let[c,u]=a.split("="),l=decodeURIComponent(u);c==="langsmith-metadata"?n=JSON.parse(l):c==="langsmith-tags"?i=l.split(","):c==="langsmith-project"?s=l:c==="langsmith-replicas"&&(o=JSON.parse(l).map(f=>Array.isArray(f)?f:rF(f)))}return new e(n,i,s,o)}toHeader(){let t=[];return this.metadata&&Object.keys(this.metadata).length>0&&t.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&t.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&t.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),t.join(",")}},An=class e{constructor(t){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),UO(t)){Object.assign(this,{...t});return}let r=e.getDefaultConfig(),{metadata:n,...i}=t,s=i.client??e.getSharedClient(),o={...n,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:o},"id"in i&&i.id==null&&delete i.id,Object.assign(this,{...r,...i,client:s}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=LO(this.start_time,this.execution_order)),this.id||(this.id=ff(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=oF(this.replicas),!this.dotted_order){let{dottedOrder:a}=tv(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+a:this.dotted_order=a}}set metadata(t){this.extra={...this.extra,metadata:{...this.extra?.metadata,...t}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let t=Date.now();return{run_type:"chain",project_name:fl(),child_runs:[],api_url:Fr("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Fr("LANGCHAIN_API_KEY"),caller_options:{},start_time:t,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return e.sharedClient||(e.sharedClient=new Li),e.sharedClient}createChild(t){let r=this.child_execution_order+1,n=this.replicas?.map(l=>{let{reroot:p,...f}=l;return f}),i=t.replicas??n,s=new e({...t,parent_run:this,project_name:this.project_name,replicas:i,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r});ni in this&&(s[ni]=this[ni]);let o=Symbol.for("lc:child_config"),a=t.extra?.[o]??this.extra[o];if(iF(a)){let l={...a},p=nF(l.callbacks)?l.callbacks.copy?.():void 0;p&&(Object.assign(p,{_parentRunId:s.id}),p.handlers?.find(FO)?.updateFromRunTree?.(s),l.callbacks=p),s.extra[o]=l}let c=new Set,u=this;for(;u!=null&&!c.has(u.id);)c.add(u.id),u.child_execution_order=Math.max(u.child_execution_order,r),u=u.parent_run;return this.child_runs.push(s),s}async end(t,r,n=Date.now(),i){this.outputs=this.outputs??t,this.error=this.error??r,this.end_time=this.end_time??n,i&&Object.keys(i).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...i}}:{metadata:i})}_convertToCreate(t,r,n=!0){let i=t.extra??{};if(i?.runtime?.library===void 0&&(i.runtime||(i.runtime={}),r))for(let[a,c]of Object.entries(r))i.runtime[a]||(i.runtime[a]=c);let s,o;return n?(o=t.parent_run?.id??t.parent_run_id,s=[]):(s=t.child_runs.map(a=>this._convertToCreate(a,r,n)),o=void 0),{id:t.id,name:t.name,start_time:t._serialized_start_time??t.start_time,end_time:t.end_time,run_type:t.run_type,reference_example_id:t.reference_example_id,extra:i,serialized:t.serialized,error:t.error,inputs:t.inputs,outputs:t.outputs,session_name:t.project_name,child_runs:s,parent_run_id:o,trace_id:t.trace_id,dotted_order:t.dotted_order,tags:t.tags,attachments:t.attachments,events:t.events}}_sliceParentId(t,r){if(r.dotted_order){let n=r.dotted_order.split("."),i=null;for(let s=0;s<n.length;s++)if(n[s].slice(-El)===t){i=s;break}if(i!==null){let s=n.slice(i+1);r.dotted_order=s.join("."),s.length>0?r.trace_id=s[0].slice(-El):r.trace_id=r.id}}r.parent_run_id===t&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(t,r){let n=ev(this,Bf)??{};n[t]=r,jO(this,Bf,n);for(let i of this.child_runs)i._setReplicaTraceRoot(t,r)}_remapForProject(t){let{projectName:r,runtimeEnv:n,excludeChildRuns:i=!0,reroot:s=!1,distributedParentId:o,apiUrl:a,apiKey:c,workspaceId:u}=t,l=this._convertToCreate(this,n,i);if(r===this.project_name)return{...l,session_name:r};if(s){if(o)this._sliceParentId(o,l);else if(l.parent_run_id=void 0,l.dotted_order){let y=l.dotted_order.split(".");y.length>0&&(l.dotted_order=y[y.length-1],l.trace_id=l.id)}let _=DO({projectName:r,apiUrl:a,apiKey:c,workspaceId:u});this._setReplicaTraceRoot(_,l.id)}let p;if(!s){let _=ev(this,Bf)??{},y=DO({projectName:r,apiUrl:a,apiKey:c,workspaceId:u});if(p=_[y],p&&(l.trace_id=p,l.dotted_order)){let x=l.dotted_order.split("."),I=null;for(let A=0;A<x.length;A++)if(x[A].slice(-El)===p){I=A;break}if(I!==null){let A=x.slice(I);l.dotted_order=A.join(".")}}}let f=l.id,d=nn(`${f}:${r}`,kl),m;l.trace_id?m=nn(`${l.trace_id}:${r}`,kl):m=d;let h;l.parent_run_id&&(h=nn(`${l.parent_run_id}:${r}`,kl));let b;return l.dotted_order&&(b=l.dotted_order.split(".").map(x=>{let I=x.slice(-El),A=nn(`${I}:${r}`,kl);return x.slice(0,-El)+A}).join(".")),{...l,id:d,trace_id:m,parent_run_id:h,dotted_order:b,session_name:r}}async postRun(t=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let r=hf();if(this.replicas&&this.replicas.length>0)for(let{projectName:n,apiKey:i,apiUrl:s,workspaceId:o,reroot:a}of this.replicas){let c=this._remapForProject({projectName:n??this.project_name,runtimeEnv:r,excludeChildRuns:!0,reroot:a,distributedParentId:this.distributedParentId,apiUrl:s,apiKey:i,workspaceId:o});await this.client.createRun(c,{apiKey:i,apiUrl:s,workspaceId:o})}else{let n=this._convertToCreate(this,r,t);await this.client.createRun(n)}if(!t){ml("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let n of this.child_runs)await n.postRun(!1)}this.child_runs=[]}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(t){if(this.replicas&&this.replicas.length>0)for(let{projectName:r,apiKey:n,apiUrl:i,workspaceId:s,updates:o,reroot:a}of this.replicas){let c=this._remapForProject({projectName:r??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:a,distributedParentId:this.distributedParentId,apiUrl:i,apiKey:n,workspaceId:s}),u={id:c.id,name:c.name,run_type:c.run_type,start_time:c.start_time,outputs:c.outputs,error:c.error,parent_run_id:c.parent_run_id,session_name:c.session_name,reference_example_id:c.reference_example_id,end_time:c.end_time,dotted_order:c.dotted_order,trace_id:c.trace_id,events:c.events,tags:c.tags,extra:c.extra,attachments:this.attachments,...o};t?.excludeInputs||(u.inputs=c.inputs),await this.client.updateRun(c.id,u,{apiKey:n,apiUrl:i,workspaceId:s})}else try{let r={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};t?.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(t){this.events||(this.events=[]),typeof t=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:t}):this.events.push({...t,time:t.time??new Date().toISOString()})}static fromRunnableConfig(t,r){let n=t?.callbacks,i,s,o,a=MO();if(n){let u=n?.getParentRunId?.()??"",l=n?.handlers?.find(p=>p?.name=="langchain_tracer");i=l?.getRun?.(u),s=l?.projectName,o=l?.client,a=a||!!l}return i?new e({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:o,tracingEnabled:a,project_name:s,tags:[...new Set((i?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...t?.metadata}}}).createChild(r):new e({...r,client:o,tracingEnabled:a,project_name:s})}static fromDottedOrder(t){return this.fromHeaders({"langsmith-trace":t})}static fromHeaders(t,r){let n="get"in t&&typeof t.get=="function"?{"langsmith-trace":t.get("langsmith-trace"),baggage:t.get("baggage")}:t,i=n["langsmith-trace"];if(!i||typeof i!="string")return;let s=i.trim(),o=s.split(".").map(l=>{let[p,f]=l.split("Z");return{strTime:p,time:Date.parse(p+"Z"),uuid:f}}),a=o[0].uuid,c={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:o.at(-1)?.uuid,trace_id:a,dotted_order:s};if(n.baggage&&typeof n.baggage=="string"){let l=Vf.fromHeader(n.baggage);c.metadata=l.metadata,c.tags=l.tags,c.project_name=l.project_name,c.replicas=l.replicas}let u=new e(c);return u.distributedParentId=u.id,u}toHeaders(t){let r={"langsmith-trace":this.dotted_order,baggage:new Vf(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(t)for(let[n,i]of Object.entries(r))t.set(n,i);return r}};Object.defineProperty(An,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function UO(e){return e!=null&&typeof e.createChild=="function"&&typeof e.postRun=="function"}function FO(e){return typeof e=="object"&&e!=null&&typeof e.name=="string"&&e.name==="langchain_tracer"}function zO(e){return Array.isArray(e)&&e.some(t=>FO(t))}function nF(e){return typeof e=="object"&&e!=null&&Array.isArray(e.handlers)}function iF(e){let t=e?.callbacks;return e!=null&&typeof t=="object"&&(zO(t?.handlers)||zO(t))}function sF(){let e=Fr("LANGSMITH_RUNS_ENDPOINTS");if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t)){let r=[];for(let n of t){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return r}else if(typeof t=="object"&&t!==null){aF(t);let r=[];for(let[n,i]of Object.entries(t)){let s=n.replace(/\/$/,"");if(typeof i=="string")r.push({apiUrl:s,apiKey:i});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof i}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof t}`),[]}catch(t){if(AO(t))throw t;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function oF(e){return e?e.map(t=>Array.isArray(t)?{projectName:t[0],updates:t[1]}:t):sF()}function aF(e){if(Object.keys(e).length>0&&wt("ENDPOINT"))throw new zf}var iv={};M(iv,{BaseTracer:()=>Zt,isBaseTracer:()=>Do});var cF=e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e};function nv(e,t){if(e)return new An({...e,start_time:e._serialized_start_time??e.start_time,parent_run:nv(t),child_runs:e.child_runs.map(r=>nv(r)).filter(r=>r!==void 0),extra:{...e.extra,runtime:H_()},tracingEnabled:!1})}function rv(e,t){return e&&!Array.isArray(e)&&typeof e=="object"?e:{[t]:e}}function Do(e){return typeof e._addRunToRunMap=="function"}var Zt=class extends zi{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?cF(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
43
-
44
- ${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let{dottedOrder:t,microsecondPrecisionDatestring:r}=tv(new Date(e.start_time).getTime(),e.id,e.execution_order),n={...e},i=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?i?(this._addChildRun(i,n),i.child_execution_order=Math.max(i.child_execution_order,n.child_execution_order),n.trace_id=i.trace_id,i.dotted_order!==void 0&&(n.dotted_order=[i.dotted_order,t].join("."),n._serialized_start_time=r)):n.parent_run_id=void 0:(n.trace_id=n.id,n.dotted_order=t,n._serialized_start_time=r),this.usesRunTreeMap){let s=nv(n,i);s!==void 0&&this.runTreeMap.set(n.id,s)}else this.runMap.set(n.id,n);return n}async _endTrace(e){let t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,n,i,s,o,a){let c=this._getExecutionOrder(n),u=Date.now(),l=o?{...i,metadata:o}:i,p={id:r,name:a??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:s||[]};return this._addRunToRunMap(p)}async handleLLMStart(e,t,r,n,i,s,o,a){let c=this.getRunById(r)??this._createRunForLLMStart(e,t,r,n,i,s,o,a);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,r,n,i,s,o,a){let c=this._getExecutionOrder(n),u=Date.now(),l=o?{...i,metadata:o}:i,p={id:r,name:a??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:s||[]};return this._addRunToRunMap(p)}async handleChatModelStart(e,t,r,n,i,s,o,a){let c=this.getRunById(r)??this._createRunForChatModelStart(e,t,r,n,i,s,o,a);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,r,n,i){let s=this.getRunById(t);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=e,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(e,t,r,n,i){let s=this.getRunById(t);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(e,t,r,n,i,s,o,a,c){let u=this._getExecutionOrder(n),l=Date.now(),p={id:r,name:a??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:u,child_execution_order:u,run_type:o??"chain",child_runs:[],extra:s?{...c,metadata:s}:{...c},tags:i||[]};return this._addRunToRunMap(p)}async handleChainStart(e,t,r,n,i,s,o,a){let c=this.getRunById(r)??this._createRunForChainStart(e,t,r,n,i,s,o,a);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,r,n,i){let s=this.getRunById(t);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=rv(e,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=rv(i.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(e,t,r,n,i){let s=this.getRunById(t);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=rv(i.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(e,t,r,n,i,s,o){let a=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:a,child_execution_order:a,run_type:"tool",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(e,t,r,n,i,s,o){let a=this.getRunById(r)??this._createRunForToolStart(e,t,r,n,i,s,o);return await this.onRunCreate?.(a),await this.onToolStart?.(a),a}async handleToolEnd(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="chain")return;let n=r;n.actions=n.actions||[],n.actions.push(e),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r)}async handleAgentEnd(e,t){let r=this.getRunById(t);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(e,t,r,n,i,s,o){let a=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:a,child_execution_order:a,run_type:"retriever",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(e,t,r,n,i,s,o){let a=this.getRunById(r)??this._createRunForRetrieverStart(e,t,r,n,i,s,o);return await this.onRunCreate?.(a),await this.onRetrieverStart?.(a),a}async handleRetrieverEnd(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(e,t){let r=this.getRunById(t);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(r))}async handleLLMNewToken(e,t,r,n,i,s){let o=this.getRunById(r);if(!o||o?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return o.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:s?.chunk}}),await this.onLLMNewToken?.(o,e,{chunk:s?.chunk}),o}};var sv=Cs(GO(),1),ov={};M(ov,{ConsoleCallbackHandler:()=>Zf});function fr(e,t){return`${e.open}${t}${e.close}`}function cn(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function KO(e){return typeof e=="string"?e.trim():e==null?e:cn(e,e.toString())}function Rs(e){if(!e.end_time)return"";let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}var{color:$r}=sv.default,Zf=class extends Zt{name="console_callback_handler";persistRun(e){return Promise.resolve()}getParents(e){let t=[],r=e;for(;r.parent_run_id;){let n=this.runMap.get(r.parent_run_id);if(n)t.push(n),r=n;else break}return t}getBreadcrumbs(e){let r=[...this.getParents(e).reverse(),e].map((n,i,s)=>{let o=`${n.execution_order}:${n.run_type}:${n.name}`;return i===s.length-1?fr(sv.default.bold,o):o}).join(" > ");return fr($r.grey,r)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.green,"[chain/start]")} [${t}] Entering Chain run with input: ${cn(e.inputs,"[inputs]")}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.cyan,"[chain/end]")} [${t}] [${Rs(e)}] Exiting Chain run with output: ${cn(e.outputs,"[outputs]")}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.red,"[chain/error]")} [${t}] [${Rs(e)}] Chain run errored with error: ${cn(e.error,"[error]")}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(n=>n.trim())}:e.inputs;console.log(`${fr($r.green,"[llm/start]")} [${t}] Entering LLM run with input: ${cn(r,"[inputs]")}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.cyan,"[llm/end]")} [${t}] [${Rs(e)}] Exiting LLM run with output: ${cn(e.outputs,"[response]")}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.red,"[llm/error]")} [${t}] [${Rs(e)}] LLM run errored with error: ${cn(e.error,"[error]")}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.green,"[tool/start]")} [${t}] Entering Tool run with input: "${KO(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.cyan,"[tool/end]")} [${t}] [${Rs(e)}] Exiting Tool run with output: "${KO(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.red,"[tool/error]")} [${t}] [${Rs(e)}] Tool run errored with error: ${cn(e.error,"[error]")}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${cn(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.cyan,"[retriever/end]")} [${t}] [${Rs(e)}] Exiting Retriever run with output: ${cn(e.outputs,"[outputs]")}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.red,"[retriever/error]")} [${t}] [${Rs(e)}] Retriever run errored with error: ${cn(e.error,"[error]")}`)}onAgentAction(e){let t=e,r=this.getBreadcrumbs(e);console.log(`${fr($r.blue,"[agent/action]")} [${r}] Agent selected action: ${cn(t.actions[t.actions.length-1],"[action]")}`)}};function Gf(e,t){return st(e,t)??{}}function qO(e,t){let r={};return(e?.audio!==void 0||t?.audio!==void 0)&&(r.audio=(e?.audio??0)+(t?.audio??0)),(e?.image!==void 0||t?.image!==void 0)&&(r.image=(e?.image??0)+(t?.image??0)),(e?.video!==void 0||t?.video!==void 0)&&(r.video=(e?.video??0)+(t?.video??0)),(e?.document!==void 0||t?.document!==void 0)&&(r.document=(e?.document??0)+(t?.document??0)),(e?.text!==void 0||t?.text!==void 0)&&(r.text=(e?.text??0)+(t?.text??0)),r}function lF(e,t){let r={...qO(e,t)};return(e?.cache_read!==void 0||t?.cache_read!==void 0)&&(r.cache_read=(e?.cache_read??0)+(t?.cache_read??0)),(e?.cache_creation!==void 0||t?.cache_creation!==void 0)&&(r.cache_creation=(e?.cache_creation??0)+(t?.cache_creation??0)),r}function pF(e,t){let r={...qO(e,t)};return(e?.reasoning!==void 0||t?.reasoning!==void 0)&&(r.reasoning=(e?.reasoning??0)+(t?.reasoning??0)),r}function mc(e,t){return{input_tokens:(e?.input_tokens??0)+(t?.input_tokens??0),output_tokens:(e?.output_tokens??0)+(t?.output_tokens??0),total_tokens:(e?.total_tokens??0)+(t?.total_tokens??0),input_token_details:lF(e?.input_token_details,t?.input_token_details),output_token_details:pF(e?.output_token_details,t?.output_token_details)}}function av(e){switch(e){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function dF(e){if(le(e.document)&&le(e.document.source)){let t=le(e.document)&&z(e.document.format)?e.document.format:"",r=av(t);if(le(e.document.source)){if(le(e.document.source.s3Location)&&z(e.document.source.s3Location.uri))return{type:"file",mimeType:r,fileId:e.document.source.s3Location.uri};if(af(e.document.source.bytes))return{type:"file",mimeType:r,data:e.document.source.bytes};if(z(e.document.source.text))return{type:"file",mimeType:r,data:Buffer.from(e.document.source.text).toString("base64")};if(qt(e.document.source.content)){let n=e.document.source.content.reduce((i,s)=>le(s)&&z(s.text)?i+s.text:i,"");return{type:"file",mimeType:r,data:n}}}}return{type:"non_standard",value:e}}function fF(e){if(re(e,"image")&&le(e.image)){let t=le(e.image)&&z(e.image.format)?e.image.format:"",r=av(t);if(le(e.image.source)){if(le(e.image.source.s3Location)&&z(e.image.source.s3Location.uri))return{type:"image",mimeType:r,fileId:e.image.source.s3Location.uri};if(af(e.image.source.bytes))return{type:"image",mimeType:r,data:e.image.source.bytes}}}return{type:"non_standard",value:e}}function mF(e){if(re(e,"video")&&le(e.video)){let t=le(e.video)&&z(e.video.format)?e.video.format:"",r=av(t);if(le(e.video.source)){if(le(e.video.source.s3Location)&&z(e.video.source.s3Location.uri))return{type:"video",mimeType:r,fileId:e.video.source.s3Location.uri};if(af(e.video.source.bytes))return{type:"video",mimeType:r,data:e.video.source.bytes}}}return{type:"non_standard",value:e}}function HO(e){function*t(){let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r){if(re(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(re(n,"citations_content")&&le(n.citationsContent)){let i=qt(n.citationsContent.content)?n.citationsContent.content.reduce((o,a)=>le(a)&&z(a.text)?o+a.text:o,""):"",s=qt(n.citationsContent.citations)?n.citationsContent.citations.reduce((o,a)=>{if(le(a)){let c=qt(a.sourceContent)?a.sourceContent.reduce((l,p)=>le(p)&&z(p.text)?l+p.text:l,""):"",u=ji(()=>{if(le(a.location)){let l=a.location.documentChar||a.location.documentPage||a.location.documentChunk;if(le(l))return{source:Ur(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:Ur(l.start)?l.start:void 0,endIndex:Ur(l.end)?l.end:void 0}}return{}});o.push({type:"citation",citedText:c,...u})}return o},[]):[];yield{type:"text",text:i,annotations:s};continue}else if(re(n,"document")&&le(n.document)){yield dF(n);continue}else if(re(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(re(n,"image")&&le(n.image)){yield fF(n);continue}else if(re(n,"reasoning_content")&&z(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(re(n,"text")&&z(n.text)){yield{type:"text",text:n.text};continue}else if(re(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(re(n,"tool_call"))continue;if(re(n,"video")&&le(n.video)){yield mF(n);continue}}yield{type:"non_standard",value:n}}}return Array.from(t())}var WO={translateContent:HO,translateContentChunk:HO};function JO(e){let t=[],r=e.additional_kwargs?.reasoning_content;if(z(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),typeof e.content=="string")e.content.length>0&&t.push({type:"text",text:e.content});else for(let n of e.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&z(n.text)&&t.push({type:"text",text:n.text});for(let n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}var XO={translateContent:JO,translateContentChunk:JO};function YO(e){function*t(){let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r){if(re(n,"text")&&z(n.text)){yield{type:"text",text:n.text};continue}else if(re(n,"thinking")&&z(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(re(n,"inlineData")&&le(n.inlineData)&&z(n.inlineData.mimeType)&&z(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(re(n,"functionCall")&&le(n.functionCall)&&z(n.functionCall.name)&&le(n.functionCall.args)){yield{type:"tool_call",id:e.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(re(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(re(n,"fileData")&&le(n.fileData)&&z(n.fileData.mimeType)&&z(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(re(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(re(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return Array.from(t())}var QO={translateContent:YO,translateContentChunk:YO};function e$(e){function*t(){let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r){if(re(n,"reasoning")&&z(n.reasoning)){let i=ji(()=>{let s=r.indexOf(n);if(qt(e.additional_kwargs?.signatures)&&s>=0)return e.additional_kwargs.signatures.at(s)});z(i)?yield{type:"reasoning",reasoning:n.reasoning,signature:i}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(re(n,"thinking")&&z(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(re(n,"text")&&z(n.text)){yield{type:"text",text:n.text};continue}else if(re(n,"image_url")){if(z(n.image_url))if(n.image_url.startsWith("data:")){let i=/^data:([^;]+);base64,(.+)$/,s=n.image_url.match(i);s?yield{type:"image",data:s[2],mimeType:s[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(re(n,"media")&&z(n.mimeType)&&z(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return Array.from(t())}var t$={translateContent:e$,translateContentChunk:e$};function r$(e){let t=[],r=e.additional_kwargs?.reasoning;if(z(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),typeof e.content=="string"){let n=e.content,i=n.match(/<think>([\s\S]*?)<\/think>/);if(i){let s=i[1].trim();s.length>0&&t.push({type:"reasoning",reasoning:s}),n=n.replace(/<think>[\s\S]*?<\/think>/,"").trim()}n.length>0&&t.push({type:"text",text:n})}else for(let n of e.content)if(typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&z(n.text)){let i=n.text,s=i.match(/<think>([\s\S]*?)<\/think>/);if(s){let o=s[1].trim();o.length>0&&t.push({type:"reasoning",reasoning:o}),i=i.replace(/<think>[\s\S]*?<\/think>/,"").trim()}i.length>0&&t.push({type:"text",text:i})}for(let n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}var n$={translateContent:r$,translateContentChunk:r$};function i$(e){let t=[],r=e.additional_kwargs?.reasoning_content;if(z(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),typeof e.content=="string")e.content.length>0&&t.push({type:"text",text:e.content});else for(let n of e.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&z(n.text)&&t.push({type:"text",text:n.text});for(let n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}var s$={translateContent:i$,translateContentChunk:i$};function o$(e){let t=[];if(le(e.additional_kwargs?.reasoning)){let n=e.additional_kwargs.reasoning;if(qt(n.summary)){let i=n.summary.reduce((s,o)=>le(o)&&z(o.text)?`${s}${o.text}`:s,"");i.length>0&&t.push({type:"reasoning",reasoning:i})}}let r=e.additional_kwargs?.reasoning_content;if(z(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),typeof e.content=="string")e.content.length>0&&t.push({type:"text",text:e.content});else for(let n of e.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&z(n.text)&&t.push({type:"text",text:n.text});for(let n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}var a$={translateContent:o$,translateContentChunk:o$};globalThis.lc_block_translators_registry??=new Map([["anthropic",Rk],["bedrock-converse",WO],["deepseek",XO],["google-genai",QO],["google-vertexai",t$],["groq",n$],["ollama",s$],["openai",Lk],["xai",a$]]);function cv(e){return globalThis.lc_block_translators_registry.get(e)}function Ms(e,t){return e.lc_error_code=t,e.message=`${e.message}
45
-
46
- Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/
47
- `,e}function js(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="tool_call")}function c$(e){return!!(e&&typeof e=="object"&&"toolCall"in e&&e.toolCall!=null&&typeof e.toolCall=="object"&&"id"in e.toolCall&&typeof e.toolCall.id=="string")}var hc=class extends Error{output;constructor(e,t){super(e),this.output=t}};function Al(e,t=ii){e=e.trim();let r=e.indexOf("```");if(r===-1)return t(e);let n=e.substring(r+3);n.startsWith(`json
48
- `)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
49
- `)&&(n=n.substring(1));let i=n.indexOf("```"),s=n;return i!==-1&&(s=n.substring(0,i)),t(s.trim())}function hF(e){try{return JSON.parse(e)}catch{}let t=e.trim();if(t.length===0)throw new Error("Unexpected end of JSON input");let r=0;function n(){for(;r<t.length&&/\s/.test(t[r]);)r+=1}function i(){if(t[r]!=='"')throw new Error(`Expected '"' at position ${r}, got '${t[r]}'`);r+=1;let l="",p=!1;for(;r<t.length;){let f=t[r];if(p){if(f==="n")l+=`
50
- `;else if(f==="t")l+=" ";else if(f==="r")l+="\r";else if(f==="\\")l+="\\";else if(f==='"')l+='"';else if(f==="b")l+="\b";else if(f==="f")l+="\f";else if(f==="/")l+="/";else if(f==="u"){let d=t.substring(r+1,r+5);if(/^[0-9A-Fa-f]{0,4}$/.test(d))d.length===4?l+=String.fromCharCode(Number.parseInt(d,16)):l+=`u${d}`,r+=d.length;else throw new Error(`Invalid unicode escape sequence '\\u${d}' at position ${r}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${r}`);p=!1}else if(f==="\\")p=!0;else{if(f==='"')return r+=1,l;l+=f}r+=1}return p&&(l+="\\"),l}function s(){let l=r,p="";if(t[r]==="-"&&(p+="-",r+=1),r<t.length&&t[r]==="0"&&(p+="0",r+=1,t[r]>="0"&&t[r]<="9"))throw new Error(`Invalid number at position ${l}`);if(r<t.length&&t[r]>="1"&&t[r]<="9")for(;r<t.length&&t[r]>="0"&&t[r]<="9";)p+=t[r],r+=1;if(r<t.length&&t[r]===".")for(p+=".",r+=1;r<t.length&&t[r]>="0"&&t[r]<="9";)p+=t[r],r+=1;if(r<t.length&&(t[r]==="e"||t[r]==="E"))for(p+=t[r],r+=1,r<t.length&&(t[r]==="+"||t[r]==="-")&&(p+=t[r],r+=1);r<t.length&&t[r]>="0"&&t[r]<="9";)p+=t[r],r+=1;if(p==="-")return-0;let f=Number.parseFloat(p);if(Number.isNaN(f))throw r=l,new Error(`Invalid number '${p}' at position ${l}`);return f}function o(){if(n(),r>=t.length)throw new Error(`Unexpected end of input at position ${r}`);let l=t[r];if(l==="{")return c();if(l==="[")return a();if(l==='"')return i();if("null".startsWith(t.substring(r,r+4)))return r+=Math.min(4,t.length-r),null;if("true".startsWith(t.substring(r,r+4)))return r+=Math.min(4,t.length-r),!0;if("false".startsWith(t.substring(r,r+5)))return r+=Math.min(5,t.length-r),!1;if(l==="-"||l>="0"&&l<="9")return s();throw new Error(`Unexpected character '${l}' at position ${r}`)}function a(){if(t[r]!=="[")throw new Error(`Expected '[' at position ${r}, got '${t[r]}'`);let l=[];if(r+=1,n(),r>=t.length)return l;if(t[r]==="]")return r+=1,l;for(;r<t.length;){if(n(),r>=t.length||(l.push(o()),n(),r>=t.length))return l;if(t[r]==="]")return r+=1,l;if(t[r]===","){r+=1;continue}throw new Error(`Expected ',' or ']' at position ${r}, got '${t[r]}'`)}return l}function c(){if(t[r]!=="{")throw new Error(`Expected '{' at position ${r}, got '${t[r]}'`);let l={};if(r+=1,n(),r>=t.length)return l;if(t[r]==="}")return r+=1,l;for(;r<t.length;){if(n(),r>=t.length)return l;let p=i();if(n(),r>=t.length)return l;if(t[r]!==":")throw new Error(`Expected ':' at position ${r}, got '${t[r]}'`);if(r+=1,n(),r>=t.length||(l[p]=o(),n(),r>=t.length))return l;if(t[r]==="}")return r+=1,l;if(t[r]===","){r+=1;continue}throw new Error(`Expected ',' or '}' at position ${r}, got '${t[r]}'`)}return l}let u=o();if(n(),r<t.length)throw new Error(`Unexpected character '${t[r]}' at position ${r}`);return u}function ii(e){try{return typeof e>"u"?null:hF(e)}catch{return null}}var mr=class u$ extends bt{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return u$}constructor(t,r){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:r}),super(t),this.role=t.role}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},Fi=class extends ur{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(e,t){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}concat(e){let t=this.constructor;return new t({content:Ht(this.content,e.content),additional_kwargs:st(this.additional_kwargs,e.additional_kwargs),response_metadata:st(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function l$(e){return e._getType()==="generic"}function p$(e){return e._getType()==="generic"}var zo=class extends bt{static lc_name(){return"FunctionMessage"}type="function";name;constructor(e){super(e),this.name=e.name}},Bi=class extends ur{static lc_name(){return"FunctionMessageChunk"}type="function";concat(e){let t=this.constructor;return new t({content:Ht(this.content,e.content),additional_kwargs:st(this.additional_kwargs,e.additional_kwargs),response_metadata:st(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function d$(e){return e._getType()==="function"}function f$(e){return e._getType()==="function"}var at=class extends bt{static lc_name(){return"HumanMessage"}type="human";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},Vi=class extends ur{static lc_name(){return"HumanMessageChunk"}type="human";constructor(e){super(e)}concat(e){let t=this.constructor;return new t({content:Ht(this.content,e.content),additional_kwargs:st(this.additional_kwargs,e.additional_kwargs),response_metadata:st(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="human"}};function m$(e){return e.getType()==="human"}function h$(e){return e.getType()==="human"}var Tn=class extends bt{type="remove";id;constructor(e){super({...e,content:[]}),this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type==="remove"}};var Br=class Kf extends bt{static lc_name(){return"SystemMessage"}type="system";constructor(t){super(t)}concat(t){if(typeof t=="string")return new Kf({...this,content:Ht(this.content,t)});if(Kf.isInstance(t))return new Kf({...this,additional_kwargs:{...this.additional_kwargs,...t.additional_kwargs},response_metadata:{...this.response_metadata,...t.response_metadata},content:Ht(this.content,t.content)});throw new Error("Unexpected chunk type for system message")}static isInstance(t){return super.isInstance(t)&&t.type==="system"}},un=class extends ur{static lc_name(){return"SystemMessageChunk"}type="system";constructor(e){super(e)}concat(e){let t=this.constructor;return new t({content:Ht(this.content,e.content),additional_kwargs:st(this.additional_kwargs,e.additional_kwargs),response_metadata:st(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="system"}};function g$(e){return e._getType()==="system"}function _$(e){return e._getType()==="system"}var qf=e=>e();function gF(e){return js(e)?e:typeof e.id=="string"&&e.type==="function"&&typeof e.function=="object"&&e.function!==null&&"arguments"in e.function&&typeof e.function.arguments=="string"&&"name"in e.function&&typeof e.function.name=="string"?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function _F(e){return typeof e=="object"&&e!=null&&e.lc===1&&Array.isArray(e.id)&&e.kwargs!=null&&typeof e.kwargs=="object"}function uv(e){let t,r;if(_F(e)){let n=e.id.at(-1);n==="HumanMessage"||n==="HumanMessageChunk"?t="user":n==="AIMessage"||n==="AIMessageChunk"?t="assistant":n==="SystemMessage"||n==="SystemMessageChunk"?t="system":n==="FunctionMessage"||n==="FunctionMessageChunk"?t="function":n==="ToolMessage"||n==="ToolMessageChunk"?t="tool":t="unknown",r=e.kwargs}else{let{type:n,...i}=e;t=n,r=i}if(t==="human"||t==="user")return new at(r);if(t==="ai"||t==="assistant"){let{tool_calls:n,...i}=r;if(!Array.isArray(n))return new $e(r);let s=n.map(gF);return new $e({...i,tool_calls:s})}else{if(t==="system")return new Br(r);if(t==="developer")return new Br({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if(t==="tool"&&"tool_call_id"in r)return new Wt({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});if(t==="remove"&&"id"in r&&typeof r.id=="string")return new Tn({...r,id:r.id});throw Ms(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
51
-
52
- Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Qt(e){if(typeof e=="string")return new at(e);if(ot(e))return e;if(Array.isArray(e)){let[t,r]=e;return uv({type:t,content:r})}else if(df(e)){let{role:t,...r}=e;return uv({...r,type:t})}else return uv(e)}function gc(e,t="Human",r="AI"){let n=[];for(let i of e){let s;if(i.type==="human")s=t;else if(i.type==="ai")s=r;else if(i.type==="system")s="System";else if(i.type==="tool")s="Tool";else if(i.type==="generic")s=i.role;else throw new Error(`Got unsupported message type: ${i.type}`);let o=i.name?`${i.name}, `:"",a=i.text,c=`${s}: ${o}${a}`;if(i.type==="ai"){let u=i;u.tool_calls&&u.tool_calls.length>0?c+=JSON.stringify(u.tool_calls):u.additional_kwargs&&"function_call"in u.additional_kwargs&&(c+=JSON.stringify(u.additional_kwargs.function_call))}n.push(c)}return n.join(`
53
- `)}function yF(e){if(e.data!==void 0)return e;{let t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}function Tl(e){let t=yF(e);switch(t.type){case"human":return new at(t.data);case"ai":return new $e(t.data);case"system":return new Br(t.data);case"function":if(t.data.name===void 0)throw new Error("Name must be defined for function messages");return new zo(t.data);case"tool":if(t.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new Wt(t.data);case"generic":if(t.data.role===void 0)throw new Error("Role must be defined for chat messages");return new mr(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function y$(e){return e.map(Tl)}function v$(e){return e.map(t=>t.toDict())}function Lo(e){let t=e._getType();if(t==="human")return new Vi({...e});if(t==="ai"){let r={...e};return"tool_calls"in r&&(r={...r,tool_call_chunks:r.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new nt({...r})}else{if(t==="system")return new un({...e});if(t==="function")return new Bi({...e});if(mr.isInstance(e))return new Fi({...e});throw new Error("Unknown message type.")}}function Hf(e){let t=e.reduce((i,s)=>{let o=i.findIndex(([a])=>"id"in s&&s.id&&"index"in s&&s.index!==void 0?s.id===a.id&&s.index===a.index:"id"in s&&s.id?s.id===a.id:"index"in s&&s.index!==void 0?s.index===a.index:!1);return o!==-1?i[o].push(s):i.push([s]),i},[]),r=[],n=[];for(let i of t){let s=null,o=i[0]?.name??"",a=i.map(l=>l.args||"").join("").trim(),c=a.length?a:"{}",u=i[0]?.id;try{if(s=ii(c),!u||s===null||typeof s!="object"||Array.isArray(s))throw new Error("Malformed tool call chunk args.");r.push({name:o,args:s,id:u,type:"tool_call"})}catch{n.push({name:o,args:c,id:u,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:e,tool_calls:r,invalid_tool_calls:n}}var $e=class extends bt{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e){let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;let r=t.additional_kwargs?.tool_calls,n=t.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
54
-
55
- Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&n===void 0){let[i,s]=pl(r);t.tool_calls=i??[],t.invalid_tool_calls=s??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(t.response_metadata!==void 0&&"output_version"in t.response_metadata&&t.response_metadata.output_version==="v1"&&(t.contentBlocks=t.content,t.content=void 0),t.contentBlocks!==void 0){t.tool_calls&&t.contentBlocks.push(...t.tool_calls.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})));let i=t.contentBlocks.filter(s=>s.type==="tool_call").filter(s=>!t.tool_calls?.some(o=>o.id===s.id&&o.name===s.name));i.length>0&&(t.tool_calls=i.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})))}}super(t),typeof t!="string"&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let t=cv(this.response_metadata.model_provider);if(t)return t.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls){let t=this.tool_calls.filter(r=>!e.some(n=>n.id===r.id&&n.name===r.name));e.push(...t.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};function si(e){return e._getType()==="ai"}function Ol(e){return e._getType()==="ai"}var nt=class extends ur{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(e){let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{let r=Hf(e.tool_call_chunks??[]);t={...e,tool_call_chunks:r.tool_call_chunks,tool_calls:r.tool_calls,invalid_tool_calls:r.invalid_tool_calls,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(t),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let t=cv(this.response_metadata.model_provider);if(t)return t.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){let t=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(let r of this.tool_calls)r.id&&!t.includes(r.id)&&e.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let t={content:Ht(this.content,e.content),additional_kwargs:st(this.additional_kwargs,e.additional_kwargs),response_metadata:Gf(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){let n=Ro(this.tool_call_chunks,e.tool_call_chunks);n!==void 0&&n.length>0&&(t.tool_call_chunks=n)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(t.usage_metadata=mc(this.usage_metadata,e.usage_metadata));let r=this.constructor;return new r(t)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};var lv,Wf=()=>{if(lv===void 0){let e=Je("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};lv=new Li(e)}return lv};var dv=class{getStore(){}run(t,r){return r()}},pv=Symbol.for("ls:tracing_async_local_storage"),vF=new dv,fv=class{getInstance(){return globalThis[pv]??vF}initializeGlobalInstance(t){globalThis[pv]===void 0&&(globalThis[pv]=t)}},bF=new fv;function b$(e=!1){let t=bF.getInstance().getStore();if(!e&&t===void 0)throw new Error(`Could not get the current run tree.
56
-
57
- Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return t}var MX=Symbol.for("langsmith:traceable:root");function Jf(e){return typeof e=="function"&&"langsmith:traceable"in e}var mv={};M(mv,{LangChainTracer:()=>$l});function wF(e){let t;for(let r of e)for(let n of r)$e.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(t=mc(t,n.message.usage_metadata));return t}var $l=class w$ extends Zt{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(t={}){super(t);let{exampleId:r,projectName:n,client:i,replicas:s}=t;this.projectName=n??fl(),this.replicas=s,this.exampleId=r,this.client=i??Wf();let o=w$.getTraceableRunTree();o&&this.updateFromRunTree(o)}async persistRun(t){}async onRunCreate(t){t.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(t.id)?.postRun()}async onRunUpdate(t){let r=this.getRunTreeWithTracingConfig(t.id);t.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun()}onLLMEnd(t){let r=t.outputs;if(r?.generations){let n=wF(r.generations);if(n!==void 0){t.extra=t.extra??{};let i=t.extra.metadata??{};i.usage_metadata=n,t.extra.metadata=i}}}getRun(t){return this.runTreeMap.get(t)}updateFromRunTree(t){this.runTreeMap.set(t.id,t);let r=t,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let i=[r];for(;i.length>0;){let s=i.shift();!s||n.has(s.id)||(n.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&i.push(...s.child_runs))}this.client=t.client??this.client,this.replicas=t.replicas??this.replicas,this.projectName=t.project_name??this.projectName,this.exampleId=t.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(t){let r=this.runTreeMap.get(t);if(r)return new An({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return b$(!0)}catch{return}}};var x$=Symbol.for("ls:tracing_async_local_storage"),Ds=Symbol.for("lc:context_variables"),I$=e=>{globalThis[x$]=e},zs=()=>globalThis[x$];var Xf=Cs(Sf(),1),Uo;function xF(){let e="default"in Xf.default?Xf.default.default:Xf.default;return new e({autoStart:!0,concurrency:1})}function IF(){return typeof Uo>"u"&&(Uo=xF()),Uo}async function ht(e,t){if(t===!0){let r=zs();r!==void 0?await r.run(void 0,async()=>e()):await e()}else Uo=IF(),Uo.add(async()=>{let r=zs();r!==void 0?await r.run(void 0,async()=>e()):await e()})}async function S$(){let e=Wf();await Promise.allSettled([typeof Uo<"u"?Uo.onIdle():Promise.resolve(),e.awaitPendingTraceBatches()])}var hv={};M(hv,{awaitAllCallbacks:()=>S$,consumeCallback:()=>ht});var E$=e=>e!==void 0?e:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>Je(r)==="true");function gv(e){let t=zs();return t===void 0?void 0:t.getStore()?.[Ds]?.[e]}var SF=Symbol("lc:configure_hooks"),k$=()=>gv(SF)||[];var yv={};M(yv,{BaseCallbackManager:()=>A$,BaseRunManager:()=>Pl,CallbackManager:()=>xt,CallbackManagerForChainRun:()=>O$,CallbackManagerForLLMRun:()=>_v,CallbackManagerForRetrieverRun:()=>T$,CallbackManagerForToolRun:()=>$$,ensureHandler:()=>_c,parseCallbackConfigArg:()=>Fo});function Fo(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}var A$=class{setHandler(e){return this.setHandlers([e])}},Pl=class{constructor(e,t,r,n,i,s,o,a){this.runId=e,this.handlers=t,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=i,this.metadata=s,this.inheritableMetadata=o,this._parentRunId=a}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>ht(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,n,i){await Promise.all(this.handlers.map(s=>ht(async()=>{try{await s.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}},T$=class extends Pl{getChild(e){let t=new xt(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>ht(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw r}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>ht(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}},t.awaitHandlers)))}},_v=class extends Pl{async handleLLMNewToken(e,t,r,n,i,s){await Promise.all(this.handlers.map(o=>ht(async()=>{if(!o.ignoreLLM)try{await o.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,s)}catch(a){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleLLMNewToken: ${a}`),o.raiseError)throw a}},o.awaitHandlers)))}async handleLLMError(e,t,r,n,i){await Promise.all(this.handlers.map(s=>ht(async()=>{if(!s.ignoreLLM)try{await s.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMError: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleLLMEnd(e,t,r,n,i){await Promise.all(this.handlers.map(s=>ht(async()=>{if(!s.ignoreLLM)try{await s.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMEnd: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}},O$=class extends Pl{getChild(e){let t=new xt(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,r,n,i){await Promise.all(this.handlers.map(s=>ht(async()=>{if(!s.ignoreChain)try{await s.handleChainError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainError: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleChainEnd(e,t,r,n,i){await Promise.all(this.handlers.map(s=>ht(async()=>{if(!s.ignoreChain)try{await s.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainEnd: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>ht(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>ht(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}},$$=class extends Pl{getChild(e){let t=new xt(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>ht(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>ht(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}},xt=class Cl extends A${handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(t,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=t}getParentRunId(){return this._parentRunId}async handleLLMStart(t,r,n=void 0,i=void 0,s=void 0,o=void 0,a=void 0,c=void 0){return Promise.all(r.map(async(u,l)=>{let p=l===0&&n?n:sn();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return Do(f)&&f._createRunForLLMStart(t,[u],p,this._parentRunId,s,this.tags,this.metadata,c),ht(async()=>{try{await f.handleLLMStart?.(t,[u],p,this._parentRunId,s,this.tags,this.metadata,c)}catch(d){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${d}`),f.raiseError)throw d}},f.awaitHandlers)})),new _v(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(t,r,n=void 0,i=void 0,s=void 0,o=void 0,a=void 0,c=void 0){return Promise.all(r.map(async(u,l)=>{let p=l===0&&n?n:sn();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return Do(f)&&f._createRunForChatModelStart(t,[u],p,this._parentRunId,s,this.tags,this.metadata,c),ht(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(t,[u],p,this._parentRunId,s,this.tags,this.metadata,c);else if(f.handleLLMStart){let d=gc(u);await f.handleLLMStart?.(t,[d],p,this._parentRunId,s,this.tags,this.metadata,c)}}catch(d){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${d}`),f.raiseError)throw d}},f.awaitHandlers)})),new _v(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(t,r,n=sn(),i=void 0,s=void 0,o=void 0,a=void 0,c=void 0,u=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreChain)return Do(l)&&l._createRunForChainStart(t,r,n,this._parentRunId,this.tags,this.metadata,i,a,u),ht(async()=>{try{await l.handleChainStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,i,a,u)}catch(p){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleChainStart: ${p}`),l.raiseError)throw p}},l.awaitHandlers)})),new O$(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(t,r,n=sn(),i=void 0,s=void 0,o=void 0,a=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return Do(c)&&c._createRunForToolStart(t,r,n,this._parentRunId,this.tags,this.metadata,a),ht(async()=>{try{await c.handleToolStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,a)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleToolStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new $$(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(t,r,n=sn(),i=void 0,s=void 0,o=void 0,a=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return Do(c)&&c._createRunForRetrieverStart(t,r,n,this._parentRunId,this.tags,this.metadata,a),ht(async()=>{try{await c.handleRetrieverStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,a)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new T$(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(t,r,n,i,s){await Promise.all(this.handlers.map(o=>ht(async()=>{if(!o.ignoreCustomEvent)try{await o.handleCustomEvent?.(t,r,n,this.tags,this.metadata)}catch(a){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleCustomEvent: ${a}`),o.raiseError)throw a}},o.awaitHandlers)))}addHandler(t,r=!0){this.handlers.push(t),r&&this.inheritableHandlers.push(t)}removeHandler(t){this.handlers=this.handlers.filter(r=>r!==t),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==t)}setHandlers(t,r=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of t)this.addHandler(n,r)}addTags(t,r=!0){this.removeTags(t),this.tags.push(...t),r&&this.inheritableTags.push(...t)}removeTags(t){this.tags=this.tags.filter(r=>!t.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!t.includes(r))}addMetadata(t,r=!0){this.metadata={...this.metadata,...t},r&&(this.inheritableMetadata={...this.inheritableMetadata,...t})}removeMetadata(t){for(let r of Object.keys(t))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(t=[],r=!0){let n=new Cl(this._parentRunId);for(let i of this.handlers){let s=this.inheritableHandlers.includes(i);n.addHandler(i,s)}for(let i of this.tags){let s=this.inheritableTags.includes(i);n.addTags([i],s)}for(let i of Object.keys(this.metadata)){let s=Object.keys(this.inheritableMetadata).includes(i);n.addMetadata({[i]:this.metadata[i]},s)}for(let i of t)n.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===i.name)||n.addHandler(i,r);return n}static fromHandlers(t){class r extends zi{name=sn();constructor(){super(),Object.assign(this,t)}}let n=new this;return n.addHandler(new r),n}static configure(t,r,n,i,s,o,a){return this._configureSync(t,r,n,i,s,o,a)}static _configureSync(t,r,n,i,s,o,a){let c;(t||r)&&(Array.isArray(t)||!t?(c=new Cl,c.setHandlers(t?.map(_c)??[],!0)):c=t,c=c.copy(Array.isArray(r)?r.map(_c):r?.handlers,!1));let u=Je("LANGCHAIN_VERBOSE")==="true"||a?.verbose,l=$l.getTraceableRunTree()?.tracingEnabled??E$(),p=l||(Je("LANGCHAIN_TRACING")??!1);if(u||p){if(c||(c=new Cl),u&&!c.handlers.some(f=>f.name===Zf.prototype.name)){let f=new Zf;c.addHandler(f,!0)}if(p&&!c.handlers.some(f=>f.name==="langchain_tracer")&&l){let f=new $l;c.addHandler(f,!0)}if(l){let f=$l.getTraceableRunTree();f&&c._parentRunId===void 0&&(c._parentRunId=f.id,c.handlers.find(m=>m.name==="langchain_tracer")?.updateFromRunTree(f))}}for(let{contextVar:f,inheritable:d=!0,handlerClass:m,envVar:h}of k$()){let b=h&&Je(h)==="true"&&m,_,y=f!==void 0?gv(f):void 0;y&&ty(y)?_=y:b&&(_=new m({})),_!==void 0&&(c||(c=new Cl),c.handlers.some(x=>x.name===_.name)||c.addHandler(_,d))}return(n||i)&&c&&(c.addTags(n??[]),c.addTags(i??[],!1)),(s||o)&&c&&(c.addMetadata(s??{}),c.addMetadata(o??{},!1)),c}};function _c(e){return"name"in e?e:zi.fromMethods(e)}var vv=class{getStore(){}run(e,t){return t()}enterWith(e){}},EF=new vv,C$=Symbol.for("lc:child_config"),kF=class{getInstance(){return zs()??EF}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[C$]}runWithConfig(e,t,r){let n=xt._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),i=this.getInstance(),s=i.getStore(),o=n?.getParentRunId(),a=n?.handlers?.find(u=>u?.name==="langchain_tracer"),c;return a&&o?c=a.getRunTreeWithTracingConfig(o):r||(c=new An({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[C$]:e}),s!==void 0&&s[Ds]!==void 0&&(c===void 0&&(c={}),c[Ds]=s[Ds]),i.run(c,t)}initializeGlobalInstance(e){zs()===void 0&&I$(e)}},Ze=new kF;var bv={};M(bv,{AsyncLocalStorageProviderSingleton:()=>Ze,MockAsyncLocalStorage:()=>vv,_CONTEXT_VARIABLES_KEY:()=>Ds});var Yf=25;async function Et(e){return xt._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function Dt(...e){let t={};for(let r of e.filter(n=>!!n))for(let n of Object.keys(r))if(n==="metadata")t[n]={...t[n],...r[n]};else if(n==="tags"){let i=t[n]??[];t[n]=[...new Set(i.concat(r[n]??[]))]}else if(n==="configurable")t[n]={...t[n],...r[n]};else if(n==="timeout")t.timeout===void 0?t.timeout=r.timeout:r.timeout!==void 0&&(t.timeout=Math.min(t.timeout,r.timeout));else if(n==="signal")t.signal===void 0?t.signal=r.signal:r.signal!==void 0&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if(n==="callbacks"){let i=t.callbacks,s=r.callbacks;if(Array.isArray(s))if(!i)t.callbacks=s;else if(Array.isArray(i))t.callbacks=i.concat(s);else{let o=i.copy();for(let a of s)o.addHandler(_c(a),!0);t.callbacks=o}else if(s)if(!i)t.callbacks=s;else if(Array.isArray(i)){let o=s.copy();for(let a of i)o.addHandler(_c(a),!0);t.callbacks=o}else t.callbacks=new xt(s._parentRunId,{handlers:i.handlers.concat(s.handlers),inheritableHandlers:i.inheritableHandlers.concat(s.inheritableHandlers),tags:Array.from(new Set(i.tags.concat(s.tags))),inheritableTags:Array.from(new Set(i.inheritableTags.concat(s.inheritableTags))),metadata:{...i.metadata,...s.metadata}})}else{let i=n;t[i]=r[i]??t[i]}return t}var AF=new Set(["string","number","boolean"]);function Ce(e){let t=Ze.getRunnableConfig(),r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){let{runId:n,runName:i,...s}=t;r=Object.entries(s).reduce((o,[a,c])=>(c!==void 0&&(o[a]=c),o),r)}if(e&&(r=Object.entries(e).reduce((n,[i,s])=>(s!==void 0&&(n[i]=s),n),r)),r?.configurable)for(let n of Object.keys(r.configurable))AF.has(typeof r.configurable[n])&&!r.metadata?.[n]&&(r.metadata||(r.metadata={}),r.metadata[n]=r.configurable[n]);if(r.timeout!==void 0){if(r.timeout<=0)throw new Error("Timeout must be a positive number");let n=r.timeout,i=AbortSignal.timeout(n);r.metadata||(r.metadata={}),r.metadata.timeoutMs===void 0&&(r.metadata.timeoutMs=n),r.signal!==void 0?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,i])):r.signal=i,delete r.timeout}return r}function Ne(e={},{callbacks:t,maxConcurrency:r,recursionLimit:n,runName:i,configurable:s,runId:o}={}){let a=Ce(e);return t!==void 0&&(delete a.runName,a.callbacks=t),n!==void 0&&(a.recursionLimit=n),r!==void 0&&(a.maxConcurrency=r),i!==void 0&&(a.runName=i),s!==void 0&&(a.configurable={...a.configurable,...s}),o!==void 0&&delete a.runId,a}function hr(e){if(e)return{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal,store:e.store}}async function ln(e,t){if(t===void 0)return e;let r;return Promise.race([e.catch(n=>{if(!t?.aborted)throw n}),new Promise((n,i)=>{r=()=>{i(Ls(t))},t.addEventListener("abort",r),t.aborted&&i(Ls(t))})]).finally(()=>t.removeEventListener("abort",r))}function Ls(e){return e?.reason instanceof Error?e.reason:typeof e?.reason=="string"?new Error(e.reason):new Error("Aborted")}var xv={};M(xv,{AsyncGeneratorWithSetup:()=>Us,IterableReadableStream:()=>kt,atee:()=>Qf,concat:()=>Vr,pipeGeneratorWithSetup:()=>Iv});var kt=class wv extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let t=await this.reader.read();return t.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:t.value}}catch(t){throw this.reader.releaseLock(),t}}async return(){if(this.ensureReader(),this.locked){let t=this.reader.cancel();this.reader.releaseLock(),await t}return{done:!0,value:void 0}}async throw(t){if(this.ensureReader(),this.locked){let r=this.reader.cancel();this.reader.releaseLock(),await r}throw t}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){let r=t.getReader();return new wv({start(n){return i();function i(){return r.read().then(({done:s,value:o})=>{if(s){n.close();return}return n.enqueue(o),i()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(t){return new wv({async pull(r){let{value:n,done:i}=await t.next();i&&r.close(),r.enqueue(n)},async cancel(r){await t.return(r)}})}};function Qf(e,t=2){let r=Array.from({length:t},()=>[]);return r.map(async function*(i){for(;;)if(i.length===0){let s=await e.next();for(let o of r)o.push(s)}else{if(i[0].done)return;yield i.shift().value}})}function Vr(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e=="string"&&typeof t=="string")return e+t;if(typeof e=="number"&&typeof t=="number")return e+t;if("concat"in e&&typeof e.concat=="function")return e.concat(t);if(typeof e=="object"&&typeof t=="object"){let r={...e};for(let[n,i]of Object.entries(t))n in r&&!Array.isArray(r[n])?r[n]=Vr(r[n],i):r[n]=i;return r}else throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var Us=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,r)=>{Ze.runWithConfig(hr(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(n=>t(void 0),r)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?Ze.runWithConfig(hr(this.config),this.signal?async()=>ln(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function Iv(e,t,r,n,...i){let s=new Us({generator:t,startSetup:r,signal:n}),o=await s.setup;return{output:e(s,o,...i),setup:o}}var TF=Object.prototype.hasOwnProperty;function tm(e,t){return TF.call(e,t)}function rm(e){if(Array.isArray(e)){let r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)tm(e,r)&&t.push(r);return t}function gr(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function nm(e){let t=0,r=e.length,n;for(;t<r;){if(n=e.charCodeAt(t),n>=48&&n<=57){t++;continue}return!1}return!0}function Zi(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function im(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function em(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let r=0,n=e.length;r<n;r++)if(em(e[r]))return!0}else if(typeof e=="object"){let r=rm(e),n=r.length;for(var t=0;t<n;t++)if(em(e[r[t]]))return!0}}return!1}function P$(e,t){let r=[e];for(let n in t){let i=typeof t[n]=="object"?JSON.stringify(t[n],null,2):t[n];typeof i<"u"&&r.push(`${n}: ${i}`)}return r.join(`
58
- `)}var sm=class extends Error{constructor(e,t,r,n,i){super(P$(e,{name:t,index:r,operation:n,tree:i})),this.name=t,this.index=r,this.operation=n,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=P$(e,{name:t,index:r,operation:n,tree:i})}};var Ev={};M(Ev,{JsonPatchError:()=>gt,_areEquals:()=>Nl,applyOperation:()=>Bo,applyPatch:()=>Fs,applyReducer:()=>CF,deepClone:()=>OF,getValueByPointer:()=>om,validate:()=>N$,validator:()=>am});var gt=sm,OF=gr;function Sv(e){return Object.getOwnPropertyNames(Object.prototype).includes(e)}var yc={add:function(e,t,r){if(Sv(t))throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){if(Sv(t))throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");var n=e[t];return delete e[t],{newDocument:r,removed:n}},replace:function(e,t,r){if(Sv(t))throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:function(e,t,r){let n=om(r,this.path);n&&(n=gr(n));let i=Bo(r,{op:"remove",path:this.from}).removed;return Bo(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(e,t,r){let n=om(r,this.from);return Bo(r,{op:"add",path:this.path,value:gr(n)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:Nl(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}},$F={add:function(e,t,r){return nm(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:r,index:t}},remove:function(e,t,r){var n=e.splice(t,1);return{newDocument:r,removed:n[0]}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:yc.move,copy:yc.copy,test:yc.test,_get:yc._get};function om(e,t){if(t=="")return e;var r={op:"_get",path:t};return Bo(e,r),r.value}function Bo(e,t,r=!1,n=!0,i=!0,s=0){if(r&&(typeof r=="function"?r(t,0,e,t.path):am(t,0)),t.path===""){let o={newDocument:e};if(t.op==="add")return o.newDocument=t.value,o;if(t.op==="replace")return o.newDocument=t.value,o.removed=e,o;if(t.op==="move"||t.op==="copy")return o.newDocument=om(e,t.from),t.op==="move"&&(o.removed=e),o;if(t.op==="test"){if(o.test=Nl(e,t.value),o.test===!1)throw new gt("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return o.newDocument=e,o}else{if(t.op==="remove")return o.removed=e,o.newDocument=null,o;if(t.op==="_get")return t.value=e,o;if(r)throw new gt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,t,e);return o}}else{n||(e=gr(e));let a=(t.path||"").split("/"),c=e,u=1,l=a.length,p,f,d;for(typeof r=="function"?d=r:d=am;;){if(f=a[u],f&&f.indexOf("~")!=-1&&(f=im(f)),i&&(f=="__proto__"||f=="prototype"&&u>0&&a[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&p===void 0&&(c[f]===void 0?p=a.slice(0,u).join("/"):u==l-1&&(p=t.path),p!==void 0&&d(t,0,e,p)),u++,Array.isArray(c)){if(f==="-")f=c.length;else{if(r&&!nm(f))throw new gt("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,t,e);nm(f)&&(f=~~f)}if(u>=l){if(r&&t.op==="add"&&f>c.length)throw new gt("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,t,e);let m=$F[t.op].call(t,c,f,e);if(m.test===!1)throw new gt("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return m}}else if(u>=l){let m=yc[t.op].call(t,c,f,e);if(m.test===!1)throw new gt("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return m}if(c=c[f],r&&u<l&&(!c||typeof c!="object"))throw new gt("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,t,e)}}}function Fs(e,t,r,n=!0,i=!0){if(r&&!Array.isArray(t))throw new gt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(e=gr(e));let s=new Array(t.length);for(let o=0,a=t.length;o<a;o++)s[o]=Bo(e,t[o],r,!0,i,o),e=s[o].newDocument;return s.newDocument=e,s}function CF(e,t,r){let n=Bo(e,t);if(n.test===!1)throw new gt("Test operation failed","TEST_OPERATION_FAILED",r,t,e);return n.newDocument}function am(e,t,r,n){if(typeof e!="object"||e===null||Array.isArray(e))throw new gt("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(yc[e.op]){if(typeof e.path!="string")throw new gt("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new gt('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new gt("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new gt("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&em(e.value))throw new gt("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r){if(e.op=="add"){var i=e.path.split("/").length,s=n.split("/").length;if(i!==s+1&&i!==s)throw new gt("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==n)throw new gt("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if(e.op==="move"||e.op==="copy"){var o={op:"_get",path:e.from,value:void 0},a=N$([o],r);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new gt("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}}else throw new gt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r)}function N$(e,t,r){try{if(!Array.isArray(e))throw new gt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)Fs(gr(t),gr(e),r||!0);else{r=r||am;for(var n=0;n<e.length;n++)r(e[n],n,t,void 0)}}catch(i){if(i instanceof gt)return i;throw i}}function Nl(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var r=Array.isArray(e),n=Array.isArray(t),i,s,o;if(r&&n){if(s=e.length,s!=t.length)return!1;for(i=s;i--!==0;)if(!Nl(e[i],t[i]))return!1;return!0}if(r!=n)return!1;var a=Object.keys(e);if(s=a.length,s!==Object.keys(t).length)return!1;for(i=s;i--!==0;)if(!t.hasOwnProperty(a[i]))return!1;for(i=s;i--!==0;)if(o=a[i],!Nl(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}function R$(e,t,r,n,i){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var s=rm(t),o=rm(e),a=!1,c=!1,u=o.length-1;u>=0;u--){var l=o[u],p=e[l];if(tm(t,l)&&!(t[l]===void 0&&p!==void 0&&Array.isArray(t)===!1)){var f=t[l];typeof p=="object"&&p!=null&&typeof f=="object"&&f!=null&&Array.isArray(p)===Array.isArray(f)?R$(p,f,r,n+"/"+Zi(l),i):p!==f&&(a=!0,i&&r.push({op:"test",path:n+"/"+Zi(l),value:gr(p)}),r.push({op:"replace",path:n+"/"+Zi(l),value:gr(f)}))}else Array.isArray(e)===Array.isArray(t)?(i&&r.push({op:"test",path:n+"/"+Zi(l),value:gr(p)}),r.push({op:"remove",path:n+"/"+Zi(l)}),c=!0):(i&&r.push({op:"test",path:n,value:e}),r.push({op:"replace",path:n,value:t}),a=!0)}if(!(!c&&s.length==o.length))for(var u=0;u<s.length;u++){var l=s[u];!tm(e,l)&&t[l]!==void 0&&r.push({op:"add",path:n+"/"+Zi(l),value:gr(t[l])})}}}function Bs(e,t,r=!1){var n=[];return R$(e,t,n,"",r),n}var dQ={...Ev,JsonPatchError:sm,deepClone:gr,escapePathComponent:Zi,unescapePathComponent:im};var Av={};M(Av,{LogStreamCallbackHandler:()=>um,RunLog:()=>cm,RunLogPatch:()=>oi,isLogStreamHandler:()=>Tv});var oi=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),r=Fs({},t);return new cm({ops:t,state:r[r.length-1].newDocument})}},cm=class kv extends oi{state;constructor(t){super(t),this.state=t.state}concat(t){let r=this.ops.concat(t.ops),n=Fs(this.state,t.ops);return new kv({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(t){let r=Fs({},t.ops);return new kv({ops:t.ops,state:r[r.length-1].newDocument})}},Tv=e=>e.name==="log_stream_tracer";async function M$(e,t){if(t==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");let{inputs:r}=e;if(["retriever","llm","prompt"].includes(e.run_type))return r;if(!(Object.keys(r).length===1&&r?.input===""))return r.input}async function j$(e,t){let{outputs:r}=e;return t==="original"||["retriever","llm","prompt"].includes(e.run_type)?r:r!==void 0&&Object.keys(r).length===1&&r?.output!==void 0?r.output:r}function PF(e){return e!==void 0&&e.message!==void 0}var um=class extends Zt{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=kt.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(r=r||t.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(r=r&&t.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(e,t){for await(let r of t){if(e!==this.rootId){let n=this.keyMapByRunId[e];n&&await this.writer.write(new oi({ops:[{op:"add",path:`/logs/${n}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new oi({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;let r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await M$(e,this._schemaFormat)),await this.writer.write(new oi({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(t===void 0)return;let r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await M$(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await j$(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let n=new oi({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){let t=new oi({ops:[{op:"replace",path:"/final_output",value:await j$(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){let n=this.keyMapByRunId[e.id];if(n===void 0)return;let i=e.inputs.messages!==void 0,s;i?PF(r?.chunk)?s=r?.chunk:s=new nt({id:`run-${e.id}`,content:t}):s=t;let o=new oi({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${n}/streamed_output/-`,value:s}]});await this.writer.write(o)}};var Ov={};M(Ov,{ChatGenerationChunk:()=>Zr,GenerationChunk:()=>ai,RUN_KEY:()=>Vo});var Vo="__run",ai=class D${text;generationInfo;constructor(t){this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new D$({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},Zr=class z$ extends ai{message;constructor(t){super(t),this.message=t.message}concat(t){return new z$({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};var NF=Object.prototype.toString,RF=e=>NF.call(e)==="[object Error]",MF=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function L$(e){if(!(e&&RF(e)&&e.name==="TypeError"&&typeof e.message=="string"))return!1;let{message:r,stack:n}=e;return r==="Load failed"?n===void 0||"__sentry_captured__"in e:r.startsWith("error sending request for url")?!0:MF.has(r)}function jF(e){if(typeof e=="number"){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function lm(e,t,{min:r=0,allowInfinity:n=!1}={}){if(t!==void 0){if(typeof t!="number"||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<r)throw new TypeError(`Expected \`${e}\` to be \u2265 ${r}.`)}}var DF=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function zF(e,t){let r=Math.max(1,e+1),n=t.randomize?Math.random()+1:1,i=Math.round(n*t.minTimeout*t.factor**(r-1));return i=Math.min(i,t.maxTimeout),i}function U$(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function LF({error:e,attemptNumber:t,retriesConsumed:r,startTime:n,options:i}){let s=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(s instanceof DF)throw s.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,a=i.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:s,attemptNumber:t,retriesLeft:o,retriesConsumed:r});if(await i.onFailedAttempt(c),U$(n,a)<=0)throw s;let u=await i.shouldConsumeRetry(c),l=U$(n,a);if(l<=0||o<=0)throw s;if(s instanceof TypeError&&!L$(s)){if(u)throw s;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw s;if(!u)return i.signal?.throwIfAborted(),!1;let p=zF(r,i),f=Math.min(p,l);return f>0&&await new Promise((d,m)=>{let h=()=>{clearTimeout(b),i.signal?.removeEventListener("abort",h),m(i.signal.reason)},b=setTimeout(()=>{i.signal?.removeEventListener("abort",h),d()},f);i.unref&&b.unref?.(),i.signal?.addEventListener("abort",h,{once:!0})}),i.signal?.throwIfAborted(),!0}async function Rl(e,t={}){if(t={...t},jF(t.retries),Object.hasOwn(t,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=Number.POSITIVE_INFINITY,t.maxRetryTime??=Number.POSITIVE_INFINITY,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,lm("factor",t.factor,{min:0,allowInfinity:!1}),lm("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),lm("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),lm("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let r=0,n=0,i=performance.now();for(;!Number.isFinite(t.retries)||n<=t.retries;){r++;try{t.signal?.throwIfAborted();let s=await e(r);return t.signal?.throwIfAborted(),s}catch(s){await LF({error:s,attemptNumber:r,retriesConsumed:n,startTime:i,options:t})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var pm=Cs(Sf(),1),$v={};M($v,{AsyncCaller:()=>Gi});var UF=[400,401,402,403,404,405,406,407,409],FF=e=>{if(typeof e!="object"||e===null)return;if("message"in e&&typeof e.message=="string"&&(e.message.startsWith("Cancel")||e.message.startsWith("AbortError"))||"name"in e&&typeof e.name=="string"&&e.name==="AbortError"||"code"in e&&typeof e.code=="string"&&e.code==="ECONNABORTED")throw e;let t="response"in e&&typeof e.response=="object"&&e.response!==null&&"status"in e.response&&typeof e.response.status=="number"?e.response.status:void 0,r="status"in e&&typeof e.status=="number"?e.status:void 0,n=t??r;if(n&&UF.includes(+n))throw e;if(("error"in e&&typeof e.error=="object"&&e.error!==null&&"code"in e.error&&typeof e.error.code=="string"?e.error.code:void 0)==="insufficient_quota"){let s=new Error("message"in e&&typeof e.message=="string"?e.message:"Insufficient quota");throw s.name="InsufficientQuotaError",s}},Gi=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??FF;let t="default"in pm.default?pm.default.default:pm.default;this.queue=new t({concurrency:this.maxConcurrency})}async call(e,...t){return this.queue.add(()=>Rl(()=>e(...t).catch(r=>{throw r instanceof Error?r:new Error(r)}),{onFailedAttempt:({error:r})=>this.onFailedAttempt?.(r),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){if(e.signal){let n;return Promise.race([this.call(t,...r),new Promise((i,s)=>{n=()=>{s(Ls(e.signal))},e.signal?.addEventListener("abort",n)})]).finally(()=>{e.signal&&n&&e.signal.removeEventListener("abort",n)})}return this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}};var Ji={};$s(Ji,{$ZodAny:()=>vw,$ZodArray:()=>Wl,$ZodAsyncError:()=>ci,$ZodBase64:()=>uw,$ZodBase64URL:()=>lw,$ZodBigInt:()=>Im,$ZodBigIntFormat:()=>hw,$ZodBoolean:()=>ql,$ZodCIDRv4:()=>ow,$ZodCIDRv6:()=>aw,$ZodCUID:()=>Wb,$ZodCUID2:()=>Jb,$ZodCatch:()=>jw,$ZodCheck:()=>pt,$ZodCheckBigIntFormat:()=>Eb,$ZodCheckEndsWith:()=>Db,$ZodCheckGreaterThan:()=>vm,$ZodCheckIncludes:()=>Mb,$ZodCheckLengthEquals:()=>Cb,$ZodCheckLessThan:()=>ym,$ZodCheckLowerCase:()=>Nb,$ZodCheckMaxLength:()=>Ob,$ZodCheckMaxSize:()=>kb,$ZodCheckMimeType:()=>Lb,$ZodCheckMinLength:()=>$b,$ZodCheckMinSize:()=>Ab,$ZodCheckMultipleOf:()=>Ib,$ZodCheckNumberFormat:()=>Sb,$ZodCheckOverwrite:()=>Ub,$ZodCheckProperty:()=>zb,$ZodCheckRegex:()=>Pb,$ZodCheckSizeEquals:()=>Tb,$ZodCheckStartsWith:()=>jb,$ZodCheckStringFormat:()=>xc,$ZodCheckUpperCase:()=>Rb,$ZodCustom:()=>Bw,$ZodCustomStringFormat:()=>fw,$ZodDate:()=>ww,$ZodDefault:()=>Pw,$ZodDiscriminatedUnion:()=>Iw,$ZodE164:()=>pw,$ZodEmail:()=>Gb,$ZodEmoji:()=>qb,$ZodEnum:()=>Tw,$ZodError:()=>Vl,$ZodFile:()=>$w,$ZodFunction:()=>Hm,$ZodGUID:()=>Vb,$ZodIPv4:()=>iw,$ZodIPv6:()=>sw,$ZodISODate:()=>tw,$ZodISODateTime:()=>ew,$ZodISODuration:()=>nw,$ZodISOTime:()=>rw,$ZodIntersection:()=>Sw,$ZodJWT:()=>dw,$ZodKSUID:()=>Qb,$ZodLazy:()=>Fw,$ZodLiteral:()=>Ow,$ZodMap:()=>kw,$ZodNaN:()=>Dw,$ZodNanoID:()=>Hb,$ZodNever:()=>Hl,$ZodNonOptional:()=>Rw,$ZodNull:()=>yw,$ZodNullable:()=>Cw,$ZodNumber:()=>xm,$ZodNumberFormat:()=>mw,$ZodObject:()=>xw,$ZodOptional:()=>Ic,$ZodPipe:()=>Xl,$ZodPrefault:()=>Nw,$ZodPromise:()=>Uw,$ZodReadonly:()=>zw,$ZodRealError:()=>wc,$ZodRecord:()=>Ew,$ZodRegistry:()=>Sc,$ZodSet:()=>Aw,$ZodString:()=>Wo,$ZodStringFormat:()=>He,$ZodSuccess:()=>Mw,$ZodSymbol:()=>gw,$ZodTemplateLiteral:()=>Lw,$ZodTransform:()=>Jl,$ZodTuple:()=>Jo,$ZodType:()=>ye,$ZodULID:()=>Xb,$ZodURL:()=>Kb,$ZodUUID:()=>Zb,$ZodUndefined:()=>_w,$ZodUnion:()=>Sm,$ZodUnknown:()=>Zs,$ZodVoid:()=>bw,$ZodXID:()=>Yb,$brand:()=>Pv,$constructor:()=>S,$input:()=>Zw,$output:()=>Vw,Doc:()=>Kl,JSONSchema:()=>WC,JSONSchemaGenerator:()=>mp,NEVER:()=>Cv,TimePrecision:()=>qw,_any:()=>mx,_array:()=>fp,_base64:()=>Zm,_base64url:()=>Gm,_bigint:()=>ax,_boolean:()=>sx,_catch:()=>vB,_cidrv4:()=>Bm,_cidrv6:()=>Vm,_coercedBigint:()=>cx,_coercedBoolean:()=>ox,_coercedDate:()=>_x,_coercedNumber:()=>Qw,_coercedString:()=>Kw,_cuid:()=>Mm,_cuid2:()=>jm,_custom:()=>kx,_date:()=>gx,_default:()=>gB,_discriminatedUnion:()=>sB,_e164:()=>Km,_email:()=>Am,_emoji:()=>Nm,_endsWith:()=>ap,_enum:()=>lB,_file:()=>Ex,_float32:()=>tx,_float64:()=>rx,_gt:()=>Hi,_gte:()=>Pr,_guid:()=>Ql,_includes:()=>sp,_int:()=>ex,_int32:()=>nx,_int64:()=>ux,_intersection:()=>oB,_ipv4:()=>Um,_ipv6:()=>Fm,_isoDate:()=>Ww,_isoDateTime:()=>Hw,_isoDuration:()=>Xw,_isoTime:()=>Jw,_jwt:()=>qm,_ksuid:()=>Lm,_lazy:()=>IB,_length:()=>Ac,_literal:()=>dB,_lowercase:()=>np,_lt:()=>qi,_lte:()=>pn,_map:()=>cB,_max:()=>pn,_maxLength:()=>kc,_maxSize:()=>Ec,_mime:()=>cp,_min:()=>Pr,_minLength:()=>Ks,_minSize:()=>Yo,_multipleOf:()=>Xo,_nan:()=>yx,_nanoid:()=>Rm,_nativeEnum:()=>pB,_negative:()=>bx,_never:()=>ep,_nonnegative:()=>xx,_nonoptional:()=>_B,_nonpositive:()=>wx,_normalize:()=>up,_null:()=>fx,_nullable:()=>hB,_number:()=>Yw,_optional:()=>mB,_overwrite:()=>Wi,_parse:()=>fm,_parseAsync:()=>mm,_pipe:()=>bB,_positive:()=>vx,_promise:()=>SB,_property:()=>Ix,_readonly:()=>wB,_record:()=>aB,_refine:()=>Ax,_regex:()=>rp,_safeParse:()=>hm,_safeParseAsync:()=>gm,_set:()=>uB,_size:()=>tp,_startsWith:()=>op,_string:()=>Gw,_stringFormat:()=>Ox,_stringbool:()=>Tx,_success:()=>yB,_symbol:()=>px,_templateLiteral:()=>xB,_toLowerCase:()=>pp,_toUpperCase:()=>dp,_transform:()=>fB,_trim:()=>lp,_tuple:()=>Sx,_uint32:()=>ix,_uint64:()=>lx,_ulid:()=>Dm,_undefined:()=>dx,_union:()=>iB,_unknown:()=>Gs,_uppercase:()=>ip,_url:()=>Pm,_uuid:()=>Tm,_uuidv4:()=>Om,_uuidv6:()=>$m,_uuidv7:()=>Cm,_void:()=>hx,_xid:()=>zm,clone:()=>lt,config:()=>At,flattenError:()=>Zl,formatError:()=>Gl,function:()=>$x,globalConfig:()=>Ml,globalRegistry:()=>ct,isValidBase64:()=>cw,isValidBase64URL:()=>oC,isValidJWT:()=>aC,locales:()=>Yl,parse:()=>ui,parseAsync:()=>Ko,prettifyError:()=>Gv,regexes:()=>Ho,registry:()=>km,safeParse:()=>Kv,safeParseAsync:()=>qv,toDotPath:()=>B$,toJSONSchema:()=>qs,treeifyError:()=>Zv,util:()=>G,version:()=>Fb});var Cv=Object.freeze({status:"aborted"});function S(e,t,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(e),t(a,c);for(let l in o.prototype)l in a||Object.defineProperty(a,l,{value:o.prototype[l].bind(a)});a._zod.constr=o,a._zod.def=c}let i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:e});function o(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var Pv=Symbol("zod_brand"),ci=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ml={};function At(e){return e&&Object.assign(Ml,e),Ml}var G={};$s(G,{BIGINT_FORMAT_RANGES:()=>Bv,Class:()=>Rv,NUMBER_FORMAT_RANGES:()=>Fv,aborted:()=>Go,allowsEval:()=>zv,assert:()=>KF,assertEqual:()=>BF,assertIs:()=>ZF,assertNever:()=>GF,assertNotEqual:()=>VF,assignProp:()=>Dv,cached:()=>zl,captureStackTrace:()=>dm,cleanEnum:()=>s6,cleanRegex:()=>Ll,clone:()=>lt,createTransparentProxy:()=>YF,defineLazy:()=>Fe,esc:()=>Zo,escapeRegex:()=>Ki,extend:()=>t6,finalizeIssue:()=>Gr,floatSafeRemainder:()=>jv,getElementAtPath:()=>qF,getEnumValues:()=>Dl,getLengthableOrigin:()=>Bl,getParsedType:()=>XF,getSizableOrigin:()=>Fl,isObject:()=>vc,isPlainObject:()=>bc,issue:()=>Vv,joinValues:()=>C,jsonStringifyReplacer:()=>Mv,merge:()=>r6,normalizeParams:()=>F,nullish:()=>Vs,numKeys:()=>JF,omit:()=>e6,optionalKeys:()=>Uv,partial:()=>n6,pick:()=>QF,prefixIssues:()=>Cr,primitiveTypes:()=>Lv,promiseAllObject:()=>HF,propertyKeyTypes:()=>Ul,randomString:()=>WF,required:()=>i6,stringifyPrimitive:()=>K,unwrapMessage:()=>jl});function BF(e){return e}function VF(e){return e}function ZF(e){}function GF(e){throw new Error}function KF(e){}function Dl(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,i])=>t.indexOf(+n)===-1).map(([n,i])=>i)}function C(e,t="|"){return e.map(r=>K(r)).join(t)}function Mv(e,t){return typeof t=="bigint"?t.toString():t}function zl(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Vs(e){return e==null}function Ll(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function jv(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return s%o/10**i}function Fe(e,t,r){Object.defineProperty(e,t,{get(){{let i=r();return e[t]=i,i}throw new Error("cached value already set")},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Dv(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function qF(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function HF(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let i={};for(let s=0;s<t.length;s++)i[t[s]]=n[s];return i})}function WF(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Zo(e){return JSON.stringify(e)}var dm=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function vc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var zv=zl(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function bc(e){if(vc(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(vc(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function JF(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var XF=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Ul=new Set(["string","number","symbol"]),Lv=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ki(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lt(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function F(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function YF(e){let t;return new Proxy({},{get(r,n,i){return t??(t=e()),Reflect.get(t,n,i)},set(r,n,i,s){return t??(t=e()),Reflect.set(t,n,i,s)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,i){return t??(t=e()),Reflect.defineProperty(t,n,i)}})}function K(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Uv(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Fv={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Bv={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function QF(e,t){let r={},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=n.shape[i])}return lt(e,{...e._zod.def,shape:r,checks:[]})}function e6(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return lt(e,{...e._zod.def,shape:r,checks:[]})}function t6(e,t){if(!bc(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return Dv(this,"shape",n),n},checks:[]};return lt(e,r)}function r6(e,t){return lt(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Dv(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function n6(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)i[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return lt(t,{...t._zod.def,shape:i,checks:[]})}function i6(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(let s in n)i[s]=new e({type:"nonoptional",innerType:n[s]});return lt(t,{...t._zod.def,shape:i,checks:[]})}function Go(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Cr(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function jl(e){return typeof e=="string"?e:e?.message}function Gr(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let i=jl(e.inst?._zod.def?.error?.(e))??jl(t?.error?.(e))??jl(r.customError?.(e))??jl(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Fl(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Bl(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Vv(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function s6(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Rv=class{constructor(...t){}};var F$=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,Mv,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Vl=S("$ZodError",F$),wc=S("$ZodError",F$,{Parent:Error});function Zl(e,t=r=>r.message){let r={},n=[];for(let i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function Gl(e,t){let r=t||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>i({issues:a}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(o))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(e),n}function Zv(e,t){let r=t||function(s){return s.message},n={errors:[]},i=(s,o=[])=>{var a,c;for(let u of s.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(l=>i({issues:l},u.path));else if(u.code==="invalid_key")i({issues:u.issues},u.path);else if(u.code==="invalid_element")i({issues:u.issues},u.path);else{let l=[...o,...u.path];if(l.length===0){n.errors.push(r(u));continue}let p=n,f=0;for(;f<l.length;){let d=l[f],m=f===l.length-1;typeof d=="string"?(p.properties??(p.properties={}),(a=p.properties)[d]??(a[d]={errors:[]}),p=p.properties[d]):(p.items??(p.items=[]),(c=p.items)[d]??(c[d]={errors:[]}),p=p.items[d]),m&&p.errors.push(r(u)),f++}}};return i(e),n}function B$(e){let t=[];for(let r of e)typeof r=="number"?t.push(`[${r}]`):typeof r=="symbol"?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function Gv(e){let t=[],r=[...e.issues].sort((n,i)=>n.path.length-i.path.length);for(let n of r)t.push(`\u2716 ${n.message}`),n.path?.length&&t.push(` \u2192 at ${B$(n.path)}`);return t.join(`
59
- `)}var fm=e=>(t,r,n,i)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new ci;if(o.issues.length){let a=new(i?.Err??e)(o.issues.map(c=>Gr(c,s,At())));throw dm(a,i?.callee),a}return o.value},ui=fm(wc),mm=e=>async(t,r,n,i)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){let a=new(i?.Err??e)(o.issues.map(c=>Gr(c,s,At())));throw dm(a,i?.callee),a}return o.value},Ko=mm(wc),hm=e=>(t,r,n)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new ci;return s.issues.length?{success:!1,error:new(e??Vl)(s.issues.map(o=>Gr(o,i,At())))}:{success:!0,data:s.value}},Kv=hm(wc),gm=e=>async(t,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(o=>Gr(o,i,At())))}:{success:!0,data:s.value}},qv=gm(wc);var Ho={};$s(Ho,{_emoji:()=>V$,base64:()=>cb,base64url:()=>_m,bigint:()=>hb,boolean:()=>yb,browserEmail:()=>m6,cidrv4:()=>ob,cidrv6:()=>ab,cuid:()=>Hv,cuid2:()=>Wv,date:()=>pb,datetime:()=>fb,domain:()=>h6,duration:()=>eb,e164:()=>lb,email:()=>rb,emoji:()=>nb,extendedDuration:()=>a6,guid:()=>tb,hostname:()=>ub,html5Email:()=>p6,integer:()=>gb,ipv4:()=>ib,ipv6:()=>sb,ksuid:()=>Yv,lowercase:()=>wb,nanoid:()=>Qv,null:()=>vb,number:()=>_b,rfc5322Email:()=>d6,string:()=>mb,time:()=>db,ulid:()=>Jv,undefined:()=>bb,unicodeEmail:()=>f6,uppercase:()=>xb,uuid:()=>qo,uuid4:()=>c6,uuid6:()=>u6,uuid7:()=>l6,xid:()=>Xv});var Hv=/^[cC][^\s-]{8,}$/,Wv=/^[0-9a-z]+$/,Jv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Xv=/^[0-9a-vA-V]{20}$/,Yv=/^[A-Za-z0-9]{27}$/,Qv=/^[a-zA-Z0-9_-]{21}$/,eb=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,a6=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,tb=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,qo=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,c6=qo(4),u6=qo(6),l6=qo(7),rb=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,p6=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,d6=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,f6=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,m6=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,V$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function nb(){return new RegExp(V$,"u")}var ib=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,sb=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,ob=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ab=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cb=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_m=/^[A-Za-z0-9_-]*$/,ub=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,h6=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,lb=/^\+(?:[0-9]){6,14}[0-9]$/,Z$="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",pb=new RegExp(`^${Z$}$`);function G$(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function db(e){return new RegExp(`^${G$(e)}$`)}function fb(e){let t=G$({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Z$}T(?:${n})$`)}var mb=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},hb=/^\d+n?$/,gb=/^\d+$/,_b=/^-?\d+(?:\.\d+)?/i,yb=/true|false/i,vb=/null/i;var bb=/undefined/i;var wb=/^[^A-Z]*$/,xb=/^[^a-z]*$/;var pt=S("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),q$={number:"number",bigint:"bigint",object:"date"},ym=S("$ZodCheckLessThan",(e,t)=>{pt.init(e,t);let r=q$[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,s=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),vm=S("$ZodCheckGreaterThan",(e,t)=>{pt.init(e,t);let r=q$[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,s=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ib=S("$ZodCheckMultipleOf",(e,t)=>{pt.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):jv(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Sb=S("$ZodCheckNumberFormat",(e,t)=>{pt.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[i,s]=Fv[t.format];e._zod.onattach.push(o=>{let a=o._zod.bag;a.format=t.format,a.minimum=i,a.maximum=s,r&&(a.pattern=gb)}),e._zod.check=o=>{let a=o.value;if(r){if(!Number.isInteger(a)){o.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}a<i&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>s&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}}),Eb=S("$ZodCheckBigIntFormat",(e,t)=>{pt.init(e,t);let[r,n]=Bv[t.format];e._zod.onattach.push(i=>{let s=i._zod.bag;s.format=t.format,s.minimum=r,s.maximum=n}),e._zod.check=i=>{let s=i.value;s<r&&i.issues.push({origin:"bigint",input:s,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),s>n&&i.issues.push({origin:"bigint",input:s,code:"too_big",maximum:n,inst:e})}}),kb=S("$ZodCheckMaxSize",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Vs(i)&&i.size!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let i=n.value;i.size<=t.maximum||n.issues.push({origin:Fl(i),code:"too_big",maximum:t.maximum,input:i,inst:e,continue:!t.abort})}}),Ab=S("$ZodCheckMinSize",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Vs(i)&&i.size!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let i=n.value;i.size>=t.minimum||n.issues.push({origin:Fl(i),code:"too_small",minimum:t.minimum,input:i,inst:e,continue:!t.abort})}}),Tb=S("$ZodCheckSizeEquals",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Vs(i)&&i.size!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=t.size,i.maximum=t.size,i.size=t.size}),e._zod.check=n=>{let i=n.value,s=i.size;if(s===t.size)return;let o=s>t.size;n.issues.push({origin:Fl(i),...o?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ob=S("$ZodCheckMaxLength",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Vs(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let i=n.value;if(i.length<=t.maximum)return;let o=Bl(i);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),$b=S("$ZodCheckMinLength",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Vs(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let i=n.value;if(i.length>=t.minimum)return;let o=Bl(i);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Cb=S("$ZodCheckLengthEquals",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Vs(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=n=>{let i=n.value,s=i.length;if(s===t.length)return;let o=Bl(i),a=s>t.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),xc=S("$ZodCheckStringFormat",(e,t)=>{var r,n;pt.init(e,t),e._zod.onattach.push(i=>{let s=i._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Pb=S("$ZodCheckRegex",(e,t)=>{xc.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Nb=S("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=wb),xc.init(e,t)}),Rb=S("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=xb),xc.init(e,t)}),Mb=S("$ZodCheckIncludes",(e,t)=>{pt.init(e,t);let r=Ki(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(i=>{let s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),jb=S("$ZodCheckStartsWith",(e,t)=>{pt.init(e,t);let r=new RegExp(`^${Ki(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Db=S("$ZodCheckEndsWith",(e,t)=>{pt.init(e,t);let r=new RegExp(`.*${Ki(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});function K$(e,t,r){e.issues.length&&t.issues.push(...Cr(r,e.issues))}var zb=S("$ZodCheckProperty",(e,t)=>{pt.init(e,t),e._zod.check=r=>{let n=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(i=>K$(i,r,t.property));K$(n,r,t.property)}}),Lb=S("$ZodCheckMimeType",(e,t)=>{pt.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(n=>{n._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e})}}),Ub=S("$ZodCheckOverwrite",(e,t)=>{pt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Kl=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
60
- `).filter(o=>o),i=Math.min(...n.map(o=>o.length-o.trimStart().length)),s=n.map(o=>o.slice(i)).map(o=>" ".repeat(this.indent*2)+o);for(let o of s)this.content.push(o)}compile(){let t=Function,r=this?.args,i=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,i.join(`
61
- `))}};var Fb={major:4,minor:0,patch:0};var ye=S("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Fb;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let i of n)for(let s of i._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(s,o,a)=>{let c=Go(s),u;for(let l of o){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let p=s.issues.length,f=l._zod.check(s);if(f instanceof Promise&&a?.async===!1)throw new ci;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,s.issues.length!==p&&(c||(c=Go(s,p)))});else{if(s.issues.length===p)continue;c||(c=Go(s,p))}}return u?u.then(()=>s):s};e._zod.run=(s,o)=>{let a=e._zod.parse(s,o);if(a instanceof Promise){if(o.async===!1)throw new ci;return a.then(c=>i(c,n,o))}return i(a,n,o)}}e["~standard"]={validate:i=>{try{let s=Kv(e,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return qv(e,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}}),Wo=S("$ZodString",(e,t)=>{ye.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??mb(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),He=S("$ZodStringFormat",(e,t)=>{xc.init(e,t),Wo.init(e,t)}),Vb=S("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tb),He.init(e,t)}),Zb=S("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=qo(n))}else t.pattern??(t.pattern=qo());He.init(e,t)}),Gb=S("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=rb),He.init(e,t)}),Kb=S("$ZodURL",(e,t)=>{He.init(e,t),e._zod.check=r=>{try{let n=r.value,i=new URL(n),s=i.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:ub.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),qb=S("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=nb()),He.init(e,t)}),Hb=S("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Qv),He.init(e,t)}),Wb=S("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Hv),He.init(e,t)}),Jb=S("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Wv),He.init(e,t)}),Xb=S("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Jv),He.init(e,t)}),Yb=S("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Xv),He.init(e,t)}),Qb=S("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Yv),He.init(e,t)}),ew=S("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=fb(t)),He.init(e,t)}),tw=S("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=pb),He.init(e,t)}),rw=S("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=db(t)),He.init(e,t)}),nw=S("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=eb),He.init(e,t)}),iw=S("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ib),He.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),sw=S("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=sb),He.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),ow=S("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ob),He.init(e,t)}),aw=S("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ab),He.init(e,t),e._zod.check=r=>{let[n,i]=r.value.split("/");try{if(!i)throw new Error;let s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function cw(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var uw=S("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cb),He.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{cw(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function oC(e){if(!_m.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return cw(r)}var lw=S("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=_m),He.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{oC(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),pw=S("$ZodE164",(e,t)=>{t.pattern??(t.pattern=lb),He.init(e,t)});function aC(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}var dw=S("$ZodJWT",(e,t)=>{He.init(e,t),e._zod.check=r=>{aC(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),fw=S("$ZodCustomStringFormat",(e,t)=>{He.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),xm=S("$ZodNumber",(e,t)=>{ye.init(e,t),e._zod.pattern=e._zod.bag.pattern??_b,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),r}}),mw=S("$ZodNumber",(e,t)=>{Sb.init(e,t),xm.init(e,t)}),ql=S("$ZodBoolean",(e,t)=>{ye.init(e,t),e._zod.pattern=yb,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),Im=S("$ZodBigInt",(e,t)=>{ye.init(e,t),e._zod.pattern=hb,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),hw=S("$ZodBigInt",(e,t)=>{Eb.init(e,t),Im.init(e,t)}),gw=S("$ZodSymbol",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;return typeof i=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:i,inst:e}),r}}),_w=S("$ZodUndefined",(e,t)=>{ye.init(e,t),e._zod.pattern=bb,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(r,n)=>{let i=r.value;return typeof i>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:i,inst:e}),r}}),yw=S("$ZodNull",(e,t)=>{ye.init(e,t),e._zod.pattern=vb,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}}),vw=S("$ZodAny",(e,t)=>{ye.init(e,t),e._zod.parse=r=>r}),Zs=S("$ZodUnknown",(e,t)=>{ye.init(e,t),e._zod.parse=r=>r}),Hl=S("$ZodNever",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),bw=S("$ZodVoid",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;return typeof i>"u"||r.issues.push({expected:"void",code:"invalid_type",input:i,inst:e}),r}}),ww=S("$ZodDate",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let i=r.value,s=i instanceof Date;return s&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...s?{received:"Invalid Date"}:{},inst:e}),r}});function W$(e,t,r){e.issues.length&&t.issues.push(...Cr(r,e.issues)),t.value[r]=e.value}var Wl=S("$ZodArray",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);let s=[];for(let o=0;o<i.length;o++){let a=i[o],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>W$(u,r,o))):W$(c,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function bm(e,t,r){e.issues.length&&t.issues.push(...Cr(r,e.issues)),t.value[r]=e.value}function J$(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...Cr(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var xw=S("$ZodObject",(e,t)=>{ye.init(e,t);let r=zl(()=>{let p=Object.keys(t.shape);for(let d of p)if(!(t.shape[d]instanceof ye))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);let f=Uv(t.shape);return{shape:t.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(f)}});Fe(e._zod,"propValues",()=>{let p=t.shape,f={};for(let d in p){let m=p[d]._zod;if(m.values){f[d]??(f[d]=new Set);for(let h of m.values)f[d].add(h)}}return f});let n=p=>{let f=new Kl(["shape","payload","ctx"]),d=r.value,m=y=>{let x=Zo(y);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),b=0;for(let y of d.keys)h[y]=`key_${b++}`;f.write("const newResult = {}");for(let y of d.keys)if(d.optionalKeys.has(y)){let x=h[y];f.write(`const ${x} = ${m(y)};`);let I=Zo(y);f.write(`
62
- if (${x}.issues.length) {
63
- if (input[${I}] === undefined) {
64
- if (${I} in input) {
65
- newResult[${I}] = undefined;
66
- }
67
- } else {
68
- payload.issues = payload.issues.concat(
69
- ${x}.issues.map((iss) => ({
70
- ...iss,
71
- path: iss.path ? [${I}, ...iss.path] : [${I}],
72
- }))
73
- );
74
- }
75
- } else if (${x}.value === undefined) {
76
- if (${I} in input) newResult[${I}] = undefined;
77
- } else {
78
- newResult[${I}] = ${x}.value;
79
- }
80
- `)}else{let x=h[y];f.write(`const ${x} = ${m(y)};`),f.write(`
81
- if (${x}.issues.length) payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
82
- ...iss,
83
- path: iss.path ? [${Zo(y)}, ...iss.path] : [${Zo(y)}]
84
- })));`),f.write(`newResult[${Zo(y)}] = ${x}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let _=f.compile();return(y,x)=>_(p,y,x)},i,s=vc,o=!Ml.jitless,c=o&&zv.value,u=t.catchall,l;e._zod.parse=(p,f)=>{l??(l=r.value);let d=p.value;if(!s(d))return p.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),p;let m=[];if(o&&c&&f?.async===!1&&f.jitless!==!0)i||(i=n(t.shape)),p=i(p,f);else{p.value={};let x=l.shape;for(let I of l.keys){let A=x[I],j=A._zod.run({value:d[I],issues:[]},f),O=A._zod.optin==="optional"&&A._zod.optout==="optional";j instanceof Promise?m.push(j.then(w=>O?J$(w,p,I,d):bm(w,p,I))):O?J$(j,p,I,d):bm(j,p,I)}}if(!u)return m.length?Promise.all(m).then(()=>p):p;let h=[],b=l.keySet,_=u._zod,y=_.def.type;for(let x of Object.keys(d)){if(b.has(x))continue;if(y==="never"){h.push(x);continue}let I=_.run({value:d[x],issues:[]},f);I instanceof Promise?m.push(I.then(A=>bm(A,p,x))):bm(I,p,x)}return h.length&&p.issues.push({code:"unrecognized_keys",keys:h,input:d,inst:e}),m.length?Promise.all(m).then(()=>p):p}});function X$(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(s=>Gr(s,n,At())))}),t}var Sm=S("$ZodUnion",(e,t)=>{ye.init(e,t),Fe(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Fe(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Fe(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Fe(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Ll(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let i=!1,s=[];for(let o of t.options){let a=o._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),i=!0;else{if(a.issues.length===0)return a;s.push(a)}}return i?Promise.all(s).then(o=>X$(o,r,e,n)):X$(s,r,e,n)}}),Iw=S("$ZodDiscriminatedUnion",(e,t)=>{Sm.init(e,t);let r=e._zod.parse;Fe(e._zod,"propValues",()=>{let i={};for(let s of t.options){let o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[a,c]of Object.entries(o)){i[a]||(i[a]=new Set);for(let u of c)i[a].add(u)}}return i});let n=zl(()=>{let i=t.options,s=new Map;for(let o of i){let a=o._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,o)}}return s});e._zod.parse=(i,s)=>{let o=i.value;if(!vc(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),i;let a=n.value.get(o?.[t.discriminator]);return a?a._zod.run(i,s):t.unionFallback?r(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[t.discriminator],inst:e}),i)}}),Sw=S("$ZodIntersection",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{let i=r.value,s=t.left._zod.run({value:i,issues:[]},n),o=t.right._zod.run({value:i,issues:[]},n);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([c,u])=>Y$(r,c,u)):Y$(r,s,o)}});function Bb(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(bc(e)&&bc(t)){let r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),i={...e,...t};for(let s of n){let o=Bb(e[s],t[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};i[s]=o.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let i=e[n],s=t[n],o=Bb(i,s);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};r.push(o.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Y$(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Go(e))return e;let n=Bb(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}var Jo=S("$ZodTuple",(e,t)=>{ye.init(e,t);let r=t.items,n=r.length-[...r].reverse().findIndex(i=>i._zod.optin!=="optional");e._zod.parse=(i,s)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=[];let a=[];if(!t.rest){let u=o.length>r.length,l=o.length<n-1;if(u||l)return i.issues.push({input:o,inst:e,origin:"array",...u?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length}}),i}let c=-1;for(let u of r){if(c++,c>=o.length&&c>=n)continue;let l=u._zod.run({value:o[c],issues:[]},s);l instanceof Promise?a.push(l.then(p=>wm(p,i,c))):wm(l,i,c)}if(t.rest){let u=o.slice(r.length);for(let l of u){c++;let p=t.rest._zod.run({value:l,issues:[]},s);p instanceof Promise?a.push(p.then(f=>wm(f,i,c))):wm(p,i,c)}}return a.length?Promise.all(a).then(()=>i):i}});function wm(e,t,r){e.issues.length&&t.issues.push(...Cr(r,e.issues)),t.value[r]=e.value}var Ew=S("$ZodRecord",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!bc(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;let s=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;r.value={};for(let c of o)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=t.valueType._zod.run({value:i[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...Cr(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Cr(c,u.issues)),r.value[c]=u.value)}let a;for(let c in i)o.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:a})}else{r.value={};for(let o of Reflect.ownKeys(i)){if(o==="__proto__")continue;let a=t.keyType._zod.run({value:o,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>Gr(u,n,At())),input:o,path:[o],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Cr(o,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Cr(o,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),kw=S("$ZodMap",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!(i instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:i,inst:e}),r;let s=[];r.value=new Map;for(let[o,a]of i){let c=t.keyType._zod.run({value:o,issues:[]},n),u=t.valueType._zod.run({value:a,issues:[]},n);c instanceof Promise||u instanceof Promise?s.push(Promise.all([c,u]).then(([l,p])=>{Q$(l,p,r,o,i,e,n)})):Q$(c,u,r,o,i,e,n)}return s.length?Promise.all(s).then(()=>r):r}});function Q$(e,t,r,n,i,s,o){e.issues.length&&(Ul.has(typeof n)?r.issues.push(...Cr(n,e.issues)):r.issues.push({origin:"map",code:"invalid_key",input:i,inst:s,issues:e.issues.map(a=>Gr(a,o,At()))})),t.issues.length&&(Ul.has(typeof n)?r.issues.push(...Cr(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:i,inst:s,key:n,issues:t.issues.map(a=>Gr(a,o,At()))})),r.value.set(e.value,t.value)}var Aw=S("$ZodSet",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!(i instanceof Set))return r.issues.push({input:i,inst:e,expected:"set",code:"invalid_type"}),r;let s=[];r.value=new Set;for(let o of i){let a=t.valueType._zod.run({value:o,issues:[]},n);a instanceof Promise?s.push(a.then(c=>eC(c,r))):eC(a,r)}return s.length?Promise.all(s).then(()=>r):r}});function eC(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}var Tw=S("$ZodEnum",(e,t)=>{ye.init(e,t);let r=Dl(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>Ul.has(typeof n)).map(n=>typeof n=="string"?Ki(n):n.toString()).join("|")})$`),e._zod.parse=(n,i)=>{let s=n.value;return e._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),Ow=S("$ZodLiteral",(e,t)=>{ye.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Ki(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let i=r.value;return e._zod.values.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}}),$w=S("$ZodFile",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;return i instanceof File||r.issues.push({expected:"file",code:"invalid_type",input:i,inst:e}),r}}),Jl=S("$ZodTransform",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{let i=t.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(r.value=o,r));if(i instanceof Promise)throw new ci;return r.value=i,r}}),Ic=S("$ZodOptional",(e,t)=>{ye.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Fe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ll(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),Cw=S("$ZodNullable",(e,t)=>{ye.init(e,t),Fe(e._zod,"optin",()=>t.innerType._zod.optin),Fe(e._zod,"optout",()=>t.innerType._zod.optout),Fe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ll(r.source)}|null)$`):void 0}),Fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Pw=S("$ZodDefault",(e,t)=>{ye.init(e,t),e._zod.optin="optional",Fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>tC(s,t)):tC(i,t)}});function tC(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Nw=S("$ZodPrefault",(e,t)=>{ye.init(e,t),e._zod.optin="optional",Fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),Rw=S("$ZodNonOptional",(e,t)=>{ye.init(e,t),Fe(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>rC(s,e)):rC(i,e)}});function rC(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Mw=S("$ZodSuccess",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>(r.value=s.issues.length===0,r)):(r.value=i.issues.length===0,r)}}),jw=S("$ZodCatch",(e,t)=>{ye.init(e,t),e._zod.optin="optional",Fe(e._zod,"optout",()=>t.innerType._zod.optout),Fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(o=>Gr(o,n,At()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>Gr(s,n,At()))},input:r.value}),r.issues=[]),r)}}),Dw=S("$ZodNaN",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>((typeof r.value!="number"||!Number.isNaN(r.value))&&r.issues.push({input:r.value,inst:e,expected:"nan",code:"invalid_type"}),r)}),Xl=S("$ZodPipe",(e,t)=>{ye.init(e,t),Fe(e._zod,"values",()=>t.in._zod.values),Fe(e._zod,"optin",()=>t.in._zod.optin),Fe(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{let i=t.in._zod.run(r,n);return i instanceof Promise?i.then(s=>nC(s,t,n)):nC(i,t,n)}});function nC(e,t,r){return Go(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var zw=S("$ZodReadonly",(e,t)=>{ye.init(e,t),Fe(e._zod,"propValues",()=>t.innerType._zod.propValues),Fe(e._zod,"values",()=>t.innerType._zod.values),Fe(e._zod,"optin",()=>t.innerType._zod.optin),Fe(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(iC):iC(i)}});function iC(e){return e.value=Object.freeze(e.value),e}var Lw=S("$ZodTemplateLiteral",(e,t)=>{ye.init(e,t);let r=[];for(let n of t.parts)if(n instanceof ye){if(!n._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...n._zod.traits].shift()}`);let i=n._zod.pattern instanceof RegExp?n._zod.pattern.source:n._zod.pattern;if(!i)throw new Error(`Invalid template literal part: ${n._zod.traits}`);let s=i.startsWith("^")?1:0,o=i.endsWith("$")?i.length-1:i.length;r.push(i.slice(s,o))}else if(n===null||Lv.has(typeof n))r.push(Ki(`${n}`));else throw new Error(`Invalid template literal part: ${n}`);e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(n,i)=>typeof n.value!="string"?(n.issues.push({input:n.value,inst:e,expected:"template_literal",code:"invalid_type"}),n):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:"invalid_format",format:"template_literal",pattern:e._zod.pattern.source}),n)}),Uw=S("$ZodPromise",(e,t)=>{ye.init(e,t),e._zod.parse=(r,n)=>Promise.resolve(r.value).then(i=>t.innerType._zod.run({value:i,issues:[]},n))}),Fw=S("$ZodLazy",(e,t)=>{ye.init(e,t),Fe(e._zod,"innerType",()=>t.getter()),Fe(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Fe(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Fe(e._zod,"optin",()=>e._zod.innerType._zod.optin),Fe(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),Bw=S("$ZodCustom",(e,t)=>{pt.init(e,t),ye.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(s=>sC(s,r,n,e));sC(i,r,n,e)}});function sC(e,t,r,n){if(!e){let i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),t.issues.push(Vv(i))}}var Yl={};$s(Yl,{ar:()=>uC,az:()=>lC,be:()=>dC,ca:()=>fC,cs:()=>mC,de:()=>hC,en:()=>Em,eo:()=>gC,es:()=>_C,fa:()=>yC,fi:()=>vC,fr:()=>bC,frCA:()=>wC,he:()=>xC,hu:()=>IC,id:()=>SC,it:()=>EC,ja:()=>kC,kh:()=>AC,ko:()=>TC,mk:()=>OC,ms:()=>$C,nl:()=>CC,no:()=>PC,ota:()=>NC,pl:()=>MC,ps:()=>RC,pt:()=>jC,ru:()=>zC,sl:()=>LC,sv:()=>UC,ta:()=>FC,th:()=>BC,tr:()=>VC,ua:()=>ZC,ur:()=>GC,vi:()=>KC,zhCN:()=>qC,zhTW:()=>HC});var g6=()=>{let e={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"};return i=>{switch(i.code){case"invalid_type":return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${i.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${K(i.values[0])}`:`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${i.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${s} ${i.maximum.toString()} ${o.unit??"\u0639\u0646\u0635\u0631"}`:`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${i.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${s} ${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${i.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${s} ${i.minimum.toString()} ${o.unit}`:`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${i.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${s} ${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${i.prefix}"`:s.format==="ends_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${s.suffix}"`:s.format==="includes"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${s.includes}"`:s.format==="regex"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${s.pattern}`:`${n[s.format]??i.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${i.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${i.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${i.keys.length>1?"\u0629":""}: ${C(i.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${i.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${i.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};function uC(){return{localeError:g6()}}var _6=()=>{let e={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${i.expected}, daxil olan ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${K(i.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${i.origin??"d\u0259y\u0259r"} ${s}${i.maximum.toString()} ${o.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${i.origin??"d\u0259y\u0259r"} ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${i.origin} ${s}${i.minimum.toString()} ${o.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${i.origin} ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${s.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:s.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${s.suffix}" il\u0259 bitm\u0259lidir`:s.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${s.includes}" daxil olmal\u0131d\u0131r`:s.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${s.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${n[s.format]??i.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${i.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${i.keys.length>1?"lar":""}: ${C(i.keys,", ")}`;case"invalid_key":return`${i.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${i.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};function lC(){return{localeError:_6()}}function pC(e,t,r,n){let i=Math.abs(e),s=i%10,o=i%100;return o>=11&&o<=19?n:s===1?t:s>=2&&s<=4?r:n}var y6=()=>{let e={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u043B\u0456\u043A";case"object":{if(Array.isArray(i))return"\u043C\u0430\u0441\u0456\u045E";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"};return i=>{switch(i.code){case"invalid_type":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${i.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${K(i.values[0])}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);if(o){let a=Number(i.maximum),c=pC(a,o.unit.one,o.unit.few,o.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${o.verb} ${s}${i.maximum.toString()} ${c}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);if(o){let a=Number(i.minimum),c=pC(a,o.unit.one,o.unit.few,o.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${i.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${o.verb} ${s}${i.minimum.toString()} ${c}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${i.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${s.prefix}"`:s.format==="ends_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${s.suffix}"`:s.format==="includes"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${s.includes}"`:s.format==="regex"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${s.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${n[s.format]??i.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${i.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${i.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${C(i.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${i.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${i.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};function dC(){return{localeError:y6()}}var v6=()=>{let e={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return i=>{switch(i.code){case"invalid_type":return`Tipus inv\xE0lid: s'esperava ${i.expected}, s'ha rebut ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Valor inv\xE0lid: s'esperava ${K(i.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${C(i.values," o ")}`;case"too_big":{let s=i.inclusive?"com a m\xE0xim":"menys de",o=t(i.origin);return o?`Massa gran: s'esperava que ${i.origin??"el valor"} contingu\xE9s ${s} ${i.maximum.toString()} ${o.unit??"elements"}`:`Massa gran: s'esperava que ${i.origin??"el valor"} fos ${s} ${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?"com a m\xEDnim":"m\xE9s de",o=t(i.origin);return o?`Massa petit: s'esperava que ${i.origin} contingu\xE9s ${s} ${i.minimum.toString()} ${o.unit}`:`Massa petit: s'esperava que ${i.origin} fos ${s} ${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${s.prefix}"`:s.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${s.suffix}"`:s.format==="includes"?`Format inv\xE0lid: ha d'incloure "${s.includes}"`:s.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${s.pattern}`:`Format inv\xE0lid per a ${n[s.format]??i.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${i.divisor}`;case"unrecognized_keys":return`Clau${i.keys.length>1?"s":""} no reconeguda${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${i.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${i.origin}`;default:return"Entrada inv\xE0lida"}}};function fC(){return{localeError:v6()}}var b6=()=>{let e={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u010D\xEDslo";case"string":return"\u0159et\u011Bzec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":{if(Array.isArray(i))return"pole";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"};return i=>{switch(i.code){case"invalid_type":return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${i.expected}, obdr\u017Eeno ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${K(i.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${i.origin??"hodnota"} mus\xED m\xEDt ${s}${i.maximum.toString()} ${o.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${i.origin??"hodnota"} mus\xED b\xFDt ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${i.origin??"hodnota"} mus\xED m\xEDt ${s}${i.minimum.toString()} ${o.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${i.origin??"hodnota"} mus\xED b\xFDt ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${s.prefix}"`:s.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${s.suffix}"`:s.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${s.includes}"`:s.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${s.pattern}`:`Neplatn\xFD form\xE1t ${n[s.format]??i.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${i.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${C(i.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${i.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${i.origin}`;default:return"Neplatn\xFD vstup"}}};function mC(){return{localeError:b6()}}var w6=()=>{let e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"Zahl";case"object":{if(Array.isArray(i))return"Array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return i=>{switch(i.code){case"invalid_type":return`Ung\xFCltige Eingabe: erwartet ${i.expected}, erhalten ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Ung\xFCltige Eingabe: erwartet ${K(i.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Zu gro\xDF: erwartet, dass ${i.origin??"Wert"} ${s}${i.maximum.toString()} ${o.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${i.origin??"Wert"} ${s}${i.maximum.toString()} ist`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Zu klein: erwartet, dass ${i.origin} ${s}${i.minimum.toString()} ${o.unit} hat`:`Zu klein: erwartet, dass ${i.origin} ${s}${i.minimum.toString()} ist`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Ung\xFCltiger String: muss mit "${s.prefix}" beginnen`:s.format==="ends_with"?`Ung\xFCltiger String: muss mit "${s.suffix}" enden`:s.format==="includes"?`Ung\xFCltiger String: muss "${s.includes}" enthalten`:s.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${s.pattern} entsprechen`:`Ung\xFCltig: ${n[s.format]??i.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${i.divisor} sein`;case"unrecognized_keys":return`${i.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${C(i.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${i.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${i.origin}`;default:return"Ung\xFCltige Eingabe"}}};function hC(){return{localeError:w6()}}var x6=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},I6=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${x6(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${K(n.values[0])}`:`Invalid option: expected one of ${C(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);return s?`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${C(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function Em(){return{localeError:I6()}}var S6=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombro";case"object":{if(Array.isArray(e))return"tabelo";if(e===null)return"senvalora";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},E6=()=>{let e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(n){return e[n]??null}let r={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return n=>{switch(n.code){case"invalid_type":return`Nevalida enigo: atendi\u011Dis ${n.expected}, ricevi\u011Dis ${S6(n.input)}`;case"invalid_value":return n.values.length===1?`Nevalida enigo: atendi\u011Dis ${K(n.values[0])}`:`Nevalida opcio: atendi\u011Dis unu el ${C(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);return s?`Tro granda: atendi\u011Dis ke ${n.origin??"valoro"} havu ${i}${n.maximum.toString()} ${s.unit??"elementojn"}`:`Tro granda: atendi\u011Dis ke ${n.origin??"valoro"} havu ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);return s?`Tro malgranda: atendi\u011Dis ke ${n.origin} havu ${i}${n.minimum.toString()} ${s.unit}`:`Tro malgranda: atendi\u011Dis ke ${n.origin} estu ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;return i.format==="starts_with"?`Nevalida karaktraro: devas komenci\u011Di per "${i.prefix}"`:i.format==="ends_with"?`Nevalida karaktraro: devas fini\u011Di per "${i.suffix}"`:i.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${i.includes}"`:i.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${i.pattern}`:`Nevalida ${r[i.format]??n.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${n.divisor}`;case"unrecognized_keys":return`Nekonata${n.keys.length>1?"j":""} \u015Dlosilo${n.keys.length>1?"j":""}: ${C(n.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${n.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${n.origin}`;default:return"Nevalida enigo"}}};function gC(){return{localeError:E6()}}var k6=()=>{let e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(i))return"arreglo";if(i===null)return"nulo";if(Object.getPrototypeOf(i)!==Object.prototype)return i.constructor.name}}return s},n={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return i=>{switch(i.code){case"invalid_type":return`Entrada inv\xE1lida: se esperaba ${i.expected}, recibido ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Entrada inv\xE1lida: se esperaba ${K(i.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Demasiado grande: se esperaba que ${i.origin??"valor"} tuviera ${s}${i.maximum.toString()} ${o.unit??"elementos"}`:`Demasiado grande: se esperaba que ${i.origin??"valor"} fuera ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Demasiado peque\xF1o: se esperaba que ${i.origin} tuviera ${s}${i.minimum.toString()} ${o.unit}`:`Demasiado peque\xF1o: se esperaba que ${i.origin} fuera ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${s.prefix}"`:s.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${s.suffix}"`:s.format==="includes"?`Cadena inv\xE1lida: debe incluir "${s.includes}"`:s.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${s.pattern}`:`Inv\xE1lido ${n[s.format]??i.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${i.divisor}`;case"unrecognized_keys":return`Llave${i.keys.length>1?"s":""} desconocida${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${i.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${i.origin}`;default:return"Entrada inv\xE1lida"}}};function _C(){return{localeError:k6()}}var A6=()=>{let e={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(i))return"\u0622\u0631\u0627\u06CC\u0647";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"};return i=>{switch(i.code){case"invalid_type":return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${i.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${r(i.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;case"invalid_value":return i.values.length===1?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${K(i.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`:`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${C(i.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${i.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${s}${i.maximum.toString()} ${o.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${i.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${s}${i.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${i.origin} \u0628\u0627\u06CC\u062F ${s}${i.minimum.toString()} ${o.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${i.origin} \u0628\u0627\u06CC\u062F ${s}${i.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${s.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:s.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${s.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:s.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${s.includes}" \u0628\u0627\u0634\u062F`:s.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${s.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${n[s.format]??i.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${i.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${i.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${C(i.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${i.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${i.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};function yC(){return{localeError:A6()}}var T6=()=>{let e={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return i=>{switch(i.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${i.expected}, oli ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${K(i.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Liian suuri: ${o.subject} t\xE4ytyy olla ${s}${i.maximum.toString()} ${o.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Liian pieni: ${o.subject} t\xE4ytyy olla ${s}${i.minimum.toString()} ${o.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${s.prefix}"`:s.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${s.suffix}"`:s.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${s.includes}"`:s.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${s.pattern}`:`Virheellinen ${n[s.format]??i.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${i.divisor} monikerta`;case"unrecognized_keys":return`${i.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${C(i.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}};function vC(){return{localeError:T6()}}var O6=()=>{let e={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"nombre";case"object":{if(Array.isArray(i))return"tableau";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};return i=>{switch(i.code){case"invalid_type":return`Entr\xE9e invalide : ${i.expected} attendu, ${r(i.input)} re\xE7u`;case"invalid_value":return i.values.length===1?`Entr\xE9e invalide : ${K(i.values[0])} attendu`:`Option invalide : une valeur parmi ${C(i.values,"|")} attendue`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Trop grand : ${i.origin??"valeur"} doit ${o.verb} ${s}${i.maximum.toString()} ${o.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${i.origin??"valeur"} doit \xEAtre ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Trop petit : ${i.origin} doit ${o.verb} ${s}${i.minimum.toString()} ${o.unit}`:`Trop petit : ${i.origin} doit \xEAtre ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${s.prefix}"`:s.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${s.suffix}"`:s.format==="includes"?`Cha\xEEne invalide : doit inclure "${s.includes}"`:s.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${s.pattern}`:`${n[s.format]??i.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${i.divisor}`;case"unrecognized_keys":return`Cl\xE9${i.keys.length>1?"s":""} non reconnue${i.keys.length>1?"s":""} : ${C(i.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${i.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${i.origin}`;default:return"Entr\xE9e invalide"}}};function bC(){return{localeError:O6()}}var $6=()=>{let e={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};return i=>{switch(i.code){case"invalid_type":return`Entr\xE9e invalide : attendu ${i.expected}, re\xE7u ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Entr\xE9e invalide : attendu ${K(i.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"\u2264":"<",o=t(i.origin);return o?`Trop grand : attendu que ${i.origin??"la valeur"} ait ${s}${i.maximum.toString()} ${o.unit}`:`Trop grand : attendu que ${i.origin??"la valeur"} soit ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?"\u2265":">",o=t(i.origin);return o?`Trop petit : attendu que ${i.origin} ait ${s}${i.minimum.toString()} ${o.unit}`:`Trop petit : attendu que ${i.origin} soit ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${s.prefix}"`:s.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${s.suffix}"`:s.format==="includes"?`Cha\xEEne invalide : doit inclure "${s.includes}"`:s.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${s.pattern}`:`${n[s.format]??i.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${i.divisor}`;case"unrecognized_keys":return`Cl\xE9${i.keys.length>1?"s":""} non reconnue${i.keys.length>1?"s":""} : ${C(i.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${i.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${i.origin}`;default:return"Entr\xE9e invalide"}}};function wC(){return{localeError:$6()}}var C6=()=>{let e={string:{unit:"\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u05E7\u05DC\u05D8",email:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",url:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",emoji:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",date:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",time:"\u05D6\u05DE\u05DF ISO",duration:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",ipv4:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",ipv6:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",cidrv4:"\u05D8\u05D5\u05D5\u05D7 IPv4",cidrv6:"\u05D8\u05D5\u05D5\u05D7 IPv6",base64:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",base64url:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",json_string:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",e164:"\u05DE\u05E1\u05E4\u05E8 E.164",jwt:"JWT",template_literal:"\u05E7\u05DC\u05D8"};return i=>{switch(i.code){case"invalid_type":return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${i.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${K(i.values[0])}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${i.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${s}${i.maximum.toString()} ${o.unit??"elements"}`:`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${i.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${i.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${s}${i.minimum.toString()} ${o.unit}`:`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${i.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${s.prefix}"`:s.format==="ends_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${s.suffix}"`:s.format==="includes"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${s.includes}"`:s.format==="regex"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${s.pattern}`:`${n[s.format]??i.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${i.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${i.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${i.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${C(i.keys,", ")}`;case"invalid_key":return`\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${i.origin}`;case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${i.origin}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};function xC(){return{localeError:C6()}}var P6=()=>{let e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"sz\xE1m";case"object":{if(Array.isArray(i))return"t\xF6mb";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"};return i=>{switch(i.code){case"invalid_type":return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${i.expected}, a kapott \xE9rt\xE9k ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${K(i.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`T\xFAl nagy: ${i.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${s}${i.maximum.toString()} ${o.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${i.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${i.origin} m\xE9rete t\xFAl kicsi ${s}${i.minimum.toString()} ${o.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${i.origin} t\xFAl kicsi ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\xC9rv\xE9nytelen string: "${s.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:s.format==="ends_with"?`\xC9rv\xE9nytelen string: "${s.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:s.format==="includes"?`\xC9rv\xE9nytelen string: "${s.includes}" \xE9rt\xE9ket kell tartalmaznia`:s.format==="regex"?`\xC9rv\xE9nytelen string: ${s.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${n[s.format]??i.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${i.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${i.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${i.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};function IC(){return{localeError:P6()}}var N6=()=>{let e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Input tidak valid: diharapkan ${i.expected}, diterima ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Input tidak valid: diharapkan ${K(i.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Terlalu besar: diharapkan ${i.origin??"value"} memiliki ${s}${i.maximum.toString()} ${o.unit??"elemen"}`:`Terlalu besar: diharapkan ${i.origin??"value"} menjadi ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Terlalu kecil: diharapkan ${i.origin} memiliki ${s}${i.minimum.toString()} ${o.unit}`:`Terlalu kecil: diharapkan ${i.origin} menjadi ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`String tidak valid: harus dimulai dengan "${s.prefix}"`:s.format==="ends_with"?`String tidak valid: harus berakhir dengan "${s.suffix}"`:s.format==="includes"?`String tidak valid: harus menyertakan "${s.includes}"`:s.format==="regex"?`String tidak valid: harus sesuai pola ${s.pattern}`:`${n[s.format]??i.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${i.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${i.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${i.origin}`;default:return"Input tidak valid"}}};function SC(){return{localeError:N6()}}var R6=()=>{let e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"numero";case"object":{if(Array.isArray(i))return"vettore";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Input non valido: atteso ${i.expected}, ricevuto ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Input non valido: atteso ${K(i.values[0])}`:`Opzione non valida: atteso uno tra ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Troppo grande: ${i.origin??"valore"} deve avere ${s}${i.maximum.toString()} ${o.unit??"elementi"}`:`Troppo grande: ${i.origin??"valore"} deve essere ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Troppo piccolo: ${i.origin} deve avere ${s}${i.minimum.toString()} ${o.unit}`:`Troppo piccolo: ${i.origin} deve essere ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Stringa non valida: deve iniziare con "${s.prefix}"`:s.format==="ends_with"?`Stringa non valida: deve terminare con "${s.suffix}"`:s.format==="includes"?`Stringa non valida: deve includere "${s.includes}"`:s.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${s.pattern}`:`Invalid ${n[s.format]??i.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${i.divisor}`;case"unrecognized_keys":return`Chiav${i.keys.length>1?"i":"e"} non riconosciut${i.keys.length>1?"e":"a"}: ${C(i.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${i.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${i.origin}`;default:return"Input non valido"}}};function EC(){return{localeError:R6()}}var M6=()=>{let e={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u6570\u5024";case"object":{if(Array.isArray(i))return"\u914D\u5217";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"};return i=>{switch(i.code){case"invalid_type":return`\u7121\u52B9\u306A\u5165\u529B: ${i.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${r(i.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;case"invalid_value":return i.values.length===1?`\u7121\u52B9\u306A\u5165\u529B: ${K(i.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${C(i.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let s=i.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",o=t(i.origin);return o?`\u5927\u304D\u3059\u304E\u308B\u5024: ${i.origin??"\u5024"}\u306F${i.maximum.toString()}${o.unit??"\u8981\u7D20"}${s}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${i.origin??"\u5024"}\u306F${i.maximum.toString()}${s}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let s=i.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",o=t(i.origin);return o?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${i.origin}\u306F${i.minimum.toString()}${o.unit}${s}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${i.origin}\u306F${i.minimum.toString()}${s}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${s.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:s.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${s.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:s.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${s.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:s.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${s.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${n[s.format]??i.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${i.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${i.keys.length>1?"\u7FA4":""}: ${C(i.keys,"\u3001")}`;case"invalid_key":return`${i.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${i.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};function kC(){return{localeError:M6()}}var j6=()=>{let e={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)":"\u179B\u17C1\u1781";case"object":{if(Array.isArray(i))return"\u17A2\u17B6\u179A\u17C1 (Array)";if(i===null)return"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"};return i=>{switch(i.code){case"invalid_type":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${K(i.values[0])}`:`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${s} ${i.maximum.toString()} ${o.unit??"\u1792\u17B6\u178F\u17BB"}`:`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${s} ${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i.origin} ${s} ${i.minimum.toString()} ${o.unit}`:`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i.origin} ${s} ${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${s.prefix}"`:s.format==="ends_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${s.suffix}"`:s.format==="includes"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${s.includes}"`:s.format==="regex"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${s.pattern}`:`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${n[s.format]??i.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${i.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${C(i.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${i.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${i.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}};function AC(){return{localeError:j6()}}var D6=()=>{let e={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"};return i=>{switch(i.code){case"invalid_type":return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${i.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${r(i.input)}\uC785\uB2C8\uB2E4`;case"invalid_value":return i.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${K(i.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${C(i.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let s=i.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",o=s==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=t(i.origin),c=a?.unit??"\uC694\uC18C";return a?`${i.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${i.maximum.toString()}${c} ${s}${o}`:`${i.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${i.maximum.toString()} ${s}${o}`}case"too_small":{let s=i.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",o=s==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=t(i.origin),c=a?.unit??"\uC694\uC18C";return a?`${i.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${i.minimum.toString()}${c} ${s}${o}`:`${i.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${i.minimum.toString()} ${s}${o}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${s.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:s.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${s.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:s.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${s.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:s.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${s.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${n[s.format]??i.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${i.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${C(i.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${i.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${i.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};function TC(){return{localeError:D6()}}var z6=()=>{let e={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u0431\u0440\u043E\u0458";case"object":{if(Array.isArray(i))return"\u043D\u0438\u0437\u0430";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"};return i=>{switch(i.code){case"invalid_type":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Invalid input: expected ${K(i.values[0])}`:`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${s}${i.maximum.toString()} ${o.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i.origin} \u0434\u0430 \u0438\u043C\u0430 ${s}${i.minimum.toString()} ${o.unit}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${s.prefix}"`:s.format==="ends_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${s.suffix}"`:s.format==="includes"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${s.includes}"`:s.format==="regex"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${s.pattern}`:`Invalid ${n[s.format]??i.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${i.divisor}`;case"unrecognized_keys":return`${i.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${C(i.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${i.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${i.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};function OC(){return{localeError:z6()}}var L6=()=>{let e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"nombor";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Input tidak sah: dijangka ${i.expected}, diterima ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Input tidak sah: dijangka ${K(i.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Terlalu besar: dijangka ${i.origin??"nilai"} ${o.verb} ${s}${i.maximum.toString()} ${o.unit??"elemen"}`:`Terlalu besar: dijangka ${i.origin??"nilai"} adalah ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Terlalu kecil: dijangka ${i.origin} ${o.verb} ${s}${i.minimum.toString()} ${o.unit}`:`Terlalu kecil: dijangka ${i.origin} adalah ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`String tidak sah: mesti bermula dengan "${s.prefix}"`:s.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${s.suffix}"`:s.format==="includes"?`String tidak sah: mesti mengandungi "${s.includes}"`:s.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${s.pattern}`:`${n[s.format]??i.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${i.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${C(i.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${i.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${i.origin}`;default:return"Input tidak sah"}}};function $C(){return{localeError:L6()}}var U6=()=>{let e={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"getal";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return i=>{switch(i.code){case"invalid_type":return`Ongeldige invoer: verwacht ${i.expected}, ontving ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Ongeldige invoer: verwacht ${K(i.values[0])}`:`Ongeldige optie: verwacht \xE9\xE9n van ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Te lang: verwacht dat ${i.origin??"waarde"} ${s}${i.maximum.toString()} ${o.unit??"elementen"} bevat`:`Te lang: verwacht dat ${i.origin??"waarde"} ${s}${i.maximum.toString()} is`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Te kort: verwacht dat ${i.origin} ${s}${i.minimum.toString()} ${o.unit} bevat`:`Te kort: verwacht dat ${i.origin} ${s}${i.minimum.toString()} is`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Ongeldige tekst: moet met "${s.prefix}" beginnen`:s.format==="ends_with"?`Ongeldige tekst: moet op "${s.suffix}" eindigen`:s.format==="includes"?`Ongeldige tekst: moet "${s.includes}" bevatten`:s.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${s.pattern}`:`Ongeldig: ${n[s.format]??i.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${i.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${i.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${i.origin}`;default:return"Ongeldige invoer"}}};function CC(){return{localeError:U6()}}var F6=()=>{let e={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"tall";case"object":{if(Array.isArray(i))return"liste";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Ugyldig input: forventet ${i.expected}, fikk ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Ugyldig verdi: forventet ${K(i.values[0])}`:`Ugyldig valg: forventet en av ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`For stor(t): forventet ${i.origin??"value"} til \xE5 ha ${s}${i.maximum.toString()} ${o.unit??"elementer"}`:`For stor(t): forventet ${i.origin??"value"} til \xE5 ha ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`For lite(n): forventet ${i.origin} til \xE5 ha ${s}${i.minimum.toString()} ${o.unit}`:`For lite(n): forventet ${i.origin} til \xE5 ha ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${s.prefix}"`:s.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${s.suffix}"`:s.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${s.includes}"`:s.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${s.pattern}`:`Ugyldig ${n[s.format]??i.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${i.divisor}`;case"unrecognized_keys":return`${i.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${C(i.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${i.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${i.origin}`;default:return"Ugyldig input"}}};function PC(){return{localeError:F6()}}var B6=()=>{let e={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"numara";case"object":{if(Array.isArray(i))return"saf";if(i===null)return"gayb";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"};return i=>{switch(i.code){case"invalid_type":return`F\xE2sit giren: umulan ${i.expected}, al\u0131nan ${r(i.input)}`;case"invalid_value":return i.values.length===1?`F\xE2sit giren: umulan ${K(i.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Fazla b\xFCy\xFCk: ${i.origin??"value"}, ${s}${i.maximum.toString()} ${o.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${i.origin??"value"}, ${s}${i.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Fazla k\xFC\xE7\xFCk: ${i.origin}, ${s}${i.minimum.toString()} ${o.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${i.origin}, ${s}${i.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let s=i;return s.format==="starts_with"?`F\xE2sit metin: "${s.prefix}" ile ba\u015Flamal\u0131.`:s.format==="ends_with"?`F\xE2sit metin: "${s.suffix}" ile bitmeli.`:s.format==="includes"?`F\xE2sit metin: "${s.includes}" ihtiv\xE2 etmeli.`:s.format==="regex"?`F\xE2sit metin: ${s.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${n[s.format]??i.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${i.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`${i.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${i.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};function NC(){return{localeError:B6()}}var V6=()=>{let e={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(i))return"\u0627\u0631\u06D0";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"};return i=>{switch(i.code){case"invalid_type":return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${i.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${r(i.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;case"invalid_value":return i.values.length===1?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${K(i.values[0])} \u0648\u0627\u06CC`:`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${C(i.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${i.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${s}${i.maximum.toString()} ${o.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${i.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${s}${i.maximum.toString()} \u0648\u064A`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${i.origin} \u0628\u0627\u06CC\u062F ${s}${i.minimum.toString()} ${o.unit} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${i.origin} \u0628\u0627\u06CC\u062F ${s}${i.minimum.toString()} \u0648\u064A`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${s.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`:s.format==="ends_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${s.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`:s.format==="includes"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${s.includes}" \u0648\u0644\u0631\u064A`:s.format==="regex"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${s.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`:`${n[s.format]??i.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${i.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${i.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${C(i.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${i.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${i.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};function RC(){return{localeError:V6()}}var Z6=()=>{let e={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"liczba";case"object":{if(Array.isArray(i))return"tablica";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"};return i=>{switch(i.code){case"invalid_type":return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${i.expected}, otrzymano ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${K(i.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${i.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${s}${i.maximum.toString()} ${o.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${i.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${i.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${s}${i.minimum.toString()} ${o.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${i.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${s.prefix}"`:s.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${s.suffix}"`:s.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${s.includes}"`:s.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${s.pattern}`:`Nieprawid\u0142ow(y/a/e) ${n[s.format]??i.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${i.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${i.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${i.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};function MC(){return{localeError:Z6()}}var G6=()=>{let e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(i))return"array";if(i===null)return"nulo";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return i=>{switch(i.code){case"invalid_type":return`Tipo inv\xE1lido: esperado ${i.expected}, recebido ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Entrada inv\xE1lida: esperado ${K(i.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Muito grande: esperado que ${i.origin??"valor"} tivesse ${s}${i.maximum.toString()} ${o.unit??"elementos"}`:`Muito grande: esperado que ${i.origin??"valor"} fosse ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Muito pequeno: esperado que ${i.origin} tivesse ${s}${i.minimum.toString()} ${o.unit}`:`Muito pequeno: esperado que ${i.origin} fosse ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${s.prefix}"`:s.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${s.suffix}"`:s.format==="includes"?`Texto inv\xE1lido: deve incluir "${s.includes}"`:s.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${s.pattern}`:`${n[s.format]??i.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${i.divisor}`;case"unrecognized_keys":return`Chave${i.keys.length>1?"s":""} desconhecida${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${i.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${i.origin}`;default:return"Campo inv\xE1lido"}}};function jC(){return{localeError:G6()}}function DC(e,t,r,n){let i=Math.abs(e),s=i%10,o=i%100;return o>=11&&o<=19?n:s===1?t:s>=2&&s<=4?r:n}var K6=()=>{let e={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(i))return"\u043C\u0430\u0441\u0441\u0438\u0432";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"};return i=>{switch(i.code){case"invalid_type":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${i.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${K(i.values[0])}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);if(o){let a=Number(i.maximum),c=DC(a,o.unit.one,o.unit.few,o.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${s}${i.maximum.toString()} ${c}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);if(o){let a=Number(i.minimum),c=DC(a,o.unit.one,o.unit.few,o.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${i.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${s}${i.minimum.toString()} ${c}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${i.origin} \u0431\u0443\u0434\u0435\u0442 ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${s.prefix}"`:s.format==="ends_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${s.suffix}"`:s.format==="includes"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${s.includes}"`:s.format==="regex"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${s.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${n[s.format]??i.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${i.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${i.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${i.keys.length>1?"\u0438":""}: ${C(i.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${i.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${i.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}};function zC(){return{localeError:K6()}}var q6=()=>{let e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u0161tevilo";case"object":{if(Array.isArray(i))return"tabela";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"};return i=>{switch(i.code){case"invalid_type":return`Neveljaven vnos: pri\u010Dakovano ${i.expected}, prejeto ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${K(i.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Preveliko: pri\u010Dakovano, da bo ${i.origin??"vrednost"} imelo ${s}${i.maximum.toString()} ${o.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${i.origin??"vrednost"} ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Premajhno: pri\u010Dakovano, da bo ${i.origin} imelo ${s}${i.minimum.toString()} ${o.unit}`:`Premajhno: pri\u010Dakovano, da bo ${i.origin} ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${s.prefix}"`:s.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${s.suffix}"`:s.format==="includes"?`Neveljaven niz: mora vsebovati "${s.includes}"`:s.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${s.pattern}`:`Neveljaven ${n[s.format]??i.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${i.divisor}`;case"unrecognized_keys":return`Neprepoznan${i.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${C(i.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${i.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${i.origin}`;default:return"Neveljaven vnos"}}};function LC(){return{localeError:q6()}}var H6=()=>{let e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"antal";case"object":{if(Array.isArray(i))return"lista";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return i=>{switch(i.code){case"invalid_type":return`Ogiltig inmatning: f\xF6rv\xE4ntat ${i.expected}, fick ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Ogiltig inmatning: f\xF6rv\xE4ntat ${K(i.values[0])}`:`Ogiltigt val: f\xF6rv\xE4ntade en av ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`F\xF6r stor(t): f\xF6rv\xE4ntade ${i.origin??"v\xE4rdet"} att ha ${s}${i.maximum.toString()} ${o.unit??"element"}`:`F\xF6r stor(t): f\xF6rv\xE4ntat ${i.origin??"v\xE4rdet"} att ha ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`F\xF6r lite(t): f\xF6rv\xE4ntade ${i.origin??"v\xE4rdet"} att ha ${s}${i.minimum.toString()} ${o.unit}`:`F\xF6r lite(t): f\xF6rv\xE4ntade ${i.origin??"v\xE4rdet"} att ha ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${s.prefix}"`:s.format==="ends_with"?`Ogiltig str\xE4ng: m\xE5ste sluta med "${s.suffix}"`:s.format==="includes"?`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${s.includes}"`:s.format==="regex"?`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${s.pattern}"`:`Ogiltig(t) ${n[s.format]??i.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${i.divisor}`;case"unrecognized_keys":return`${i.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${C(i.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${i.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${i.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};function UC(){return{localeError:H6()}}var W6=()=>{let e={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1":"\u0B8E\u0BA3\u0BCD";case"object":{if(Array.isArray(i))return"\u0B85\u0BA3\u0BBF";if(i===null)return"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${K(i.values[0])}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${C(i.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${s}${i.maximum.toString()} ${o.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${s}${i.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i.origin} ${s}${i.minimum.toString()} ${o.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i.origin} ${s}${i.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${s.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:s.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${s.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:s.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${s.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:s.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${s.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${n[s.format]??i.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${i.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${i.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${C(i.keys,", ")}`;case"invalid_key":return`${i.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${i.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}};function FC(){return{localeError:W6()}}var J6=()=>{let e={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)":"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02";case"object":{if(Array.isArray(i))return"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)";if(i===null)return"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"};return i=>{switch(i.code){case"invalid_type":return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${i.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${K(i.values[0])}`:`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",o=t(i.origin);return o?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${i.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${s} ${i.maximum.toString()} ${o.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`:`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${i.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${s} ${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",o=t(i.origin);return o?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${i.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${s} ${i.minimum.toString()} ${o.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${i.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${s} ${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${s.prefix}"`:s.format==="ends_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${s.suffix}"`:s.format==="includes"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${s.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:s.format==="regex"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${s.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${n[s.format]??i.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${i.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${C(i.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${i.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${i.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};function BC(){return{localeError:J6()}}var X6=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},Y6=()=>{let e={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function t(n){return e[n]??null}let r={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"};return n=>{switch(n.code){case"invalid_type":return`Ge\xE7ersiz de\u011Fer: beklenen ${n.expected}, al\u0131nan ${X6(n.input)}`;case"invalid_value":return n.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${K(n.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${C(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);return s?`\xC7ok b\xFCy\xFCk: beklenen ${n.origin??"de\u011Fer"} ${i}${n.maximum.toString()} ${s.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${n.origin??"de\u011Fer"} ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);return s?`\xC7ok k\xFC\xE7\xFCk: beklenen ${n.origin} ${i}${n.minimum.toString()} ${s.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${n.origin} ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;return i.format==="starts_with"?`Ge\xE7ersiz metin: "${i.prefix}" ile ba\u015Flamal\u0131`:i.format==="ends_with"?`Ge\xE7ersiz metin: "${i.suffix}" ile bitmeli`:i.format==="includes"?`Ge\xE7ersiz metin: "${i.includes}" i\xE7ermeli`:i.format==="regex"?`Ge\xE7ersiz metin: ${i.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${r[i.format]??n.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${n.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${n.keys.length>1?"lar":""}: ${C(n.keys,", ")}`;case"invalid_key":return`${n.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${n.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};function VC(){return{localeError:Y6()}}var Q6=()=>{let e={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(i))return"\u043C\u0430\u0441\u0438\u0432";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"};return i=>{switch(i.code){case"invalid_type":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${i.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${K(i.values[0])}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${o.verb} ${s}${i.maximum.toString()} ${o.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${i.origin} ${o.verb} ${s}${i.minimum.toString()} ${o.unit}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${i.origin} \u0431\u0443\u0434\u0435 ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${s.prefix}"`:s.format==="ends_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${s.suffix}"`:s.format==="includes"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${s.includes}"`:s.format==="regex"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${s.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${n[s.format]??i.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${i.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${i.keys.length>1?"\u0456":""}: ${C(i.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${i.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${i.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}};function ZC(){return{localeError:Q6()}}var eB=()=>{let e={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u0646\u0645\u0628\u0631";case"object":{if(Array.isArray(i))return"\u0622\u0631\u06D2";if(i===null)return"\u0646\u0644";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"};return i=>{switch(i.code){case"invalid_type":return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${i.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${r(i.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;case"invalid_value":return i.values.length===1?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${K(i.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${C(i.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${i.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${s}${i.maximum.toString()} ${o.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0628\u0691\u0627: ${i.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${s}${i.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${i.origin} \u06A9\u06D2 ${s}${i.minimum.toString()} ${o.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${i.origin} \u06A9\u0627 ${s}${i.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${s.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:s.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${s.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:s.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${s.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:s.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${s.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${n[s.format]??i.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${i.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${i.keys.length>1?"\u0632":""}: ${C(i.keys,"\u060C ")}`;case"invalid_key":return`${i.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${i.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};function GC(){return{localeError:eB()}}var tB=()=>{let e={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"s\u1ED1";case"object":{if(Array.isArray(i))return"m\u1EA3ng";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"};return i=>{switch(i.code){case"invalid_type":return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${i.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${K(i.values[0])}`:`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${i.origin??"gi\xE1 tr\u1ECB"} ${o.verb} ${s}${i.maximum.toString()} ${o.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${i.origin??"gi\xE1 tr\u1ECB"} ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${i.origin} ${o.verb} ${s}${i.minimum.toString()} ${o.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${i.origin} ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${s.prefix}"`:s.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${s.suffix}"`:s.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${s.includes}"`:s.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${s.pattern}`:`${n[s.format]??i.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${i.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${C(i.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${i.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${i.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};function KC(){return{localeError:tB()}}var rB=()=>{let e={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"\u975E\u6570\u5B57(NaN)":"\u6570\u5B57";case"object":{if(Array.isArray(i))return"\u6570\u7EC4";if(i===null)return"\u7A7A\u503C(null)";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"};return i=>{switch(i.code){case"invalid_type":return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${i.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${K(i.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${i.origin??"\u503C"} ${s}${i.maximum.toString()} ${o.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${i.origin??"\u503C"} ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${i.origin} ${s}${i.minimum.toString()} ${o.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${i.origin} ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${s.prefix}" \u5F00\u5934`:s.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${s.suffix}" \u7ED3\u5C3E`:s.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${s.includes}"`:s.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${s.pattern}`:`\u65E0\u6548${n[s.format]??i.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${i.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${C(i.keys,", ")}`;case"invalid_key":return`${i.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${i.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};function qC(){return{localeError:rB()}}var nB=()=>{let e={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"};return i=>{switch(i.code){case"invalid_type":return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${i.expected}\uFF0C\u4F46\u6536\u5230 ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${K(i.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${i.origin??"\u503C"} \u61C9\u70BA ${s}${i.maximum.toString()} ${o.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${i.origin??"\u503C"} \u61C9\u70BA ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${i.origin} \u61C9\u70BA ${s}${i.minimum.toString()} ${o.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${i.origin} \u61C9\u70BA ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${s.prefix}" \u958B\u982D`:s.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${s.suffix}" \u7D50\u5C3E`:s.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${s.includes}"`:s.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${s.pattern}`:`\u7121\u6548\u7684 ${n[s.format]??i.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${i.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${i.keys.length>1?"\u5011":""}\uFF1A${C(i.keys,"\u3001")}`;case"invalid_key":return`${i.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${i.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};function HC(){return{localeError:nB()}}var Vw=Symbol("ZodOutput"),Zw=Symbol("ZodInput"),Sc=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){let n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function km(){return new Sc}var ct=km();function Gw(e,t){return new e({type:"string",...F(t)})}function Kw(e,t){return new e({type:"string",coerce:!0,...F(t)})}function Am(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...F(t)})}function Ql(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...F(t)})}function Tm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...F(t)})}function Om(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...F(t)})}function $m(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...F(t)})}function Cm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...F(t)})}function Pm(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...F(t)})}function Nm(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...F(t)})}function Rm(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...F(t)})}function Mm(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...F(t)})}function jm(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...F(t)})}function Dm(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...F(t)})}function zm(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...F(t)})}function Lm(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...F(t)})}function Um(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...F(t)})}function Fm(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...F(t)})}function Bm(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...F(t)})}function Vm(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...F(t)})}function Zm(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...F(t)})}function Gm(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...F(t)})}function Km(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...F(t)})}function qm(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...F(t)})}var qw={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Hw(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...F(t)})}function Ww(e,t){return new e({type:"string",format:"date",check:"string_format",...F(t)})}function Jw(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...F(t)})}function Xw(e,t){return new e({type:"string",format:"duration",check:"string_format",...F(t)})}function Yw(e,t){return new e({type:"number",checks:[],...F(t)})}function Qw(e,t){return new e({type:"number",coerce:!0,checks:[],...F(t)})}function ex(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...F(t)})}function tx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...F(t)})}function rx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...F(t)})}function nx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...F(t)})}function ix(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...F(t)})}function sx(e,t){return new e({type:"boolean",...F(t)})}function ox(e,t){return new e({type:"boolean",coerce:!0,...F(t)})}function ax(e,t){return new e({type:"bigint",...F(t)})}function cx(e,t){return new e({type:"bigint",coerce:!0,...F(t)})}function ux(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...F(t)})}function lx(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...F(t)})}function px(e,t){return new e({type:"symbol",...F(t)})}function dx(e,t){return new e({type:"undefined",...F(t)})}function fx(e,t){return new e({type:"null",...F(t)})}function mx(e){return new e({type:"any"})}function Gs(e){return new e({type:"unknown"})}function ep(e,t){return new e({type:"never",...F(t)})}function hx(e,t){return new e({type:"void",...F(t)})}function gx(e,t){return new e({type:"date",...F(t)})}function _x(e,t){return new e({type:"date",coerce:!0,...F(t)})}function yx(e,t){return new e({type:"nan",...F(t)})}function qi(e,t){return new ym({check:"less_than",...F(t),value:e,inclusive:!1})}function pn(e,t){return new ym({check:"less_than",...F(t),value:e,inclusive:!0})}function Hi(e,t){return new vm({check:"greater_than",...F(t),value:e,inclusive:!1})}function Pr(e,t){return new vm({check:"greater_than",...F(t),value:e,inclusive:!0})}function vx(e){return Hi(0,e)}function bx(e){return qi(0,e)}function wx(e){return pn(0,e)}function xx(e){return Pr(0,e)}function Xo(e,t){return new Ib({check:"multiple_of",...F(t),value:e})}function Ec(e,t){return new kb({check:"max_size",...F(t),maximum:e})}function Yo(e,t){return new Ab({check:"min_size",...F(t),minimum:e})}function tp(e,t){return new Tb({check:"size_equals",...F(t),size:e})}function kc(e,t){return new Ob({check:"max_length",...F(t),maximum:e})}function Ks(e,t){return new $b({check:"min_length",...F(t),minimum:e})}function Ac(e,t){return new Cb({check:"length_equals",...F(t),length:e})}function rp(e,t){return new Pb({check:"string_format",format:"regex",...F(t),pattern:e})}function np(e){return new Nb({check:"string_format",format:"lowercase",...F(e)})}function ip(e){return new Rb({check:"string_format",format:"uppercase",...F(e)})}function sp(e,t){return new Mb({check:"string_format",format:"includes",...F(t),includes:e})}function op(e,t){return new jb({check:"string_format",format:"starts_with",...F(t),prefix:e})}function ap(e,t){return new Db({check:"string_format",format:"ends_with",...F(t),suffix:e})}function Ix(e,t,r){return new zb({check:"property",property:e,schema:t,...F(r)})}function cp(e,t){return new Lb({check:"mime_type",mime:e,...F(t)})}function Wi(e){return new Ub({check:"overwrite",tx:e})}function up(e){return Wi(t=>t.normalize(e))}function lp(){return Wi(e=>e.trim())}function pp(){return Wi(e=>e.toLowerCase())}function dp(){return Wi(e=>e.toUpperCase())}function fp(e,t,r){return new e({type:"array",element:t,...F(r)})}function iB(e,t,r){return new e({type:"union",options:t,...F(r)})}function sB(e,t,r,n){return new e({type:"union",options:r,discriminator:t,...F(n)})}function oB(e,t,r){return new e({type:"intersection",left:t,right:r})}function Sx(e,t,r,n){let i=r instanceof ye,s=i?n:r,o=i?r:null;return new e({type:"tuple",items:t,rest:o,...F(s)})}function aB(e,t,r,n){return new e({type:"record",keyType:t,valueType:r,...F(n)})}function cB(e,t,r,n){return new e({type:"map",keyType:t,valueType:r,...F(n)})}function uB(e,t,r){return new e({type:"set",valueType:t,...F(r)})}function lB(e,t,r){let n=Array.isArray(t)?Object.fromEntries(t.map(i=>[i,i])):t;return new e({type:"enum",entries:n,...F(r)})}function pB(e,t,r){return new e({type:"enum",entries:t,...F(r)})}function dB(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...F(r)})}function Ex(e,t){return new e({type:"file",...F(t)})}function fB(e,t){return new e({type:"transform",transform:t})}function mB(e,t){return new e({type:"optional",innerType:t})}function hB(e,t){return new e({type:"nullable",innerType:t})}function gB(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}function _B(e,t,r){return new e({type:"nonoptional",innerType:t,...F(r)})}function yB(e,t){return new e({type:"success",innerType:t})}function vB(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}function bB(e,t,r){return new e({type:"pipe",in:t,out:r})}function wB(e,t){return new e({type:"readonly",innerType:t})}function xB(e,t,r){return new e({type:"template_literal",parts:t,...F(r)})}function IB(e,t){return new e({type:"lazy",getter:t})}function SB(e,t){return new e({type:"promise",innerType:t})}function kx(e,t,r){let n=F(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Ax(e,t,r){return new e({type:"custom",check:"custom",fn:t,...F(r)})}function Tx(e,t){let r=F(t),n=r.truthy??["true","1","yes","on","y","enabled"],i=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(n=n.map(m=>typeof m=="string"?m.toLowerCase():m),i=i.map(m=>typeof m=="string"?m.toLowerCase():m));let s=new Set(n),o=new Set(i),a=e.Pipe??Xl,c=e.Boolean??ql,u=e.String??Wo,l=e.Transform??Jl,p=new l({type:"transform",transform:(m,h)=>{let b=m;return r.case!=="sensitive"&&(b=b.toLowerCase()),s.has(b)?!0:o.has(b)?!1:(h.issues.push({code:"invalid_value",expected:"stringbool",values:[...s,...o],input:h.value,inst:p}),{})},error:r.error}),f=new a({type:"pipe",in:new u({type:"string",error:r.error}),out:p,error:r.error});return new a({type:"pipe",in:f,out:new c({type:"boolean",error:r.error}),error:r.error})}function Ox(e,t,r,n={}){let i=F(n),s={...F(n),check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:a=>r.test(a),...i};return r instanceof RegExp&&(s.pattern=r),new e(s)}var Hm=class{constructor(t){this._def=t,this.def=t}implement(t){if(typeof t!="function")throw new Error("implement() must be called with a function");let r=((...n)=>{let i=this._def.input?ui(this._def.input,n,void 0,{callee:r}):n;if(!Array.isArray(i))throw new Error("Invalid arguments schema: not an array or tuple schema.");let s=t(...i);return this._def.output?ui(this._def.output,s,void 0,{callee:r}):s});return r}implementAsync(t){if(typeof t!="function")throw new Error("implement() must be called with a function");let r=(async(...n)=>{let i=this._def.input?await Ko(this._def.input,n,void 0,{callee:r}):n;if(!Array.isArray(i))throw new Error("Invalid arguments schema: not an array or tuple schema.");let s=await t(...i);return this._def.output?Ko(this._def.output,s,void 0,{callee:r}):s});return r}input(...t){let r=this.constructor;return Array.isArray(t[0])?new r({type:"function",input:new Jo({type:"tuple",items:t[0],rest:t[1]}),output:this._def.output}):new r({type:"function",input:t[0],output:this._def.output})}output(t){let r=this.constructor;return new r({type:"function",input:this._def.input,output:t})}};function $x(e){return new Hm({type:"function",input:Array.isArray(e?.input)?Sx(Jo,e?.input):e?.input??fp(Wl,Gs(Zs)),output:e?.output??Gs(Zs)})}var mp=class{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??ct,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;let i=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(t);if(o)return o.count++,r.schemaPath.includes(t)&&(o.cycle=r.path),o.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,a);let c=t._zod.toJSONSchema?.();if(c)a.schema=c;else{let p={...r,schemaPath:[...r.schemaPath,t],path:r.path},f=t._zod.parent;if(f)a.ref=f,this.process(f,p),this.seen.get(f).isParent=!0;else{let d=a.schema;switch(i.type){case"string":{let m=d;m.type="string";let{minimum:h,maximum:b,format:_,patterns:y,contentEncoding:x}=t._zod.bag;if(typeof h=="number"&&(m.minLength=h),typeof b=="number"&&(m.maxLength=b),_&&(m.format=s[_]??_,m.format===""&&delete m.format),x&&(m.contentEncoding=x),y&&y.size>0){let I=[...y];I.length===1?m.pattern=I[0].source:I.length>1&&(a.schema.allOf=[...I.map(A=>({...this.target==="draft-7"?{type:"string"}:{},pattern:A.source}))])}break}case"number":{let m=d,{minimum:h,maximum:b,format:_,multipleOf:y,exclusiveMaximum:x,exclusiveMinimum:I}=t._zod.bag;typeof _=="string"&&_.includes("int")?m.type="integer":m.type="number",typeof I=="number"&&(m.exclusiveMinimum=I),typeof h=="number"&&(m.minimum=h,typeof I=="number"&&(I>=h?delete m.minimum:delete m.exclusiveMinimum)),typeof x=="number"&&(m.exclusiveMaximum=x),typeof b=="number"&&(m.maximum=b,typeof x=="number"&&(x<=b?delete m.maximum:delete m.exclusiveMaximum)),typeof y=="number"&&(m.multipleOf=y);break}case"boolean":{let m=d;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{d.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{d.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=d,{minimum:h,maximum:b}=t._zod.bag;typeof h=="number"&&(m.minItems=h),typeof b=="number"&&(m.maxItems=b),m.type="array",m.items=this.process(i.element,{...p,path:[...p.path,"items"]});break}case"object":{let m=d;m.type="object",m.properties={};let h=i.shape;for(let y in h)m.properties[y]=this.process(h[y],{...p,path:[...p.path,"properties",y]});let b=new Set(Object.keys(h)),_=new Set([...b].filter(y=>{let x=i.shape[y]._zod;return this.io==="input"?x.optin===void 0:x.optout===void 0}));_.size>0&&(m.required=Array.from(_)),i.catchall?._zod.def.type==="never"?m.additionalProperties=!1:i.catchall?i.catchall&&(m.additionalProperties=this.process(i.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=d;m.anyOf=i.options.map((h,b)=>this.process(h,{...p,path:[...p.path,"anyOf",b]}));break}case"intersection":{let m=d,h=this.process(i.left,{...p,path:[...p.path,"allOf",0]}),b=this.process(i.right,{...p,path:[...p.path,"allOf",1]}),_=x=>"allOf"in x&&Object.keys(x).length===1,y=[..._(h)?h.allOf:[h],..._(b)?b.allOf:[b]];m.allOf=y;break}case"tuple":{let m=d;m.type="array";let h=i.items.map((y,x)=>this.process(y,{...p,path:[...p.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?m.prefixItems=h:m.items=h,i.rest){let y=this.process(i.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?m.items=y:m.additionalItems=y}i.rest&&(m.items=this.process(i.rest,{...p,path:[...p.path,"items"]}));let{minimum:b,maximum:_}=t._zod.bag;typeof b=="number"&&(m.minItems=b),typeof _=="number"&&(m.maxItems=_);break}case"record":{let m=d;m.type="object",m.propertyNames=this.process(i.keyType,{...p,path:[...p.path,"propertyNames"]}),m.additionalProperties=this.process(i.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=d,h=Dl(i.entries);h.every(b=>typeof b=="number")&&(m.type="number"),h.every(b=>typeof b=="string")&&(m.type="string"),m.enum=h;break}case"literal":{let m=d,h=[];for(let b of i.values)if(b===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof b=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(b))}else h.push(b);if(h.length!==0)if(h.length===1){let b=h[0];m.type=b===null?"null":typeof b,m.const=b}else h.every(b=>typeof b=="number")&&(m.type="number"),h.every(b=>typeof b=="string")&&(m.type="string"),h.every(b=>typeof b=="boolean")&&(m.type="string"),h.every(b=>b===null)&&(m.type="null"),m.enum=h;break}case"file":{let m=d,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:b,maximum:_,mime:y}=t._zod.bag;b!==void 0&&(h.minLength=b),_!==void 0&&(h.maxLength=_),y?y.length===1?(h.contentMediaType=y[0],Object.assign(m,h)):m.anyOf=y.map(x=>({...h,contentMediaType:x})):Object.assign(m,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(i.innerType,p);d.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(i.innerType,p),a.ref=i.innerType;break}case"success":{let m=d;m.type="boolean";break}case"default":{this.process(i.innerType,p),a.ref=i.innerType,d.default=JSON.parse(JSON.stringify(i.defaultValue));break}case"prefault":{this.process(i.innerType,p),a.ref=i.innerType,this.io==="input"&&(d._prefault=JSON.parse(JSON.stringify(i.defaultValue)));break}case"catch":{this.process(i.innerType,p),a.ref=i.innerType;let m;try{m=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}d.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=d,h=t._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=h.source;break}case"pipe":{let m=this.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;this.process(m,p),a.ref=m;break}case"readonly":{this.process(i.innerType,p),a.ref=i.innerType,d.readOnly=!0;break}case"promise":{this.process(i.innerType,p),a.ref=i.innerType;break}case"optional":{this.process(i.innerType,p),a.ref=i.innerType;break}case"lazy":{let m=t._zod.innerType;this.process(m,p),a.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(t);return u&&Object.assign(a.schema,u),this.io==="input"&&Ct(t)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(t).schema}emit(t,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},i=this.seen.get(t);if(!i)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(l[0])?.id,b=n.external.uri??(y=>y);if(h)return{ref:b(h)};let _=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=_,{defId:_,ref:`${b("__shared")}#/${p}/${_}`}}if(l[1]===i)return{ref:"#"};let d=`#/${p}/`,m=l[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:d+m}},o=l=>{if(l[1].schema.$ref)return;let p=l[1],{ref:f,defId:d}=s(l);p.def={...p.schema},d&&(p.defId=d);let m=p.schema;for(let h in m)delete m[h];m.$ref=f};if(n.cycles==="throw")for(let l of this.seen.entries()){let p=l[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
85
-
86
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let p=l[1];if(t===l[0]){o(l);continue}if(n.external){let d=n.external.registry.get(l[0])?.id;if(t!==l[0]&&d){o(l);continue}}if(this.metadataRegistry.get(l[0])?.id){o(l);continue}if(p.cycle){o(l);continue}if(p.count>1&&n.reused==="ref"){o(l);continue}}let a=(l,p)=>{let f=this.seen.get(l),d=f.def??f.schema,m={...d};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){a(h,p);let b=this.seen.get(h).schema;b.$ref&&p.target==="draft-7"?(d.allOf=d.allOf??[],d.allOf.push(b)):(Object.assign(d,b),Object.assign(d,m))}f.isParent||this.override({zodSchema:l,jsonSchema:d,path:f.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(t)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,i.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let p=l[1];p.def&&p.defId&&(u[p.defId]=p.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function qs(e,t){if(e instanceof Sc){let n=new mp(t),i={};for(let a of e._idmap.entries()){let[c,u]=a;n.process(u)}let s={},o={registry:e,uri:t?.uri,defs:i};for(let a of e._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...t,external:o})}if(Object.keys(i).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:i}}return{schemas:s}}let r=new mp(t);return r.process(e),r.emit(e,t)}function Ct(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let i=e._zod.def;switch(i.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ct(i.element,r);case"object":{for(let s in i.shape)if(Ct(i.shape[s],r))return!0;return!1}case"union":{for(let s of i.options)if(Ct(s,r))return!0;return!1}case"intersection":return Ct(i.left,r)||Ct(i.right,r);case"tuple":{for(let s of i.items)if(Ct(s,r))return!0;return!!(i.rest&&Ct(i.rest,r))}case"record":return Ct(i.keyType,r)||Ct(i.valueType,r);case"map":return Ct(i.keyType,r)||Ct(i.valueType,r);case"set":return Ct(i.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ct(i.innerType,r);case"lazy":return Ct(i.getter(),r);case"default":return Ct(i.innerType,r);case"prefault":return Ct(i.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ct(i.in,r)||Ct(i.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${i.type}`)}var WC={};function We(e){if(typeof e!="object"||e===null)return!1;let t=e;if(!("_zod"in t))return!1;let r=t._zod;return typeof r=="object"&&r!==null&&"def"in r}function it(e){if(typeof e!="object"||e===null)return!1;let t=e;if(!("_def"in t)||"_zod"in t)return!1;let r=t._def;return typeof r=="object"&&r!=null&&"typeName"in r}function JC(e){return We(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),it(e)}function _r(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(We(e)||it(e))}function Cx(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodLiteral"}function Px(e){return We(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="literal":!1}function XC(e){return!!(Cx(e)||Px(e))}async function Jm(e,t){if(We(e))try{return{success:!0,data:await Ko(e,t)}}catch(r){return{success:!1,error:r}}if(it(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Hs(e,t){if(We(e))return await Ko(e,t);if(it(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function YC(e,t){if(We(e))try{return{success:!0,data:ui(e,t)}}catch(r){return{success:!1,error:r}}if(it(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Oc(e,t){if(We(e))return ui(e,t);if(it(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function On(e){if(We(e))return ct.get(e)?.description;if(it(e)||"description"in e&&typeof e.description=="string")return e.description}function QC(e){if(!_r(e))return!1;if(it(e)){let t=e._def;if(t.typeName==="ZodObject"){let r=e;return!r.shape||Object.keys(r.shape).length===0}if(t.typeName==="ZodRecord")return!0}if(We(e)){let t=e._zod.def;if(t.type==="object"){let r=e;return!r.shape||Object.keys(r.shape).length===0}if(t.type==="record")return!0}return typeof e=="object"&&e!==null&&!("shape"in e)}function $c(e){return _r(e)?it(e)?e._def.typeName==="ZodString":We(e)?e._zod.def.type==="string":!1:!1}function Xm(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodObject"}function dn(e){return We(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="object":!1}function hp(e){return We(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="array":!1}function Nx(e){return We(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="optional":!1}function Rx(e){return We(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="nullable":!1}function yr(e){return!!(Xm(e)||dn(e))}function ea(e){if(it(e))return e.shape;if(We(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ym(e,t){if(it(e))return e.extend(t);if(We(e))return G.extend(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Cc(e){if(it(e))return e.partial();if(We(e))return G.partial(Ic,e,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Tc(e,t=!1){if(it(e))return e.strict();if(dn(e)){let r=e._zod.def.shape;if(t)for(let[s,o]of Object.entries(e._zod.def.shape)){if(dn(o)){let c=Tc(o,t);r[s]=c}else if(hp(o)){let c=o._zod.def.element;dn(c)&&(c=Tc(c,t)),r[s]=lt(o,{...o._zod.def,element:c})}else r[s]=o;let a=ct.get(o);a&&ct.add(r[s],a)}let n=lt(e,{...e._zod.def,shape:r,catchall:ep(Hl)}),i=ct.get(e);return i&&ct.add(n,i),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Wm(e,t=!1){if(Xm(e))return e.passthrough();if(dn(e)){let r=e._zod.def.shape;if(t)for(let[s,o]of Object.entries(e._zod.def.shape)){if(dn(o)){let c=Wm(o,t);r[s]=c}else if(hp(o)){let c=o._zod.def.element;dn(c)&&(c=Wm(c,t)),r[s]=lt(o,{...o._zod.def,element:c})}else r[s]=o;let a=ct.get(o);a&&ct.add(r[s],a)}let n=lt(e,{...e._zod.def,shape:r,catchall:Gs(Zs)}),i=ct.get(e);return i&&ct.add(n,i),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Qm(e){if(it(e))try{let t=e.parse(void 0);return()=>t}catch{return}if(We(e))try{let t=ui(e,void 0);return()=>t}catch{return}}function EB(e){return it(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function kB(e){return We(e)&&e._zod.def.type==="pipe"}function Qo(e,t,r){let n=r.get(e);if(n!==void 0)return n;if(it(e))return EB(e)?Qo(e._def.schema,t,r):e;if(We(e)){let i=e;if(kB(e)&&(i=Qo(e._zod.def.in,t,r)),t){if(dn(i)){let o={};for(let[a,c]of Object.entries(i._zod.def.shape))o[a]=Qo(c,t,r);i=lt(i,{...i._zod.def,shape:o})}else if(hp(i)){let o=Qo(i._zod.def.element,t,r);i=lt(i,{...i._zod.def,element:o})}else if(Nx(i)){let o=Qo(i._zod.def.innerType,t,r);i=lt(i,{...i._zod.def,innerType:o})}else if(Rx(i)){let o=Qo(i._zod.def.innerType,t,r);i=lt(i,{...i._zod.def,innerType:o})}}let s=ct.get(e);return s&&ct.add(i,s),r.set(e,i),i}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function eh(e,t=!1){return Qo(e,t,new WeakMap)}function eP(e,t){if(it(e)){let r=ea(e),n={};for(let[i,s]of Object.entries(r))t(i,s)?n[i]=s.optional():n[i]=s;return e.extend(n)}if(We(e)){let r=ea(e),n={...e._zod.def.shape};for(let[o,a]of Object.entries(r))t(o,a)&&(n[o]=new Ic({type:"optional",innerType:a}));let i=lt(e,{...e._zod.def,shape:n}),s=ct.get(e);return s&&ct.add(i,s),i}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function th(e){return e instanceof Error&&(e.constructor.name==="ZodError"||e.constructor.name==="$ZodError")}var rP=Symbol("Let zodToJsonSchema decide on which parser to use"),tP={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},nP=e=>typeof e=="string"?{...tP,name:e}:{...tP,...e};var iP=e=>{let t=nP(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};var rh=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function ut(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?rh(t,e.currentPath):t.join("/")}}function Mx(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function Le(e,t,r,n,i){e[t]=r,Mx(e,t,n,i)}var ce={};$s(ce,{BRAND:()=>YB,DIRTY:()=>ta,EMPTY_PATH:()=>$B,INVALID:()=>pe,NEVER:()=>jV,OK:()=>er,ParseStatus:()=>Gt,Schema:()=>Ee,ZodAny:()=>Xs,ZodArray:()=>es,ZodBigInt:()=>na,ZodBoolean:()=>ia,ZodBranded:()=>_p,ZodCatch:()=>ha,ZodDate:()=>sa,ZodDefault:()=>ma,ZodDiscriminatedUnion:()=>sh,ZodEffects:()=>hn,ZodEnum:()=>da,ZodError:()=>Nr,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>ah,ZodIntersection:()=>ua,ZodIssueCode:()=>D,ZodLazy:()=>la,ZodLiteral:()=>pa,ZodMap:()=>Dc,ZodNaN:()=>Lc,ZodNativeEnum:()=>fa,ZodNever:()=>$n,ZodNull:()=>aa,ZodNullable:()=>di,ZodNumber:()=>ra,ZodObject:()=>Rr,ZodOptional:()=>fn,ZodParsedType:()=>X,ZodPipeline:()=>yp,ZodPromise:()=>Ys,ZodReadonly:()=>ga,ZodRecord:()=>oh,ZodSchema:()=>Ee,ZodSet:()=>zc,ZodString:()=>Js,ZodSymbol:()=>Mc,ZodTransformer:()=>hn,ZodTuple:()=>pi,ZodType:()=>Ee,ZodUndefined:()=>oa,ZodUnion:()=>ca,ZodUnknown:()=>Qi,ZodVoid:()=>jc,addIssueToContext:()=>q,any:()=>aV,array:()=>pV,bigint:()=>rV,boolean:()=>hP,coerce:()=>MV,custom:()=>dP,date:()=>nV,datetimeRegex:()=>lP,defaultErrorMap:()=>Xi,discriminatedUnion:()=>hV,effect:()=>AV,enum:()=>SV,function:()=>wV,getErrorMap:()=>Pc,getParsedType:()=>li,instanceof:()=>eV,intersection:()=>gV,isAborted:()=>nh,isAsync:()=>Nc,isDirty:()=>ih,isValid:()=>Ws,late:()=>QB,lazy:()=>xV,literal:()=>IV,makeIssue:()=>gp,map:()=>vV,nan:()=>tV,nativeEnum:()=>EV,never:()=>uV,null:()=>oV,nullable:()=>OV,number:()=>mP,object:()=>dV,objectUtil:()=>jx,oboolean:()=>RV,onumber:()=>NV,optional:()=>TV,ostring:()=>PV,pipeline:()=>CV,preprocess:()=>$V,promise:()=>kV,quotelessJson:()=>AB,record:()=>yV,set:()=>bV,setErrorMap:()=>OB,strictObject:()=>fV,string:()=>fP,symbol:()=>iV,transformer:()=>AV,tuple:()=>_V,undefined:()=>sV,union:()=>mV,unknown:()=>cV,util:()=>ze,void:()=>lV});var ze;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},e.getValidEnumValues=i=>{let s=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),o={};for(let a of s)o[a]=i[a];return e.objectValues(o)},e.objectValues=i=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},e.find=(i,s)=>{for(let o of i)if(s(o))return o},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(ze||(ze={}));var jx;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(jx||(jx={}));var X=ze.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),li=e=>{switch(typeof e){case"undefined":return X.undefined;case"string":return X.string;case"number":return Number.isNaN(e)?X.nan:X.number;case"boolean":return X.boolean;case"function":return X.function;case"bigint":return X.bigint;case"symbol":return X.symbol;case"object":return Array.isArray(e)?X.array:e===null?X.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?X.promise:typeof Map<"u"&&e instanceof Map?X.map:typeof Set<"u"&&e instanceof Set?X.set:typeof Date<"u"&&e instanceof Date?X.date:X.object;default:return X.unknown}};var D=ze.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),AB=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Nr=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(o))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ze.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Nr.create=e=>new Nr(e);var TB=(e,t)=>{let r;switch(e.code){case D.invalid_type:e.received===X.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case D.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,ze.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:r=`Unrecognized key(s) in object: ${ze.joinValues(e.keys,", ")}`;break;case D.invalid_union:r="Invalid input";break;case D.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ze.joinValues(e.options)}`;break;case D.invalid_enum_value:r=`Invalid enum value. Expected ${ze.joinValues(e.options)}, received '${e.received}'`;break;case D.invalid_arguments:r="Invalid function arguments";break;case D.invalid_return_type:r="Invalid function return type";break;case D.invalid_date:r="Invalid date";break;case D.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:ze.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case D.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case D.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case D.custom:r="Invalid input";break;case D.invalid_intersection_types:r="Intersection results could not be merged";break;case D.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case D.not_finite:r="Number must be finite";break;default:r=t.defaultError,ze.assertNever(e)}return{message:r}},Xi=TB;var sP=Xi;function OB(e){sP=e}function Pc(){return sP}var gp=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,s=[...r,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(o,{data:t,defaultError:a}).message;return{...i,path:s,message:a}},$B=[];function q(e,t){let r=Pc(),n=gp({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Xi?void 0:Xi].filter(i=>!!i)});e.common.issues.push(n)}var Gt=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return pe;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let s=await i.key,o=await i.value;n.push({key:s,value:o})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return pe;s.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[s.value]=o.value)}return{status:t.value,value:n}}},pe=Object.freeze({status:"aborted"}),ta=e=>({status:"dirty",value:e}),er=e=>({status:"valid",value:e}),nh=e=>e.status==="aborted",ih=e=>e.status==="dirty",Ws=e=>e.status==="valid",Nc=e=>typeof Promise<"u"&&e instanceof Promise;var ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(ne||(ne={}));var mn=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},oP=(e,t)=>{if(Ws(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Nr(e.common.issues);return this._error=r,this._error}}};function Ie(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(o,a)=>{let{message:c}=e;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var Ee=class{get description(){return this._def.description}_getType(t){return li(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:li(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Gt,ctx:{common:t.parent.common,data:t.data,parsedType:li(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(Nc(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:li(t)},i=this._parseSync({data:t,path:n.path,parent:n});return oP(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:li(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return Ws(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Ws(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:li(t)},i=this._parse({data:t,path:n.path,parent:n}),s=await(Nc(i)?i:Promise.resolve(i));return oP(n,s)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let o=t(i),a=()=>s.addIssue({code:D.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new hn({schema:this,typeName:T.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return fn.create(this,this._def)}nullable(){return di.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return es.create(this)}promise(){return Ys.create(this,this._def)}or(t){return ca.create([this,t],this._def)}and(t){return ua.create(this,t,this._def)}transform(t){return new hn({...Ie(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new ma({...Ie(this._def),innerType:this,defaultValue:r,typeName:T.ZodDefault})}brand(){return new _p({typeName:T.ZodBranded,type:this,...Ie(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new ha({...Ie(this._def),innerType:this,catchValue:r,typeName:T.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return yp.create(this,t)}readonly(){return ga.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},CB=/^c[^\s-]{8,}$/i,PB=/^[0-9a-z]+$/,NB=/^[0-9A-HJKMNP-TV-Z]{26}$/i,RB=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,MB=/^[a-z0-9_-]{21}$/i,jB=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,DB=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,zB=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,LB="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Dx,UB=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,FB=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,BB=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,VB=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ZB=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,GB=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,cP="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",KB=new RegExp(`^${cP}$`);function uP(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function qB(e){return new RegExp(`^${uP(e)}$`)}function lP(e){let t=`${cP}T${uP(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function HB(e,t){return!!((t==="v4"||!t)&&UB.test(e)||(t==="v6"||!t)&&BB.test(e))}function WB(e,t){if(!jB.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function JB(e,t){return!!((t==="v4"||!t)&&FB.test(e)||(t==="v6"||!t)&&VB.test(e))}var Js=class e extends Ee{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==X.string){let s=this._getOrReturnCtx(t);return q(s,{code:D.invalid_type,expected:X.string,received:s.parsedType}),pe}let n=new Gt,i;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(i=this._getOrReturnCtx(t,i),q(i,{code:D.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(i=this._getOrReturnCtx(t,i),q(i,{code:D.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let o=t.data.length>s.value,a=t.data.length<s.value;(o||a)&&(i=this._getOrReturnCtx(t,i),o?q(i,{code:D.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&q(i,{code:D.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")zB.test(t.data)||(i=this._getOrReturnCtx(t,i),q(i,{validation:"email",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Dx||(Dx=new RegExp(LB,"u")),Dx.test(t.data)||(i=this._getOrReturnCtx(t,i),q(i,{validation:"emoji",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")RB.test(t.data)||(i=this._getOrReturnCtx(t,i),q(i,{validation:"uuid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")MB.test(t.data)||(i=this._getOrReturnCtx(t,i),q(i,{validation:"nanoid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")CB.test(t.data)||(i=this._getOrReturnCtx(t,i),q(i,{validation:"cuid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")PB.test(t.data)||(i=this._getOrReturnCtx(t,i),q(i,{validation:"cuid2",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")NB.test(t.data)||(i=this._getOrReturnCtx(t,i),q(i,{validation:"ulid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),q(i,{validation:"url",code:D.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),q(i,{validation:"regex",code:D.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(t,i),q(i,{code:D.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(i=this._getOrReturnCtx(t,i),q(i,{code:D.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(i=this._getOrReturnCtx(t,i),q(i,{code:D.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?lP(s).test(t.data)||(i=this._getOrReturnCtx(t,i),q(i,{code:D.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?KB.test(t.data)||(i=this._getOrReturnCtx(t,i),q(i,{code:D.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?qB(s).test(t.data)||(i=this._getOrReturnCtx(t,i),q(i,{code:D.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?DB.test(t.data)||(i=this._getOrReturnCtx(t,i),q(i,{validation:"duration",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?HB(t.data,s.version)||(i=this._getOrReturnCtx(t,i),q(i,{validation:"ip",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?WB(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),q(i,{validation:"jwt",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?JB(t.data,s.version)||(i=this._getOrReturnCtx(t,i),q(i,{validation:"cidr",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?ZB.test(t.data)||(i=this._getOrReturnCtx(t,i),q(i,{validation:"base64",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?GB.test(t.data)||(i=this._getOrReturnCtx(t,i),q(i,{validation:"base64url",code:D.invalid_string,message:s.message}),n.dirty()):ze.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:D.invalid_string,...ne.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...ne.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...ne.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...ne.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...ne.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...ne.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...ne.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...ne.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...ne.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...ne.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...ne.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...ne.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...ne.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...ne.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...ne.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...ne.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...ne.errToObj(r)})}nonempty(t){return this.min(1,ne.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Js.create=e=>new Js({checks:[],typeName:T.ZodString,coerce:e?.coerce??!1,...Ie(e)});function XB(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return s%o/10**i}var ra=class e extends Ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==X.number){let s=this._getOrReturnCtx(t);return q(s,{code:D.invalid_type,expected:X.number,received:s.parsedType}),pe}let n,i=new Gt;for(let s of this._def.checks)s.kind==="int"?ze.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),q(n,{code:D.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),q(n,{code:D.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),q(n,{code:D.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?XB(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),q(n,{code:D.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),q(n,{code:D.not_finite,message:s.message}),i.dirty()):ze.assertNever(s);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,ne.toString(r))}gt(t,r){return this.setLimit("min",t,!1,ne.toString(r))}lte(t,r){return this.setLimit("max",t,!0,ne.toString(r))}lt(t,r){return this.setLimit("max",t,!1,ne.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:ne.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ne.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:ne.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ne.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&ze.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};ra.create=e=>new ra({checks:[],typeName:T.ZodNumber,coerce:e?.coerce||!1,...Ie(e)});var na=class e extends Ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==X.bigint)return this._getInvalidInput(t);let n,i=new Gt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),q(n,{code:D.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),q(n,{code:D.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),q(n,{code:D.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):ze.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return q(r,{code:D.invalid_type,expected:X.bigint,received:r.parsedType}),pe}gte(t,r){return this.setLimit("min",t,!0,ne.toString(r))}gt(t,r){return this.setLimit("min",t,!1,ne.toString(r))}lte(t,r){return this.setLimit("max",t,!0,ne.toString(r))}lt(t,r){return this.setLimit("max",t,!1,ne.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:ne.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ne.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:ne.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};na.create=e=>new na({checks:[],typeName:T.ZodBigInt,coerce:e?.coerce??!1,...Ie(e)});var ia=class extends Ee{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==X.boolean){let n=this._getOrReturnCtx(t);return q(n,{code:D.invalid_type,expected:X.boolean,received:n.parsedType}),pe}return er(t.data)}};ia.create=e=>new ia({typeName:T.ZodBoolean,coerce:e?.coerce||!1,...Ie(e)});var sa=class e extends Ee{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==X.date){let s=this._getOrReturnCtx(t);return q(s,{code:D.invalid_type,expected:X.date,received:s.parsedType}),pe}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return q(s,{code:D.invalid_date}),pe}let n=new Gt,i;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),q(i,{code:D.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(i=this._getOrReturnCtx(t,i),q(i,{code:D.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ze.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:ne.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:ne.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};sa.create=e=>new sa({checks:[],coerce:e?.coerce||!1,typeName:T.ZodDate,...Ie(e)});var Mc=class extends Ee{_parse(t){if(this._getType(t)!==X.symbol){let n=this._getOrReturnCtx(t);return q(n,{code:D.invalid_type,expected:X.symbol,received:n.parsedType}),pe}return er(t.data)}};Mc.create=e=>new Mc({typeName:T.ZodSymbol,...Ie(e)});var oa=class extends Ee{_parse(t){if(this._getType(t)!==X.undefined){let n=this._getOrReturnCtx(t);return q(n,{code:D.invalid_type,expected:X.undefined,received:n.parsedType}),pe}return er(t.data)}};oa.create=e=>new oa({typeName:T.ZodUndefined,...Ie(e)});var aa=class extends Ee{_parse(t){if(this._getType(t)!==X.null){let n=this._getOrReturnCtx(t);return q(n,{code:D.invalid_type,expected:X.null,received:n.parsedType}),pe}return er(t.data)}};aa.create=e=>new aa({typeName:T.ZodNull,...Ie(e)});var Xs=class extends Ee{constructor(){super(...arguments),this._any=!0}_parse(t){return er(t.data)}};Xs.create=e=>new Xs({typeName:T.ZodAny,...Ie(e)});var Qi=class extends Ee{constructor(){super(...arguments),this._unknown=!0}_parse(t){return er(t.data)}};Qi.create=e=>new Qi({typeName:T.ZodUnknown,...Ie(e)});var $n=class extends Ee{_parse(t){let r=this._getOrReturnCtx(t);return q(r,{code:D.invalid_type,expected:X.never,received:r.parsedType}),pe}};$n.create=e=>new $n({typeName:T.ZodNever,...Ie(e)});var jc=class extends Ee{_parse(t){if(this._getType(t)!==X.undefined){let n=this._getOrReturnCtx(t);return q(n,{code:D.invalid_type,expected:X.void,received:n.parsedType}),pe}return er(t.data)}};jc.create=e=>new jc({typeName:T.ZodVoid,...Ie(e)});var es=class e extends Ee{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==X.array)return q(r,{code:D.invalid_type,expected:X.array,received:r.parsedType}),pe;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(o||a)&&(q(r,{code:o?D.too_big:D.too_small,minimum:a?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(q(r,{code:D.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(q(r,{code:D.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>i.type._parseAsync(new mn(r,o,r.path,a)))).then(o=>Gt.mergeArray(n,o));let s=[...r.data].map((o,a)=>i.type._parseSync(new mn(r,o,r.path,a)));return Gt.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:ne.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:ne.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:ne.toString(r)}})}nonempty(t){return this.min(1,t)}};es.create=(e,t)=>new es({type:e,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...Ie(t)});function Rc(e){if(e instanceof Rr){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=fn.create(Rc(n))}return new Rr({...e._def,shape:()=>t})}else return e instanceof es?new es({...e._def,type:Rc(e.element)}):e instanceof fn?fn.create(Rc(e.unwrap())):e instanceof di?di.create(Rc(e.unwrap())):e instanceof pi?pi.create(e.items.map(t=>Rc(t))):e}var Rr=class e extends Ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=ze.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==X.object){let u=this._getOrReturnCtx(t);return q(u,{code:D.invalid_type,expected:X.object,received:u.parsedType}),pe}let{status:n,ctx:i}=this._processInputParams(t),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof $n&&this._def.unknownKeys==="strip"))for(let u in i.data)o.includes(u)||a.push(u);let c=[];for(let u of o){let l=s[u],p=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new mn(i,p,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof $n){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(u==="strict")a.length>0&&(q(i,{code:D.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let p=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new mn(i,p,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let p=await l.key,f=await l.value;u.push({key:p,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Gt.mergeObjectSync(n,u)):Gt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return ne.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:ne.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:T.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of ze.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of ze.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return Rc(this)}partial(t){let r={};for(let n of ze.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of ze.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof fn;)s=s._def.innerType;r[n]=s}return new e({...this._def,shape:()=>r})}keyof(){return pP(ze.objectKeys(this.shape))}};Rr.create=(e,t)=>new Rr({shape:()=>e,unknownKeys:"strip",catchall:$n.create(),typeName:T.ZodObject,...Ie(t)});Rr.strictCreate=(e,t)=>new Rr({shape:()=>e,unknownKeys:"strict",catchall:$n.create(),typeName:T.ZodObject,...Ie(t)});Rr.lazycreate=(e,t)=>new Rr({shape:e,unknownKeys:"strip",catchall:$n.create(),typeName:T.ZodObject,...Ie(t)});var ca=class extends Ee{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(a=>new Nr(a.ctx.common.issues));return q(r,{code:D.invalid_union,unionErrors:o}),pe}if(r.common.async)return Promise.all(n.map(async s=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(c=>new Nr(c));return q(r,{code:D.invalid_union,unionErrors:a}),pe}}get options(){return this._def.options}};ca.create=(e,t)=>new ca({options:e,typeName:T.ZodUnion,...Ie(t)});var Yi=e=>e instanceof la?Yi(e.schema):e instanceof hn?Yi(e.innerType()):e instanceof pa?[e.value]:e instanceof da?e.options:e instanceof fa?ze.objectValues(e.enum):e instanceof ma?Yi(e._def.innerType):e instanceof oa?[void 0]:e instanceof aa?[null]:e instanceof fn?[void 0,...Yi(e.unwrap())]:e instanceof di?[null,...Yi(e.unwrap())]:e instanceof _p||e instanceof ga?Yi(e.unwrap()):e instanceof ha?Yi(e._def.innerType):[],sh=class e extends Ee{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==X.object)return q(r,{code:D.invalid_type,expected:X.object,received:r.parsedType}),pe;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(q(r,{code:D.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),pe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let s of r){let o=Yi(s.shape[t]);if(!o.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of o){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,s)}}return new e({typeName:T.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Ie(n)})}};function zx(e,t){let r=li(e),n=li(t);if(e===t)return{valid:!0,data:e};if(r===X.object&&n===X.object){let i=ze.objectKeys(t),s=ze.objectKeys(e).filter(a=>i.indexOf(a)!==-1),o={...e,...t};for(let a of s){let c=zx(e[a],t[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(r===X.array&&n===X.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let s=0;s<e.length;s++){let o=e[s],a=t[s],c=zx(o,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===X.date&&n===X.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var ua=class extends Ee{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(s,o)=>{if(nh(s)||nh(o))return pe;let a=zx(s.value,o.value);return a.valid?((ih(s)||ih(o))&&r.dirty(),{status:r.value,value:a.data}):(q(n,{code:D.invalid_intersection_types}),pe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ua.create=(e,t,r)=>new ua({left:e,right:t,typeName:T.ZodIntersection,...Ie(r)});var pi=class e extends Ee{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==X.array)return q(n,{code:D.invalid_type,expected:X.array,received:n.parsedType}),pe;if(n.data.length<this._def.items.length)return q(n,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),pe;!this._def.rest&&n.data.length>this._def.items.length&&(q(n,{code:D.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new mn(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(s).then(o=>Gt.mergeArray(r,o)):Gt.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};pi.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new pi({items:e,typeName:T.ZodTuple,rest:null,...Ie(t)})};var oh=class e extends Ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==X.object)return q(n,{code:D.invalid_type,expected:X.object,received:n.parsedType}),pe;let i=[],s=this._def.keyType,o=this._def.valueType;for(let a in n.data)i.push({key:s._parse(new mn(n,a,n.path,a)),value:o._parse(new mn(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Gt.mergeObjectAsync(r,i):Gt.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Ee?new e({keyType:t,valueType:r,typeName:T.ZodRecord,...Ie(n)}):new e({keyType:Js.create(),valueType:t,typeName:T.ZodRecord,...Ie(r)})}},Dc=class extends Ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==X.map)return q(n,{code:D.invalid_type,expected:X.map,received:n.parsedType}),pe;let i=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new mn(n,a,n.path,[u,"key"])),value:s._parse(new mn(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return pe;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of o){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return pe;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Dc.create=(e,t,r)=>new Dc({valueType:t,keyType:e,typeName:T.ZodMap,...Ie(r)});var zc=class e extends Ee{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==X.set)return q(n,{code:D.invalid_type,expected:X.set,received:n.parsedType}),pe;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(q(n,{code:D.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(q(n,{code:D.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function o(c){let u=new Set;for(let l of c){if(l.status==="aborted")return pe;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new mn(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:ne.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:ne.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};zc.create=(e,t)=>new zc({valueType:e,minSize:null,maxSize:null,typeName:T.ZodSet,...Ie(t)});var ah=class e extends Ee{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==X.function)return q(r,{code:D.invalid_type,expected:X.function,received:r.parsedType}),pe;function n(a,c){return gp({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Pc(),Xi].filter(u=>!!u),issueData:{code:D.invalid_arguments,argumentsError:c}})}function i(a,c){return gp({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Pc(),Xi].filter(u=>!!u),issueData:{code:D.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Ys){let a=this;return er(async function(...c){let u=new Nr([]),l=await a._def.args.parseAsync(c,s).catch(d=>{throw u.addIssue(n(c,d)),u}),p=await Reflect.apply(o,this,l);return await a._def.returns._def.type.parseAsync(p,s).catch(d=>{throw u.addIssue(i(p,d)),u})})}else{let a=this;return er(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Nr([n(c,u.error)]);let l=Reflect.apply(o,this,u.data),p=a._def.returns.safeParse(l,s);if(!p.success)throw new Nr([i(l,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:pi.create(t).rest(Qi.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||pi.create([]).rest(Qi.create()),returns:r||Qi.create(),typeName:T.ZodFunction,...Ie(n)})}},la=class extends Ee{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};la.create=(e,t)=>new la({getter:e,typeName:T.ZodLazy,...Ie(t)});var pa=class extends Ee{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return q(r,{received:r.data,code:D.invalid_literal,expected:this._def.value}),pe}return{status:"valid",value:t.data}}get value(){return this._def.value}};pa.create=(e,t)=>new pa({value:e,typeName:T.ZodLiteral,...Ie(t)});function pP(e,t){return new da({values:e,typeName:T.ZodEnum,...Ie(t)})}var da=class e extends Ee{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return q(r,{expected:ze.joinValues(n),received:r.parsedType,code:D.invalid_type}),pe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return q(r,{received:r.data,code:D.invalid_enum_value,options:n}),pe}return er(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};da.create=pP;var fa=class extends Ee{_parse(t){let r=ze.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==X.string&&n.parsedType!==X.number){let i=ze.objectValues(r);return q(n,{expected:ze.joinValues(i),received:n.parsedType,code:D.invalid_type}),pe}if(this._cache||(this._cache=new Set(ze.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=ze.objectValues(r);return q(n,{received:n.data,code:D.invalid_enum_value,options:i}),pe}return er(t.data)}get enum(){return this._def.values}};fa.create=(e,t)=>new fa({values:e,typeName:T.ZodNativeEnum,...Ie(t)});var Ys=class extends Ee{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==X.promise&&r.common.async===!1)return q(r,{code:D.invalid_type,expected:X.promise,received:r.parsedType}),pe;let n=r.parsedType===X.promise?r.data:Promise.resolve(r.data);return er(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ys.create=(e,t)=>new Ys({type:e,typeName:T.ZodPromise,...Ie(t)});var hn=class extends Ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===T.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,s={addIssue:o=>{q(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(n.data,s);if(n.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return pe;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?pe:c.status==="dirty"?ta(c.value):r.value==="dirty"?ta(c.value):c});{if(r.value==="aborted")return pe;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?pe:a.status==="dirty"?ta(a.value):r.value==="dirty"?ta(a.value):a}}if(i.type==="refinement"){let o=a=>{let c=i.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?pe:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?pe:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ws(o))return pe;let a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>Ws(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:r.value,value:a})):pe);ze.assertNever(i)}};hn.create=(e,t,r)=>new hn({schema:e,typeName:T.ZodEffects,effect:t,...Ie(r)});hn.createWithPreprocess=(e,t,r)=>new hn({schema:t,effect:{type:"preprocess",transform:e},typeName:T.ZodEffects,...Ie(r)});var fn=class extends Ee{_parse(t){return this._getType(t)===X.undefined?er(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};fn.create=(e,t)=>new fn({innerType:e,typeName:T.ZodOptional,...Ie(t)});var di=class extends Ee{_parse(t){return this._getType(t)===X.null?er(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};di.create=(e,t)=>new di({innerType:e,typeName:T.ZodNullable,...Ie(t)});var ma=class extends Ee{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===X.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ma.create=(e,t)=>new ma({innerType:e,typeName:T.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ie(t)});var ha=class extends Ee{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Nc(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Nr(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Nr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ha.create=(e,t)=>new ha({innerType:e,typeName:T.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ie(t)});var Lc=class extends Ee{_parse(t){if(this._getType(t)!==X.nan){let n=this._getOrReturnCtx(t);return q(n,{code:D.invalid_type,expected:X.nan,received:n.parsedType}),pe}return{status:"valid",value:t.data}}};Lc.create=e=>new Lc({typeName:T.ZodNaN,...Ie(e)});var YB=Symbol("zod_brand"),_p=class extends Ee{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},yp=class e extends Ee{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?pe:s.status==="dirty"?(r.dirty(),ta(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?pe:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:T.ZodPipeline})}},ga=class extends Ee{_parse(t){let r=this._def.innerType._parse(t),n=i=>(Ws(i)&&(i.value=Object.freeze(i.value)),i);return Nc(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};ga.create=(e,t)=>new ga({innerType:e,typeName:T.ZodReadonly,...Ie(t)});function aP(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function dP(e,t={},r){return e?Xs.create().superRefine((n,i)=>{let s=e(n);if(s instanceof Promise)return s.then(o=>{if(!o){let a=aP(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!s){let o=aP(t,n),a=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:a})}}):Xs.create()}var QB={object:Rr.lazycreate},T;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(T||(T={}));var eV=(e,t={message:`Input not instance of ${e.name}`})=>dP(r=>r instanceof e,t),fP=Js.create,mP=ra.create,tV=Lc.create,rV=na.create,hP=ia.create,nV=sa.create,iV=Mc.create,sV=oa.create,oV=aa.create,aV=Xs.create,cV=Qi.create,uV=$n.create,lV=jc.create,pV=es.create,dV=Rr.create,fV=Rr.strictCreate,mV=ca.create,hV=sh.create,gV=ua.create,_V=pi.create,yV=oh.create,vV=Dc.create,bV=zc.create,wV=ah.create,xV=la.create,IV=pa.create,SV=da.create,EV=fa.create,kV=Ys.create,AV=hn.create,TV=fn.create,OV=di.create,$V=hn.createWithPreprocess,CV=yp.create,PV=()=>fP().optional(),NV=()=>mP().optional(),RV=()=>hP().optional(),MV={string:(e=>Js.create({...e,coerce:!0})),number:(e=>ra.create({...e,coerce:!0})),boolean:(e=>ia.create({...e,coerce:!0})),bigint:(e=>na.create({...e,coerce:!0})),date:(e=>sa.create({...e,coerce:!0}))};var jV=pe;function gP(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==T.ZodAny&&(r.items=me(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Le(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Le(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Le(r,"minItems",e.exactLength.value,e.exactLength.message,t),Le(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function _P(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?Le(r,"minimum",n.value,n.message,t):Le(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Le(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Le(r,"maximum",n.value,n.message,t):Le(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Le(r,"maximum",n.value,n.message,t));break;case"multipleOf":Le(r,"multipleOf",n.value,n.message,t);break}return r}function yP(){return{type:"boolean"}}function ch(e,t){return me(e.type._def,t)}var vP=(e,t)=>me(e.innerType._def,t);function Lx(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(i=>Lx(e,t,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return DV(e,t)}}var DV=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":Le(r,"minimum",n.value,n.message,t);break;case"max":Le(r,"maximum",n.value,n.message,t);break}return r};function bP(e,t){return{...me(e.innerType._def,t),default:e.defaultValue()}}function wP(e,t){return t.effectStrategy==="input"?me(e.schema._def,t):ut(t)}function xP(e){return{type:"string",enum:Array.from(e.values)}}var zV=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function IP(e,t){let r=[me(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),me(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(s=>{if(zV(s))i.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;o=c}else n=void 0;i.push(o)}}),i.length?{allOf:i,...n}:void 0}function SP(e,t){let r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var Ux,Cn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ux===void 0&&(Ux=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ux),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function uh(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":Le(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":Le(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Pn(r,"email",n.message,t);break;case"format:idn-email":Pn(r,"idn-email",n.message,t);break;case"pattern:zod":vr(r,Cn.email,n.message,t);break}break;case"url":Pn(r,"uri",n.message,t);break;case"uuid":Pn(r,"uuid",n.message,t);break;case"regex":vr(r,n.regex,n.message,t);break;case"cuid":vr(r,Cn.cuid,n.message,t);break;case"cuid2":vr(r,Cn.cuid2,n.message,t);break;case"startsWith":vr(r,RegExp(`^${Fx(n.value,t)}`),n.message,t);break;case"endsWith":vr(r,RegExp(`${Fx(n.value,t)}$`),n.message,t);break;case"datetime":Pn(r,"date-time",n.message,t);break;case"date":Pn(r,"date",n.message,t);break;case"time":Pn(r,"time",n.message,t);break;case"duration":Pn(r,"duration",n.message,t);break;case"length":Le(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),Le(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":vr(r,RegExp(Fx(n.value,t)),n.message,t);break;case"ip":n.version!=="v6"&&Pn(r,"ipv4",n.message,t),n.version!=="v4"&&Pn(r,"ipv6",n.message,t);break;case"base64url":vr(r,Cn.base64url,n.message,t);break;case"jwt":vr(r,Cn.jwt,n.message,t);break;case"cidr":n.version!=="v6"&&vr(r,Cn.ipv4Cidr,n.message,t),n.version!=="v4"&&vr(r,Cn.ipv6Cidr,n.message,t);break;case"emoji":vr(r,Cn.emoji(),n.message,t);break;case"ulid":vr(r,Cn.ulid,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":Pn(r,"binary",n.message,t);break;case"contentEncoding:base64":Le(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":vr(r,Cn.base64,n.message,t);break}break;case"nanoid":vr(r,Cn.nanoid,n.message,t);break;case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Fx(e,t){return t.patternStrategy==="escape"?UV(e):e}var LV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function UV(e){let t="";for(let r=0;r<e.length;r++)LV.has(e[r])||(t+="\\"),t+=e[r];return t}function Pn(e,t,r,n){e.format||e.anyOf?.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Le(e,"format",t,r,n)}function vr(e,t,r,n){e.pattern||e.allOf?.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:EP(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Le(e,"pattern",EP(t,n),r,n)}function EP(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source,i="",s=!1,o=!1,a=!1;for(let c=0;c<n.length;c++){if(s){i+=n[c],s=!1;continue}if(r.i){if(o){if(n[c].match(/[a-z]/)){a?(i+=n[c],i+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(i+=n[c],a=!0):i+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){i+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){i+=`(^|(?<=[\r
87
- ]))`;continue}else if(n[c]==="$"){i+=`($|(?=[\r
88
- ]))`;continue}}if(r.s&&n[c]==="."){i+=o?`${n[c]}\r
89
- `:`[${n[c]}\r
90
- ]`;continue}i+=n[c],n[c]==="\\"?s=!0:o&&n[c]==="]"?o=!1:!o&&n[c]==="["&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function lh(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===T.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,i)=>({...n,[i]:me(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",i]})??ut(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:me(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===T.ZodString&&e.keyType._def.checks?.length){let{type:n,...i}=uh(e.keyType._def,t);return{...r,propertyNames:i}}else{if(e.keyType?._def.typeName===T.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===T.ZodBranded&&e.keyType._def.type._def.typeName===T.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...i}=ch(e.keyType._def,t);return{...r,propertyNames:i}}}return r}function kP(e,t){if(t.mapStrategy==="record")return lh(e,t);let r=me(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||ut(t),n=me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||ut(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function AP(e){let t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),i=Array.from(new Set(n.map(s=>typeof s)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function TP(e){return e.target==="openAi"?void 0:{not:ut({...e,currentPath:[...e.currentPath,"not"]})}}function OP(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var vp={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function CP(e,t){if(t.target==="openApi3")return $P(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in vp&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((i,s)=>{let o=vp[s._def.typeName];return o&&!i.includes(o)?[...i,o]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((i,s)=>{let o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...i,o];case"bigint":return[...i,"integer"];case"object":return s._def.value===null?[...i,"null"]:i;case"symbol":case"undefined":case"function":default:return i}},[]);if(n.length===r.length){let i=n.filter((s,o,a)=>a.indexOf(s)===o);return{type:i.length>1?i:i[0],enum:r.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(s=>!n.includes(s))],[])};return $P(e,t)}var $P=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,i)=>me(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function PP(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:vp[e.innerType._def.typeName],nullable:!0}:{type:[vp[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=me(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function NP(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",Mx(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?Le(r,"minimum",n.value,n.message,t):Le(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Le(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Le(r,"maximum",n.value,n.message,t):Le(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Le(r,"maximum",n.value,n.message,t));break;case"multipleOf":Le(r,"multipleOf",n.value,n.message,t);break}return r}function RP(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},i=[],s=e.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=BV(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=me(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||i.push(a))}i.length&&(n.required=i);let o=FV(e,t);return o!==void 0&&(n.additionalProperties=o),n}function FV(e,t){if(e.catchall._def.typeName!=="ZodNever")return me(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function BV(e){try{return e.isOptional()}catch{return!0}}var MP=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return me(e.innerType._def,t);let r=me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ut(t)},r]}:ut(t)};var jP=(e,t)=>{if(t.pipeStrategy==="input")return me(e.in._def,t);if(t.pipeStrategy==="output")return me(e.out._def,t);let r=me(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=me(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function DP(e,t){return me(e.type._def,t)}function zP(e,t){let n={type:"array",uniqueItems:!0,items:me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Le(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Le(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function LP(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>me(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:me(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>me(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function UP(e){return{not:ut(e)}}function FP(e){return ut(e)}var BP=(e,t)=>me(e.innerType._def,t);var VP=(e,t,r)=>{switch(t){case T.ZodString:return uh(e,r);case T.ZodNumber:return NP(e,r);case T.ZodObject:return RP(e,r);case T.ZodBigInt:return _P(e,r);case T.ZodBoolean:return yP();case T.ZodDate:return Lx(e,r);case T.ZodUndefined:return UP(r);case T.ZodNull:return OP(r);case T.ZodArray:return gP(e,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return CP(e,r);case T.ZodIntersection:return IP(e,r);case T.ZodTuple:return LP(e,r);case T.ZodRecord:return lh(e,r);case T.ZodLiteral:return SP(e,r);case T.ZodEnum:return xP(e);case T.ZodNativeEnum:return AP(e);case T.ZodNullable:return PP(e,r);case T.ZodOptional:return MP(e,r);case T.ZodMap:return kP(e,r);case T.ZodSet:return zP(e,r);case T.ZodLazy:return()=>e.getter()._def;case T.ZodPromise:return DP(e,r);case T.ZodNaN:case T.ZodNever:return TP(r);case T.ZodEffects:return wP(e,r);case T.ZodAny:return ut(r);case T.ZodUnknown:return FP(r);case T.ZodDefault:return bP(e,r);case T.ZodBranded:return ch(e,r);case T.ZodReadonly:return BP(e,r);case T.ZodCatch:return vP(e,r);case T.ZodPipeline:return jP(e,r);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(n=>{})(t)}};function me(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==rP)return a}if(n&&!r){let a=VV(n,t);if(a!==void 0)return a}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let s=VP(e,e.typeName,t),o=typeof s=="function"?me(s(),t):s;if(o&&ZV(e,t,o),t.postProcess){let a=t.postProcess(o,e,t);return i.jsonSchema=o,a}return i.jsonSchema=o,o}var VV=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:rh(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),ut(t)):t.$refStrategy==="seen"?ut(t):void 0}},ZV=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var ZP=(e,t)=>{let r=iP(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:me(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ut(r)}),{}):void 0,i=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=me(e._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??ut(r),o=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;o!==void 0&&(s.title=o),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=i===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function fi(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let i=0;i<n;i++)if(!fi(e[i],t[i]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(let o of n)if(!fi(e[o],t[o]))return!1;return!0}return e===t}function Kr(e){return encodeURI(GV(e))}function GV(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var KV={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},qV={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},HV={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},WV=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Nn(e,t=Object.create(null),r=WV,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e.$id||e.id;if(s){let o=new URL(s,r.href);o.hash.length>1?t[o.href]=e:(o.hash="",n===""?r=o:Nn(e,t,r))}}else if(e!==!0&&e!==!1)return t;let i=r.href+(n?"#"+n:"");if(t[i]!==void 0)throw new Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let s=new URL(e.$ref,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let s=new URL(e.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){let s=new URL("#"+e.$anchor,r.href);t[s.href]=e}for(let s in e){if(HV[s])continue;let o=`${n}/${Kr(s)}`,a=e[s];if(Array.isArray(a)){if(KV[s]){let c=a.length;for(let u=0;u<c;u++)Nn(a[u],t,r,`${o}/${u}`)}}else if(qV[s])for(let c in a)Nn(a[c],t,r,`${o}/${Kr(c)}`);else Nn(a,t,r,o)}return t}var JV=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,XV=[0,31,28,31,30,31,30,31,31,30,31,30,31],YV=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,QV=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,eZ=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,tZ=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,rZ=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,nZ=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,iZ=/^(?:\/(?:[^~/]|~0|~1)*)*$/,sZ=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,oZ=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,aZ=e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},cZ=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,uZ=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,lZ=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function mi(e){return e.test.bind(e)}var Bx={date:GP,time:KP.bind(void 0,!1),"date-time":fZ,duration:lZ,uri:gZ,"uri-reference":mi(eZ),"uri-template":mi(tZ),url:mi(rZ),email:aZ,hostname:mi(QV),ipv4:mi(cZ),ipv6:mi(uZ),regex:yZ,uuid:mi(nZ),"json-pointer":mi(iZ),"json-pointer-uri-fragment":mi(sZ),"relative-json-pointer":mi(oZ)};function pZ(e){return e%4===0&&(e%100!==0||e%400===0)}function GP(e){let t=e.match(JV);if(!t)return!1;let r=+t[1],n=+t[2],i=+t[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&pZ(r)?29:XV[n])}function KP(e,t){let r=t.match(YV);if(!r)return!1;let n=+r[1],i=+r[2],s=+r[3],o=!!r[5];return(n<=23&&i<=59&&s<=59||n==23&&i==59&&s==60)&&(!e||o)}var dZ=/t|\s/i;function fZ(e){let t=e.split(dZ);return t.length==2&&GP(t[0])&&KP(!0,t[1])}var mZ=/\/|:/,hZ=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function gZ(e){return mZ.test(e)&&hZ.test(e)}var _Z=/[^\\]\\Z/;function yZ(e){if(_Z.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var qP;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(qP||(qP={}));function HP(e){let t=0,r=e.length,n=0,i;for(;n<r;)t++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<r&&(i=e.charCodeAt(n),(i&64512)==56320&&n++);return t}function Xe(e,t,r="2019-09",n=Nn(t),i=!0,s=null,o="#",a="#",c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:"false",keywordLocation:o,error:"False boolean schema."}]};let u=typeof e,l;switch(u){case"boolean":case"number":case"string":l=u;break;case"object":e===null?l="null":Array.isArray(e)?l="array":l="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}let{$ref:p,$recursiveRef:f,$recursiveAnchor:d,type:m,const:h,enum:b,required:_,not:y,anyOf:x,allOf:I,oneOf:A,if:j,then:O,else:w,format:U,properties:P,patternProperties:V,additionalProperties:Oe,unevaluatedProperties:Ke,minProperties:cr,maxProperties:Lr,propertyNames:Me,dependentRequired:Ao,dependentSchemas:$i,dependencies:To,prefixItems:xn,items:Ci,additionalItems:nl,unevaluatedItems:il,contains:sl,minContains:In,maxContains:v,minItems:g,maxItems:R,uniqueItems:E,minimum:je,maximum:qe,exclusiveMinimum:tt,exclusiveMaximum:St,multipleOf:Bt,minLength:Sn,maxLength:mt,pattern:tn,__absolute_ref__:oc,__absolute_recursive_ref__:Bd}=t,J=[];if(d===!0&&s===null&&(s=t),f==="#"){let he=s===null?n[Bd]:s,oe=`${a}/$recursiveRef`,ve=Xe(e,s===null?t:s,r,n,i,he,o,oe,c);ve.valid||J.push({instanceLocation:o,keyword:"$recursiveRef",keywordLocation:oe,error:"A subschema had errors."},...ve.errors)}if(p!==void 0){let oe=n[oc||p];if(oe===void 0){let H=`Unresolved $ref "${p}".`;throw oc&&oc!==p&&(H+=` Absolute URI "${oc}".`),H+=`
91
- Known schemas:
92
- - ${Object.keys(n).join(`
93
- - `)}`,new Error(H)}let ve=`${a}/$ref`,ee=Xe(e,oe,r,n,i,s,o,ve,c);if(ee.valid||J.push({instanceLocation:o,keyword:"$ref",keywordLocation:ve,error:"A subschema had errors."},...ee.errors),r==="4"||r==="7")return{valid:J.length===0,errors:J}}if(Array.isArray(m)){let he=m.length,oe=!1;for(let ve=0;ve<he;ve++)if(l===m[ve]||m[ve]==="integer"&&l==="number"&&e%1===0&&e===e){oe=!0;break}oe||J.push({instanceLocation:o,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${l}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(l!=="number"||e%1||e!==e)&&J.push({instanceLocation:o,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${l}" is invalid. Expected "${m}".`}):m!==void 0&&l!==m&&J.push({instanceLocation:o,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${l}" is invalid. Expected "${m}".`});if(h!==void 0&&(l==="object"||l==="array"?fi(e,h)||J.push({instanceLocation:o,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&J.push({instanceLocation:o,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),b!==void 0&&(l==="object"||l==="array"?b.some(he=>fi(e,he))||J.push({instanceLocation:o,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(he=>e===he)||J.push({instanceLocation:o,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),y!==void 0){let he=`${a}/not`;Xe(e,y,r,n,i,s,o,he).valid&&J.push({instanceLocation:o,keyword:"not",keywordLocation:he,error:'Instance matched "not" schema.'})}let Oo=[];if(x!==void 0){let he=`${a}/anyOf`,oe=J.length,ve=!1;for(let ee=0;ee<x.length;ee++){let H=x[ee],_e=Object.create(c),ge=Xe(e,H,r,n,i,d===!0?s:null,o,`${he}/${ee}`,_e);J.push(...ge.errors),ve=ve||ge.valid,ge.valid&&Oo.push(_e)}ve?J.length=oe:J.splice(oe,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:he,error:"Instance does not match any subschemas."})}if(I!==void 0){let he=`${a}/allOf`,oe=J.length,ve=!0;for(let ee=0;ee<I.length;ee++){let H=I[ee],_e=Object.create(c),ge=Xe(e,H,r,n,i,d===!0?s:null,o,`${he}/${ee}`,_e);J.push(...ge.errors),ve=ve&&ge.valid,ge.valid&&Oo.push(_e)}ve?J.length=oe:J.splice(oe,0,{instanceLocation:o,keyword:"allOf",keywordLocation:he,error:"Instance does not match every subschema."})}if(A!==void 0){let he=`${a}/oneOf`,oe=J.length,ve=A.filter((ee,H)=>{let _e=Object.create(c),ge=Xe(e,ee,r,n,i,d===!0?s:null,o,`${he}/${H}`,_e);return J.push(...ge.errors),ge.valid&&Oo.push(_e),ge.valid}).length;ve===1?J.length=oe:J.splice(oe,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:he,error:`Instance does not match exactly one subschema (${ve} matches).`})}if((l==="object"||l==="array")&&Object.assign(c,...Oo),j!==void 0){let he=`${a}/if`;if(Xe(e,j,r,n,i,s,o,he,c).valid){if(O!==void 0){let ve=Xe(e,O,r,n,i,s,o,`${a}/then`,c);ve.valid||J.push({instanceLocation:o,keyword:"if",keywordLocation:he,error:'Instance does not match "then" schema.'},...ve.errors)}}else if(w!==void 0){let ve=Xe(e,w,r,n,i,s,o,`${a}/else`,c);ve.valid||J.push({instanceLocation:o,keyword:"if",keywordLocation:he,error:'Instance does not match "else" schema.'},...ve.errors)}}if(l==="object"){if(_!==void 0)for(let ee of _)ee in e||J.push({instanceLocation:o,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${ee}".`});let he=Object.keys(e);if(cr!==void 0&&he.length<cr&&J.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${cr} properties.`}),Lr!==void 0&&he.length>Lr&&J.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${Lr} properties.`}),Me!==void 0){let ee=`${a}/propertyNames`;for(let H in e){let _e=`${o}/${Kr(H)}`,ge=Xe(H,Me,r,n,i,s,_e,ee);ge.valid||J.push({instanceLocation:o,keyword:"propertyNames",keywordLocation:ee,error:`Property name "${H}" does not match schema.`},...ge.errors)}}if(Ao!==void 0){let ee=`${a}/dependantRequired`;for(let H in Ao)if(H in e){let _e=Ao[H];for(let ge of _e)ge in e||J.push({instanceLocation:o,keyword:"dependentRequired",keywordLocation:ee,error:`Instance has "${H}" but does not have "${ge}".`})}}if($i!==void 0)for(let ee in $i){let H=`${a}/dependentSchemas`;if(ee in e){let _e=Xe(e,$i[ee],r,n,i,s,o,`${H}/${Kr(ee)}`,c);_e.valid||J.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:H,error:`Instance has "${ee}" but does not match dependant schema.`},..._e.errors)}}if(To!==void 0){let ee=`${a}/dependencies`;for(let H in To)if(H in e){let _e=To[H];if(Array.isArray(_e))for(let ge of _e)ge in e||J.push({instanceLocation:o,keyword:"dependencies",keywordLocation:ee,error:`Instance has "${H}" but does not have "${ge}".`});else{let ge=Xe(e,_e,r,n,i,s,o,`${ee}/${Kr(H)}`);ge.valid||J.push({instanceLocation:o,keyword:"dependencies",keywordLocation:ee,error:`Instance has "${H}" but does not match dependant schema.`},...ge.errors)}}}let oe=Object.create(null),ve=!1;if(P!==void 0){let ee=`${a}/properties`;for(let H in P){if(!(H in e))continue;let _e=`${o}/${Kr(H)}`,ge=Xe(e[H],P[H],r,n,i,s,_e,`${ee}/${Kr(H)}`);if(ge.valid)c[H]=oe[H]=!0;else if(ve=i,J.push({instanceLocation:o,keyword:"properties",keywordLocation:ee,error:`Property "${H}" does not match schema.`},...ge.errors),ve)break}}if(!ve&&V!==void 0){let ee=`${a}/patternProperties`;for(let H in V){let _e=new RegExp(H,"u"),ge=V[H];for(let kr in e){if(!_e.test(kr))continue;let XE=`${o}/${Kr(kr)}`,YE=Xe(e[kr],ge,r,n,i,s,XE,`${ee}/${Kr(H)}`);YE.valid?c[kr]=oe[kr]=!0:(ve=i,J.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:ee,error:`Property "${kr}" matches pattern "${H}" but does not match associated schema.`},...YE.errors))}}}if(!ve&&Oe!==void 0){let ee=`${a}/additionalProperties`;for(let H in e){if(oe[H])continue;let _e=`${o}/${Kr(H)}`,ge=Xe(e[H],Oe,r,n,i,s,_e,ee);ge.valid?c[H]=!0:(ve=i,J.push({instanceLocation:o,keyword:"additionalProperties",keywordLocation:ee,error:`Property "${H}" does not match additional properties schema.`},...ge.errors))}}else if(!ve&&Ke!==void 0){let ee=`${a}/unevaluatedProperties`;for(let H in e)if(!c[H]){let _e=`${o}/${Kr(H)}`,ge=Xe(e[H],Ke,r,n,i,s,_e,ee);ge.valid?c[H]=!0:J.push({instanceLocation:o,keyword:"unevaluatedProperties",keywordLocation:ee,error:`Property "${H}" does not match unevaluated properties schema.`},...ge.errors)}}}else if(l==="array"){R!==void 0&&e.length>R&&J.push({instanceLocation:o,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${R}).`}),g!==void 0&&e.length<g&&J.push({instanceLocation:o,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${g}).`});let he=e.length,oe=0,ve=!1;if(xn!==void 0){let ee=`${a}/prefixItems`,H=Math.min(xn.length,he);for(;oe<H;oe++){let _e=Xe(e[oe],xn[oe],r,n,i,s,`${o}/${oe}`,`${ee}/${oe}`);if(c[oe]=!0,!_e.valid&&(ve=i,J.push({instanceLocation:o,keyword:"prefixItems",keywordLocation:ee,error:"Items did not match schema."},..._e.errors),ve))break}}if(Ci!==void 0){let ee=`${a}/items`;if(Array.isArray(Ci)){let H=Math.min(Ci.length,he);for(;oe<H;oe++){let _e=Xe(e[oe],Ci[oe],r,n,i,s,`${o}/${oe}`,`${ee}/${oe}`);if(c[oe]=!0,!_e.valid&&(ve=i,J.push({instanceLocation:o,keyword:"items",keywordLocation:ee,error:"Items did not match schema."},..._e.errors),ve))break}}else for(;oe<he;oe++){let H=Xe(e[oe],Ci,r,n,i,s,`${o}/${oe}`,ee);if(c[oe]=!0,!H.valid&&(ve=i,J.push({instanceLocation:o,keyword:"items",keywordLocation:ee,error:"Items did not match schema."},...H.errors),ve))break}if(!ve&&nl!==void 0){let H=`${a}/additionalItems`;for(;oe<he;oe++){let _e=Xe(e[oe],nl,r,n,i,s,`${o}/${oe}`,H);c[oe]=!0,_e.valid||(ve=i,J.push({instanceLocation:o,keyword:"additionalItems",keywordLocation:H,error:"Items did not match additional items schema."},..._e.errors))}}}if(sl!==void 0)if(he===0&&In===void 0)J.push({instanceLocation:o,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(In!==void 0&&he<In)J.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${he}) than minContains (${In}).`});else{let ee=`${a}/contains`,H=J.length,_e=0;for(let ge=0;ge<he;ge++){let kr=Xe(e[ge],sl,r,n,i,s,`${o}/${ge}`,ee);kr.valid?(c[ge]=!0,_e++):J.push(...kr.errors)}_e>=(In||0)&&(J.length=H),In===void 0&&v===void 0&&_e===0?J.splice(H,0,{instanceLocation:o,keyword:"contains",keywordLocation:ee,error:"Array does not contain item matching schema."}):In!==void 0&&_e<In?J.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${In} items matching schema. Only ${_e} items were found.`}):v!==void 0&&_e>v&&J.push({instanceLocation:o,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${v} items matching schema. ${_e} items were found.`})}if(!ve&&il!==void 0){let ee=`${a}/unevaluatedItems`;for(oe;oe<he;oe++){if(c[oe])continue;let H=Xe(e[oe],il,r,n,i,s,`${o}/${oe}`,ee);c[oe]=!0,H.valid||J.push({instanceLocation:o,keyword:"unevaluatedItems",keywordLocation:ee,error:"Items did not match unevaluated items schema."},...H.errors)}}if(E)for(let ee=0;ee<he;ee++){let H=e[ee],_e=typeof H=="object"&&H!==null;for(let ge=0;ge<he;ge++){if(ee===ge)continue;let kr=e[ge];(H===kr||_e&&(typeof kr=="object"&&kr!==null)&&fi(H,kr))&&(J.push({instanceLocation:o,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${ee} and ${ge}.`}),ee=Number.MAX_SAFE_INTEGER,ge=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(je!==void 0&&(tt===!0&&e<=je||e<je)&&J.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${tt?"or equal to ":""} ${je}.`}),qe!==void 0&&(St===!0&&e>=qe||e>qe)&&J.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${St?"or equal to ":""} ${qe}.`})):(je!==void 0&&e<je&&J.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${je}.`}),qe!==void 0&&e>qe&&J.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${qe}.`}),tt!==void 0&&e<=tt&&J.push({instanceLocation:o,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${tt}.`}),St!==void 0&&e>=St&&J.push({instanceLocation:o,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${St}.`})),Bt!==void 0){let he=e%Bt;Math.abs(0-he)>=11920929e-14&&Math.abs(Bt-he)>=11920929e-14&&J.push({instanceLocation:o,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Bt}.`})}}else if(l==="string"){let he=Sn===void 0&&mt===void 0?0:HP(e);Sn!==void 0&&he<Sn&&J.push({instanceLocation:o,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${he} < ${Sn}).`}),mt!==void 0&&he>mt&&J.push({instanceLocation:o,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${he} > ${mt}).`}),tn!==void 0&&!new RegExp(tn,"u").test(e)&&J.push({instanceLocation:o,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),U!==void 0&&Bx[U]&&!Bx[U](e)&&J.push({instanceLocation:o,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${U}".`})}return{valid:J.length===0,errors:J}}var ph=class{schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",n=!0){this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=Nn(t)}validate(t){return Xe(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),Nn(t,this.lookup)}};var Vx={};M(Vx,{Validator:()=>ph,deepCompareStrict:()=>fi,toJsonSchema:()=>Ye,validatesOnlyStrings:()=>Uc});function Ye(e,t){if(We(e)){let r=eh(e,!0);if(dn(r)){let n=Tc(r,!0);return qs(n,t)}else return qs(e,t)}return it(e)?ZP(e):e}function Uc(e){if(!e||typeof e!="object"||Object.keys(e).length===0||Array.isArray(e))return!1;if("type"in e)return typeof e.type=="string"?e.type==="string":Array.isArray(e.type)?e.type.every(t=>t==="string"):!1;if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(t=>typeof t=="string");if("const"in e)return typeof e.const=="string";if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some(t=>Uc(t));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){let t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every(r=>Uc(r))}if("not"in e)return!1;if("$ref"in e&&typeof e.$ref=="string"){let t=e.$ref,r=Nn(e);return r[t]?Uc(r[t]):!1}return!1}function bp(e){return e?e.lc_runnable:!1}var WP=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,n=e.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t)),this.includeTags!==void 0&&(r=r||n.some(i=>this.includeTags?.includes(i))),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(r=r&&n.every(i=>!this.excludeTags?.includes(i))),r}},JP=e=>btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function Zx(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}var vZ=["*","_","`"];function bZ(e){let t="";for(let[r,n]of Object.entries(e))t+=` classDef ${r} ${n};
94
- `;return t}function XP(e,t,r){let{firstNode:n,lastNode:i,nodeColors:s,withStyles:o=!0,curveStyle:a="linear",wrapLabelNWords:c=9}=r??{},u=o?`%%{init: {'flowchart': {'curve': '${a}'}}}%%
95
- graph TD;
96
- `:`graph TD;
97
- `;if(o){let m="default",h={[m]:"{0}({1})"};n!==void 0&&(h[n]="{0}([{1}]):::first"),i!==void 0&&(h[i]="{0}([{1}]):::last");for(let[b,_]of Object.entries(e)){let y=_.name.split(":").pop()??"",I=vZ.some(j=>y.startsWith(j)&&y.endsWith(j))?`<p>${y}</p>`:y;Object.keys(_.metadata??{}).length&&(I+=`<hr/><small><em>${Object.entries(_.metadata??{}).map(([j,O])=>`${j} = ${O}`).join(`
98
- `)}</em></small>`);let A=(h[b]??h[m]).replace("{0}",Zx(b)).replace("{1}",I);u+=` ${A}
99
- `}}let l={};for(let m of t){let h=m.source.split(":"),b=m.target.split(":"),_=h.filter((y,x)=>y===b[x]).join(":");l[_]||(l[_]=[]),l[_].push(m)}let p=new Set;function f(m){return[...m].sort((h,b)=>h.split(":").length-b.split(":").length)}function d(m,h){let b=m.length===1&&m[0].source===m[0].target;if(h&&!b){let y=h.split(":").pop();if(p.has(h))throw new Error(`Found duplicate subgraph '${y}' at '${h} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);p.add(h),u+=` subgraph ${y}
100
- `}let _=f(Object.keys(l).filter(y=>y.startsWith(`${h}:`)&&y!==h&&y.split(":").length===h.split(":").length+1));for(let y of _)d(l[y],y);for(let y of m){let{source:x,target:I,data:A,conditional:j}=y,O="";if(A!==void 0){let w=A,U=w.split(" ");U.length>c&&(w=Array.from({length:Math.ceil(U.length/c)},(P,V)=>U.slice(V*c,(V+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),O=j?` -. &nbsp;${w}&nbsp; .-> `:` -- &nbsp;${w}&nbsp; --> `}else O=j?" -.-> ":" --> ";u+=` ${Zx(x)}${O}${Zx(I)};
101
- `}h&&!b&&(u+=` end
102
- `)}d(l[""]??[],"");for(let m in l)!m.includes(":")&&m!==""&&d(l[m],m);return o&&(u+=bZ(s??{})),u}async function YP(e,t){let r=t?.backgroundColor??"white",n=t?.imageType??"png",i=JP(e);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let s=`https://mermaid.ink/img/${i}?bgColor=${r}&type=${n}`,o=await fetch(s);if(!o.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${o.status}`,`Status text: ${o.statusText}`].join(`
103
- `));return await o.blob()}var Gx={};M(Gx,{Graph:()=>_a});function wZ(e,t){if(e!==void 0&&!En(e))return e;if(bp(t))try{let r=t.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return t.getName()}else return t.name??"UnknownSchema"}function xZ(e){return bp(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...Ye(e.data.schema),title:e.data.name}}}var _a=class tN{nodes={};edges=[];constructor(t){this.nodes=t?.nodes??this.nodes,this.edges=t?.edges??this.edges}toJSON(){let t={};return Object.values(this.nodes).forEach((r,n)=>{t[r.id]=En(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:t[r.id],...xZ(r)})),edges:this.edges.map(r=>{let n={source:t[r.source],target:t[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(t,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);let i=r??Ar(),s={id:i,data:t,name:wZ(r,t),metadata:n};return this.nodes[i]=s,s}removeNode(t){delete this.nodes[t.id],this.edges=this.edges.filter(r=>r.source!==t.id&&r.target!==t.id)}addEdge(t,r,n,i){if(this.nodes[t.id]===void 0)throw new Error(`Source node ${t.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);let s={source:t.id,target:r.id,data:n,conditional:i};return this.edges.push(s),s}firstNode(){return QP(this)}lastNode(){return eN(this)}extend(t,r=""){let n=r;Object.values(t.nodes).map(u=>u.id).every(En)&&(n="");let s=u=>n?`${n}:${u}`:u;Object.entries(t.nodes).forEach(([u,l])=>{this.nodes[s(u)]={...l,id:s(u)}});let o=t.edges.map(u=>({...u,source:s(u.source),target:s(u.target)}));this.edges=[...this.edges,...o];let a=t.firstNode(),c=t.lastNode();return[a?{id:s(a.id),data:a.data}:void 0,c?{id:s(c.id),data:c.data}:void 0]}trimFirstNode(){let t=this.firstNode();t&&QP(this,[t.id])&&this.removeNode(t)}trimLastNode(){let t=this.lastNode();t&&eN(this,[t.id])&&this.removeNode(t)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(i=>[i.id,i.name])),r=new Map;Object.values(t).forEach(i=>{r.set(i,(r.get(i)||0)+1)});let n=i=>{let s=t[i];return En(i)&&r.get(s)===1?s:i};return new tN({nodes:Object.fromEntries(Object.entries(this.nodes).map(([i,s])=>[n(i),{...s,id:n(i)}])),edges:this.edges.map(i=>({...i,source:n(i.source),target:n(i.target)}))})}drawMermaid(t){let{withStyles:r,curveStyle:n,nodeColors:i={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=t??{},o=this.reid(),a=o.firstNode(),c=o.lastNode();return XP(o.nodes,o.edges,{firstNode:a?.id,lastNode:c?.id,withStyles:r,curveStyle:n,nodeColors:i,wrapLabelNWords:s})}async drawMermaidPng(t){let r=this.drawMermaid(t);return YP(r,{backgroundColor:t?.backgroundColor})}};function QP(e,t=[]){let r=new Set(e.edges.filter(i=>!t.includes(i.source)).map(i=>i.target)),n=[];for(let i of Object.values(e.nodes))!t.includes(i.id)&&!r.has(i.id)&&n.push(i);return n.length===1?n[0]:void 0}function eN(e,t=[]){let r=new Set(e.edges.filter(i=>!t.includes(i.target)).map(i=>i.source)),n=[];for(let i of Object.values(e.nodes))!t.includes(i.id)&&!r.has(i.id)&&n.push(i);return n.length===1?n[0]:void 0}function dh({name:e,serialized:t}){return e!==void 0?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}var rN=e=>e.name==="event_stream_tracer",nN=class extends Zt{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;readableStreamClosed=!1;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=kt.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(r=r||t.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(r=r&&t.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(e,t){let r=await t.next();if(r.done)return;let n=this.runInfoMap.get(e);if(n===void 0){yield r.value;return}function i(o,a){return o==="llm"&&typeof a=="string"?new ai({text:a}):a}let s=this.tappedPromises.get(e);if(s===void 0){let o;s=new Promise(a=>{o=a}),this.tappedPromises.set(e,s);try{let a={event:`on_${n.runType}_stream`,run_id:e,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...a,data:{chunk:i(n.runType,r.value)}},n),yield r.value;for await(let c of t)n.runType!=="tool"&&n.runType!=="retriever"&&await this.send({...a,data:{chunk:i(n.runType,c)}},n),yield c}finally{o?.()}}else{yield r.value;for await(let o of t)yield o}}async send(e,t){this.readableStreamClosed||this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){let t=dh(e),r=e.inputs.messages!==void 0?"chat_model":"llm",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,n);let i=`on_${r}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onLLMNewToken(e,t,r){let n=this.runInfoMap.get(e.id),i,s;if(n===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(n.runType==="chat_model")s="on_chat_model_stream",r?.chunk===void 0?i=new nt({content:t,id:`run-${e.id}`}):i=r.chunk.message;else if(n.runType==="llm")s="on_llm_stream",r?.chunk===void 0?i=new ai({text:t}):i=r.chunk;else throw new Error(`Unexpected run type ${n.runType}`);await this.send({event:s,data:{chunk:i},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){let t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let n=e.outputs?.generations,i;if(t.runType==="chat_model"){for(let s of n??[]){if(i!==void 0)break;i=s[0]?.message}r="on_chat_model_end"}else if(t.runType==="llm")i={generations:n?.map(s=>s.map(o=>({text:o.text,generationInfo:o.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:r,data:{output:i,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){let t=dh(e),r=e.run_type??"chain",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},i={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(i={},n.inputs={}):e.inputs.input!==void 0?(i.input=e.inputs.input,n.inputs=e.inputs.input):(i.input=e.inputs,n.inputs=e.inputs),this.runInfoMap.set(e.id,n),await this.send({event:`on_${r}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let r=`on_${e.run_type}_end`,n=e.inputs??t.inputs??{},s={output:e.outputs?.output??e.outputs,input:n};n.input&&Object.keys(n).length===1&&(s.input=n.input,t.inputs=n.input),await this.sendEndEvent({event:r,data:s,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=dh(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let r=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:t.inputs,error:e.error},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){let t=dh(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,n),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){let n=this.runInfoMap.get(r);if(n===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:n.tags,metadata:n.metadata,data:t},n)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}};var Kx=class extends Zt{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:r,onError:n}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=n}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function iN(e){let t=new TextEncoder,r=new ReadableStream({async start(n){for await(let i of e)n.enqueue(t.encode(`event: data
104
- data: ${JSON.stringify(i)}
105
-
106
- `));n.enqueue(t.encode(`event: end
107
-
108
- `)),n.close()}});return kt.fromReadableStream(r)}function qx(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.iterator]=="function"&&typeof e.next=="function"}var sN=e=>e!=null&&typeof e=="object"&&"next"in e&&typeof e.next=="function";function fh(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.asyncIterator]=="function"}function*Hx(e,t){for(;;){let{value:r,done:n}=Ze.runWithConfig(hr(e),t.next.bind(t),!0);if(n)break;yield r}}async function*mh(e,t){let r=t[Symbol.asyncIterator]();for(;;){let{value:n,done:i}=await Ze.runWithConfig(hr(e),r.next.bind(t),!0);if(i)break;yield n}}function Tt(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}var ue=class extends vt{lc_runnable=!0;name;getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new gh({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new gn({bound:this,config:e,kwargs:{}})}withFallbacks(e){let t=Array.isArray(e)?e:e.fallbacks;return new Wx({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(Ce);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let r=Object.fromEntries(Object.entries(e).filter(([n])=>n!=="runId"));return Array.from({length:t},(n,i)=>Ce(i===0?e:r))}return Array.from({length:t},()=>Ce(e))}async batch(e,t,r){let n=this._getOptionsList(t??{},e.length),i=n[0]?.maxConcurrency??r?.maxConcurrency,s=new Gi({maxConcurrency:i,onFailedAttempt:a=>{throw a}}),o=e.map((a,c)=>s.call(async()=>{try{return await this.invoke(a,n[c])}catch(u){if(r?.returnExceptions)return u;throw u}}));return Promise.all(o)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let r=Ce(t),n=new Us({generator:this._streamIterator(e,r),config:r});return await n.setup,kt.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=Ce(e):t=Ce({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[t,r]}async _callWithConfig(e,t,r){let n=Ce(r),s=await(await Et(n))?.handleChainStart(this.toJSON(),Tt(t,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName());delete n.runId;let o;try{let a=e.call(this,t,n,s);o=await ln(a,r?.signal)}catch(a){throw await s?.handleChainError(a),a}return await s?.handleChainEnd(Tt(o,"output")),o}async _batchWithConfig(e,t,r,n){let i=this._getOptionsList(r??{},t.length),s=await Promise.all(i.map(Et)),o=await Promise.all(s.map(async(c,u)=>{let l=await c?.handleChainStart(this.toJSON(),Tt(t[u],"input"),i[u].runId,i[u].runType,void 0,void 0,i[u].runName??this.getName());return delete i[u].runId,l})),a;try{let c=e.call(this,t,i,o,n);a=await ln(c,i?.[0]?.signal)}catch(c){throw await Promise.all(o.map(u=>u?.handleChainError(c))),c}return await Promise.all(o.map(c=>c?.handleChainEnd(Tt(a,"output")))),a}_concatOutputChunks(e,t){return Vr(e,t)}async*_transformStreamWithConfig(e,t,r){let n,i=!0,s,o=!0,a=Ce(r),c=await Et(a),u=this;async function*l(){for await(let f of e){if(i)if(n===void 0)n=f;else try{n=u._concatOutputChunks(n,f)}catch{n=void 0,i=!1}yield f}}let p;try{let f=await Iv(t.bind(this),l(),async()=>c?.handleChainStart(this.toJSON(),{input:""},a.runId,a.runType,void 0,void 0,a.runName??this.getName(),void 0,{lc_defers_inputs:!0}),r?.signal,a);delete a.runId,p=f.setup;let d=p?.handlers.find(rN),m=f.output;d!==void 0&&p!==void 0&&(m=d.tapOutputIterable(p.runId,m));let h=p?.handlers.find(Tv);h!==void 0&&p!==void 0&&(m=h.tapOutputIterable(p.runId,m));for await(let b of m)if(yield b,o)if(s===void 0)s=b;else try{s=this._concatOutputChunks(s,b)}catch{s=void 0,o=!1}}catch(f){throw await p?.handleChainError(f,void 0,void 0,void 0,{inputs:Tt(n,"input")}),f}await p?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:Tt(n,"input")})}getGraph(e){let t=new _a,r=t.addNode({name:`${this.getName()}Input`,schema:ce.any()}),n=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:ce.any()});return t.addEdge(r,n),t.addEdge(n,i),t}pipe(e){return new br({first:this,last:dt(e)})}pick(e){return this.pipe(new Jx(e))}assign(e){return this.pipe(new xp(new Qs({steps:e})))}async*transform(e,t){let r;for await(let n of e)r===void 0?r=n:r=this._concatOutputChunks(r,n);yield*this._streamIterator(r,Ce(t))}async*streamLog(e,t,r){let n=new um({...r,autoClose:!1,_schemaFormat:"original"}),i=Ce(t);yield*this._streamLog(e,n,i)}async*_streamLog(e,t,r){let{callbacks:n}=r;if(n===void 0)r.callbacks=[t];else if(Array.isArray(n))r.callbacks=n.concat([t]);else{let a=n.copy();a.addHandler(t,!0),r.callbacks=a}let i=this.stream(e,r);async function s(){try{let a=await i;for await(let c of a){let u=new oi({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(u)}}finally{await t.writer.close()}}let o=s();try{for await(let a of t)yield a}finally{await o}}streamEvents(e,t,r){let n;if(t.version==="v1")n=this._streamEventsV1(e,t,r);else if(t.version==="v2")n=this._streamEventsV2(e,t,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?iN(n):kt.fromAsyncGenerator(n)}async*_streamEventsV2(e,t,r){let n=new nN({...r,autoClose:!1}),i=Ce(t),s=i.runId??Ar();i.runId=s;let o=i.callbacks;if(o===void 0)i.callbacks=[n];else if(Array.isArray(o))i.callbacks=o.concat(n);else{let d=o.copy();d.addHandler(n,!0),i.callbacks=d}let a=new AbortController,c=this;async function u(){let d,m=null;try{t?.signal?"any"in AbortSignal?d=AbortSignal.any([a.signal,t.signal]):(d=t.signal,m=()=>{a.abort()},t.signal.addEventListener("abort",m,{once:!0})):d=a.signal;let h=await c.stream(e,{...i,signal:d}),b=n.tapOutputIterable(s,h);for await(let _ of b)if(a.signal.aborted)break}finally{await n.finish(),d&&m&&d.removeEventListener("abort",m)}}let l=u(),p=!1,f;try{for await(let d of n){if(!p){d.data.input=e,p=!0,f=d.run_id,yield d;continue}d.run_id===f&&d.event.endsWith("_end")&&d.data?.input&&delete d.data.input,yield d}}finally{a.abort(),await l}}async*_streamEventsV1(e,t,r){let n,i=!1,s=Ce(t),o=s.tags??[],a=s.metadata??{},c=s.runName??this.getName(),u=new um({...r,autoClose:!1,_schemaFormat:"streaming_events"}),l=new WP({...r}),p=this._streamLog(e,u,s);for await(let d of p){if(n?n=n.concat(d):n=cm.fromRunLogPatch(d),n.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;let _={...n.state},y={run_id:_.id,event:`on_${_.type}_start`,name:c,tags:o,metadata:a,data:{input:e}};l.includeEvent(y,_.type)&&(yield y)}let m=d.ops.filter(_=>_.path.startsWith("/logs/")).map(_=>_.path.split("/")[2]),h=[...new Set(m)];for(let _ of h){let y,x={},I=n.state.logs[_];if(I.end_time===void 0?I.streamed_output.length>0?y="stream":y="start":y="end",y==="start")I.inputs!==void 0&&(x.input=I.inputs);else if(y==="end")I.inputs!==void 0&&(x.input=I.inputs),x.output=I.final_output;else if(y==="stream"){let A=I.streamed_output.length;if(A!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${A} instead. Encountered in: "${I.name}"`);x={chunk:I.streamed_output[0]},I.streamed_output=[]}yield{event:`on_${I.type}_${y}`,name:I.name,run_id:I.id,tags:I.tags,metadata:I.metadata,data:x}}let{state:b}=n;if(b.streamed_output.length>0){let _=b.streamed_output.length;if(_!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${_} instead. Encountered in: "${b.name}"`);let y={chunk:b.streamed_output[0]};b.streamed_output=[];let x={event:`on_${b.type}_stream`,run_id:b.id,tags:o,metadata:a,name:c,data:y};l.includeEvent(x,b.type)&&(yield x)}}let f=n?.state;if(f!==void 0){let d={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:o,metadata:a,data:{output:f.final_output}};l.includeEvent(d,f.type)&&(yield d)}}static isRunnable(e){return bp(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new gn({bound:this,config:{},configFactories:[n=>({callbacks:[new Kx({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return EZ(this,e)}},gn=class oN extends ue{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(t){super(t),this.bound=t.bound,this.kwargs=t.kwargs,this.config=t.config,this.configFactories=t.configFactories}getName(t){return this.bound.getName(t)}async _mergeConfig(...t){let r=Dt(this.config,...t);return Dt(r,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(r))):[])}withConfig(t){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...t}})}withRetry(t){return new gh({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:t?.stopAfterAttempt,...t})}async invoke(t,r){return this.bound.invoke(t,await this._mergeConfig(r,this.kwargs))}async batch(t,r,n){let i=Array.isArray(r)?await Promise.all(r.map(async s=>this._mergeConfig(Ce(s),this.kwargs))):await this._mergeConfig(Ce(r),this.kwargs);return this.bound.batch(t,i,n)}_concatOutputChunks(t,r){return this.bound._concatOutputChunks(t,r)}async*_streamIterator(t,r){yield*this.bound._streamIterator(t,await this._mergeConfig(Ce(r),this.kwargs))}async stream(t,r){return this.bound.stream(t,await this._mergeConfig(Ce(r),this.kwargs))}async*transform(t,r){yield*this.bound.transform(t,await this._mergeConfig(Ce(r),this.kwargs))}streamEvents(t,r,n){let i=this,s=async function*(){yield*i.bound.streamEvents(t,{...await i._mergeConfig(Ce(r),i.kwargs),version:r.version},n)};return kt.fromAsyncGenerator(s())}static isRunnableBinding(t){return t.bound&&ue.isRunnable(t.bound)}withListeners({onStart:t,onEnd:r,onError:n}){return new oN({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[i=>({callbacks:[new Kx({config:i,onStart:t,onEnd:r,onError:n})]})]})}},aN=class cN extends ue{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(t){super(t),this.bound=t.bound}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async _invoke(t,r,n){return this.bound.batch(t,Ne(r,{callbacks:n?.getChild()}))}withListeners({onStart:t,onEnd:r,onError:n}){return new cN({bound:this.bound.withListeners({onStart:t,onEnd:r,onError:n})})}},gh=class extends gn{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){let n=e>1?`retry:attempt:${e}`:void 0;return Ne(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return Rl(n=>super.invoke(e,this._patchConfigForRetry(n,t,r)),{onFailedAttempt:({error:n})=>this.onFailedAttempt(n,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,n){let i={};try{await Rl(async s=>{let o=e.map((p,f)=>f).filter(p=>i[p.toString()]===void 0||i[p.toString()]instanceof Error),a=o.map(p=>e[p]),c=o.map(p=>this._patchConfigForRetry(s,t?.[p],r?.[p])),u=await super.batch(a,c,{...n,returnExceptions:!0}),l;for(let p=0;p<u.length;p+=1){let f=u[p],d=o[p];f instanceof Error&&l===void 0&&(l=f,l.input=a[p]),i[d.toString()]=f}if(l)throw l;return u},{onFailedAttempt:({error:s})=>this.onFailedAttempt(s,s.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(s){if(n?.returnExceptions!==!0)throw s}return Object.keys(i).sort((s,o)=>parseInt(s,10)-parseInt(o,10)).map(s=>i[parseInt(s,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}},br=class wp extends ue{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(t){super(t),this.first=t.first,this.middle=t.middle??this.middle,this.last=t.last,this.name=t.name,this.omitSequenceTags=t.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(t,r){let n=Ce(r),s=await(await Et(n))?.handleChainStart(this.toJSON(),Tt(t,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let o=t,a;try{let c=[this.first,...this.middle];for(let u=0;u<c.length;u+=1){let p=c[u].invoke(o,Ne(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${u+1}`)}));o=await ln(p,r?.signal)}if(r?.signal?.aborted)throw Ls(r.signal);a=await this.last.invoke(o,Ne(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await s?.handleChainError(c),c}return await s?.handleChainEnd(Tt(a,"output")),a}async batch(t,r,n){let i=this._getOptionsList(r??{},t.length),s=await Promise.all(i.map(Et)),o=await Promise.all(s.map(async(c,u)=>{let l=await c?.handleChainStart(this.toJSON(),Tt(t[u],"input"),i[u].runId,void 0,void 0,void 0,i[u].runName);return delete i[u].runId,l})),a=t;try{for(let c=0;c<this.steps.length;c+=1){let l=this.steps[c].batch(a,o.map((p,f)=>{let d=p?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return Ne(i[f],{callbacks:d})}),n);a=await ln(l,i[0]?.signal)}}catch(c){throw await Promise.all(o.map(u=>u?.handleChainError(c))),c}return await Promise.all(o.map(c=>c?.handleChainEnd(Tt(a,"output")))),a}_concatOutputChunks(t,r){return this.last._concatOutputChunks(t,r)}async*_streamIterator(t,r){let n=await Et(r),{runId:i,...s}=r??{},o=await n?.handleChainStart(this.toJSON(),Tt(t,"input"),i,void 0,void 0,void 0,s?.runName),a=[this.first,...this.middle,this.last],c=!0,u;async function*l(){yield t}try{let p=a[0].transform(l(),Ne(s,{callbacks:o?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let f=1;f<a.length;f+=1)p=await a[f].transform(p,Ne(s,{callbacks:o?.getChild(this.omitSequenceTags?void 0:`seq:step:${f+1}`)}));for await(let f of p)if(r?.signal?.throwIfAborted(),yield f,c)if(u===void 0)u=f;else try{u=this._concatOutputChunks(u,f)}catch{u=void 0,c=!1}}catch(p){throw await o?.handleChainError(p),p}await o?.handleChainEnd(Tt(u,"output"))}getGraph(t){let r=new _a,n=null;return this.steps.forEach((i,s)=>{let o=i.getGraph(t);s!==0&&o.trimFirstNode(),s!==this.steps.length-1&&o.trimLastNode(),r.extend(o);let a=o.firstNode();if(!a)throw new Error(`Runnable ${i} has no first node`);n&&r.addEdge(n,a),n=o.lastNode()}),r}pipe(t){return wp.isRunnableSequence(t)?new wp({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new wp({first:this.first,middle:[...this.middle,this.last],last:dt(t),name:this.name})}static isRunnableSequence(t){return Array.isArray(t.middle)&&ue.isRunnable(t)}static from([t,...r],n){let i={};return typeof n=="string"?i.name=n:n!==void 0&&(i=n),new wp({...i,first:dt(t),middle:r.slice(0,-1).map(dt),last:dt(r[r.length-1])})}},Qs=class uN extends ue{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(t){super(t),this.steps={};for(let[r,n]of Object.entries(t.steps))this.steps[r]=dt(n)}static from(t){return new uN({steps:t})}async invoke(t,r){let n=Ce(r),s=await(await Et(n))?.handleChainStart(this.toJSON(),{input:t},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let o={};try{let a=Object.entries(this.steps).map(async([c,u])=>{o[c]=await u.invoke(t,Ne(n,{callbacks:s?.getChild(`map:key:${c}`)}))});await ln(Promise.all(a),r?.signal)}catch(a){throw await s?.handleChainError(a),a}return await s?.handleChainEnd(o),o}async*_transform(t,r,n){let i={...this.steps},s=Qf(t,Object.keys(i).length),o=new Map(Object.entries(i).map(([a,c],u)=>{let l=c.transform(s[u],Ne(n,{callbacks:r?.getChild(`map:key:${a}`)}));return[a,l.next().then(p=>({key:a,gen:l,result:p}))]}));for(;o.size;){let a=Promise.race(o.values()),{key:c,result:u,gen:l}=await ln(a,n?.signal);o.delete(c),u.done||(yield{[c]:u.value},o.set(c,l.next().then(p=>({key:c,gen:l,result:p}))))}}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}let i=Ce(r),s=new Us({generator:this.transform(n(),i),config:i});return await s.setup,kt.fromAsyncGenerator(s)}},IZ=class lN extends ue{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(t){if(super(t),!Jf(t.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=t.func}async invoke(t,r){let[n]=this._getOptionsList(r??{},1),i=await Et(n),s=this.func(Ne(n,{callbacks:i}),t);return ln(s,n?.signal)}async*_streamIterator(t,r){let[n]=this._getOptionsList(r??{},1),i=await this.invoke(t,r);if(fh(i)){for await(let s of i)n?.signal?.throwIfAborted(),yield s;return}if(sN(i)){for(;;){n?.signal?.throwIfAborted();let s=i.next();if(s.done)break;yield s.value}return}yield i}static from(t){return new lN({func:t})}};function SZ(e){if(Jf(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var tr=class pN extends ue{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(t){if(Jf(t.func))return IZ.from(t.func);super(t),SZ(t.func),this.func=t.func}static from(t){return new pN({func:t})}async _invoke(t,r,n){return new Promise((i,s)=>{let o=Ne(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??Yf)-1});Ze.runWithConfig(hr(o),async()=>{try{let a=await this.func(t,{...o});if(a&&ue.isRunnable(a)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");a=await a.invoke(t,{...o,recursionLimit:(o.recursionLimit??Yf)-1})}else if(fh(a)){let c;for await(let u of mh(o,a))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}a=c}else if(qx(a)){let c;for(let u of Hx(o,a))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}a=c}i(a)}catch(a){s(a)}})})}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async*_transform(t,r,n){let i;for await(let a of t)if(i===void 0)i=a;else try{i=this._concatOutputChunks(i,a)}catch{i=a}let s=Ne(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??Yf)-1}),o=await new Promise((a,c)=>{Ze.runWithConfig(hr(s),async()=>{try{let u=await this.func(i,{...s,config:s});a(u)}catch(u){c(u)}})});if(o&&ue.isRunnable(o)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");let a=await o.stream(i,s);for await(let c of a)yield c}else if(fh(o))for await(let a of mh(s,o))n?.signal?.throwIfAborted(),yield a;else if(qx(o))for(let a of Hx(s,o))n?.signal?.throwIfAborted(),yield a;else yield o}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}let i=Ce(r),s=new Us({generator:this.transform(n(),i),config:i});return await s.setup,kt.fromAsyncGenerator(s)}},dN=class extends Qs{},Wx=class extends ue{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(let e of this.fallbacks)yield e}async invoke(e,t){let r=Ce(t),n=await Et(r),{runId:i,...s}=r,o=await n?.handleChainStart(this.toJSON(),Tt(e,"input"),i,void 0,void 0,void 0,s?.runName),a=Ne(s,{callbacks:o?.getChild()});return await Ze.runWithConfig(a,async()=>{let u;for(let l of this.runnables()){r?.signal?.throwIfAborted();try{let p=await l.invoke(e,a);return await o?.handleChainEnd(Tt(p,"output")),p}catch(p){u===void 0&&(u=p)}}throw u===void 0?new Error("No error stored at end of fallback."):(await o?.handleChainError(u),u)})}async*_streamIterator(e,t){let r=Ce(t),n=await Et(r),{runId:i,...s}=r,o=await n?.handleChainStart(this.toJSON(),Tt(e,"input"),i,void 0,void 0,void 0,s?.runName),a,c;for(let l of this.runnables()){r?.signal?.throwIfAborted();let p=Ne(s,{callbacks:o?.getChild()});try{let f=await l.stream(e,p);c=mh(p,f);break}catch(f){a===void 0&&(a=f)}}if(c===void 0){let l=a??new Error("No error stored at end of fallback.");throw await o?.handleChainError(l),l}let u;try{for await(let l of c){yield l;try{u=u===void 0?u:this._concatOutputChunks(u,l)}catch{u=void 0}}}catch(l){throw await o?.handleChainError(l),l}await o?.handleChainEnd(Tt(u,"output"))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");let n=this._getOptionsList(t??{},e.length),i=await Promise.all(n.map(a=>Et(a))),s=await Promise.all(i.map(async(a,c)=>{let u=await a?.handleChainStart(this.toJSON(),Tt(e[c],"input"),n[c].runId,void 0,void 0,void 0,n[c].runName);return delete n[c].runId,u})),o;for(let a of this.runnables()){n[0].signal?.throwIfAborted();try{let c=await a.batch(e,s.map((u,l)=>Ne(n[l],{callbacks:u?.getChild()})),r);return await Promise.all(s.map((u,l)=>u?.handleChainEnd(Tt(c[l],"output")))),c}catch(c){o===void 0&&(o=c)}}throw o?(await Promise.all(s.map(a=>a?.handleChainError(o))),o):new Error("No error stored at end of fallbacks.")}};function dt(e){if(typeof e=="function")return new tr({func:e});if(ue.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=dt(n);return new Qs({steps:t})}else throw new Error(`Expected a Runnable, function or object.
109
- Instead got an unsupported type.`)}var xp=class extends ue{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof Qs&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){let r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){let n=this.mapper.getStepsKeys(),[i,s]=Qf(e),o=this.mapper.transform(s,Ne(r,{callbacks:t?.getChild()})),a=o.next();for await(let c of i){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);let u=Object.fromEntries(Object.entries(c).filter(([l])=>!n.includes(l)));Object.keys(u).length>0&&(yield u)}yield(await a).value;for await(let c of o)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=Ce(t),i=new Us({generator:this.transform(r(),n),config:n});return await i.setup,kt.fromAsyncGenerator(i)}},Jx=class extends ue{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{let t=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(let t of e){let r=await this._pick(t);r!==void 0&&(yield r)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=Ce(t),i=new Us({generator:this.transform(r(),n),config:n});return await i.setup,kt.fromAsyncGenerator(i)}},hh=class extends gn{name;description;schema;constructor(e){let t=br.from([tr.from(async r=>{let n;if(js(r))try{n=await Hs(this.schema,r.args)}catch{throw new hc("Received tool input did not match expected schema",JSON.stringify(r.args))}else n=r;return n}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function EZ(e,t){let r=t.name??e.getName(),n=t.description??On(t.schema);return $c(t.schema)?new hh({name:r,description:n,schema:ce.object({input:ce.string()}).transform(i=>i.input),bound:e}):new hh({name:r,description:n,schema:t.schema,bound:e})}var _h=(e,t)=>{let r=[...new Set(t?.map(i=>{if(typeof i=="string")return i;let s=new i({});if(!("getType"in s)||typeof s.getType!="function")throw new Error("Invalid type provided.");return s.getType()}))],n=e.getType();return r.some(i=>i===n)};function _N(e,t){return Array.isArray(e)?fN(e,t):tr.from(r=>fN(r,e))}function fN(e,t={}){let{includeNames:r,excludeNames:n,includeTypes:i,excludeTypes:s,includeIds:o,excludeIds:a}=t,c=[];for(let u of e)if(!(n&&u.name&&n.includes(u.name))){{if(s&&_h(u,s))continue;if(a&&u.id&&a.includes(u.id))continue}i||o||r?(r&&u.name&&r.some(l=>l===u.name)||i&&_h(u,i)||o&&u.id&&o.some(l=>l===u.id))&&c.push(u):c.push(u)}return c}function yN(e){return Array.isArray(e)?mN(e):tr.from(mN)}function mN(e){if(!e.length)return[];let t=[];for(let r of e){let n=r,i=t.pop();if(!i)t.push(n);else if(n.getType()==="tool"||n.getType()!==i.getType())t.push(i,n);else{let s=Lo(i),o=Lo(n),a=s.concat(o);typeof s.content=="string"&&typeof o.content=="string"&&(a.content=`${s.content}
110
- ${o.content}`),t.push(AZ(a))}}return t}function vN(e,t){if(Array.isArray(e)){let r=e;if(!t)throw new Error("Options parameter is required when providing messages.");return hN(r,t)}else{let r=e;return tr.from(n=>hN(n,r)).withConfig({runName:"trim_messages"})}}async function hN(e,t){let{maxTokens:r,tokenCounter:n,strategy:i="last",allowPartial:s=!1,endOn:o,startOn:a,includeSystem:c=!1,textSplitter:u}=t;if(a&&i==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&i==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let l;"getNumTokens"in n?l=async f=>(await Promise.all(f.map(m=>n.getNumTokens(m.content)))).reduce((m,h)=>m+h,0):l=async f=>n(f);let p=Yx;if(u&&("splitText"in u?p=u.splitText:p=async f=>u(f)),i==="first")return bN(e,{maxTokens:r,tokenCounter:l,textSplitter:p,partialStrategy:s?"first":void 0,endOn:o});if(i==="last")return kZ(e,{maxTokens:r,tokenCounter:l,textSplitter:p,allowPartial:s,includeSystem:c,startOn:a,endOn:o});throw new Error(`Unrecognized strategy: '${i}'. Must be one of 'first' or 'last'.`)}async function bN(e,t){let{maxTokens:r,tokenCounter:n,textSplitter:i,partialStrategy:s,endOn:o}=t,a=[...e],c=0;for(let u=0;u<a.length;u+=1){let l=u>0?a.slice(0,-u):a;if(await n(l)<=r){c=a.length-u;break}}if(c<a.length&&s){let u=!1;if(Array.isArray(a[c].content)){let l=a[c];if(typeof l.content=="string")throw new Error("Expected content to be an array.");let p=l.content.length,f=s==="last"?[...l.content].reverse():l.content;for(let d=1;d<=p;d+=1){let m=s==="first"?f.slice(0,d):f.slice(-d),h=Object.fromEntries(Object.entries(l).filter(([y])=>y!=="type"&&!y.startsWith("lc_"))),b=Xx(l.getType(),{...h,content:m}),_=[...a.slice(0,c),b];if(await n(_)<=r)a=_,c+=1,u=!0;else break}u&&s==="last"&&(l.content=[...f].reverse())}if(!u){let l=a[c],p;if(Array.isArray(l.content)&&l.content.some(f=>typeof f=="string"||f.type==="text")?p=l.content.find(d=>d.type==="text"&&d.text)?.text:typeof l.content=="string"&&(p=l.content),p){let f=await i(p),d=f.length;s==="last"&&f.reverse();for(let m=0;m<d-1;m+=1)if(f.pop(),l.content=f.join(""),await n([...a.slice(0,c),l])<=r){s==="last"&&(l.content=[...f].reverse().join("")),a=[...a.slice(0,c),l],c+=1;break}}}}if(o){let u=Array.isArray(o)?o:[o];for(;c>0&&!_h(a[c-1],u);)c-=1}return a.slice(0,c)}async function kZ(e,t){let{allowPartial:r=!1,includeSystem:n=!1,endOn:i,startOn:s,...o}=t,a=e.map(l=>{let p=Object.fromEntries(Object.entries(l).filter(([f])=>f!=="type"&&!f.startsWith("lc_")));return Xx(l.getType(),p,Di(l))});if(i){let l=Array.isArray(i)?i:[i];for(;a.length>0&&!_h(a[a.length-1],l);)a=a.slice(0,-1)}let c=n&&a[0]?.getType()==="system",u=c?a.slice(0,1).concat(a.slice(1).reverse()):a.reverse();return u=await bN(u,{...o,partialStrategy:r?"last":void 0,endOn:s}),c?[u[0],...u.slice(1).reverse()]:u.reverse()}var gN={human:{message:at,messageChunk:Vi},ai:{message:$e,messageChunk:nt},system:{message:Br,messageChunk:un},developer:{message:Br,messageChunk:un},tool:{message:Wt,messageChunk:Ns},function:{message:zo,messageChunk:Bi},generic:{message:mr,messageChunk:Fi},remove:{message:Tn,messageChunk:Tn}};function Xx(e,t,r){let n,i;switch(e){case"human":r?n=new Vi(t):i=new at(t);break;case"ai":if(r){let s={...t};"tool_calls"in s&&(s={...s,tool_call_chunks:s.tool_calls?.map(o=>({...o,type:"tool_call_chunk",index:void 0,args:JSON.stringify(o.args)}))}),n=new nt(s)}else i=new $e(t);break;case"system":r?n=new un(t):i=new Br(t);break;case"developer":r?n=new un({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):i=new Br({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in t)r?n=new Ns(t):i=new Wt(t);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(r)n=new Bi(t);else{if(!t.name)throw new Error("FunctionMessage must have a 'name' field");i=new zo(t)}break;case"generic":if("role"in t)r?n=new Fi(t):i=new mr(t);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognized message type ${e}`)}if(r&&n)return n;if(i)return i;throw new Error(`Unrecognized message type ${e}`)}function AZ(e){let t=e.getType(),r,n=Object.fromEntries(Object.entries(e).filter(([i])=>!["type","tool_call_chunks"].includes(i)&&!i.startsWith("lc_")));if(t in gN&&(r=Xx(t,n)),!r)throw new Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(gN)}`);return r}function Yx(e){let t=e.split(`
111
- `);return Promise.resolve([...t.slice(0,-1).map(r=>`${r}
112
- `),t[t.length-1]])}var wN=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var xN=["image","video","audio","text-plain","file"];var IN=["text","reasoning",...wN,...xN];var Qx={};M(Qx,{AIMessage:()=>$e,AIMessageChunk:()=>nt,BaseMessage:()=>bt,BaseMessageChunk:()=>ur,ChatMessage:()=>mr,ChatMessageChunk:()=>Fi,DEFAULT_MERGE_IGNORE_KEYS:()=>X_,FunctionMessage:()=>zo,FunctionMessageChunk:()=>Bi,HumanMessage:()=>at,HumanMessageChunk:()=>Vi,KNOWN_BLOCK_TYPES:()=>IN,RemoveMessage:()=>Tn,SystemMessage:()=>Br,SystemMessageChunk:()=>un,ToolMessage:()=>Wt,ToolMessageChunk:()=>Ns,_isMessageFieldWithRole:()=>df,_mergeDicts:()=>st,_mergeLists:()=>Ro,_mergeObj:()=>pf,_mergeStatus:()=>lf,coerceMessageLikeToMessage:()=>Qt,collapseToolCallChunks:()=>Hf,convertToChunk:()=>Lo,convertToOpenAIImageBlock:()=>of,convertToProviderContentBlock:()=>pc,defaultTextSplitter:()=>Yx,defaultToolCallParser:()=>pl,filterMessages:()=>_N,getBufferString:()=>gc,iife:()=>qf,isAIMessage:()=>si,isAIMessageChunk:()=>Ol,isBase64ContentBlock:()=>lc,isBaseMessage:()=>ot,isBaseMessageChunk:()=>Di,isChatMessage:()=>l$,isChatMessageChunk:()=>p$,isDataContentBlock:()=>Tr,isDirectToolOutput:()=>ll,isFunctionMessage:()=>d$,isFunctionMessageChunk:()=>f$,isHumanMessage:()=>m$,isHumanMessageChunk:()=>h$,isIDContentBlock:()=>sf,isMessage:()=>uf,isOpenAIToolCallArray:()=>Fk,isPlainTextContentBlock:()=>$k,isSystemMessage:()=>g$,isSystemMessageChunk:()=>_$,isToolMessage:()=>Mo,isToolMessageChunk:()=>Q_,isURLContentBlock:()=>uc,mapChatMessagesToStoredMessages:()=>v$,mapStoredMessageToChatMessage:()=>Tl,mapStoredMessagesToChatMessages:()=>y$,mergeContent:()=>Ht,mergeMessageRuns:()=>yN,mergeResponseMetadata:()=>Gf,mergeUsageMetadata:()=>mc,parseBase64DataUrl:()=>Ps,parseMimeType:()=>ul,trimMessages:()=>vN});var e0={};M(e0,{BaseChatMessageHistory:()=>t0,BaseListChatMessageHistory:()=>yh,InMemoryChatMessageHistory:()=>TZ});var t0=class extends vt{async addMessages(e){for(let t of e)await this.addMessage(t)}},yh=class extends vt{addUserMessage(e){return this.addMessage(new at(e))}addAIMessage(e){return this.addMessage(new $e(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw new Error("Not implemented.")}},TZ=class extends yh{lc_namespace=["langchain","stores","message","in_memory"];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}};var r0={};M(r0,{Embeddings:()=>Fc});var Fc=class{caller;constructor(e){this.caller=new Gi(e??{})}};var SN={};var n0={};M(n0,{BaseMemory:()=>OZ,getInputValue:()=>$Z,getOutputValue:()=>CZ,getPromptInputKey:()=>PZ});var OZ=class{},EN=(e,t)=>{if(t!==void 0)return e[t];let r=Object.keys(e);if(r.length===1)return e[r[0]]},$Z=(e,t)=>{let r=EN(e,t);if(!r){let n=Object.keys(e);throw new Error(`input values have ${n.length} keys, you must specify an input key or pass only 1 key as input`)}return r},CZ=(e,t)=>{let r=EN(e,t);if(!r&&r!==""){let n=Object.keys(e);throw new Error(`output values have ${n.length} keys, you must specify an output key or pass only 1 key as output`)}return r};function PZ(e,t){let r=Object.keys(e).filter(n=>!t.includes(n)&&n!=="stop");if(r.length!==1)throw new Error(`One input key expected, but got ${r.length}`);return r[0]}var i0={};M(i0,{BasePromptValue:()=>vh,ChatPromptValue:()=>Sp,ImagePromptValue:()=>s0,StringPromptValue:()=>Ip});var vh=class extends vt{},Ip=class extends vh{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new at(this.value)]}},Sp=class extends vh{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return gc(this.messages)}toChatMessages(){return this.messages}},s0=class extends vh{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new at({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}};var o0={};M(o0,{BaseStore:()=>kN,InMemoryStore:()=>NZ});var kN=class extends vt{},NZ=class extends kN{lc_namespace=["langchain","storage"];store={};async mget(e){return e.map(t=>this.store[t])}async mset(e){for(let[t,r]of e)this.store[t]=r}async mdelete(e){for(let t of e)delete this.store[t]}async*yieldKeys(e){let t=Object.keys(this.store);for(let r of t)(e===void 0||r.startsWith(e))&&(yield r)}};var a0={};M(a0,{BaseRetriever:()=>Ep});var Ep=class extends ue{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw new Error("Not implemented!")}async invoke(e,t){let r=Ce(Fo(t)),i=await(await xt.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName);try{let s=await this._getRelevantDocuments(e,i);return await i?.handleRetrieverEnd(s),s}catch(s){throw await i?.handleRetrieverError(s),s}}};var c0={};M(c0,{SaveableVectorStore:()=>RZ,VectorStore:()=>wh,VectorStoreRetriever:()=>bh});var bh=class extends Ep{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}vectorStore;k=4;searchType="similarity";searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType==="mmr"&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!="function")throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild("vectorstore"))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},wh=class extends vt{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,t=4,r=void 0,n=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)).map(s=>s[0])}async similaritySearchWithScore(e,t=4,r=void 0,n=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)}static fromTexts(e,t,r,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,t,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,t,r,n,i,s){if(typeof e=="number")return new bh({vectorStore:this,k:e,filter:t,tags:[...n??[],this._vectorstoreType()],metadata:i,verbose:s,callbacks:r});{let o={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType==="mmr"?new bh({...o,searchKwargs:e.searchKwargs}):new bh({...o})}}},RZ=class extends wh{static load(e,t){throw new Error("Not implemented")}};var te="0123456789abcdef".split(""),MZ=[-2147483648,8388608,32768,128],Rn=[24,16,8,0],xh=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],zt=[];function Mn(e,t){t?(zt[0]=zt[16]=zt[1]=zt[2]=zt[3]=zt[4]=zt[5]=zt[6]=zt[7]=zt[8]=zt[9]=zt[10]=zt[11]=zt[12]=zt[13]=zt[14]=zt[15]=0,this.blocks=zt):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}Mn.prototype.update=function(e){if(!this.finalized){var t,r=typeof e;if(r!=="string"){if(r==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);t=!0}for(var n,i=0,s,o=e.length,a=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,a[0]=this.block,this.block=a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),t)for(s=this.start;i<o&&s<64;++i)a[s>>>2]|=e[i]<<Rn[s++&3];else for(s=this.start;i<o&&s<64;++i)n=e.charCodeAt(i),n<128?a[s>>>2]|=n<<Rn[s++&3]:n<2048?(a[s>>>2]|=(192|n>>>6)<<Rn[s++&3],a[s>>>2]|=(128|n&63)<<Rn[s++&3]):n<55296||n>=57344?(a[s>>>2]|=(224|n>>>12)<<Rn[s++&3],a[s>>>2]|=(128|n>>>6&63)<<Rn[s++&3],a[s>>>2]|=(128|n&63)<<Rn[s++&3]):(n=65536+((n&1023)<<10|e.charCodeAt(++i)&1023),a[s>>>2]|=(240|n>>>18)<<Rn[s++&3],a[s>>>2]|=(128|n>>>12&63)<<Rn[s++&3],a[s>>>2]|=(128|n>>>6&63)<<Rn[s++&3],a[s>>>2]|=(128|n&63)<<Rn[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=a[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};Mn.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=MZ[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};Mn.prototype.hash=function(){var e=this.h0,t=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,o=this.h6,a=this.h7,c=this.blocks,u,l,p,f,d,m,h,b,_,y,x;for(u=16;u<64;++u)d=c[u-15],l=(d>>>7|d<<25)^(d>>>18|d<<14)^d>>>3,d=c[u-2],p=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,c[u]=c[u-16]+l+c[u-7]+p<<0;for(x=t&r,u=0;u<64;u+=4)this.first?(this.is224?(b=300032,d=c[0]-1413257819,a=d-150054599<<0,n=d+24177077<<0):(b=704751109,d=c[0]-210244248,a=d-1521486534<<0,n=d+143694565<<0),this.first=!1):(l=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),p=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),b=e&t,f=b^e&r^x,h=i&s^~i&o,d=a+p+h+xh[u]+c[u],m=l+f,a=n+d<<0,n=d+m<<0),l=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),p=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),_=n&e,f=_^n&t^b,h=o&a^~o&i,d=s+p+h+xh[u+1]+c[u+1],m=l+f,o=r+d<<0,r=d+m<<0,l=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),p=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),y=r&n,f=y^r&e^_,h=s&o^~s&a,d=i+p+h+xh[u+2]+c[u+2],m=l+f,s=t+d<<0,t=d+m<<0,l=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),p=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),x=t&r,f=x^t&n^y,h=s&o^~s&a,d=i+p+h+xh[u+3]+c[u+3],m=l+f,i=e+d<<0,e=d+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+i<<0,this.h5=this.h5+s<<0,this.h6=this.h6+o<<0,this.h7=this.h7+a<<0};Mn.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,o=this.h6,a=this.h7,c=te[e>>>28&15]+te[e>>>24&15]+te[e>>>20&15]+te[e>>>16&15]+te[e>>>12&15]+te[e>>>8&15]+te[e>>>4&15]+te[e&15]+te[t>>>28&15]+te[t>>>24&15]+te[t>>>20&15]+te[t>>>16&15]+te[t>>>12&15]+te[t>>>8&15]+te[t>>>4&15]+te[t&15]+te[r>>>28&15]+te[r>>>24&15]+te[r>>>20&15]+te[r>>>16&15]+te[r>>>12&15]+te[r>>>8&15]+te[r>>>4&15]+te[r&15]+te[n>>>28&15]+te[n>>>24&15]+te[n>>>20&15]+te[n>>>16&15]+te[n>>>12&15]+te[n>>>8&15]+te[n>>>4&15]+te[n&15]+te[i>>>28&15]+te[i>>>24&15]+te[i>>>20&15]+te[i>>>16&15]+te[i>>>12&15]+te[i>>>8&15]+te[i>>>4&15]+te[i&15]+te[s>>>28&15]+te[s>>>24&15]+te[s>>>20&15]+te[s>>>16&15]+te[s>>>12&15]+te[s>>>8&15]+te[s>>>4&15]+te[s&15]+te[o>>>28&15]+te[o>>>24&15]+te[o>>>20&15]+te[o>>>16&15]+te[o>>>12&15]+te[o>>>8&15]+te[o>>>4&15]+te[o&15];return this.is224||(c+=te[a>>>28&15]+te[a>>>24&15]+te[a>>>20&15]+te[a>>>16&15]+te[a>>>12&15]+te[a>>>8&15]+te[a>>>4&15]+te[a&15]),c};Mn.prototype.toString=Mn.prototype.hex;Mn.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,o=this.h6,a=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(a>>>24&255,a>>>16&255,a>>>8&255,a&255),c};Mn.prototype.array=Mn.prototype.digest;Mn.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};var Bc=(...e)=>new Mn(!1,!0).update(e.join("")).hex();var u0={};M(u0,{sha256:()=>Bc});var l0={};M(l0,{BaseCache:()=>TN,InMemoryCache:()=>p0,defaultHashKeyEncoder:()=>AN,deserializeStoredGeneration:()=>jZ,serializeGeneration:()=>DZ});var AN=(...e)=>Bc(e.join("_"));function jZ(e){return e.message!==void 0?{text:e.text,message:Tl(e.message)}:{text:e.text}}function DZ(e){let t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var TN=class{keyEncoder=AN;makeDefaultKeyEncoder(e){this.keyEncoder=e}},zZ=new Map,p0=class ON extends TN{cache;constructor(t){super(),this.cache=t??new Map}lookup(t,r){return Promise.resolve(this.cache.get(this.keyEncoder(t,r))??null)}async update(t,r,n){this.cache.set(this.keyEncoder(t,r),n)}static global(){return new ON(zZ)}};var d0={};M(d0,{BaseDocumentLoader:()=>f0});var f0=class{};var m0={};M(m0,{LangSmithLoader:()=>LZ});var LZ=class extends f0{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw new Error("client and clientConfig cannot both be provided.");this.client=e.client??new Li(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split("."):[],this.formatContent=e.formatContent??UZ,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){let e=[];for await(let t of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let r=t.inputs;for(let s of this.contentKey)r=r[s];let n=this.formatContent(r),i=t;["created_at","modified_at"].forEach(s=>{s in i&&typeof i[s]=="object"&&(i[s]=i[s].toString())}),e.push({pageContent:n,metadata:i})}return e}};function UZ(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var qr=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent!==void 0?e.pageContent.toString():"",this.metadata=e.metadata??{},this.id=e.id}};var h0=class extends ue{lc_namespace=["langchain_core","documents","transformers"];invoke(e,t){return this.transformDocuments(e)}},$N=class extends h0{async transformDocuments(e){let t=[];for(let r of e){let n=await this._transformDocument(r);t.push(n)}return t}};var g0={};M(g0,{BaseDocumentTransformer:()=>h0,Document:()=>qr,MappingDocumentTransformer:()=>$N});var Vc=class extends vt{lc_namespace=["langchain_core","example_selectors","base"]};var _0=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},CN=class extends _0{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(let[t,r]of this.conditionals)if(t(e))return r;return this.defaultPrompt}};function PN(e){return e._modelType()==="base_llm"}function NN(e){return e._modelType()==="base_chat_model"}function RN(e){return e.split(/\n| /).length}var MN=class jN extends Vc{examples=[];examplePrompt;getTextLength=RN;maxLength=2048;exampleTextLengths=[];constructor(t){super(t),this.examplePrompt=t.examplePrompt,this.maxLength=t.maxLength??2048,this.getTextLength=t.getTextLength??RN}async addExample(t){this.examples.push(t);let r=await this.examplePrompt.format(t);this.exampleTextLengths.push(this.getTextLength(r))}async calculateExampleTextLengths(t,r){if(t.length>0)return t;let{examples:n,examplePrompt:i}=r;return(await Promise.all(n.map(o=>i.format(o)))).map(o=>this.getTextLength(o))}async selectExamples(t){let r=Object.values(t).join(" "),n=this.maxLength-this.getTextLength(r),i=0,s=[];for(;n>0&&i<this.examples.length;){let o=n-this.exampleTextLengths[i];if(o<0)break;s.push(this.examples[i]),n=o,i+=1}return s}static async fromExamples(t,r){let n=new jN(r);return await Promise.all(t.map(i=>n.addExample(i))),n}};function y0(e){return Object.keys(e).sort().map(t=>e[t])}var DN=class zN extends Vc{vectorStoreRetriever;exampleKeys;inputKeys;constructor(t){if(super(t),this.exampleKeys=t.exampleKeys,this.inputKeys=t.inputKeys,t.vectorStore!==void 0)this.vectorStoreRetriever=t.vectorStore.asRetriever({k:t.k??4,filter:t.filter});else if(t.vectorStoreRetriever)this.vectorStoreRetriever=t.vectorStoreRetriever;else throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(t){let r=this.inputKeys??Object.keys(t),n=y0(r.reduce((i,s)=>({...i,[s]:t[s]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new qr({pageContent:n,metadata:t})])}async selectExamples(t){let r=this.inputKeys??Object.keys(t),n=y0(r.reduce((o,a)=>({...o,[a]:t[a]}),{})).join(" "),s=(await this.vectorStoreRetriever.invoke(n)).map(o=>o.metadata);return this.exampleKeys?s.map(o=>this.exampleKeys.reduce((a,c)=>({...a,[c]:o[c]}),{})):s}static async fromExamples(t,r,n,i={}){let s=i.inputKeys??null,o=t.map(c=>y0(s?s.reduce((u,l)=>({...u,[l]:c[l]}),{}):c).join(" ")),a=await n.fromTexts(o,t,r,i);return new zN({vectorStore:a,k:i.k??4,exampleKeys:i.exampleKeys,inputKeys:i.inputKeys})}};var v0={};M(v0,{BaseExampleSelector:()=>Vc,BasePromptSelector:()=>_0,ConditionalPromptSelector:()=>CN,LengthBasedExampleSelector:()=>MN,SemanticSimilarityExampleSelector:()=>DN,isChatModel:()=>NN,isLLM:()=>PN});var kp="10f90ea3-90a4-4962-bf75-83a0f3c1c62a",LN=class extends vt{lc_namespace=["langchain","recordmanagers"]};var b0=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Bc;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){let e=["hash_","content_hash","metadata_hash"];for(let r of e)if(r in this.metadata)throw new Error(`Metadata cannot contain key ${r} as it is reserved for internal use. Restricted keys: [${e.join(", ")}]`);let t=this._hashStringToUUID(this.pageContent);try{let r=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=r}catch(r){throw new Error(`Failed to hash metadata: ${r}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||(this.uid=this.hash_)}toDocument(){return new qr({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){let r=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return r.calculateHashes(),r}_hashStringToUUID(e){let t=this.keyEncoder(e);return nn(t,kp)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort()),r=this.keyEncoder(t);return nn(r,kp)}};function w0(e,t){let r=[],n=[];return t.forEach(i=>{n.push(i),n.length>=e&&(r.push(n),n=[])}),n.length>0&&r.push(n),r}function x0(e){let t=new Set,r=[];for(let n of e){if(!n.hash_)throw new Error("Hashed document does not have a hash");t.has(n.hash_)||(t.add(n.hash_),r.push(n))}return r}function I0(e){if(e===null)return t=>null;if(typeof e=="string")return t=>t.metadata[e];if(typeof e=="function")return e;throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}var S0=e=>"load"in e&&typeof e.load=="function"&&"loadAndSplit"in e&&typeof e.loadAndSplit=="function";async function UN(e){let{docsSource:t,recordManager:r,vectorStore:n,options:i}=e,{batchSize:s=100,cleanup:o,sourceIdKey:a,cleanupBatchSize:c=1e3,forceUpdate:u=!1}=i??{};if(o==="incremental"&&!a)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");let l=S0(t)?await t.load():t,p=I0(a??null),f=await r.getTime(),d=0,m=0,h=0,b=0,_=w0(s??100,l);for(let y of _){let x=x0(y.map(P=>b0.fromDocument(P))),I=x.map(P=>p(P));o==="incremental"&&x.forEach((P,V)=>{if(I[V]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});let A=await r.exists(x.map(P=>P.uid)),j=[],O=[],w=[],U=new Set;if(x.forEach((P,V)=>{if(A[V])if(u)U.add(P.uid);else{w.push(P.uid);return}j.push(P.uid),O.push(P.toDocument())}),w.length>0&&(await r.update(w,{timeAtLeast:f}),b+=w.length),O.length>0&&(await n.addDocuments(O,{ids:j}),d+=O.length-U.size,h+=U.size),await r.update(x.map(P=>P.uid),{timeAtLeast:f,groupIds:I}),o==="incremental"){I.forEach(V=>{if(!V)throw new Error("Source id cannot be null")});let P=await r.listKeys({before:f,groupIds:I});P.length>0&&(await n.delete({ids:P}),await r.deleteKeys(P),m+=P.length)}}if(o==="full"){let y=await r.listKeys({before:f,limit:c});for(;y.length>0;)await n.delete({ids:y}),await r.deleteKeys(y),m+=y.length,y=await r.listKeys({before:f,limit:c})}return{numAdded:d,numDeleted:m,numUpdated:h,numSkipped:b}}var E0={};M(E0,{RecordManager:()=>LN,UUIDV5_NAMESPACE:()=>kp,_HashedDocument:()=>b0,_batch:()=>w0,_deduplicateInOrder:()=>x0,_getSourceIdAssigner:()=>I0,_isBaseDocumentLoader:()=>S0,index:()=>UN});var ZN=Cs(VN(),1),HZ=Object.defineProperty,WZ=(e,t,r)=>t in e?HZ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,JZ=(e,t,r)=>(WZ(e,typeof t!="symbol"?t+"":t,r),r);function XZ(e,t){let r=Array.from({length:e.length},(n,i)=>({start:i,end:i+1}));for(;r.length>1;){let n=null;for(let i=0;i<r.length-1;i++){let s=e.slice(r[i].start,r[i+1].end),o=t.get(s.join(","));o!=null&&(n==null||o<n[0])&&(n=[o,i])}if(n!=null){let i=n[1];r[i]={start:r[i].start,end:r[i+1].end},r.splice(i+1,1)}else break}return r}function YZ(e,t){return e.length===1?[t.get(e.join(","))]:XZ(e,t).map(r=>t.get(e.slice(r.start,r.end).join(","))).filter(r=>r!=null)}function QZ(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var A0=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;let r=e.bpe_ranks.split(`
113
- `).filter(Boolean).reduce((n,i)=>{let[s,o,...a]=i.split(" "),c=Number.parseInt(o,10);return a.forEach((u,l)=>n[u]=c+l),n},{});for(let[n,i]of Object.entries(r)){let s=ZN.default.toByteArray(n);this.rankMap.set(s.join(","),i),this.textMap.set(i,s)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[i,s])=>(n[s]=this.textEncoder.encode(i),n),{})}encode(e,t=[],r="all"){let n=new RegExp(this.patStr,"ug"),i=A0.specialTokenRegex(Object.keys(this.specialTokens)),s=[],o=new Set(t==="all"?Object.keys(this.specialTokens):t),a=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!o.has(u)):r);if(a.size>0){let u=A0.specialTokenRegex([...a]),l=e.match(u);if(l!=null)throw new Error(`The text contains a special token that is not allowed: ${l[0]}`)}let c=0;for(;;){let u=null,l=c;for(;i.lastIndex=l,u=i.exec(e),!(u==null||o.has(u[0]));)l=u.index+1;let p=u?.index??e.length;for(let d of e.substring(c,p).matchAll(n)){let m=this.textEncoder.encode(d[0]),h=this.rankMap.get(m.join(","));if(h!=null){s.push(h);continue}s.push(...YZ(m,this.rankMap))}if(u==null)break;let f=this.specialTokens[u[0]];s.push(f),c=u.index+u[0].length}return s}decode(e){let t=[],r=0;for(let s=0;s<e.length;++s){let o=e[s],a=this.textMap.get(o)??this.inverseSpecialTokens[o];a!=null&&(t.push(a),r+=a.length)}let n=new Uint8Array(r),i=0;for(let s of t)n.set(s,i),i+=s.length;return this.textDecoder.decode(n)}},Sh=A0;JZ(Sh,"specialTokenRegex",e=>new RegExp(e.map(t=>QZ(t)).join("|"),"g"));function T0(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var O0={};M(O0,{encodingForModel:()=>kh,getEncoding:()=>GN});var Eh={},e9=new Gi({});async function GN(e){return e in Eh||(Eh[e]=e9.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new Sh(t)).catch(t=>{throw delete Eh[e],t})),await Eh[e]}async function kh(e){return GN(T0(e))}var $0={};M($0,{BaseLangChain:()=>Th,BaseLanguageModel:()=>Tp,calculateMaxTokens:()=>qN,getEmbeddingContextSize:()=>t9,getModelContextSize:()=>KN,getModelNameForTiktoken:()=>Ah,isOpenAITool:()=>Ap});var Ah=e=>e.startsWith("gpt-5")?"gpt-5":e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,t9=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},KN=e=>{switch(Ah(e)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function Ap(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}var qN=async({prompt:e,modelName:t})=>{let r;try{r=(await kh(Ah(t))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),r=Math.ceil(e.length/4)}return KN(t)-r},r9=()=>!1,Th=class extends ue{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??r9(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},Tp=class extends Th{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:t,...r}){let{cache:n,...i}=r;super({callbacks:e??t,...i}),typeof n=="object"?this.cache=n:n?this.cache=p0.global():this.cache=void 0,this.caller=new Gi(r??{})}_encoding;async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(n=>typeof n=="string"?n:n.type==="text"&&"text"in n?n.text:"").join("");let r=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await kh("modelName"in this?Ah(this.modelName):"gpt2")}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}if(this._encoding)try{r=this._encoding.encode(t).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new Ip(e):Array.isArray(e)?new Sp(e.map(Qt)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){let r={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([s,o])=>o!==void 0).map(([s,o])=>`${s}:${JSON.stringify(o)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}get profile(){return{}}};var yn=class extends ue{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){let r=Ce(t);return this.func&&await this.func(e,r),this._callWithConfig(n=>Promise.resolve(n),e,r)}async*transform(e,t){let r=Ce(t),n,i=!0;for await(let s of this._transformStreamWithConfig(e,o=>o,r))if(yield s,i)if(n===void 0)n=s;else try{n=Vr(n,s)}catch{n=void 0,i=!1}this.func&&n!==void 0&&await this.func(n,r)}static assign(e){return new xp(new Qs({steps:e}))}};var HN=e=>e();function Oh(e){let t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}var P0={};M(P0,{BaseChatModel:()=>eo,SimpleChatModel:()=>n9});function C0(e){let t=[];for(let r of e){let n=r;if(Array.isArray(r.content))for(let i=0;i<r.content.length;i++){let s=r.content[i];(uc(s)||lc(s))&&n===r&&(n=new r.constructor({...n,content:[...r.content.slice(0,i),of(s),...r.content.slice(i+1)]}))}t.push(n)}return t}var eo=class va extends Tp{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(t){super(t),this.outputVersion=HN(()=>{let r=t.outputVersion??Je("LC_OUTPUT_VERSION");return r&&["v0","v1"].includes(r)?r:"v0"})}_separateRunnableConfigFromCallOptionsCompat(t){let[r,n]=super._separateRunnableConfigFromCallOptions(t);return n.signal=r.signal,[r,n]}async invoke(t,r){let n=va._convertInputToPromptValue(t);return(await this.generatePrompt([n],r,r?.callbacks)).generations[0][0].message}async*_streamResponseChunks(t,r,n){throw new Error("Not implemented.")}async*_streamIterator(t,r){if(this._streamResponseChunks===va.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,r);else{let i=va._convertInputToPromptValue(t).toChatMessages(),[s,o]=this._separateRunnableConfigFromCallOptionsCompat(r),a={...s.metadata,...this.getLsParams(o)},c=await xt.configure(s.callbacks,this.callbacks,s.tags,this.tags,a,this.metadata,{verbose:this.verbose}),u={options:o,invocation_params:this?.invocationParams(o),batch_size:1},l=o.outputVersion??this.outputVersion,p=await c?.handleChatModelStart(this.toJSON(),[C0(i)],s.runId,void 0,u,void 0,void 0,s.runName),f,d;try{for await(let m of this._streamResponseChunks(i,o,p?.[0])){if(m.message.id==null){let h=p?.at(0)?.runId;h!=null&&m.message._updateId(`run-${h}`)}m.message.response_metadata={...m.generationInfo,...m.message.response_metadata},l==="v1"?yield Oh(m.message):yield m.message,f?f=f.concat(m):f=m,Ol(m.message)&&m.message.usage_metadata!==void 0&&(d={tokenUsage:{promptTokens:m.message.usage_metadata.input_tokens,completionTokens:m.message.usage_metadata.output_tokens,totalTokens:m.message.usage_metadata.total_tokens}})}}catch(m){throw await Promise.all((p??[]).map(h=>h?.handleLLMError(m))),m}await Promise.all((p??[]).map(m=>m?.handleLLMEnd({generations:[[f]],llmOutput:d})))}}getLsParams(t){let r=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:t.stop,ls_provider:r}}async _generateUncached(t,r,n,i){let s=t.map(f=>f.map(Qt)),o;if(i!==void 0&&i.length===s.length)o=i;else{let f={...n.metadata,...this.getLsParams(r)},d=await xt.configure(n.callbacks,this.callbacks,n.tags,this.tags,f,this.metadata,{verbose:this.verbose}),m={options:r,invocation_params:this?.invocationParams(r),batch_size:1};o=await d?.handleChatModelStart(this.toJSON(),s.map(C0),n.runId,void 0,m,void 0,void 0,n.runName)}let a=r.outputVersion??this.outputVersion,c=[],u=[];if(!!o?.[0].handlers.find(dl)&&!this.disableStreaming&&s.length===1&&this._streamResponseChunks!==va.prototype._streamResponseChunks)try{let f=await this._streamResponseChunks(s[0],r,o?.[0]),d,m;for await(let h of f){if(h.message.id==null){let b=o?.at(0)?.runId;b!=null&&h.message._updateId(`run-${b}`)}d===void 0?d=h:d=Vr(d,h),Ol(h.message)&&h.message.usage_metadata!==void 0&&(m={tokenUsage:{promptTokens:h.message.usage_metadata.input_tokens,completionTokens:h.message.usage_metadata.output_tokens,totalTokens:h.message.usage_metadata.total_tokens}})}if(d===void 0)throw new Error("Received empty response from chat model call.");c.push([d]),await o?.[0].handleLLMEnd({generations:c,llmOutput:m})}catch(f){throw await o?.[0].handleLLMError(f),f}else{let f=await Promise.allSettled(s.map(async(d,m)=>{let h=await this._generate(d,{...r,promptIndex:m},o?.[m]);if(a==="v1")for(let b of h.generations)b.message=Oh(b.message);return h}));await Promise.all(f.map(async(d,m)=>{if(d.status==="fulfilled"){let h=d.value;for(let b of h.generations){if(b.message.id==null){let _=o?.at(0)?.runId;_!=null&&b.message._updateId(`run-${_}`)}b.message.response_metadata={...b.generationInfo,...b.message.response_metadata}}return h.generations.length===1&&(h.generations[0].message.response_metadata={...h.llmOutput,...h.generations[0].message.response_metadata}),c[m]=h.generations,u[m]=h.llmOutput,o?.[m]?.handleLLMEnd({generations:[h.generations],llmOutput:h.llmOutput})}else return await o?.[m]?.handleLLMError(d.reason),Promise.reject(d.reason)}))}let p={generations:c,llmOutput:u.length?this._combineLLMOutput?.(...u):void 0};return Object.defineProperty(p,Vo,{value:o?{runIds:o?.map(f=>f.runId)}:void 0,configurable:!0}),p}async _generateCached({messages:t,cache:r,llmStringKey:n,parsedOptions:i,handledOptions:s}){let o=t.map(_=>_.map(Qt)),a={...s.metadata,...this.getLsParams(i)},c=await xt.configure(s.callbacks,this.callbacks,s.tags,this.tags,a,this.metadata,{verbose:this.verbose}),u={options:i,invocation_params:this?.invocationParams(i),batch_size:1},l=await c?.handleChatModelStart(this.toJSON(),o.map(C0),s.runId,void 0,u,void 0,void 0,s.runName),p=[],d=(await Promise.allSettled(o.map(async(_,y)=>{let x=va._convertInputToPromptValue(_).toString(),I=await r.lookup(x,n);return I==null&&p.push(y),I}))).map((_,y)=>({result:_,runManager:l?.[y]})).filter(({result:_})=>_.status==="fulfilled"&&_.value!=null||_.status==="rejected"),m=i.outputVersion??this.outputVersion,h=[];await Promise.all(d.map(async({result:_,runManager:y},x)=>{if(_.status==="fulfilled"){let I=_.value;return h[x]=I.map(A=>("message"in A&&ot(A.message)&&si(A.message)&&(A.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},m==="v1"&&(A.message=Oh(A.message))),A.generationInfo={...A.generationInfo,tokenUsage:{}},A)),I.length&&await y?.handleLLMNewToken(I[0].text),y?.handleLLMEnd({generations:[I]},void 0,void 0,void 0,{cached:!0})}else return await y?.handleLLMError(_.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(_.reason)}));let b={generations:h,missingPromptIndices:p,startedRunManagers:l};return Object.defineProperty(b,Vo,{value:l?{runIds:l?.map(_=>_.runId)}:void 0,configurable:!0}),b}async generate(t,r,n){let i;Array.isArray(r)?i={stop:r}:i=r;let s=t.map(m=>m.map(Qt)),[o,a]=this._separateRunnableConfigFromCallOptionsCompat(i);if(o.callbacks=o.callbacks??n,!this.cache)return this._generateUncached(s,a,o);let{cache:c}=this,u=this._getSerializedCacheKeyParametersForCall(a),{generations:l,missingPromptIndices:p,startedRunManagers:f}=await this._generateCached({messages:s,cache:c,llmStringKey:u,parsedOptions:a,handledOptions:o}),d={};if(p.length>0){let m=await this._generateUncached(p.map(h=>s[h]),a,o,f!==void 0?p.map(h=>f?.[h]):void 0);await Promise.all(m.generations.map(async(h,b)=>{let _=p[b];l[_]=h;let y=va._convertInputToPromptValue(s[_]).toString();return c.update(y,u,h)})),d=m.llmOutput??{}}return{generations:l,llmOutput:d}}invocationParams(t){return{}}_modelType(){return"base_chat_model"}async generatePrompt(t,r,n){let i=t.map(s=>s.toChatMessages());return this.generate(i,r,n)}withStructuredOutput(t,r){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(r?.strict)throw new Error('"strict" mode is not supported for this model by default.');let n=t,i=r?.name,s=On(n)??"A function available to call.",o=r?.method,a=r?.includeRaw;if(o==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let c=i??"extract",u;_r(n)?u=[{type:"function",function:{name:c,description:s,parameters:Ye(n)}}]:("name"in n&&(c=n.name),u=[{type:"function",function:{name:c,description:s,parameters:n}}]);let l=this.bindTools(u),p=tr.from(h=>{if(!nt.isInstance(h))throw new Error("Input is not an AIMessageChunk.");if(!h.tool_calls||h.tool_calls.length===0)throw new Error("No tool calls found in the response.");let b=h.tool_calls.find(_=>_.name===c);if(!b)throw new Error(`No tool call found with name ${c}.`);return b.args});if(!a)return l.pipe(p).withConfig({runName:"StructuredOutput"});let f=yn.assign({parsed:(h,b)=>p.invoke(h.raw,b)}),d=yn.assign({parsed:()=>null}),m=f.withFallbacks({fallbacks:[d]});return br.from([{raw:l},m]).withConfig({runName:"StructuredOutputRunnable"})}},n9=class extends eo{async _generate(e,t,r){let n=await this._call(e,t,r),i=new $e(n);if(typeof i.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:i.content,message:i}]}}};var N0={};M(N0,{BaseLLM:()=>R0,LLM:()=>$h});var R0=class Op extends Tp{lc_namespace=["langchain","llms",this._llmType()];async invoke(t,r){let n=Op._convertInputToPromptValue(t);return(await this.generatePrompt([n],r,r?.callbacks)).generations[0][0].text}async*_streamResponseChunks(t,r,n){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(t){let[r,n]=super._separateRunnableConfigFromCallOptions(t);return n.signal=r.signal,[r,n]}async*_streamIterator(t,r){if(this._streamResponseChunks===Op.prototype._streamResponseChunks)yield this.invoke(t,r);else{let n=Op._convertInputToPromptValue(t),[i,s]=this._separateRunnableConfigFromCallOptionsCompat(r),o=await xt.configure(i.callbacks,this.callbacks,i.tags,this.tags,i.metadata,this.metadata,{verbose:this.verbose}),a={options:s,invocation_params:this?.invocationParams(s),batch_size:1},c=await o?.handleLLMStart(this.toJSON(),[n.toString()],i.runId,void 0,a,void 0,void 0,i.runName),u=new ai({text:""});try{for await(let l of this._streamResponseChunks(n.toString(),s,c?.[0]))u?u=u.concat(l):u=l,typeof l.text=="string"&&(yield l.text)}catch(l){throw await Promise.all((c??[]).map(p=>p?.handleLLMError(l))),l}await Promise.all((c??[]).map(l=>l?.handleLLMEnd({generations:[[u]]})))}}async generatePrompt(t,r,n){let i=t.map(s=>s.toString());return this.generate(i,r,n)}invocationParams(t){return{}}_flattenLLMResult(t){let r=[];for(let n=0;n<t.generations.length;n+=1){let i=t.generations[n];if(n===0)r.push({generations:[i],llmOutput:t.llmOutput});else{let s=t.llmOutput?{...t.llmOutput,tokenUsage:{}}:void 0;r.push({generations:[i],llmOutput:s})}}return r}async _generateUncached(t,r,n,i){let s;if(i!==void 0&&i.length===t.length)s=i;else{let u=await xt.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}),l={options:r,invocation_params:this?.invocationParams(r),batch_size:t.length};s=await u?.handleLLMStart(this.toJSON(),t,n.runId,void 0,l,void 0,void 0,n?.runName)}let o=!!s?.[0].handlers.find(dl),a;if(o&&t.length===1&&this._streamResponseChunks!==Op.prototype._streamResponseChunks)try{let u=await this._streamResponseChunks(t[0],r,s?.[0]),l;for await(let p of u)l===void 0?l=p:l=Vr(l,p);if(l===void 0)throw new Error("Received empty response from chat model call.");a={generations:[[l]],llmOutput:{}},await s?.[0].handleLLMEnd(a)}catch(u){throw await s?.[0].handleLLMError(u),u}else{try{a=await this._generate(t,r,s?.[0])}catch(l){throw await Promise.all((s??[]).map(p=>p?.handleLLMError(l))),l}let u=this._flattenLLMResult(a);await Promise.all((s??[]).map((l,p)=>l?.handleLLMEnd(u[p])))}let c=s?.map(u=>u.runId)||void 0;return Object.defineProperty(a,Vo,{value:c?{runIds:c}:void 0,configurable:!0}),a}async _generateCached({prompts:t,cache:r,llmStringKey:n,parsedOptions:i,handledOptions:s,runId:o}){let a=await xt.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),c={options:i,invocation_params:this?.invocationParams(i),batch_size:t.length},u=await a?.handleLLMStart(this.toJSON(),t,o,void 0,c,void 0,void 0,s?.runName),l=[],f=(await Promise.allSettled(t.map(async(h,b)=>{let _=await r.lookup(h,n);return _==null&&l.push(b),_}))).map((h,b)=>({result:h,runManager:u?.[b]})).filter(({result:h})=>h.status==="fulfilled"&&h.value!=null||h.status==="rejected"),d=[];await Promise.all(f.map(async({result:h,runManager:b},_)=>{if(h.status==="fulfilled"){let y=h.value;return d[_]=y.map(x=>(x.generationInfo={...x.generationInfo,tokenUsage:{}},x)),y.length&&await b?.handleLLMNewToken(y[0].text),b?.handleLLMEnd({generations:[y]},void 0,void 0,void 0,{cached:!0})}else return await b?.handleLLMError(h.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(h.reason)}));let m={generations:d,missingPromptIndices:l,startedRunManagers:u};return Object.defineProperty(m,Vo,{value:u?{runIds:u?.map(h=>h.runId)}:void 0,configurable:!0}),m}async generate(t,r,n){if(!Array.isArray(t))throw new Error("Argument 'prompts' is expected to be a string[]");let i;Array.isArray(r)?i={stop:r}:i=r;let[s,o]=this._separateRunnableConfigFromCallOptionsCompat(i);if(s.callbacks=s.callbacks??n,!this.cache)return this._generateUncached(t,o,s);let{cache:a}=this,c=this._getSerializedCacheKeyParametersForCall(o),{generations:u,missingPromptIndices:l,startedRunManagers:p}=await this._generateCached({prompts:t,cache:a,llmStringKey:c,parsedOptions:o,handledOptions:s,runId:s.runId}),f={};if(l.length>0){let d=await this._generateUncached(l.map(m=>t[m]),o,s,p!==void 0?l.map(m=>p?.[m]):void 0);await Promise.all(d.generations.map(async(m,h)=>{let b=l[h];return u[b]=m,a.update(t[b],c,m)})),f=d.llmOutput??{}}return{generations:u,llmOutput:f}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},$h=class extends R0{async _generate(e,t,r){return{generations:await Promise.all(e.map((i,s)=>this._call(i,{...t,promptIndex:s},r).then(o=>[{text:o}])))}}};var WN={};var JN=class extends ue{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,t){let{key:r,input:n}=e,i=this.runnables[r];if(i===void 0)throw new Error(`No runnable associated with key "${r}".`);return i.invoke(n,Ce(t))}async batch(e,t,r){let n=e.map(p=>p.key),i=e.map(p=>p.input);if(n.find(p=>this.runnables[p]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");let o=n.map(p=>this.runnables[p]),a=this._getOptionsList(t??{},e.length),c=a[0]?.maxConcurrency??r?.maxConcurrency,u=c&&c>0?c:e.length,l=[];for(let p=0;p<i.length;p+=u){let f=i.slice(p,p+u).map((m,h)=>o[h].invoke(m,a[h])),d=await Promise.all(f);l.push(d)}return l.flat()}async stream(e,t){let{key:r,input:n}=e,i=this.runnables[r];if(i===void 0)throw new Error(`No runnable associated with key "${r}".`);return i.stream(n,t)}};var XN=class extends ue{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");let r=e.slice(0,-1).map(([i,s])=>[dt(i),dt(s)]),n=dt(e[e.length-1]);return new this({branches:r,default:n})}async _invoke(e,t,r){let n;for(let i=0;i<this.branches.length;i+=1){let[s,o]=this.branches[i];if(await s.invoke(e,Ne(t,{callbacks:r?.getChild(`condition:${i+1}`)}))){n=await o.invoke(e,Ne(t,{callbacks:r?.getChild(`branch:${i+1}`)}));break}}return n||(n=await this.default.invoke(e,Ne(t,{callbacks:r?.getChild("branch:default")}))),n}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){let n=await(await Et(t))?.handleChainStart(this.toJSON(),Tt(e,"input"),t?.runId,void 0,void 0,void 0,t?.runName),i,s=!0,o;try{for(let a=0;a<this.branches.length;a+=1){let[c,u]=this.branches[a];if(await c.invoke(e,Ne(t,{callbacks:n?.getChild(`condition:${a+1}`)}))){o=await u.stream(e,Ne(t,{callbacks:n?.getChild(`branch:${a+1}`)}));for await(let p of o)if(yield p,s)if(i===void 0)i=p;else try{i=Vr(i,p)}catch{i=void 0,s=!1}break}}if(o===void 0){o=await this.default.stream(e,Ne(t,{callbacks:n?.getChild("branch:default")}));for await(let a of o)if(yield a,s)if(i===void 0)i=a;else try{i=Vr(i,a)}catch{i=void 0,s=!1}}}catch(a){throw await n?.handleChainError(a),a}await n?.handleChainEnd(i??{})}};var YN=class extends gn{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=tr.from((s,o)=>this._enterHistory(s,o??{})).withConfig({runName:"loadHistory"}),r=e.historyMessagesKey??e.inputMessagesKey;r&&(t=yn.assign({[r]:t}).withConfig({runName:"insertHistory"}));let n=t.pipe(e.runnable.withListeners({onEnd:(s,o)=>this._exitHistory(s,o??{})})).withConfig({runName:"RunnableWithMessageHistory"}),i=e.config??{};super({...e,config:i,bound:n}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e=="object"&&!Array.isArray(e)&&!ot(e)){let r;this.inputMessagesKey?r=this.inputMessagesKey:Object.keys(e).length===1?r=Object.keys(e)[0]:r="input",Array.isArray(e[r])&&Array.isArray(e[r][0])?t=e[r][0]:t=e[r]}else t=e;if(typeof t=="string")return[new at(t)];if(Array.isArray(t))return t;if(ot(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
114
- Got ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!ot(e)&&typeof e!="string"){let r;this.outputMessagesKey!==void 0?r=this.outputMessagesKey:Object.keys(e).length===1?r=Object.keys(e)[0]:r="output",e.generations!==void 0?t=e.generations[0][0].message:t=e[r]}else t=e;if(typeof t=="string")return[new $e(t)];if(Array.isArray(t))return t;if(ot(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){let n=await(t?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?n.concat(this._getInputMessages(e)):n}async _exitHistory(e,t){let r=t.configurable?.messageHistory,n;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?n=e.inputs[0]:n=e.inputs;let i=this._getInputMessages(n);if(this.historyMessagesKey===void 0){let a=await r.getMessages();i=i.slice(a.length)}let s=e.outputs;if(!s)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);let o=this._getOutputMessages(s);await r.addMessages([...i,...o])}async _mergeConfig(...e){let t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){let n={[this.inputMessagesKey??"input"]:"foo"},i={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
115
- eg. chain.invoke(${JSON.stringify(n)}, ${JSON.stringify(i)})`)}let{sessionId:r}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(r),t}};var M0={};M(M0,{RouterRunnable:()=>JN,Runnable:()=>ue,RunnableAssign:()=>xp,RunnableBinding:()=>gn,RunnableBranch:()=>XN,RunnableEach:()=>aN,RunnableLambda:()=>tr,RunnableMap:()=>Qs,RunnableParallel:()=>dN,RunnablePassthrough:()=>yn,RunnablePick:()=>Jx,RunnableRetry:()=>gh,RunnableSequence:()=>br,RunnableToolLike:()=>hh,RunnableWithFallbacks:()=>Wx,RunnableWithMessageHistory:()=>YN,_coerceToRunnable:()=>dt,ensureConfig:()=>Ce,getCallbackManagerForConfig:()=>Et,mergeConfigs:()=>Dt,patchConfig:()=>Ne,pickRunnableConfigKeys:()=>hr,raceWithSignal:()=>ln});var j0={};M(j0,{applyPatch:()=>Fs,compare:()=>Bs});var Zc=class extends ue{parseResultWithPrompt(e,t,r){return this.parseResult(e,r)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e=="string"?this._callWithConfig(async(r,n)=>this.parseResult([{text:r}],n?.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(r,n)=>this.parseResult([{message:r,text:this._baseMessageToString(r)}],n?.callbacks),e,{...t,runType:"parser"})}},ts=class extends Zc{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,r){return this.parse(e,r)}_type(){throw new Error("_type not implemented")}},Hr=class extends Error{llmOutput;observation;sendToLLM;constructor(e,t,r,n=!1){if(super(e),this.llmOutput=t,this.observation=r,this.sendToLLM=n,n&&(r===void 0||t===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");Ms(this,"OUTPUT_PARSING_FAILURE")}};var rs=class extends ts{async*_transform(e){for await(let t of e)typeof t=="string"?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}},gi=class extends rs{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let t,r;for await(let n of e){if(typeof n!="string"&&typeof n.content!="string")throw new Error("Cannot handle non-string output.");let i;if(Di(n)){if(typeof n.content!="string")throw new Error("Cannot handle non-string message output.");i=new Zr({message:n,text:n.content})}else if(ot(n)){if(typeof n.content!="string")throw new Error("Cannot handle non-string message output.");i=new Zr({message:Lo(n),text:n.content})}else i=new ai({text:n});r===void 0?r=i:r=r.concat(i);let s=await this.parsePartialResult([r]);s!=null&&!fi(s,t)&&(this.diff?yield this._diff(t,s):yield s,t=s)}}getFormatInstructions(){return""}};var QN=class extends rs{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}};var Gc=class extends rs{re;async*_transform(e){let t="";for await(let r of e)if(typeof r=="string"?t+=r:t+=r.content,this.re){let n=[...t.matchAll(this.re)];if(n.length>1){let i=0;for(let s of n.slice(0,-1))yield[s[1]],i+=(s.index??0)+s[0].length;t=t.slice(i)}}else{let n=await this.parse(t);if(n.length>1){for(let i of n.slice(0,-1))yield[i];t=n[n.length-1]}}for(let r of await this.parse(t))yield[r]}},eR=class extends Gc{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(e){try{return e.trim().split(",").map(t=>t.trim())}catch{throw new Hr(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},tR=class extends Gc{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:e,separator:t}){super(...arguments),this.length=e,this.separator=t||","}async parse(e){try{let t=e.trim().split(this.separator).map(r=>r.trim());if(this.length!==void 0&&t.length!==this.length)throw new Hr(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===Hr.prototype?t:new Hr(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},rR=class extends Gc{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
116
-
117
- 1. foo
118
-
119
- 2. bar
120
-
121
- 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},nR=class extends Gc{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
122
-
123
- 1. foo
124
-
125
- 2. bar
126
-
127
- 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}};var iR=class extends rs{static lc_name(){return"StrOutputParser"}lc_namespace=["langchain_core","output_parsers","string"];lc_serializable=!0;parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((t,r)=>t+this._messageContentToString(r),"")}};var Kc=class extends ts{static lc_name(){return"StructuredOutputParser"}lc_namespace=["langchain","output_parsers","structured"];toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),this.schema=e}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let t=ce.object(Object.fromEntries(Object.entries(e).map(([r,n])=>[r,ce.string().describe(n)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
128
-
129
- "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
130
-
131
- For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
132
- would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
133
- Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
134
-
135
- Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
136
-
137
- Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
138
- \`\`\`json
139
- ${JSON.stringify(Ye(this.schema))}
140
- \`\`\`
141
- `}async parse(e){try{let t=e.trim(),n=(t.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||t.match(/```json\s*([\s\S]*?)```/)?.[1]||t).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(i,s)=>`"${s.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await Hs(this.schema,JSON.parse(n))}catch(t){throw new Hr(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}},D0=class extends Kc{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(e){let t=e?.interpolationDepth??1;if(t<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
142
- \`\`\`json
143
- ${this._schemaToInstruction(Ye(this.schema)).replaceAll("{","{".repeat(t)).replaceAll("}","}".repeat(t))}
144
- \`\`\``}_schemaToInstruction(e,t=2){let r=e;if("type"in r){let n=!1,i;if(Array.isArray(r.type)){let a=r.type.findIndex(c=>c==="null");a!==-1&&(n=!0,r.type.splice(a,1)),i=r.type.join(" | ")}else i=r.type;if(r.type==="object"&&r.properties){let a=r.description?` // ${r.description}`:"";return`{
145
- ${Object.entries(r.properties).map(([u,l])=>{let p=r.required?.includes(u)?"":" (optional)";return`${" ".repeat(t)}"${u}": ${this._schemaToInstruction(l,t+2)}${p}`}).join(`
146
- `)}
147
- ${" ".repeat(t-2)}}${a}`}if(r.type==="array"&&r.items){let a=r.description?` // ${r.description}`:"";return`array[
148
- ${" ".repeat(t)}${this._schemaToInstruction(r.items,t+2)}
149
- ${" ".repeat(t-2)}] ${a}`}let s=n?" (nullable)":"",o=r.description?` // ${r.description}`:"";return`${i}${o}${s}`}if("anyOf"in r)return r.anyOf.map(n=>this._schemaToInstruction(n,t)).join(`
150
- ${" ".repeat(t-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let t=ce.object(Object.fromEntries(Object.entries(e).map(([r,n])=>[r,ce.string().describe(n)])));return new this(t)}},sR=class extends ts{structuredInputParser;constructor({inputSchema:e}){super(...arguments),this.structuredInputParser=new D0(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(r){throw new Hr(`Failed to parse. Text: "${e}". Error: ${r}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}};var $p=class extends gi{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?Bs(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Al(e[0].text)}async parse(e){return Al(e,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(e){return e.text}};var i9=function(){let e={};e.parser=function(v,g){return new r(v,g)},e.SAXParser=r,e.SAXStream=u,e.createStream=c,e.MAX_BUFFER_LENGTH=65536;let t=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];e.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function r(v,g){if(!(this instanceof r))return new r(v,g);var R=this;i(R),R.q=R.c="",R.bufferCheckPosition=e.MAX_BUFFER_LENGTH,R.opt=g||{},R.opt.lowercase=R.opt.lowercase||R.opt.lowercasetags,R.looseCase=R.opt.lowercase?"toLowerCase":"toUpperCase",R.tags=[],R.closed=R.closedRoot=R.sawRoot=!1,R.tag=R.error=null,R.strict=!!v,R.noscript=!!(v||R.opt.noscript),R.state=w.BEGIN,R.strictEntities=R.opt.strictEntities,R.ENTITIES=R.strictEntities?Object.create(e.XML_ENTITIES):Object.create(e.ENTITIES),R.attribList=[],R.opt.xmlns&&(R.ns=Object.create(m)),R.trackPosition=R.opt.position!==!1,R.trackPosition&&(R.position=R.line=R.column=0),P(R,"onready")}Object.create||(Object.create=function(v){function g(){}g.prototype=v;var R=new g;return R}),Object.keys||(Object.keys=function(v){var g=[];for(var R in v)v.hasOwnProperty(R)&&g.push(R);return g});function n(v){for(var g=Math.max(e.MAX_BUFFER_LENGTH,10),R=0,E=0,je=t.length;E<je;E++){var qe=v[t[E]].length;if(qe>g)switch(t[E]){case"textNode":Oe(v);break;case"cdata":V(v,"oncdata",v.cdata),v.cdata="";break;case"script":V(v,"onscript",v.script),v.script="";break;default:cr(v,"Max buffer length exceeded: "+t[E])}R=Math.max(R,qe)}var tt=e.MAX_BUFFER_LENGTH-R;v.bufferCheckPosition=tt+v.position}function i(v){for(var g=0,R=t.length;g<R;g++)v[t[g]]=""}function s(v){Oe(v),v.cdata!==""&&(V(v,"oncdata",v.cdata),v.cdata=""),v.script!==""&&(V(v,"onscript",v.script),v.script="")}r.prototype={end:function(){Lr(this)},write:In,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){s(this)}};var o=ReadableStream;o||(o=function(){});var a=e.EVENTS.filter(function(v){return v!=="error"&&v!=="end"});function c(v,g){return new u(v,g)}function u(v,g){if(!(this instanceof u))return new u(v,g);o.apply(this),this._parser=new r(v,g),this.writable=!0,this.readable=!0;var R=this;this._parser.onend=function(){R.emit("end")},this._parser.onerror=function(E){R.emit("error",E),R._parser.error=null},this._decoder=null,a.forEach(function(E){Object.defineProperty(R,"on"+E,{get:function(){return R._parser["on"+E]},set:function(je){if(!je)return R.removeAllListeners(E),R._parser["on"+E]=je,je;R.on(E,je)},enumerable:!0,configurable:!1})})}u.prototype=Object.create(o.prototype,{constructor:{value:u}}),u.prototype.write=function(v){return this._parser.write(v.toString()),this.emit("data",v),!0},u.prototype.end=function(v){return v&&v.length&&this.write(v),this._parser.end(),!0},u.prototype.on=function(v,g){var R=this;return!R._parser["on"+v]&&a.indexOf(v)!==-1&&(R._parser["on"+v]=function(){var E=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);E.splice(0,0,v),R.emit.apply(R,E)}),o.prototype.on.call(R,v,g)};var l="[CDATA[",p="DOCTYPE",f="http://www.w3.org/XML/1998/namespace",d="http://www.w3.org/2000/xmlns/",m={xml:f,xmlns:d},h=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,b=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,_=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,y=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function x(v){return v===" "||v===`
151
- `||v==="\r"||v===" "}function I(v){return v==='"'||v==="'"}function A(v){return v===">"||x(v)}function j(v,g){return v.test(g)}function O(v,g){return!j(v,g)}var w=0;e.STATE={BEGIN:w++,BEGIN_WHITESPACE:w++,TEXT:w++,TEXT_ENTITY:w++,OPEN_WAKA:w++,SGML_DECL:w++,SGML_DECL_QUOTED:w++,DOCTYPE:w++,DOCTYPE_QUOTED:w++,DOCTYPE_DTD:w++,DOCTYPE_DTD_QUOTED:w++,COMMENT_STARTING:w++,COMMENT:w++,COMMENT_ENDING:w++,COMMENT_ENDED:w++,CDATA:w++,CDATA_ENDING:w++,CDATA_ENDING_2:w++,PROC_INST:w++,PROC_INST_BODY:w++,PROC_INST_ENDING:w++,OPEN_TAG:w++,OPEN_TAG_SLASH:w++,ATTRIB:w++,ATTRIB_NAME:w++,ATTRIB_NAME_SAW_WHITE:w++,ATTRIB_VALUE:w++,ATTRIB_VALUE_QUOTED:w++,ATTRIB_VALUE_CLOSED:w++,ATTRIB_VALUE_UNQUOTED:w++,ATTRIB_VALUE_ENTITY_Q:w++,ATTRIB_VALUE_ENTITY_U:w++,CLOSE_TAG:w++,CLOSE_TAG_SAW_WHITE:w++,SCRIPT:w++,SCRIPT_ENDING:w++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach(function(v){var g=e.ENTITIES[v],R=typeof g=="number"?String.fromCharCode(g):g;e.ENTITIES[v]=R});for(var U in e.STATE)e.STATE[e.STATE[U]]=U;w=e.STATE;function P(v,g,R){v[g]&&v[g](R)}function V(v,g,R){v.textNode&&Oe(v),P(v,g,R)}function Oe(v){v.textNode=Ke(v.opt,v.textNode),v.textNode&&P(v,"ontext",v.textNode),v.textNode=""}function Ke(v,g){return v.trim&&(g=g.trim()),v.normalize&&(g=g.replace(/\s+/g," ")),g}function cr(v,g){return Oe(v),v.trackPosition&&(g+=`
152
- Line: `+v.line+`
153
- Column: `+v.column+`
154
- Char: `+v.c),g=new Error(g),v.error=g,P(v,"onerror",g),v}function Lr(v){return v.sawRoot&&!v.closedRoot&&Me(v,"Unclosed root tag"),v.state!==w.BEGIN&&v.state!==w.BEGIN_WHITESPACE&&v.state!==w.TEXT&&cr(v,"Unexpected end"),Oe(v),v.c="",v.closed=!0,P(v,"onend"),r.call(v,v.strict,v.opt),v}function Me(v,g){if(typeof v!="object"||!(v instanceof r))throw new Error("bad call to strictFail");v.strict&&cr(v,g)}function Ao(v){v.strict||(v.tagName=v.tagName[v.looseCase]());var g=v.tags[v.tags.length-1]||v,R=v.tag={name:v.tagName,attributes:{}};v.opt.xmlns&&(R.ns=g.ns),v.attribList.length=0,V(v,"onopentagstart",R)}function $i(v,g){var R=v.indexOf(":"),E=R<0?["",v]:v.split(":"),je=E[0],qe=E[1];return g&&v==="xmlns"&&(je="xmlns",qe=""),{prefix:je,local:qe}}function To(v){if(v.strict||(v.attribName=v.attribName[v.looseCase]()),v.attribList.indexOf(v.attribName)!==-1||v.tag.attributes.hasOwnProperty(v.attribName)){v.attribName=v.attribValue="";return}if(v.opt.xmlns){var g=$i(v.attribName,!0),R=g.prefix,E=g.local;if(R==="xmlns")if(E==="xml"&&v.attribValue!==f)Me(v,"xml: prefix must be bound to "+f+`
155
- Actual: `+v.attribValue);else if(E==="xmlns"&&v.attribValue!==d)Me(v,"xmlns: prefix must be bound to "+d+`
156
- Actual: `+v.attribValue);else{var je=v.tag,qe=v.tags[v.tags.length-1]||v;je.ns===qe.ns&&(je.ns=Object.create(qe.ns)),je.ns[E]=v.attribValue}v.attribList.push([v.attribName,v.attribValue])}else v.tag.attributes[v.attribName]=v.attribValue,V(v,"onattribute",{name:v.attribName,value:v.attribValue});v.attribName=v.attribValue=""}function xn(v,g){if(v.opt.xmlns){var R=v.tag,E=$i(v.tagName);R.prefix=E.prefix,R.local=E.local,R.uri=R.ns[E.prefix]||"",R.prefix&&!R.uri&&(Me(v,"Unbound namespace prefix: "+JSON.stringify(v.tagName)),R.uri=E.prefix);var je=v.tags[v.tags.length-1]||v;R.ns&&je.ns!==R.ns&&Object.keys(R.ns).forEach(function(Oo){V(v,"onopennamespace",{prefix:Oo,uri:R.ns[Oo]})});for(var qe=0,tt=v.attribList.length;qe<tt;qe++){var St=v.attribList[qe],Bt=St[0],Sn=St[1],mt=$i(Bt,!0),tn=mt.prefix,oc=mt.local,Bd=tn===""?"":R.ns[tn]||"",J={name:Bt,value:Sn,prefix:tn,local:oc,uri:Bd};tn&&tn!=="xmlns"&&!Bd&&(Me(v,"Unbound namespace prefix: "+JSON.stringify(tn)),J.uri=tn),v.tag.attributes[Bt]=J,V(v,"onattribute",J)}v.attribList.length=0}v.tag.isSelfClosing=!!g,v.sawRoot=!0,v.tags.push(v.tag),V(v,"onopentag",v.tag),g||(!v.noscript&&v.tagName.toLowerCase()==="script"?v.state=w.SCRIPT:v.state=w.TEXT,v.tag=null,v.tagName=""),v.attribName=v.attribValue="",v.attribList.length=0}function Ci(v){if(!v.tagName){Me(v,"Weird empty close tag."),v.textNode+="</>",v.state=w.TEXT;return}if(v.script){if(v.tagName!=="script"){v.script+="</"+v.tagName+">",v.tagName="",v.state=w.SCRIPT;return}V(v,"onscript",v.script),v.script=""}var g=v.tags.length,R=v.tagName;v.strict||(R=R[v.looseCase]());for(var E=R;g--;){var je=v.tags[g];if(je.name!==E)Me(v,"Unexpected close tag");else break}if(g<0){Me(v,"Unmatched closing tag: "+v.tagName),v.textNode+="</"+v.tagName+">",v.state=w.TEXT;return}v.tagName=R;for(var qe=v.tags.length;qe-- >g;){var tt=v.tag=v.tags.pop();v.tagName=v.tag.name,V(v,"onclosetag",v.tagName);var St={};for(var Bt in tt.ns)St[Bt]=tt.ns[Bt];var Sn=v.tags[v.tags.length-1]||v;v.opt.xmlns&&tt.ns!==Sn.ns&&Object.keys(tt.ns).forEach(function(mt){var tn=tt.ns[mt];V(v,"onclosenamespace",{prefix:mt,uri:tn})})}g===0&&(v.closedRoot=!0),v.tagName=v.attribValue=v.attribName="",v.attribList.length=0,v.state=w.TEXT}function nl(v){var g=v.entity,R=g.toLowerCase(),E,je="";return v.ENTITIES[g]?v.ENTITIES[g]:v.ENTITIES[R]?v.ENTITIES[R]:(g=R,g.charAt(0)==="#"&&(g.charAt(1)==="x"?(g=g.slice(2),E=parseInt(g,16),je=E.toString(16)):(g=g.slice(1),E=parseInt(g,10),je=E.toString(10))),g=g.replace(/^0+/,""),isNaN(E)||je.toLowerCase()!==g?(Me(v,"Invalid character entity"),"&"+v.entity+";"):String.fromCodePoint(E))}function il(v,g){g==="<"?(v.state=w.OPEN_WAKA,v.startTagPosition=v.position):x(g)||(Me(v,"Non-whitespace before first tag."),v.textNode=g,v.state=w.TEXT)}function sl(v,g){var R="";return g<v.length&&(R=v.charAt(g)),R}function In(v){var g=this;if(this.error)throw this.error;if(g.closed)return cr(g,"Cannot write after close. Assign an onready handler.");if(v===null)return Lr(g);typeof v=="object"&&(v=v.toString());for(var R=0,E="";E=sl(v,R++),g.c=E,!!E;)switch(g.trackPosition&&(g.position++,E===`
157
- `?(g.line++,g.column=0):g.column++),g.state){case w.BEGIN:if(g.state=w.BEGIN_WHITESPACE,E==="\uFEFF")continue;il(g,E);continue;case w.BEGIN_WHITESPACE:il(g,E);continue;case w.TEXT:if(g.sawRoot&&!g.closedRoot){for(var je=R-1;E&&E!=="<"&&E!=="&";)E=sl(v,R++),E&&g.trackPosition&&(g.position++,E===`
158
- `?(g.line++,g.column=0):g.column++);g.textNode+=v.substring(je,R-1)}E==="<"&&!(g.sawRoot&&g.closedRoot&&!g.strict)?(g.state=w.OPEN_WAKA,g.startTagPosition=g.position):(!x(E)&&(!g.sawRoot||g.closedRoot)&&Me(g,"Text data outside of root node."),E==="&"?g.state=w.TEXT_ENTITY:g.textNode+=E);continue;case w.SCRIPT:E==="<"?g.state=w.SCRIPT_ENDING:g.script+=E;continue;case w.SCRIPT_ENDING:E==="/"?g.state=w.CLOSE_TAG:(g.script+="<"+E,g.state=w.SCRIPT);continue;case w.OPEN_WAKA:if(E==="!")g.state=w.SGML_DECL,g.sgmlDecl="";else if(!x(E))if(j(h,E))g.state=w.OPEN_TAG,g.tagName=E;else if(E==="/")g.state=w.CLOSE_TAG,g.tagName="";else if(E==="?")g.state=w.PROC_INST,g.procInstName=g.procInstBody="";else{if(Me(g,"Unencoded <"),g.startTagPosition+1<g.position){var qe=g.position-g.startTagPosition;E=new Array(qe).join(" ")+E}g.textNode+="<"+E,g.state=w.TEXT}continue;case w.SGML_DECL:(g.sgmlDecl+E).toUpperCase()===l?(V(g,"onopencdata"),g.state=w.CDATA,g.sgmlDecl="",g.cdata=""):g.sgmlDecl+E==="--"?(g.state=w.COMMENT,g.comment="",g.sgmlDecl=""):(g.sgmlDecl+E).toUpperCase()===p?(g.state=w.DOCTYPE,(g.doctype||g.sawRoot)&&Me(g,"Inappropriately located doctype declaration"),g.doctype="",g.sgmlDecl=""):E===">"?(V(g,"onsgmldeclaration",g.sgmlDecl),g.sgmlDecl="",g.state=w.TEXT):(I(E)&&(g.state=w.SGML_DECL_QUOTED),g.sgmlDecl+=E);continue;case w.SGML_DECL_QUOTED:E===g.q&&(g.state=w.SGML_DECL,g.q=""),g.sgmlDecl+=E;continue;case w.DOCTYPE:E===">"?(g.state=w.TEXT,V(g,"ondoctype",g.doctype),g.doctype=!0):(g.doctype+=E,E==="["?g.state=w.DOCTYPE_DTD:I(E)&&(g.state=w.DOCTYPE_QUOTED,g.q=E));continue;case w.DOCTYPE_QUOTED:g.doctype+=E,E===g.q&&(g.q="",g.state=w.DOCTYPE);continue;case w.DOCTYPE_DTD:g.doctype+=E,E==="]"?g.state=w.DOCTYPE:I(E)&&(g.state=w.DOCTYPE_DTD_QUOTED,g.q=E);continue;case w.DOCTYPE_DTD_QUOTED:g.doctype+=E,E===g.q&&(g.state=w.DOCTYPE_DTD,g.q="");continue;case w.COMMENT:E==="-"?g.state=w.COMMENT_ENDING:g.comment+=E;continue;case w.COMMENT_ENDING:E==="-"?(g.state=w.COMMENT_ENDED,g.comment=Ke(g.opt,g.comment),g.comment&&V(g,"oncomment",g.comment),g.comment=""):(g.comment+="-"+E,g.state=w.COMMENT);continue;case w.COMMENT_ENDED:E!==">"?(Me(g,"Malformed comment"),g.comment+="--"+E,g.state=w.COMMENT):g.state=w.TEXT;continue;case w.CDATA:E==="]"?g.state=w.CDATA_ENDING:g.cdata+=E;continue;case w.CDATA_ENDING:E==="]"?g.state=w.CDATA_ENDING_2:(g.cdata+="]"+E,g.state=w.CDATA);continue;case w.CDATA_ENDING_2:E===">"?(g.cdata&&V(g,"oncdata",g.cdata),V(g,"onclosecdata"),g.cdata="",g.state=w.TEXT):E==="]"?g.cdata+="]":(g.cdata+="]]"+E,g.state=w.CDATA);continue;case w.PROC_INST:E==="?"?g.state=w.PROC_INST_ENDING:x(E)?g.state=w.PROC_INST_BODY:g.procInstName+=E;continue;case w.PROC_INST_BODY:if(!g.procInstBody&&x(E))continue;E==="?"?g.state=w.PROC_INST_ENDING:g.procInstBody+=E;continue;case w.PROC_INST_ENDING:E===">"?(V(g,"onprocessinginstruction",{name:g.procInstName,body:g.procInstBody}),g.procInstName=g.procInstBody="",g.state=w.TEXT):(g.procInstBody+="?"+E,g.state=w.PROC_INST_BODY);continue;case w.OPEN_TAG:j(b,E)?g.tagName+=E:(Ao(g),E===">"?xn(g):E==="/"?g.state=w.OPEN_TAG_SLASH:(x(E)||Me(g,"Invalid character in tag name"),g.state=w.ATTRIB));continue;case w.OPEN_TAG_SLASH:E===">"?(xn(g,!0),Ci(g)):(Me(g,"Forward-slash in opening tag not followed by >"),g.state=w.ATTRIB);continue;case w.ATTRIB:if(x(E))continue;E===">"?xn(g):E==="/"?g.state=w.OPEN_TAG_SLASH:j(h,E)?(g.attribName=E,g.attribValue="",g.state=w.ATTRIB_NAME):Me(g,"Invalid attribute name");continue;case w.ATTRIB_NAME:E==="="?g.state=w.ATTRIB_VALUE:E===">"?(Me(g,"Attribute without value"),g.attribValue=g.attribName,To(g),xn(g)):x(E)?g.state=w.ATTRIB_NAME_SAW_WHITE:j(b,E)?g.attribName+=E:Me(g,"Invalid attribute name");continue;case w.ATTRIB_NAME_SAW_WHITE:if(E==="=")g.state=w.ATTRIB_VALUE;else{if(x(E))continue;Me(g,"Attribute without value"),g.tag.attributes[g.attribName]="",g.attribValue="",V(g,"onattribute",{name:g.attribName,value:""}),g.attribName="",E===">"?xn(g):j(h,E)?(g.attribName=E,g.state=w.ATTRIB_NAME):(Me(g,"Invalid attribute name"),g.state=w.ATTRIB)}continue;case w.ATTRIB_VALUE:if(x(E))continue;I(E)?(g.q=E,g.state=w.ATTRIB_VALUE_QUOTED):(Me(g,"Unquoted attribute value"),g.state=w.ATTRIB_VALUE_UNQUOTED,g.attribValue=E);continue;case w.ATTRIB_VALUE_QUOTED:if(E!==g.q){E==="&"?g.state=w.ATTRIB_VALUE_ENTITY_Q:g.attribValue+=E;continue}To(g),g.q="",g.state=w.ATTRIB_VALUE_CLOSED;continue;case w.ATTRIB_VALUE_CLOSED:x(E)?g.state=w.ATTRIB:E===">"?xn(g):E==="/"?g.state=w.OPEN_TAG_SLASH:j(h,E)?(Me(g,"No whitespace between attributes"),g.attribName=E,g.attribValue="",g.state=w.ATTRIB_NAME):Me(g,"Invalid attribute name");continue;case w.ATTRIB_VALUE_UNQUOTED:if(!A(E)){E==="&"?g.state=w.ATTRIB_VALUE_ENTITY_U:g.attribValue+=E;continue}To(g),E===">"?xn(g):g.state=w.ATTRIB;continue;case w.CLOSE_TAG:if(g.tagName)E===">"?Ci(g):j(b,E)?g.tagName+=E:g.script?(g.script+="</"+g.tagName,g.tagName="",g.state=w.SCRIPT):(x(E)||Me(g,"Invalid tagname in closing tag"),g.state=w.CLOSE_TAG_SAW_WHITE);else{if(x(E))continue;O(h,E)?g.script?(g.script+="</"+E,g.state=w.SCRIPT):Me(g,"Invalid tagname in closing tag."):g.tagName=E}continue;case w.CLOSE_TAG_SAW_WHITE:if(x(E))continue;E===">"?Ci(g):Me(g,"Invalid characters in closing tag");continue;case w.TEXT_ENTITY:case w.ATTRIB_VALUE_ENTITY_Q:case w.ATTRIB_VALUE_ENTITY_U:var tt,St;switch(g.state){case w.TEXT_ENTITY:tt=w.TEXT,St="textNode";break;case w.ATTRIB_VALUE_ENTITY_Q:tt=w.ATTRIB_VALUE_QUOTED,St="attribValue";break;case w.ATTRIB_VALUE_ENTITY_U:tt=w.ATTRIB_VALUE_UNQUOTED,St="attribValue";break}if(E===";")if(g.opt.unparsedEntities){var Bt=nl(g);g.entity="",g.state=tt,g.write(Bt)}else g[St]+=nl(g),g.entity="",g.state=tt;else j(g.entity.length?y:_,E)?g.entity+=E:(Me(g,"Invalid character in entity name"),g[St]+="&"+g.entity+E,g.entity="",g.state=tt);continue;default:throw new Error(g,"Unknown state: "+g.state)}return g.position>=g.bufferCheckPosition&&n(g),g}return String.fromCodePoint||(function(){var v=String.fromCharCode,g=Math.floor,R=function(){var E=16384,je=[],qe,tt,St=-1,Bt=arguments.length;if(!Bt)return"";for(var Sn="";++St<Bt;){var mt=Number(arguments[St]);if(!isFinite(mt)||mt<0||mt>1114111||g(mt)!==mt)throw RangeError("Invalid code point: "+mt);mt<=65535?je.push(mt):(mt-=65536,qe=(mt>>10)+55296,tt=mt%1024+56320,je.push(qe,tt)),(St+1===Bt||je.length>E)&&(Sn+=v.apply(null,je),je.length=0)}return Sn};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:R,configurable:!0,writable:!0}):String.fromCodePoint=R})(),e},oR=i9();var Ch=`The output should be formatted as a XML file.
159
- 1. Output should conform to the tags below.
160
- 2. If tags are not given, make them on your own.
161
- 3. Remember to always open and close all the tags.
162
-
163
- As an example, for the tags ["foo", "bar", "baz"]:
164
- 1. String "<foo>
165
- <bar>
166
- <baz></baz>
167
- </bar>
168
- </foo>" is a well-formatted instance of the schema.
169
- 2. String "<foo>
170
- <bar>
171
- </foo>" is a badly-formatted instance.
172
- 3. String "<foo>
173
- <tag>
174
- </tag>
175
- </foo>" is a badly-formatted instance.
176
-
177
- Here are the output tags:
178
- \`\`\`
179
- {tags}
180
- \`\`\``,aR=class extends gi{tags;constructor(e){super(e),this.tags=e?.tags}static lc_name(){return"XMLOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_diff(e,t){if(t)return e?Bs(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Ph(e[0].text)}async parse(e){return Ph(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?Ch.replace("{tags}",this.tags?.join(", ")??""):Ch}},s9=e=>e.split(`
181
- `).map(t=>t.replace(/^\s+/,"")).join(`
182
- `).trim(),cR=e=>{if(Object.keys(e).length===0)return{};let t={};return e.children.length>0?(t[e.name]=e.children.map(cR),t):(t[e.name]=e.text??void 0,t)};function Ph(e){let t=s9(e),r=oR.parser(!0),n={},i=[];r.onopentag=a=>{let c={name:a.name,attributes:a.attributes,children:[],text:"",isSelfClosing:a.isSelfClosing};i.length>0?i[i.length-1].children.push(c):n=c,a.isSelfClosing||i.push(c)},r.onclosetag=()=>{if(i.length>0){let a=i.pop();i.length===0&&a&&(n=a)}},r.ontext=a=>{if(i.length>0){let c=i[i.length-1];c.text+=a}},r.onattribute=a=>{if(i.length>0){let c=i[i.length-1];c.attributes[a.name]=a.value}};let s=/```(xml)?(.*)```/s.exec(t),o=s?s[2]:t;return r.write(o).close(),n&&n.name==="?xml"&&(n=n.children[0]),cR(n)}var z0={};M(z0,{AsymmetricStructuredOutputParser:()=>sR,BaseCumulativeTransformOutputParser:()=>gi,BaseLLMOutputParser:()=>Zc,BaseOutputParser:()=>ts,BaseTransformOutputParser:()=>rs,BytesOutputParser:()=>QN,CommaSeparatedListOutputParser:()=>eR,CustomListOutputParser:()=>tR,JsonMarkdownStructuredOutputParser:()=>D0,JsonOutputParser:()=>$p,ListOutputParser:()=>Gc,MarkdownListOutputParser:()=>nR,NumberedListOutputParser:()=>rR,OutputParserException:()=>Hr,StringOutputParser:()=>iR,StructuredOutputParser:()=>Kc,XMLOutputParser:()=>aR,XML_FORMAT_INSTRUCTIONS:()=>Ch,parseJsonMarkdown:()=>Al,parsePartialJson:()=>ii,parseXMLMarkdown:()=>Ph});var L0=class extends Zc{static lc_name(){return"OutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;argsOnly=!0;constructor(e){super(),this.argsOnly=e?.argsOnly??this.argsOnly}async parseResult(e){if("message"in e[0]){let r=e[0].message.additional_kwargs.function_call;if(!r)throw new Error(`No function_call in message ${JSON.stringify(e)}`);if(!r.arguments)throw new Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?r.arguments:JSON.stringify(r)}else throw new Error(`No message in generations ${JSON.stringify(e)}`)}},U0=class extends gi{static lc_name(){return"JsonOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser;argsOnly=!0;constructor(e){super(e),this.argsOnly=e?.argsOnly??this.argsOnly,this.outputParser=new L0(e)}_diff(e,t){return t?Bs(e??{},t):void 0}async parsePartialResult(e){let t=e[0];if(!t.message)return;let{message:r}=t,n=r.additional_kwargs.function_call;if(n)return this.argsOnly?ii(n.arguments):{...n,arguments:ii(n.arguments)}}async parseResult(e){let t=await this.outputParser.parseResult(e);if(!t)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){let t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return""}},uR=class extends Zc{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new U0;attrName;get lc_aliases(){return{attrName:"key_name"}}constructor(e){super(e),this.attrName=e.attrName}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}};var F0={};M(F0,{JsonKeyOutputFunctionsParser:()=>uR,JsonOutputFunctionsParser:()=>U0,OutputFunctionsParser:()=>L0});function ba(e,t){if(e.function===void 0)return;let r;if(t?.partial)try{r=ii(e.function.arguments??"{}")}catch{return}else try{r=JSON.parse(e.function.arguments)}catch(i){throw new Hr([`Function "${e.function.name}" arguments:`,"",e.function.arguments,"","are not valid JSON.",`Error: ${i.message}`].join(`
183
- `))}let n={name:e.function.name,args:r,type:"tool_call"};return t?.returnId&&(n.id=e.id),n}function Nh(e){if(e.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}}function to(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:"invalid_tool_call"}}var B0=class extends gi{static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(e){super(e),this.returnId=e?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){let r=e[0].message,n;if(si(r)&&r.tool_calls?.length?n=r.tool_calls.map(s=>{let{id:o,...a}=s;return this.returnId?{id:o,...a}:a}):r.additional_kwargs.tool_calls!==void 0&&(n=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(o=>ba(o,{returnId:this.returnId,partial:t}))),!n)return[];let i=[];for(let s of n)if(s!==void 0){let o={type:s.name,args:s.args,id:s.id};i.push(o)}return i}},Cp=class extends B0{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;let t=await Jm(this.zodSchema,e);if(t.success)return t.data;throw new Hr(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let r=(await super.parsePartialResult(e)).filter(i=>i.type===this.keyName),n=r;if(r.length)return this.returnId||(n=r.map(i=>i.args)),this.returnSingle?n[0]:n}async parseResult(e){let r=(await super.parsePartialResult(e,!1)).filter(s=>s.type===this.keyName),n=r;return r.length?(this.returnId||(n=r.map(s=>s.args)),this.returnSingle?this._validateResult(n[0]):await Promise.all(n.map(s=>this._validateResult(s)))):void 0}};var V0={};M(V0,{JsonOutputKeyToolsParser:()=>Cp,JsonOutputToolsParser:()=>B0,convertLangChainToolCallToOpenAI:()=>Nh,makeInvalidToolCall:()=>to,parseToolCall:()=>ba});var _i=class extends ue{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(e){super(e);let{inputVariables:t}=e;if(t.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},r={};for(let[i,s]of Object.entries(t))typeof s=="string"?r[i]=s:r[i]=await s();return{...r,...e}}async invoke(e,t){let r={...this.metadata,...t?.metadata},n=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(i=>this.formatPromptValue(i),e,{...t,tags:n,metadata:r,runType:"prompt"})}};var ns=class extends _i{async formatPromptValue(e){let t=await this.format(e);return new Ip(t)}};var o9=Object.prototype.toString,Hc=Array.isArray||function(t){return o9.call(t)==="[object Array]"};function G0(e){return typeof e=="function"}function a9(e){return Hc(e)?"array":typeof e}function Z0(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function lR(e,t){return e!=null&&typeof e=="object"&&t in e}function c9(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var u9=RegExp.prototype.test;function l9(e,t){return u9.call(e,t)}var p9=/\S/;function d9(e){return!l9(p9,e)}var f9={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function m9(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return f9[r]})}var h9=/\s*/,g9=/\s+/,pR=/\s*=/,_9=/\s*\}/,y9=/#|\^|\/|>|\{|&|=|!/;function v9(e,t){if(!e)return[];var r=!1,n=[],i=[],s=[],o=!1,a=!1,c="",u=0;function l(){if(o&&!a)for(;s.length;)delete i[s.pop()];else s=[];o=!1,a=!1}var p,f,d;function m(w){if(typeof w=="string"&&(w=w.split(g9,2)),!Hc(w)||w.length!==2)throw new Error("Invalid tags: "+w);p=new RegExp(Z0(w[0])+"\\s*"),f=new RegExp("\\s*"+Z0(w[1])),d=new RegExp("\\s*"+Z0("}"+w[1]))}m(t||vn.tags);for(var h=new Np(e),b,_,y,x,I,A;!h.eos();){if(b=h.pos,y=h.scanUntil(p),y)for(var j=0,O=y.length;j<O;++j)x=y.charAt(j),d9(x)?(s.push(i.length),c+=x):(a=!0,r=!0,c+=" "),i.push(["text",x,b,b+1]),b+=1,x===`
184
- `&&(l(),c="",u=0,r=!1);if(!h.scan(p))break;if(o=!0,_=h.scan(y9)||"name",h.scan(h9),_==="="?(y=h.scanUntil(pR),h.scan(pR),h.scanUntil(f)):_==="{"?(y=h.scanUntil(d),h.scan(_9),h.scanUntil(f),_="&"):y=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(_==">"?I=[_,y,b,h.pos,c,u,r]:I=[_,y,b,h.pos],u++,i.push(I),_==="#"||_==="^")n.push(I);else if(_==="/"){if(A=n.pop(),!A)throw new Error('Unopened section "'+y+'" at '+b);if(A[1]!==y)throw new Error('Unclosed section "'+A[1]+'" at '+b)}else _==="name"||_==="{"||_==="&"?a=!0:_==="="&&m(y)}if(l(),A=n.pop(),A)throw new Error('Unclosed section "'+A[1]+'" at '+h.pos);return w9(b9(i))}function b9(e){for(var t=[],r,n,i=0,s=e.length;i<s;++i)r=e[i],r&&(r[0]==="text"&&n&&n[0]==="text"?(n[1]+=r[1],n[3]=r[3]):(t.push(r),n=r));return t}function w9(e){for(var t=[],r=t,n=[],i,s,o=0,a=e.length;o<a;++o)switch(i=e[o],i[0]){case"#":case"^":r.push(i),n.push(i),r=i[4]=[];break;case"/":s=n.pop(),s[5]=i[2],r=n.length>0?n[n.length-1][4]:t;break;default:r.push(i)}return t}function Np(e){this.string=e,this.tail=e,this.pos=0}Np.prototype.eos=function(){return this.tail===""};Np.prototype.scan=function(t){var r=this.tail.match(t);if(!r||r.index!==0)return"";var n=r[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};Np.prototype.scanUntil=function(t){var r=this.tail.search(t),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};function qc(e,t){this.view=e,this.cache={".":this.view},this.parent=t}qc.prototype.push=function(t){return new qc(t,this)};qc.prototype.lookup=function(t){var r=this.cache,n;if(r.hasOwnProperty(t))n=r[t];else{for(var i=this,s,o,a,c=!1;i;){if(t.indexOf(".")>0)for(s=i.view,o=t.split("."),a=0;s!=null&&a<o.length;)a===o.length-1&&(c=lR(s,o[a])||c9(s,o[a])),s=s[o[a++]];else s=i.view[t],c=lR(i.view,t);if(c){n=s;break}i=i.parent}r[t]=n}return G0(n)&&(n=n.call(this.view)),n};function wr(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}wr.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};wr.prototype.parse=function(t,r){var n=this.templateCache,i=t+":"+(r||vn.tags).join(":"),s=typeof n<"u",o=s?n.get(i):void 0;return o==null&&(o=v9(t,r),s&&n.set(i,o)),o};wr.prototype.render=function(t,r,n,i){var s=this.getConfigTags(i),o=this.parse(t,s),a=r instanceof qc?r:new qc(r,void 0);return this.renderTokens(o,a,n,t,i)};wr.prototype.renderTokens=function(t,r,n,i,s){for(var o="",a,c,u,l=0,p=t.length;l<p;++l)u=void 0,a=t[l],c=a[0],c==="#"?u=this.renderSection(a,r,n,i,s):c==="^"?u=this.renderInverted(a,r,n,i,s):c===">"?u=this.renderPartial(a,r,n,s):c==="&"?u=this.unescapedValue(a,r):c==="name"?u=this.escapedValue(a,r,s):c==="text"&&(u=this.rawValue(a)),u!==void 0&&(o+=u);return o};wr.prototype.renderSection=function(t,r,n,i,s){var o=this,a="",c=r.lookup(t[1]);function u(f){return o.render(f,r,n,s)}if(c){if(Hc(c))for(var l=0,p=c.length;l<p;++l)a+=this.renderTokens(t[4],r.push(c[l]),n,i,s);else if(typeof c=="object"||typeof c=="string"||typeof c=="number")a+=this.renderTokens(t[4],r.push(c),n,i,s);else if(G0(c)){if(typeof i!="string")throw new Error("Cannot use higher-order sections without the original template");c=c.call(r.view,i.slice(t[3],t[5]),u),c!=null&&(a+=c)}else a+=this.renderTokens(t[4],r,n,i,s);return a}};wr.prototype.renderInverted=function(t,r,n,i,s){var o=r.lookup(t[1]);if(!o||Hc(o)&&o.length===0)return this.renderTokens(t[4],r,n,i,s)};wr.prototype.indentPartial=function(t,r,n){for(var i=r.replace(/[^ \t]/g,""),s=t.split(`
185
- `),o=0;o<s.length;o++)s[o].length&&(o>0||!n)&&(s[o]=i+s[o]);return s.join(`
186
- `)};wr.prototype.renderPartial=function(t,r,n,i){if(n){var s=this.getConfigTags(i),o=G0(n)?n(t[1]):n[t[1]];if(o!=null){var a=t[6],c=t[5],u=t[4],l=o;c==0&&u&&(l=this.indentPartial(o,u,a));var p=this.parse(l,s);return this.renderTokens(p,r,n,l,i)}}};wr.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};wr.prototype.escapedValue=function(t,r,n){var i=this.getConfigEscape(n)||vn.escape,s=r.lookup(t[1]);if(s!=null)return typeof s=="number"&&i===vn.escape?String(s):i(s)};wr.prototype.rawValue=function(t){return t[1]};wr.prototype.getConfigTags=function(t){return Hc(t)?t:t&&typeof t=="object"?t.tags:void 0};wr.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!Hc(t))return t.escape};var vn={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){Pp.templateCache=e},get templateCache(){return Pp.templateCache}},Pp=new wr;vn.clearCache=function(){return Pp.clearCache()};vn.parse=function(t,r){return Pp.parse(t,r)};vn.render=function(t,r,n,i){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+a9(t)+'" was given as the first argument for mustache#render(template, view, partials)');return Pp.render(t,r,n,i)};vn.escape=m9;vn.Scanner=Np;vn.Context=qc;vn.Writer=wr;var Rh=vn;function dR(){Rh.escape=e=>e}var wa=e=>{let t=e.split(""),r=[],n=(s,o)=>{for(let a=o;a<t.length;a+=1)if(s.includes(t[a]))return a;return-1},i=0;for(;i<t.length;)if(t[i]==="{"&&i+1<t.length&&t[i+1]==="{")r.push({type:"literal",text:"{"}),i+=2;else if(t[i]==="}"&&i+1<t.length&&t[i+1]==="}")r.push({type:"literal",text:"}"}),i+=2;else if(t[i]==="{"){let s=n("}",i);if(s<0)throw new Error("Unclosed '{' in template.");r.push({type:"variable",name:t.slice(i+1,s).join("")}),i=s+1}else{if(t[i]==="}")throw new Error("Single '}' in template.");{let s=n("{}",i),o=(s<0?t.slice(i):t.slice(i,s)).join("");r.push({type:"literal",text:o}),i=s<0?t.length:s}}return r},fR=(e,t=[])=>{let r=[];for(let n of e)if(n[0]==="name"){let i=n[1].includes(".")?n[1].split(".")[0]:n[1];r.push({type:"variable",name:i})}else if(["#","&","^",">"].includes(n[0])){if(r.push({type:"variable",name:n[1]}),n[0]==="#"&&n.length>4&&Array.isArray(n[4])){let i=[...t,n[1]],s=fR(n[4],i);r.push(...s)}}else r.push({type:"literal",text:n[1]});return r},Wc=e=>{dR();let t=Rh.parse(e);return fR(t)},K0=(e,t)=>wa(e).reduce((r,n)=>{if(n.type==="variable"){if(n.name in t){let i=typeof t[n.name]=="string"?t[n.name]:JSON.stringify(t[n.name]);return r+i}throw new Error(`(f-string) Missing value for input ${n.name}`)}return r+n.text},""),q0=(e,t)=>(dR(),Rh.render(e,t)),Rp={"f-string":K0,mustache:q0},H0={"f-string":wa,mustache:Wc},rr=(e,t,r)=>{try{return Rp[t](e,r)}catch(n){throw Ms(n,"INVALID_PROMPT_INPUT")}},xa=(e,t)=>H0[t](e),is=(e,t,r)=>{if(!(t in Rp)){let n=Object.keys(Rp);throw new Error(`Invalid template format. Got \`${t}\`;
187
- should be one of ${n}`)}try{let n=Object.fromEntries(r.map(i=>[i,"foo"]));Array.isArray(e)?e.forEach(i=>{if(i.type==="text"&&"text"in i&&typeof i.text=="string")rr(i.text,t,n);else if(i.type==="image_url"){if(typeof i.image_url=="string")rr(i.image_url,t,n);else if(typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url&&typeof i.image_url.url=="string"){let s=i.image_url.url;rr(s,t,n)}}else throw new Error(`Invalid message template received. ${JSON.stringify(i,null,2)}`)}):rr(e,t,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}};var jn=class Mp extends ns{static lc_name(){return"PromptTemplate"}template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(t){if(super(t),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),is(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(t){let r=await this.mergePartialAndUserVariables(t);return rr(this.template,this.templateFormat,r)}static fromExamples(t,r,n,i=`
188
-
189
- `,s=""){let o=[s,...t,r].join(i);return new Mp({inputVariables:n,template:o})}static fromTemplate(t,r){let{templateFormat:n="f-string",...i}=r??{},s=new Set;return xa(t,n).forEach(o=>{o.type==="variable"&&s.add(o.name)}),new Mp({inputVariables:[...s],templateFormat:n,template:t,...i})}async partial(t){let r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new Mp(i)}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(t){if(!t.template)throw new Error("Prompt template must have a template");return new Mp({inputVariables:t.input_variables,template:t.template,templateFormat:t.template_format})}};var Jc=class mR extends _i{static lc_name(){return"ImagePromptTemplate"}lc_namespace=["langchain_core","prompts","image"];template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(t){if(super(t),this.template=t.template,this.templateFormat=t.templateFormat??this.templateFormat,this.validateTemplate=t.validateTemplate??this.validateTemplate,this.additionalContentFields=t.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),is([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}_getPromptType(){return"prompt"}async partial(t){let r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new mR(i)}async format(t){let r={};for(let[o,a]of Object.entries(this.template))typeof a=="string"?r[o]=rr(a,this.templateFormat,t):r[o]=a;let n=t.url||r.url,i=t.detail||r.detail;if(!n)throw new Error("Must provide either an image URL.");if(typeof n!="string")throw new Error("url must be a string.");let s={url:n};return i&&(s.detail=i),s}async formatPromptValue(t){let r=await this.format(t);return new s0(r)}};var jp=class extends ue{lc_namespace=["langchain_core","prompts","dict"];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return"DictPromptTemplate"}constructor(e){let t=e.templateFormat??"f-string",r=W0(e.template,t);super({inputVariables:r,...e}),this.template=e.template,this.templateFormat=t,this.inputVariables=r}async format(e){return J0(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}};function W0(e,t){let r=[];for(let n of Object.values(e))if(typeof n=="string")xa(n,t).forEach(i=>{i.type==="variable"&&r.push(i.name)});else if(Array.isArray(n))for(let i of n)typeof i=="string"?xa(i,t).forEach(s=>{s.type==="variable"&&r.push(s.name)}):typeof i=="object"&&r.push(...W0(i,t));else typeof n=="object"&&n!==null&&r.push(...W0(n,t));return Array.from(new Set(r))}function J0(e,t,r){let n={};for(let[i,s]of Object.entries(e))if(typeof s=="string")n[i]=rr(s,r,t);else if(Array.isArray(s)){let o=[];for(let a of s)typeof a=="string"?o.push(rr(a,r,t)):typeof a=="object"&&o.push(J0(a,t,r));n[i]=o}else typeof s=="object"&&s!==null?n[i]=J0(s,t,r):n[i]=s;return n}var Dp=class extends ue{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(e,t){return this._callWithConfig(r=>this.formatMessages(r),e,{...t,runType:"prompt"})}},jh=class extends Dp{static lc_name(){return"MessagesPlaceholder"}variableName;optional;constructor(e){typeof e=="string"&&(e={variableName:e}),super(e),this.variableName=e.variableName,this.optional=e.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(e){let t=e[this.variableName];if(this.optional&&!t)return[];if(!t){let n=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw n.name="InputFormatError",n}let r;try{Array.isArray(t)?r=t.map(Qt):r=[Qt(t)]}catch(n){let i=typeof t=="string"?t:JSON.stringify(t,null,2),s=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${i}`,`Additional message: ${n.message}`].join(`
190
-
191
- `));throw s.name="InputFormatError",s.lc_error_code=n.lc_error_code,s}return r}},X0=class extends Dp{prompt;constructor(e){"prompt"in e||(e={prompt:e}),super(e),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},zp=class extends _i{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){let t=await this.formatMessages(e);return new Sp(t)}},Y0=class extends X0{static lc_name(){return"ChatMessagePromptTemplate"}role;constructor(e,t){"prompt"in e||(e={prompt:e,role:t}),super(e),this.role=e.role}async format(e){return new mr(await this.prompt.format(e),this.role)}static fromTemplate(e,t,r){return new this(jn.fromTemplate(e,{templateFormat:r?.templateFormat}),t)}};function x9(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.keys(e).length===1&&"text"in e&&typeof e.text=="string"}function I9(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:"image_url"in e&&(typeof e.image_url=="string"||typeof e.image_url=="object"&&e.image_url!==null&&"url"in e.image_url&&typeof e.image_url.url=="string")}var Q0=class extends Dp{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}chatMessageClass;constructor(e,t){if("prompt"in e||(e={prompt:e}),super(e),this.prompt=e.prompt,Array.isArray(this.prompt)){let r=[];this.prompt.forEach(n=>{"inputVariables"in n&&(r=r.concat(n.inputVariables))}),this.inputVariables=r}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=t??this.additionalOptions}createMessage(e){let t=this.constructor;if(t._messageClass()){let r=t._messageClass();return new r({content:e})}else if(t.chatMessageClass){let r=t.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,t){if(typeof e=="string")return new this(jn.fromTemplate(e,t));let r=[];for(let n of e)if(typeof n=="string")r.push(jn.fromTemplate(n,t));else if(n!==null)if(x9(n)){let i="";typeof n.text=="string"&&(i=n.text??"");let s={...t,additionalContentFields:n};r.push(jn.fromTemplate(i,s))}else if(I9(n)){let i=n.image_url??"",s,o=[];if(typeof i=="string"){let a;t?.templateFormat==="mustache"?a=Wc(i):a=wa(i);let c=a.flatMap(u=>u.type==="variable"?[u.name]:[]);if((c?.length??0)>0){if(c.length>1)throw new Error(`Only one format variable allowed per image template.
192
- Got: ${c}
193
- From: ${i}`);o=[c[0]]}else o=[];i={url:i},s=new Jc({template:i,inputVariables:o,templateFormat:t?.templateFormat,additionalContentFields:n})}else if(typeof i=="object"){if("url"in i){let a;t?.templateFormat==="mustache"?a=Wc(i.url):a=wa(i.url),o=a.flatMap(c=>c.type==="variable"?[c.name]:[])}else o=[];s=new Jc({template:i,inputVariables:o,templateFormat:t?.templateFormat,additionalContentFields:n})}else throw new Error("Invalid image template");r.push(s)}else typeof n=="object"&&r.push(new jp({template:n,templateFormat:t?.templateFormat}));return new this({prompt:r,additionalOptions:t})}async format(e){if(this.prompt instanceof ns){let t=await this.prompt.format(e);return this.createMessage(t)}else{let t=[];for(let r of this.prompt){let n={};if(!("inputVariables"in r))throw new Error(`Prompt ${r} does not have inputVariables defined.`);for(let i of r.inputVariables)n||(n={[i]:e[i]}),n={...n,[i]:e[i]};if(r instanceof ns){let i=await r.format(n),s;"additionalContentFields"in r&&(s=r.additionalContentFields),i!==""&&t.push({...s,type:"text",text:i})}else if(r instanceof Jc){let i=await r.format(n),s;"additionalContentFields"in r&&(s=r.additionalContentFields),t.push({...s,type:"image_url",image_url:i})}else if(r instanceof jp){let i=await r.format(n),s;"additionalContentFields"in r&&(s=r.additionalContentFields),t.push({...s,...i})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}},Dh=class extends Q0{static _messageClass(){return at}static lc_name(){return"HumanMessagePromptTemplate"}},eI=class extends Q0{static _messageClass(){return $e}static lc_name(){return"AIMessagePromptTemplate"}},Lp=class extends Q0{static _messageClass(){return Br}static lc_name(){return"SystemMessagePromptTemplate"}};function S9(e){return typeof e.formatMessages=="function"}function E9(e,t){if(S9(e)||ot(e))return e;if(Array.isArray(e)&&e[0]==="placeholder"){let i=e[1];if(t?.templateFormat==="mustache"&&typeof i=="string"&&i.slice(0,2)==="{{"&&i.slice(-2)==="}}"){let s=i.slice(2,-2);return new jh({variableName:s,optional:!0})}else if(typeof i=="string"&&i[0]==="{"&&i[i.length-1]==="}"){let s=i.slice(1,-1);return new jh({variableName:s,optional:!0})}throw new Error(`Invalid placeholder template for format ${t?.templateFormat??'"f-string"'}: "${e[1]}". Expected a variable name surrounded by ${t?.templateFormat==="mustache"?"double":"single"} curly braces.`)}let r=Qt(e),n;if(typeof r.content=="string"?n=r.content:n=r.content.map(i=>"text"in i?{...i,text:i.text}:"image_url"in i?{...i,image_url:i.image_url}:i),r._getType()==="human")return Dh.fromTemplate(n,t);if(r._getType()==="ai")return eI.fromTemplate(n,t);if(r._getType()==="system")return Lp.fromTemplate(n,t);if(mr.isInstance(r))return Y0.fromTemplate(r.content,r.role,t);throw new Error(`Could not coerce message prompt template from input. Received message type: "${r._getType()}".`)}function k9(e){return e.constructor.lc_name()==="MessagesPlaceholder"}var ro=class Mh extends zp{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}promptMessages;validateTemplate=!0;templateFormat="f-string";constructor(t){if(super(t),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){let r=new Set;for(let a of this.promptMessages)if(!(a instanceof bt))for(let c of a.inputVariables)r.add(c);let n=this.inputVariables,i=new Set(this.partialVariables?n.concat(Object.keys(this.partialVariables)):n),s=new Set([...i].filter(a=>!r.has(a)));if(s.size>0)throw new Error(`Input variables \`${[...s]}\` are not used in any of the prompt messages.`);let o=new Set([...r].filter(a=>!i.has(a)));if(o.size>0)throw new Error(`Input variables \`${[...o]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(t,r){if(typeof t.content=="string")return t;let n=await Promise.all(t.content.map(async i=>{if(i.type!=="image_url")return i;let s="";typeof i.image_url=="string"?s=i.image_url:typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url&&typeof i.image_url.url=="string"&&(s=i.image_url.url);let a=await jn.fromTemplate(s,{templateFormat:this.templateFormat}).format(r);return typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url?i.image_url.url=a:i.image_url=a,i}));return t.content=n,t}async formatMessages(t){let r=await this.mergePartialAndUserVariables(t),n=[];for(let i of this.promptMessages)if(i instanceof bt)n.push(await this._parseImagePrompts(i,r));else{let s;this.templateFormat==="mustache"?s={...r}:s=i.inputVariables.reduce((a,c)=>{if(!(c in r)&&!(k9(i)&&i.optional))throw Ms(new Error(`Missing value for input variable \`${c.toString()}\``),"INVALID_PROMPT_INPUT");return a[c]=r[c],a},{});let o=await i.formatMessages(s);n=n.concat(o)}return n}async partial(t){let r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new Mh(i)}static fromTemplate(t,r){let n=jn.fromTemplate(t,r),i=new Dh({prompt:n});return this.fromMessages([i])}static fromMessages(t,r){let n=t.reduce((o,a)=>o.concat(a instanceof Mh?a.promptMessages:[E9(a,r)]),[]),i=t.reduce((o,a)=>a instanceof Mh?Object.assign(o,a.partialVariables):o,Object.create(null)),s=new Set;for(let o of n)if(!(o instanceof bt))for(let a of o.inputVariables)a in i||s.add(a);return new this({...r,inputVariables:[...s],promptMessages:n,partialVariables:i,templateFormat:r?.templateFormat})}};var hR=class tI extends ns{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
194
-
195
- `;prefix="";templateFormat="f-string";validateTemplate=!0;constructor(t){if(super(t),Object.assign(this,t),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),is(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(t){let r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new tI(i)}async format(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r),i=await Promise.all(n.map(o=>this.examplePrompt.format(o))),s=[this.prefix,...i,this.suffix].join(this.exampleSeparator);return rr(s,this.templateFormat,r)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(t){let{example_prompt:r}=t;if(!r)throw new Error("Missing example prompt");let n=await jn.deserialize(r),i;if(Array.isArray(t.examples))i=t.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new tI({inputVariables:t.input_variables,examplePrompt:n,examples:i,exampleSeparator:t.example_separator,prefix:t.prefix,suffix:t.suffix,templateFormat:t.template_format})}},gR=class _R extends zp{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
196
-
197
- `;prefix="";templateFormat="f-string";validateTemplate=!0;_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(t){if(super(t),this.examples=t.examples,this.examplePrompt=t.examplePrompt,this.exampleSeparator=t.exampleSeparator??`
198
-
199
- `,this.exampleSelector=t.exampleSelector,this.prefix=t.prefix??"",this.suffix=t.suffix??"",this.templateFormat=t.templateFormat??"f-string",this.validateTemplate=t.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),is(this.prefix+this.suffix,this.templateFormat,r)}}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r);n=n.map(s=>{let o={};return this.examplePrompt.inputVariables.forEach(a=>{o[a]=s[a]}),o});let i=[];for(let s of n){let o=await this.examplePrompt.formatMessages(s);i.push(...o)}return i}async format(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r),s=(await Promise.all(n.map(a=>this.examplePrompt.formatMessages(a)))).flat().map(a=>a.content),o=[this.prefix,...s,this.suffix].join(this.exampleSeparator);return rr(o,this.templateFormat,r)}async partial(t){let r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new _R(i)}};var yR=class zh extends _i{static lc_name(){return"PipelinePromptTemplate"}pipelinePrompts;finalPrompt;constructor(t){super({...t,inputVariables:[]}),this.pipelinePrompts=t.pipelinePrompts,this.finalPrompt=t.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){let t=this.pipelinePrompts.map(n=>n.name),r=this.pipelinePrompts.map(n=>n.prompt.inputVariables.filter(i=>!t.includes(i))).flat();return[...new Set(r)]}static extractRequiredInputValues(t,r){return r.reduce((n,i)=>(n[i]=t[i],n),{})}async formatPipelinePrompts(t){let r=await this.mergePartialAndUserVariables(t);for(let{name:n,prompt:i}of this.pipelinePrompts){let s=zh.extractRequiredInputValues(r,i.inputVariables);i instanceof ro?r[n]=await i.formatMessages(s):r[n]=await i.format(s)}return zh.extractRequiredInputValues(r,this.finalPrompt.inputVariables)}async formatPromptValue(t){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(t))}async format(t){return this.finalPrompt.format(await this.formatPipelinePrompts(t))}async partial(t){let r={...this};return r.inputVariables=this.inputVariables.filter(n=>!(n in t)),r.partialVariables={...this.partialVariables??{},...t},new zh(r)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function vR(e){return typeof e=="object"&&e!=null&&"withStructuredOutput"in e&&typeof e.withStructuredOutput=="function"}function A9(e){return typeof e=="object"&&e!=null&&"lc_id"in e&&Array.isArray(e.lc_id)&&e.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var bR=class wR extends ro{schema;method;lc_namespace=["langchain_core","prompts","structured"];get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(t){super(t),this.schema=t.schema,this.method=t.method}pipe(t){if(vR(t))return super.pipe(t.withStructuredOutput(this.schema));if(A9(t)&&vR(t.bound))return super.pipe(new gn({bound:t.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:t.kwargs??{},config:t.config,configFactories:t.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(t,r,n){return wR.fromMessages(t,{schema:r,method:n})}};var rI={};M(rI,{AIMessagePromptTemplate:()=>eI,BaseChatPromptTemplate:()=>zp,BaseMessagePromptTemplate:()=>Dp,BaseMessageStringPromptTemplate:()=>X0,BasePromptTemplate:()=>_i,BaseStringPromptTemplate:()=>ns,ChatMessagePromptTemplate:()=>Y0,ChatPromptTemplate:()=>ro,DEFAULT_FORMATTER_MAPPING:()=>Rp,DEFAULT_PARSER_MAPPING:()=>H0,DictPromptTemplate:()=>jp,FewShotChatMessagePromptTemplate:()=>gR,FewShotPromptTemplate:()=>hR,HumanMessagePromptTemplate:()=>Dh,ImagePromptTemplate:()=>Jc,MessagesPlaceholder:()=>jh,PipelinePromptTemplate:()=>yR,PromptTemplate:()=>jn,StructuredPrompt:()=>bR,SystemMessagePromptTemplate:()=>Lp,checkValidTemplate:()=>is,interpolateFString:()=>K0,interpolateMustache:()=>q0,parseFString:()=>wa,parseMustache:()=>Wc,parseTemplate:()=>xa,renderTemplate:()=>rr});var nI={};M(nI,{BaseDocumentCompressor:()=>T9});var T9=class{static isBaseDocumentCompressor(e){return e?.compressDocuments!==void 0}};var Dn={and:"and",or:"or",not:"not"},Re={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"},Lh=class{},Uh=class{accept(e){if(this.exprName==="Operation")return e.visitOperation(this);if(this.exprName==="Comparison")return e.visitComparison(this);if(this.exprName==="StructuredQuery")return e.visitStructuredQuery(this);throw new Error("Unknown Expression type")}},Fh=class extends Uh{},xR=class extends Fh{exprName="Comparison";constructor(e,t,r){super(),this.comparator=e,this.attribute=t,this.value=r}},IR=class extends Fh{exprName="Operation";constructor(e,t){super(),this.operator=e,this.args=t}},SR=class extends Uh{exprName="StructuredQuery";constructor(e,t){super(),this.query=e,this.filter=t}};function iI(e){return e&&typeof e=="object"&&!Array.isArray(e)}function Mr(e){return e?typeof e=="string"&&e.length>0||typeof e=="function"?!1:iI(e)&&Object.keys(e).length===0:!0}function sI(e){if(typeof e=="number")return e%1===0;if(typeof e=="string"){let t=parseInt(e,10);return!Number.isNaN(t)&&t%1===0&&t.toString()===e}return!1}function oI(e){if(typeof e=="number")return e%1!==0;if(typeof e=="string"){let t=parseFloat(e);return!Number.isNaN(t)&&t%1!==0&&t.toString()===e}return!1}function aI(e){return typeof e=="string"&&(Number.isNaN(parseFloat(e))||parseFloat(e).toString()!==e)}function cI(e){return typeof e=="boolean"}function Xc(e){let t;if(aI(e))t=e;else if(sI(e))t=parseInt(e,10);else if(oI(e))t=parseFloat(e);else if(cI(e))t=!!e;else throw new Error("Unsupported value type");return t}var Up=class extends Lh{},ER=class extends Up{allowedOperators;allowedComparators;constructor(e){super(),this.allowedOperators=e?.allowedOperators??[Dn.and,Dn.or],this.allowedComparators=e?.allowedComparators??[Re.eq,Re.ne,Re.gt,Re.gte,Re.lt,Re.lte]}formatFunction(e){if(e in Re){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw new Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(e in Dn){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw new Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw new Error("Unknown comparator or operator");return`$${e}`}visitOperation(e){let t=e.args?.map(r=>r.accept(this));return{[this.formatFunction(e.operator)]:t}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:Xc(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,r="and",n=!1){if(!(Mr(e)&&Mr(t))){if(Mr(e)||r==="replace")return Mr(t)?void 0:t;if(Mr(t))return n?e:r==="and"?void 0:e;if(r==="and")return{$and:[e,t]};if(r==="or")return{$or:[e,t]};throw new Error("Unknown merge type")}}};var kR=class extends Up{allowedOperators=[Dn.and,Dn.or];allowedComparators=[Re.eq,Re.ne,Re.gt,Re.gte,Re.lt,Re.lte];formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(e){switch(e){case"string":return[Re.eq,Re.ne,Re.gt,Re.gte,Re.lt,Re.lte];case"number":return[Re.eq,Re.ne,Re.gt,Re.gte,Re.lt,Re.lte];case"boolean":return[Re.eq,Re.ne];default:throw new Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case Re.eq:return(t,r)=>t===r;case Re.ne:return(t,r)=>t!==r;case Re.gt:return(t,r)=>t>r;case Re.gte:return(t,r)=>t>=r;case Re.lt:return(t,r)=>t<r;case Re.lte:return(t,r)=>t<=r;default:throw new Error("Unknown comparator")}}getOperatorFunction(e){switch(e){case Dn.and:return(t,r)=>t&&r;case Dn.or:return(t,r)=>t||r;default:throw new Error("Unknown operator")}}visitOperation(e){let{operator:t,args:r}=e;if(this.allowedOperators.includes(t)){let n=this.getOperatorFunction(t);return i=>r?r.reduce((s,o)=>{let a=o.accept(this);if(typeof a=="function")return n(s,a(i));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(e){let{comparator:t,attribute:r,value:n}=e,i=[Re.ne];if(this.allowedComparators.includes(t)){if(!this.getAllowedComparatorsForType(typeof n).includes(t))throw new Error(`'${t}' comparator not allowed to be used with ${typeof n}`);let s=this.getComparatorFunction(t);return o=>{let a=o.metadata[r];return a===void 0?!!i.includes(t):s(a,Xc(n))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(e){if(!e.filter)return{};let t=e.filter?.accept(this);if(typeof t!="function")throw new Error("Structured query filter is not a function");return{filter:t}}mergeFilters(e,t,r="and"){if(!(Mr(e)&&Mr(t))){if(Mr(e)||r==="replace")return Mr(t)?void 0:t;if(Mr(t))return r==="and"?void 0:e;if(r==="and")return n=>e(n)&&t(n);if(r==="or")return n=>e(n)||t(n);throw new Error("Unknown merge type")}}};var uI={};M(uI,{BaseTranslator:()=>Up,BasicTranslator:()=>ER,Comparators:()=>Re,Comparison:()=>xR,Expression:()=>Uh,FilterDirective:()=>Fh,FunctionalTranslator:()=>kR,Operation:()=>IR,Operators:()=>Dn,StructuredQuery:()=>SR,Visitor:()=>Lh,castValue:()=>Xc,isBoolean:()=>cI,isFilterEmpty:()=>Mr,isFloat:()=>oI,isInt:()=>sI,isObject:()=>iI,isString:()=>aI});function Fp(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function Bp(e){return e!==void 0&&ue.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function Vp(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(_r(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function Ia(e){return Vp(e)||Bp(e)||Fp(e)}var Z={};$s(Z,{$brand:()=>Pv,$input:()=>Zw,$output:()=>Vw,NEVER:()=>Cv,TimePrecision:()=>qw,ZodAny:()=>jR,ZodArray:()=>UR,ZodBase64:()=>RI,ZodBase64URL:()=>MI,ZodBigInt:()=>Hp,ZodBigIntFormat:()=>zI,ZodBoolean:()=>qp,ZodCIDRv4:()=>PI,ZodCIDRv6:()=>NI,ZodCUID:()=>EI,ZodCUID2:()=>kI,ZodCatch:()=>s1,ZodCustom:()=>rg,ZodCustomStringFormat:()=>OR,ZodDate:()=>Qh,ZodDefault:()=>QR,ZodDiscriminatedUnion:()=>FR,ZodE164:()=>jI,ZodEmail:()=>wI,ZodEmoji:()=>II,ZodEnum:()=>Zp,ZodError:()=>$9,ZodFile:()=>XR,ZodGUID:()=>qh,ZodIPv4:()=>$I,ZodIPv6:()=>CI,ZodISODate:()=>Vh,ZodISODateTime:()=>Bh,ZodISODuration:()=>Gh,ZodISOTime:()=>Zh,ZodIntersection:()=>BR,ZodIssueCode:()=>R3,ZodJWT:()=>DI,ZodKSUID:()=>OI,ZodLazy:()=>p1,ZodLiteral:()=>WR,ZodMap:()=>KR,ZodNaN:()=>a1,ZodNanoID:()=>SI,ZodNever:()=>zR,ZodNonOptional:()=>GI,ZodNull:()=>RR,ZodNullable:()=>YR,ZodNumber:()=>Kp,ZodNumberFormat:()=>Qc,ZodObject:()=>eg,ZodOptional:()=>ZI,ZodPipe:()=>KI,ZodPrefault:()=>t1,ZodPromise:()=>f1,ZodReadonly:()=>c1,ZodRealError:()=>Yc,ZodRecord:()=>FI,ZodSet:()=>qR,ZodString:()=>Gp,ZodStringFormat:()=>Qe,ZodSuccess:()=>i1,ZodSymbol:()=>PR,ZodTemplateLiteral:()=>l1,ZodTransform:()=>BI,ZodTuple:()=>ZR,ZodType:()=>Pe,ZodULID:()=>AI,ZodURL:()=>xI,ZodUUID:()=>ss,ZodUndefined:()=>NR,ZodUnion:()=>UI,ZodUnknown:()=>DR,ZodVoid:()=>LR,ZodXID:()=>TI,_ZodString:()=>bI,_default:()=>e1,any:()=>l3,array:()=>LI,base64:()=>J9,base64url:()=>X9,bigint:()=>s3,boolean:()=>CR,catch:()=>o1,check:()=>m1,cidrv4:()=>H9,cidrv6:()=>W9,clone:()=>lt,coerce:()=>qI,config:()=>At,core:()=>Ji,cuid:()=>F9,cuid2:()=>B9,custom:()=>O3,date:()=>d3,discriminatedUnion:()=>_3,e164:()=>Y9,email:()=>P9,emoji:()=>L9,endsWith:()=>ap,enum:()=>HR,file:()=>I3,flattenError:()=>Zl,float32:()=>t3,float64:()=>r3,formatError:()=>Gl,function:()=>$x,getErrorMap:()=>j3,globalRegistry:()=>ct,gt:()=>Hi,gte:()=>Pr,guid:()=>N9,includes:()=>sp,instanceof:()=>$3,int:()=>vI,int32:()=>n3,int64:()=>o3,intersection:()=>VR,ipv4:()=>K9,ipv6:()=>q9,iso:()=>Kh,json:()=>P3,jwt:()=>Q9,keyof:()=>f3,ksuid:()=>G9,lazy:()=>d1,length:()=>Ac,literal:()=>JR,locales:()=>Yl,looseObject:()=>g3,lowercase:()=>np,lt:()=>qi,lte:()=>pn,map:()=>b3,maxLength:()=>kc,maxSize:()=>Ec,mime:()=>cp,minLength:()=>Ks,minSize:()=>Yo,multipleOf:()=>Xo,nan:()=>k3,nanoid:()=>U9,nativeEnum:()=>x3,negative:()=>bx,never:()=>Yh,nonnegative:()=>xx,nonoptional:()=>n1,nonpositive:()=>wx,normalize:()=>up,null:()=>MR,nullable:()=>Jh,nullish:()=>S3,number:()=>$R,object:()=>m3,optional:()=>Wh,overwrite:()=>Wi,parse:()=>mI,parseAsync:()=>hI,partialRecord:()=>v3,pipe:()=>Xh,positive:()=>vx,prefault:()=>r1,preprocess:()=>N3,prettifyError:()=>Gv,promise:()=>T3,property:()=>Ix,readonly:()=>u1,record:()=>GR,refine:()=>h1,regex:()=>rp,regexes:()=>Ho,registry:()=>km,safeParse:()=>gI,safeParseAsync:()=>_I,set:()=>w3,setErrorMap:()=>M3,size:()=>tp,startsWith:()=>op,strictObject:()=>h3,string:()=>yI,stringFormat:()=>e3,stringbool:()=>C3,success:()=>E3,superRefine:()=>g1,symbol:()=>c3,templateLiteral:()=>A3,toJSONSchema:()=>qs,toLowerCase:()=>pp,toUpperCase:()=>dp,transform:()=>VI,treeifyError:()=>Zv,trim:()=>lp,tuple:()=>y3,uint32:()=>i3,uint64:()=>a3,ulid:()=>V9,undefined:()=>u3,union:()=>tg,unknown:()=>Hh,uppercase:()=>ip,url:()=>z9,uuid:()=>R9,uuidv4:()=>M9,uuidv6:()=>j9,uuidv7:()=>D9,void:()=>p3,xid:()=>Z9});var Kh={};$s(Kh,{ZodISODate:()=>Vh,ZodISODateTime:()=>Bh,ZodISODuration:()=>Gh,ZodISOTime:()=>Zh,date:()=>pI,datetime:()=>lI,duration:()=>fI,time:()=>dI});var Bh=S("ZodISODateTime",(e,t)=>{ew.init(e,t),Qe.init(e,t)});function lI(e){return Hw(Bh,e)}var Vh=S("ZodISODate",(e,t)=>{tw.init(e,t),Qe.init(e,t)});function pI(e){return Ww(Vh,e)}var Zh=S("ZodISOTime",(e,t)=>{rw.init(e,t),Qe.init(e,t)});function dI(e){return Jw(Zh,e)}var Gh=S("ZodISODuration",(e,t)=>{nw.init(e,t),Qe.init(e,t)});function fI(e){return Xw(Gh,e)}var TR=(e,t)=>{Vl.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Gl(e,r)},flatten:{value:r=>Zl(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},$9=S("ZodError",TR),Yc=S("ZodError",TR,{Parent:Error});var mI=fm(Yc),hI=mm(Yc),gI=hm(Yc),_I=gm(Yc);var Pe=S("ZodType",(e,t)=>(ye.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>lt(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>mI(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>gI(e,r,n),e.parseAsync=async(r,n)=>hI(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>_I(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(h1(r,n)),e.superRefine=r=>e.check(g1(r)),e.overwrite=r=>e.check(Wi(r)),e.optional=()=>Wh(e),e.nullable=()=>Jh(e),e.nullish=()=>Wh(Jh(e)),e.nonoptional=r=>n1(e,r),e.array=()=>LI(e),e.or=r=>tg([e,r]),e.and=r=>VR(e,r),e.transform=r=>Xh(e,VI(r)),e.default=r=>e1(e,r),e.prefault=r=>r1(e,r),e.catch=r=>o1(e,r),e.pipe=r=>Xh(e,r),e.readonly=()=>u1(e),e.describe=r=>{let n=e.clone();return ct.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return ct.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return ct.get(e);let n=e.clone();return ct.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),bI=S("_ZodString",(e,t)=>{Wo.init(e,t),Pe.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(rp(...n)),e.includes=(...n)=>e.check(sp(...n)),e.startsWith=(...n)=>e.check(op(...n)),e.endsWith=(...n)=>e.check(ap(...n)),e.min=(...n)=>e.check(Ks(...n)),e.max=(...n)=>e.check(kc(...n)),e.length=(...n)=>e.check(Ac(...n)),e.nonempty=(...n)=>e.check(Ks(1,...n)),e.lowercase=n=>e.check(np(n)),e.uppercase=n=>e.check(ip(n)),e.trim=()=>e.check(lp()),e.normalize=(...n)=>e.check(up(...n)),e.toLowerCase=()=>e.check(pp()),e.toUpperCase=()=>e.check(dp())}),Gp=S("ZodString",(e,t)=>{Wo.init(e,t),bI.init(e,t),e.email=r=>e.check(Am(wI,r)),e.url=r=>e.check(Pm(xI,r)),e.jwt=r=>e.check(qm(DI,r)),e.emoji=r=>e.check(Nm(II,r)),e.guid=r=>e.check(Ql(qh,r)),e.uuid=r=>e.check(Tm(ss,r)),e.uuidv4=r=>e.check(Om(ss,r)),e.uuidv6=r=>e.check($m(ss,r)),e.uuidv7=r=>e.check(Cm(ss,r)),e.nanoid=r=>e.check(Rm(SI,r)),e.guid=r=>e.check(Ql(qh,r)),e.cuid=r=>e.check(Mm(EI,r)),e.cuid2=r=>e.check(jm(kI,r)),e.ulid=r=>e.check(Dm(AI,r)),e.base64=r=>e.check(Zm(RI,r)),e.base64url=r=>e.check(Gm(MI,r)),e.xid=r=>e.check(zm(TI,r)),e.ksuid=r=>e.check(Lm(OI,r)),e.ipv4=r=>e.check(Um($I,r)),e.ipv6=r=>e.check(Fm(CI,r)),e.cidrv4=r=>e.check(Bm(PI,r)),e.cidrv6=r=>e.check(Vm(NI,r)),e.e164=r=>e.check(Km(jI,r)),e.datetime=r=>e.check(lI(r)),e.date=r=>e.check(pI(r)),e.time=r=>e.check(dI(r)),e.duration=r=>e.check(fI(r))});function yI(e){return Gw(Gp,e)}var Qe=S("ZodStringFormat",(e,t)=>{He.init(e,t),bI.init(e,t)}),wI=S("ZodEmail",(e,t)=>{Gb.init(e,t),Qe.init(e,t)});function P9(e){return Am(wI,e)}var qh=S("ZodGUID",(e,t)=>{Vb.init(e,t),Qe.init(e,t)});function N9(e){return Ql(qh,e)}var ss=S("ZodUUID",(e,t)=>{Zb.init(e,t),Qe.init(e,t)});function R9(e){return Tm(ss,e)}function M9(e){return Om(ss,e)}function j9(e){return $m(ss,e)}function D9(e){return Cm(ss,e)}var xI=S("ZodURL",(e,t)=>{Kb.init(e,t),Qe.init(e,t)});function z9(e){return Pm(xI,e)}var II=S("ZodEmoji",(e,t)=>{qb.init(e,t),Qe.init(e,t)});function L9(e){return Nm(II,e)}var SI=S("ZodNanoID",(e,t)=>{Hb.init(e,t),Qe.init(e,t)});function U9(e){return Rm(SI,e)}var EI=S("ZodCUID",(e,t)=>{Wb.init(e,t),Qe.init(e,t)});function F9(e){return Mm(EI,e)}var kI=S("ZodCUID2",(e,t)=>{Jb.init(e,t),Qe.init(e,t)});function B9(e){return jm(kI,e)}var AI=S("ZodULID",(e,t)=>{Xb.init(e,t),Qe.init(e,t)});function V9(e){return Dm(AI,e)}var TI=S("ZodXID",(e,t)=>{Yb.init(e,t),Qe.init(e,t)});function Z9(e){return zm(TI,e)}var OI=S("ZodKSUID",(e,t)=>{Qb.init(e,t),Qe.init(e,t)});function G9(e){return Lm(OI,e)}var $I=S("ZodIPv4",(e,t)=>{iw.init(e,t),Qe.init(e,t)});function K9(e){return Um($I,e)}var CI=S("ZodIPv6",(e,t)=>{sw.init(e,t),Qe.init(e,t)});function q9(e){return Fm(CI,e)}var PI=S("ZodCIDRv4",(e,t)=>{ow.init(e,t),Qe.init(e,t)});function H9(e){return Bm(PI,e)}var NI=S("ZodCIDRv6",(e,t)=>{aw.init(e,t),Qe.init(e,t)});function W9(e){return Vm(NI,e)}var RI=S("ZodBase64",(e,t)=>{uw.init(e,t),Qe.init(e,t)});function J9(e){return Zm(RI,e)}var MI=S("ZodBase64URL",(e,t)=>{lw.init(e,t),Qe.init(e,t)});function X9(e){return Gm(MI,e)}var jI=S("ZodE164",(e,t)=>{pw.init(e,t),Qe.init(e,t)});function Y9(e){return Km(jI,e)}var DI=S("ZodJWT",(e,t)=>{dw.init(e,t),Qe.init(e,t)});function Q9(e){return qm(DI,e)}var OR=S("ZodCustomStringFormat",(e,t)=>{fw.init(e,t),Qe.init(e,t)});function e3(e,t,r={}){return Ox(OR,e,t,r)}var Kp=S("ZodNumber",(e,t)=>{xm.init(e,t),Pe.init(e,t),e.gt=(n,i)=>e.check(Hi(n,i)),e.gte=(n,i)=>e.check(Pr(n,i)),e.min=(n,i)=>e.check(Pr(n,i)),e.lt=(n,i)=>e.check(qi(n,i)),e.lte=(n,i)=>e.check(pn(n,i)),e.max=(n,i)=>e.check(pn(n,i)),e.int=n=>e.check(vI(n)),e.safe=n=>e.check(vI(n)),e.positive=n=>e.check(Hi(0,n)),e.nonnegative=n=>e.check(Pr(0,n)),e.negative=n=>e.check(qi(0,n)),e.nonpositive=n=>e.check(pn(0,n)),e.multipleOf=(n,i)=>e.check(Xo(n,i)),e.step=(n,i)=>e.check(Xo(n,i)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function $R(e){return Yw(Kp,e)}var Qc=S("ZodNumberFormat",(e,t)=>{mw.init(e,t),Kp.init(e,t)});function vI(e){return ex(Qc,e)}function t3(e){return tx(Qc,e)}function r3(e){return rx(Qc,e)}function n3(e){return nx(Qc,e)}function i3(e){return ix(Qc,e)}var qp=S("ZodBoolean",(e,t)=>{ql.init(e,t),Pe.init(e,t)});function CR(e){return sx(qp,e)}var Hp=S("ZodBigInt",(e,t)=>{Im.init(e,t),Pe.init(e,t),e.gte=(n,i)=>e.check(Pr(n,i)),e.min=(n,i)=>e.check(Pr(n,i)),e.gt=(n,i)=>e.check(Hi(n,i)),e.gte=(n,i)=>e.check(Pr(n,i)),e.min=(n,i)=>e.check(Pr(n,i)),e.lt=(n,i)=>e.check(qi(n,i)),e.lte=(n,i)=>e.check(pn(n,i)),e.max=(n,i)=>e.check(pn(n,i)),e.positive=n=>e.check(Hi(BigInt(0),n)),e.negative=n=>e.check(qi(BigInt(0),n)),e.nonpositive=n=>e.check(pn(BigInt(0),n)),e.nonnegative=n=>e.check(Pr(BigInt(0),n)),e.multipleOf=(n,i)=>e.check(Xo(n,i));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function s3(e){return ax(Hp,e)}var zI=S("ZodBigIntFormat",(e,t)=>{hw.init(e,t),Hp.init(e,t)});function o3(e){return ux(zI,e)}function a3(e){return lx(zI,e)}var PR=S("ZodSymbol",(e,t)=>{gw.init(e,t),Pe.init(e,t)});function c3(e){return px(PR,e)}var NR=S("ZodUndefined",(e,t)=>{_w.init(e,t),Pe.init(e,t)});function u3(e){return dx(NR,e)}var RR=S("ZodNull",(e,t)=>{yw.init(e,t),Pe.init(e,t)});function MR(e){return fx(RR,e)}var jR=S("ZodAny",(e,t)=>{vw.init(e,t),Pe.init(e,t)});function l3(){return mx(jR)}var DR=S("ZodUnknown",(e,t)=>{Zs.init(e,t),Pe.init(e,t)});function Hh(){return Gs(DR)}var zR=S("ZodNever",(e,t)=>{Hl.init(e,t),Pe.init(e,t)});function Yh(e){return ep(zR,e)}var LR=S("ZodVoid",(e,t)=>{bw.init(e,t),Pe.init(e,t)});function p3(e){return hx(LR,e)}var Qh=S("ZodDate",(e,t)=>{ww.init(e,t),Pe.init(e,t),e.min=(n,i)=>e.check(Pr(n,i)),e.max=(n,i)=>e.check(pn(n,i));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});function d3(e){return gx(Qh,e)}var UR=S("ZodArray",(e,t)=>{Wl.init(e,t),Pe.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Ks(r,n)),e.nonempty=r=>e.check(Ks(1,r)),e.max=(r,n)=>e.check(kc(r,n)),e.length=(r,n)=>e.check(Ac(r,n)),e.unwrap=()=>e.element});function LI(e,t){return fp(UR,e,t)}function f3(e){let t=e._zod.def.shape;return JR(Object.keys(t))}var eg=S("ZodObject",(e,t)=>{xw.init(e,t),Pe.init(e,t),G.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>HR(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Hh()}),e.loose=()=>e.clone({...e._zod.def,catchall:Hh()}),e.strict=()=>e.clone({...e._zod.def,catchall:Yh()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>G.extend(e,r),e.merge=r=>G.merge(e,r),e.pick=r=>G.pick(e,r),e.omit=r=>G.omit(e,r),e.partial=(...r)=>G.partial(ZI,e,r[0]),e.required=(...r)=>G.required(GI,e,r[0])});function m3(e,t){let r={type:"object",get shape(){return G.assignProp(this,"shape",{...e}),this.shape},...G.normalizeParams(t)};return new eg(r)}function h3(e,t){return new eg({type:"object",get shape(){return G.assignProp(this,"shape",{...e}),this.shape},catchall:Yh(),...G.normalizeParams(t)})}function g3(e,t){return new eg({type:"object",get shape(){return G.assignProp(this,"shape",{...e}),this.shape},catchall:Hh(),...G.normalizeParams(t)})}var UI=S("ZodUnion",(e,t)=>{Sm.init(e,t),Pe.init(e,t),e.options=t.options});function tg(e,t){return new UI({type:"union",options:e,...G.normalizeParams(t)})}var FR=S("ZodDiscriminatedUnion",(e,t)=>{UI.init(e,t),Iw.init(e,t)});function _3(e,t,r){return new FR({type:"union",options:t,discriminator:e,...G.normalizeParams(r)})}var BR=S("ZodIntersection",(e,t)=>{Sw.init(e,t),Pe.init(e,t)});function VR(e,t){return new BR({type:"intersection",left:e,right:t})}var ZR=S("ZodTuple",(e,t)=>{Jo.init(e,t),Pe.init(e,t),e.rest=r=>e.clone({...e._zod.def,rest:r})});function y3(e,t,r){let n=t instanceof ye,i=n?r:t,s=n?t:null;return new ZR({type:"tuple",items:e,rest:s,...G.normalizeParams(i)})}var FI=S("ZodRecord",(e,t)=>{Ew.init(e,t),Pe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function GR(e,t,r){return new FI({type:"record",keyType:e,valueType:t,...G.normalizeParams(r)})}function v3(e,t,r){return new FI({type:"record",keyType:tg([e,Yh()]),valueType:t,...G.normalizeParams(r)})}var KR=S("ZodMap",(e,t)=>{kw.init(e,t),Pe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function b3(e,t,r){return new KR({type:"map",keyType:e,valueType:t,...G.normalizeParams(r)})}var qR=S("ZodSet",(e,t)=>{Aw.init(e,t),Pe.init(e,t),e.min=(...r)=>e.check(Yo(...r)),e.nonempty=r=>e.check(Yo(1,r)),e.max=(...r)=>e.check(Ec(...r)),e.size=(...r)=>e.check(tp(...r))});function w3(e,t){return new qR({type:"set",valueType:e,...G.normalizeParams(t)})}var Zp=S("ZodEnum",(e,t)=>{Tw.init(e,t),Pe.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,i)=>{let s={};for(let o of n)if(r.has(o))s[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Zp({...t,checks:[],...G.normalizeParams(i),entries:s})},e.exclude=(n,i)=>{let s={...t.entries};for(let o of n)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new Zp({...t,checks:[],...G.normalizeParams(i),entries:s})}});function HR(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Zp({type:"enum",entries:r,...G.normalizeParams(t)})}function x3(e,t){return new Zp({type:"enum",entries:e,...G.normalizeParams(t)})}var WR=S("ZodLiteral",(e,t)=>{Ow.init(e,t),Pe.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function JR(e,t){return new WR({type:"literal",values:Array.isArray(e)?e:[e],...G.normalizeParams(t)})}var XR=S("ZodFile",(e,t)=>{$w.init(e,t),Pe.init(e,t),e.min=(r,n)=>e.check(Yo(r,n)),e.max=(r,n)=>e.check(Ec(r,n)),e.mime=(r,n)=>e.check(cp(Array.isArray(r)?r:[r],n))});function I3(e){return Ex(XR,e)}var BI=S("ZodTransform",(e,t)=>{Jl.init(e,t),Pe.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(G.issue(s,r.value,t));else{let o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!0),r.issues.push(G.issue(o))}};let i=t.transform(r.value,r);return i instanceof Promise?i.then(s=>(r.value=s,r)):(r.value=i,r)}});function VI(e){return new BI({type:"transform",transform:e})}var ZI=S("ZodOptional",(e,t)=>{Ic.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Wh(e){return new ZI({type:"optional",innerType:e})}var YR=S("ZodNullable",(e,t)=>{Cw.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Jh(e){return new YR({type:"nullable",innerType:e})}function S3(e){return Wh(Jh(e))}var QR=S("ZodDefault",(e,t)=>{Pw.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function e1(e,t){return new QR({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var t1=S("ZodPrefault",(e,t)=>{Nw.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function r1(e,t){return new t1({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var GI=S("ZodNonOptional",(e,t)=>{Rw.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function n1(e,t){return new GI({type:"nonoptional",innerType:e,...G.normalizeParams(t)})}var i1=S("ZodSuccess",(e,t)=>{Mw.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function E3(e){return new i1({type:"success",innerType:e})}var s1=S("ZodCatch",(e,t)=>{jw.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function o1(e,t){return new s1({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var a1=S("ZodNaN",(e,t)=>{Dw.init(e,t),Pe.init(e,t)});function k3(e){return yx(a1,e)}var KI=S("ZodPipe",(e,t)=>{Xl.init(e,t),Pe.init(e,t),e.in=t.in,e.out=t.out});function Xh(e,t){return new KI({type:"pipe",in:e,out:t})}var c1=S("ZodReadonly",(e,t)=>{zw.init(e,t),Pe.init(e,t)});function u1(e){return new c1({type:"readonly",innerType:e})}var l1=S("ZodTemplateLiteral",(e,t)=>{Lw.init(e,t),Pe.init(e,t)});function A3(e,t){return new l1({type:"template_literal",parts:e,...G.normalizeParams(t)})}var p1=S("ZodLazy",(e,t)=>{Fw.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.getter()});function d1(e){return new p1({type:"lazy",getter:e})}var f1=S("ZodPromise",(e,t)=>{Uw.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function T3(e){return new f1({type:"promise",innerType:e})}var rg=S("ZodCustom",(e,t)=>{Bw.init(e,t),Pe.init(e,t)});function m1(e){let t=new pt({check:"custom"});return t._zod.check=e,t}function O3(e,t){return kx(rg,e??(()=>!0),t)}function h1(e,t={}){return Ax(rg,e,t)}function g1(e){let t=m1(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(G.issue(n,r.value,t._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),r.issues.push(G.issue(i))}},e(r.value,r)));return t}function $3(e,t={error:`Input not instance of ${e.name}`}){let r=new rg({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...G.normalizeParams(t)});return r._zod.bag.Class=e,r}var C3=(...e)=>Tx({Pipe:KI,Boolean:qp,String:Gp,Transform:BI},...e);function P3(e){let t=d1(()=>tg([yI(e),$R(),CR(),MR(),LI(t),GR(yI(),t)]));return t}function N3(e,t){return Xh(VI(e),t)}var R3={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function M3(e){At({customError:e})}function j3(){return At().customError}var qI={};$s(qI,{bigint:()=>U3,boolean:()=>L3,date:()=>F3,number:()=>z3,string:()=>D3});function D3(e){return Kw(Gp,e)}function z3(e){return Qw(Kp,e)}function L3(e){return ox(qp,e)}function U3(e){return cx(Hp,e)}function F3(e){return _x(Qh,e)}At(Em());var HI={};M(HI,{BaseToolkit:()=>B3,DynamicStructuredTool:()=>_1,DynamicTool:()=>JI,StructuredTool:()=>Wp,Tool:()=>WI,ToolInputParsingException:()=>hc,isLangChainTool:()=>Ia,isRunnableToolLike:()=>Bp,isStructuredTool:()=>Fp,isStructuredToolParams:()=>Vp,tool:()=>Jp});var Wp=class extends Th{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata,this.extras=e?.extras??this.extras}async invoke(e,t){let r,n=Ce(Dt(this.defaultConfig,t));return js(e)?(r=e.args,n={...n,toolCall:e}):r=e,this.call(r,n)}async call(e,t,r){let n=js(e)?e.args:e,i;if(_r(this.schema))try{i=await Hs(this.schema,n)}catch(d){let m="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(m=`${m}
200
- Details: ${d.message}`),th(d)&&(m=`${m}
201
-
202
- ${Z.prettifyError(d)}`),new hc(m,JSON.stringify(e))}else{let d=Xe(n,this.schema);if(!d.valid){let m="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(m=`${m}
203
- Details: ${d.errors.map(h=>`${h.keywordLocation}: ${h.error}`).join(`
204
- `)}`),new hc(m,JSON.stringify(e))}i=n}let s=Fo(t),a=await xt.configure(s.callbacks,this.callbacks,s.tags||r,this.tags,s.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),s.runId,void 0,void 0,void 0,s.runName);delete s.runId;let c;try{c=await this._call(i,a,s)}catch(d){throw await a?.handleToolError(d),d}let u,l;if(this.responseFormat==="content_and_artifact")if(Array.isArray(c)&&c.length===2)[u,l]=c;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
205
- Result: ${JSON.stringify(c)}`);else u=c;let p;js(e)&&(p=e.id),!p&&c$(s)&&(p=s.toolCall.id);let f=V3({content:u,artifact:l,toolCallId:p,name:this.name,metadata:this.metadata});return await a?.handleToolEnd(f),f}},WI=class extends Wp{schema=ce.object({input:ce.string().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){let r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,t)}},JI=class extends WI{static lc_name(){return"DynamicTool"}name;description;func;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){let r=Fo(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}async _call(e,t,r){return this.func(e,t,r)}},_1=class extends Wp{static lc_name(){return"DynamicStructuredTool"}description;func;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,t,r){let n=Fo(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n,r)}_call(e,t,r){return this.func(e,t,r)}},B3=class{getTools(){return this.tools}};function Jp(e,t){let r=$c(t.schema),n=Uc(t.schema);if(!t.schema||r||n)return new JI({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(o,a,c)=>new Promise((u,l)=>{let p=Ne(c,{callbacks:a?.getChild()});Ze.runWithConfig(hr(p),async()=>{try{u(e(o,p))}catch(f){l(f)}})})});let i=t.schema,s=t.description??t.schema.description??`${t.name} tool`;return new _1({...t,description:s,schema:i,func:async(o,a,c)=>new Promise((u,l)=>{let p,f=()=>{c?.signal&&p&&c.signal.removeEventListener("abort",p)};c?.signal&&(p=()=>{f(),l(Ls(c.signal))},c.signal.addEventListener("abort",p));let d=Ne(c,{callbacks:a?.getChild()});Ze.runWithConfig(hr(d),async()=>{try{let m=await e(o,d);if(c?.signal?.aborted){f();return}f(),u(m)}catch(m){f(),l(m)}})})})}function V3(e){let{content:t,artifact:r,toolCallId:n,metadata:i}=e;return n&&!ll(t)?typeof t=="string"||Array.isArray(t)&&t.every(s=>typeof s=="object")?new Wt({status:"success",content:t,artifact:r,tool_call_id:n,name:e.name,metadata:i}):new Wt({status:"success",content:Z3(t),artifact:r,tool_call_id:n,name:e.name,metadata:i}):t}function Z3(e){try{return JSON.stringify(e)??""}catch{return`${e}`}}var XI={};M(XI,{RunCollectorCallbackHandler:()=>G3});var G3=class extends Zt{name="run_collector";exampleId;tracedRuns;constructor({exampleId:e}={}){super({_awaitHandler:!0}),this.exampleId=e,this.tracedRuns=[]}async persistRun(e){let t={...e};t.reference_example_id=this.exampleId,this.tracedRuns.push(t)}};var y1={};var YI={};M(YI,{chunkArray:()=>ng});var ng=(e,t)=>e.reduce((r,n,i)=>{let s=Math.floor(i/t),o=r[s]||[];return r[s]=o.concat([n]),r},[]);var QI={};M(QI,{context:()=>K3});function K3(e,...t){let r=e.raw,n="";for(let i=0;i<r.length;i++){let s=r[i].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(n+=s,i<t.length){let o=q3(t[i],n);n+=typeof o=="string"?o:JSON.stringify(o)}}return n=H3(n),n=n.trim(),n=n.replace(/\\n/g,`
206
- `),n}function q3(e,t){if(typeof e!="string"||!e.includes(`
207
- `))return e;let n=t.slice(t.lastIndexOf(`
208
- `)+1).match(/^(\s+)/);if(n){let i=n[1];return e.replace(/\n/g,`
209
- ${i}`)}return e}function H3(e){let t=e.split(`
210
- `),r=null;for(let n of t){let i=n.match(/^(\s+)\S+/);if(i){let s=i[1].length;r===null?r=s:r=Math.min(r,s)}}return r===null?e:t.map(n=>n[0]===" "||n[0]===" "?n.slice(r):n).join(`
211
- `)}var tS={};M(tS,{EventStreamContentType:()=>W3,convertEventStreamToIterableReadableDataStream:()=>X3,getBytes:()=>v1,getLines:()=>b1,getMessages:()=>w1});var W3="text/event-stream";async function v1(e,t){if(e instanceof ReadableStream){let r=e.getReader();for(;;){let n=await r.read();if(n.done){t(new Uint8Array,!0);break}t(n.value)}}else try{for await(let r of e)t(new Uint8Array(r));t(new Uint8Array,!0)}catch(r){throw new Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${r.message}`].join(`
212
- `))}}var eu=(function(e){return e[e.NewLine=10]="NewLine",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.Colon=58]="Colon",e})(eu||{});function b1(e){let t,r,n,i=!1;return function(o,a){if(a){e(o,0,!0);return}t===void 0?(t=o,r=0,n=-1):t=J3(t,o);let c=t.length,u=0;for(;r<c;){i&&(t[r]===eu.NewLine&&(u=++r),i=!1);let l=-1;for(;r<c&&l===-1;++r)switch(t[r]){case eu.Colon:n===-1&&(n=r-u);break;case eu.CarriageReturn:i=!0;case eu.NewLine:l=r;break}if(l===-1)break;e(t.subarray(u,l),n),u=r,n=-1}u===c?t=void 0:u!==0&&(t=t.subarray(u),r-=u)}}function w1(e,t,r){let n=eS(),i=new TextDecoder;return function(o,a,c){if(c){Y3(n)||(e?.(n),n=eS());return}if(o.length===0)e?.(n),n=eS();else if(a>0){let u=i.decode(o.subarray(0,a)),l=a+(o[a+1]===eu.Space?2:1),p=i.decode(o.subarray(l));switch(u){case"data":n.data=n.data?n.data+`
213
- `+p:p;break;case"event":n.event=p;break;case"id":t?.(n.id=p);break;case"retry":{let f=parseInt(p,10);Number.isNaN(f)||r?.(n.retry=f);break}}}}}function J3(e,t){let r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function eS(){return{data:"",event:"",id:"",retry:void 0}}function X3(e,t){let r=new ReadableStream({async start(n){let i=w1(o=>{if(o.event==="error")throw new Error(o.data??"Unspecified event streaming error.");o.event==="metadata"?t?.(o):o.data&&n.enqueue(o.data)});await v1(e,b1((o,a,c)=>{i(o,a,c),c&&n.close()}))}});return kt.fromReadableStream(r)}function Y3(e){return e.data===""&&e.event===""&&e.id===""&&e.retry===void 0}var x1={};var rS={};M(rS,{convertToOpenAIFunction:()=>I1,convertToOpenAITool:()=>nS,isLangChainTool:()=>Ia,isRunnableToolLike:()=>Bp,isStructuredTool:()=>Fp,isStructuredToolParams:()=>Vp});function I1(e,t){let r=typeof t=="number"?void 0:t;return{name:e.name,description:e.description,parameters:Ye(e.schema),...r?.strict!==void 0?{strict:r.strict}:{}}}function nS(e,t){let r=typeof t=="number"?void 0:t,n;return Ia(e)?n={type:"function",function:I1(e)}:n=e,r?.strict!==void 0&&(n.function.strict=r.strict),n}function ig(e,t){let r=0,n=0,i=0;for(let s=0;s<e.length;s++)r+=e[s]*t[s],n+=e[s]*e[s],i+=t[s]*t[s];return r/(Math.sqrt(n)*Math.sqrt(i))}function S1(e,t){let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r}function Q3(e,t){let r=0;for(let n=0;n<e.length;n++)r+=(e[n]-t[n])*(e[n]-t[n]);return r}function E1(e,t){return Math.sqrt(Q3(e,t))}var sS={};M(sS,{cosineSimilarity:()=>iS,euclideanDistance:()=>rG,innerProduct:()=>tG,matrixFunc:()=>sg,maximalMarginalRelevance:()=>nG,normalize:()=>eG});function sg(e,t,r){if(e.length===0||e[0].length===0||t.length===0||t[0].length===0)return[[]];if(e[0].length!==t[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[e.length,e[0].length]} and Y has shape ${[t.length,t[0].length]}.`);return e.map(n=>t.map(i=>r(n,i)).map(i=>Number.isNaN(i)?0:i))}function eG(e,t=!1){let r=iG(e);return e.map(n=>n.map(i=>t?1-i/r:i/r))}function iS(e,t){return sg(e,t,ig)}function tG(e,t){return sg(e,t,S1)}function rG(e,t){return sg(e,t,E1)}function nG(e,t,r=.5,n=4){if(Math.min(n,t.length)<=0)return[];let i=Array.isArray(e[0])?e:[e],s=iS(i,t)[0],o=k1(s).maxIndex,a=[t[o]],c=[o];for(;c.length<Math.min(n,t.length);){let u=-1/0,l=-1,p=iS(t,a);s.forEach((f,d)=>{if(c.includes(d))return;let m=Math.max(...p[d]),h=r*f-(1-r)*m;h>u&&(u=h,l=d)}),a.push(t[l]),c.push(l)}return c}function k1(e){if(e.length===0)return{maxIndex:-1,maxValue:NaN};let t=e[0],r=0;for(let n=1;n<e.length;n+=1)e[n]>t&&(r=n,t=e[n]);return{maxIndex:r,maxValue:t}}function iG(e){return e.reduce((t,r)=>Math.max(t,k1(r).maxValue),0)}var A1=class extends eo{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(e,t,r){if(t?.stop?.length)return{generations:[{message:new $e(t.stop[0]),text:t.stop[0]}]};let n=e.map(i=>typeof i.content=="string"?i.content:JSON.stringify(i.content,null,2)).join(`
214
- `);return await r?.handleLLMNewToken(n),{generations:[{message:new $e(n),text:n}],llmOutput:{}}}},T1=class O1 extends eo{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:t=50,responses:r=[],chunks:n=[],toolStyle:i="openai",thrownErrorString:s,...o}){super(o),this.sleep=t,this.responses=r,this.chunks=n,this.toolStyle=i,this.thrownErrorString=s}_llmType(){return"fake"}bindTools(t){let r=[...this.tools,...t],n=r.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:Ye(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:Ye(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:Ye(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:Ye(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle==="google"?[{functionDeclarations:n}]:n,s=new O1({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return s.tools=r,s.withConfig({tools:i})}async _generate(t,r,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let i=this.responses?.[0]?.content??t[0].content??"";return{generations:[{text:"",message:new $e({content:i,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(t,r,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(let o of this.chunks){let a=new Zr({message:new nt({content:o.content,tool_calls:o.tool_calls,additional_kwargs:o.additional_kwargs??{}}),text:o.content?.toString()??""});if(r.signal?.aborted)break;yield a,await n?.handleLLMNewToken(o.content,void 0,void 0,void 0,void 0,{chunk:a})}return}let i=this.responses?.[0]??new $e(typeof t[0].content=="string"?t[0].content:""),s=typeof i.content=="string"?i.content:"";for(let o of s){await new Promise(c=>setTimeout(c,this.sleep));let a=new Zr({message:new nt({content:o}),text:o});if(r.signal?.aborted)break;yield a,await n?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:a})}}},$1=class C1 extends eo{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle="openai";constructor(t){super(t);let{responses:r,sleep:n,emitCustomEvent:i,generationInfo:s}=t;this.responses=r,this.sleep=n,this.emitCustomEvent=i??this.emitCustomEvent,this.generationInfo=s}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(t,r,n){if(await this._sleepIfRequested(),r?.thrownErrorString)throw new Error(r.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0}),r?.stop?.length)return{generations:[this._formatGeneration(r.stop[0])]};{let i=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(i)],llmOutput:{}}}}_formatGeneration(t){return{message:new $e(t),text:t}}async*_streamResponseChunks(t,r,n){let i=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0});let s=[...i];for(let o=0;o<s.length;o++){let a=s[o],c=o===s.length-1;if(await this._sleepIfRequested(),r?.thrownErrorString)throw new Error(r.thrownErrorString);let u=this._createResponseChunk(a,c?this.generationInfo:void 0);if(r.signal?.aborted)break;yield u,n?.handleLLMNewToken(a)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(t=>{setTimeout(()=>t(),this.sleep)})}_createResponseChunk(t,r){return new Zr({message:new nt({content:t}),text:t,generationInfo:r})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(t){let r=[...this.tools,...t],n=r.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:Ye(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:Ye(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:Ye(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:Ye(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle==="google"?[{functionDeclarations:n}]:n,s=new C1({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return s.tools=r,s.toolStyle=this.toolStyle,s.i=this.i,s.withConfig({tools:i})}withStructuredOutput(t,r){return tr.from(async n=>{let i=await this.invoke(n);if(i.tool_calls?.[0]?.args)return i.tool_calls[0].args;if(typeof i.content=="string")return JSON.parse(i.content);throw new Error("No structured output found")})}};var P1=class extends Fc{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(t=>this.embedQuery(t)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,"");let r=t.length%this.vectorSize,n=r===0?0:this.vectorSize-r,i=t.length+n;t=t.padEnd(i," ");let s=t.length/this.vectorSize,o=[];for(let c=0;c<t.length;c+=s)o.push(t.slice(c,c+s));return o.map(c=>{let u=0;for(let p=0;p<c.length;p+=1)u+=c===" "?0:c.charCodeAt(p);return u%26/26})}},N1=class extends Fc{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}};var R1=class extends $h{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let n=this.response??e;return await r?.handleLLMNewToken(n),n}},M1=class extends $h{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let n=this.responses?.[0];this.responses=this.responses?.slice(1);for(let i of n??e)await new Promise(s=>setTimeout(s,this.sleep)),yield{text:i,generationInfo:{}},await r?.handleLLMNewToken(i)}};var j1=class extends t0{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new at(e))}async addAIMessage(e){this.messages.push(new $e(e))}async clear(){this.messages=[]}},D1=class extends yh{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},z1=class extends Zt{name="fake_tracer";runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}};var L1=class extends ts{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(e){return e.split(",").map(t=>t.trim())}};var U1=class extends Ep{lc_namespace=["test","fake"];output=[new qr({pageContent:"foo"}),new qr({pageContent:"bar"})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}};var F1=class extends ue{lc_namespace=["tests","fake"];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}};var B1=class extends Wp{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}};var V1=class extends Zt{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}};var Z1=class G1 extends wh{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(t,{similarity:r,...n}={}){super(t,n),this.similarity=r??ig}async addDocuments(t){let r=t.map(({pageContent:n})=>n);return this.addVectors(await this.embeddings.embedDocuments(r),t)}async addVectors(t,r){let n=t.map((i,s)=>({content:r[s].pageContent,embedding:i,metadata:r[s].metadata}));this.memoryVectors=this.memoryVectors.concat(n)}async similaritySearchVectorWithScore(t,r,n){let i=c=>{if(!n)return!0;let u=new qr({metadata:c.metadata,pageContent:c.content});return n(u)},s=this.memoryVectors.filter(i);return s.map((c,u)=>({similarity:this.similarity(t,c.embedding),index:u})).sort((c,u)=>c.similarity>u.similarity?-1:0).slice(0,r).map(c=>[new qr({metadata:s[c.index].metadata,pageContent:s[c.index].content}),c.similarity])}static async fromTexts(t,r,n,i){let s=[];for(let o=0;o<t.length;o+=1){let a=Array.isArray(r)?r[o]:r,c=new qr({pageContent:t[o],metadata:a});s.push(c)}return G1.fromDocuments(s,n,i)}static async fromDocuments(t,r,n){let i=new this(r,n);return await i.addDocuments(t),i}static async fromExistingIndex(t,r){return new this(t,r)}};var oS={};M(oS,{FakeChatMessageHistory:()=>j1,FakeChatModel:()=>A1,FakeEmbeddings:()=>N1,FakeLLM:()=>R1,FakeListChatMessageHistory:()=>D1,FakeListChatModel:()=>$1,FakeRetriever:()=>U1,FakeRunnable:()=>F1,FakeSplitIntoListParser:()=>L1,FakeStreamingChatModel:()=>T1,FakeStreamingLLM:()=>M1,FakeTool:()=>B1,FakeTracer:()=>z1,FakeVectorStore:()=>Z1,SingleRunExtractor:()=>V1,SyntheticEmbeddings:()=>P1});var aS={};M(aS,{extendInteropZodObject:()=>Ym,getInteropZodDefaultGetter:()=>Qm,getInteropZodObjectShape:()=>ea,getSchemaDescription:()=>On,interopParse:()=>Oc,interopParseAsync:()=>Hs,interopSafeParse:()=>YC,interopSafeParseAsync:()=>Jm,interopZodObjectMakeFieldsOptional:()=>eP,interopZodObjectPartial:()=>Cc,interopZodObjectPassthrough:()=>Wm,interopZodObjectStrict:()=>Tc,interopZodTransformInputSchema:()=>eh,isInteropZodError:()=>th,isInteropZodLiteral:()=>XC,isInteropZodObject:()=>yr,isInteropZodSchema:()=>_r,isShapelessZodSchema:()=>QC,isSimpleStringZodSchema:()=>$c,isZodArrayV4:()=>hp,isZodLiteralV3:()=>Cx,isZodLiteralV4:()=>Px,isZodNullableV4:()=>Rx,isZodObjectV3:()=>Xm,isZodObjectV4:()=>dn,isZodOptionalV4:()=>Nx,isZodSchema:()=>JC,isZodSchemaV3:()=>it,isZodSchemaV4:()=>We});var cS={};M(cS,{agents:()=>Ok,caches:()=>l0,callbacks__base:()=>ey,callbacks__manager:()=>yv,callbacks__promises:()=>hv,chat_history:()=>e0,document_loaders__base:()=>d0,document_loaders__langsmith:()=>m0,documents:()=>g0,embeddings:()=>r0,example_selectors:()=>v0,index:()=>SN,indexing:()=>E0,language_models__base:()=>$0,language_models__chat_models:()=>P0,language_models__llms:()=>N0,language_models__profile:()=>WN,load__serializable:()=>G_,memory:()=>n0,messages:()=>Qx,messages__tool:()=>Y_,output_parsers:()=>z0,output_parsers__openai_functions:()=>F0,output_parsers__openai_tools:()=>V0,outputs:()=>Ov,prompt_values:()=>i0,prompts:()=>rI,retrievers:()=>a0,retrievers__document_compressors:()=>nI,runnables:()=>M0,runnables__graph:()=>Gx,singletons:()=>bv,stores:()=>o0,structured_query:()=>uI,tools:()=>HI,tracers__base:()=>iv,tracers__console:()=>ov,tracers__log_stream:()=>Av,tracers__run_collector:()=>XI,tracers__tracer_langchain:()=>mv,types__stream:()=>y1,utils__async_caller:()=>$v,utils__chunk_array:()=>YI,utils__context:()=>QI,utils__env:()=>q_,utils__event_source_parse:()=>tS,utils__format:()=>x1,utils__function_calling:()=>rS,utils__hash:()=>u0,utils__json_patch:()=>j0,utils__json_schema:()=>Vx,utils__math:()=>sS,utils__stream:()=>xv,utils__testing:()=>oS,utils__tiktoken:()=>O0,utils__types:()=>aS,vectorstores:()=>c0});var sG=50;function oG(e){let t={};for(let r=e;r&&r.prototype;r=Object.getPrototypeOf(r))Object.assign(t,Reflect.get(r.prototype,"lc_aliases"));return Object.entries(t).reduce((r,[n,i])=>(r[i]=n,r),{})}async function og(e){let{optionalImportsMap:t,optionalImportEntrypoints:r,importMap:n,secretsMap:i,secretsFromEnv:s,path:o,depth:a,maxDepth:c}=this,u=o.join(".");if(a>c)throw new Error(`Maximum recursion depth (${c}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof e!="object"||e==null)return e;if(Array.isArray(e))return Promise.all(e.map((f,d)=>og.call({...this,path:[...o,`${d}`],depth:a+1},f)));let l=e;if(Z_(l))return ef(l);if("lc"in l&&"type"in l&&"id"in l&&l.lc===1&&l.type==="secret"){let f=l,[d]=f.id;if(d in i)return i[d];if(s){let m=Je(d);if(m)return m}throw new Error(`Missing secret "${d}" at ${u}`)}if("lc"in l&&"type"in l&&"id"in l&&l.lc===1&&l.type==="not_implemented"){let d=JSON.stringify(l);throw new Error(`Trying to load an object that doesn't implement serialization: ${u} -> ${d}`)}if("lc"in l&&"type"in l&&"id"in l&&"kwargs"in l&&l.lc===1&&l.type==="constructor"){let f=l,d=JSON.stringify(f),[m,...h]=f.id.slice().reverse(),b=h.reverse(),_={langchain_core:cS,langchain:n},y=null,x=[b.join("/")];b[0]==="langchain_community"&&x.push(["langchain",...b.slice(1)].join("/"));let I=x.find(w=>w in t);if(Tk.concat(r).includes(b.join("/"))||I)if(I!==void 0)y=await t[I];else throw new Error(`Missing key "${b.join("/")}" for ${u} in load(optionalImportsMap={})`);else{let w;if(b[0]==="langchain"||b[0]==="langchain_core")w=_[b[0]],b.shift();else throw new Error(`Invalid namespace: ${u} -> ${d}`);if(b.length===0)throw new Error(`Invalid namespace: ${u} -> ${d}`);let U;do{if(U=b.join("__"),U in w)break;b.pop()}while(b.length>0);U in w&&(y=w[U])}if(typeof y!="object"||y===null)throw new Error(`Invalid namespace: ${u} -> ${d}`);let A=y[m]??Object.values(y).find(w=>typeof w=="function"&&cc(w)===m);if(typeof A!="function")throw new Error(`Invalid identifer: ${u} -> ${d}`);let j=await og.call({...this,path:[...o,"kwargs"],depth:a+1},f.kwargs),O=new A(Yd(j,wk,oG(A)));return Object.defineProperty(O.constructor,"name",{value:m}),O}let p={};for(let[f,d]of Object.entries(l))p[f]=await og.call({...this,path:[...o,f],depth:a+1},d);return p}async function K1(e,t){let r=JSON.parse(e),n={optionalImportsMap:t?.optionalImportsMap??{},optionalImportEntrypoints:t?.optionalImportEntrypoints??[],secretsMap:t?.secretsMap??{},secretsFromEnv:t?.secretsFromEnv??!1,importMap:t?.importMap??{},path:["$"],depth:0,maxDepth:t?.maxDepth??sG};return og.call(n,r)}function aG(e){return e!==null&&e.lc===1&&e.type==="constructor"&&Array.isArray(e.id)}async function lS(e){if(e&&typeof e=="object"){if(Array.isArray(e))return await Promise.all(e.map(r=>lS(r)));{let t={};for(let[r,n]of Object.entries(e))t[r]=await lS(n);if(t.lc===2&&t.type==="undefined")return;if(t.lc===2&&t.type==="constructor"&&Array.isArray(t.id))try{let r=t.id[t.id.length-1],n;switch(r){case"Set":n=Set;break;case"Map":n=Map;break;case"RegExp":n=RegExp;break;case"Error":n=Error;break;default:return t}return t.method?n[t.method](...t.args||[]):new n(...t.args||[])}catch{return t}else if(aG(t))return K1(JSON.stringify(t));return t}}return e}function uS(e,t,r,n){return{lc:2,type:"constructor",id:[e.name],method:t??null,args:r??[],kwargs:n??{}}}function cG(e){return e===void 0?{lc:2,type:"undefined"}:e instanceof Set||e instanceof Map?uS(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?uS(RegExp,void 0,[e.source,e.flags]):e instanceof Error?uS(e.constructor,void 0,[e.message]):e?.lg_name==="Send"?{node:e.node,args:e.args}:e}var ag=class{_dumps(e){return new TextEncoder().encode(ck(e,(r,n)=>cG(n)))}async dumpsTyped(e){return e instanceof Uint8Array?["bytes",e]:["json",this._dumps(e)]}async _loads(e){let t=JSON.parse(e);return lS(t)}async loadsTyped(e,t){if(e==="bytes")return typeof t=="string"?new TextEncoder().encode(t):t;if(e==="json")return this._loads(typeof t=="string"?t:new TextDecoder().decode(t));throw new Error(`Unknown serialization type: ${e}`)}};function pS(e){if(typeof e!="object"||e===null)return e;let t=Array.isArray(e)?[]:{};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=pS(e[r]));return t}function tu(){return{v:4,id:al(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function zn(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values},channel_versions:{...e.channel_versions},versions_seen:pS(e.versions_seen)}}var cg=class{serde=new ag;constructor(e){this.serde=e||this.serde}async get(e){let t=await this.getTuple(e);return t?t.checkpoint:void 0}getNextVersion(e){if(typeof e=="string")throw new Error("Please override this method to use string versions.");return e!==void 0&&typeof e=="number"?e+1:1}};function ug(e,t){return typeof e=="number"&&typeof t=="number"?Math.sign(e-t):String(e).localeCompare(String(t))}function Xp(...e){return e.reduce((t,r,n)=>n===0?r:ug(t,r)>=0?t:r)}var Yp={[z_]:-1,[No]:-2,[L_]:-3,[U_]:-4};function dS(e){return e.configurable?.checkpoint_id||e.configurable?.thread_ts||""}function Qp(e,t,r){return JSON.stringify([e,t,r])}function uG(e){let[t,r,n]=JSON.parse(e);return{threadId:t,checkpointNamespace:r,checkpointId:n}}var lg=class extends cg{storage={};writes={};constructor(e){super(e)}async _migratePendingSends(e,t,r,n){let i=e,s=Qp(t,r,n),o=await Promise.all(Object.values(this.writes[s]??{}).filter(([a,c])=>c===cl).map(async([a,c,u])=>await this.serde.loadsTyped("json",u)));i.channel_values??={},i.channel_values[cl]=o,i.channel_versions??={},i.channel_versions[cl]=Object.keys(i.channel_versions).length>0?Xp(...Object.values(i.channel_versions)):this.getNextVersion(void 0)}async getTuple(e){let t=e.configurable?.thread_id,r=e.configurable?.checkpoint_ns??"",n=dS(e);if(n){let i=this.storage[t]?.[r]?.[n];if(i!==void 0){let[s,o,a]=i,c=Qp(t,r,n),u=await this.serde.loadsTyped("json",s);u.v<4&&a!==void 0&&await this._migratePendingSends(u,t,r,a);let l=await Promise.all(Object.values(this.writes[c]||{}).map(async([f,d,m])=>[f,d,await this.serde.loadsTyped("json",m)])),p={config:e,checkpoint:u,metadata:await this.serde.loadsTyped("json",o),pendingWrites:l};return a!==void 0&&(p.parentConfig={configurable:{thread_id:t,checkpoint_ns:r,checkpoint_id:a}}),p}}else{let i=this.storage[t]?.[r];if(i!==void 0){n=Object.keys(i).sort((d,m)=>m.localeCompare(d))[0];let s=i[n],[o,a,c]=s,u=Qp(t,r,n),l=await this.serde.loadsTyped("json",o);l.v<4&&c!==void 0&&await this._migratePendingSends(l,t,r,c);let p=await Promise.all(Object.values(this.writes[u]||{}).map(async([d,m,h])=>[d,m,await this.serde.loadsTyped("json",h)])),f={config:{configurable:{thread_id:t,checkpoint_id:n,checkpoint_ns:r}},checkpoint:l,metadata:await this.serde.loadsTyped("json",a),pendingWrites:p};return c!==void 0&&(f.parentConfig={configurable:{thread_id:t,checkpoint_ns:r,checkpoint_id:c}}),f}}}async*list(e,t){let{before:r,limit:n,filter:i}=t??{},s=e.configurable?.thread_id?[e.configurable?.thread_id]:Object.keys(this.storage),o=e.configurable?.checkpoint_ns,a=e.configurable?.checkpoint_id;for(let c of s)for(let u of Object.keys(this.storage[c]??{})){if(o!==void 0&&u!==o)continue;let l=this.storage[c]?.[u]??{},p=Object.entries(l).sort((f,d)=>d[0].localeCompare(f[0]));for(let[f,[d,m,h]]of p){if(a&&f!==a||r&&r.configurable?.checkpoint_id&&f>=r.configurable.checkpoint_id)continue;let b=await this.serde.loadsTyped("json",m);if(i&&!Object.entries(i).every(([j,O])=>b[j]===O))continue;if(n!==void 0){if(n<=0)break;n-=1}let _=Qp(c,u,f),y=Object.values(this.writes[_]||{}),x=await Promise.all(y.map(async([j,O,w])=>[j,O,await this.serde.loadsTyped("json",w)])),I=await this.serde.loadsTyped("json",d);I.v<4&&h!==void 0&&await this._migratePendingSends(I,c,u,h);let A={config:{configurable:{thread_id:c,checkpoint_ns:u,checkpoint_id:f}},checkpoint:I,metadata:b,pendingWrites:x};h!==void 0&&(A.parentConfig={configurable:{thread_id:c,checkpoint_ns:u,checkpoint_id:h}}),yield A}}}async put(e,t,r){let n=zn(t),i=e.configurable?.thread_id,s=e.configurable?.checkpoint_ns??"";if(i===void 0)throw new Error('Failed to put checkpoint. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property.');this.storage[i]||(this.storage[i]={}),this.storage[i][s]||(this.storage[i][s]={});let[[,o],[,a]]=await Promise.all([this.serde.dumpsTyped(n),this.serde.dumpsTyped(r)]);return this.storage[i][s][t.id]=[o,a,e.configurable?.checkpoint_id],{configurable:{thread_id:i,checkpoint_ns:s,checkpoint_id:t.id}}}async putWrites(e,t,r){let n=e.configurable?.thread_id,i=e.configurable?.checkpoint_ns,s=e.configurable?.checkpoint_id;if(n===void 0)throw new Error('Failed to put writes. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property');if(s===void 0)throw new Error('Failed to put writes. The passed RunnableConfig is missing a required "checkpoint_id" field in its "configurable" property.');let o=Qp(n,i,s),a=this.writes[o];this.writes[o]===void 0&&(this.writes[o]={}),await Promise.all(t.map(async([c,u],l)=>{let[,p]=await this.serde.dumpsTyped(u),f=[r,Yp[c]||l],d=`${f[0]},${f[1]}`;f[1]>=0&&a&&d in a||(this.writes[o][d]=[r,c,p])}))}async deleteThread(e){delete this.storage[e];for(let t of Object.keys(this.writes))uG(t).threadId===e&&delete this.writes[t]}};var ru=class extends Error{constructor(e){super(e),this.name="InvalidNamespaceError"}};function lG(e){if(e.length===0)throw new ru("Namespace cannot be empty.");for(let t of e){if(typeof t!="string")throw new ru(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes("."))throw new ru(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t==="")throw new ru(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]==="langgraph")throw new ru(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var ed=class{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){let{filter:r,limit:n=10,offset:i=0,query:s}=t;return(await this.batch([{namespacePrefix:e,filter:r,limit:n,offset:i,query:s}]))[0]}async put(e,t,r,n){lG(e),await this.batch([{namespace:e,key:t,value:r,index:n}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){let{prefix:t,suffix:r,maxDepth:n,limit:i=100,offset:s=0}=e,o=[];return t&&o.push({matchType:"prefix",path:t}),r&&o.push({matchType:"suffix",path:r}),(await this.batch([{matchConditions:o.length?o:void 0,maxDepth:n,limit:i,offset:s}]))[0]}start(){}stop(){}};var pG=e=>"lg_name"in e&&e.lg_name==="AsyncBatchedStore"?e.store:e,pg=class extends ed{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=pG(e)}get isRunning(){return this.running}async batch(e){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){let{filter:r,limit:n=10,offset:i=0,query:s}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:r,limit:n,offset:i,query:s})}async put(e,t,r){return this.enqueueOperation({namespace:e,key:t,value:r})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,r)=>{let n=this.nextKey;this.nextKey+=1,this.queue.set(n,{operation:e,resolve:t,reject:r})})}async processBatchQueue(){for(;this.running;){if(await new Promise(t=>{setTimeout(t,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let t=Array.from(e.values()).map(({operation:n})=>n),r=await this.store.batch(t);e.forEach(({resolve:n},i)=>{let s=Array.from(e.keys()).indexOf(i);n(r[s])})}catch(t){e.forEach(({reject:r})=>{r(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}};var dg=class{serde=new ag;constructor(e){this.serde=e||this.serde}};function mS(e){return e!=null&&e.lg_is_channel===!0}var Lt=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===Ve.unminifiable_name)return!1;throw e}}equals(e){return this===e}},fS=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function td(e){if(e[fS]===!0)return e;let t={};for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let n=e[r];mS(n)&&(t[r]=n)}return Object.assign(t,{[fS]:!0}),t}function no(e,t){let r=td(e),n={};for(let i in r){if(!Object.prototype.hasOwnProperty.call(r,i))continue;let s=t.channel_values[i];n[i]=r[i].fromCheckpoint(s)}return Object.assign(n,{[fS]:!0}),n}function Ln(e,t,r,n){let i;if(t===void 0)i=e.channel_values;else{i={};for(let s in t)if(Object.prototype.hasOwnProperty.call(t,s))try{i[s]=t[s].checkpoint()}catch(o){if(o.name!==Ve.unminifiable_name)throw o}}return{v:4,id:n?.id??al(r),ts:new Date().toISOString(),channel_values:i,channel_versions:e.channel_versions,versions_seen:e.versions_seen}}var fG=e=>e!=null&&e.lc_graph_name==="BinaryOperatorAggregate",os=class q1 extends Lt{lc_graph_name="BinaryOperatorAggregate";value;operator;initialValueFactory;constructor(t,r){super(),this.operator=t,this.initialValueFactory=r,this.value=r?.()}fromCheckpoint(t){let r=new q1(this.operator,this.initialValueFactory);return typeof t<"u"&&(r.value=t),r}update(t){let r=t;if(!r.length)return!1;this.value===void 0&&([this.value]=r,r=r.slice(1));for(let n of r)this.value!==void 0&&(this.value=this.operator(this.value,n));return!0}get(){if(this.value===void 0)throw new Ve;return this.value}checkpoint(){if(this.value===void 0)throw new Ve;return this.value}isAvailable(){return this.value!==void 0}equals(t){return this===t?!0:fG(t)?this.operator===t.operator:!1}};var Un=class H1 extends Lt{lc_graph_name="LastValue";value=[];constructor(t){super(),this.initialValueFactory=t,t&&(this.value=[t()])}fromCheckpoint(t){let r=new H1(this.initialValueFactory);return typeof t<"u"&&(r.value=[t]),r}update(t){if(t.length===0)return!1;if(t.length!==1)throw new De("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new Ve;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Ve;return this.value[0]}isAvailable(){return this.value.length!==0}},hS=class W1 extends Lt{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(t){let r=new W1;if(typeof t<"u"){let[n,i]=t;r.value=[n],r.finished=i}return r}update(t){return t.length===0?!1:(this.finished=!1,this.value=[t[t.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new Ve;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}};var fg=class{lc_graph_name="AnnotationRoot";spec;constructor(e){this.spec=e}static isInstance(e){return typeof e=="object"&&e!==null&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"}},Fn=function(e){return e?mg(e):new Un};Fn.Root=e=>new fg(e);function mg(e){return typeof e=="object"&&e&&"reducer"in e&&e.reducer?new os(e.reducer,e.default):typeof e=="object"&&e&&"value"in e&&e.value?new os(e.value,e.default):new Un}var Ae="__start__",xe="__end__",Bn="__input__",X1="__copy__",Ot="__error__",hg="__pregel_ns_writes",bn="__pregel_send",nd="__pregel_call",Vn="__pregel_read",ft="__pregel_checkpointer",yi="__pregel_resuming",Ea="__pregel_task_id",nu="__pregel_stream",mG="__pregel_resume_value",iu="__pregel_resume_map",Wr="__pregel_scratchpad",su="__pregel_previous",gS="__pregel_durability",gg="checkpoint_id",Jr="checkpoint_ns",Y1="__pregel_node_finished",xr="checkpoint_map",_S="__pregel_abort_signals",ke="__interrupt__",Nt="__resume__",id="__no_writes__",Zn="__return__",ka="__previous__",Be="langsmith:hidden",Q1="langsmith:nostream",yS="__self__",Ut="__pregel_tasks",nr="__pregel_push",sd="__pregel_pull",ir="00000000-0000-0000-0000-000000000000",eM=[Be,Bn,ke,Nt,Ot,id,bn,Vn,ft,gS,nu,yi,Ea,nd,mG,Wr,su,xr,Jr,gg],et="|",Ir=":",J1=Symbol.for("langgraph.command"),hG=class{[J1];constructor(e){this[J1]=e}};function _g(e){let t=e;return t!=null&&typeof t.node=="string"&&t.args!==void 0}var Sa=class{lg_name="Send";node;args;constructor(e,t){this.node=e,this.args=rd(t)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function $t(e){return e instanceof Sa}function od(e){return!e||typeof e!="object"||!(ke in e)?!1:Array.isArray(e[ke])}var jr=class extends hG{lg_name="Command";lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT="__parent__";constructor(e){super(e),this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?rd(e.goto):[rd(e.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){let e;return typeof this.goto=="string"?e=this.goto:$t(this.goto)?e=this.goto.toJSON():e=this.goto?.map(t=>typeof t=="string"?t:t.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}};function Pt(e){return typeof e!="object"||e==null?!1:"lg_name"in e&&e.lg_name==="Command"}function rd(e,t=new Map){if(e!=null&&typeof e=="object"){if(t.has(e))return t.get(e);let r;if(Array.isArray(e))r=[],t.set(e,r),e.forEach((n,i)=>{r[i]=rd(n,t)});else if(Pt(e)&&!(e instanceof jr))r=new jr(e),t.set(e,r);else if(_g(e)&&!(e instanceof Sa))r=new Sa(e.node,e.args),t.set(e,r);else if(Pt(e)||$t(e))r=e,t.set(e,r);else if("lc_serializable"in e&&e.lc_serializable)r=e,t.set(e,r);else{r={},t.set(e,r);for(let[n,i]of Object.entries(e))r[n]=rd(i,t)}return r}return e}var gG=["tags","metadata","callbacks","configurable"],_G=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],yG=25;function ad(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:yG,configurable:{}},r=Ze.getRunnableConfig();if(r!==void 0){for(let[n,i]of Object.entries(r))if(i!==void 0)if(gG.includes(n)){let s;Array.isArray(i)?s=[...i]:typeof i=="object"?n==="callbacks"&&"copy"in i&&typeof i.copy=="function"?s=i.copy():s={...i}:s=i,t[n]=s}else t[n]=i}for(let n of e)if(n!==void 0)for(let[i,s]of Object.entries(n))s!==void 0&&_G.includes(i)&&(t[i]=s);for(let[n,i]of Object.entries(t.configurable))t.metadata=t.metadata??{},!n.startsWith("__")&&(typeof i=="string"||typeof i=="number"||typeof i=="boolean")&&!(n in t.metadata)&&(t.metadata[n]=i);return t}function tM(){return Ze.getRunnableConfig()}function yg(e){return e.split(et).filter(t=>!t.match(/^\d+$/)).map(t=>t.split(Ir)[0]).join(et)}function rM(e){let t=e.split(et);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(et)}var sr=class extends ue{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,t,r){return new Promise((n,i)=>{let s=Ne(t,{callbacks:r?.getChild()});Ze.runWithConfig(s,async()=>{try{n(await this.func(e,s))}catch(o){i(o)}})})}async invoke(e,t){let r,n=ad(t),i=Dt(this.config,n);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,i):r=await Ze.runWithConfig(i,async()=>this.func(e,i)),ue.isRunnable(r)&&this.recurse?await Ze.runWithConfig(i,async()=>r.invoke(e,i)):r}};function*as(e,t){if(t===void 0)yield*e;else for(let r of e)yield[t,r]}async function Gn(e){let t=[];for await(let r of await e)t.push(r);return t}function Aa(e){let t=[];for(let r of e)t.push(r);return t}function Ta(e,t){return e?"configurable"in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function nM(e){return e!=null&&typeof e=="function"&&e instanceof Object.getPrototypeOf(async function*(){}).constructor}function iM(e){return e!=null&&typeof e=="function"&&e instanceof Object.getPrototypeOf(function*(){}).constructor}var Uve={[Symbol.for("LG_SKIP_WRITE")]:!0};function vG(e){return typeof e=="object"&&e?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}var Dr={[Symbol.for("LG_PASSTHROUGH")]:!0};function vg(e){return typeof e=="object"&&e?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}var vS=Symbol("IS_WRITER"),_t=class wS extends sr{writes;constructor(t,r){let n=`ChannelWrite<${t.map(i=>$t(i)?i.node:"channel"in i?i.channel:"...").join(",")}>`;super({writes:t,name:n,tags:r,func:async(i,s)=>this._write(i,s??{})}),this.writes=t}async _write(t,r){let n=this.writes.map(i=>bS(i)&&vg(i.value)?{mapper:i.mapper,value:t}:bg(i)&&vg(i.value)?{channel:i.channel,value:t,skipNone:i.skipNone,mapper:i.mapper}:i);return await wS.doWrite(r,n),t}static async doWrite(t,r){for(let s of r){if(bg(s)){if(s.channel===Ut)throw new De("Cannot write to the reserved channel TASKS");if(vg(s.value))throw new De("PASSTHROUGH value must be replaced")}if(bS(s)&&vg(s.value))throw new De("PASSTHROUGH value must be replaced")}let n=[];for(let s of r)if($t(s))n.push([Ut,s]);else if(bS(s)){let o=await s.mapper.invoke(s.value,t);o!=null&&o.length>0&&n.push(...o)}else if(bg(s)){let o=s.mapper!==void 0?await s.mapper.invoke(s.value,t):s.value;if(vG(o)||s.skipNone&&o===void 0)continue;n.push([s.channel,o])}else throw new Error(`Invalid write entry: ${JSON.stringify(s)}`);let i=t.configurable?.[bn];i(n)}static isWriter(t){return t instanceof wS||vS in t&&!!t[vS]}static registerWriter(t){return Object.defineProperty(t,vS,{value:!0})}};function bg(e){return e!==void 0&&typeof e.channel=="string"}function bS(e){return e!==void 0&&!bg(e)&&ue.isRunnable(e.mapper)}var sM=class oM extends sr{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(t,r,n=!1){super({func:(i,s)=>oM.doRead(s,this.channel,this.fresh,this.mapper)}),this.fresh=n,this.mapper=r,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(",")}>`:`ChannelRead<${t}>`}static doRead(t,r,n,i){let s=t.configurable?.[Vn];if(!s)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return i?i(s(r,n)):s(r,n)}},ou=new yn,Kn=class cd extends gn{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=ou;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(t){let{channels:r,triggers:n,mapper:i,writers:s,bound:o,kwargs:a,metadata:c,retryPolicy:u,cachePolicy:l,tags:p,subgraphs:f,ends:d}=t,m=[...t.config?.tags?t.config.tags:[],...p??[]];super({...t,bound:t.bound??ou,config:{...t.config?t.config:{},tags:m}}),this.channels=r,this.triggers=n,this.mapper=i,this.writers=s??this.writers,this.bound=o??this.bound,this.kwargs=a??this.kwargs,this.metadata=c??this.metadata,this.tags=m,this.retryPolicy=u,this.cachePolicy=l,this.subgraphs=f,this.ends=d}getWriters(){let t=[...this.writers];for(;t.length>1&&t[t.length-1]instanceof _t&&t[t.length-2]instanceof _t;){let r=t.slice(-2),n=r[0].writes.concat(r[1].writes);t[t.length-2]=new _t(n,r[0].config?.tags),t.pop()}return t}getNode(){let t=this.getWriters();if(!(this.bound===ou&&t.length===0))return this.bound===ou&&t.length===1?t[0]:this.bound===ou?new br({first:t[0],middle:t.slice(1,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):t.length>0?new br({first:this.bound,middle:t.slice(0,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))throw new Error("channels must be a list");if(typeof this.channels!="object")throw new Error("all channels must be named when using .join()");return new cd({channels:{...this.channels,...Object.fromEntries(t.map(r=>[r,r]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}pipe(t){return _t.isWriter(t)?new cd({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):this.bound===ou?new cd({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:dt(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new cd({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function bG(e){return"steps"in e&&Array.isArray(e.steps)}function ud(e){return"lg_is_pregel"in e&&e.lg_is_pregel===!0}function wg(e){let t=[e];for(let r of t){if(ud(r))return r;bG(r)&&t.push(...r.steps)}}var L=e=>BigInt(e),Ge=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),lM=L("0x9E3779B1"),pM=L("0x85EBCA77"),wG=L("0xC2B2AE3D"),io=L("0x9E3779B185EBCA87"),Oa=L("0xC2B2AE3D27D4EB4F"),dM=L("0x165667B19E3779F9"),SS=L("0x85EBCA77C2B2AE63"),xG=L("0x27D4EB2F165667C5"),IG=L("0x165667919E3779F9"),SG=L("0x9FB21C651E98DF25"),EG=e=>{let t=e.length;if(t%2!==0)throw new Error("String should have an even number of characters");let r=t/2,n=new Uint8Array(r),i=0,s=0;for(;s<r;){let o=e.slice(i,i+=2);n[s]=Number.parseInt(o,16),s+=1}return Ge(n)},vi=EG("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),au=(L(1)<<L(128))-L(1),Te=(L(1)<<L(64))-L(1),Eg=(L(1)<<L(32))-L(1),cs=64,fM=cs/8,kG=8,xg=4;function cu(e){if(!e)throw new Error("Assert failed")}function AG(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function TG(e){let t=e;return t=(t&L(65535))<<L(16)|(t&L(4294901760))>>L(16),t=(t&L(16711935))<<L(8)|(t&L(4278255360))>>L(8),t}function OG(e,t){return(e&Eg)*(t&Eg)&Te}function $G(e,t){return(e<<t|e>>L(32)-t)&Eg}function mM(e,t,r){for(let n=0;n<fM;n+=1){let i=t.getBigUint64(n*8,!0),s=i^r.getBigUint64(n*8,!0);e[n^1]+=i,e[n]+=OG(s,s>>L(32))}return e}function aM(e,t,r,n){for(let i=0;i<n;i+=1)mM(e,Ge(t,i*cs),Ge(r,i*8));return e}function CG(e,t){for(let r=0;r<fM;r+=1){let n=t.getBigUint64(r*8,!0),i=e[r];i=xS(i,L(47)),i^=n,i*=lM,e[r]=i&Te}return e}function Ig(e,t){return hM(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(kG,!0))}function cM(e,t,r){let n=r;return n+=Ig(e.slice(0),Ge(t,0*xg)),n+=Ig(e.slice(2),Ge(t,4*xg)),n+=Ig(e.slice(4),Ge(t,8*xg)),n+=Ig(e.slice(6),Ge(t,12*xg)),bi(n&Te)}function PG(e,t,r,n,i){let s=e,o=Math.floor((r.byteLength-cs)/8),a=cs*o,c=Math.floor((t.byteLength-1)/a);for(let u=0;u<c;u+=1)s=aM(s,Ge(t,u*a),r,o),s=i(s,Ge(r,r.byteLength-cs));{let u=Math.floor((t.byteLength-1-a*c)/cs);s=aM(s,Ge(t,c*a),r,u),s=n(s,Ge(t,t.byteLength-cs),Ge(r,r.byteLength-cs-7))}return s}function NG(e,t){let r=new BigUint64Array([wG,io,Oa,dM,SS,pM,xG,lM]);cu(e.byteLength>128),r=PG(r,e,t,mM,CG),cu(r.length*8===64);{let n=cM(r,Ge(t,11),L(e.byteLength)*io&Te);return cM(r,Ge(t,t.byteLength-cs-11),~(L(e.byteLength)*Oa)&Te)<<L(64)|n}}function hM(e,t){let r=e*t&au;return r&Te^r>>L(64)}function uM(e,t,r){return hM((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+r)&Te,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-r)&Te)}function Sg(e,t,r,n,i){let s=e&Te,o=e>>L(64)&Te;return s+=uM(t,n,i),s^=r.getBigUint64(0,!0)+r.getBigUint64(8,!0),s&=Te,o+=uM(r,Ge(n,16),i),o^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),o&=Te,o<<L(64)|s}function bi(e){let t=e;return t^=t>>L(37),t*=IG,t&=Te,t^=t>>L(32),t}function kg(e){let t=e;return t^=t>>L(33),t*=Oa,t&=Te,t^=t>>L(29),t*=dM,t&=Te,t^=t>>L(32),t}function RG(e,t,r){let n=e.byteLength;cu(n>0&&n<=3);let i=L(e.getUint8(n-1))|L(n<<8)|L(e.getUint8(0)<<16)|L(e.getUint8(n>>1)<<24),s=(i^(L(t.getUint32(0,!0))^L(t.getUint32(4,!0)))+r)&Te,o=(L(t.getUint32(8,!0))^L(t.getUint32(12,!0)))-r;return(kg(($G(TG(i),L(13))^o)&Te)&Te)<<L(64)|kg(s)}function xS(e,t){return e^e>>t}function MG(e,t,r){let n=e.byteLength;cu(n>=4&&n<=8);{let i=e.getUint32(0,!0),s=e.getUint32(n-4,!0),o=((L(i)|L(s)<<L(32))^(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+r&Te)*(io+(L(n)<<L(2)))&au;return o+=(o&Te)<<L(65),o&=au,o^=o>>L(67),xS(xS(o&Te,L(35))*SG&Te,L(28))|bi(o>>L(64))<<L(64)}}function jG(e,t,r){let n=e.byteLength;cu(n>=9&&n<=16);{let i=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+r&Te,s=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-r&Te,o=e.getBigUint64(0,!0),a=e.getBigUint64(n-8,!0),c=(o^a^i)*io,u=(c&Te)+(L(n-1)<<L(54));c=c&(au^Te)|u,a^=s,c+=a+(a&Eg)*(pM-L(1))<<L(64),c&=au,c^=AG(c>>L(64));let l=(c&Te)*Oa;return l+=(c>>L(64))*Oa<<L(64),l&=au,bi(l&Te)|bi(l>>L(64))<<L(64)}}function DG(e,t){let r=e.byteLength;return cu(r<=16),r>8?jG(e,vi,t):r>=4?MG(e,vi,t):r>0?RG(e,vi,t):kg(t^vi.getBigUint64(64,!0)^vi.getBigUint64(72,!0))|kg(t^vi.getBigUint64(80,!0)^vi.getBigUint64(88,!0))<<L(64)}function IS(e){return~e+L(1)&Te}function zG(e,t,r){let n=L(e.byteLength)*io&Te,i=L(e.byteLength-1)/L(32);for(;i>=0;){let a=Number(i);n=Sg(n,Ge(e,16*a),Ge(e,e.byteLength-16*(a+1)),Ge(t,32*a),r),i-=L(1)}let s=n+(n>>L(64))&Te;s=bi(s);let o=(n&Te)*io+(n>>L(64))*SS+(L(e.byteLength)-r&Te)*Oa;return o&=Te,o=IS(bi(o)),s|o<<L(64)}function LG(e,t,r){let n=L(e.byteLength)*io&Te;for(let o=32;o<160;o+=32)n=Sg(n,Ge(e,o-32),Ge(e,o-16),Ge(t,o-32),r);n=bi(n&Te)|bi(n>>L(64))<<L(64);for(let o=160;o<=e.byteLength;o+=32)n=Sg(n,Ge(e,o-32),Ge(e,o-16),Ge(t,3+o-160),r);n=Sg(n,Ge(e,e.byteLength-16),Ge(e,e.byteLength-32),Ge(t,103),IS(r));let i=n+(n>>L(64))&Te;i=bi(i);let s=(n&Te)*io+(n>>L(64))*SS+(L(e.byteLength)-r&Te)*Oa;return s&=Te,s=IS(bi(s)),i|s<<L(64)}function us(e,t=L(0)){let r=new TextEncoder,n=Ge(typeof e=="string"?r.encode(e):e),i=n.byteLength,s=o=>o.toString(16).padStart(32,"0");return i<=16?s(DG(n,t)):i<=128?s(zG(n,vi,t)):i<=240?s(LG(n,vi,t)):s(NG(n,vi))}function Ag(e){return/^[0-9a-f]{32}$/.test(e)}function $a(e,t,r=!0,n=!1){try{return e[t].get()}catch(i){if(i.name===Ve.unminifiable_name){if(n)return i;if(r)return null}throw i}}function qn(e,t,r=!0){if(Array.isArray(t)){let n={};for(let i of t)try{n[i]=$a(e,i,!r)}catch(s){if(s.name===Ve.unminifiable_name)continue}return n}else return $a(e,t)}function*gM(e,t){if(e.graph===jr.PARENT)throw new De("There is no parent graph.");if(e.goto){let r;Array.isArray(e.goto)?r=e.goto:r=[e.goto];for(let n of r)if($t(n))yield[ir,Ut,n];else if(typeof n=="string")yield[ir,`branch:to:${n}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof n}`)}if(e.resume)if(typeof e.resume=="object"&&Object.keys(e.resume).length&&Object.keys(e.resume).every(Ag))for(let[r,n]of Object.entries(e.resume)){let i=t.filter(s=>s[0]===r&&s[1]===Nt).map(s=>s[2]).slice(0,1)??[];i.push(n),yield[r,Nt,i]}else yield[ir,Nt,e.resume];if(e.update){if(typeof e.update!="object"||!e.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(e.update))for(let[r,n]of e.update)yield[ir,r,n];else for(let[r,n]of Object.entries(e.update))yield[ir,r,n]}}function*Tg(e,t){if(t!=null)if(Array.isArray(e)&&typeof t=="object"&&!Array.isArray(t))for(let r in t)e.includes(r)&&(yield[r,t[r]]);else{if(Array.isArray(e))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[e,t]}}function*Og(e,t,r){Array.isArray(e)?(t===!0||t.find(([n,i])=>e.includes(n)))&&(yield qn(r,e)):(t===!0||t.some(([n,i])=>n===e))&&(yield $a(r,e))}function*_M(e,t,r){let n=t.filter(([a,c])=>(a.config===void 0||!a.config.tags?.includes(Be))&&c[0][0]!==Ot&&c[0][0]!==ke);if(!n.length)return;let i;n.some(([a])=>a.writes.some(([c,u])=>c===Zn))?i=n.flatMap(([a])=>a.writes.filter(([c,u])=>c===Zn).map(([c,u])=>[a.name,u])):Array.isArray(e)?i=n.flatMap(([a])=>{let{writes:c}=a,u={};for(let[l]of c)e.includes(l)&&(u[l]=(u[l]||0)+1);return Object.values(u).some(l=>l>1)?c.filter(([l])=>e.includes(l)).map(([l,p])=>[a.name,{[l]:p}]):[[a.name,Object.fromEntries(c.filter(([l])=>e.includes(l)))]]}):i=n.flatMap(([a])=>a.writes.filter(([c,u])=>c===e).map(([c,u])=>[a.name,u]));let s={};for(let[a,c]of i)a in s||(s[a]=[]),s[a].push(c);let o={};for(let a in s)if(s[a].length===1){let[c]=s[a];o[a]=c}else o[a]=s[a];r&&(o.__metadata__={cached:r}),yield o}function $g(e){let t=typeof e[Ae];if(t==="number")return 0;if(t==="string")return"";for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let n=typeof e[r];if(n==="number")return 0;if(n==="string")return"";break}}function uu(e,t){if(Object.keys(e).length>0){let r=$g(t);return Object.fromEntries(Object.entries(t).filter(([n,i])=>i>(e[n]??r)))}else return t}function yM(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}function zr(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function so(e,t){let r=t?.parents??{};return Object.keys(r).length>0?zr(e,{[xr]:{...r,[e.configurable?.checkpoint_ns??""]:e.configurable?.checkpoint_id}}):e}function lu(...e){let t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};let r=new AbortController,n=()=>{let s=t.find(o=>o.aborted)?.reason;r.abort(s),t.forEach(o=>o.removeEventListener("abort",n))};t.forEach(s=>s.addEventListener("abort",n,{once:!0}));let i=t.find(s=>s.aborted);return i&&r.abort(i.reason),{signal:r.signal,dispose:()=>{t.forEach(s=>s.removeEventListener("abort",n))}}}var vM=(e,t)=>{if(!(!e&&!t))return e?t?Array.isArray(e)&&Array.isArray(t)?[...e,...t]:Array.isArray(e)?[...e,t]:Array.isArray(t)?[e,...t]:[e,t]:e:t};var bM=class{func;name;input;retry;cache;callbacks;__lg_type="call";constructor({func:e,name:t,input:r,retry:n,cache:i,callbacks:s}){this.func=e,this.name=t,this.input=r,this.retry=n,this.cache=i,this.callbacks=s}};function wM(e){return typeof e=="object"&&e!==null&&"__lg_type"in e&&e.__lg_type==="call"}function xM(e,t){return new br({name:e,first:new sr({func:r=>t(...r),name:e,trace:!1,recurse:!1}),last:new _t([{channel:Zn,value:Dr}],[Be])})}function IM(e,t){return new sr({func:(r,n)=>t(r,n),name:e,trace:!1,recurse:!1})}var SM=e=>e!==void 0?e+1:1;function UG(e,t){if(t==null)return!1;for(let r of e)if(t[r])return!0;return!1}function FG(e){let t;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t==null?t=e[r]:t=Xp(t,e[r]));return t}function pd(e,t,r){let n=$g(e.channel_versions),i=e.versions_seen[ke]??{},s=!1;if((e.channel_versions[Ae]??n)>(i[Ae]??n))s=!0;else for(let a in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,a)&&e.channel_versions[a]>(i[a]??n)){s=!0;break}let o=r.some(a=>t==="*"?!a.config?.tags?.includes(Be):t.includes(a.name));return s&&o}function ld(e,t,r,n,i=!1){let s=new Set;if(Array.isArray(n))s=new Set(n.filter(a=>r.writes.some(([c,u])=>c===a)));else{for(let[a]of r.writes)if(a===n){s=new Set([a]);break}s=s||new Set}let o;if(i&&s.size>0){let a=Object.fromEntries(Object.entries(t).filter(([l,p])=>s.has(l))),c=Ln(e,a,-1),u=no(a,c);Sr(zn(c),u,[r],void 0,void 0),o=qn({...t,...u},n)}else o=qn(t,n);return o}function ES(e,t,r){for(let[n,i]of r)if([nr,Ut].includes(n)&&i!=null){if(!$t(i))throw new De(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(i)}`);if(!(i.node in t))throw new De(`Invalid node name "${i.node}" in Send packet`)}e(r)}var BG=new Set([id,nr,Nt,ke,Zn,Ot]);function Sr(e,t,r,n,i){r.sort((f,d)=>{let m=f.path?.slice(0,3)||[],h=d.path?.slice(0,3)||[];for(let b=0;b<Math.min(m.length,h.length);b+=1){if(m[b]<h[b])return-1;if(m[b]>h[b])return 1}return m.length-h.length});let s=r.some(f=>f.triggers.length>0),o=td(t);for(let f of r){e.versions_seen[f.name]??={};for(let d of f.triggers)d in e.channel_versions&&(e.versions_seen[f.name][d]=e.channel_versions[d])}let a=FG(e.channel_versions),c=new Set(r.flatMap(f=>f.triggers).filter(f=>!eM.includes(f))),u=!1;for(let f of c)f in o&&o[f].consume()&&n!==void 0&&(e.channel_versions[f]=n(a),u=!0);let l={};for(let f of r)for(let[d,m]of f.writes)BG.has(d)||d in o&&(l[d]??=[],l[d].push(m));a!=null&&n!=null&&(a=u?n(a):a);let p=new Set;for(let[f,d]of Object.entries(l))if(f in o){let m=o[f],h;try{h=m.update(d)}catch(b){if(b.name===De.unminifiable_name){let _=new De(`Invalid update for channel "${f}" with values ${JSON.stringify(d)}: ${b.message}`);throw _.lc_error_code=b.lc_error_code,_}else throw b}h&&n!==void 0&&(e.channel_versions[f]=n(a),m.isAvailable()&&p.add(f))}if(s)for(let f in o){if(!Object.prototype.hasOwnProperty.call(o,f))continue;let d=o[f];d.isAvailable()&&!p.has(f)&&d.update([])&&n!==void 0&&(e.channel_versions[f]=n(a),d.isAvailable()&&p.add(f))}if(s&&!UG(p,i))for(let f in o){if(!Object.prototype.hasOwnProperty.call(o,f))continue;let d=o[f];d.finish()&&n!==void 0&&(e.channel_versions[f]=n(a),d.isAvailable()&&p.add(f))}return p}function*VG(e,t,r){if(r.updatedChannels!=null&&r.triggerToNodes!=null){let n=new Set;for(let i of r.updatedChannels){let s=r.triggerToNodes[i];for(let o of s??[])n.add(o)}yield*[...n].sort();return}if(!(()=>{for(let n in e.channel_versions)if(e.channel_versions[n]!==null)return!1;return!0})())for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(yield n)}function oo(e,t,r,n,i,s,o){let a={},c=n[Ut];if(c?.isAvailable()){let u=c.get().length;for(let l=0;l<u;l+=1){let p=Cg([nr,l],e,t,r,n,i,s,o);p!==void 0&&(a[p.id]=p)}}for(let u of VG(e,r,o)){let l=Cg([sd,u],e,t,r,n,i,s,o);l!==void 0&&(a[l.id]=l)}return a}function Cg(e,t,r,n,i,s,o,a){let{step:c,checkpointer:u,manager:l}=a,p=s.configurable??{},f=p.checkpoint_ns??"";if(e[0]===nr&&wM(e[e.length-1])){let d=e[e.length-1],m=xM(d.name,d.func),h=[nr],b=f===""?d.name:`${f}${et}${d.name}`,_=Mi(JSON.stringify([b,c.toString(),d.name,nr,e[1],e[2]]),t.id),y=`${b}${Ir}${_}`,x=[...e.slice(0,3),!0],I={langgraph_step:c,langgraph_node:d.name,langgraph_triggers:h,langgraph_path:x,langgraph_checkpoint_ns:y};if(o){let A=[];return{name:d.name,input:d.input,proc:m,writes:A,config:Ne(Dt(s,{metadata:I,store:a.store??s.store}),{runName:d.name,callbacks:l?.getChild(`graph:step:${c}`),configurable:{[Ea]:_,[bn]:j=>ES(O=>A.push(...O),n,j),[Vn]:(j,O=!1)=>ld(t,i,{name:d.name,writes:A,triggers:h,path:x},j,O),[ft]:u??p[ft],[xr]:{...p[xr],[f]:t.id},[Wr]:kS({pendingWrites:r??[],taskId:_,currentTaskInput:d.input,resumeMap:s.configurable?.[iu],namespaceHash:us(y)}),[su]:t.channel_values[ka],checkpoint_id:void 0,checkpoint_ns:y}}),triggers:h,retry_policy:d.retry,cache_key:d.cache?{key:us((d.cache.keyFunc??JSON.stringify)([d.input])),ns:[hg,d.name??"__dynamic__"],ttl:d.cache.ttl}:void 0,id:_,path:x,writers:[]}}else return{id:_,name:d.name,interrupts:[],path:x}}else if(e[0]===nr){let d=typeof e[1]=="number"?e[1]:parseInt(e[1],10);if(!i[Ut]?.isAvailable())return;let m=i[Ut].get();if(d<0||d>=m.length)return;let h=_g(m[d])&&!$t(m[d])?new Sa(m[d].node,m[d].args):m[d];if(!_g(h)){console.warn(`Ignoring invalid packet ${JSON.stringify(h)} in pending sends.`);return}if(!(h.node in n)){console.warn(`Ignoring unknown node name ${h.node} in pending sends.`);return}let b=[nr],_=f===""?h.node:`${f}${et}${h.node}`,y=Mi(JSON.stringify([_,c.toString(),h.node,nr,d.toString()]),t.id),x=`${_}${Ir}${y}`,I={langgraph_step:c,langgraph_node:h.node,langgraph_triggers:b,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:x};if(o){let A=n[h.node],j=A.getNode();if(j!==void 0){A.metadata!==void 0&&(I={...I,...A.metadata});let O=[];return{name:h.node,input:h.args,proc:j,subgraphs:A.subgraphs,writes:O,config:Ne(Dt(s,{metadata:I,tags:A.tags,store:a.store??s.store}),{runName:h.node,callbacks:l?.getChild(`graph:step:${c}`),configurable:{[Ea]:y,[bn]:w=>ES(U=>O.push(...U),n,w),[Vn]:(w,U=!1)=>ld(t,i,{name:h.node,writes:O,triggers:b,path:e},w,U),[ft]:u??p[ft],[xr]:{...p[xr],[f]:t.id},[Wr]:kS({pendingWrites:r??[],taskId:y,currentTaskInput:h.args,resumeMap:s.configurable?.[iu],namespaceHash:us(x)}),[su]:t.channel_values[ka],checkpoint_id:void 0,checkpoint_ns:x}}),triggers:b,retry_policy:A.retryPolicy,cache_key:A.cachePolicy?{key:us((A.cachePolicy.keyFunc??JSON.stringify)([h.args])),ns:[hg,A.name??"__dynamic__",h.node],ttl:A.cachePolicy.ttl}:void 0,id:y,path:e,writers:A.getWriters()}}}else return{id:y,name:h.node,interrupts:[],path:e}}else if(e[0]===sd){let d=e[1].toString(),m=n[d];if(m===void 0)return;if(r?.length){let y=f===""?d:`${f}${et}${d}`,x=Mi(JSON.stringify([y,c.toString(),d,sd,d]),t.id);if(r.some(I=>I[0]===x&&I[1]!==Ot))return}let h=$g(t.channel_versions);if(h===void 0)return;let b=t.versions_seen[d]??{},_=m.triggers.find(y=>i[y].isAvailable()?(t.channel_versions[y]??h)>(b[y]??h):!1);if(_!==void 0){let y=ZG(m,i,o);if(y===void 0)return;let x=f===""?d:`${f}${et}${d}`,I=Mi(JSON.stringify([x,c.toString(),d,sd,[_]]),t.id),A=`${x}${Ir}${I}`,j={langgraph_step:c,langgraph_node:d,langgraph_triggers:[_],langgraph_path:e,langgraph_checkpoint_ns:A};if(o){let O=m.getNode();if(O!==void 0){m.metadata!==void 0&&(j={...j,...m.metadata});let w=[];return{name:d,input:y,proc:O,subgraphs:m.subgraphs,writes:w,config:Ne(Dt(s,{metadata:j,tags:m.tags,store:a.store??s.store}),{runName:d,callbacks:l?.getChild(`graph:step:${c}`),configurable:{[Ea]:I,[bn]:U=>ES(P=>{w.push(...P)},n,U),[Vn]:(U,P=!1)=>ld(t,i,{name:d,writes:w,triggers:[_],path:e},U,P),[ft]:u??p[ft],[xr]:{...p[xr],[f]:t.id},[Wr]:kS({pendingWrites:r??[],taskId:I,currentTaskInput:y,resumeMap:s.configurable?.[iu],namespaceHash:us(A)}),[su]:t.channel_values[ka],checkpoint_id:void 0,checkpoint_ns:A}}),triggers:[_],retry_policy:m.retryPolicy,cache_key:m.cachePolicy?{key:us((m.cachePolicy.keyFunc??JSON.stringify)([y])),ns:[hg,m.name??"__dynamic__",d],ttl:m.cachePolicy.ttl}:void 0,id:I,path:e,writers:m.getWriters()}}}else return{id:I,name:d,interrupts:[],path:e}}}}function ZG(e,t,r){let n;if(typeof e.channels=="object"&&!Array.isArray(e.channels)){n={};for(let[i,s]of Object.entries(e.channels))if(e.triggers.includes(s))try{n[i]=$a(t,s,!1)}catch(o){if(o.name===Ve.unminifiable_name)return;throw o}else if(s in t)try{n[i]=$a(t,s,!1)}catch(o){if(o.name===Ve.unminifiable_name)continue;throw o}}else if(Array.isArray(e.channels)){let i=!1;for(let s of e.channels)try{n=$a(t,s,!1),i=!0;break}catch(o){if(o.name===Ve.unminifiable_name)continue;throw o}if(!i)return}else throw new Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return r&&e.mapper!==void 0&&(n=e.mapper(n)),n}function EM(e,t){if(typeof e.args!="object"||e.args===null)return e;let r={};for(let[n,i]of Object.entries(e.args)){let s=t[n];(!s||s.lc_graph_name!=="UntrackedValue")&&(r[n]=i)}return new Sa(e.node,r)}function kS({pendingWrites:e,taskId:t,currentTaskInput:r,resumeMap:n,namespaceHash:i}){let s=e.find(([a,c])=>a===ir&&c===Nt)?.[2],o={callCounter:0,interruptCounter:-1,resume:(()=>{let a=e.filter(([c,u])=>c===t&&u===Nt).flatMap(([c,u,l])=>l);if(n!=null&&i in n){let c=n[i];a.push(c)}return a})(),nullResume:s,subgraphCounter:0,currentTaskInput:r,consumeNullResume:()=>{if(o.nullResume)return delete o.nullResume,e.splice(e.findIndex(([a,c])=>a===ir&&c===Nt),1),s}};return o}var dd={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},fd=(e,t)=>`${e.start}${t}${e.end}`;function*AS(e){for(let{id:t,name:r,input:n,config:i,triggers:s,writes:o}of e)i?.tags?.includes(Be)||(yield{id:t,name:r,input:n,triggers:s,interrupts:o.filter(([a,c])=>a===t&&c===ke).map(([,a])=>a)})}function GG(e){return typeof e!="object"||e===null?!1:"$writes"in e&&Array.isArray(e.$writes)}function kM(e){let t={};for(let[r,n]of e){let i=String(r);if(i in t){let s=GG(t[i])?t[i].$writes:[t[i]];s.push(n),t[i]={$writes:s}}else t[i]=n}return t}function*AM(e,t){for(let[{id:r,name:n,config:i},s]of e)i?.tags?.includes(Be)||(yield{id:r,name:n,result:kM(s.filter(([o])=>Array.isArray(t)?t.includes(o):o===t)),interrupts:s.filter(o=>o[0]===ke).map(o=>o[1])})}function*TM(e,t,r,n,i,s,o,a){function c(p){let f={};return p.callbacks!=null&&(f.callbacks=p.callbacks),p.configurable!=null&&(f.configurable=p.configurable),p.maxConcurrency!=null&&(f.max_concurrency=p.maxConcurrency),p.metadata!=null&&(f.metadata=p.metadata),p.recursionLimit!=null&&(f.recursion_limit=p.recursionLimit),p.runId!=null&&(f.run_id=p.runId),p.runName!=null&&(f.run_name=p.runName),p.tags!=null&&(f.tags=p.tags),f}let u=e.configurable?.checkpoint_ns,l={};for(let p of i){if(!(p.subgraphs?.length?p.subgraphs:[p.proc]).find(wg))continue;let f=`${p.name}:${p.id}`;u&&(f=`${u}|${f}`),l[p.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:f}}}yield{config:c(e),values:qn(t,r),metadata:n,next:i.map(p=>p.name),tasks:TS(i,s,l,a),parentConfig:o?c(o):void 0}}function TS(e,t,r,n){return e.map(i=>{let s=t.find(([u,l])=>u===i.id&&l===Ot)?.[2],o=t.filter(([u,l])=>u===i.id&&l===ke).map(([,,u])=>u),a=(()=>{if(s||o.length||!t.length)return;let u=t.findIndex(([l,p])=>l===i.id&&p===Zn);if(u>=0)return t[u][2];if(typeof n=="string")return t.find(([l,p])=>l===i.id&&p===n)?.[2];if(Array.isArray(n)){let l=t.filter(([p,f])=>p===i.id&&n.includes(f)).map(([,p,f])=>[p,f]);return l.length?kM(l):void 0}})();if(s)return{id:i.id,name:i.name,path:i.path,error:s,interrupts:o,result:a};let c=r?.[i.id];return{id:i.id,name:i.name,path:i.path,interrupts:o,...c!==void 0?{state:c}:{},result:a}})}function OM(e,t,r){console.log([`${fd(dd.blue,`[${e}:checkpoint]`)}`,`\x1B[1m State at the end of step ${e}:\x1B[0m
215
- `,JSON.stringify(qn(t,r),null,2)].join(""))}function Pg(e,t){let r=t.length;console.log([`${fd(dd.blue,`[${e}:tasks]`)}`,`\x1B[1m Starting step ${e} with ${r} task${r===1?"":"s"}:\x1B[0m
216
- `,t.map(n=>`- ${fd(dd.green,String(n.name))} -> ${JSON.stringify(n.input,null,2)}`).join(`
217
- `)].join(""))}function $M(e,t,r){let n={};for(let[i,s]of t)r.includes(i)&&(n[i]||(n[i]=[]),n[i].push(s));console.log([`${fd(dd.blue,`[${e}:writes]`)}`,`\x1B[1m Finished step ${e} with writes to ${Object.keys(n).length} channel${Object.keys(n).length!==1?"s":""}:\x1B[0m
218
- `,Object.entries(n).map(([i,s])=>`- ${fd(dd.yellow,i)} -> ${s.map(o=>JSON.stringify(o)).join(", ")}`).join(`
219
- `)].join(""))}var $S=class extends kt{_abortController;_innerReader;constructor(e,t){let r=e.getReader(),n=t??new AbortController;super({start(i){return s();function s(){return r.read().then(({done:o,value:a})=>{if(o){i.close();return}return i.enqueue(a),s()})}}}),this._abortController=n,this._innerReader=r}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},Ng=class extends kt{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(e){let t,r=new Promise(n=>{t=n});super({start:n=>{t(n)}}),r.then(n=>{this.controller=n}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this.passthroughFn?.(e),this.controller.enqueue(e)}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){this.controller.error(e)}};function KG(e){return JSON.stringify(e,function(t,r){let n=this[t];if(n!=null&&typeof n=="object"&&"toDict"in n&&typeof n.toDict=="function"){let{type:i,data:s}=n.toDict();return{...s,type:i}}return r})}function qG(e){return e instanceof Error?{error:e.name,message:e.message}:{error:"Error",message:JSON.stringify(e)}}function CS(e){return typeof e!="object"||e==null?!1:"configurable"in e&&typeof e.configurable=="object"&&e.configurable!=null}function OS(e){return!CS(e)||!e.configurable.thread_id?null:{thread_id:e.configurable.thread_id,checkpoint_ns:e.configurable.checkpoint_ns||"",checkpoint_id:e.configurable.checkpoint_id||null,checkpoint_map:e.configurable.checkpoint_map||null}}function CM(e){if(CS(e)){let t=Object.fromEntries(Object.entries(e.configurable).filter(([n])=>!n.startsWith("__"))),r={...e,configurable:t};return delete r.callbacks,r}return e}function PM(e){let t={...e,checkpoint:OS(e.config),parent_checkpoint:OS(e.parentConfig),config:CM(e.config),parent_config:CM(e.parentConfig),tasks:e.tasks.map(r=>{if(CS(r.state)){let n=OS(r.state);if(n!=null){let i={...r,checkpoint:n};return delete i.state,i}}return r})};return delete t.parentConfig,t}function NM(e){let t=new TextEncoder;return new ReadableStream({async start(r){let n=i=>{r.enqueue(t.encode(`event: ${i.event}
220
- data: ${KG(i.data)}
221
-
222
- `))};try{for await(let i of e){let[s,o,a]=i,c=a;if(o==="debug"){let u=a;u.type==="checkpoint"&&(c={...u,payload:PM(u.payload)})}o==="checkpoints"&&(c=PM(a)),n({event:s?.length?`${o}|${s.join("|")}`:o,data:c})}}catch(i){n({event:"error",data:qG(i)})}r.close()}})}var Rg=Symbol.for("INPUT_DONE"),PS=Symbol.for("INPUT_RESUMING"),HG=25;function WG(...e){return new Ng({passthroughFn:t=>{for(let r of e)r.modes.has(t[1])&&r.push(t)},modes:new Set(e.flatMap(t=>Array.from(t.modes)))})}var JG=class extends dg{cache;queue=Promise.resolve();constructor(e){super(),this.cache=e}async get(e){return this.enqueueOperation("get",e)}async set(e){return this.enqueueOperation("set",e)}async clear(e){return this.enqueueOperation("clear",e)}async stop(){await this.queue}enqueueOperation(e,...t){let r=this.queue.then(()=>this.cache[e](...t));return this.queue=r.then(()=>{},()=>{}),r}},RM=class MM{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status="pending";tasks={};stream;checkpointerPromises=[];isNested;_checkpointerChainedPromise=Promise.resolve();store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let t=!1;if(Ae in this.checkpoint.channel_versions)t=!0;else for(let a in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,a)){t=!0;break}let r=this.config.configurable?.[yi]!==void 0&&this.config.configurable?.[yi],n=this.input===null||this.input===void 0,i=Pt(this.input)&&this.input.resume!=null,s=this.input===PS,o=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return t&&(r||n||i||s||o)}constructor(t){this.input=t.input,this.checkpointer=t.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=SM,this.checkpoint=t.checkpoint,this.checkpointMetadata=t.checkpointMetadata,this.checkpointPreviousVersions=t.checkpointPreviousVersions,this.channels=t.channels,this.checkpointPendingWrites=t.checkpointPendingWrites,this.step=t.step,this.stop=t.stop,this.config=t.config,this.checkpointConfig=t.checkpointConfig,this.isNested=t.isNested,this.manager=t.manager,this.outputKeys=t.outputKeys,this.streamKeys=t.streamKeys,this.nodes=t.nodes,this.skipDoneTasks=t.skipDoneTasks,this.store=t.store,this.cache=t.cache?new JG(t.cache):void 0,this.stream=t.stream,this.checkpointNamespace=t.checkpointNamespace,this.prevCheckpointConfig=t.prevCheckpointConfig,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.durability=t.durability,this.debug=t.debug,this.triggerToNodes=t.triggerToNodes}static async initialize(t){let{config:r,stream:n}=t;n!==void 0&&r.configurable?.[nu]!==void 0&&(n=WG(n,r.configurable[nu]));let i=r.configurable?!("checkpoint_id"in r.configurable):!0,s=r.configurable?.[Wr];r.configurable&&s&&(s.subgraphCounter>0&&(r=zr(r,{[Jr]:[r.configurable[Jr],s.subgraphCounter.toString()].join(et)})),s.subgraphCounter+=1);let o=Vn in(r.configurable??{});!o&&r.configurable?.checkpoint_ns!==void 0&&r.configurable?.checkpoint_ns!==""&&(r=zr(r,{checkpoint_ns:"",checkpoint_id:void 0}));let a=r;r.configurable?.[xr]!==void 0&&r.configurable?.[xr]?.[r.configurable?.checkpoint_ns]&&(a=zr(r,{checkpoint_id:r.configurable[xr][r.configurable?.checkpoint_ns]}));let c=r.configurable?.checkpoint_ns?.split(et)??[],u=await t.checkpointer?.getTuple(a)??{config:r,checkpoint:tu(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};a={...r,...u.config,configurable:{checkpoint_ns:"",...r.configurable,...u.config.configurable}};let l=u.parentConfig,p=zn(u.checkpoint),f={...u.metadata},d=u.pendingWrites??[],m=no(t.channelSpecs,p),h=(f.step??0)+1,b=h+(r.recursionLimit??HG)+1,_={...p.channel_versions},y=t.store?new pg(t.store):void 0;return y&&await y.start(),new MM({input:t.input,config:r,checkpointer:t.checkpointer,checkpoint:p,checkpointMetadata:f,checkpointConfig:a,prevCheckpointConfig:l,checkpointNamespace:c,channels:m,isNested:o,manager:t.manager,skipDoneTasks:i,step:h,stop:b,checkpointPreviousVersions:_,checkpointPendingWrites:d,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:n,store:y,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes})}_checkpointerPutAfterPrevious(t){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(t.config,t.checkpoint,t.metadata,t.newVersions)),this.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(t,r){let n=r;if(n.length===0)return;n.every(([c])=>c in Yp)&&(n=Array.from(new Map(n.map(c=>[c[0],c])).values()));let i=!1;for(let c in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,c)&&this.channels[c].lc_graph_name==="UntrackedValue"){i=!0;break}let s=n;i&&(s=n.filter(([c])=>{let u=this.channels[c];return!u||u.lc_graph_name!=="UntrackedValue"}).map(([c,u])=>c===Ut&&$t(u)?[c,EM(u,this.channels)]:[c,u])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(c=>c[0]!==t);for(let[c,u]of s)this.checkpointPendingWrites.push([t,c,u]);let o=zr(this.checkpointConfig,{[Jr]:this.config.configurable?.checkpoint_ns??"",[gg]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(o,s,t)),this.tasks&&this._outputWrites(t,n),!r.length||!this.cache||!this.tasks)return;let a=this.tasks[t];a==null||a.cache_key==null||r[0][0]===Ot||r[0][0]===ke||this.cache.set([{key:[a.cache_key.ns,a.cache_key.key],value:a.writes,ttl:a.cache_key.ttl}])}_outputWrites(t,r,n=!1){let i=this.tasks[t];if(i!==void 0){if(i.config!==void 0&&(i.config.tags??[]).includes(Be))return;if(r.length>0)if(r[0][0]===ke){if(i.path?.[0]===nr&&i.path?.[i.path.length-1]===!0)return;let s=r.filter(o=>o[0]===ke).flatMap(o=>o[1]);this._emit([["updates",{[ke]:s}],["values",{[ke]:s}]])}else r[0][0]!==Ot&&this._emit(Aa(as(_M(this.outputKeys,[[i,r]],n),"updates")));n||this._emit(Aa(as(AM([[i,r]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];let t=[],r=([o,a])=>`ns:${o.join(",")}|key:${a}`,n=[],i={};for(let o of Object.values(this.tasks))o.cache_key!=null&&!o.writes.length&&(n.push([o.cache_key.ns,o.cache_key.key]),i[r([o.cache_key.ns,o.cache_key.key])]=o);if(n.length===0)return[];let s=await this.cache.get(n);for(let{key:o,value:a}of s){let c=i[r(o)];c!=null&&(c.writes.push(...a),t.push({task:c,result:a}))}return t}async tick(t){this.store&&!this.store.isRunning&&await this.store?.start();let{inputKeys:r=[]}=t;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![Rg,PS].includes(this.input))await this._first(r);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new Ni;if(Object.values(this.tasks).every(i=>i.writes.length>0)){let i=Object.values(this.tasks).flatMap(o=>o.writes);this.updatedChannels=Sr(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);let s=await Gn(as(Og(this.outputKeys,i,this.channels),"values"));if(this._emit(s),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),pd(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new Ni;this.config.configurable?.[yi]!==void 0&&delete this.config.configurable?.[yi]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;if(this.tasks=oo(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream,triggerToNodes:this.triggerToNodes,updatedChannels:this.updatedChannels}),this.checkpointer&&this._emit(await Gn(as(TM(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(let[i,s,o]of this.checkpointPendingWrites){if(s===Ot||s===ke||s===Nt)continue;let a=Object.values(this.tasks).find(c=>c.id===i);a&&a.writes.push([s,o])}for(let i of Object.values(this.tasks))i.writes.length>0&&this._outputWrites(i.id,i.writes,!0)}if(Object.values(this.tasks).every(i=>i.writes.length>0))return this.tick({inputKeys:r});if(pd(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new Ni;let n=await Gn(as(AS(Object.values(this.tasks)),"tasks"));return this._emit(n),!0}async finishAndHandleError(t){this.durability==="exit"&&(!this.isNested||typeof t<"u"||this.checkpointNamespace.every(n=>!n.includes(Ir)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());let r=this._suppressInterrupt(t);return(r||t===void 0)&&(this.output=qn(this.channels,this.outputKeys)),r&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(n=>n.writes.length>0)&&(this.updatedChannels=Sr(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(Aa(as(Og(this.outputKeys,Object.values(this.tasks).flatMap(n=>n.writes),this.channels),"values")))),Ri(t)&&!t.interrupts.length&&this._emit([["updates",{[ke]:[]}],["values",{[ke]:[]}]])),r}async acceptPush(t,r,n){if(this.interruptAfter?.length>0&&pd(this.checkpoint,this.interruptAfter,[t])){this.toInterrupt.push(t);return}let i=Cg([nr,t.path??[],r,t.id,n],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,t.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!i)return;if(this.interruptBefore?.length>0&&pd(this.checkpoint,this.interruptBefore,[i])){this.toInterrupt.push(i);return}this._emit(Aa(as(AS([i]),"tasks"))),this.debug&&Pg(this.step,[i]),this.tasks[i.id]=i,this.skipDoneTasks&&this._matchWrites({[i.id]:i});let s=await this._matchCachedWrites();for(let{task:o}of s)this._outputWrites(o.id,o.writes,!0);return i}_suppressInterrupt(t){return Ri(t)&&!this.isNested}async _first(t){let{configurable:r}=this.config,n=r?.[Wr];if(n&&n.nullResume!==void 0&&this.putWrites(ir,[[Nt,n.nullResume]]),Pt(this.input)){let o=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(Ag)&&(this.config.configurable??={},this.config.configurable[iu]=this.input.resume),o&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");let a={};for(let[c,u,l]of gM(this.input,this.checkpointPendingWrites))a[c]??=[],a[c].push([u,l]);if(Object.keys(a).length===0)throw new Gd("Received empty Command input");for(let[c,u]of Object.entries(a))this.putWrites(c,u)}let i=(this.checkpointPendingWrites??[]).filter(o=>o[0]===ir).map(o=>o.slice(1));i.length>0&&Sr(this.checkpoint,this.channels,[{name:Bn,writes:i,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let s=Pt(this.input)&&i.length>0;if(this.isResuming||s){for(let a in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,a)&&this.checkpoint.channel_versions[a]!==void 0){let c=this.checkpoint.channel_versions[a];this.checkpoint.versions_seen[ke]={...this.checkpoint.versions_seen[ke],[a]:c}}let o=await Gn(as(Og(this.outputKeys,!0,this.channels),"values"));this._emit(o)}if(this.isResuming)this.input=PS;else if(s)await this._putCheckpoint({source:"input"}),this.input=Rg;else{let o=await Gn(Tg(t,this.input));if(o.length>0){let a=oo(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=Sr(this.checkpoint,this.channels,Object.values(a).concat([{name:Bn,writes:o,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=Rg}else if(yi in(this.config.configurable??{}))this.input=Rg;else throw new Gd(`Received no input writes for ${JSON.stringify(t,null,2)}`)}this.isNested||(this.config=zr(this.config,{[yi]:this.isResuming}))}_emit(t){for(let[r,n]of t)if(this.stream.modes.has(r)&&this.stream.push([this.checkpointNamespace,r,n]),(r==="checkpoints"||r==="tasks")&&this.stream.modes.has("debug")){let i=r==="checkpoints"?this.step-1:this.step,s=new Date().toISOString(),o=r==="checkpoints"?"checkpoint":typeof n=="object"&&n!=null&&"result"in n?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:i,type:o,timestamp:s,payload:n}])}}_putCheckpoint(t){let r=this.checkpointMetadata===t,n=this.checkpointer!=null&&(this.durability!=="exit"||r),i=s=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=zr(this.checkpointConfig,{[Jr]:this.config.configurable?.checkpoint_ns??""});let o={...this.checkpoint.channel_versions},a=uu(this.checkpointPreviousVersions,o);this.checkpointPreviousVersions=o,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:zn(s),metadata:{...this.checkpointMetadata},newVersions:a}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};r||(this.checkpointMetadata={...t,step:this.step,parents:this.config.configurable?.[xr]??{}}),this.checkpoint=Ln(this.checkpoint,n?this.channels:void 0,this.step,r?{id:this.checkpoint.id}:void 0),n&&i(this.checkpoint),r||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;let t=zr(this.checkpointConfig,{[Jr]:this.config.configurable?.checkpoint_ns??"",[gg]:this.checkpoint.id}),r={};for(let[n,i,s]of this.checkpointPendingWrites)r[n]??=[],r[n].push([i,s]);for(let[n,i]of Object.entries(r))this.checkpointerPromises.push(this.checkpointer.putWrites(t,i,n))}_matchWrites(t){for(let[r,n,i]of this.checkpointPendingWrites){if(n===Ot||n===ke||n===Nt)continue;let s=Object.values(t).find(o=>o.id===r);s&&s.writes.push([n,i])}for(let r of Object.values(t))r.writes.length>0&&this._outputWrites(r.id,r.writes,!0)}};function XG(e){return ot(e?.message)}var jM=class extends zi{name="StreamMessagesHandler";streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(e){super(),this.streamFn=e}_emit(e,t,r,n=!1){if(n&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let i=t.id;r!=null&&(Mo(t)?i??=`run-${r}-tool-${t.tool_call_id}`:((i==null||i===`run-${r}`)&&(i=this.stableMessageIdMap[r]??i??`run-${r}`),this.stableMessageIdMap[r]??=i)),i!==t.id&&(t.id=i,t.lc_kwargs.id=i),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],"messages",[t,e[1]]])}handleChatModelStart(e,t,r,n,i,s,o,a){o&&(!s||!s.includes(Q1)&&!s.includes("nostream"))&&(this.metadatas[r]=[o.langgraph_checkpoint_ns.split("|"),{tags:s,name:a,...o}])}handleLLMNewToken(e,t,r,n,i,s){let o=s?.chunk;this.emittedChatModelRunIds[r]=!0,this.metadatas[r]!==void 0&&(XG(o)?this._emit(this.metadatas[r],o.message,r):this._emit(this.metadatas[r],new nt({content:e}),r))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let r=e.generations?.[0]?.[0];ot(r?.message)&&this._emit(this.metadatas[t],r?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,r,n,i,s,o,a){if(s!==void 0&&a===s.langgraph_node&&(i===void 0||!i.includes(Be))&&(this.metadatas[r]=[s.langgraph_checkpoint_ns.split("|"),{tags:i,name:a,...s}],typeof t=="object")){for(let c of Object.values(t))if((ot(c)||Di(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(let u of c)(ot(u)||Di(u))&&u.id!==void 0&&(this.seen[u.id]=u)}}handleChainEnd(e,t){let r=this.metadatas[t];if(delete this.metadatas[t],r!==void 0){if(ot(e))this._emit(r,e,t,!0);else if(Array.isArray(e))for(let n of e)ot(n)&&this._emit(r,n,t,!0);else if(e!=null&&typeof e=="object"){for(let n of Object.values(e))if(ot(n))this._emit(r,n,t,!0);else if(Array.isArray(n))for(let i of n)ot(i)&&this._emit(r,i,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};var YG=500,QG=2,e5=128e3,t5=3,r5=[400,401,402,403,404,405,406,407,409],n5=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e.name==="GraphValueError"||e?.code==="ECONNABORTED")return!1;let t=e?.response?.status??e?.status;return!(t&&r5.includes(+t)||e?.error?.code==="insufficient_quota")};async function NS(e,t,r,n){let i=e.retry_policy??t,s=i!==void 0?i.initialInterval??YG:0,o=0,a,c,{config:u}=e;for(r&&(u=zr(u,r)),u={...u,signal:n};!n?.aborted;){e.writes.splice(0,e.writes.length),a=void 0;try{c=await e.proc.invoke(e.input,u);break}catch(l){if(a=l,a.pregelTaskId=e.id,O_(a)){let d=u?.configurable?.checkpoint_ns,m=a.command;if(m.graph===d){for(let h of e.writers)await h.invoke(m,u);a=void 0;break}else if(m.graph===jr.PARENT){let h=rM(d);a.command=new jr({...a.command,graph:h})}}if(Co(a)||i===void 0||(o+=1,o>=(i.maxAttempts??t5))||!(i.retryOn??n5)(a))break;s=Math.min(i.maxInterval??e5,s*(i.backoffFactor??QG));let p=i.jitter?Math.floor(s+Math.random()*1e3):s;await new Promise(d=>setTimeout(d,p));let f=a.name??a.constructor.unminifiable_name??a.constructor.name;(i?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${s.toFixed(2)}ms (attempt ${o}) after ${f}: ${a}`),u=zr(u,{[yi]:!0})}}return{task:e,result:c,error:a,signalAborted:n?.aborted}}var RS=Symbol.for("promiseAdded");function i5(){let e={next:()=>{},wait:Promise.resolve(RS)};function t(r){e.next=()=>{e.wait=new Promise(t),r(RS)}}return e.wait=new Promise(t),e}var DM=class{nodeFinished;loop;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){let{timeout:t,retryPolicy:r,onStepWrite:n,maxConcurrency:i}=e,s=new Set,o,a=new AbortController,c=a.signal,u=t?AbortSignal.timeout(t):void 0,l=Object.values(this.loop.tasks).filter(m=>m.writes.length===0),{signals:p,disposeCombinedSignal:f}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:u,signal:e.signal}),d=this._executeTasksWithRetry(l,{signals:p,retryPolicy:r,maxConcurrency:i});for await(let{task:m,error:h,signalAborted:b}of d)this._commit(m,h),Ri(h)||Co(h)&&!Ri(o)?o=h:h&&(s.size===0||!b)&&(a.abort(),s.add(h));if(f?.(),n?.(this.loop.step,Object.values(this.loop.tasks).map(m=>m.writes).flat()),s.size===1)throw Array.from(s)[0];if(s.size>1)throw new AggregateError(Array.from(s),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(Ri(o)||Co(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:r}){let n=this.loop.config.configurable?.[_S]??{},i=n.externalAbortSignal??r,s=t??n.timeoutAbortSignal,{signal:o,dispose:a}=lu(i,s,e),c={externalAbortSignal:i,timeoutAbortSignal:s,composedAbortSignal:o};return this.loop.config=zr(this.loop.config,{[_S]:c}),{signals:c,disposeCombinedSignal:a}}async*_executeTasksWithRetry(e,t){let{retryPolicy:r,maxConcurrency:n,signals:i}=t??{},s=i5(),o={},a={executingTasksMap:o,barrier:s,retryPolicy:r,scheduleTask:async(f,d,m)=>this.loop.acceptPush(f,d,m)};if(i?.composedAbortSignal?.aborted)throw new Error("Abort");let c=0,u,l=lu(i?.externalAbortSignal,i?.timeoutAbortSignal),p=l.signal?new Promise((f,d)=>{u=()=>d(new Error("Abort")),l.signal?.addEventListener("abort",u,{once:!0})}):void 0;for(;(c===0||Object.keys(o).length>0)&&e.length;){for(;Object.values(o).length<(n??e.length)&&c<e.length;c+=1){let d=e[c];o[d.id]=NS(d,r,{[nd]:zM?.bind(a,this,d)},i?.composedAbortSignal).catch(m=>({task:d,error:m,signalAborted:i?.composedAbortSignal?.aborted}))}let f=await Promise.race([...Object.values(o),...p?[p]:[],s.wait]);f!==RS&&(yield f,u!=null&&(l.signal?.removeEventListener("abort",u),l.dispose?.()),delete o[f.task.id])}}_commit(e,t){if(t!==void 0)if(Ri(t)){if(t.interrupts.length){let r=t.interrupts.map(i=>[ke,i]),n=e.writes.filter(i=>i[0]===Nt);n.length&&r.push(...n),this.loop.putWrites(e.id,r)}}else Co(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[Ot,{message:t.message,name:t.name}]]);else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes(Be))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([id,null]),this.loop.putWrites(e.id,e.writes)}};async function zM(e,t,r,n,i,s={}){let o=t.config?.configurable?.[Wr];if(!o)throw new Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let a=o.callCounter;o.callCounter+=1;let c=new bM({func:r,name:n,input:i,cache:s.cache,retry:s.retry,callbacks:s.callbacks}),u=await this.scheduleTask(t,a,c);if(!u)return;let l=this.executingTasksMap[u.id];if(l!==void 0)return l;if(u.writes.length>0){let p=u.writes.filter(([d])=>d===Zn),f=u.writes.filter(([d])=>d===Ot);if(p.length>0){if(p.length===1)return Promise.resolve(p[0][1]);throw new Error(`BUG: multiple returns found for task ${u.name}__${u.id}`)}if(f.length>0){if(f.length===1){let d=f[0][1],m=d instanceof Error?d:new Error(String(d));return Promise.reject(m)}throw new Error(`BUG: multiple errors found for task ${u.name}__${u.id}`)}return}else{let p=NS(u,s.retry,{[nd]:zM.bind(this,e,u)});return this.executingTasksMap[u.id]=p,this.barrier.next(),p.then(({result:f,error:d})=>d?Promise.reject(d):f)}}var ls=class extends Error{constructor(e){super(e),this.name="GraphValidationError"}};function LM({nodes:e,channels:t,inputChannels:r,outputChannels:n,streamChannels:i,interruptAfterNodes:s,interruptBeforeNodes:o}){if(!t)throw new ls("Channels not provided");let a=new Set,c=new Set;for(let[u,l]of Object.entries(e)){if(u===ke)throw new ls(`"Node name ${ke} is reserved"`);if(l.constructor===Kn)l.triggers.forEach(p=>a.add(p));else throw new ls(`Invalid node type ${typeof l}, expected PregelNode`)}for(let u of a)if(!(u in t))throw new ls(`Subscribed channel '${String(u)}' not in channels`);if(Array.isArray(r)){if(r.every(u=>!a.has(u)))throw new ls(`None of the input channels ${r} are subscribed to by any node`)}else if(!a.has(r))throw new ls(`Input channel ${String(r)} is not subscribed to by any node`);Array.isArray(n)?n.forEach(u=>c.add(u)):c.add(n),i&&!Array.isArray(i)?c.add(i):Array.isArray(i)&&i.forEach(u=>c.add(u));for(let u of c)if(!(u in t))throw new ls(`Output channel '${String(u)}' not in channels`);if(s&&s!=="*"){for(let u of s)if(!(u in e))throw new ls(`Node ${String(u)} not in nodes`)}if(o&&o!=="*"){for(let u of o)if(!(u in e))throw new ls(`Node ${String(u)} not in nodes`)}}function MS(e,t){if(Array.isArray(e)){for(let r of e)if(!(r in t))throw new Error(`Key ${String(r)} not found in channels`)}else if(!(e in t))throw new Error(`Key ${String(e)} not found in channels`)}var jS=class UM extends Lt{lc_graph_name="Topic";unique=!1;accumulate=!1;seen;values;constructor(t){super(),this.unique=t?.unique??this.unique,this.accumulate=t?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(t){let r=new UM({unique:this.unique,accumulate:this.accumulate});return typeof t<"u"&&(r.seen=new Set(t[0]),r.values=t[1]),r}update(t){let r=!1;this.accumulate||(r=this.values.length>0,this.values=[]);let n=t.flat();if(n.length>0)if(this.unique)for(let i of n)this.seen.has(i)||(r=!0,this.seen.add(i),this.values.push(i));else r=!0,this.values.push(...n);return r}get(){if(this.values.length===0)throw new Ve;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}};function FM(e){let t=Ze.getRunnableConfig();if(!t)throw new Error("Called interrupt() outside the context of a graph.");let r=t.configurable;if(!r)throw new Error("No configurable found in config");if(!r[ft])throw new $o("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=r[Wr];n.interruptCounter+=1;let i=n.interruptCounter;if(n.resume.length>0&&i<n.resume.length)return r[bn]?.([[Nt,n.resume]]),n.resume[i];if(n.nullResume!==void 0){if(n.resume.length!==i)throw new Error(`Resume length mismatch: ${n.resume.length} !== ${i}`);let o=n.consumeNullResume();return n.resume.push(o),r[bn]?.([[Nt,n.resume]]),o}let s=r[Jr]?.split(et);throw new Ni([{id:s?us(s.join(et)):void 0,value:e}])}var BM=class{static subscribeTo(e,t){let{key:r,tags:n}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&r!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let i;return typeof e=="string"?r?i={[r]:e}:i=[e]:i=Object.fromEntries(e.map(s=>[s,s])),new Kn({channels:i,triggers:Array.isArray(e)?e:[e],tags:n})}static writeTo(e,t){let r=[];for(let n of e)r.push({channel:n,value:Dr,skipNone:!1});for(let[n,i]of Object.entries(t??{}))ue.isRunnable(i)||typeof i=="function"?r.push({channel:n,value:Dr,skipNone:!0,mapper:dt(i)}):r.push({channel:n,value:i,skipNone:!1});return new _t(r)}},s5=class extends ue{lc_namespace=["langgraph","pregel"];invoke(e,t){throw new Error("Not implemented")}withConfig(e){return super.withConfig(e)}stream(e,t){return super.stream(e,t)}},Mg=class extends s5{static lc_name(){return"LangGraph"}lc_namespace=["langgraph","pregel"];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=["values"];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;triggerToNodes={};constructor(e){super(e);let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),this.nodes=e.nodes,this.channels=e.channels,Ut in this.channels&&"lc_graph_name"in this.channels[Ut]&&this.channels[Ut].lc_graph_name!=="Topic")throw new Error(`Channel '${Ut}' is reserved and cannot be used in the graph.`);this.channels[Ut]=new jS({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.autoValidate&&this.validate()}withConfig(e){let t=Dt(this.config,e);return new this.constructor({...this,config:t})}validate(){LM({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(let[e,t]of Object.entries(this.nodes))for(let r of t.triggers)this.triggerToNodes[r]??=[],this.triggerToNodes[r].push(e);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){for(let[r,n]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(r))continue;let i=n.subgraphs?.length?n.subgraphs:[n.bound];for(let s of i){let o=wg(s);if(o!==void 0){if(r===e){yield[r,o];return}if(e===void 0&&(yield[r,o]),t){let a=e;e!==void 0&&(a=e.slice(r.length+1));for(let[c,u]of o.getSubgraphs(a,t))yield[`${r}${et}${c}`,u]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:r,applyPendingWrites:n=!1}){if(t===void 0)return{values:{},next:[],config:e,tasks:[]};let i=no(this.channels,t.checkpoint);if(t.pendingWrites?.length){let p=t.pendingWrites.filter(([f,d])=>f===ir).map(([f,d,m])=>[String(d),m]);p.length>0&&Sr(t.checkpoint,i,[{name:Bn,writes:p,triggers:[]}],void 0,this.triggerToNodes)}let s=Object.values(oo(t.checkpoint,t.pendingWrites,this.nodes,i,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await Gn(this.getSubgraphsAsync()),a=t.config.configurable?.checkpoint_ns??"",c={};for(let p of s){let f=o.find(([m])=>m===p.name);if(!f)continue;let d=`${String(p.name)}${Ir}${p.id}`;if(a&&(d=`${a}${et}${d}`),r===void 0){let m={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:d}};c[p.id]=m}else{let m={configurable:{[ft]:r,thread_id:t.config.configurable?.thread_id,checkpoint_ns:d}},h=f[1];c[p.id]=await h.getState(m,{subgraphs:!0})}}if(n&&t.pendingWrites?.length){let p=Object.fromEntries(s.map(d=>[d.id,d]));for(let[d,m,h]of t.pendingWrites)[Ot,ke,No].includes(m)||d in p&&p[d].writes.push([String(m),h]);let f=s.filter(d=>d.writes.length>0);f.length>0&&Sr(t.checkpoint,i,f,void 0,this.triggerToNodes)}let u=t?.metadata;u&&t?.config?.configurable?.thread_id&&(u={...u,thread_id:t.config.configurable.thread_id});let l=s.filter(p=>p.writes.length===0).map(p=>p.name);return{values:qn(i,this.streamChannelsAsIs),next:l,tasks:TS(s,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:u,config:so(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){let r=e.configurable?.[ft]??this.checkpointer;if(!r)throw new $o("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.[ft]===void 0){let o=yg(n);for await(let[a,c]of this.getSubgraphsAsync(o,!0))if(a===o)return await c.getState(Ta(e,{[ft]:r}),{subgraphs:t?.subgraphs});throw new Error(`Subgraph with namespace "${o}" not found.`)}let i=Dt(this.config,e),s=await r.getTuple(e);return await this._prepareStateSnapshot({config:i,saved:s,subgraphCheckpointer:t?.subgraphs?r:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){let r=e.configurable?.[ft]??this.checkpointer;if(!r)throw new $o("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.[ft]===void 0){let s=yg(n);for await(let[o,a]of this.getSubgraphsAsync(s,!0))if(o===s){yield*a.getStateHistory(Ta(e,{[ft]:r}),t);return}throw new Error(`Subgraph with namespace "${s}" not found.`)}let i=Dt(this.config,e,{configurable:{checkpoint_ns:n}});for await(let s of r.list(i,t))yield this._prepareStateSnapshot({config:s.config,saved:s})}async bulkUpdateState(e,t){let r=e.configurable?.[ft]??this.checkpointer;if(!r)throw new $o("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(t.length===0)throw new Error("No supersteps provided");if(t.some(o=>o.updates.length===0))throw new Error("No updates provided");let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.[ft]===void 0){let o=yg(n);for await(let[,a]of this.getSubgraphsAsync(o,!0))return await a.bulkUpdateState(Ta(e,{[ft]:r}),t);throw new Error(`Subgraph "${o}" not found`)}let i=async(o,a)=>{let c=this.config?Dt(this.config,o):o,u=await r.getTuple(c),l=u!==void 0?zn(u.checkpoint):tu(),p={...u?.checkpoint.channel_versions},f=u?.metadata?.step??-1,d=Ta(c,{checkpoint_ns:c.configurable?.checkpoint_ns??""}),m=c.metadata??{};u?.config.configurable&&(d=Ta(c,u.config.configurable),m={...u.metadata,...m});let{values:h,asNode:b}=a[0];if(h==null&&b===void 0){if(a.length>1)throw new De("Cannot create empty checkpoint with multiple updates");return so(await r.put(d,Ln(l,void 0,f),{source:"update",step:f+1,parents:u?.metadata?.parents??{}},{}),u?u.metadata:void 0)}let _=no(this.channels,l);if(h===null&&b===xe){if(a.length>1)throw new De("Cannot apply multiple updates when clearing state");if(u){let O=oo(l,u.pendingWrites||[],this.nodes,_,u.config,!0,{step:(u.metadata?.step??-1)+1,checkpointer:r,store:this.store}),w=(u.pendingWrites||[]).filter(U=>U[0]===ir).map(U=>U.slice(1));w.length>0&&Sr(l,_,[{name:Bn,writes:w,triggers:[]}],r.getNextVersion.bind(r),this.triggerToNodes);for(let[U,P,V]of u.pendingWrites||[])[Ot,ke,No].includes(P)||U in O&&O[U].writes.push([P,V]);Sr(l,_,Object.values(O),r.getNextVersion.bind(r),this.triggerToNodes)}return so(await r.put(d,Ln(l,_,f),{...m,source:"update",step:f+1,parents:u?.metadata?.parents??{}},uu(p,l.channel_versions)),u?u.metadata:void 0)}if(b===X1){if(a.length>1)throw new De("Cannot copy checkpoint with multiple updates");if(u==null)throw new De("Cannot copy a non-existent checkpoint");let O=P=>!Array.isArray(P)||P.length===0?!1:P.every(V=>Array.isArray(V)&&V.length===2),w=Ln(l,void 0,f),U=await r.put(u.parentConfig??Ta(u.config,{checkpoint_id:void 0}),w,{source:"fork",step:f+1,parents:u.metadata?.parents??{}},{});if(O(h)){let P=oo(w,u.pendingWrites,this.nodes,_,U,!1,{step:f+2}),V=Object.values(P).reduce((Ke,{name:cr,id:Lr})=>(Ke[cr]??=[],Ke[cr].push({id:Lr}),Ke),{}),Oe=h.reduce((Ke,cr)=>{let[Lr,Me]=cr;Ke[Me]??=[];let Ao=Ke[Me].length,$i=V[Me]?.[Ao]?.id;return Ke[Me].push({values:Lr,asNode:Me,taskId:$i}),Ke},{});return i(so(U,u.metadata),Object.values(Oe).flat())}return so(U,u.metadata)}if(b===Bn){if(a.length>1)throw new De("Cannot apply multiple updates when updating as input");let O=await Gn(Tg(this.inputChannels,h));if(O.length===0)throw new De(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);Sr(l,_,[{name:Bn,writes:O,triggers:[]}],r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let w=u?.metadata?.step!=null?u.metadata.step+1:-1,U=await r.put(d,Ln(l,_,w),{source:"input",step:w,parents:u?.metadata?.parents??{}},uu(p,l.channel_versions));return await r.putWrites(U,O,Mi(Bn,l.id)),so(U,u?u.metadata:void 0)}if(c.configurable?.checkpoint_id===void 0&&u?.pendingWrites!==void 0&&u.pendingWrites.length>0){let O=oo(l,u.pendingWrites,this.nodes,_,u.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(u.metadata?.step??-1)+1}),w=(u.pendingWrites??[]).filter(P=>P[0]===ir).map(P=>P.slice(1));w.length>0&&Sr(u.checkpoint,_,[{name:Bn,writes:w,triggers:[]}],void 0,this.triggerToNodes);for(let[P,V,Oe]of u.pendingWrites)[Ot,ke,No].includes(V)||O[P]===void 0||O[P].writes.push([V,Oe]);let U=Object.values(O).filter(P=>P.writes.length>0);U.length>0&&Sr(l,_,U,void 0,this.triggerToNodes)}let y=Object.values(l.versions_seen).map(O=>Object.values(O)).flat().find(O=>!!O),x=[];if(a.length===1){let{values:O,asNode:w,taskId:U}=a[0];if(w===void 0&&Object.keys(this.nodes).length===1)[w]=Object.keys(this.nodes);else if(w===void 0&&y===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(w=this.inputChannels);else if(w===void 0){let P=Object.entries(l.versions_seen).map(([V,Oe])=>Object.values(Oe).map(Ke=>[Ke,V])).flat().filter(([V,Oe])=>Oe!==ke).sort(([V],[Oe])=>ug(V,Oe));P&&(P.length===1?w=P[0][1]:P[P.length-1][0]!==P[P.length-2][0]&&(w=P[P.length-1][1]))}if(w===void 0)throw new De('Ambiguous update, specify "asNode"');x.push({values:O,asNode:w,taskId:U})}else for(let{asNode:O,values:w,taskId:U}of a){if(O==null)throw new De('"asNode" is required when applying multiple updates');x.push({values:w,asNode:O,taskId:U})}let I=[];for(let{asNode:O,values:w,taskId:U}of x){if(this.nodes[O]===void 0)throw new De(`Node "${O.toString()}" does not exist`);let P=this.nodes[O].getWriters();if(!P.length)throw new De(`No writers found for node "${O.toString()}"`);I.push({name:O,input:w,proc:P.length>1?br.from(P,{omitSequenceTags:!0}):P[0],writes:[],triggers:[ke],id:U??Mi(ke,l.id),writers:[]})}for(let O of I)await O.proc.invoke(O.input,Ne({...c,store:c?.store??this.store},{runName:c.runName??`${this.getName()}UpdateState`,configurable:{[bn]:w=>O.writes.push(...w),[Vn]:(w,U=!1)=>ld(l,_,O,w,U)}}));for(let O of I){let w=O.writes.filter(U=>U[0]!==nr);u!==void 0&&w.length>0&&await r.putWrites(d,w,O.id)}Sr(l,_,I,r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let A=uu(p,l.channel_versions),j=await r.put(d,Ln(l,_,f+1),{source:"update",step:f+1,parents:u?.metadata?.parents??{}},A);for(let O of I){let w=O.writes.filter(U=>U[0]===nr);w.length>0&&await r.putWrites(j,w,O.id)}return so(j,u?u.metadata:void 0)},s=e;for(let{updates:o}of t)s=await i(s,o);return s}async updateState(e,t,r){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:r}]}])}_defaults(e){let{debug:t,streamMode:r,inputKeys:n,outputKeys:i,interruptAfter:s,interruptBefore:o,...a}=e,c=!0,u=t!==void 0?t:this.debug,l=i;l===void 0?l=this.streamChannelsAsIs:MS(l,this.channels);let p=n;p===void 0?p=this.inputChannels:MS(p,this.channels);let f=o??this.interruptBefore??[],d=s??this.interruptAfter??[],m;r!==void 0?(m=Array.isArray(r)?r:[r],c=typeof r=="string"):(e.configurable?.[Ea]!==void 0?m=["values"]:m=this.streamMode,c=!0);let h;if(this.checkpointer===!1)h=void 0;else if(e!==void 0&&e.configurable?.[ft]!==void 0)h=e.configurable[ft];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");h=this.checkpointer}let b=e.store??this.store,_=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");let y=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?"exit":"async"})(),x=e.durability??y??e?.configurable?.[gS]??"async";return[u,m,p,l,a,f,d,h,b,c,_,x]}async stream(e,t){let r=new AbortController,n={recursionLimit:this.config?.recursionLimit,...t,signal:lu(t?.signal,r.signal).signal},i=await super.stream(e,n);return new $S(t?.encoding==="text/event-stream"?NM(i):i,r)}streamEvents(e,t,r){let n=new AbortController,i={recursionLimit:this.config?.recursionLimit,...t,callbacks:vM(this.config?.callbacks,t?.callbacks),signal:lu(t?.signal,n.signal).signal};return new $S(super.streamEvents(e,i,r),n)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){let r="version"in(t??{})?void 0:t?.encoding??void 0,n=t?.subgraphs,i=ad(this.config,t);if(i.recursionLimit===void 0||i.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&i.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');let s=await this._validateInput(e),{runId:o,...a}=i,[c,u,,l,p,f,d,m,h,b,_,y]=this._defaults(a);typeof p.context<"u"?p.context=await this._validateContext(p.context):p.configurable=await this._validateContext(p.configurable);let x=new Ng({modes:new Set(u)});if(this.checkpointer===!0){p.configurable??={};let P=p.configurable[Jr]??"";p.configurable[Jr]=P.split(et).map(V=>V.split(Ir)[0]).join(et)}if(u.includes("messages")){let P=new jM(Oe=>x.push(Oe)),{callbacks:V}=p;if(V===void 0)p.callbacks=[P];else if(Array.isArray(V))p.callbacks=V.concat(P);else{let Oe=V.copy();Oe.addHandler(P,!0),p.callbacks=Oe}}p.writer??=P=>{if(!u.includes("custom"))return;let V=tM()?.configurable?.[Jr]?.split(et).slice(0,-1);x.push([V??[],"custom",P])},p.interrupt??=this.userInterrupt??FM;let I=await(await Et(p))?.handleChainStart(this.toJSON(),yM(e,"input"),o,void 0,void 0,void 0,p?.runName??this.getName()),A=td(this.channels),j,O,U=(async()=>{try{j=await RM.initialize({input:s,config:p,checkpointer:m,nodes:this.nodes,channelSpecs:A,outputKeys:l,streamKeys:this.streamChannelsAsIs,store:h,cache:_,stream:x,interruptAfter:d,interruptBefore:f,manager:I,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:y});let P=new DM({loop:j,nodeFinished:p.configurable?.[Y1]});t?.subgraphs&&(j.config.configurable={...j.config.configurable,[nu]:j.stream}),await this._runLoop({loop:j,runner:P,debug:c,config:p}),y==="sync"&&await Promise.all(j?.checkpointerPromises??[])}catch(P){O=P}finally{try{j&&(await j.store?.stop(),await j.cache?.stop()),await Promise.all(j?.checkpointerPromises??[])}catch(P){O=O??P}O?x.error(O):x.close()}})();try{for await(let P of x){if(P===void 0)throw new Error("Data structure error.");let[V,Oe,Ke]=P;if(u.includes(Oe)){if(r==="text/event-stream"){n?yield[V,Oe,Ke]:yield[null,Oe,Ke];continue}n&&!b?yield[V,Oe,Ke]:b?n?yield[V,Ke]:yield Ke:yield[Oe,Ke]}}}catch(P){throw await I?.handleChainError(O),P}finally{await U}await I?.handleChainEnd(j?.output??{},o,void 0,void 0,void 0)}async invoke(e,t){let r=t?.streamMode??"values",n={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:r,encoding:void 0},i=[],s=await this.stream(e,n),o=[],a;for await(let c of s)r==="values"?od(c)?o.push(c[ke]):a=c:i.push(c);if(r==="values"){if(o.length>0){let c=o.flat(1);if(a==null)return{[ke]:c};if(typeof a=="object")return{...a,[ke]:c}}return a}return i}async _runLoop(e){let{loop:t,runner:r,debug:n,config:i}=e,s;try{for(;await t.tick({inputKeys:this.inputChannels});){for(let{task:o}of await t._matchCachedWrites())t._outputWrites(o.id,o.writes,!0);n&&OM(t.checkpointMetadata.step,t.channels,this.streamChannelsList),n&&Pg(t.step,Object.values(t.tasks)),await r.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(o,a)=>{n&&$M(o,a,this.streamChannelsList)},maxConcurrency:i.maxConcurrency,signal:i.signal})}if(t.status==="out_of_steps")throw new T_([`Recursion limit of ${i.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(o){if(s=o,!await t.finishAndHandleError(s))throw o}finally{s===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}};var Hn=class VM extends Lt{lc_graph_name="EphemeralValue";guard;value=[];constructor(t=!0){super(),this.guard=t}fromCheckpoint(t){let r=new VM(this.guard);return typeof t<"u"&&(r.value=[t]),r}update(t){if(t.length===0){let r=this.value.length>0;return this.value=[],r}if(t.length!==1&&this.guard)throw new De("EphemeralValue can only receive one value per step.");return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new Ve;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Ve;return this.value[0]}isAvailable(){return this.value.length!==0}};var DS=class{path;ends;constructor(e){ue.isRunnable(e.path)?this.path=e.path:this.path=dt(e.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((t,r)=>(t[r]=r,t),{}):e.pathMap}run(e,t){return _t.registerWriter(new sr({name:"<branch_run>",trace:!1,func:async(r,n)=>{try{return await this._route(r,n,e,t)}catch(i){throw i.name===Vd.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
223
- NodeInterrupt should only be thrown inside a node, not in edge conditions.`),i}}}))}async _route(e,t,r,n){let i=await this.path.invoke(n?n(t):e,t);Array.isArray(i)||(i=[i]);let s;if(this.ends?s=i.map(o=>$t(o)?o:this.ends[o]):s=i,s.some(o=>!o))throw new Error("Branch condition returned unknown or null destination");if(s.filter($t).some(o=>o.node===xe))throw new De("Cannot send a packet to the END node");return await r(s,t)??e}},zS=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(...e){function t(n){return n.length>=1&&typeof n[0]!="string"}let r=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(let[n,i,s]of r){for(let a of[et,Ir])if(n.includes(a))throw new Error(`"${a}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),n in this.nodes)throw new Error(`Node \`${n}\` already present.`);if(n===xe)throw new Error(`Node \`${n}\` is reserved.`);let o=dt(i);this.nodes[n]={runnable:o,metadata:s?.metadata,subgraphs:ud(o)?[o]:s?.subgraphs,ends:s?.ends}}return this}addEdge(e,t){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),e===xe)throw new Error("END cannot be a start node");if(t===Ae)throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([r])=>r===e)&&!("channels"in this))throw new Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,r){let n=typeof e=="object"?e:{source:e,path:t,pathMap:r};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!ue.isRunnable(n.path)){let s=Array.isArray(n.pathMap)?n.pathMap.join(","):Object.keys(n.pathMap??{}).join(",");n.path=dt(n.path).withConfig({runName:`Branch<${n.source}${s!==""?`,${s}`:""}>`.slice(0,63)})}let i=n.path.getName()==="RunnableLambda"?"condition":n.path.getName();if(this.branches[n.source]&&this.branches[n.source][i])throw new Error(`Condition \`${i}\` already present for node \`${e}\``);return this.branches[n.source]??={},this.branches[n.source][i]=new DS(n),this}setEntryPoint(e){return this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(Ae,e)}setFinishPoint(e){return this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(e,xe)}compile({checkpointer:e,interruptBefore:t,interruptAfter:r,name:n}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(r)?r:[]]);let i=new LS({builder:this,checkpointer:e,interruptAfter:r,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[Ae]:new Hn,[xe]:new Hn},inputChannels:Ae,outputChannels:xe,streamChannels:[],streamMode:"values",name:n});for(let[s,o]of Object.entries(this.nodes))i.attachNode(s,o);for(let[s,o]of this.edges)i.attachEdge(s,o);for(let[s,o]of Object.entries(this.branches))for(let[a,c]of Object.entries(o))i.attachBranch(s,a,c);return i.validate()}validate(e){let t=new Set([...this.allEdges].map(([n,i])=>n));for(let[n]of Object.entries(this.branches))t.add(n);for(let n of t)if(n!==Ae&&!(n in this.nodes))throw new Error(`Found edge starting at unknown node \`${n}\``);let r=new Set([...this.allEdges].map(([n,i])=>i));for(let[n,i]of Object.entries(this.branches))for(let s of Object.values(i))if(s.ends!=null)for(let o of Object.values(s.ends))r.add(o);else{r.add(xe);for(let o of Object.keys(this.nodes))o!==n&&r.add(o)}for(let n of Object.values(this.nodes))for(let i of n.ends??[])r.add(i);for(let n of Object.keys(this.nodes))if(!r.has(n))throw new $_([`Node \`${n}\` is not reachable.`,"","If you are returning Command objects from your node,",'make sure you are passing names of potential destination nodes as an "ends" array','into ".addNode(..., { ends: ["node1", "node2"] })".'].join(`
224
- `),{lc_error_code:"UNREACHABLE_NODE"});for(let n of r)if(n!==xe&&!(n in this.nodes))throw new Error(`Found edge ending at unknown node \`${n}\``);if(e){for(let n of e)if(!(n in this.nodes))throw new Error(`Interrupt node \`${n}\` is not present`)}this.compiled=!0}},LS=class extends Mg{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new Hn,this.nodes[e]=new Kn({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new _t([{channel:e,value:Dr}],[Be])),this.streamChannels.push(e)}attachEdge(e,t){if(t===xe){if(e===Ae)throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new _t([{channel:xe,value:Dr}],[Be]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,r){e===Ae&&!this.nodes[Ae]&&(this.nodes[Ae]=BM.subscribeTo(Ae,{tags:[Be]})),this.nodes[e].pipe(r.run(i=>new _t(i.map(s=>$t(s)?s:{channel:s===xe?xe:`branch:${e}:${t}:${s}`,value:Dr}),[Be])));let n=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(let i of n)if(i!==xe){let s=`branch:${e}:${t}:${i}`;this.channels[s]=new Hn,this.nodes[i].triggers.push(s),this.nodes[i].channels.push(s)}}async getGraphAsync(e){let t=e?.xray,r=new _a,n={[Ae]:r.addNode({schema:Z.any()},Ae)},i={},s={};t&&(s=Object.fromEntries((await Gn(this.getSubgraphsAsync())).filter(c=>ZM(c[1]))));function o(c,u,l,p=!1){if(u===xe&&i[xe]===void 0&&(i[xe]=r.addNode({schema:Z.any()},xe)),n[c]!==void 0){if(i[u]===void 0)throw new Error(`End node ${u} not found!`);return r.addEdge(n[c],i[u],l!==u?l:void 0,p)}}for(let[c,u]of Object.entries(this.builder.nodes)){let l=or(c),p=u.runnable,f=u.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?f.__interrupt="before,after":this.interruptBefore?.includes(c)?f.__interrupt="before":this.interruptAfter?.includes(c)&&(f.__interrupt="after"),t){let d=typeof t=="number"?t-1:t,m=s[c]!==void 0?await s[c].getGraphAsync({...e,xray:d}):p.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let _=function(x){return x?x.lc_runnable:!1},y=function(x,I){if(x!==void 0&&!En(x))return x;if(_(I))try{let A=I.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return I.getName()}else return I.name??"UnknownSchema"},[h,b]=r.extend(m,l);if(h===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);b!==void 0&&(n[l]={name:y(b.id,b.data),...b}),i[l]={name:y(h.id,h.data),...h}}else{let h=r.addNode(p,l,f);n[l]=h,i[l]=h}}else{let d=r.addNode(p,l,f);n[l]=d,i[l]=d}}let a=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of a)o(or(c),or(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==c).map(p=>[or(p),or(p)])),[xe]:xe};for(let p of Object.values(u)){let f;p.ends!==void 0?f=p.ends:f=l;for(let[d,m]of Object.entries(f))o(or(c),or(m),d,!0)}}for(let[c,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let l of u.ends)o(or(c),or(l),void 0,!0);return r}getGraph(e){let t=e?.xray,r=new _a,n={[Ae]:r.addNode({schema:Z.any()},Ae)},i={},s={};t&&(s=Object.fromEntries(Aa(this.getSubgraphs()).filter(c=>ZM(c[1]))));function o(c,u,l,p=!1){return u===xe&&i[xe]===void 0&&(i[xe]=r.addNode({schema:Z.any()},xe)),r.addEdge(n[c],i[u],l!==u?l:void 0,p)}for(let[c,u]of Object.entries(this.builder.nodes)){let l=or(c),p=u.runnable,f=u.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?f.__interrupt="before,after":this.interruptBefore?.includes(c)?f.__interrupt="before":this.interruptAfter?.includes(c)&&(f.__interrupt="after"),t){let d=typeof t=="number"?t-1:t,m=s[c]!==void 0?s[c].getGraph({...e,xray:d}):p.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let _=function(x){return x?x.lc_runnable:!1},y=function(x,I){if(x!==void 0&&!En(x))return x;if(_(I))try{let A=I.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return I.getName()}else return I.name??"UnknownSchema"},[h,b]=r.extend(m,l);if(h===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);b!==void 0&&(n[l]={name:y(b.id,b.data),...b}),i[l]={name:y(h.id,h.data),...h}}else{let h=r.addNode(p,l,f);n[l]=h,i[l]=h}}else{let d=r.addNode(p,l,f);n[l]=d,i[l]=d}}let a=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of a)o(or(c),or(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==c).map(p=>[or(p),or(p)])),[xe]:xe};for(let p of Object.values(u)){let f;p.ends!==void 0?f=p.ends:f=l;for(let[d,m]of Object.entries(f))o(or(c),or(m),d,!0)}}return r}};function ZM(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function or(e){return e==="subgraph"?`"${e}"`:e}function ao(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function GM(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function co(e){if(GM(e))try{return e["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function uo(e){if(e!=null&&ao(e))try{let t=e["~standard"].validate(void 0);if(t&&typeof t=="object"&&!("then"in t&&typeof t.then=="function")){let r=t;if(!r.issues){let n=r.value;return()=>n}}}catch{}}var US=Symbol.for("langgraph.channel.missing"),jg=class KM extends Lt{lc_graph_name="UntrackedValue";guard;_value=US;initialValueFactory;constructor(t){super(),this.guard=t?.guard??!0,this.initialValueFactory=t?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new KM({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(t){if(t.length===0)return!1;if(t.length!==1&&this.guard)throw new De("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this._value=t[t.length-1],!0}get(){if(this._value===US)throw new Ve;return this._value}checkpoint(){}isAvailable(){return this._value!==US}};var lo=(e,t)=>e.size===t.size&&[...e].every(r=>t.has(r)),FS=class qM extends Lt{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){let r=new qM(this.names);return typeof t<"u"&&(r.seen=new Set(t)),r}update(t){let r=!1;for(let n of t)if(this.names.has(n))this.seen.has(n)||(this.seen.add(n),r=!0);else throw new De(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!lo(this.names,this.seen))throw new Ve}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&lo(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&lo(this.names,this.seen)}},BS=class HM extends Lt{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(t){super(),this.names=t,this.seen=new Set,this.finished=!1}fromCheckpoint(t){let r=new HM(this.names);if(typeof t<"u"){let[n,i]=t;r.seen=new Set(n),r.finished=i}return r}update(t){let r=!1;for(let n of t)if(this.names.has(n)&&!this.seen.has(n))this.seen.add(n),r=!0;else if(!this.names.has(n))throw new De(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!this.finished||!lo(this.names,this.seen))throw new Ve}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&lo(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&lo(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&lo(this.names,this.seen)}};var VS=Symbol.for("langgraph.state.reduced_value"),ps=class{[VS]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.jsonSchemaExtra=t.jsonSchemaExtra,this.valueSchema=e,this.inputSchema="inputSchema"in t?t.inputSchema:e,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e=="object"&&e!==null&&VS in e&&e[VS]===!0}};var WM=Symbol.for("langgraph.state.untracked_value"),Ca=class{[WM]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e=="object"&&e!==null&&WM in e}};var ZS=Symbol.for("langgraph.state.state_schema"),wi=class{[ZS]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,r]of Object.entries(this.fields))if(ps.isInstance(r)){let n=uo(r.valueSchema);e[t]=new os(r.reducer,n)}else if(Ca.isInstance(r)){let n=r.schema?uo(r.schema):void 0;e[t]=new jg({guard:r.guard,initialValueFactory:n})}else if(ao(r))e[t]=new Un(uo(r));else throw new Error(`Invalid state field "${t}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[r,n]of Object.entries(this.fields)){let i;if(ps.isInstance(n)?(i=co(n.valueSchema),i&&n.jsonSchemaExtra&&(i={...i,...n.jsonSchemaExtra})):Ca.isInstance(n)?i=n.schema?co(n.schema):void 0:ao(n)&&(i=co(n)),i){e[r]=i;let s=!1;ps.isInstance(n)?s=uo(n.valueSchema)!==void 0:Ca.isInstance(n)?s=n.schema?uo(n.schema)!==void 0:!1:s=uo(n)!==void 0,s||t.push(r)}}return{type:"object",properties:e,required:t.length>0?t:void 0}}getInputJsonSchema(){let e={};for(let[t,r]of Object.entries(this.fields)){let n;ps.isInstance(r)?n=co(r.inputSchema):Ca.isInstance(r)?n=r.schema?co(r.schema):void 0:ao(r)&&(n=co(r)),n&&(e[t]=n)}return{type:"object",properties:e}}getChannelKeys(){return Object.entries(this.fields).map(([e])=>e)}getAllKeys(){return Object.keys(this.fields)}async validateInput(e){if(e==null||typeof e!="object")return e;let t={};for(let[r,n]of Object.entries(e)){let i=this.fields[r];if(i===void 0){t[r]=n;continue}let s;if(ps.isInstance(i)?s=i.inputSchema:Ca.isInstance(i)?s=i.schema:ao(i)&&(s=i),s){let o=await s["~standard"].validate(n);if(o.issues)throw new Error(`Validation failed for field "${r}": ${JSON.stringify(o.issues)}`);t[r]=o.value}else t[r]=n}return t}static isInstance(e){return typeof e=="object"&&e!==null&&ZS in e&&e[ZS]===!0}};var JM="__remove_all__";function ds(e,t){let r=Array.isArray(e)?e:[e],n=Array.isArray(t)?t:[t],i=r.map(Qt),s=n.map(Qt);for(let l of i)(l.id===null||l.id===void 0)&&(l.id=Ar(),l.lc_kwargs.id=l.id);let o;for(let l=0;l<s.length;l+=1){let p=s[l];(p.id===null||p.id===void 0)&&(p.id=Ar(),p.lc_kwargs.id=p.id),Tn.isInstance(p)&&p.id===JM&&(o=l)}if(o!=null)return s.slice(o+1);let a=[...i],c=new Map(a.map((l,p)=>[l.id,p])),u=new Set;for(let l of s){let p=c.get(l.id);if(p!==void 0)Tn.isInstance(l)?u.add(l.id):(u.delete(l.id),a[p]=l);else{if(Tn.isInstance(l))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${l.id}')`);c.set(l.id,a.length),a.push(l)}}return a.filter(l=>!u.has(l.id))}var o5=Z.custom().default(()=>[]),a5=Z.custom(),c5=new ps(o5,{inputSchema:a5,reducer:ds,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var u5="lg:",l5=class{_map=new WeakMap;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){let r=this.get(e);this._map.set(e,t(r))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){let t={},r=ea(e);for(let[n,i]of Object.entries(r)){let s=this.get(i);s?.reducer?t[n]=new os(s.reducer.fn,s.default):t[n]=new Un(s?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let r=Object.entries(t).filter(([,s])=>s===!0).sort(([s],[o])=>s.localeCompare(o)).map(([s,o])=>`${s}:${o}`).join("|"),n=this._extensionCache.get(r)??new WeakMap;if(n.has(e))return n.get(e);let i=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let s=Object.entries(ea(e)).map(([o,a])=>{let c=this.get(a),u=t.withReducerSchema?c?.reducer?.schema??a:a;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){let l=On(u)??On(a),p=JSON.stringify({...c.jsonSchemaExtra,description:l});u=u.describe(`${u5}${p}`)}return[o,u]});i=Ym(e,Object.fromEntries(s)),it(i)&&(i._def.unknownKeys="strip")}return t.asPartial&&(i=Cc(i)),n.set(e,i),this._extensionCache.set(r,n),i}},md=new l5;function XM(e,t){if(t.reducer&&!t.default){let r=Qm(e);r!=null&&(t.default=r)}if(t.reducer){let r=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return md.extend(r,()=>t),r}else return md.extend(e,()=>t),e}function Pa(e){return e==null?!1:!!(wi.isInstance(e)||yr(e)||typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(t=>typeof t=="function"||mS(t)))}function YM(e){if(typeof e!="object"||e==null)return!1;let t=e,r="state"in t&&Pa(t.state),n="stateSchema"in t&&Pa(t.stateSchema),i="input"in t&&Pa(t.input);return!(!r&&!n&&!i||"input"in t&&t.input!=null&&!Pa(t.input)||"output"in t&&t.output!=null&&!Pa(t.output))}var fs="__root__",Dg=Symbol.for("langgraph.state.partial"),zg=class extends zS{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=md;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(e,t){super();let r=this._normalizeToStateGraphInit(e,t),n=r.state??r.stateSchema??r.input;if(!n)throw new ol;let i=this._getChannelsFromSchema(n);this._schemaDefinition=i,wi.isInstance(n)?this._schemaRuntimeDefinition=n:yr(n)&&(this._schemaRuntimeDefinition=n),r.input?wi.isInstance(r.input)?this._inputRuntimeDefinition=r.input:yr(r.input)?this._inputRuntimeDefinition=r.input:this._inputRuntimeDefinition=Dg:this._inputRuntimeDefinition=Dg,r.output?wi.isInstance(r.output)?this._outputRuntimeDefinition=r.output:yr(r.output)?this._outputRuntimeDefinition=r.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let s=r.input?this._getChannelsFromSchema(r.input):i,o=r.output?this._getChannelsFromSchema(r.output):i;this._inputDefinition=s,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),r.context&&yr(r.context)&&(this._configRuntimeSchema=r.context),this._interrupt=r.interrupt,this._writer=r.writer}_normalizeToStateGraphInit(e,t){if(YM(e)){if(yr(t)||fg.isInstance(t))return{...e,context:t};let r=t;return{...e,input:e.input??r?.input,output:e.output??r?.output,context:e.context??r?.context,interrupt:e.interrupt??r?.interrupt,writer:e.writer??r?.writer,nodes:e.nodes??r?.nodes}}if(Pa(e)){if(yr(t)||fg.isInstance(t))return{state:e,context:t};let r=t;return{state:e,input:r?.input,output:r?.output,context:r?.context,interrupt:r?.interrupt,writer:r?.writer,nodes:r?.nodes}}if(d5(e))return{state:p5(e.channels)};throw new ol}_getChannelsFromSchema(e){if(wi.isInstance(e))return e.getChannels();if(yr(e))return this._metaRegistry.getChannelsForSchema(e);if(typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot")return e.spec;if(typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0)return e;throw new ol("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.")}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(r=>[r,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(let[t,r]of Object.entries(e)){let n;if(typeof r=="function"?n=r():n=r,this.channels[t]!==void 0){if(!this.channels[t].equals(n)&&n.lc_graph_name!=="LastValue")throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=n}}}addNode(...e){function t(n){return n.length>=1&&typeof n[0]!="string"}let r=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([n,i])=>[n,i]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(let[n,i,s]of r){if(n in this.channels)throw new Error(`${n} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let l of[et,Ir])if(n.includes(l))throw new Error(`"${l}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),n in this.nodes)throw new Error(`Node \`${n}\` already present.`);if(n===xe||n===Ae)throw new Error(`Node \`${n}\` is reserved.`);let o=this._schemaDefinition;s?.input!==void 0&&(o=this._getChannelsFromSchema(s.input)),this._addSchema(o);let a;ue.isRunnable(i)?a=i:typeof i=="function"?a=new sr({func:i,name:n,trace:!1}):a=dt(i);let c=s?.cachePolicy;typeof c=="boolean"&&(c=c?{}:void 0);let u={runnable:a,retryPolicy:s?.retryPolicy,cachePolicy:c,metadata:s?.metadata,input:o??this._schemaDefinition,subgraphs:ud(a)?[a]:s?.subgraphs,ends:s?.ends,defer:s?.defer};this.nodes[n]=u}return this}addEdge(e,t){if(typeof e=="string")return super.addEdge(e,t);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(let r of e){if(r===xe)throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(n=>n===r))throw new Error(`Need to add a node named "${r}" first`)}if(t===xe)throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(r=>r===t))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){let t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw new Error("Sequence requires at least one node.");let r;for(let[n,i,s]of t){if(n in this.nodes)throw new Error(`Node names must be unique: node with the name "${n}" already exists.`);let o=n;this.addNode(o,i,s),r!=null&&this.addEdge(r,o),r=o}return this}compile({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:i,name:s,description:o}={}){this.validate([...Array.isArray(n)?n:[],...Array.isArray(i)?i:[]]);let a=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=a.length===1&&a[0]===fs?fs:a,u=Object.keys(this.channels),l=u.length===1&&u[0]===fs?fs:u,p=this._interrupt,f=new ej({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:n,autoValidate:!1,nodes:{},channels:{...this.channels,[Ae]:new Hn},inputChannels:Ae,outputChannels:c,streamChannels:l,streamMode:"updates",store:t,cache:r,name:s,description:o,userInterrupt:p});f.attachNode(Ae);for(let[d,m]of Object.entries(this.nodes))f.attachNode(d,m);f.attachBranch(Ae,yS,QM(),{withReader:!1});for(let[d]of Object.entries(this.nodes))f.attachBranch(d,yS,QM(),{withReader:!1});for(let[d,m]of this.edges)f.attachEdge(d,m);for(let[d,m]of this.waitingEdges)f.attachEdge(d,m);for(let[d,m]of Object.entries(this.branches))for(let[h,b]of Object.entries(m))f.attachBranch(d,h,b);return f.validate()}};function p5(e){let t={};for(let[r,n]of Object.entries(e))r===fs?t[r]=mg(n):t[r]=mg(n);return t}var ej=class extends LS{description;_metaRegistry=md;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let r;e===Ae?r=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([a])=>a):r=Object.keys(this.builder.channels);function n(a){if(Pt(a))return a.graph===jr.PARENT?null:a._updateAsTuples();if(Array.isArray(a)&&a.length>0&&a.some(c=>Pt(c))){let c=[];for(let u of a)if(Pt(u)){if(u.graph===jr.PARENT)continue;c.push(...u._updateAsTuples())}else c.push([fs,u]);return c}else if(a!=null)return[[fs,a]];return null}let i=e;function s(a){if(a){if(Pt(a))return a.graph===jr.PARENT?null:a._updateAsTuples().filter(([c])=>r.includes(c));if(Array.isArray(a)&&a.length>0&&a.some(Pt)){let c=[];for(let u of a)if(Pt(u)){if(u.graph===jr.PARENT)continue;c.push(...u._updateAsTuples().filter(([l])=>r.includes(l)))}else{let l=s(u);l&&c.push(...l??[])}return c}else{if(typeof a=="object"&&!Array.isArray(a))return Object.entries(a).filter(([c])=>r.includes(c));{let c=Array.isArray(a)?"array":typeof a;throw new De(`Expected node "${i.toString()}" to return an object or an array containing at least one Command object, received ${c}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}let o=[{value:Dr,mapper:new sr({func:r.length&&r[0]===fs?n:s,trace:!1,recurse:!1})}];if(e===Ae)this.nodes[e]=new Kn({tags:[Be],triggers:[Ae],channels:[Ae],writers:[new _t(o,[Be])]});else{let a=t?.input??this.builder._schemaDefinition,c=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(a)).map(p=>[p,p])),u=Object.keys(c).length===1&&fs in c,l=`branch:to:${e}`;this.channels[l]=t?.defer?new hS:new Hn(!1),this.nodes[e]=new Kn({triggers:[l],channels:u?Object.keys(c):c,writers:[new _t(o,[Be])],mapper:u?void 0:p=>Object.fromEntries(Object.entries(p).filter(([f])=>f in c)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:t?.cachePolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!==xe){if(typeof e=="string")this.nodes[e].writers.push(new _t([{channel:`branch:to:${t}`,value:null}],[Be]));else if(Array.isArray(e)){let r=`join:${e.join("+")}:${t}`;this.channels[r]=this.builder.nodes[t].defer?new BS(new Set(e)):new FS(new Set(e)),this.nodes[t].triggers.push(r);for(let n of e)this.nodes[n].writers.push(new _t([{channel:r,value:n}],[Be]))}}}attachBranch(e,t,r,n={withReader:!0}){let i=async(s,o)=>{let a=s.filter(u=>u!==xe);if(!a.length)return;let c=a.map(u=>$t(u)?u:{channel:u===xe?u:`branch:to:${u}`,value:e});await _t.doWrite({...o,tags:(o.tags??[]).concat([Be])},c)};this.nodes[e].writers.push(r.run(i,n.withReader?s=>sM.doRead(s,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;let t=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition;if(wi.isInstance(t)){if(Pt(e)){let i=e;return e.update&&(i.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),i}return await t.validateInput(e)}if(t===Dg&&wi.isInstance(r)){if(Pt(e)){let i=e;return e.update&&(i.update=await r.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),i}return await r.validateInput(e)}let n=(()=>{let i=s=>{if(s!=null)return this._metaRegistry.getExtendedChannelSchemas(s,{withReducerSchema:!0})};if(yr(t))return i(t);if(t===Dg)return yr(r)?Cc(i(r)):void 0})();if(Pt(e)){let i=e;return e.update&&n!=null&&(i.update=Oc(n,e.update)),i}return n!=null?Oc(n,e):e}isInterrupted(e){return od(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return yr(t)&&Oc(t,e),e}};function d5(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function f5(e){if($t(e))return[e];let t=[];Pt(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(Pt));let r=[];for(let n of t){if(n.graph===jr.PARENT)throw new Zd(n);$t(n.goto)||typeof n.goto=="string"?r.push(n.goto):Array.isArray(n.goto)&&r.push(...n.goto)}return r}function QM(){return new DS({path:new sr({func:f5,tags:[Be],trace:!1,recurse:!1,name:"<control_branch>"})})}var tj=function(t,r){let{name:n,checkpointer:i,store:s,cache:o}=typeof t=="string"?{name:t,checkpointer:void 0,store:void 0}:t;if(nM(r)||iM(r))throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write.");let a="updates",c=IM(n,r);function u(d){return typeof d=="object"&&d!==null&&"__lg_type"in d&&d.__lg_type==="__pregel_final"}let l=new sr({name:"pluckReturnValue",func:d=>u(d)?d.value:d}),p=new sr({name:"pluckSaveValue",func:d=>u(d)?d.save:d}),f=new Kn({bound:c,triggers:[Ae],channels:[Ae],writers:[new _t([{channel:xe,value:Dr,mapper:l},{channel:ka,value:Dr,mapper:p}],[Be])]});return new Mg({name:n,checkpointer:i,nodes:{[n]:f},channels:{[Ae]:new Hn,[xe]:new Un,[ka]:new Un},inputChannels:Ae,outputChannels:xe,streamChannels:xe,streamMode:a,store:s,cache:o})};tj.final=function({value:t,save:r}){return{value:t,save:r,__lg_type:"__pregel_final"}};var m5=Fn.Root({messages:Fn({reducer:ds,default:()=>[]})}),rj={reducer:{fn:ds},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]},h5=ce.object({messages:XM(ce.custom(),rj)});async function GS(e,t,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
225
-
226
- If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
227
-
228
- Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
229
- |`,`
230
- \u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
231
- `].join(" "));let n=await Et(r),i=n?.getParentRunId();n!==void 0&&i!==void 0&&await n.handleCustomEvent?.(e,t,i)}var wn=ce;function hd(e,t){return e.lc_error_code=t,e.message=`${e.message}
232
-
233
- Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/
234
- `,e}function se(e,t,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r}function k(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var KS=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return KS=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function gd(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var _d=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};var W=class extends Error{},Rt=class e extends W{constructor(t,r,n,i){super(`${e.makeMessage(t,r,n)}`),this.status=t,this.headers=i,this.requestID=i?.get("x-request-id"),this.error=r;let s=r;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(t,r,n){let i=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&i?`${t} ${i}`:t?`${t} status code (no body)`:i||"(no status code or body)"}static generate(t,r,n,i){if(!t||!i)return new po({message:n,cause:_d(r)});let s=r?.error;return t===400?new pu(t,s,n,i):t===401?new du(t,s,n,i):t===403?new fu(t,s,n,i):t===404?new mu(t,s,n,i):t===409?new hu(t,s,n,i):t===422?new gu(t,s,n,i):t===429?new _u(t,s,n,i):t>=500?new yu(t,s,n,i):new e(t,s,n,i)}},yt=class extends Rt{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}},po=class extends Rt{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0),r&&(this.cause=r)}},xi=class extends po{constructor({message:t}={}){super({message:t??"Request timed out."})}},pu=class extends Rt{},du=class extends Rt{},fu=class extends Rt{},mu=class extends Rt{},hu=class extends Rt{},gu=class extends Rt{},_u=class extends Rt{},yu=class extends Rt{},vu=class extends W{constructor(){super("Could not parse response content as the length limit was reached")}},bu=class extends W{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Ii=class extends Error{constructor(t){super(t)}};var _5=/^[a-z][a-z0-9+.-]*:/i,nj=e=>_5.test(e),ar=e=>(ar=Array.isArray,ar(e)),qS=ar;function HS(e){return typeof e!="object"?{}:e??{}}function ij(e){if(!e)return!0;for(let t in e)return!1;return!0}function sj(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function yd(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var oj=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new W(`${e} must be an integer`);if(t<0)throw new W(`${e} must be a positive integer`);return t};var aj=e=>{try{return JSON.parse(e)}catch{return}};var Si=e=>new Promise(t=>setTimeout(t,e));var fo="6.16.0";var pj=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function y5(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var v5=()=>{let e=y5();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fo,"X-Stainless-OS":uj(Deno.build.os),"X-Stainless-Arch":cj(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fo,"X-Stainless-OS":uj(globalThis.process.platform??"unknown"),"X-Stainless-Arch":cj(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=b5();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function b5(){if(typeof navigator>"u"||!navigator)return null;let e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:t,pattern:r}of e){let n=r.exec(navigator.userAgent);if(n){let i=n[1]||0,s=n[2]||0,o=n[3]||0;return{browser:t,version:`${i}.${s}.${o}`}}}return null}var cj=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",uj=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),lj,dj=()=>lj??(lj=v5());function fj(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function WS(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Lg(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return WS({start(){},async pull(r){let{done:n,value:i}=await t.next();n?r.close():r.enqueue(i)},async cancel(){await t.return?.()}})}function JS(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function mj(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var hj=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var Ug="RFC3986",XS=e=>String(e),Fg={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:XS},YS="RFC1738";var Bg=(e,t)=>(Bg=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Bg(e,t)),Ei=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();var QS=1024,gj=(e,t,r,n,i)=>{if(e.length===0)return e;let s=e;if(typeof e=="symbol"?s=Symbol.prototype.toString.call(e):typeof e!="string"&&(s=String(e)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let o="";for(let a=0;a<s.length;a+=QS){let c=s.length>=QS?s.slice(a,a+QS):s,u=[];for(let l=0;l<c.length;++l){let p=c.charCodeAt(l);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||i===YS&&(p===40||p===41)){u[u.length]=c.charAt(l);continue}if(p<128){u[u.length]=Ei[p];continue}if(p<2048){u[u.length]=Ei[192|p>>6]+Ei[128|p&63];continue}if(p<55296||p>=57344){u[u.length]=Ei[224|p>>12]+Ei[128|p>>6&63]+Ei[128|p&63];continue}l+=1,p=65536+((p&1023)<<10|c.charCodeAt(l)&1023),u[u.length]=Ei[240|p>>18]+Ei[128|p>>12&63]+Ei[128|p>>6&63]+Ei[128|p&63]}o+=u.join("")}return o};function _j(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function eE(e,t){if(ar(e)){let r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}var vj={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},bj=function(e,t){Array.prototype.push.apply(e,ar(t)?t:[t])},yj,Mt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:gj,encodeValuesOnly:!1,format:Ug,formatter:XS,indices:!1,serializeDate(e){return(yj??(yj=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function I5(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}var tE={};function wj(e,t,r,n,i,s,o,a,c,u,l,p,f,d,m,h,b,_){let y=e,x=_,I=0,A=!1;for(;(x=x.get(tE))!==void 0&&!A;){let P=x.get(e);if(I+=1,typeof P<"u"){if(P===I)throw new RangeError("Cyclic object value");A=!0}typeof x.get(tE)>"u"&&(I=0)}if(typeof u=="function"?y=u(t,y):y instanceof Date?y=f?.(y):r==="comma"&&ar(y)&&(y=eE(y,function(P){return P instanceof Date?f?.(P):P})),y===null){if(s)return c&&!h?c(t,Mt.encoder,b,"key",d):t;y=""}if(I5(y)||_j(y)){if(c){let P=h?t:c(t,Mt.encoder,b,"key",d);return[m?.(P)+"="+m?.(c(y,Mt.encoder,b,"value",d))]}return[m?.(t)+"="+m?.(String(y))]}let j=[];if(typeof y>"u")return j;let O;if(r==="comma"&&ar(y))h&&c&&(y=eE(y,c)),O=[{value:y.length>0?y.join(",")||null:void 0}];else if(ar(u))O=u;else{let P=Object.keys(y);O=l?P.sort(l):P}let w=a?String(t).replace(/\./g,"%2E"):String(t),U=n&&ar(y)&&y.length===1?w+"[]":w;if(i&&ar(y)&&y.length===0)return U+"[]";for(let P=0;P<O.length;++P){let V=O[P],Oe=typeof V=="object"&&typeof V.value<"u"?V.value:y[V];if(o&&Oe===null)continue;let Ke=p&&a?V.replace(/\./g,"%2E"):V,cr=ar(y)?typeof r=="function"?r(U,Ke):U:U+(p?"."+Ke:"["+Ke+"]");_.set(e,I);let Lr=new WeakMap;Lr.set(tE,_),bj(j,wj(Oe,cr,r,n,i,s,o,a,r==="comma"&&h&&ar(y)?null:c,u,l,p,f,d,m,h,b,Lr))}return j}function S5(e=Mt){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");let t=e.charset||Mt.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Ug;if(typeof e.format<"u"){if(!Bg(Fg,e.format))throw new TypeError("Unknown format option provided.");r=e.format}let n=Fg[r],i=Mt.filter;(typeof e.filter=="function"||ar(e.filter))&&(i=e.filter);let s;if(e.arrayFormat&&e.arrayFormat in vj?s=e.arrayFormat:"indices"in e?s=e.indices?"indices":"repeat":s=Mt.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:Mt.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:Mt.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:Mt.allowEmptyArrays,arrayFormat:s,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Mt.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?Mt.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:Mt.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:Mt.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:Mt.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:Mt.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:Mt.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:Mt.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Mt.strictNullHandling}}function rE(e,t={}){let r=e,n=S5(t),i,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):ar(n.filter)&&(s=n.filter,i=s);let o=[];if(typeof r!="object"||r===null)return"";let a=vj[n.arrayFormat],c=a==="comma"&&n.commaRoundTrip;i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);let u=new WeakMap;for(let f=0;f<i.length;++f){let d=i[f];n.skipNulls&&r[d]===null||bj(o,wj(r[d],d,a,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}let l=o.join(n.delimiter),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),l.length>0?p+l:""}function Sj(e){let t=0;for(let i of e)t+=i.length;let r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}var xj;function wu(e){let t;return(xj??(t=new globalThis.TextEncoder,xj=t.encode.bind(t)))(e)}var Ij;function nE(e){let t;return(Ij??(t=new globalThis.TextDecoder,Ij=t.decode.bind(t)))(e)}var Xr,Yr,Na=class{constructor(){Xr.set(this,void 0),Yr.set(this,void 0),se(this,Xr,new Uint8Array,"f"),se(this,Yr,null,"f")}decode(t){if(t==null)return[];let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?wu(t):t;se(this,Xr,Sj([k(this,Xr,"f"),r]),"f");let n=[],i;for(;(i=k5(k(this,Xr,"f"),k(this,Yr,"f")))!=null;){if(i.carriage&&k(this,Yr,"f")==null){se(this,Yr,i.index,"f");continue}if(k(this,Yr,"f")!=null&&(i.index!==k(this,Yr,"f")+1||i.carriage)){n.push(nE(k(this,Xr,"f").subarray(0,k(this,Yr,"f")-1))),se(this,Xr,k(this,Xr,"f").subarray(k(this,Yr,"f")),"f"),se(this,Yr,null,"f");continue}let s=k(this,Yr,"f")!==null?i.preceding-1:i.preceding,o=nE(k(this,Xr,"f").subarray(0,s));n.push(o),se(this,Xr,k(this,Xr,"f").subarray(i.index),"f"),se(this,Yr,null,"f")}return n}flush(){return k(this,Xr,"f").length?this.decode(`
235
- `):[]}};Xr=new WeakMap,Yr=new WeakMap;Na.NEWLINE_CHARS=new Set([`
236
- `,"\r"]);Na.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function k5(e,t){for(let i=t??0;i<e.length;i++){if(e[i]===10)return{preceding:i,index:i+1,carriage:!1};if(e[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function Ej(e){for(let n=0;n<e.length-1;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var Zg={off:0,error:200,warn:300,info:400,debug:500},iE=(e,t,r)=>{if(e){if(sj(Zg,e))return e;It(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Zg))}`)}};function vd(){}function Vg(e,t,r){return!t||Zg[e]>Zg[r]?vd:t[e].bind(t)}var A5={error:vd,warn:vd,info:vd,debug:vd},kj=new WeakMap;function It(e){let t=e.logger,r=e.logLevel??"off";if(!t)return A5;let n=kj.get(t);if(n&&n[0]===r)return n[1];let i={error:Vg("error",t,r),warn:Vg("warn",t,r),info:Vg("info",t,r),debug:Vg("debug",t,r)};return kj.set(t,[r,i]),i}var ms=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var bd,ki=class e{constructor(t,r,n){this.iterator=t,bd.set(this,void 0),this.controller=r,se(this,bd,n,"f")}static fromSSEResponse(t,r,n){let i=!1,s=n?It(n):console;async function*o(){if(i)throw new W("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let c of T5(t,r))if(!a){if(c.data.startsWith("[DONE]")){a=!0;continue}if(c.event===null||!c.event.startsWith("thread.")){let u;try{u=JSON.parse(c.data)}catch(l){throw s.error("Could not parse message into JSON:",c.data),s.error("From chunk:",c.raw),l}if(u&&u.error)throw new Rt(void 0,u.error,void 0,t.headers);yield u}else{let u;try{u=JSON.parse(c.data)}catch(l){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),l}if(c.event=="error")throw new Rt(void 0,u.error,u.message,void 0);yield{event:c.event,data:u}}}a=!0}catch(c){if(gd(c))return;throw c}finally{a||r.abort()}}return new e(o,r,n)}static fromReadableStream(t,r,n){let i=!1;async function*s(){let a=new Na,c=JS(t);for await(let u of c)for(let l of a.decode(u))yield l;for(let u of a.flush())yield u}async function*o(){if(i)throw new W("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let c of s())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(gd(c))return;throw c}finally{a||r.abort()}}return new e(o,r,n)}[(bd=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],r=[],n=this.iterator(),i=s=>({next:()=>{if(s.length===0){let o=n.next();t.push(o),r.push(o)}return s.shift()}});return[new e(()=>i(t),this.controller,k(this,bd,"f")),new e(()=>i(r),this.controller,k(this,bd,"f"))]}toReadableStream(){let t=this,r;return WS({async start(){r=t[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:s}=await r.next();if(s)return n.close();let o=wu(JSON.stringify(i)+`
237
- `);n.enqueue(o)}catch(i){n.error(i)}},async cancel(){await r.return?.()}})}};async function*T5(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new W("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new W("Attempted to iterate over a response with no body");let r=new sE,n=new Na,i=JS(e.body);for await(let s of O5(i))for(let o of n.decode(s)){let a=r.decode(o);a&&(yield a)}for(let s of n.flush()){let o=r.decode(s);o&&(yield o)}}async function*O5(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?wu(r):r,i=new Uint8Array(t.length+n.length);i.set(t),i.set(n,t.length),t=i;let s;for(;(s=Ej(t))!==-1;)yield t.slice(0,s),t=t.slice(s)}t.length>0&&(yield t)}var sE=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
238
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(t),t.startsWith(":"))return null;let[r,n,i]=$5(t,":");return i.startsWith(" ")&&(i=i.substring(1)),r==="event"?this.event=i:r==="data"&&this.data.push(i),null}};function $5(e,t){let r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}async function Gg(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:s}=t,o=await(async()=>{if(t.options.stream)return It(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(r,t.controller,e):ki.fromSSEResponse(r,t.controller,e);if(r.status===204)return null;if(t.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){let p=await r.json();return oE(p,r)}return await r.text()})();return It(e).debug(`[${n}] response parsed`,ms({retryOfRequestLogID:i,url:r.url,status:r.status,body:o,durationMs:Date.now()-s})),o}function oE(e,t){return!e||typeof e!="object"||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var wd,Ra=class e extends Promise{constructor(t,r,n=Gg){super(i=>{i(null)}),this.responsePromise=r,this.parseResponse=n,wd.set(this,void 0),se(this,wd,t,"f")}_thenUnwrap(t){return new e(k(this,wd,"f"),this.responsePromise,async(r,n)=>oE(t(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(k(this,wd,"f"),t))),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};wd=new WeakMap;var Kg,xd=class{constructor(t,r,n,i){Kg.set(this,void 0),se(this,Kg,t,"f"),this.options=i,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let t=this.nextPageRequestOptions();if(!t)throw new W("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await k(this,Kg,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(Kg=new WeakMap,Symbol.asyncIterator)](){for await(let t of this.iterPages())for(let r of t.getPaginatedItems())yield r}},Id=class extends Ra{constructor(t,r,n){super(t,r,async(i,s)=>new n(i,s.response,await Gg(i,s),s.options))}async*[Symbol.asyncIterator](){let t=await this;for await(let r of t)yield r}},Ai=class extends xd{constructor(t,r,n,i){super(t,r,n,i),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},Se=class extends xd{constructor(t,r,n,i){super(t,r,n,i),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let t=this.getPaginatedItems(),r=t[t.length-1]?.id;return r?{...this.options,query:{...HS(this.options.query),after:r}}:null}},hs=class extends xd{constructor(t,r,n,i){super(t,r,n,i),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let t=this.last_id;return t?{...this.options,query:{...HS(this.options.query),after:t}}:null}};var uE=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function xu(e,t,r){return uE(),new File(e,t??"unknown_file",r)}function Sd(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var qg=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",lE=async(e,t)=>aE(e.body)?{...e,body:await Tj(e.body,t)}:e,Qr=async(e,t)=>({...e,body:await Tj(e.body,t)}),Aj=new WeakMap;function P5(e){let t=typeof e=="function"?e:e.fetch,r=Aj.get(t);if(r)return r;let n=(async()=>{try{let i="Response"in t?t.Response:(await t("data:,")).constructor,s=new FormData;return s.toString()!==await new i(s).text()}catch{return!0}})();return Aj.set(t,n),n}var Tj=async(e,t)=>{if(!await P5(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,i])=>cE(r,n,i))),r},Oj=e=>e instanceof Blob&&"name"in e,N5=e=>typeof e=="object"&&e!==null&&(e instanceof Response||qg(e)||Oj(e)),aE=e=>{if(N5(e))return!0;if(Array.isArray(e))return e.some(aE);if(e&&typeof e=="object"){for(let t in e)if(aE(e[t]))return!0}return!1},cE=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,xu([await r.blob()],Sd(r)));else if(qg(r))e.append(t,xu([await new Response(Lg(r)).blob()],Sd(r)));else if(Oj(r))e.append(t,r,Sd(r));else if(Array.isArray(r))await Promise.all(r.map(n=>cE(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,i])=>cE(e,`${t}[${n}]`,i)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var $j=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",R5=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&$j(e),M5=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Ed(e,t,r){if(uE(),e=await e,R5(e))return e instanceof File?e:xu([await e.arrayBuffer()],e.name);if(M5(e)){let i=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),xu(await pE(i),t,r)}let n=await pE(e);if(t||(t=Sd(e)),!r?.type){let i=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof i=="string"&&(r={...r,type:i})}return xu(n,t,r)}async function pE(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if($j(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(qg(e))for await(let r of e)t.push(...await pE(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${j5(e)}`)}return t}function j5(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}var N=class{constructor(t){this._client=t}};function Pj(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Cj=Object.freeze(Object.create(null)),z5=(e=Pj)=>function(r,...n){if(r.length===1)return r[0];let i=!1,s=[],o=r.reduce((l,p,f)=>{/[?#]/.test(p)&&(i=!0);let d=n[f],m=(i?encodeURIComponent:e)(""+d);return f!==n.length&&(d==null||typeof d=="object"&&d.toString===Object.getPrototypeOf(Object.getPrototypeOf(d.hasOwnProperty??Cj)??Cj)?.toString)&&(m=d+"",s.push({start:l.length+p.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(d).slice(8,-1)} is not a valid path parameter`})),l+p+(f===n.length?"":m)},""),a=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=c.exec(a))!==null;)s.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(s.sort((l,p)=>l.start-p.start),s.length>0){let l=0,p=s.reduce((f,d)=>{let m=" ".repeat(d.start-l),h="^".repeat(d.length);return l=d.start+d.length,f+m+h},"");throw new W(`Path parameters result in path with invalid segments:
239
- ${s.map(f=>f.error).join(`
240
- `)}
241
- ${o}
242
- ${p}`)}return o},$=z5(Pj);var Ma=class extends N{list(t,r={},n){return this._client.getAPIList($`/chat/completions/${t}/messages`,Se,{query:r,...n})}};function kd(e){return e!==void 0&&"function"in e&&e.function!==void 0}function Nj(e,t){let r={...e};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),r}function Ad(e){return e?.$brand==="auto-parseable-response-format"}function ja(e){return e?.$brand==="auto-parseable-tool"}function Rj(e,t){return!t||!dE(t)?{...e,choices:e.choices.map(r=>(jj(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:Td(e,t)}function Td(e,t){let r=e.choices.map(n=>{if(n.finish_reason==="length")throw new vu;if(n.finish_reason==="content_filter")throw new bu;return jj(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(i=>B5(t,i))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?F5(t,n.message.content):null}}});return{...e,choices:r}}function F5(e,t){return e.response_format?.type!=="json_schema"?null:e.response_format?.type==="json_schema"?"$parseRaw"in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function B5(e,t){let r=e.tools?.find(n=>kd(n)&&n.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:ja(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}}function Mj(e,t){if(!e||!("tools"in e)||!e.tools)return!1;let r=e.tools?.find(n=>kd(n)&&n.function?.name===t.function.name);return kd(r)&&(ja(r)||r?.function.strict||!1)}function dE(e){return Ad(e.response_format)?!0:e.tools?.some(t=>ja(t)||t.type==="function"&&t.function.strict===!0)??!1}function jj(e){for(let t of e||[])if(t.type!=="function")throw new W(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function Dj(e){for(let t of e??[]){if(t.type!=="function")throw new W(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new W(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Iu=e=>e?.role==="assistant",fE=e=>e?.role==="tool";var mE,Hg,Wg,Od,$d,Jg,Cd,gs,Pd,Xg,Yg,Su,zj,mo=class{constructor(){mE.add(this),this.controller=new AbortController,Hg.set(this,void 0),Wg.set(this,()=>{}),Od.set(this,()=>{}),$d.set(this,void 0),Jg.set(this,()=>{}),Cd.set(this,()=>{}),gs.set(this,{}),Pd.set(this,!1),Xg.set(this,!1),Yg.set(this,!1),Su.set(this,!1),se(this,Hg,new Promise((t,r)=>{se(this,Wg,t,"f"),se(this,Od,r,"f")}),"f"),se(this,$d,new Promise((t,r)=>{se(this,Jg,t,"f"),se(this,Cd,r,"f")}),"f"),k(this,Hg,"f").catch(()=>{}),k(this,$d,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},k(this,mE,"m",zj).bind(this))},0)}_connected(){this.ended||(k(this,Wg,"f").call(this),this._emit("connect"))}get ended(){return k(this,Pd,"f")}get errored(){return k(this,Xg,"f")}get aborted(){return k(this,Yg,"f")}abort(){this.controller.abort()}on(t,r){return(k(this,gs,"f")[t]||(k(this,gs,"f")[t]=[])).push({listener:r}),this}off(t,r){let n=k(this,gs,"f")[t];if(!n)return this;let i=n.findIndex(s=>s.listener===r);return i>=0&&n.splice(i,1),this}once(t,r){return(k(this,gs,"f")[t]||(k(this,gs,"f")[t]=[])).push({listener:r,once:!0}),this}emitted(t){return new Promise((r,n)=>{se(this,Su,!0,"f"),t!=="error"&&this.once("error",n),this.once(t,r)})}async done(){se(this,Su,!0,"f"),await k(this,$d,"f")}_emit(t,...r){if(k(this,Pd,"f"))return;t==="end"&&(se(this,Pd,!0,"f"),k(this,Jg,"f").call(this));let n=k(this,gs,"f")[t];if(n&&(k(this,gs,"f")[t]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...r))),t==="abort"){let i=r[0];!k(this,Su,"f")&&!n?.length&&Promise.reject(i),k(this,Od,"f").call(this,i),k(this,Cd,"f").call(this,i),this._emit("end");return}if(t==="error"){let i=r[0];!k(this,Su,"f")&&!n?.length&&Promise.reject(i),k(this,Od,"f").call(this,i),k(this,Cd,"f").call(this,i),this._emit("end")}}_emitFinal(){}};Hg=new WeakMap,Wg=new WeakMap,Od=new WeakMap,$d=new WeakMap,Jg=new WeakMap,Cd=new WeakMap,gs=new WeakMap,Pd=new WeakMap,Xg=new WeakMap,Yg=new WeakMap,Su=new WeakMap,mE=new WeakSet,zj=function(t){if(se(this,Xg,!0,"f"),t instanceof Error&&t.name==="AbortError"&&(t=new yt),t instanceof yt)return se(this,Yg,!0,"f"),this._emit("abort",t);if(t instanceof W)return this._emit("error",t);if(t instanceof Error){let r=new W(t.message);return r.cause=t,this._emit("error",r)}return this._emit("error",new W(String(t)))};function Lj(e){return typeof e.parse=="function"}var Er,hE,Qg,gE,_E,yE,Uj,Fj,V5=10,Eu=class extends mo{constructor(){super(...arguments),Er.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(t){this._chatCompletions.push(t),this._emit("chatCompletion",t);let r=t.choices[0]?.message;return r&&this._addMessage(r),t}_addMessage(t,r=!0){if("content"in t||(t.content=null),this.messages.push(t),r){if(this._emit("message",t),fE(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(Iu(t)&&t.tool_calls)for(let n of t.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let t=this._chatCompletions[this._chatCompletions.length-1];if(!t)throw new W("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),k(this,Er,"m",hE).call(this)}async finalMessage(){return await this.done(),k(this,Er,"m",Qg).call(this)}async finalFunctionToolCall(){return await this.done(),k(this,Er,"m",gE).call(this)}async finalFunctionToolCallResult(){return await this.done(),k(this,Er,"m",_E).call(this)}async totalUsage(){return await this.done(),k(this,Er,"m",yE).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);let r=k(this,Er,"m",Qg).call(this);r&&this._emit("finalMessage",r);let n=k(this,Er,"m",hE).call(this);n&&this._emit("finalContent",n);let i=k(this,Er,"m",gE).call(this);i&&this._emit("finalFunctionToolCall",i);let s=k(this,Er,"m",_E).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(o=>o.usage)&&this._emit("totalUsage",k(this,Er,"m",yE).call(this))}async _createChatCompletion(t,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),k(this,Er,"m",Uj).call(this,r);let s=await t.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Td(s,r))}async _runChatCompletion(t,r,n){for(let i of r.messages)this._addMessage(i,!1);return await this._createChatCompletion(t,r,n)}async _runTools(t,r,n){let i="tool",{tool_choice:s="auto",stream:o,...a}=r,c=typeof s!="string"&&s.type==="function"&&s?.function?.name,{maxChatCompletions:u=V5}=n||{},l=r.tools.map(d=>{if(ja(d)){if(!d.$callback)throw new W("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:d.$callback,name:d.function.name,description:d.function.description||"",parameters:d.function.parameters,parse:d.$parseRaw,strict:!0}}}return d}),p={};for(let d of l)d.type==="function"&&(p[d.function.name||d.function.function.name]=d.function);let f="tools"in r?l.map(d=>d.type==="function"?{type:"function",function:{name:d.function.name||d.function.function.name,parameters:d.function.parameters,description:d.function.description,strict:d.function.strict}}:d):void 0;for(let d of r.messages)this._addMessage(d,!1);for(let d=0;d<u;++d){let h=(await this._createChatCompletion(t,{...a,tool_choice:s,tools:f,messages:[...this.messages]},n)).choices[0]?.message;if(!h)throw new W("missing message in ChatCompletion response");if(!h.tool_calls?.length)return;for(let b of h.tool_calls){if(b.type!=="function")continue;let _=b.id,{name:y,arguments:x}=b.function,I=p[y];if(I){if(c&&c!==y){let w=`Invalid tool_call: ${JSON.stringify(y)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:i,tool_call_id:_,content:w});continue}}else{let w=`Invalid tool_call: ${JSON.stringify(y)}. Available options are: ${Object.keys(p).map(U=>JSON.stringify(U)).join(", ")}. Please try again`;this._addMessage({role:i,tool_call_id:_,content:w});continue}let A;try{A=Lj(I)?await I.parse(x):x}catch(w){let U=w instanceof Error?w.message:String(w);this._addMessage({role:i,tool_call_id:_,content:U});continue}let j=await I.function(A,this),O=k(this,Er,"m",Fj).call(this,j);if(this._addMessage({role:i,tool_call_id:_,content:O}),c)return}}}};Er=new WeakSet,hE=function(){return k(this,Er,"m",Qg).call(this).content??null},Qg=function(){let t=this.messages.length;for(;t-- >0;){let r=this.messages[t];if(Iu(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new W("stream ended without producing a ChatCompletionMessage with role=assistant")},gE=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(Iu(r)&&r?.tool_calls?.length)return r.tool_calls.filter(n=>n.type==="function").at(-1)?.function}},_E=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(fE(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(i=>i.type==="function"&&i.id===r.tool_call_id)))return r.content}},yE=function(){let t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)r&&(t.completion_tokens+=r.completion_tokens,t.prompt_tokens+=r.prompt_tokens,t.total_tokens+=r.total_tokens);return t},Uj=function(t){if(t.n!=null&&t.n>1)throw new W("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Fj=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};var Nd=class e extends Eu{static runTools(t,r,n){let i=new e,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(t,r,s)),i}_addMessage(t,r=!0){super._addMessage(t,r),Iu(t)&&t.content&&this._emit("content",t.content)}};var Ft={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},vE=class extends Error{},bE=class extends Error{};function Z5(e,t=Ft.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return G5(e.trim(),t)}var G5=(e,t)=>{let r=e.length,n=0,i=f=>{throw new vE(`${f} at position ${n}`)},s=f=>{throw new bE(`${f} at position ${n}`)},o=()=>(p(),n>=r&&i("Unexpected end of input"),e[n]==='"'?a():e[n]==="{"?c():e[n]==="["?u():e.substring(n,n+4)==="null"||Ft.NULL&t&&r-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||Ft.BOOL&t&&r-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||Ft.BOOL&t&&r-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||Ft.INFINITY&t&&r-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||Ft.MINUS_INFINITY&t&&1<r-n&&r-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||Ft.NAN&t&&r-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):l()),a=()=>{let f=n,d=!1;for(n++;n<r&&(e[n]!=='"'||d&&e[n-1]==="\\");)d=e[n]==="\\"?!d:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(f,++n-Number(d)))}catch(m){s(String(m))}else if(Ft.STR&t)try{return JSON.parse(e.substring(f,n-Number(d))+'"')}catch{return JSON.parse(e.substring(f,e.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},c=()=>{n++,p();let f={};try{for(;e[n]!=="}";){if(p(),n>=r&&Ft.OBJ&t)return f;let d=a();p(),n++;try{let m=o();Object.defineProperty(f,d,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if(Ft.OBJ&t)return f;throw m}p(),e[n]===","&&n++}}catch{if(Ft.OBJ&t)return f;i("Expected '}' at end of object")}return n++,f},u=()=>{n++;let f=[];try{for(;e[n]!=="]";)f.push(o()),p(),e[n]===","&&n++}catch{if(Ft.ARR&t)return f;i("Expected ']' at end of array")}return n++,f},l=()=>{if(n===0){e==="-"&&Ft.NUM&t&&i("Not sure what '-' is");try{return JSON.parse(e)}catch(d){if(Ft.NUM&t)try{return e[e.length-1]==="."?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}s(String(d))}}let f=n;for(e[n]==="-"&&n++;e[n]&&!",]}".includes(e[n]);)n++;n==r&&!(Ft.NUM&t)&&i("Unterminated number literal");try{return JSON.parse(e.substring(f,n))}catch{e.substring(f,n)==="-"&&Ft.NUM&t&&i("Not sure what '-' is");try{return JSON.parse(e.substring(f,e.lastIndexOf("e")))}catch(m){s(String(m))}}},p=()=>{for(;n<r&&`
243
- \r `.includes(e[n]);)n++};return o()},wE=e=>Z5(e,Ft.ALL^Ft.NUM);var jt,_s,ku,ho,xE,e_,IE,SE,EE,t_,kE,Bj,Da=class e extends Eu{constructor(t){super(),jt.add(this),_s.set(this,void 0),ku.set(this,void 0),ho.set(this,void 0),se(this,_s,t,"f"),se(this,ku,[],"f")}get currentChatCompletionSnapshot(){return k(this,ho,"f")}static fromReadableStream(t){let r=new e(null);return r._run(()=>r._fromReadableStream(t)),r}static createChatCompletion(t,r,n){let i=new e(r);return i._run(()=>i._runChatCompletion(t,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createChatCompletion(t,r,n){super._createChatCompletion;let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),k(this,jt,"m",xE).call(this);let s=await t.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let o of s)k(this,jt,"m",IE).call(this,o);if(s.controller.signal?.aborted)throw new yt;return this._addChatCompletion(k(this,jt,"m",t_).call(this))}async _fromReadableStream(t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),k(this,jt,"m",xE).call(this),this._connected();let i=ki.fromReadableStream(t,this.controller),s;for await(let o of i)s&&s!==o.id&&this._addChatCompletion(k(this,jt,"m",t_).call(this)),k(this,jt,"m",IE).call(this,o),s=o.id;if(i.controller.signal?.aborted)throw new yt;return this._addChatCompletion(k(this,jt,"m",t_).call(this))}[(_s=new WeakMap,ku=new WeakMap,ho=new WeakMap,jt=new WeakSet,xE=function(){this.ended||se(this,ho,void 0,"f")},e_=function(r){let n=k(this,ku,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},k(this,ku,"f")[r.index]=n,n)},IE=function(r){if(this.ended)return;let n=k(this,jt,"m",Bj).call(this,r);this._emit("chunk",r,n);for(let i of r.choices){let s=n.choices[i.index];i.delta.content!=null&&s.message?.role==="assistant"&&s.message?.content&&(this._emit("content",i.delta.content,s.message.content),this._emit("content.delta",{delta:i.delta.content,snapshot:s.message.content,parsed:s.message.parsed})),i.delta.refusal!=null&&s.message?.role==="assistant"&&s.message?.refusal&&this._emit("refusal.delta",{delta:i.delta.refusal,snapshot:s.message.refusal}),i.logprobs?.content!=null&&s.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:i.logprobs?.content,snapshot:s.logprobs?.content??[]}),i.logprobs?.refusal!=null&&s.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:i.logprobs?.refusal,snapshot:s.logprobs?.refusal??[]});let o=k(this,jt,"m",e_).call(this,s);s.finish_reason&&(k(this,jt,"m",EE).call(this,s),o.current_tool_call_index!=null&&k(this,jt,"m",SE).call(this,s,o.current_tool_call_index));for(let a of i.delta.tool_calls??[])o.current_tool_call_index!==a.index&&(k(this,jt,"m",EE).call(this,s),o.current_tool_call_index!=null&&k(this,jt,"m",SE).call(this,s,o.current_tool_call_index)),o.current_tool_call_index=a.index;for(let a of i.delta.tool_calls??[]){let c=s.message.tool_calls?.[a.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:a.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(c?.type,void 0))}}},SE=function(r,n){if(k(this,jt,"m",e_).call(this,r).done_tool_calls.has(n))return;let s=r.message.tool_calls?.[n];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){let o=k(this,_s,"f")?.tools?.find(a=>kd(a)&&a.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:n,arguments:s.function.arguments,parsed_arguments:ja(o)?o.$parseRaw(s.function.arguments):o?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},EE=function(r){let n=k(this,jt,"m",e_).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let i=k(this,jt,"m",kE).call(this);this._emit("content.done",{content:r.message.content,parsed:i?i.$parseRaw(r.message.content):null})}r.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),r.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),r.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},t_=function(){if(this.ended)throw new W("stream has ended, this shouldn't happen");let r=k(this,ho,"f");if(!r)throw new W("request ended without sending any chunks");return se(this,ho,void 0,"f"),se(this,ku,[],"f"),K5(r,k(this,_s,"f"))},kE=function(){let r=k(this,_s,"f")?.response_format;return Ad(r)?r:null},Bj=function(r){var n,i,s,o;let a=k(this,ho,"f"),{choices:c,...u}=r;a?Object.assign(a,u):a=se(this,ho,{...u,choices:[]},"f");for(let{delta:l,finish_reason:p,index:f,logprobs:d=null,...m}of r.choices){let h=a.choices[f];if(h||(h=a.choices[f]={finish_reason:p,index:f,message:{},logprobs:d,...m}),d)if(!h.logprobs)h.logprobs=Object.assign({},d);else{let{content:j,refusal:O,...w}=d;Object.assign(h.logprobs,w),j&&((n=h.logprobs).content??(n.content=[]),h.logprobs.content.push(...j)),O&&((i=h.logprobs).refusal??(i.refusal=[]),h.logprobs.refusal.push(...O))}if(p&&(h.finish_reason=p,k(this,_s,"f")&&dE(k(this,_s,"f")))){if(p==="length")throw new vu;if(p==="content_filter")throw new bu}if(Object.assign(h,m),!l)continue;let{content:b,refusal:_,function_call:y,role:x,tool_calls:I,...A}=l;if(Object.assign(h.message,A),_&&(h.message.refusal=(h.message.refusal||"")+_),x&&(h.message.role=x),y&&(h.message.function_call?(y.name&&(h.message.function_call.name=y.name),y.arguments&&((s=h.message.function_call).arguments??(s.arguments=""),h.message.function_call.arguments+=y.arguments)):h.message.function_call=y),b&&(h.message.content=(h.message.content||"")+b,!h.message.refusal&&k(this,jt,"m",kE).call(this)&&(h.message.parsed=wE(h.message.content))),I){h.message.tool_calls||(h.message.tool_calls=[]);for(let{index:j,id:O,type:w,function:U,...P}of I){let V=(o=h.message.tool_calls)[j]??(o[j]={});Object.assign(V,P),O&&(V.id=O),w&&(V.type=w),U&&(V.function??(V.function={name:U.name??"",arguments:""})),U?.name&&(V.function.name=U.name),U?.arguments&&(V.function.arguments+=U.arguments,Mj(k(this,_s,"f"),V)&&(V.function.parsed_arguments=wE(V.function.arguments)))}}}return a},Symbol.asyncIterator)](){let t=[],r=[],n=!1;return this.on("chunk",i=>{let s=r.shift();s?s.resolve(i):t.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let s of r)s.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let s of r)s.reject(i);r.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,o)=>r.push({resolve:s,reject:o})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ki(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function K5(e,t){let{id:r,choices:n,created:i,model:s,system_fingerprint:o,...a}=e,c={...a,id:r,choices:n.map(({message:u,finish_reason:l,index:p,logprobs:f,...d})=>{if(!l)throw new W(`missing finish_reason for choice ${p}`);let{content:m=null,function_call:h,tool_calls:b,..._}=u,y=u.role;if(!y)throw new W(`missing role for choice ${p}`);if(h){let{arguments:x,name:I}=h;if(x==null)throw new W(`missing function_call.arguments for choice ${p}`);if(!I)throw new W(`missing function_call.name for choice ${p}`);return{...d,message:{content:m,function_call:{arguments:x,name:I},role:y,refusal:u.refusal??null},finish_reason:l,index:p,logprobs:f}}return b?{...d,index:p,finish_reason:l,logprobs:f,message:{..._,role:y,content:m,refusal:u.refusal??null,tool_calls:b.map((x,I)=>{let{function:A,type:j,id:O,...w}=x,{arguments:U,name:P,...V}=A||{};if(O==null)throw new W(`missing choices[${p}].tool_calls[${I}].id
244
- ${r_(e)}`);if(j==null)throw new W(`missing choices[${p}].tool_calls[${I}].type
245
- ${r_(e)}`);if(P==null)throw new W(`missing choices[${p}].tool_calls[${I}].function.name
246
- ${r_(e)}`);if(U==null)throw new W(`missing choices[${p}].tool_calls[${I}].function.arguments
247
- ${r_(e)}`);return{...w,id:O,type:j,function:{...V,name:P,arguments:U}}})}}:{...d,message:{..._,content:m,role:y,refusal:u.refusal??null},finish_reason:l,index:p,logprobs:f}}),created:i,model:s,object:"chat.completion",...o?{system_fingerprint:o}:{}};return Rj(c,t)}function r_(e){return JSON.stringify(e)}var Rd=class e extends Da{static fromReadableStream(t){let r=new e(null);return r._run(()=>r._fromReadableStream(t)),r}static runTools(t,r,n){let i=new e(r),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(t,r,s)),i}};var ys=class extends N{constructor(){super(...arguments),this.messages=new Ma(this._client)}create(t,r){return this._client.post("/chat/completions",{body:t,...r,stream:t.stream??!1})}retrieve(t,r){return this._client.get($`/chat/completions/${t}`,r)}update(t,r,n){return this._client.post($`/chat/completions/${t}`,{body:r,...n})}list(t={},r){return this._client.getAPIList("/chat/completions",Se,{query:t,...r})}delete(t,r){return this._client.delete($`/chat/completions/${t}`,r)}parse(t,r){return Dj(t.tools),this._client.chat.completions.create(t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>Td(n,t))}runTools(t,r){return t.stream?Rd.runTools(this._client,t,r):Nd.runTools(this._client,t,r)}stream(t,r){return Da.createChatCompletion(this._client,t,r)}};ys.Messages=Ma;var go=class extends N{constructor(){super(...arguments),this.completions=new ys(this._client)}};go.Completions=ys;var Vj=Symbol("brand.privateNullableHeaders");function*H5(e){if(!e)return;if(Vj in e){let{values:n,nulls:i}=e;yield*n.entries();for(let s of i)yield[s,null];return}let t=!1,r;e instanceof Headers?r=e.entries():qS(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let s=qS(n[1])?n[1]:[n[1]],o=!1;for(let a of s)a!==void 0&&(t&&!o&&(o=!0,yield[i,null]),yield[i,a])}}var B=e=>{let t=new Headers,r=new Set;for(let n of e){let i=new Set;for(let[s,o]of H5(n)){let a=s.toLowerCase();i.has(a)||(t.delete(s),i.add(a)),o===null?(t.delete(s),r.add(a)):(t.append(s,o),r.delete(a))}}return{[Vj]:!0,values:t,nulls:r}};var Au=class extends N{create(t,r){return this._client.post("/audio/speech",{body:t,...r,headers:B([{Accept:"application/octet-stream"},r?.headers]),__binaryResponse:!0})}};var Tu=class extends N{create(t,r){return this._client.post("/audio/transcriptions",Qr({body:t,...r,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}};var Ou=class extends N{create(t,r){return this._client.post("/audio/translations",Qr({body:t,...r,__metadata:{model:t.model}},this._client))}};var Ti=class extends N{constructor(){super(...arguments),this.transcriptions=new Tu(this._client),this.translations=new Ou(this._client),this.speech=new Au(this._client)}};Ti.Transcriptions=Tu;Ti.Translations=Ou;Ti.Speech=Au;var za=class extends N{create(t,r){return this._client.post("/batches",{body:t,...r})}retrieve(t,r){return this._client.get($`/batches/${t}`,r)}list(t={},r){return this._client.getAPIList("/batches",Se,{query:t,...r})}cancel(t,r){return this._client.post($`/batches/${t}/cancel`,r)}};var $u=class extends N{create(t,r){return this._client.post("/assistants",{body:t,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(t,r){return this._client.get($`/assistants/${t}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(t,r,n){return this._client.post($`/assistants/${t}`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(t={},r){return this._client.getAPIList("/assistants",Se,{query:t,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(t,r){return this._client.delete($`/assistants/${t}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Cu=class extends N{create(t,r){return this._client.post("/realtime/sessions",{body:t,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Pu=class extends N{create(t,r){return this._client.post("/realtime/transcription_sessions",{body:t,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var _o=class extends N{constructor(){super(...arguments),this.sessions=new Cu(this._client),this.transcriptionSessions=new Pu(this._client)}};_o.Sessions=Cu;_o.TranscriptionSessions=Pu;var Nu=class extends N{create(t,r){return this._client.post("/chatkit/sessions",{body:t,...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}cancel(t,r){return this._client.post($`/chatkit/sessions/${t}/cancel`,{...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};var Ru=class extends N{retrieve(t,r){return this._client.get($`/chatkit/threads/${t}`,{...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}list(t={},r){return this._client.getAPIList("/chatkit/threads",hs,{query:t,...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}delete(t,r){return this._client.delete($`/chatkit/threads/${t}`,{...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}listItems(t,r={},n){return this._client.getAPIList($`/chatkit/threads/${t}/items`,hs,{query:r,...n,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}};var yo=class extends N{constructor(){super(...arguments),this.sessions=new Nu(this._client),this.threads=new Ru(this._client)}};yo.Sessions=Nu;yo.Threads=Ru;var Mu=class extends N{create(t,r,n){return this._client.post($`/threads/${t}/messages`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(t,r,n){let{thread_id:i}=r;return this._client.get($`/threads/${i}/messages/${t}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(t,r,n){let{thread_id:i,...s}=r;return this._client.post($`/threads/${i}/messages/${t}`,{body:s,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(t,r={},n){return this._client.getAPIList($`/threads/${t}/messages`,Se,{query:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(t,r,n){let{thread_id:i}=r;return this._client.delete($`/threads/${i}/messages/${t}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var ju=class extends N{retrieve(t,r,n){let{thread_id:i,run_id:s,...o}=r;return this._client.get($`/threads/${i}/runs/${s}/steps/${t}`,{query:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(t,r,n){let{thread_id:i,...s}=r;return this._client.getAPIList($`/threads/${i}/runs/${t}/steps`,Se,{query:s,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Zj=e=>{if(typeof Buffer<"u"){let t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),r=t.length,n=new Uint8Array(r);for(let i=0;i<r;i++)n[i]=t.charCodeAt(i);return Array.from(new Float32Array(n.buffer))}};var vo=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()};var Kt,Ua,AE,Oi,n_,Wn,Fa,Du,La,o_,en,i_,s_,Dd,Md,jd,Gj,Kj,qj,Hj,Wj,Jj,Xj,vs=class extends mo{constructor(){super(...arguments),Kt.add(this),AE.set(this,[]),Oi.set(this,{}),n_.set(this,{}),Wn.set(this,void 0),Fa.set(this,void 0),Du.set(this,void 0),La.set(this,void 0),o_.set(this,void 0),en.set(this,void 0),i_.set(this,void 0),s_.set(this,void 0),Dd.set(this,void 0)}[(AE=new WeakMap,Oi=new WeakMap,n_=new WeakMap,Wn=new WeakMap,Fa=new WeakMap,Du=new WeakMap,La=new WeakMap,o_=new WeakMap,en=new WeakMap,i_=new WeakMap,s_=new WeakMap,Dd=new WeakMap,Kt=new WeakSet,Symbol.asyncIterator)](){let t=[],r=[],n=!1;return this.on("event",i=>{let s=r.shift();s?s.resolve(i):t.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let s of r)s.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let s of r)s.reject(i);r.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,o)=>r.push({resolve:s,reject:o})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(t){let r=new Ua;return r._run(()=>r._fromReadableStream(t)),r}async _fromReadableStream(t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let i=ki.fromReadableStream(t,this.controller);for await(let s of i)k(this,Kt,"m",Md).call(this,s);if(i.controller.signal?.aborted)throw new yt;return this._addRun(k(this,Kt,"m",jd).call(this))}toReadableStream(){return new ki(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,r,n,i){let s=new Ua;return s._run(()=>s._runToolAssistantStream(t,r,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(t,r,n,i){let s=i?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...n,stream:!0},a=await t.submitToolOutputs(r,o,{...i,signal:this.controller.signal});this._connected();for await(let c of a)k(this,Kt,"m",Md).call(this,c);if(a.controller.signal?.aborted)throw new yt;return this._addRun(k(this,Kt,"m",jd).call(this))}static createThreadAssistantStream(t,r,n){let i=new Ua;return i._run(()=>i._threadAssistantStream(t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}static createAssistantStream(t,r,n,i){let s=new Ua;return s._run(()=>s._runAssistantStream(t,r,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return k(this,i_,"f")}currentRun(){return k(this,s_,"f")}currentMessageSnapshot(){return k(this,Wn,"f")}currentRunStepSnapshot(){return k(this,Dd,"f")}async finalRunSteps(){return await this.done(),Object.values(k(this,Oi,"f"))}async finalMessages(){return await this.done(),Object.values(k(this,n_,"f"))}async finalRun(){if(await this.done(),!k(this,Fa,"f"))throw Error("Final run was not received.");return k(this,Fa,"f")}async _createThreadAssistantStream(t,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let s={...r,stream:!0},o=await t.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(let a of o)k(this,Kt,"m",Md).call(this,a);if(o.controller.signal?.aborted)throw new yt;return this._addRun(k(this,Kt,"m",jd).call(this))}async _createAssistantStream(t,r,n,i){let s=i?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...n,stream:!0},a=await t.create(r,o,{...i,signal:this.controller.signal});this._connected();for await(let c of a)k(this,Kt,"m",Md).call(this,c);if(a.controller.signal?.aborted)throw new yt;return this._addRun(k(this,Kt,"m",jd).call(this))}static accumulateDelta(t,r){for(let[n,i]of Object.entries(r)){if(!t.hasOwnProperty(n)){t[n]=i;continue}let s=t[n];if(s==null){t[n]=i;continue}if(n==="index"||n==="type"){t[n]=i;continue}if(typeof s=="string"&&typeof i=="string")s+=i;else if(typeof s=="number"&&typeof i=="number")s+=i;else if(yd(s)&&yd(i))s=this.accumulateDelta(s,i);else if(Array.isArray(s)&&Array.isArray(i)){if(s.every(o=>typeof o=="string"||typeof o=="number")){s.push(...i);continue}for(let o of i){if(!yd(o))throw new Error(`Expected array delta entry to be an object but got: ${o}`);let a=o.index;if(a==null)throw console.error(o),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=s[a];c==null?s.push(o):s[a]=this.accumulateDelta(c,o)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${i}, accValue: ${s}`);t[n]=s}return t}_addRun(t){return t}async _threadAssistantStream(t,r,n){return await this._createThreadAssistantStream(r,t,n)}async _runAssistantStream(t,r,n,i){return await this._createAssistantStream(r,t,n,i)}async _runToolAssistantStream(t,r,n,i){return await this._createToolAssistantStream(r,t,n,i)}};Ua=vs,Md=function(t){if(!this.ended)switch(se(this,i_,t,"f"),k(this,Kt,"m",qj).call(this,t),t.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":k(this,Kt,"m",Xj).call(this,t);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":k(this,Kt,"m",Kj).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":k(this,Kt,"m",Gj).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},jd=function(){if(this.ended)throw new W("stream has ended, this shouldn't happen");if(!k(this,Fa,"f"))throw Error("Final run has not been received");return k(this,Fa,"f")},Gj=function(t){let[r,n]=k(this,Kt,"m",Wj).call(this,t,k(this,Wn,"f"));se(this,Wn,r,"f"),k(this,n_,"f")[r.id]=r;for(let i of n){let s=r.content[i.index];s?.type=="text"&&this._emit("textCreated",s.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,r),t.data.delta.content)for(let i of t.data.delta.content){if(i.type=="text"&&i.text){let s=i.text,o=r.content[i.index];if(o&&o.type=="text")this._emit("textDelta",s,o.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(i.index!=k(this,Du,"f")){if(k(this,La,"f"))switch(k(this,La,"f").type){case"text":this._emit("textDone",k(this,La,"f").text,k(this,Wn,"f"));break;case"image_file":this._emit("imageFileDone",k(this,La,"f").image_file,k(this,Wn,"f"));break}se(this,Du,i.index,"f")}se(this,La,r.content[i.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(k(this,Du,"f")!==void 0){let i=t.data.content[k(this,Du,"f")];if(i)switch(i.type){case"image_file":this._emit("imageFileDone",i.image_file,k(this,Wn,"f"));break;case"text":this._emit("textDone",i.text,k(this,Wn,"f"));break}}k(this,Wn,"f")&&this._emit("messageDone",t.data),se(this,Wn,void 0,"f")}},Kj=function(t){let r=k(this,Kt,"m",Hj).call(this,t);switch(se(this,Dd,r,"f"),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":let n=t.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let s of n.step_details.tool_calls)s.index==k(this,o_,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(k(this,en,"f")&&this._emit("toolCallDone",k(this,en,"f")),se(this,o_,s.index,"f"),se(this,en,r.step_details.tool_calls[s.index],"f"),k(this,en,"f")&&this._emit("toolCallCreated",k(this,en,"f")));this._emit("runStepDelta",t.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":se(this,Dd,void 0,"f"),t.data.step_details.type=="tool_calls"&&k(this,en,"f")&&(this._emit("toolCallDone",k(this,en,"f")),se(this,en,void 0,"f")),this._emit("runStepDone",t.data,r);break;case"thread.run.step.in_progress":break}},qj=function(t){k(this,AE,"f").push(t),this._emit("event",t)},Hj=function(t){switch(t.event){case"thread.run.step.created":return k(this,Oi,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let r=k(this,Oi,"f")[t.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=t.data;if(n.delta){let i=Ua.accumulateDelta(r,n.delta);k(this,Oi,"f")[t.data.id]=i}return k(this,Oi,"f")[t.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":k(this,Oi,"f")[t.data.id]=t.data;break}if(k(this,Oi,"f")[t.data.id])return k(this,Oi,"f")[t.data.id];throw new Error("No snapshot available")},Wj=function(t,r){let n=[];switch(t.event){case"thread.message.created":return[t.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let i=t.data;if(i.delta.content)for(let s of i.delta.content)if(s.index in r.content){let o=r.content[s.index];r.content[s.index]=k(this,Kt,"m",Jj).call(this,s,o)}else r.content[s.index]=s,n.push(s);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Jj=function(t,r){return Ua.accumulateDelta(r,t)},Xj=function(t){switch(se(this,s_,t.data,"f"),t.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":se(this,Fa,t.data,"f"),k(this,en,"f")&&(this._emit("toolCallDone",k(this,en,"f")),se(this,en,void 0,"f"));break;case"thread.run.cancelling":break}};var Ba=class extends N{constructor(){super(...arguments),this.steps=new ju(this._client)}create(t,r,n){let{include:i,...s}=r;return this._client.post($`/threads/${t}/runs`,{query:{include:i},body:s,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1})}retrieve(t,r,n){let{thread_id:i}=r;return this._client.get($`/threads/${i}/runs/${t}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(t,r,n){let{thread_id:i,...s}=r;return this._client.post($`/threads/${i}/runs/${t}`,{body:s,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(t,r={},n){return this._client.getAPIList($`/threads/${t}/runs`,Se,{query:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(t,r,n){let{thread_id:i}=r;return this._client.post($`/threads/${i}/runs/${t}/cancel`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(t,r,n){let i=await this.create(t,r,n);return await this.poll(i.id,{thread_id:t},n)}createAndStream(t,r,n){return vs.createAssistantStream(t,this._client.beta.threads.runs,r,n)}async poll(t,r,n){let i=B([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:o}=await this.retrieve(t,r,{...n,headers:{...n?.headers,...i}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=o.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(a=u)}}await Si(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(t,r,n){return vs.createAssistantStream(t,this._client.beta.threads.runs,r,n)}submitToolOutputs(t,r,n){let{thread_id:i,...s}=r;return this._client.post($`/threads/${i}/runs/${t}/submit_tool_outputs`,{body:s,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1})}async submitToolOutputsAndPoll(t,r,n){let i=await this.submitToolOutputs(t,r,n);return await this.poll(i.id,r,n)}submitToolOutputsStream(t,r,n){return vs.createToolAssistantStream(t,this._client.beta.threads.runs,r,n)}};Ba.Steps=ju;var bo=class extends N{constructor(){super(...arguments),this.runs=new Ba(this._client),this.messages=new Mu(this._client)}create(t={},r){return this._client.post("/threads",{body:t,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(t,r){return this._client.get($`/threads/${t}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(t,r,n){return this._client.post($`/threads/${t}`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(t,r){return this._client.delete($`/threads/${t}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}createAndRun(t,r){return this._client.post("/threads/runs",{body:t,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async createAndRunPoll(t,r){let n=await this.createAndRun(t,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(t,r){return vs.createThreadAssistantStream(t,this._client.beta.threads,r)}};bo.Runs=Ba;bo.Messages=Mu;var Jn=class extends N{constructor(){super(...arguments),this.realtime=new _o(this._client),this.chatkit=new yo(this._client),this.assistants=new $u(this._client),this.threads=new bo(this._client)}};Jn.Realtime=_o;Jn.ChatKit=yo;Jn.Assistants=$u;Jn.Threads=bo;var Va=class extends N{create(t,r){return this._client.post("/completions",{body:t,...r,stream:t.stream??!1})}};var zu=class extends N{retrieve(t,r,n){let{container_id:i}=r;return this._client.get($`/containers/${i}/files/${t}/content`,{...n,headers:B([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}};var Za=class extends N{constructor(){super(...arguments),this.content=new zu(this._client)}create(t,r,n){return this._client.post($`/containers/${t}/files`,Qr({body:r,...n},this._client))}retrieve(t,r,n){let{container_id:i}=r;return this._client.get($`/containers/${i}/files/${t}`,n)}list(t,r={},n){return this._client.getAPIList($`/containers/${t}/files`,Se,{query:r,...n})}delete(t,r,n){let{container_id:i}=r;return this._client.delete($`/containers/${i}/files/${t}`,{...n,headers:B([{Accept:"*/*"},n?.headers])})}};Za.Content=zu;var wo=class extends N{constructor(){super(...arguments),this.files=new Za(this._client)}create(t,r){return this._client.post("/containers",{body:t,...r})}retrieve(t,r){return this._client.get($`/containers/${t}`,r)}list(t={},r){return this._client.getAPIList("/containers",Se,{query:t,...r})}delete(t,r){return this._client.delete($`/containers/${t}`,{...r,headers:B([{Accept:"*/*"},r?.headers])})}};wo.Files=Za;var Lu=class extends N{create(t,r,n){let{include:i,...s}=r;return this._client.post($`/conversations/${t}/items`,{query:{include:i},body:s,...n})}retrieve(t,r,n){let{conversation_id:i,...s}=r;return this._client.get($`/conversations/${i}/items/${t}`,{query:s,...n})}list(t,r={},n){return this._client.getAPIList($`/conversations/${t}/items`,hs,{query:r,...n})}delete(t,r,n){let{conversation_id:i}=r;return this._client.delete($`/conversations/${i}/items/${t}`,n)}};var xo=class extends N{constructor(){super(...arguments),this.items=new Lu(this._client)}create(t={},r){return this._client.post("/conversations",{body:t,...r})}retrieve(t,r){return this._client.get($`/conversations/${t}`,r)}update(t,r,n){return this._client.post($`/conversations/${t}`,{body:r,...n})}delete(t,r){return this._client.delete($`/conversations/${t}`,r)}};xo.Items=Lu;var Ga=class extends N{create(t,r){let n=!!t.encoding_format,i=n?t.encoding_format:"base64";n&&It(this._client).debug("embeddings/user defined encoding_format:",t.encoding_format);let s=this._client.post("/embeddings",{body:{...t,encoding_format:i},...r});return n?s:(It(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(o=>(o&&o.data&&o.data.forEach(a=>{let c=a.embedding;a.embedding=Zj(c)}),o)))}};var Uu=class extends N{retrieve(t,r,n){let{eval_id:i,run_id:s}=r;return this._client.get($`/evals/${i}/runs/${s}/output_items/${t}`,n)}list(t,r,n){let{eval_id:i,...s}=r;return this._client.getAPIList($`/evals/${i}/runs/${t}/output_items`,Se,{query:s,...n})}};var Ka=class extends N{constructor(){super(...arguments),this.outputItems=new Uu(this._client)}create(t,r,n){return this._client.post($`/evals/${t}/runs`,{body:r,...n})}retrieve(t,r,n){let{eval_id:i}=r;return this._client.get($`/evals/${i}/runs/${t}`,n)}list(t,r={},n){return this._client.getAPIList($`/evals/${t}/runs`,Se,{query:r,...n})}delete(t,r,n){let{eval_id:i}=r;return this._client.delete($`/evals/${i}/runs/${t}`,n)}cancel(t,r,n){let{eval_id:i}=r;return this._client.post($`/evals/${i}/runs/${t}`,n)}};Ka.OutputItems=Uu;var Io=class extends N{constructor(){super(...arguments),this.runs=new Ka(this._client)}create(t,r){return this._client.post("/evals",{body:t,...r})}retrieve(t,r){return this._client.get($`/evals/${t}`,r)}update(t,r,n){return this._client.post($`/evals/${t}`,{body:r,...n})}list(t={},r){return this._client.getAPIList("/evals",Se,{query:t,...r})}delete(t,r){return this._client.delete($`/evals/${t}`,r)}};Io.Runs=Ka;var qa=class extends N{create(t,r){return this._client.post("/files",Qr({body:t,...r},this._client))}retrieve(t,r){return this._client.get($`/files/${t}`,r)}list(t={},r){return this._client.getAPIList("/files",Se,{query:t,...r})}delete(t,r){return this._client.delete($`/files/${t}`,r)}content(t,r){return this._client.get($`/files/${t}/content`,{...r,headers:B([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}async waitForProcessing(t,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let i=new Set(["processed","error","deleted"]),s=Date.now(),o=await this.retrieve(t);for(;!o.status||!i.has(o.status);)if(await Si(r),o=await this.retrieve(t),Date.now()-s>n)throw new xi({message:`Giving up on waiting for file ${t} to finish processing after ${n} milliseconds.`});return o}};var Fu=class extends N{};var Bu=class extends N{run(t,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:t,...r})}validate(t,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:t,...r})}};var Ha=class extends N{constructor(){super(...arguments),this.graders=new Bu(this._client)}};Ha.Graders=Bu;var Vu=class extends N{create(t,r,n){return this._client.getAPIList($`/fine_tuning/checkpoints/${t}/permissions`,Ai,{body:r,method:"post",...n})}retrieve(t,r={},n){return this._client.get($`/fine_tuning/checkpoints/${t}/permissions`,{query:r,...n})}delete(t,r,n){let{fine_tuned_model_checkpoint:i}=r;return this._client.delete($`/fine_tuning/checkpoints/${i}/permissions/${t}`,n)}};var Wa=class extends N{constructor(){super(...arguments),this.permissions=new Vu(this._client)}};Wa.Permissions=Vu;var Zu=class extends N{list(t,r={},n){return this._client.getAPIList($`/fine_tuning/jobs/${t}/checkpoints`,Se,{query:r,...n})}};var Ja=class extends N{constructor(){super(...arguments),this.checkpoints=new Zu(this._client)}create(t,r){return this._client.post("/fine_tuning/jobs",{body:t,...r})}retrieve(t,r){return this._client.get($`/fine_tuning/jobs/${t}`,r)}list(t={},r){return this._client.getAPIList("/fine_tuning/jobs",Se,{query:t,...r})}cancel(t,r){return this._client.post($`/fine_tuning/jobs/${t}/cancel`,r)}listEvents(t,r={},n){return this._client.getAPIList($`/fine_tuning/jobs/${t}/events`,Se,{query:r,...n})}pause(t,r){return this._client.post($`/fine_tuning/jobs/${t}/pause`,r)}resume(t,r){return this._client.post($`/fine_tuning/jobs/${t}/resume`,r)}};Ja.Checkpoints=Zu;var Xn=class extends N{constructor(){super(...arguments),this.methods=new Fu(this._client),this.jobs=new Ja(this._client),this.checkpoints=new Wa(this._client),this.alpha=new Ha(this._client)}};Xn.Methods=Fu;Xn.Jobs=Ja;Xn.Checkpoints=Wa;Xn.Alpha=Ha;var Gu=class extends N{};var So=class extends N{constructor(){super(...arguments),this.graderModels=new Gu(this._client)}};So.GraderModels=Gu;var Xa=class extends N{createVariation(t,r){return this._client.post("/images/variations",Qr({body:t,...r},this._client))}edit(t,r){return this._client.post("/images/edits",Qr({body:t,...r,stream:t.stream??!1},this._client))}generate(t,r){return this._client.post("/images/generations",{body:t,...r,stream:t.stream??!1})}};var Ya=class extends N{retrieve(t,r){return this._client.get($`/models/${t}`,r)}list(t){return this._client.getAPIList("/models",Ai,t)}delete(t,r){return this._client.delete($`/models/${t}`,r)}};var Qa=class extends N{create(t,r){return this._client.post("/moderations",{body:t,...r})}};var Ku=class extends N{accept(t,r,n){return this._client.post($`/realtime/calls/${t}/accept`,{body:r,...n,headers:B([{Accept:"*/*"},n?.headers])})}hangup(t,r){return this._client.post($`/realtime/calls/${t}/hangup`,{...r,headers:B([{Accept:"*/*"},r?.headers])})}refer(t,r,n){return this._client.post($`/realtime/calls/${t}/refer`,{body:r,...n,headers:B([{Accept:"*/*"},n?.headers])})}reject(t,r={},n){return this._client.post($`/realtime/calls/${t}/reject`,{body:r,...n,headers:B([{Accept:"*/*"},n?.headers])})}};var qu=class extends N{create(t,r){return this._client.post("/realtime/client_secrets",{body:t,...r})}};var bs=class extends N{constructor(){super(...arguments),this.clientSecrets=new qu(this._client),this.calls=new Ku(this._client)}};bs.ClientSecrets=qu;bs.Calls=Ku;function Yj(e,t){return!t||!EK(t)?{...e,output_parsed:null,output:e.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)}:TE(e,t)}function TE(e,t){let r=e.output.map(i=>{if(i.type==="function_call")return{...i,parsed_arguments:TK(t,i)};if(i.type==="message"){let s=i.content.map(o=>o.type==="output_text"?{...o,parsed:SK(t,o.text)}:o);return{...i,content:s}}return i}),n=Object.assign({},e,{output:r});return Object.getOwnPropertyDescriptor(e,"output_text")||a_(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let i of n.output)if(i.type==="message"){for(let s of i.content)if(s.type==="output_text"&&s.parsed!==null)return s.parsed}return null}}),n}function SK(e,t){return e.text?.format?.type!=="json_schema"?null:"$parseRaw"in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t)}function EK(e){return!!Ad(e.text?.format)}function kK(e){return e?.$brand==="auto-parseable-tool"}function AK(e,t){return e.find(r=>r.type==="function"&&r.name===t)}function TK(e,t){let r=AK(e.tools??[],t.name);return{...t,...t,parsed_arguments:kK(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function a_(e){let t=[];for(let r of e.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&t.push(n.text);e.output_text=t.join("")}var Hu,c_,Eo,u_,Qj,eD,tD,rD,l_=class e extends mo{constructor(t){super(),Hu.add(this),c_.set(this,void 0),Eo.set(this,void 0),u_.set(this,void 0),se(this,c_,t,"f")}static createResponse(t,r,n){let i=new e(r);return i._run(()=>i._createOrRetrieveResponse(t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createOrRetrieveResponse(t,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),k(this,Hu,"m",Qj).call(this);let s,o=null;"response_id"in r?(s=await t.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),o=r.starting_after??null):s=await t.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let a of s)k(this,Hu,"m",eD).call(this,a,o);if(s.controller.signal?.aborted)throw new yt;return k(this,Hu,"m",tD).call(this)}[(c_=new WeakMap,Eo=new WeakMap,u_=new WeakMap,Hu=new WeakSet,Qj=function(){this.ended||se(this,Eo,void 0,"f")},eD=function(r,n){if(this.ended)return;let i=(o,a)=>{(n==null||a.sequence_number>n)&&this._emit(o,a)},s=k(this,Hu,"m",rD).call(this,r);switch(i("event",r),r.type){case"response.output_text.delta":{let o=s.output[r.output_index];if(!o)throw new W(`missing output at index ${r.output_index}`);if(o.type==="message"){let a=o.content[r.content_index];if(!a)throw new W(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new W(`expected content to be 'output_text', got ${a.type}`);i("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let o=s.output[r.output_index];if(!o)throw new W(`missing output at index ${r.output_index}`);o.type==="function_call"&&i("response.function_call_arguments.delta",{...r,snapshot:o.arguments});break}default:i(r.type,r);break}},tD=function(){if(this.ended)throw new W("stream has ended, this shouldn't happen");let r=k(this,Eo,"f");if(!r)throw new W("request ended without sending any events");se(this,Eo,void 0,"f");let n=OK(r,k(this,c_,"f"));return se(this,u_,n,"f"),n},rD=function(r){let n=k(this,Eo,"f");if(!n){if(r.type!=="response.created")throw new W(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return n=se(this,Eo,r.response,"f"),n}switch(r.type){case"response.output_item.added":{n.output.push(r.item);break}case"response.content_part.added":{let i=n.output[r.output_index];if(!i)throw new W(`missing output at index ${r.output_index}`);let s=i.type,o=r.part;s==="message"&&o.type!=="reasoning_text"?i.content.push(o):s==="reasoning"&&o.type==="reasoning_text"&&(i.content||(i.content=[]),i.content.push(o));break}case"response.output_text.delta":{let i=n.output[r.output_index];if(!i)throw new W(`missing output at index ${r.output_index}`);if(i.type==="message"){let s=i.content[r.content_index];if(!s)throw new W(`missing content at index ${r.content_index}`);if(s.type!=="output_text")throw new W(`expected content to be 'output_text', got ${s.type}`);s.text+=r.delta}break}case"response.function_call_arguments.delta":{let i=n.output[r.output_index];if(!i)throw new W(`missing output at index ${r.output_index}`);i.type==="function_call"&&(i.arguments+=r.delta);break}case"response.reasoning_text.delta":{let i=n.output[r.output_index];if(!i)throw new W(`missing output at index ${r.output_index}`);if(i.type==="reasoning"){let s=i.content?.[r.content_index];if(!s)throw new W(`missing content at index ${r.content_index}`);if(s.type!=="reasoning_text")throw new W(`expected content to be 'reasoning_text', got ${s.type}`);s.text+=r.delta}break}case"response.completed":{se(this,Eo,r.response,"f");break}}return n},Symbol.asyncIterator)](){let t=[],r=[],n=!1;return this.on("event",i=>{let s=r.shift();s?s.resolve(i):t.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let s of r)s.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let s of r)s.reject(i);r.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,o)=>r.push({resolve:s,reject:o})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let t=k(this,u_,"f");if(!t)throw new W("stream ended without producing a ChatCompletion");return t}};function OK(e,t){return Yj(e,t)}var Wu=class extends N{list(t,r={},n){return this._client.getAPIList($`/responses/${t}/input_items`,Se,{query:r,...n})}};var Ju=class extends N{count(t={},r){return this._client.post("/responses/input_tokens",{body:t,...r})}};var ws=class extends N{constructor(){super(...arguments),this.inputItems=new Wu(this._client),this.inputTokens=new Ju(this._client)}create(t,r){return this._client.post("/responses",{body:t,...r,stream:t.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&a_(n),n))}retrieve(t,r={},n){return this._client.get($`/responses/${t}`,{query:r,...n,stream:r?.stream??!1})._thenUnwrap(i=>("object"in i&&i.object==="response"&&a_(i),i))}delete(t,r){return this._client.delete($`/responses/${t}`,{...r,headers:B([{Accept:"*/*"},r?.headers])})}parse(t,r){return this._client.responses.create(t,r)._thenUnwrap(n=>TE(n,t))}stream(t,r){return l_.createResponse(this._client,t,r)}cancel(t,r){return this._client.post($`/responses/${t}/cancel`,r)}compact(t,r){return this._client.post("/responses/compact",{body:t,...r})}};ws.InputItems=Wu;ws.InputTokens=Ju;var Xu=class extends N{create(t,r,n){return this._client.post($`/uploads/${t}/parts`,Qr({body:r,...n},this._client))}};var ko=class extends N{constructor(){super(...arguments),this.parts=new Xu(this._client)}create(t,r){return this._client.post("/uploads",{body:t,...r})}cancel(t,r){return this._client.post($`/uploads/${t}/cancel`,r)}complete(t,r,n){return this._client.post($`/uploads/${t}/complete`,{body:r,...n})}};ko.Parts=Xu;var nD=async e=>{let t=await Promise.allSettled(e),r=t.filter(i=>i.status==="rejected");if(r.length){for(let i of r)console.error(i.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let i of t)i.status==="fulfilled"&&n.push(i.value);return n};var Yu=class extends N{create(t,r,n){return this._client.post($`/vector_stores/${t}/file_batches`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(t,r,n){let{vector_store_id:i}=r;return this._client.get($`/vector_stores/${i}/file_batches/${t}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(t,r,n){let{vector_store_id:i}=r;return this._client.post($`/vector_stores/${i}/file_batches/${t}/cancel`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(t,r,n){let i=await this.create(t,r);return await this.poll(t,i.id,n)}listFiles(t,r,n){let{vector_store_id:i,...s}=r;return this._client.getAPIList($`/vector_stores/${i}/file_batches/${t}/files`,Se,{query:s,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(t,r,n){let i=B([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:o}=await this.retrieve(r,{vector_store_id:t},{...n,headers:i}).withResponse();switch(s.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=o.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(a=u)}}await Si(a);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(t,{files:r,fileIds:n=[]},i){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=i?.maxConcurrency??5,o=Math.min(s,r.length),a=this._client,c=r.values(),u=[...n];async function l(f){for(let d of f){let m=await a.files.create({file:d,purpose:"assistants"},i);u.push(m.id)}}let p=Array(o).fill(c).map(l);return await nD(p),await this.createAndPoll(t,{file_ids:u})}};var Qu=class extends N{create(t,r,n){return this._client.post($`/vector_stores/${t}/files`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(t,r,n){let{vector_store_id:i}=r;return this._client.get($`/vector_stores/${i}/files/${t}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(t,r,n){let{vector_store_id:i,...s}=r;return this._client.post($`/vector_stores/${i}/files/${t}`,{body:s,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(t,r={},n){return this._client.getAPIList($`/vector_stores/${t}/files`,Se,{query:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(t,r,n){let{vector_store_id:i}=r;return this._client.delete($`/vector_stores/${i}/files/${t}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(t,r,n){let i=await this.create(t,r,n);return await this.poll(t,i.id,n)}async poll(t,r,n){let i=B([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(r,{vector_store_id:t},{...n,headers:i}).withResponse(),o=s.data;switch(o.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=s.response.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(a=u)}}await Si(a);break;case"failed":case"completed":return o}}}async upload(t,r,n){let i=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(t,{file_id:i.id},n)}async uploadAndPoll(t,r,n){let i=await this.upload(t,r,n);return await this.poll(t,i.id,n)}content(t,r,n){let{vector_store_id:i}=r;return this._client.getAPIList($`/vector_stores/${i}/files/${t}/content`,Ai,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var xs=class extends N{constructor(){super(...arguments),this.files=new Qu(this._client),this.fileBatches=new Yu(this._client)}create(t,r){return this._client.post("/vector_stores",{body:t,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(t,r){return this._client.get($`/vector_stores/${t}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(t,r,n){return this._client.post($`/vector_stores/${t}`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(t={},r){return this._client.getAPIList("/vector_stores",Se,{query:t,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(t,r){return this._client.delete($`/vector_stores/${t}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}search(t,r,n){return this._client.getAPIList($`/vector_stores/${t}/search`,Ai,{body:r,method:"post",...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};xs.Files=Qu;xs.FileBatches=Yu;var ec=class extends N{create(t,r){return this._client.post("/videos",lE({body:t,...r},this._client))}retrieve(t,r){return this._client.get($`/videos/${t}`,r)}list(t={},r){return this._client.getAPIList("/videos",hs,{query:t,...r})}delete(t,r){return this._client.delete($`/videos/${t}`,r)}downloadContent(t,r={},n){return this._client.get($`/videos/${t}/content`,{query:r,...n,headers:B([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}remix(t,r,n){return this._client.post($`/videos/${t}/remix`,lE({body:r,...n},this._client))}};var el,iD,p_,tc=class extends N{constructor(){super(...arguments),el.add(this)}async unwrap(t,r,n=this._client.webhookSecret,i=300){return await this.verifySignature(t,r,n,i),JSON.parse(t)}async verifySignature(t,r,n=this._client.webhookSecret,i=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");k(this,el,"m",iD).call(this,n);let s=B([r]).values,o=k(this,el,"m",p_).call(this,s,"webhook-signature"),a=k(this,el,"m",p_).call(this,s,"webhook-timestamp"),c=k(this,el,"m",p_).call(this,s,"webhook-id"),u=parseInt(a,10);if(isNaN(u))throw new Ii("Invalid webhook timestamp format");let l=Math.floor(Date.now()/1e3);if(l-u>i)throw new Ii("Webhook timestamp is too old");if(u>l+i)throw new Ii("Webhook timestamp is too new");let p=o.split(" ").map(h=>h.startsWith("v1,")?h.substring(3):h),f=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),d=c?`${c}.${a}.${t}`:`${a}.${t}`,m=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let h of p)try{let b=Buffer.from(h,"base64");if(await crypto.subtle.verify("HMAC",m,b,new TextEncoder().encode(d)))return}catch{continue}throw new Ii("The given webhook signature does not match the expected signature")}};el=new WeakSet,iD=function(t){if(typeof t!="string"||t.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},p_=function(t,r){if(!t)throw new Error("Headers are required");let n=t.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var OE,$E,d_,sD,de=class{constructor({baseURL:t=vo("OPENAI_BASE_URL"),apiKey:r=vo("OPENAI_API_KEY"),organization:n=vo("OPENAI_ORG_ID")??null,project:i=vo("OPENAI_PROJECT_ID")??null,webhookSecret:s=vo("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(OE.add(this),d_.set(this,void 0),this.completions=new Va(this),this.chat=new go(this),this.embeddings=new Ga(this),this.files=new qa(this),this.images=new Xa(this),this.audio=new Ti(this),this.moderations=new Qa(this),this.models=new Ya(this),this.fineTuning=new Xn(this),this.graders=new So(this),this.vectorStores=new xs(this),this.webhooks=new tc(this),this.beta=new Jn(this),this.batches=new za(this),this.uploads=new ko(this),this.responses=new ws(this),this.realtime=new bs(this),this.conversations=new xo(this),this.evals=new Io(this),this.containers=new wo(this),this.videos=new ec(this),r===void 0)throw new W("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:r,organization:n,project:i,webhookSecret:s,...o,baseURL:t||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&pj())throw new W(`It looks like you're running in a browser-like environment.
248
-
249
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
250
- If you understand the risks and have appropriate mitigations in place,
251
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
252
-
253
- new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
254
-
255
- https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
256
- `);this.baseURL=a.baseURL,this.timeout=a.timeout??$E.DEFAULT_TIMEOUT,this.logger=a.logger??console;let c="warn";this.logLevel=c,this.logLevel=iE(a.logLevel,"ClientOptions.logLevel",this)??iE(vo("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??fj(),se(this,d_,hj,"f"),this._options=a,this.apiKey=typeof r=="string"?r:"Missing Key",this.organization=n,this.project=i,this.webhookSecret=s}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...t})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:r}){}async authHeaders(t){return B([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return rE(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${fo}`}defaultIdempotencyKey(){return`stainless-node-retry-${KS()}`}makeStatusError(t,r,n,i){return Rt.generate(t,r,n,i)}async _callApiKey(){let t=this._options.apiKey;if(typeof t!="function")return!1;let r;try{r=await t()}catch(n){throw n instanceof W?n:new W(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new W(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(t,r,n){let i=!k(this,OE,"m",sD).call(this)&&n||this.baseURL,s=nj(t)?new URL(t):new URL(i+(i.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),o=this.defaultQuery();return ij(o)||(r={...o,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(t){await this._callApiKey()}async prepareRequest(t,{url:r,options:n}){}get(t,r){return this.methodRequest("get",t,r)}post(t,r){return this.methodRequest("post",t,r)}patch(t,r){return this.methodRequest("patch",t,r)}put(t,r){return this.methodRequest("put",t,r)}delete(t,r){return this.methodRequest("delete",t,r)}methodRequest(t,r,n){return this.request(Promise.resolve(n).then(i=>({method:t,path:r,...i})))}request(t,r=null){return new Ra(this,this.makeRequest(t,r,void 0))}async makeRequest(t,r,n){let i=await t,s=i.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(i);let{req:o,url:a,timeout:c}=await this.buildRequest(i,{retryCount:s-r});await this.prepareRequest(o,{url:a,options:i});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=n===void 0?"":`, retryOf: ${n}`,p=Date.now();if(It(this).debug(`[${u}] sending request`,ms({retryOfRequestLogID:n,method:i.method,url:a,options:i,headers:o.headers})),i.signal?.aborted)throw new yt;let f=new AbortController,d=await this.fetchWithTimeout(a,o,c,f).catch(_d),m=Date.now();if(d instanceof globalThis.Error){let _=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new yt;let y=gd(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):""));if(r)return It(this).info(`[${u}] connection ${y?"timed out":"failed"} - ${_}`),It(this).debug(`[${u}] connection ${y?"timed out":"failed"} (${_})`,ms({retryOfRequestLogID:n,url:a,durationMs:m-p,message:d.message})),this.retryRequest(i,r,n??u);throw It(this).info(`[${u}] connection ${y?"timed out":"failed"} - error; no more retries left`),It(this).debug(`[${u}] connection ${y?"timed out":"failed"} (error; no more retries left)`,ms({retryOfRequestLogID:n,url:a,durationMs:m-p,message:d.message})),y?new xi:new po({cause:d})}let h=[...d.headers.entries()].filter(([_])=>_==="x-request-id").map(([_,y])=>", "+_+": "+JSON.stringify(y)).join(""),b=`[${u}${l}${h}] ${o.method} ${a} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${m-p}ms`;if(!d.ok){let _=await this.shouldRetry(d);if(r&&_){let O=`retrying, ${r} attempts remaining`;return await mj(d.body),It(this).info(`${b} - ${O}`),It(this).debug(`[${u}] response error (${O})`,ms({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:m-p})),this.retryRequest(i,r,n??u,d.headers)}let y=_?"error; no more retries left":"error; not retryable";It(this).info(`${b} - ${y}`);let x=await d.text().catch(O=>_d(O).message),I=aj(x),A=I?void 0:x;throw It(this).debug(`[${u}] response error (${y})`,ms({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:A,durationMs:Date.now()-p})),this.makeStatusError(d.status,I,A,d.headers)}return It(this).info(b),It(this).debug(`[${u}] response start`,ms({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:m-p})),{response:d,options:i,controller:f,requestLogID:u,retryOfRequestLogID:n,startTime:p}}getAPIList(t,r,n){return this.requestAPIList(r,{method:"get",path:t,...n})}requestAPIList(t,r){let n=this.makeRequest(r,null,void 0);return new Id(this,n,t)}async fetchWithTimeout(t,r,n,i){let{signal:s,method:o,...a}=r||{};s&&s.addEventListener("abort",()=>i.abort());let c=setTimeout(()=>i.abort(),n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,l={signal:i.signal,...u?{duplex:"half"}:{},method:"GET",...a};o&&(l.method=o.toUpperCase());try{return await this.fetch.call(void 0,t,l)}finally{clearTimeout(c)}}async shouldRetry(t){let r=t.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,r,n,i){let s,o=i?.get("retry-after-ms");if(o){let c=parseFloat(o);Number.isNaN(c)||(s=c)}let a=i?.get("retry-after");if(a&&!s){let c=parseFloat(a);Number.isNaN(c)?s=Date.parse(a)-Date.now():s=c*1e3}if(!(s&&0<=s&&s<60*1e3)){let c=t.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,c)}return await Si(s),this.makeRequest(t,r-1,n)}calculateDefaultRetryTimeoutMillis(t,r){let s=r-t,o=Math.min(.5*Math.pow(2,s),8),a=1-Math.random()*.25;return o*a*1e3}async buildRequest(t,{retryCount:r=0}={}){let n={...t},{method:i,path:s,query:o,defaultBaseURL:a}=n,c=this.buildURL(s,o,a);"timeout"in n&&oj("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:u,body:l}=this.buildBody({options:n}),p=await this.buildHeaders({options:t,method:i,bodyHeaders:u,retryCount:r});return{req:{method:i,headers:p,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:t,method:r,bodyHeaders:n,retryCount:i}){let s={};this.idempotencyHeader&&r!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=t.idempotencyKey);let o=B([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...dj(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(t),this._options.defaultHeaders,n,t.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:t,headers:r}}){if(!t)return{bodyHeaders:void 0,body:void 0};let n=B([r]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Lg(t)}:k(this,d_,"f").call(this,{body:t,headers:n})}};$E=de,d_=new WeakMap,OE=new WeakSet,sD=function(){return this.baseURL!=="https://api.openai.com/v1"};de.OpenAI=$E;de.DEFAULT_TIMEOUT=6e5;de.OpenAIError=W;de.APIError=Rt;de.APIConnectionError=po;de.APIConnectionTimeoutError=xi;de.APIUserAbortError=yt;de.NotFoundError=mu;de.ConflictError=hu;de.RateLimitError=_u;de.BadRequestError=pu;de.AuthenticationError=du;de.InternalServerError=yu;de.PermissionDeniedError=fu;de.UnprocessableEntityError=gu;de.InvalidWebhookSignatureError=Ii;de.toFile=Ed;de.Completions=Va;de.Chat=go;de.Embeddings=Ga;de.Files=qa;de.Images=Xa;de.Audio=Ti;de.Moderations=Qa;de.Models=Ya;de.FineTuning=Xn;de.Graders=So;de.VectorStores=xs;de.Webhooks=tc;de.Beta=Jn;de.Batches=za;de.Uploads=ko;de.Responses=ws;de.Realtime=bs;de.Conversations=xo;de.Evals=Io;de.Containers=wo;de.Videos=ec;function Yn(e){if(!e||typeof e!="object")return e;let t;return e.constructor.name===xi.name&&"message"in e&&typeof e.message=="string"?(t=new Error(e.message),t.name="TimeoutError"):e.constructor.name===yt.name&&"message"in e&&typeof e.message=="string"?(t=new Error(e.message),t.name="AbortError"):"status"in e&&e.status===400&&"message"in e&&typeof e.message=="string"&&e.message.includes("tool_calls")?t=hd(e,"INVALID_TOOL_RESULTS"):"status"in e&&e.status===401?t=hd(e,"MODEL_AUTHENTICATION"):"status"in e&&e.status===429?t=hd(e,"MODEL_RATE_LIMIT"):"status"in e&&e.status===404?t=hd(e,"MODEL_NOT_FOUND"):t=e,t}var Is=e=>e();function Ss(e){return e?!!(/^o\d/.test(e??"")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat")):!1}function jK(e){return e.role!=="system"&&e.role!=="developer"&&e.role!=="assistant"&&e.role!=="user"&&e.role!=="function"&&e.role!=="tool"&&console.warn(`Unknown message role: ${e.role}`),e.role}function tl(e){let t=e.metadata?.filename??e.metadata?.name??e.metadata?.title;if(!t)throw new Error("a filename or name or title is needed via meta-data for OpenAI when working with multimodal blocks");return t}function Es(e){let t=e._getType();switch(t){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!mr.isInstance(e))throw new Error("Invalid generic chat message");return jK(e);default:throw new Error(`Unknown message type: ${t}`)}}function oD(e){return e.includes("gpt-5.2-pro")}function ks(e){let{azureOpenAIApiDeploymentName:t,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:i,baseURL:s,azureADTokenProvider:o,azureOpenAIEndpoint:a}=e;if((n||o)&&i&&t)return`${i}/${t}`;if((n||o)&&a&&t)return`${a}/openai/deployments/${t}`;if(n||o){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!t)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${t}`}return s}function PE(e){return typeof Headers<"u"&&e!==null&&typeof e=="object"&&Object.prototype.toString.call(e)==="[object Headers]"}function aD(e){let t=Is(()=>{if(PE(e))return e;if(Array.isArray(e))return new Headers(e);if(typeof e=="object"&&e!==null&&"values"in e&&PE(e.values))return e.values;if(typeof e=="object"&&e!==null){let r=Object.entries(e).filter(([,n])=>typeof n=="string").map(([n,i])=>[n,i]);return new Headers(r)}return new Headers});return Object.fromEntries(t.entries())}function cD(){let e=nf();return(e==="node"||e==="deno")&&(e=`(${e}/${process.version}; ${process.platform}; ${process.arch})`),e}function As(e,t=!1,r="1.0.0"){let n=aD(e),i=cD(),s=`langchainjs${t?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${i})${n["User-Agent"]}`:`${s}/${r} (${i})`}}function uD(e,t){let r;return Ia(e)?r=nS(e):r=e,t?.strict!==void 0&&(r.function.strict=t.strict),r}function DK(e){return e.anyOf!==void 0&&Array.isArray(e.anyOf)}function lD(e){let t=["namespace functions {",""];for(let r of e)r.description&&t.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(t.push(`type ${r.name} = (_: {`),t.push(pD(r.parameters,0)),t.push("}) => any;")):t.push(`type ${r.name} = () => any;`),t.push("");return t.push("} // namespace functions"),t.join(`
257
- `)}function pD(e,t){let r=[];for(let[n,i]of Object.entries(e.properties??{}))i.description&&t<2&&r.push(`// ${i.description}`),e.required?.includes(n)?r.push(`${n}: ${f_(i,t)},`):r.push(`${n}?: ${f_(i,t)},`);return r.map(n=>" ".repeat(t)+n).join(`
258
- `)}function f_(e,t){if(DK(e))return e.anyOf.map(r=>f_(r,t)).join(" | ");switch(e.type){case"string":return e.enum?e.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return e.enum?e.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return e.enum?e.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",pD(e,t+2),"}"].join(`
259
- `);case"array":return e.items?`${f_(e.items,t)}[]`:"any[]";default:return""}}function m_(e){if(e)return e==="any"||e==="required"?"required":e==="auto"?"auto":e==="none"?"none":typeof e=="string"?{type:"function",function:{name:e}}:e}function rl(e){return"type"in e&&e.type!=="function"}function dD(e){return typeof e=="object"&&e!==null&&"extras"in e&&typeof e.extras=="object"&&e.extras!==null&&"providerToolDefinition"in e.extras&&typeof e.extras.providerToolDefinition=="object"&&e.extras.providerToolDefinition!==null}function fD(e){return e!=null&&typeof e=="object"&&"type"in e&&e.type!=="function"}function rc(e){return typeof e=="object"&&e!==null&&"metadata"in e&&typeof e.metadata=="object"&&e.metadata!==null&&"customTool"in e.metadata&&typeof e.metadata.customTool=="object"&&e.metadata.customTool!==null}function h_(e){return"type"in e&&e.type==="custom"&&"custom"in e&&typeof e.custom=="object"&&e.custom!==null}function mD(e){if(e.type==="custom_tool_call")return{...e,type:"tool_call",call_id:e.id,id:e.call_id,name:e.name,isCustomTool:!0,args:{input:e.input}}}function hD(e){if(e.type==="computer_call")return{...e,type:"tool_call",call_id:e.id,id:e.call_id,name:"computer_use",isComputerTool:!0,args:{action:e.action}}}function gD(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="tool_call"&&"isComputerTool"in e&&e.isComputerTool===!0}function _D(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="tool_call"&&"isCustomTool"in e&&e.isCustomTool===!0}function yD(e){let t=()=>{if(e.custom.format){if(e.custom.format.type==="grammar")return{type:"grammar",definition:e.custom.format.grammar.definition,syntax:e.custom.format.grammar.syntax};if(e.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:e.custom.name,description:e.custom.description,format:t()}}function vD(e){let t=()=>{if(e.format){if(e.format.type==="grammar")return{type:"grammar",grammar:{definition:e.format.definition,syntax:e.format.syntax}};if(e.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:e.name,description:e.description,format:t()}}}var wD=Symbol("Let zodToJsonSchema decide on which parser to use"),bD={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},xD=e=>typeof e=="string"?{...bD,basePath:["#"],definitions:{},name:e}:{...bD,basePath:["#"],definitions:{},...e};var zd=e=>"_def"in e?e._def:e;function ID(e){if(!e)return!0;for(let t in e)return!1;return!0}var SD=e=>{let t=xD(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(t.definitions).map(([n,i])=>[zd(i),{def:zd(i),path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function NE(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function Ue(e,t,r,n,i){e[t]=r,NE(e,t,n,i)}function ED(){return{}}function kD(e,t){let r={type:"array"};return e.type?._def?.typeName!==T.ZodAny&&(r.items=fe(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Ue(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Ue(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Ue(r,"minItems",e.exactLength.value,e.exactLength.message,t),Ue(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function AD(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?Ue(r,"minimum",n.value,n.message,t):Ue(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Ue(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Ue(r,"maximum",n.value,n.message,t):Ue(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Ue(r,"maximum",n.value,n.message,t));break;case"multipleOf":Ue(r,"multipleOf",n.value,n.message,t);break}return r}function TD(){return{type:"boolean"}}function OD(e,t){return fe(e.type._def,t)}var $D=(e,t)=>fe(e.innerType._def,t);function RE(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,s)=>RE(e,t,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return zK(e,t)}}var zK=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":Ue(r,"minimum",n.value,n.message,t);break;case"max":Ue(r,"maximum",n.value,n.message,t);break}return r};function CD(e,t){return{...fe(e.innerType._def,t),default:e.defaultValue()}}function PD(e,t,r){return t.effectStrategy==="input"?fe(e.schema._def,t,r):{}}function ND(e){return{type:"string",enum:[...e.values]}}var LK=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function RD(e,t){let r=[fe(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),fe(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(s=>{if(LK(s))i.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;o=c}else n=void 0;i.push(o)}}),i.length?{allOf:i,...n}:void 0}function MD(e,t){let r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var ME,nc={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ME===void 0&&(ME=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ME),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function g_(e,t){let r={type:"string"};function n(i){return t.patternStrategy==="escape"?UK(i):i}if(e.checks)for(let i of e.checks)switch(i.kind){case"min":Ue(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,i.value):i.value,i.message,t);break;case"max":Ue(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,i.value):i.value,i.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Qn(r,"email",i.message,t);break;case"format:idn-email":Qn(r,"idn-email",i.message,t);break;case"pattern:zod":ei(r,nc.email,i.message,t);break}break;case"url":Qn(r,"uri",i.message,t);break;case"uuid":Qn(r,"uuid",i.message,t);break;case"regex":ei(r,i.regex,i.message,t);break;case"cuid":ei(r,nc.cuid,i.message,t);break;case"cuid2":ei(r,nc.cuid2,i.message,t);break;case"startsWith":ei(r,RegExp(`^${n(i.value)}`),i.message,t);break;case"endsWith":ei(r,RegExp(`${n(i.value)}$`),i.message,t);break;case"datetime":Qn(r,"date-time",i.message,t);break;case"date":Qn(r,"date",i.message,t);break;case"time":Qn(r,"time",i.message,t);break;case"duration":Qn(r,"duration",i.message,t);break;case"length":Ue(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,i.value):i.value,i.message,t),Ue(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,i.value):i.value,i.message,t);break;case"includes":{ei(r,RegExp(n(i.value)),i.message,t);break}case"ip":{i.version!=="v6"&&Qn(r,"ipv4",i.message,t),i.version!=="v4"&&Qn(r,"ipv6",i.message,t);break}case"emoji":ei(r,nc.emoji,i.message,t);break;case"ulid":{ei(r,nc.ulid,i.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Qn(r,"binary",i.message,t);break}case"contentEncoding:base64":{Ue(r,"contentEncoding","base64",i.message,t);break}case"pattern:zod":{ei(r,nc.base64,i.message,t);break}}break}case"nanoid":ei(r,nc.nanoid,i.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var UK=e=>Array.from(e).map(t=>/[a-zA-Z0-9]/.test(t)?t:`\\${t}`).join(""),Qn=(e,t,r,n)=>{e.format||e.anyOf?.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Ue(e,"format",t,r,n)},ei=(e,t,r,n)=>{e.pattern||e.allOf?.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:jD(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Ue(e,"pattern",jD(t,n),r,n)},jD=(e,t)=>{let r=typeof e=="function"?e():e;if(!t.applyRegexFlags||!r.flags)return r.source;let n={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},i=n.i?r.source.toLowerCase():r.source,s="",o=!1,a=!1,c=!1;for(let u=0;u<i.length;u++){if(o){s+=i[u],o=!1;continue}if(n.i){if(a){if(i[u].match(/[a-z]/)){c?(s+=i[u],s+=`${i[u-2]}-${i[u]}`.toUpperCase(),c=!1):i[u+1]==="-"&&i[u+2]?.match(/[a-z]/)?(s+=i[u],c=!0):s+=`${i[u]}${i[u].toUpperCase()}`;continue}}else if(i[u].match(/[a-z]/)){s+=`[${i[u]}${i[u].toUpperCase()}]`;continue}}if(n.m){if(i[u]==="^"){s+=`(^|(?<=[\r
260
- ]))`;continue}else if(i[u]==="$"){s+=`($|(?=[\r
261
- ]))`;continue}}if(n.s&&i[u]==="."){s+=a?`${i[u]}\r
262
- `:`[${i[u]}\r
263
- ]`;continue}s+=i[u],i[u]==="\\"?o=!0:a&&i[u]==="]"?a=!1:!a&&i[u]==="["&&(a=!0)}try{let u=new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return s};function __(e,t){if(t.target==="openApi3"&&e.keyType?._def.typeName===T.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,i)=>({...n,[i]:fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",i]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===T.ZodString&&e.keyType._def.checks?.length){let n=Object.entries(g_(e.keyType._def,t)).reduce((i,[s,o])=>s==="type"?i:{...i,[s]:o},{});return{...r,propertyNames:n}}else if(e.keyType?._def.typeName===T.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};return r}function DD(e,t){if(t.mapStrategy==="record")return __(e,t);let r=fe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},n=fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function zD(e){let t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),i=Array.from(new Set(n.map(s=>typeof s)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function LD(){return{not:{}}}function UD(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ld={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function BD(e,t){if(t.target==="openApi3")return FD(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Ld&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((i,s)=>{let o=Ld[s._def.typeName];return o&&!i.includes(o)?[...i,o]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((i,s)=>{let o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...i,o];case"bigint":return[...i,"integer"];case"object":if(s._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(n.length===r.length){let i=n.filter((s,o,a)=>a.indexOf(s)===o);return{type:i.length>1?i:i[0],enum:r.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(s=>!n.includes(s))],[])};return FD(e,t)}var FD=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,i)=>fe(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function VD(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"||t.nullableStrategy==="property"?{type:Ld[e.innerType._def.typeName],nullable:!0}:{type:[Ld[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=fe(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=fe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function ZD(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",NE(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?Ue(r,"minimum",n.value,n.message,t):Ue(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Ue(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Ue(r,"maximum",n.value,n.message,t):Ue(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Ue(r,"maximum",n.value,n.message,t));break;case"multipleOf":Ue(r,"multipleOf",n.value,n.message,t);break}return r}function FK(e,t){return t.removeAdditionalStrategy==="strict"?e.catchall._def.typeName==="ZodNever"?e.unknownKeys!=="strict":fe(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:e.catchall._def.typeName==="ZodNever"?e.unknownKeys==="passthrough":fe(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}function GD(e,t){let r={type:"object",...Object.entries(e.shape()).reduce((n,[i,s])=>{if(s===void 0||s._def===void 0)return n;let o=[...t.currentPath,"properties",i],a=fe(s._def,{...t,currentPath:o,propertyPath:o});if(a===void 0)return n;if(t.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${o.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[i]:a},required:s.isOptional()&&!t.openaiStrictMode?n.required:[...n.required,i]}},{properties:{},required:[]}),additionalProperties:FK(e,t)};return r.required.length||delete r.required,r}var KD=(e,t)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return fe(e.innerType._def,{...t,currentPath:t.currentPath});let r=fe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}};var qD=(e,t)=>{if(t.pipeStrategy==="input")return fe(e.in._def,t);if(t.pipeStrategy==="output")return fe(e.out._def,t);let r=fe(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=fe(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function HD(e,t){return fe(e.type._def,t)}function WD(e,t){let n={type:"array",uniqueItems:!0,items:fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Ue(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Ue(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function JD(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>fe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:fe(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>fe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function XD(){return{not:{}}}function YD(){return{}}var QD=(e,t)=>fe(e.innerType._def,t);function fe(e,t,r=!1){let n=t.seen.get(e);if(t.override){let o=t.override?.(e,t,n,r);if(o!==wD)return o}if(n&&!r){let o=BK(n,t);if(o!==void 0)return"$ref"in o&&t.seenRefs.add(o.$ref),o}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let s=ZK(e,e.typeName,t,r);return s&&GK(e,t,s),i.jsonSchema=s,s}var BK=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"extract-to-root":let r=e.path.slice(t.basePath.length+1).join("_");return r!==t.name&&t.nameStrategy==="duplicate-ref"&&(t.definitions[r]=e.def),{$ref:[...t.basePath,t.definitionPath,r].join("/")};case"relative":return{$ref:VK(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,i)=>t.currentPath[i]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):t.$refStrategy==="seen"?{}:void 0}},VK=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},ZK=(e,t,r,n)=>{switch(t){case T.ZodString:return g_(e,r);case T.ZodNumber:return ZD(e,r);case T.ZodObject:return GD(e,r);case T.ZodBigInt:return AD(e,r);case T.ZodBoolean:return TD();case T.ZodDate:return RE(e,r);case T.ZodUndefined:return XD();case T.ZodNull:return UD(r);case T.ZodArray:return kD(e,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return BD(e,r);case T.ZodIntersection:return RD(e,r);case T.ZodTuple:return JD(e,r);case T.ZodRecord:return __(e,r);case T.ZodLiteral:return MD(e,r);case T.ZodEnum:return ND(e);case T.ZodNativeEnum:return zD(e);case T.ZodNullable:return VD(e,r);case T.ZodOptional:return KD(e,r);case T.ZodMap:return DD(e,r);case T.ZodSet:return WD(e,r);case T.ZodLazy:return fe(e.getter()._def,r);case T.ZodPromise:return HD(e,r);case T.ZodNaN:case T.ZodNever:return LD();case T.ZodEffects:return PD(e,r,n);case T.ZodAny:return ED();case T.ZodUnknown:return YD();case T.ZodDefault:return CD(e,r);case T.ZodBranded:return OD(e,r);case T.ZodReadonly:return QD(e,r);case T.ZodCatch:return $D(e,r);case T.ZodPipeline:return qD(e,r);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(i=>{})(t)}},GK=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var jE=(e,t)=>{let r=SD(t),n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=fe(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(i.title=s);let o=(()=>{if(ID(r.definitions))return;let c={},u=new Set;for(let l=0;l<500;l++){let p=Object.entries(r.definitions).filter(([f])=>!u.has(f));if(p.length===0)break;for(let[f,d]of p)c[f]=fe(zd(d),{...r,currentPath:[...r.basePath,r.definitionPath,f]},!0)??{},u.add(f)}return c})(),a=n===void 0?o?{...i,[r.definitionPath]:o}:i:r.nameStrategy==="duplicate-ref"?{...i,...o||r.seenRefs.size?{[r.definitionPath]:{...o,...r.seenRefs.size?{[n]:i}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]:i}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function ez(e){if(e.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${e.type?`'${e.type}'`:"undefined"}`);let t=structuredClone(e);return Ts(t,[],t)}function DE(e){if(typeof e=="boolean")return!1;if(e.type==="null")return!0;for(let t of e.oneOf??[])if(DE(t))return!0;for(let t of e.anyOf??[])if(DE(t))return!0;return!1}function Ts(e,t,r){if(typeof e=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${t.join("/")}`);if(!ic(e))throw new TypeError(`Expected ${JSON.stringify(e)} to be an object; path=${t.join("/")}`);let n=e.$defs;if(ic(n))for(let[f,d]of Object.entries(n))Ts(d,[...t,"$defs",f],r);let i=e.definitions;if(ic(i))for(let[f,d]of Object.entries(i))Ts(d,[...t,"definitions",f],r);e.type==="object"&&!("additionalProperties"in e)&&(e.additionalProperties=!1);let o=e.required??[],a=e.properties;if(ic(a)){for(let[f,d]of Object.entries(a))if(!DE(d)&&!o.includes(f))throw new Error(`Zod field at \`${[...t,"properties",f].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);e.required=Object.keys(a),e.properties=Object.fromEntries(Object.entries(a).map(([f,d])=>[f,Ts(d,[...t,"properties",f],r)]))}let c=e.items;ic(c)&&(e.items=Ts(c,[...t,"items"],r));let u=e.anyOf;Array.isArray(u)&&(e.anyOf=u.map((f,d)=>Ts(f,[...t,"anyOf",String(d)],r)));let l=e.allOf;if(Array.isArray(l))if(l.length===1){let f=Ts(l[0],[...t,"allOf","0"],r);Object.assign(e,f),delete e.allOf}else e.allOf=l.map((f,d)=>Ts(f,[...t,"allOf",String(d)],r));e.default===null&&delete e.default;let p=e.$ref;if(p&&qK(e,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${t.join("/")}`);let f=KK(r,p);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!ic(f))throw new Error(`Expected \`$ref: ${p}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(e,{...f,...e}),delete e.$ref,Ts(e,t,r)}return e}function KK(e,t){if(!t.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(t)}; Does not start with #/`);let r=t.slice(2).split("/"),n=e;for(let i of r){if(!ic(n))throw new Error(`encountered non-object entry while resolving ${t} - ${JSON.stringify(n)}`);let s=n[i];if(s===void 0)throw new Error(`Key ${i} not found while resolving ${t}`);n=s}return n}function ic(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qK(e,t){let r=0;for(let n in e)if(r++,r>t)return!0;return!1}function HK(e,t){return jE(e,{openaiStrictMode:!0,name:t.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function WK(e){return ez(qs(e,{target:"draft-7"}))}function JK(e){return"_zod"in e}function tz(e,t,r){return Nj({type:"json_schema",json_schema:{...r,name:t,strict:!0,schema:JK(e)?WK(e):HK(e,{name:t})}},n=>e.parse(JSON.parse(n)))}var rz=["jsonSchema","functionCalling","jsonMode"];function nz(e,t){if(typeof t<"u"&&!rz.includes(t))throw new Error(`Invalid method: ${t}. Supported methods are: ${rz.join(", ")}`);let r=!e.startsWith("gpt-3")&&!e.startsWith("gpt-4-")&&e!=="gpt-4";if(r&&!t)return"jsonSchema";if(!r&&t==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${e}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return t??"functionCalling"}function XK(e,t){let r={...e};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),r}function iz(e,t,r){if(it(e))return tz(e,t,r);if(We(e))return XK({type:"json_schema",json_schema:{...r,name:t,strict:!0,schema:Ye(e,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=t}})}},n=>ui(e,JSON.parse(n)));throw new Error("Unsupported schema response format")}function sz(e,t){if(t&&typeof t=="object"&&"images"in t&&Array.isArray(t.images)){let r=t.images.filter(n=>typeof n?.image_url?.url=="string").map(n=>({type:"image",url:n.image_url.url}));return[{type:"text",text:e},...r]}return e}var YK={"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}},oz=YK;var sc=class extends eo{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{});let t=typeof e?.configuration?.apiKey=="string"||typeof e?.configuration?.apiKey=="function"?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??t??Je("OPENAI_API_KEY"),this.organization=e?.configuration?.organization??Je("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=e?.promptCacheRetention??this.promptCacheRetention,this.verbosity=e?.verbosity??this.verbosity,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.disableStreaming&&(this.streaming=!1),e?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1}_getReasoningParams(e){if(!Ss(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),e?.reasoning!==void 0&&(t={...t,...e.reasoning}),t}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&_r(e.json_schema.schema)?iz(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){let r={baseURL:this.clientConfig.baseURL},n=ks(r),i={...this.clientConfig,baseURL:n,timeout:this.timeout,maxRetries:0};i.baseURL||delete i.baseURL,i.defaultHeaders=As(i.defaultHeaders),this.client=new de(i)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return rc(e)?vD(e.metadata.customTool):Ap(e)?t?.strict!==void 0?{...e,function:{...e.function,strict:t.strict}}:e:uD(e,t)}bindTools(e,t){let r;return t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:e.map(n=>rl(n)||rc(n)?n:dD(n)?n.extras.providerToolDefinition:this._convertChatOpenAIToolToCompletionsTool(n,{strict:r})),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((t,r)=>(r&&r.tokenUsage&&(t.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,t.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,t.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),t),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,r=0,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let i=await Promise.all(e.map(async s=>{let[o,a]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(Es(s))]),c=s.name!==void 0?n+await this.getNumTokens(s.name):0,u=o+r+a+c,l=s;if(l._getType()==="function"&&(u-=2),l.additional_kwargs?.function_call&&(u+=3),l?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(l.additional_kwargs.function_call?.name)),l.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(l.additional_kwargs.function_call?.arguments)))}catch(p){console.error("Error parsing function arguments",p,JSON.stringify(l.additional_kwargs.function_call)),u+=await this.getNumTokens(l.additional_kwargs.function_call?.arguments)}return t+=u,u}));return t+=3,{totalCount:t,countPerMessage:i}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async r=>r.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([r.message])).countPerMessage[0]:await this.getNumTokens(r.message.content)))).reduce((r,n)=>r+n,0)}async _getEstimatedTokenCountFromPrompt(e,t,r){let n=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&r!=="auto"){let i=lD(t);n+=await this.getNumTokens(i),n+=9}return t&&e.find(i=>i._getType()==="system")&&(n-=4),r==="none"?n+=1:typeof r=="object"&&(n+=await this.getNumTokens(r.name)+4),n}async moderateContent(e,t){let r=this._getClientOptions(t?.options),n=t?.model??"omni-moderation-latest",i={input:e,model:n};return this.caller.call(async()=>{try{return await this.client.moderations.create(i,r)}catch(s){throw Yn(s)}})}get profile(){return oz[this.model]??{}}_getStructuredOutputMethod(e){let t={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(t?.method===void 0)return"jsonSchema"}else t.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let r,n,{schema:i,name:s,includeRaw:o}={...t,schema:e};if(t?.strict!==void 0&&t.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let a=nz(this.model,t?.method);if(a==="jsonMode"){_r(i)?n=Kc.fromZodSchema(i):n=new $p;let p=Ye(i);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...p}}})}else if(a==="jsonSchema"){let p={name:s??"extract",description:On(i),schema:i,strict:t?.strict},f=Ye(p.schema);if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:p},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:p.name,description:p.description,...f}}}),_r(i)){let d=Kc.fromZodSchema(i);n=tr.from(m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:d)}else n=new $p}else{let p=s??"extract";if(_r(i)){let f=Ye(i);r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:{name:p,description:f.description,parameters:f}}],tool_choice:{type:"function",function:{name:p}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:p,...f}},...t?.strict!==void 0?{strict:t.strict}:{}}),n=new Cp({returnSingle:!0,keyName:p,zodSchema:i})}else{let f;typeof i.name=="string"&&typeof i.parameters=="object"&&i.parameters!=null?(f=i,p=i.name):(p=i.title??p,f={name:p,description:i.description??"",parameters:i});let d=Ye(i);r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:p}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:p,...d}},...t?.strict!==void 0?{strict:t.strict}:{}}),n=new Cp({returnSingle:!0,keyName:p})}}if(!o)return r.pipe(n);let c=yn.assign({parsed:(p,f)=>n.invoke(p.raw,f)}),u=yn.assign({parsed:()=>null}),l=c.withFallbacks({fallbacks:[u]});return br.from([{raw:r},l])}};var y_={providerName:"ChatOpenAI",fromStandardTextBlock(e){return{type:"text",text:e.text}},fromStandardImageBlock(e){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if(e.source_type==="base64")return{type:"image_url",image_url:{url:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if(e.source_type==="url"){let t=Ps({dataUrl:e.url});if(!t)throw new Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);let r=t.mime_type||e.mime_type||"",n;try{n=ul(r)}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:n.subtype,data:t.data}}}if(e.source_type==="base64"){let t;try{t=ul(e.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(t.type!=="audio"||t.subtype!=="wav"&&t.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:t.subtype,data:e.data}}}throw new Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if(e.source_type==="url"){let t=Ps({dataUrl:e.url}),r=tl(e);if(!t)throw new Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:e.url,...e.metadata?.filename||e.metadata?.name?{filename:r}:{}}}}if(e.source_type==="base64"){let t=tl(e);return{type:"file",file:{file_data:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.filename||e.metadata?.name||e.metadata?.title?{filename:t}:{}}}}if(e.source_type==="id")return{type:"file",file:{file_id:e.id}};throw new Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}},zE=({message:e,rawResponse:t,includeRawResponse:r})=>{let n=e.tool_calls;switch(e.role){case"assistant":{let i=[],s=[];for(let u of n??[])try{i.push(ba(u,{returnId:!0}))}catch(l){s.push(to(u,l.message))}let o={function_call:e.function_call,tool_calls:n};r!==void 0&&(o.__raw_response=t);let a={model_provider:"openai",model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};e.audio&&(o.audio=e.audio);let c=sz(e.content||"",t.choices?.[0]?.message);return new $e({content:c,tool_calls:i,invalid_tool_calls:s,additional_kwargs:o,response_metadata:a,id:t.id})}default:return new mr(e.content||"",e.role??"unknown")}},LE=({delta:e,rawResponse:t,includeRawResponse:r,defaultRole:n})=>{let i=e.role??n,s=e.content??"",o;e.function_call?o={function_call:e.function_call}:e.tool_calls?o={tool_calls:e.tool_calls}:o={},r&&(o.__raw_response=t),e.audio&&(o.audio={...e.audio,index:t.choices[0].index});let a={model_provider:"openai",usage:{...t.usage}};if(i==="user")return new Vi({content:s,response_metadata:a});if(i==="assistant"){let c=[];if(Array.isArray(e.tool_calls))for(let u of e.tool_calls)c.push({name:u.function?.name,args:u.function?.arguments,id:u.id,index:u.index,type:"tool_call_chunk"});return new nt({content:s,tool_call_chunks:c,additional_kwargs:o,id:t.id,response_metadata:a})}else return i==="system"?new un({content:s,response_metadata:a}):i==="developer"?new un({content:s,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):i==="function"?new Bi({content:s,additional_kwargs:o,name:e.name,response_metadata:a}):i==="tool"?new Ns({content:s,additional_kwargs:o,tool_call_id:e.tool_call_id,response_metadata:a}):new Fi({content:s,role:i,response_metadata:a})},az=e=>{if(e.type==="image"){if(e.url)return{type:"image_url",image_url:{url:e.url}};if(e.data)return{type:"image_url",image_url:{url:`data:${e.mimeType};base64,${e.data}`}}}if(e.type==="audio"&&e.data){let t=qf(()=>{let[,r]=e.mimeType.split("/");return r==="wav"||r==="mp3"?r:"wav"});return{type:"input_audio",input_audio:{data:e.data.toString(),format:t}}}if(e.type==="file"){if(e.data){let t=tl(e);return{type:"file",file:{file_data:`data:${e.mimeType};base64,${e.data}`,filename:t}}}if(e.fileId)return{type:"file",file:{file_id:e.fileId}}}},cz=({message:e,model:t})=>{let r=Es(e);if(r==="system"&&Ss(t)&&(r="developer"),r==="developer")return{role:"developer",content:e.contentBlocks.filter(i=>i.type==="text")};if(r==="system")return{role:"system",content:e.contentBlocks.filter(i=>i.type==="text")};if(r==="assistant")return{role:"assistant",content:e.contentBlocks.filter(i=>i.type==="text")};if(r==="tool"&&Wt.isInstance(e))return{role:"tool",tool_call_id:e.tool_call_id,content:e.contentBlocks.filter(i=>i.type==="text")};if(r==="function")return{role:"function",name:e.name??"",content:e.contentBlocks.filter(i=>i.type==="text").join("")};function*n(i){for(let s of i){s.type==="text"&&(yield{type:"text",text:s.text});let o=az(s);o&&(yield o)}}return{role:"user",content:Array.from(n(e.contentBlocks))}},Ud=({messages:e,model:t})=>e.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return cz({message:r});let n=Es(r);n==="system"&&Ss(t)&&(n="developer");let i=typeof r.content=="string"?r.content:r.content.map(o=>Tr(o)?pc(o,y_):o),s={role:n,content:i};if(r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),$e.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Nh):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),Wt.isInstance(r)&&r.tool_call_id!=null&&(s.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let o={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[s,o]}return s});var v_=class extends sc{invocationParams(e,t){let r;e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let n={};e?.stream_options!==void 0?n={stream_options:e.stream_options}:this.streamUsage&&(this.streaming||t?.streaming)&&(n={stream_options:{include_usage:!0}});let i={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(o=>this._convertChatOpenAIToolToCompletionsTool(o,{strict:r})):void 0,tool_choice:m_(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...n,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,verbosity:e?.verbosity??this.verbosity};e?.prediction!==void 0&&(i.prediction=e.prediction),this.service_tier!==void 0&&(i.service_tier=this.service_tier),e?.service_tier!==void 0&&(i.service_tier=e.service_tier);let s=this._getReasoningParams(e);return s!==void 0&&s.effort!==void 0&&(i.reasoning_effort=s.effort),Ss(i.model)?i.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:i.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,i}async _generate(e,t,r){let n={},i=this.invocationParams(t),s=Ud({messages:e,model:this.model});if(i.stream){let o=this._streamResponseChunks(e,t,r),a={};for await(let d of o){d.message.response_metadata={...d.generationInfo,...d.message.response_metadata};let m=d.generationInfo?.completion??0;a[m]===void 0?a[m]=d:a[m]=a[m].concat(d)}let c=Object.entries(a).sort(([d],[m])=>parseInt(d,10)-parseInt(m,10)).map(([d,m])=>m),{functions:u,function_call:l}=this.invocationParams(t),p=await this._getEstimatedTokenCountFromPrompt(e,u,l),f=await this._getNumTokensFromGenerations(c);return n.input_tokens=p,n.output_tokens=f,n.total_tokens=p+f,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let o=await this.completionWithRetry({...i,stream:!1,messages:s},{signal:t?.signal,...t?.options}),{completion_tokens:a,prompt_tokens:c,total_tokens:u,prompt_tokens_details:l,completion_tokens_details:p}=o?.usage??{};a&&(n.output_tokens=(n.output_tokens??0)+a),c&&(n.input_tokens=(n.input_tokens??0)+c),u&&(n.total_tokens=(n.total_tokens??0)+u),(l?.audio_tokens!==null||l?.cached_tokens!==null)&&(n.input_token_details={...l?.audio_tokens!==null&&{audio:l?.audio_tokens},...l?.cached_tokens!==null&&{cache_read:l?.cached_tokens}}),(p?.audio_tokens!==null||p?.reasoning_tokens!==null)&&(n.output_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.reasoning_tokens!==null&&{reasoning:p?.reasoning_tokens}});let f=[];for(let d of o?.choices??[]){let h={text:d.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(d.message??{role:"assistant"},o)};h.generationInfo={...d.finish_reason?{finish_reason:d.finish_reason}:{},...d.logprobs?{logprobs:d.logprobs}:{}},si(h.message)&&(h.message.usage_metadata=n),h.message=new $e(Object.fromEntries(Object.entries(h.message).filter(([b])=>!b.startsWith("lc_")))),f.push(h)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamResponseChunks(e,t,r){let n=Ud({messages:e,model:this.model}),i={...this.invocationParams(t,{streaming:!0}),messages:n,stream:!0},s,o=await this.completionWithRetry(i,t),a;for await(let c of o){let u=c?.choices?.[0];if(c.usage&&(a=c.usage),!u)continue;let{delta:l}=u;if(!l)continue;let p=this._convertCompletionsDeltaToBaseMessageChunk(l,c,s);s=l.role??s;let f={prompt:t.promptIndex??0,completion:u.index??0};if(typeof p.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let d={...f};u.finish_reason!=null&&(d.finish_reason=u.finish_reason,d.system_fingerprint=c.system_fingerprint,d.model_name=c.model,d.service_tier=c.service_tier),this.logprobs&&(d.logprobs=u.logprobs);let m=new Zr({message:p,text:p.content,generationInfo:d});yield m,await r?.handleLLMNewToken(m.text??"",f,void 0,void 0,void 0,{chunk:m})}if(a){let c={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},u={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}};yield new Zr({message:new nt({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(u).length>0&&{output_token_details:u}}}),text:""})}if(t.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(e,t){let r=this._getClientOptions(t),n=e.response_format&&e.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!e.stream?await this.client.chat.completions.parse(e,r):await this.client.chat.completions.create(e,r)}catch(i){throw Yn(i)}})}_convertCompletionsDeltaToBaseMessageChunk(e,t,r){return LE({delta:e,rawResponse:t,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(e,t){return zE({message:e,rawResponse:t,includeRawResponse:this.__includeRawResponse})}};var b_="__openai_function_call_ids__";function mz(e){return e.type==="url_citation"?{type:"citation",source:"url_citation",url:e.url,title:e.title,startIndex:e.start_index,endIndex:e.end_index}:e.type==="file_citation"?{type:"citation",source:"file_citation",title:e.filename,startIndex:e.index,file_id:e.file_id}:e.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:e.filename,startIndex:e.start_index,endIndex:e.end_index,file_id:e.file_id,container_id:e.container_id}:e.type==="file_path"?{type:"citation",source:"file_path",startIndex:e.index,file_id:e.file_id}:{type:"non_standard",value:e}}var UE=e=>{let t={...e?.input_tokens_details?.cached_tokens!=null&&{cache_read:e?.input_tokens_details?.cached_tokens}},r={...e?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:e?.output_tokens_details?.reasoning_tokens}};return{input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,input_token_details:t,output_token_details:r}},w_=e=>{if(e.error){let a=new Error(e.error.message);throw a.name=e.error.code,a}let t,r=[],n=[],i=[],s={model_provider:"openai",model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},o={};for(let a of e.output)if(a.type==="message")t=a.id,r.push(...a.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(o.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations.map(mz)}):c.type==="refusal"?(o.refusal=c.refusal,[]):c));else if(a.type==="function_call"){let c={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{n.push(ba(c,{returnId:!0}))}catch(u){let l;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(l=u.message),i.push(to(c,l))}o[b_]??={},a.id&&(o[b_][a.call_id]=a.id)}else if(a.type==="reasoning"){o.reasoning=a;let c=a.summary?.map(u=>u.text).filter(Boolean).join("");c&&r.push({type:"reasoning",reasoning:c})}else if(a.type==="custom_tool_call"){let c=mD(a);c?n.push(c):i.push(to(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let c=hD(a);c?n.push(c):i.push(to(a,"Malformed computer call"))}else a.type==="image_generation_call"?(a.result&&r.push({type:"image",mimeType:"image/png",data:a.result,id:a.id,metadata:{status:a.status}}),o.tool_outputs??=[],o.tool_outputs.push(a)):(o.tool_outputs??=[],o.tool_outputs.push(a));return new $e({id:t,content:r,tool_calls:n,invalid_tool_calls:i,usage_metadata:UE(e.usage),additional_kwargs:o,response_metadata:s})},hz=e=>{let t=(e.summary.length>1?e.summary.reduce((r,n)=>{let i=r[r.length-1];return i.index===n.index?i.text+=n.text:r.push(n),r},[{...e.summary[0]}]):e.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([n])=>n!=="index")));return{...e,summary:t}},FE=e=>{let t=[],r={},n,i=[],s={model_provider:"openai"},o={},a;if(e.type==="response.output_text.delta")t.push({type:"text",text:e.delta,index:e.content_index});else if(e.type==="response.output_text.annotation.added")t.push({type:"text",text:"",annotations:[mz(e.annotation)],index:e.content_index});else if(e.type==="response.output_item.added"&&e.item.type==="message")a=e.item.id;else if(e.type==="response.output_item.added"&&e.item.type==="function_call")i.push({type:"tool_call_chunk",name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),o[b_]={[e.item.call_id]:e.item.id};else if(e.type==="response.output_item.done"&&e.item.type==="computer_call")i.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:e.item.action}),id:e.item.call_id,index:e.output_index}),o.tool_outputs=[e.item];else if(e.type==="response.output_item.done"&&e.item.type==="image_generation_call")e.item.result&&t.push({type:"image",mimeType:"image/png",data:e.item.result,id:e.item.id,metadata:{status:e.item.status}}),o.tool_outputs=[e.item];else if(e.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call"].includes(e.item.type))o.tool_outputs=[e.item];else if(e.type==="response.created")s.id=e.response.id,s.model_name=e.response.model,s.model=e.response.model;else if(e.type==="response.completed"){let c=w_(e.response);n=UE(e.response.usage),e.response.text?.format?.type==="json_schema"&&(o.parsed??=JSON.parse(c.text));for(let[u,l]of Object.entries(e.response))u!=="id"&&(s[u]=l)}else if(e.type==="response.function_call_arguments.delta"||e.type==="response.custom_tool_call_input.delta")i.push({type:"tool_call_chunk",args:e.delta,index:e.output_index});else if(e.type==="response.web_search_call.completed"||e.type==="response.file_search_call.completed")r={tool_outputs:{id:e.item_id,type:e.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(e.type==="response.refusal.done")o.refusal=e.refusal;else if(e.type==="response.output_item.added"&&"item"in e&&e.item.type==="reasoning"){let c=e.item.summary?e.item.summary.map((l,p)=>({...l,index:p})):void 0;o.reasoning={id:e.item.id,type:e.item.type,...c?{summary:c}:{}};let u=e.item.summary?.map(l=>l.text).filter(Boolean).join("");u&&t.push({type:"reasoning",reasoning:u})}else if(e.type==="response.reasoning_summary_part.added")o.reasoning={type:"reasoning",summary:[{...e.part,index:e.summary_index}]},e.part.text&&t.push({type:"reasoning",reasoning:e.part.text});else if(e.type==="response.reasoning_summary_text.delta")o.reasoning={type:"reasoning",summary:[{text:e.delta,type:"summary_text",index:e.summary_index}]},e.delta&&t.push({type:"reasoning",reasoning:e.delta});else return e.type==="response.image_generation_call.partial_image",null;return new Zr({text:t.map(c=>c.text).join(""),message:new nt({id:a,content:t,tool_call_chunks:i,usage_metadata:n,additional_kwargs:o,response_metadata:s}),generationInfo:r})},gz=e=>{let t=$e.isInstance(e)&&e.response_metadata?.model_provider==="openai";function*r(){let n=Is(()=>{try{let _=Es(e);return _==="system"||_==="developer"||_==="assistant"||_==="user"?_:"assistant"}catch{return"assistant"}}),i,s=new Set,o=new Set,a=new Map,c=new Map;function*u(){if(!i)return;let _=i.content;(typeof _=="string"&&_.length>0||Array.isArray(_)&&_.length>0)&&(yield i),i=void 0}let l=_=>{i||(i={type:"message",role:n,content:[]}),typeof i.content=="string"?i.content=i.content.length>0?[{type:"input_text",text:i.content},..._]:[..._]:i.content.push(..._)},p=_=>{if(typeof _=="string")return _;try{return JSON.stringify(_??{})}catch{return"{}"}},f=_=>{let y=Is(()=>{let x=_.metadata?.detail;return x==="low"||x==="high"||x==="auto"?x:"auto"});if(_.fileId)return{type:"input_image",detail:y,file_id:_.fileId};if(_.url)return{type:"input_image",detail:y,image_url:_.url};if(_.data){let x=typeof _.data=="string"?_.data:Buffer.from(_.data).toString("base64"),I=_.mimeType??"image/png";return{type:"input_image",detail:y,image_url:`data:${I};base64,${x}`}}},d=_=>{let y=tl(_);if(_.fileId&&typeof y=="string")return{type:"input_file",file_id:_.fileId,...y?{filename:y}:{}};if(_.url&&typeof y=="string")return{type:"input_file",file_url:_.url,...y?{filename:y}:{}};if(_.data&&typeof y=="string"){let x=typeof _.data=="string"?_.data:Buffer.from(_.data).toString("base64");return{type:"input_file",file_data:`data:${_.mimeType??"application/octet-stream"};base64,${x}`,...y?{filename:y}:{}}}},m=_=>{let y=Is(()=>{if(Array.isArray(_.summary)){let j=_.summary?.map(O=>O?.text).filter(O=>typeof O=="string")??[];if(j.length>0)return j}return _.reasoning?[_.reasoning]:[]}),x=y.length>0?y.map(A=>({type:"summary_text",text:A})):[{type:"summary_text",text:""}],I={type:"reasoning",id:_.id??"",summary:x};return _.reasoning&&(I.content=[{type:"reasoning_text",text:_.reasoning}]),I},h=_=>({type:"function_call",name:_.name??"",call_id:_.id??"",arguments:p(_.args)}),b=_=>{let y=p(_.output),x=_.status==="success"?"completed":_.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:_.toolCallId??"",output:y,...x?{status:x}:{}}};for(let _ of e.contentBlocks)if(_.type==="text")l([{type:"input_text",text:_.text}]);else if(_.type!=="invalid_tool_call"){if(_.type==="reasoning")yield*u(),yield m(_);else if(_.type==="tool_call"){yield*u();let y=_.id??"";y&&(s.add(y),a.delete(y)),yield h(_)}else if(_.type==="tool_call_chunk"){if(_.id){let y=a.get(_.id)??{name:_.name,args:[]};_.name&&(y.name=_.name),_.args&&y.args.push(_.args),a.set(_.id,y)}}else if(_.type==="server_tool_call"){yield*u();let y=_.id??"";y&&(o.add(y),c.delete(y)),yield h(_)}else if(_.type==="server_tool_call_chunk"){if(_.id){let y=c.get(_.id)??{name:_.name,args:[]};_.name&&(y.name=_.name),_.args&&y.args.push(_.args),c.set(_.id,y)}}else if(_.type==="server_tool_call_result")yield*u(),yield b(_);else if(_.type!=="audio")if(_.type==="file"){let y=d(_);y&&l([y])}else if(_.type==="image"){let y=f(_);y&&l([y])}else if(_.type==="video"){let y=d(_);y&&l([y])}else _.type==="text-plain"?_.text&&l([{type:"input_text",text:_.text}]):_.type==="non_standard"&&t&&(yield*u(),yield _.value)}yield*u();for(let[_,y]of a){if(!_||s.has(_))continue;let x=y.args.join("");!y.name&&!x||(yield{type:"function_call",call_id:_,name:y.name??"",arguments:x})}for(let[_,y]of c){if(!_||o.has(_))continue;let x=y.args.join("");!y.name&&!x||(yield{type:"function_call",call_id:_,name:y.name??"",arguments:x})}}return Array.from(r())},x_=({messages:e,zdrEnabled:t,model:r})=>e.flatMap(n=>{let i=n.response_metadata;if(i?.output_version==="v1")return gz(n);let s=n.additional_kwargs,o=Es(n);if(o==="system"&&Ss(r)&&(o="developer"),o==="function")throw new Error("Function messages are not supported in Responses API");if(o==="tool"){let a=n;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let l=a.content.find(d=>d.type==="input_image");if(l)return l;let p=a.content.find(d=>d.type==="computer_screenshot");if(p)return p;let f=a.content.find(d=>d.type==="image_url");if(f)return{type:"input_image",image_url:typeof f.image_url=="string"?f.image_url:f.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let c=Array.isArray(a.content)&&a.content.every(u=>typeof u=="object"&&u!==null&&"type"in u&&(u.type==="input_file"||u.type==="input_image"||u.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:c?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(o==="assistant"){if(!t&&i?.output!=null&&Array.isArray(i?.output)&&i?.output.length>0&&i?.output.every(f=>"type"in f))return i?.output;let a=[];if(s?.reasoning&&!t){let f=hz(s.reasoning);a.push(f)}let{content:c}=n;s?.refusal&&(typeof c=="string"&&(c=[{type:"output_text",text:c,annotations:[]}]),c=[...c,{type:"refusal",refusal:s.refusal}]),(typeof c=="string"||c.length>0)&&a.push({type:"message",role:"assistant",...n.id&&!t&&n.id.startsWith("msg_")?{id:n.id}:{},content:Is(()=>typeof c=="string"?c:c.flatMap(f=>f.type==="text"?{type:"output_text",text:f.text,annotations:f.annotations??[]}:f.type==="output_text"||f.type==="refusal"?f:[]))});let u=s?.[b_];$e.isInstance(n)&&n.tool_calls?.length?a.push(...n.tool_calls.map(f=>_D(f)?{type:"custom_tool_call",id:f.call_id,call_id:f.id??"",input:f.args.input,name:f.name}:gD(f)?{type:"computer_call",id:f.call_id,call_id:f.id??"",action:f.args.action}:{type:"function_call",name:f.name,arguments:JSON.stringify(f.args),call_id:f.id,...t?{}:{id:u?.[f.id]}})):s?.tool_calls&&a.push(...s.tool_calls.map(f=>({type:"function_call",name:f.function.name,call_id:f.id,arguments:f.function.arguments,...t?{}:{id:u?.[f.id]}})));let l=i?.output?.length?i?.output:s.tool_outputs,p=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(l!=null){let d=l?.filter(m=>p.includes(m.type));d.length>0&&a.push(...d)}return a}if(o==="user"||o==="system"||o==="developer"){if(typeof n.content=="string")return{type:"message",role:o,content:n.content};let a=[],c=n.content.flatMap(u=>{if(u.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:u.approval_request_id,approve:u.approve}),Tr(u))return pc(u,y_);if(u.type==="text")return{type:"input_text",text:u.text};if(u.type==="image_url"){let l=Is(()=>{if(typeof u.image_url=="string")return u.image_url;if(typeof u.image_url=="object"&&u.image_url!==null&&"url"in u.image_url)return u.image_url.url}),p=Is(()=>{if(typeof u.image_url=="string")return"auto";if(typeof u.image_url=="object"&&u.image_url!==null&&"detail"in u.image_url)return u.image_url.detail});return{type:"input_image",image_url:l,detail:p}}return u.type==="input_text"||u.type==="input_image"||u.type==="input_file"?u:[]});return c.length>0&&a.push({type:"message",role:o,content:c}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${o}`),[]});var I_=class extends sc{invocationParams(e){let t;e?.strict!==void 0&&(t=e.strict),t===void 0&&this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);let r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:fD(e?.tool_choice)?e?.tool_choice:(()=>{let i=m_(e?.tool_choice);if(typeof i=="object"&&"type"in i){if(i.type==="function")return{type:"function",name:i.function.name};if(i.type==="allowed_tools")return{type:"allowed_tools",mode:i.allowed_tools.mode,tools:i.allowed_tools.tools};if(i.type==="custom")return{type:"custom",name:i.custom.name}}})(),text:(()=>{if(e?.text)return e.text;let i=this._getResponseFormat(e?.response_format);return i?.type==="json_schema"?i.json_schema.schema!=null?{format:{type:"json_schema",schema:i.json_schema.schema,description:i.json_schema.description,name:i.json_schema.name,strict:i.json_schema.strict},verbosity:e?.verbosity}:void 0:{format:i,verbosity:e?.verbosity}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(e);return n!==void 0&&(r.reasoning=n),r}async _generate(e,t,r){let n=this.invocationParams(t);if(n.stream){let i=this._streamResponseChunks(e,t,r),s;for await(let o of i)o.message.response_metadata={...o.generationInfo,...o.message.response_metadata},s=s?.concat(o)??o;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let i=await this.completionWithRetry({input:x_({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:i.output_text,message:w_(i)}],llmOutput:{id:i.id,estimatedTokenUsage:i.usage?{promptTokens:i.usage.input_tokens,completionTokens:i.usage.output_tokens,totalTokens:i.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(e,t,r){let n=await this.completionWithRetry({...this.invocationParams(t),input:x_({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t);for await(let i of n){let s=FE(i);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}async completionWithRetry(e,t){return this.caller.call(async()=>{let r=this._getClientOptions(t);try{return e.text?.format?.type==="json_schema"&&!e.stream?await this.client.responses.parse(e,r):await this.client.responses.create(e,r)}catch(n){throw Yn(n)}})}_reduceChatOpenAITools(e,t){let r=[];for(let n of e)if(rl(n))n.type==="image_generation"&&t?.stream&&(n.partial_images=1),r.push(n);else if(rc(n)){let i=n.metadata.customTool;r.push({type:"custom",name:i.name,description:i.description,format:i.format})}else Ap(n)?r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:t?.strict??null}):h_(n)&&r.push(yD(n));return r}};var S_=class _z extends sc{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}constructor(t){super(t),this.fields=t,this.useResponsesApi=t?.useResponsesApi??!1,this.responses=t?.responses??new I_(t),this.completions=t?.completions??new v_(t)}_useResponsesApi(t){let r=t?.tools?.some(rl),n=t?.previous_response_id!=null||t?.text!=null||t?.truncation!=null||t?.include!=null||t?.reasoning?.summary!=null||this.reasoning?.summary!=null,i=t?.tools?.some(h_)||t?.tools?.some(rc);return this.useResponsesApi||r||n||i||oD(this.model)}getLsParams(t){let r=this._combineCallOptions(t);return this._useResponsesApi(t)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(t){let r=this._combineCallOptions(t);return this._useResponsesApi(t)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(t,r,n){return this._useResponsesApi(r)?this.responses._generate(t,r):this.completions._generate(t,r,n)}async*_streamResponseChunks(t,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(t,this._combineCallOptions(r),n);return}yield*this.completions._streamResponseChunks(t,this._combineCallOptions(r),n)}withConfig(t){let r=new _z(this.fields);return r.defaultOptions={...this.defaultOptions,...t},r}};var E_=class extends Fc{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(e){let t={maxConcurrency:2,...e};super(t);let r=t?.apiKey??t?.openAIApiKey??Je("OPENAI_API_KEY");this.organization=t?.configuration?.organization??Je("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelName=this.model,this.batchSize=t?.batchSize??this.batchSize,this.stripNewLines=t?.stripNewLines??this.stripNewLines,this.timeout=t?.timeout,this.dimensions=t?.dimensions,this.encodingFormat=t?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration}}async embedDocuments(e){let t=ng(this.stripNewLines?e.map(s=>s.replace(/\n/g," ")):e,this.batchSize),r=t.map(s=>{let o={model:this.model,input:s};return this.dimensions&&(o.dimensions=this.dimensions),this.encodingFormat&&(o.encoding_format=this.encodingFormat),this.embeddingWithRetry(o)}),n=await Promise.all(r),i=[];for(let s=0;s<n.length;s+=1){let o=t[s],{data:a}=n[s];for(let c=0;c<o.length;c+=1)i.push(a[c].embedding)}return i}async embedQuery(e){let t={model:this.model,input:this.stripNewLines?e.replace(/\n/g," "):e};this.dimensions&&(t.dimensions=this.dimensions),this.encodingFormat&&(t.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(t);return r[0].embedding}async embeddingWithRetry(e){if(!this.client){let r={baseURL:this.clientConfig.baseURL},n=ks(r),i={...this.clientConfig,baseURL:n,timeout:this.timeout,maxRetries:0};i.baseURL||delete i.baseURL,i.defaultHeaders=As(i.defaultHeaders),this.client=new de(i)}let t={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(e,t)}catch(r){throw Yn(r)}})}};var nq=Z.object({type:Z.literal("screenshot")}),iq=Z.object({type:Z.literal("click"),x:Z.number(),y:Z.number(),button:Z.enum(["left","right","wheel","back","forward"]).default("left")}),sq=Z.object({type:Z.literal("double_click"),x:Z.number(),y:Z.number(),button:Z.enum(["left","right","wheel","back","forward"]).default("left")}),oq=Z.object({type:Z.literal("drag"),path:Z.array(Z.object({x:Z.number(),y:Z.number()}))}),aq=Z.object({type:Z.literal("keypress"),keys:Z.array(Z.string())}),cq=Z.object({type:Z.literal("move"),x:Z.number(),y:Z.number()}),uq=Z.object({type:Z.literal("scroll"),x:Z.number(),y:Z.number(),scroll_x:Z.number(),scroll_y:Z.number()}),lq=Z.object({type:Z.literal("type"),text:Z.string()}),pq=Z.object({type:Z.literal("wait"),duration:Z.number().optional()}),dq=Z.discriminatedUnion("type",[nq,iq,sq,oq,aq,cq,uq,lq,pq]),eje=Z.object({action:dq});var fq=Z.object({type:Z.literal("exec"),command:Z.array(Z.string()),env:Z.record(Z.string(),Z.string()).optional(),working_directory:Z.string().optional(),timeout_ms:Z.number().optional(),user:Z.string().optional()}),ije=Z.discriminatedUnion("type",[fq]);var cje=Z.object({commands:Z.array(Z.string()).describe("Array of shell commands to execute"),timeout_ms:Z.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:Z.number().optional().describe("Optional maximum number of characters to return from each command")});var mq=Z.object({type:Z.literal("create_file"),path:Z.string(),diff:Z.string()}),hq=Z.object({type:Z.literal("update_file"),path:Z.string(),diff:Z.string()}),gq=Z.object({type:Z.literal("delete_file"),path:Z.string()}),dje=Z.discriminatedUnion("type",[mq,hq,gq]);var Iz={default:"gpt-5.2",fast:"gpt-5.2"},Sz={default:"text-embedding-ada-002"},BE=new Map,k_=null,yq=()=>(console.log("TODO: Use Portal helper services to get ArcGIS AI Models Service URL"),"https://aimodelsdev.arcgis.com"),vq=(e,t)=>`${e}/${t}/openai/v1`,Ez=async e=>{let t=yq();if(BE.size===0&&(k_||(k_=(async()=>{try{let r=await fetch(`${t}/models`);if(!r.ok)throw new Error("Failed to fetch AI service discovery data.");(await r.json()).models.forEach(n=>BE.set(n.name,n))}catch(r){throw k_=null,r}})()),await k_),!BE.get(e))throw new Error(`Model '${e}' is not available in the discovery service.`);return vq(t,e)},bq=async(e="default")=>await Ez(Iz[e]),kz=async(e="default")=>await Ez(Sz[e]),wq=async e=>{let t=await xq(),r=await kz("default"),n=KE.getDefault(),i=(await GE.getCredential(`${n.url}/sharing`)).token,s={type:"generateEmbeddings",layersAndFieldsRegistry:e,auth:{apiUrl:r,token:i}};return t.postMessage(s),await new Promise((o,a)=>{let c=l=>{l.data==="completed"&&(t.removeEventListener("message",c),o())},u=l=>{t.removeEventListener("message",c),a(l instanceof Error?l:new Error("Embeddings worker error"))};t.addEventListener("message",c),t.addEventListener("error",u,{once:!0})}),t},xq=async()=>{let e=(await import("./ZF7JAW4Z.js")).default;return new e},yz=(e,t)=>t,Iq=Fn.Root({userInput:Fn(),messages:Fn({reducer:ds,default:()=>[]}),pendingIntents:Fn({default:()=>[],reducer:yz}),currentIntent:Fn({default:()=>"none",reducer:yz})}),Os=async(e,t)=>{await GS("trace_message",e,t)},UDe=async(e,t)=>{await GS("graph_ux_suggestion",e,t)},Sq=e=>{e.currentIntent="none",e.pendingIntents=[]},Eq=async(e,t)=>{if(e.userInput){let n=new at(e.userInput.trim());e.messages=[...e.messages,n],Sq(e)}let r=t?.configurable?.services.agentRegistry.list().map(n=>n.agent.id)??[];return await Os({text:`Available agents: ${[...r].join(", ")}`},t),await Os({text:"Analyzing user input"},t),e},kq=async(e,t)=>(await Os({text:"Exiting..."},t),e),Aq=e=>{if(e.pendingIntents.length===0)return{...e,currentIntent:"none"};let[t,...r]=e.pendingIntents;return{...e,currentIntent:t,pendingIntents:r}},vz=4e3,Tq=async(e,t)=>{let r=t?.configurable,{agentRegistry:n}=r.services,i=n?.get(e.currentIntent);if(!i)return console.warn(`No agent found for intent: ${e.currentIntent}`),e;await Os({text:`Executing registered agent: ${i.agent.name}`},t);let s={...t??{},configurable:{...r??{},agentId:i.agent.id,context:i.getContext?await i.getContext():void 0}},o=await i.agent.createGraph().compile().invoke({messages:[...e.messages]},s);await Os({text:`Finished executing registered agent: ${i.agent.name}`},t);let a=typeof o?.outputMessage=="string"?o.outputMessage.trim():"";if(!a)return e;let c=a.length>vz?`${a.slice(0,vz-14)}
264
- [truncated]`:a;return{...e,messages:[...e.messages,new $e(c)]}},Oq=(e,t,r)=>{let n=e[t];return n?typeof n=="function"?n():Promise.resolve(n):new Promise((i,s)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(s.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==r?". Note that variables only represent file names one level deep.":""))))})},qE=async e=>(await Oq(Object.assign({"./field_descriptions_prompt.md":()=>import("./W5CHGOOR.js"),"./intent_prompt.md":()=>import("./CN6VFVA2.js"),"./layer_descriptions_prompt.md":()=>import("./JDL3HFFX.js")}),`./${e}.md`,2)).default,$q=(e,t=3)=>e.filter(r=>r instanceof at).slice(-t),Cq=e=>{let t=-1;for(let r=e.length-1;r>=0;r--)if(e[r]instanceof at){t=r;break}return t===-1?"":e.slice(t+1).filter(r=>r instanceof $e).map(r=>r.content).join(`
265
- `)},Az=e=>async(t,r)=>{let n=new Headers(r?.headers);return n.delete("Authorization"),n.delete("api-key"),e&&e.length>0&&n.set("X-Esri-Authorization",`Bearer ${e}`),await fetch(t,{...r,headers:n})},HE=async(e="default",t=0)=>{let r=KE.getDefault(),n=await GE.getCredential(`${r.url}/sharing`),i=Iz[e],s=await bq(e);return new S_({temperature:t,modelName:i,apiKey:"dummy-key",configuration:{baseURL:s,fetch:Az(n.token)}})},Pq=async(e="default")=>{let t=KE.getDefault(),r=await GE.getCredential(`${t.url}/sharing`),n=Sz[e],i=await kz(e);return new E_({modelName:n,apiKey:"dummy-key",configuration:{baseURL:i,fetch:Az(r.token)},batchSize:2048,maxConcurrency:10})},Nq=e=>{let t=new Set;for(let r of e)if(si(r)){let n=r;n.tool_calls&&n.tool_calls.length>0&&n.tool_calls.forEach(i=>{i.id&&t.add(i.id)})}return e.filter(r=>{if(Mo(r)){let n=r;return t.has(n.tool_call_id)}return!0})},WE=(e,t)=>{let r=Lp.fromTemplate(e);return ro.fromMessages([r,...t])},Rq=async e=>{let{promptText:t,modelTier:r,temperature:n,messages:i}=e,s=WE(t,i??[]),o=await HE(r,n);return s.pipe(o)},FDe=async e=>{let{promptText:t,modelTier:r="default",temperature:n=0,messages:i,inputVariables:s}=e,o=await(await Rq({promptText:t,modelTier:r,temperature:n,messages:i})).invoke(s??{});if(typeof o=="string")return o;let a=o.content;return typeof a=="string"?a:JSON.stringify(a)},JE=async e=>{let{promptText:t,modelTier:r="default",temperature:n=0,messages:i,inputVariables:s,schema:o}=e,a=WE(t,i??[]),c=(await HE(r,n)).withStructuredOutput(o);return await a.pipe(c).invoke(s??{})},BDe=async e=>{let{promptText:t,modelTier:r="default",temperature:n=0,messages:i,inputVariables:s,tools:o}=e,a=o.length>0?Nq(i??[]):i??[],c=WE(t,a),u=await HE(r,n);return await c.pipe(u.bindTools(o)).invoke(s??{})},Mq=ce.object({id:ce.string().min(1),name:ce.string().min(1),description:ce.string().min(1)});ce.array(Mq);var jq=e=>{let t=e.map(n=>n.id),r=ce.enum(t);return ce.object({intents:ce.array(r)})},Dq=async(e,t)=>{try{await Os({text:"Asking LLM to detect intents"},t);let r=await qE("intent_prompt"),n=(t?.configurable?.services.agentRegistry?.list()??[]).map(({agent:d})=>({id:d.id,name:d.name,description:d.description}));if(!n.length)return await Os({text:"No agents registered; skipping intent detection"},t),{...e,currentIntent:"none",pendingIntents:[]};let i=n.map(d=>JSON.stringify(d)).join(`
266
- `),s=n.length,o=jq(n),a={maxIntents:s,registeredAgents:i},c=await JE({promptText:r,modelTier:"fast",schema:o,messages:$q(e.messages),inputVariables:a}),u=new Set,l=(c.intents??[]).filter(d=>u.has(d)?!1:(u.add(d),!0)).slice(0,s),p=l[0]??"none",f={...e,currentIntent:p,pendingIntents:l};return await Os({text:`Intents came back as: ${l.join(", ")||"none"}`},t),f}catch(r){throw await Os({text:"Error during intent detection"},t),new Error(`Error during intent detection: ${r instanceof Error?r.message:String(r)}`)}},zq=()=>new zg(Iq).addNode("ingestInput",Eq).addNode("intentLLM",Dq).addNode("intentDispatcher",Aq).addNode("executeRegisteredAgent",Tq).addNode("exit",kq).addEdge(Ae,"ingestInput").addEdge("ingestInput","intentLLM").addEdge("intentLLM","intentDispatcher").addConditionalEdges("intentDispatcher",e=>e.currentIntent==="none"?"exit":"executeRegisteredAgent").addEdge("executeRegisteredAgent","intentDispatcher").addEdge("exit",xe),VE=class{constructor(){this.agentRegistry=new Map}register(t){let{agent:r}=t;if(this.agentRegistry.has(r.id))throw new Error(`Duplicate agent id: ${r.id}`);this.agentRegistry.set(r.id,t)}get(t){return this.agentRegistry.get(t)}list(){return[...this.agentRegistry.values()]}},ZE=class{constructor(t,r){this.graph=t,this.config={...r}}async waitForUser(){return await new Promise((t,r)=>{this.resolveWait=t,this.rejectWait=r})}handle(t,r){try{let n={agentId:t.agentId,id:t.id,payload:r},i=this.graph.streamEvents(null,{...this.config,configurable:{...this.config.configurable,hitlResponse:n},subgraphs:!0,version:"v2"});this.resolveWait?.(i)}catch(n){this.rejectWait?.(n)}finally{this.resolveWait=void 0,this.rejectWait=void 0}}cancel(){this.rejectWait&&(this.rejectWait(new Error("User cancelled HITL")),this.resolveWait=void 0,this.rejectWait=void 0)}},Lq=wn.object({name:wn.string(),description:wn.string(),valueType:wn.string(),alias:wn.string()}),Uq=wn.object({fields:wn.array(Lq)});function bz(e,t){let r=new Map;for(let n of e.fields){let i=t.fields.find(o=>o.name===n.name),s={name:n.name,type:n.type,alias:i?.alias??n.alias??"",description:i?.description??n.description??"",valueType:i?.valueType??n.valueType??""};r.set(n.name,s)}return r}var Fq=async e=>{let t=await qE("field_descriptions_prompt"),r=e.fields.filter(s=>!(s.alias&&s.description)).map(s=>{let{name:o,type:a,alias:c,description:u}=s;return[`Name: ${o}`,`Type: ${a}`,`Alias: ${c}`,`Description: ${u??"N/A"}`].join(", ")}).join(`
267
- `);if(r.length===0)return bz(e,{fields:[]});let n={existingItemTitle:e.portalItem?.title,existingItemDescription:e.portalItem?.description,existingLayerTitle:e.title,existingLayerDescription:e.portalItem?.description,fieldInformation:r},i=await JE({promptText:t,modelTier:"fast",schema:Uq,inputVariables:n});return bz(e,i)},Bq=wn.object({title:wn.string(),description:wn.string(),name:wn.string().nullable()}),Vq=async(e,t)=>{let r=await qE("layer_descriptions_prompt"),n=Array.from(t.values()),i={fieldInformation:JSON.stringify(n,null,2),existingLayerTitle:e.title,existingLayerDescription:e.portalItem?.description,existingLayerSnippet:e.portalItem?.snippet,layerGeometryType:e.geometryType};return{...await JE({promptText:r,modelTier:"fast",schema:Bq,inputVariables:i}),name:e.title??null}},Zq=async e=>{let t=e.allLayers.toArray(),r=[],n=new Map;for(let i of t)if(i instanceof _q){let s=(async()=>{let o=await Fq(i),a=await Vq(i,o);n.set(i.id,{layerItem:a,fieldRegistry:o})})();r.push(s)}return await Promise.all(r),n},Gq=async e=>await(await Pq()).embedQuery(e),Tz=async(e,t)=>{let r=t.get(e);if(r)return r;let n=await Gq(e);return t.set(e,n),n};async function Kq(e,t,r,n){let i=`req-${Date.now()}`,s={type:"layerSearch",precomputedEmbedding:n?await Tz(e,n):void 0,requestId:i};return await new Promise(o=>{let a=c=>{if(c.data.requestId!==i)return;let u=c.data.results.filter(([,l])=>l>=r).map(([l,p])=>({id:l.id??"",score:p}));o(u)};t.addEventListener("message",a,{once:!0}),t.postMessage(s)})}function qq(e){let{worker:t}=e;return{async searchLayers({text:r,minScore:n,embeddingCache:i}){return await Kq(r,t,n,i)}}}var Hq=async({combinedQuery:e,layerIds:t,embeddingsWorker:r,minScore:n,topResults:i,embeddingCache:s})=>{let o=`req-${Date.now()}`,a=s?await Tz(e,s):void 0,c={type:"fieldSearch",layerIdForFieldsSearch:t,precomputedEmbedding:a,requestId:o};return await new Promise(u=>{let l=p=>{if(p.data.requestId!==o)return;let f=p.data.results.map(({layerId:d,results:m})=>{let h=m.filter(([,b])=>b>=n).map(([b,_])=>({name:b.id??"",score:_})).sort((b,_)=>_.score-b.score).slice(0,i);return{layerId:d,results:h}});u(f)};r.addEventListener("message",l,{once:!0}),r.postMessage(c)})};function Wq(e){let{worker:t}=e;return{async searchFields({text:r,layerIds:n,minScore:i,topResults:s,embeddingCache:o}){return await Hq({combinedQuery:r,layerIds:n,embeddingsWorker:t,minScore:i,topResults:s,embeddingCache:o})}}}var wz=class e{constructor(t){this.deps=t,this.orchestratorReady=!1,this.chatHistory=[],this.threadId="",this.agentRegistry=new VE,this.streamEpoch=0}static async init(t){let r=new e(t);if(t.view&&(await xz.whenOnce(()=>t.view.ready),t.view.map)){let n=await Zq(t.view.map);r.layersAndFieldsRegistry=n,r.embeddingsWorker=await wq(n)}return t.agents?.forEach(n=>{r.agentRegistry.register(n)}),r.orchestratorReady=!0,r}async*ask(t){if(!this.orchestratorReady)throw new Error("Orchestrator is not ready yet.");if(!this.agentRegistry.list().length)throw new Error("Orchestrator has no registered agents.");if(++this.streamEpoch,!t.trim())return;this.threadId=String(Date.now()),this.graph||(this.graph=zq().compile({checkpointer:new lg}));let r=this.embeddingsWorker?qq({worker:this.embeddingsWorker}):void 0,n=this.embeddingsWorker?Wq({worker:this.embeddingsWorker}):void 0,i=new Map,s={version:"v2",streamMode:"custom",configurable:{thread_id:this.threadId,hitlResponse:null,services:{layerSearch:r,fieldSearch:n,layersAndFieldsRegistry:this.layersAndFieldsRegistry,agentRegistry:this.agentRegistry,portal:this.deps.portal,embeddingCache:i}},subgraphs:!0},o=this.graph?.streamEvents({userInput:t,messages:this.chatHistory},s),a=++this.streamEpoch;for(yield*this.pipeStream(o,a);;){let u=(await this.graph.getState(s,{subgraphs:!0})).tasks.find(l=>l.interrupts.length>0)?.interrupts[0]?.value;if(!u)break;this.currentInterrupt=u,this.interruptHandler=new ZE(this.graph,s),yield{runId:this.threadId,timestamp:Date.now(),type:"interrupt",interrupt:u};try{let l=await this.interruptHandler.waitForUser(),p=++this.streamEpoch;yield*this.pipeStream(l,p)}catch(l){if(l){yield{runId:this.threadId,timestamp:Date.now(),type:"error",error:{message:l?.message}};return}yield{runId:this.threadId,timestamp:Date.now(),type:"cancelled"};return}}let c=(await this.graph.getState(s,{subgraphs:!0})).values;this.chatHistory=c.messages.length?c.messages:this.chatHistory,yield{runId:this.threadId,timestamp:Date.now(),type:"completed",result:{content:Cq(c.messages)}}}newConversation(){this.chatHistory=[]}resumeInterrupt(t){if(!this.currentInterrupt||!this.interruptHandler)throw new Error("No pending interrupt to resume.");this.interruptHandler.handle(this.currentInterrupt,t)}cancelInterrupt(){this.interruptHandler&&this.interruptHandler.cancel()}async*pipeStream(t,r){for await(let n of t){if(r!==this.streamEpoch){console.log("Stale stream detected, aborting.");break}n.event==="on_custom_event"&&n.name==="trace_message"?yield{runId:this.threadId,timestamp:Date.now(),type:"trace",data:n.data}:n.name==="graph_ux_suggestion"&&(yield{runId:this.threadId,timestamp:Date.now(),type:"ux-suggestion",suggestion:n.data})}}dispose(){this.embeddingsWorker&&(this.embeddingsWorker.terminate(),this.embeddingsWorker=void 0),this.orchestratorReady=!1}};var Jq="0.1",Fd=1536,Xq="openai",Yq="text-embedding-ada-002",Qq=`Name: {name}
268
- Title: {title}
269
- Description: {description}`,eH=`Name: {name}
270
- Alias: {alias}
271
- Description: {description}`,VDe=ce.object({schemaVersion:ce.literal(Jq),modified:ce.number().int().nonnegative(),embeddings:ce.object({modelProvider:ce.literal(Xq),model:ce.literal(Yq),dimensions:ce.literal(Fd),templates:ce.object({layer:ce.string().default(Qq),field:ce.string().default(eH)})}),layers:ce.array(ce.object({id:ce.string().min(1),name:ce.string().min(1),title:ce.string().catch(""),description:ce.string().catch(""),vector:ce.array(ce.number()).length(Fd,{message:`Layer vector must be exactly ${Fd} dimensions`}),fields:ce.array(ce.object({name:ce.string().min(1),alias:ce.string().catch(""),description:ce.string().catch(""),vector:ce.array(ce.number()).length(Fd,{message:`Field vector must be exactly ${Fd} dimensions`})}))})).min(1)});return{a:Vd,b:Ri,c:ot,d:Wt,e:at,f:$e,g:si,h:ce,i:Jp,j:Fn,k:Ae,l:xe,m:$t,n:jr,o:Pt,p:sr,q:ds,r:zg,s:wn,t:Os,u:UDe,v:FDe,w:JE,x:BDe,y:wz}},"identity/IdentityManager","portal/Portal","layers/FeatureLayer","core/reactiveUtils")