@shumai-one/shumai 0.4.2 → 0.4.4

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 (269) hide show
  1. package/bin/chunk-071x515q.js +4 -0
  2. package/bin/{chunk-adekdctx.css → chunk-0ccg9ddn.css} +1 -1
  3. package/bin/chunk-0cmx7k4c.js +1 -0
  4. package/bin/chunk-0qaq0sp8.js +5 -0
  5. package/bin/chunk-0qjfahk9.js +2 -0
  6. package/bin/chunk-0zv3bks2.js +2 -0
  7. package/bin/chunk-16xax8kk.js +1 -0
  8. package/bin/chunk-1gvscz88.js +5 -0
  9. package/bin/chunk-1j27fzy1.js +2 -0
  10. package/bin/chunk-1t167cvj.js +11 -0
  11. package/bin/chunk-1xh34aew.js +2 -0
  12. package/bin/chunk-1zwajpwf.js +8 -0
  13. package/bin/chunk-2w5xqhjm.js +1 -0
  14. package/bin/chunk-3tedzb2j.js +54 -0
  15. package/bin/chunk-3ttrhqy3.js +2 -0
  16. package/bin/chunk-3zkasqb8.js +1 -0
  17. package/bin/chunk-453ykvaw.js +2 -0
  18. package/bin/chunk-4991gz3y.js +13 -0
  19. package/bin/chunk-4hkkdm2q.js +2 -0
  20. package/bin/chunk-4mjywsj8.js +3 -0
  21. package/bin/chunk-4v41a1r9.js +6 -0
  22. package/bin/chunk-4wy87hwd.js +3 -0
  23. package/bin/chunk-579e4wv4.js +3 -0
  24. package/bin/chunk-5adsx8x4.js +2 -0
  25. package/bin/chunk-5hg6kcfz.js +45 -0
  26. package/bin/chunk-5nm2jvg5.js +32 -0
  27. package/bin/chunk-5tcdwep5.js +11 -0
  28. package/bin/chunk-5vzrpz50.js +2 -0
  29. package/bin/chunk-6ghcj4a9.js +3 -0
  30. package/bin/chunk-77fmkpdz.js +10 -0
  31. package/bin/chunk-7bcxj1jd.js +2 -0
  32. package/bin/chunk-7gmdnsdg.js +2 -0
  33. package/bin/chunk-7jtmwt5a.js +3 -0
  34. package/bin/chunk-7kjgvxqa.js +2 -0
  35. package/bin/chunk-7pw1550a.js +2 -0
  36. package/bin/chunk-7rhz2gze.js +211 -0
  37. package/bin/chunk-837fky18.js +3 -0
  38. package/bin/chunk-84as6x83.js +1 -0
  39. package/bin/chunk-8e28hcny.js +2 -0
  40. package/bin/chunk-914bp49r.js +4 -0
  41. package/bin/chunk-97f2af6d.js +12 -0
  42. package/bin/chunk-98715kc3.js +2 -0
  43. package/bin/chunk-9ccw540k.js +2 -0
  44. package/bin/chunk-9t8n2des.js +2 -0
  45. package/bin/chunk-9ybt6vbm.js +1 -0
  46. package/bin/chunk-a6gx7f5q.js +1 -0
  47. package/bin/chunk-avwgktxb.js +2 -0
  48. package/bin/chunk-bkr5zm4h.js +2 -0
  49. package/bin/chunk-cbgq517y.js +2 -0
  50. package/bin/chunk-d27mm390.js +1 -0
  51. package/bin/chunk-dj92fss9.js +2 -0
  52. package/bin/chunk-dqxeztfa.js +2 -0
  53. package/bin/chunk-drepsbb4.js +2 -0
  54. package/bin/chunk-f6svp4dp.js +2 -0
  55. package/bin/chunk-fahk9h62.js +8 -0
  56. package/bin/chunk-fb40xxz3.js +3 -0
  57. package/bin/chunk-fnmwksnb.js +3 -0
  58. package/bin/chunk-fpc4p0j8.js +3 -0
  59. package/bin/chunk-fsyzs0tf.js +1 -0
  60. package/bin/chunk-fxecgp5k.js +1 -0
  61. package/bin/chunk-g3fpmyyn.js +3 -0
  62. package/bin/chunk-gc5sbfa5.js +2 -0
  63. package/bin/chunk-gdm6yfqq.js +2 -0
  64. package/bin/chunk-gk2q9a3f.js +2 -0
  65. package/bin/chunk-gt4csat6.js +3 -0
  66. package/bin/chunk-gye8gabk.js +2 -0
  67. package/bin/chunk-hk5rc6cd.js +24 -0
  68. package/bin/chunk-hm0dkzed.js +3 -0
  69. package/bin/chunk-hmpwg5za.js +16 -0
  70. package/bin/chunk-j1tkmcae.js +3 -0
  71. package/bin/chunk-j2bvj2yn.js +2 -0
  72. package/bin/chunk-jffktpqg.js +1 -0
  73. package/bin/chunk-jgs8an3h.js +18 -0
  74. package/bin/chunk-jmpb5633.js +2 -0
  75. package/bin/chunk-jrjnqx78.js +2 -0
  76. package/bin/chunk-k2k9vjq6.js +1 -0
  77. package/bin/chunk-kpgfqkp0.js +3 -0
  78. package/bin/chunk-ks8xzc95.js +3 -0
  79. package/bin/chunk-kswvyqq1.js +2 -0
  80. package/bin/chunk-m9pr03kn.js +2 -0
  81. package/bin/chunk-mfn9qjm4.js +2 -0
  82. package/bin/chunk-msfw3jmc.js +3 -0
  83. package/bin/chunk-mz0yjra0.js +5 -0
  84. package/bin/chunk-nbdw8fen.js +1 -0
  85. package/bin/chunk-nkdk229f.js +2 -0
  86. package/bin/chunk-nr20tvnw.js +3 -0
  87. package/bin/chunk-pazjhrnf.js +12 -0
  88. package/bin/chunk-q806pqeh.js +1 -0
  89. package/bin/chunk-qka4mkmj.js +2 -0
  90. package/bin/chunk-qsr1a0rp.js +2 -0
  91. package/bin/chunk-rchsme43.js +3 -0
  92. package/bin/chunk-reyxk4bw.js +2 -0
  93. package/bin/chunk-rhvv1vvk.js +3 -0
  94. package/bin/chunk-rq0n0vcc.js +2 -0
  95. package/bin/chunk-rqf7999q.js +42 -0
  96. package/bin/chunk-rssgmj7x.js +2 -0
  97. package/bin/chunk-ryzz5fht.js +2 -0
  98. package/bin/chunk-s2fnfyn9.js +2 -0
  99. package/bin/chunk-s2k4qntr.js +3 -0
  100. package/bin/chunk-snhsjs4x.js +299 -0
  101. package/bin/chunk-t2hy6tj9.js +2 -0
  102. package/bin/chunk-t7nsgg5k.js +4 -0
  103. package/bin/chunk-tm7f32c7.js +14 -0
  104. package/bin/chunk-trveq4wg.js +3 -0
  105. package/bin/chunk-vap4k11j.js +20 -0
  106. package/bin/chunk-vm5fx7td.js +3 -0
  107. package/bin/chunk-vy8gntez.js +1 -0
  108. package/bin/chunk-vyzptrea.js +2 -0
  109. package/bin/chunk-w4ghe71n.js +2 -0
  110. package/bin/chunk-wdsf44hs.js +2 -0
  111. package/bin/chunk-wjyaezs7.js +2 -0
  112. package/bin/chunk-wndm3px3.js +1 -0
  113. package/bin/chunk-x5jwwvs0.js +1 -0
  114. package/bin/chunk-x92cq59c.js +1 -0
  115. package/bin/chunk-xa18z1py.js +3 -0
  116. package/bin/chunk-xarsrs08.js +2 -0
  117. package/bin/chunk-xtf3c29c.css +1 -0
  118. package/bin/chunk-xx337zcw.js +2 -0
  119. package/bin/chunk-xz6713tj.js +2 -0
  120. package/bin/chunk-yfnem6se.js +2 -0
  121. package/bin/chunk-ytdwk2fq.js +2 -0
  122. package/bin/chunk-ze20rm02.js +7 -0
  123. package/bin/chunk-zw86wnwe.js +7 -0
  124. package/bin/chunk-zxk7q0zk.js +2 -0
  125. package/bin/{pdf.worker.min-szxdj13d.mjs → pdf.worker.min-vf48er29.mjs} +14423 -13889
  126. package/bin/shumai-app.html +1 -1
  127. package/bin/shumai-app.js +841 -678
  128. package/package.json +18 -18
  129. package/prisma/migrations/20260904022457_add_agent_id_to_assets_and_audit_logs/migration.sql +17 -0
  130. package/prisma/migrations/20260906081230_default_denied_tools_delete_asset/migration.sql +15 -0
  131. package/prisma/migrations/20260907021754_add_asset_upload_id/migration.sql +2 -0
  132. package/prisma/schema.prisma +10 -0
  133. package/bin/chunk-07h4b77v.js +0 -2
  134. package/bin/chunk-0t4n4d5w.js +0 -4
  135. package/bin/chunk-1611z9jg.js +0 -2
  136. package/bin/chunk-1phqxp6z.js +0 -3
  137. package/bin/chunk-23hckrrz.js +0 -2
  138. package/bin/chunk-30z44j1g.js +0 -2
  139. package/bin/chunk-3j463k1g.js +0 -1
  140. package/bin/chunk-4181tdds.js +0 -14
  141. package/bin/chunk-480jtqng.js +0 -4
  142. package/bin/chunk-4c3g146q.js +0 -2
  143. package/bin/chunk-4ca0zt5e.js +0 -1
  144. package/bin/chunk-4d9bgmf2.js +0 -2
  145. package/bin/chunk-4ev56fss.js +0 -9
  146. package/bin/chunk-4gk52tjq.js +0 -45
  147. package/bin/chunk-4mdqkj4d.js +0 -1
  148. package/bin/chunk-4r91fggc.js +0 -2
  149. package/bin/chunk-50fb1x3w.js +0 -1
  150. package/bin/chunk-59gj1njz.js +0 -1
  151. package/bin/chunk-5pr0t7fb.js +0 -2
  152. package/bin/chunk-5vewxmz7.js +0 -3
  153. package/bin/chunk-62zx96pe.js +0 -2
  154. package/bin/chunk-63y0eb07.js +0 -2
  155. package/bin/chunk-6d5xrgfx.js +0 -2
  156. package/bin/chunk-6gbtz5bf.js +0 -67
  157. package/bin/chunk-6gjg5egq.js +0 -3
  158. package/bin/chunk-6m4jz9s1.js +0 -44
  159. package/bin/chunk-6s4x525w.js +0 -2
  160. package/bin/chunk-6w2wmvqs.js +0 -3
  161. package/bin/chunk-77d23vcn.js +0 -2
  162. package/bin/chunk-77m5p188.js +0 -2
  163. package/bin/chunk-7bvx087f.js +0 -1
  164. package/bin/chunk-7pfjfrjg.js +0 -5
  165. package/bin/chunk-7q10s127.js +0 -4
  166. package/bin/chunk-7thx8ctx.js +0 -3
  167. package/bin/chunk-8t4s91gh.js +0 -2
  168. package/bin/chunk-98ey5p2e.js +0 -3
  169. package/bin/chunk-9amndcyh.js +0 -6
  170. package/bin/chunk-9bk23g9x.js +0 -1
  171. package/bin/chunk-9mkcfy43.js +0 -1
  172. package/bin/chunk-9t3nsq5n.js +0 -2
  173. package/bin/chunk-9tjq99ds.js +0 -2
  174. package/bin/chunk-9wm9rwh1.js +0 -2
  175. package/bin/chunk-ab16fyg4.js +0 -4
  176. package/bin/chunk-arv0g2av.js +0 -1
  177. package/bin/chunk-aytj4zxg.js +0 -3
  178. package/bin/chunk-b1ypjqgp.js +0 -2
  179. package/bin/chunk-bdjv0ykq.js +0 -2
  180. package/bin/chunk-c1k86mfa.js +0 -10
  181. package/bin/chunk-caa96dgd.js +0 -2
  182. package/bin/chunk-ce4v2yjy.js +0 -1
  183. package/bin/chunk-cqh60y54.js +0 -3
  184. package/bin/chunk-cvq7zgw7.js +0 -1
  185. package/bin/chunk-d9mjbtp2.js +0 -2
  186. package/bin/chunk-dn7sbjws.js +0 -3
  187. package/bin/chunk-dxyq9h8n.js +0 -3
  188. package/bin/chunk-e3cabksx.js +0 -3
  189. package/bin/chunk-egcrbj94.js +0 -2
  190. package/bin/chunk-ev17v1mv.js +0 -2
  191. package/bin/chunk-evtpwg71.js +0 -2
  192. package/bin/chunk-f3e0nsv2.js +0 -2
  193. package/bin/chunk-f40gjqpq.js +0 -2
  194. package/bin/chunk-fe7822ak.js +0 -299
  195. package/bin/chunk-g8tkhw9j.js +0 -2
  196. package/bin/chunk-g9r0p4t8.js +0 -2
  197. package/bin/chunk-gbjyh9ms.js +0 -1
  198. package/bin/chunk-gtbsb39v.js +0 -3
  199. package/bin/chunk-gytz1q13.js +0 -13
  200. package/bin/chunk-h0fxysxs.js +0 -7
  201. package/bin/chunk-h8bdvsqt.js +0 -2
  202. package/bin/chunk-hag024w8.js +0 -2
  203. package/bin/chunk-hc6w5nw4.js +0 -7
  204. package/bin/chunk-j69dqc48.js +0 -2
  205. package/bin/chunk-jbtw1zym.js +0 -8
  206. package/bin/chunk-jc1vb7rj.js +0 -5
  207. package/bin/chunk-jdv78w9r.js +0 -2
  208. package/bin/chunk-jjs70y9v.js +0 -3
  209. package/bin/chunk-jmdar2gz.js +0 -2
  210. package/bin/chunk-jvwz10n4.js +0 -2
  211. package/bin/chunk-k47md1g4.js +0 -2
  212. package/bin/chunk-k4v0brcb.js +0 -2
  213. package/bin/chunk-k6n7c07e.js +0 -1
  214. package/bin/chunk-kk2cstsg.js +0 -2
  215. package/bin/chunk-knz4h56q.js +0 -12
  216. package/bin/chunk-kqqtt6bd.js +0 -3
  217. package/bin/chunk-kvyp1t4j.js +0 -7
  218. package/bin/chunk-kxskpgsq.js +0 -5
  219. package/bin/chunk-m6srbjcs.js +0 -2
  220. package/bin/chunk-mcc1scxs.js +0 -12
  221. package/bin/chunk-mq83a0kk.js +0 -2
  222. package/bin/chunk-mxm8g4q0.js +0 -1
  223. package/bin/chunk-nhpgdqq5.js +0 -2
  224. package/bin/chunk-nne496aa.js +0 -2
  225. package/bin/chunk-nqpb0r9h.js +0 -11
  226. package/bin/chunk-ns0zww9g.js +0 -2
  227. package/bin/chunk-ps4xfp23.js +0 -2
  228. package/bin/chunk-pz2ec6xt.js +0 -2
  229. package/bin/chunk-q163k309.js +0 -2
  230. package/bin/chunk-q1da61ps.js +0 -1
  231. package/bin/chunk-qrf0ady6.js +0 -68
  232. package/bin/chunk-qy28f25e.js +0 -2
  233. package/bin/chunk-r7s4ypw1.js +0 -2
  234. package/bin/chunk-ran23vm9.js +0 -1
  235. package/bin/chunk-rfvdc4n0.js +0 -2
  236. package/bin/chunk-rgthkvgx.js +0 -3
  237. package/bin/chunk-s39n3yw3.js +0 -2
  238. package/bin/chunk-s7wdd0g7.js +0 -8
  239. package/bin/chunk-s88ha5kx.js +0 -3
  240. package/bin/chunk-sf91bt9m.js +0 -2
  241. package/bin/chunk-sjwbjf9j.js +0 -2
  242. package/bin/chunk-t62076pv.js +0 -1
  243. package/bin/chunk-tbbwss3v.js +0 -3
  244. package/bin/chunk-tjcc7a6y.js +0 -24
  245. package/bin/chunk-tp6ab26e.js +0 -2
  246. package/bin/chunk-v2wxk9p5.js +0 -4
  247. package/bin/chunk-vbk6y4hk.js +0 -2
  248. package/bin/chunk-vfgfg5fk.js +0 -2
  249. package/bin/chunk-vm6c3xx9.js +0 -2
  250. package/bin/chunk-vsx96mt6.js +0 -3
  251. package/bin/chunk-wbyw1shz.js +0 -6
  252. package/bin/chunk-whh2vh50.css +0 -1
  253. package/bin/chunk-wjkcq65s.js +0 -2
  254. package/bin/chunk-wkefwkfp.js +0 -41
  255. package/bin/chunk-x7bsnk1e.js +0 -2
  256. package/bin/chunk-xbhw6bpz.js +0 -3
  257. package/bin/chunk-xg5yrcj5.js +0 -2
  258. package/bin/chunk-xg9xscqz.js +0 -1
  259. package/bin/chunk-xw2gpcsh.js +0 -3
  260. package/bin/chunk-ycq8ank7.js +0 -2
  261. package/bin/chunk-yp9hvkc5.js +0 -73
  262. package/bin/chunk-ytypyfkc.js +0 -65
  263. package/bin/chunk-z1kjmf60.js +0 -2
  264. package/bin/chunk-z36bx86r.js +0 -2
  265. package/bin/chunk-z7hdnecp.js +0 -3
  266. package/bin/chunk-zeby1cq7.js +0 -2
  267. package/bin/chunk-zs5e8z1w.js +0 -1
  268. package/bin/chunk-zxnyefg5.js +0 -2
  269. /package/bin/{chunk-24ke0th1.css → chunk-kegybs91.css} +0 -0
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ function Pn(i){return typeof i>"u"||i===void 0}function Vt(i){return typeof i==="string"}function jo(i){return typeof i==="number"}function vs(i){return typeof i==="boolean"}function Xs(i){return i===null}function Su(i){return i instanceof Date}function ea(i){return typeof i==="bigint"}function nm(i){return typeof Buffer<"u"&&Buffer.isBuffer(i)}function Kt(i){return typeof i==="function"}function Er(i){return typeof i==="object"&&i!==null}function f(i){return Object.freeze(i)}function pc(i){if(Nn(i))return i;else return[i]}function Nn(i){return Array.isArray(i)}function Gn(i){return i}var om=["preserve rows","delete rows","drop"],On=f({is(i){return i.kind==="CreateTableNode"},create(i){return f({kind:"CreateTableNode",table:i,columns:f([])})},cloneWithColumn(i,t){return f({...i,columns:f([...i.columns,t])})},cloneWithConstraint(i,t){return f({...i,constraints:i.constraints?f([...i.constraints,t]):f([t])})},cloneWithFrontModifier(i,t){return f({...i,frontModifiers:i.frontModifiers?f([...i.frontModifiers,t]):f([t])})},cloneWithEndModifier(i,t){return f({...i,endModifiers:i.endModifiers?f([...i.endModifiers,t]):f([t])})},cloneWith(i,t){return f({...i,...t})}});var Ir=f({is(i){return i.kind==="InsertQueryNode"},create(i,t,e){return f({kind:"InsertQueryNode",into:i,...t&&{with:t},replace:e})},createWithoutInto(){return f({kind:"InsertQueryNode"})},cloneWith(i,t){return f({...i,...t})}});class r{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#i=f({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this)});visitNode=(i)=>{this.nodeStack.push(i),this.#i[i.kind](i),this.nodeStack.pop()}}var h=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from"],d=["+","-","*","/","%","^","&","|","#","<<",">>"],a=["->","->>"],l=[...h,...d,"&&","||"],c=["exists","not exists"],u=["not","-",...c],sm=[...l,...a,...u,"between","between symmetric"],Mo=f({is(i){return i.kind==="OperatorNode"},create(i){return f({kind:"OperatorNode",operator:i})}});function lf(i){return Vt(i)&&a.includes(i)}var Ro=f({is(i){return i.kind==="ParensNode"},create(i){return f({kind:"ParensNode",node:i})}});var Bt=f({is(i){return i.kind==="RawNode"},create(i,t){return f({kind:"RawNode",sqlFragments:f(i),parameters:f(t)})},createWithSql(i){return Bt.create([i],[])},createWithChild(i){return Bt.create(["",""],[i])},createWithChildren(i){return Bt.create(Array(i.length+1).fill(""),i)}});var ze=f({is(i){return i.kind==="IdentifierNode"},create(i){return f({kind:"IdentifierNode",name:i})}});var gn=f({is(i){return i.kind==="SchemableIdentifierNode"},create(i){return f({kind:"SchemableIdentifierNode",identifier:ze.create(i)})},createWithSchema(i,t){return f({kind:"SchemableIdentifierNode",schema:ze.create(i),identifier:ze.create(t)})}});var ss=f({is(i){return i.kind==="CreateViewNode"},create(i){return f({kind:"CreateViewNode",name:gn.create(i)})},cloneWith(i,t){return f({...i,...t})}});var Cu=f({is(i){return i.kind==="SetOperationNode"},create(i,t,e){return f({kind:"SetOperationNode",operator:i,expression:t,all:e})}});var qo=f({is(i){return i.kind==="WhenNode"},create(i){return f({kind:"WhenNode",condition:i})},cloneWithResult(i,t){return f({...i,result:t})}});var p=new Set;function os(i){if(p.has(i))return;p.add(i),console.log(i)}var m=/'/g,N=/['"]/g;class Dn extends r{#i="";#t=[];get numParameters(){return this.#t.length}compileQuery(i,t){return this.#i="",this.#t=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(i),f({query:i,queryId:t,sql:this.getSql(),parameters:[...this.#t]})}getSql(){return this.#i}visitSelectQuery(i){let t=this.parentNode!==void 0&&!Ro.is(this.parentNode)&&!Ir.is(this.parentNode)&&!On.is(this.parentNode)&&!ss.is(this.parentNode)&&!Cu.is(this.parentNode);if(this.parentNode===void 0&&i.explain)this.visitNode(i.explain),this.append(" ");if(t)this.append("(");if(i.with)this.visitNode(i.with),this.append(" ");if(this.append("select"),i.distinctOn)this.append(" "),this.compileDistinctOn(i.distinctOn);if(i.frontModifiers?.length)this.append(" "),this.compileList(i.frontModifiers," ");if(i.top)this.append(" "),this.visitNode(i.top);if(i.selections)this.append(" "),this.compileList(i.selections);if(i.from)this.append(" "),this.visitNode(i.from);if(i.joins)this.append(" "),this.compileList(i.joins," ");if(i.where)this.append(" "),this.visitNode(i.where);if(i.groupBy)this.append(" "),this.visitNode(i.groupBy);if(i.having)this.append(" "),this.visitNode(i.having);if(i.setOperations)this.append(" "),this.compileList(i.setOperations," ");if(i.orderBy)this.append(" "),this.visitNode(i.orderBy);if(i.limit)this.append(" "),this.visitNode(i.limit);if(i.offset)this.append(" "),this.visitNode(i.offset);if(i.fetch)this.append(" "),this.visitNode(i.fetch);if(i.endModifiers?.length)this.append(" "),this.compileList(this.sortSelectModifiers([...i.endModifiers])," ");if(t)this.append(")")}visitFrom(i){this.append("from "),this.compileList(i.froms)}visitSelection(i){this.visitNode(i.selection)}visitColumn(i){this.visitNode(i.column)}compileDistinctOn(i){this.append("distinct on ("),this.compileList(i),this.append(")")}compileList(i,t=", "){let e=i.length-1;for(let s=0;s<=e;s++)if(this.visitNode(i[s]),s<e)this.append(t)}visitWhere(i){this.append("where "),this.visitNode(i.where)}visitHaving(i){this.append("having "),this.visitNode(i.having)}visitInsertQuery(i){let t=this.parentNode!==void 0&&!Ro.is(this.parentNode)&&!Bt.is(this.parentNode)&&!qo.is(this.parentNode);if(this.parentNode===void 0&&i.explain)this.visitNode(i.explain),this.append(" ");if(t)this.append("(");if(i.with)this.visitNode(i.with),this.append(" ");if(this.append(i.replace?"replace":"insert"),i.ignore)os("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."),this.append(" ignore");if(i.orAction)this.append(" "),this.visitNode(i.orAction);if(i.top)this.append(" "),this.visitNode(i.top);if(i.into)this.append(" into "),this.visitNode(i.into);if(i.columns)this.append(" ("),this.compileList(i.columns),this.append(")");if(i.output)this.append(" "),this.visitNode(i.output);if(i.values)this.append(" "),this.visitNode(i.values);if(i.defaultValues)this.append(" "),this.append("default values");if(i.onConflict)this.append(" "),this.visitNode(i.onConflict);if(i.onDuplicateKey)this.append(" "),this.visitNode(i.onDuplicateKey);if(i.returning)this.append(" "),this.visitNode(i.returning);if(t)this.append(")");if(i.endModifiers?.length)this.append(" "),this.compileList(i.endModifiers," ")}visitValues(i){this.append("values "),this.compileList(i.values)}visitDeleteQuery(i){let t=this.parentNode!==void 0&&!Ro.is(this.parentNode)&&!Bt.is(this.parentNode);if(this.parentNode===void 0&&i.explain)this.visitNode(i.explain),this.append(" ");if(t)this.append("(");if(i.with)this.visitNode(i.with),this.append(" ");if(this.append("delete "),i.top)this.visitNode(i.top),this.append(" ");if(this.visitNode(i.from),i.output)this.append(" "),this.visitNode(i.output);if(i.using)this.append(" "),this.visitNode(i.using);if(i.joins)this.append(" "),this.compileList(i.joins," ");if(i.where)this.append(" "),this.visitNode(i.where);if(i.orderBy)this.append(" "),this.visitNode(i.orderBy);if(i.limit)this.append(" "),this.visitNode(i.limit);if(i.returning)this.append(" "),this.visitNode(i.returning);if(t)this.append(")");if(i.endModifiers?.length)this.append(" "),this.compileList(i.endModifiers," ")}visitReturning(i){this.append("returning "),this.compileList(i.selections)}visitAlias(i){this.visitNode(i.node),this.append(" as "),this.visitNode(i.alias)}visitReference(i){if(i.table)this.visitNode(i.table),this.append(".");this.visitNode(i.column)}visitSelectAll(i){this.append("*")}visitIdentifier(i){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(i),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(i){if(!Vt(i.name))throw Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier(i.name))}visitAnd(i){this.visitNode(i.left),this.append(" and "),this.visitNode(i.right)}visitOr(i){this.visitNode(i.left),this.append(" or "),this.visitNode(i.right)}visitValue(i){if(i.immediate)this.appendImmediateValue(i.value);else this.appendValue(i.value)}visitValueList(i){this.append("("),this.compileList(i.values),this.append(")")}visitTuple(i){this.append("("),this.compileList(i.values),this.append(")")}visitPrimitiveValueList(i){this.append("(");let{values:t}=i;for(let e=0;e<t.length;++e)if(this.appendValue(t[e]),e!==t.length-1)this.append(", ");this.append(")")}visitParens(i){this.append("("),this.visitNode(i.node),this.append(")")}visitJoin(i){if(this.append(g[i.joinType]),this.append(" "),this.visitNode(i.table),i.on)this.append(" "),this.visitNode(i.on)}visitOn(i){this.append("on "),this.visitNode(i.on)}visitRaw(i){let{sqlFragments:t,parameters:e}=i;for(let s=0;s<t.length;++s)if(this.append(t[s]),e.length>s)this.visitNode(e[s])}visitOperator(i){this.append(i.operator)}visitTable(i){this.visitNode(i.table)}visitSchemableIdentifier(i){if(i.schema)this.visitNode(i.schema),this.append(".");this.visitNode(i.identifier)}visitCreateTable(i){if(this.append("create "),i.frontModifiers?.length)this.compileList(i.frontModifiers," "),this.append(" ");if(i.temporary)this.append("temporary ");if(this.append("table "),i.ifNotExists)this.append("if not exists ");if(this.visitNode(i.table),!i.selectQuery)this.append(" ("),this.compileList([...i.columns,...i.constraints??[]]),this.append(")");if(i.onCommit)this.append(" on commit "),this.append(i.onCommit);if(i.endModifiers?.length)this.append(" "),this.compileList(i.endModifiers," ");if(i.selectQuery)this.append(" as "),this.visitNode(i.selectQuery)}visitColumnDefinition(i){if(i.ifNotExists)this.append("if not exists ");if(this.visitNode(i.column),this.append(" "),this.visitNode(i.dataType),i.unsigned)this.append(" unsigned");if(i.frontModifiers&&i.frontModifiers.length>0)this.append(" "),this.compileList(i.frontModifiers," ");if(i.generated)this.append(" "),this.visitNode(i.generated);if(i.identity)this.append(" identity");if(i.defaultTo)this.append(" "),this.visitNode(i.defaultTo);if(i.notNull)this.append(" not null");if(i.unique)this.append(" unique");if(i.nullsNotDistinct)this.append(" nulls not distinct");if(i.primaryKey)this.append(" primary key");if(i.autoIncrement)this.append(" "),this.append(this.getAutoIncrement());if(i.references)this.append(" "),this.visitNode(i.references);if(i.check)this.append(" "),this.visitNode(i.check);if(i.endModifiers&&i.endModifiers.length>0)this.append(" "),this.compileList(i.endModifiers," ")}getAutoIncrement(){return"auto_increment"}visitReferences(i){if(this.append("references "),this.visitNode(i.table),this.append(" ("),this.compileList(i.columns),this.append(")"),i.onDelete)this.append(" on delete "),this.append(i.onDelete);if(i.onUpdate)this.append(" on update "),this.append(i.onUpdate)}visitDropTable(i){if(this.append("drop table "),i.ifExists)this.append("if exists ");if(this.visitNode(i.table),i.cascade)this.append(" cascade")}visitDataType(i){this.append(i.dataType)}visitOrderBy(i){this.append("order by "),this.compileList(i.items)}visitOrderByItem(i){if(this.visitNode(i.orderBy),i.collation)this.append(" "),this.visitNode(i.collation);if(i.direction)this.append(" "),this.visitNode(i.direction);if(i.nulls)this.append(" nulls "),this.append(i.nulls)}visitGroupBy(i){this.append("group by "),this.compileList(i.items)}visitGroupByItem(i){this.visitNode(i.groupBy)}visitUpdateQuery(i){let t=this.parentNode!==void 0&&!Ro.is(this.parentNode)&&!Bt.is(this.parentNode)&&!qo.is(this.parentNode);if(this.parentNode===void 0&&i.explain)this.visitNode(i.explain),this.append(" ");if(t)this.append("(");if(i.with)this.visitNode(i.with),this.append(" ");if(this.append("update "),i.top)this.visitNode(i.top),this.append(" ");if(i.table)this.visitNode(i.table),this.append(" ");if(this.append("set "),i.updates)this.compileList(i.updates);if(i.output)this.append(" "),this.visitNode(i.output);if(i.from)this.append(" "),this.visitNode(i.from);if(i.joins){if(!i.from)throw Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList(i.joins," ")}if(i.where)this.append(" "),this.visitNode(i.where);if(i.returning)this.append(" "),this.visitNode(i.returning);if(i.orderBy)this.append(" "),this.visitNode(i.orderBy);if(i.limit)this.append(" "),this.visitNode(i.limit);if(t)this.append(")");if(i.endModifiers?.length)this.append(" "),this.compileList(i.endModifiers," ")}visitColumnUpdate(i){this.visitNode(i.column),this.append(" = "),this.visitNode(i.value)}visitLimit(i){this.append("limit "),this.visitNode(i.limit)}visitOffset(i){this.append("offset "),this.visitNode(i.offset)}visitOnConflict(i){if(this.append("on conflict"),i.columns)this.append(" ("),this.compileList(i.columns),this.append(")");else if(i.constraint)this.append(" on constraint "),this.visitNode(i.constraint);else if(i.indexExpression)this.append(" ("),this.visitNode(i.indexExpression),this.append(")");if(i.indexWhere)this.append(" "),this.visitNode(i.indexWhere);if(i.doNothing===!0)this.append(" do nothing");else if(i.updates){if(this.append(" do update set "),this.compileList(i.updates),i.updateWhere)this.append(" "),this.visitNode(i.updateWhere)}}visitOnDuplicateKey(i){this.append("on duplicate key update "),this.compileList(i.updates)}visitCreateIndex(i){if(this.append("create "),i.unique)this.append("unique ");if(this.append("index "),i.ifNotExists)this.append("if not exists ");if(this.visitNode(i.name),i.table)this.append(" on "),this.visitNode(i.table);if(i.using)this.append(" using "),this.visitNode(i.using);if(i.columns)this.append(" ("),this.compileList(i.columns),this.append(")");if(i.nullsNotDistinct)this.append(" nulls not distinct");if(i.where)this.append(" "),this.visitNode(i.where)}visitDropIndex(i){if(this.append("drop index "),i.ifExists)this.append("if exists ");if(this.visitNode(i.name),i.table)this.append(" on "),this.visitNode(i.table);if(i.cascade)this.append(" cascade")}visitCreateSchema(i){if(this.append("create schema "),i.ifNotExists)this.append("if not exists ");this.visitNode(i.schema)}visitDropSchema(i){if(this.append("drop schema "),i.ifExists)this.append("if exists ");if(this.visitNode(i.schema),i.cascade)this.append(" cascade")}visitPrimaryKeyConstraint(i){if(i.name)this.append("constraint "),this.visitNode(i.name),this.append(" ");this.append("primary key ("),this.compileList(i.columns),this.append(")"),this.buildDeferrable(i)}buildDeferrable(i){if(i.deferrable!==void 0)if(i.deferrable)this.append(" deferrable");else this.append(" not deferrable");if(i.initiallyDeferred!==void 0)if(i.initiallyDeferred)this.append(" initially deferred");else this.append(" initially immediate")}visitUniqueConstraint(i){if(i.name)this.append("constraint "),this.visitNode(i.name),this.append(" ");if(this.append("unique"),i.nullsNotDistinct)this.append(" nulls not distinct");this.append(" ("),this.compileList(i.columns),this.append(")"),this.buildDeferrable(i)}visitCheckConstraint(i){if(i.name)this.append("constraint "),this.visitNode(i.name),this.append(" ");this.append("check ("),this.visitNode(i.expression),this.append(")")}visitForeignKeyConstraint(i){if(i.name)this.append("constraint "),this.visitNode(i.name),this.append(" ");if(this.append("foreign key ("),this.compileList(i.columns),this.append(") "),this.visitNode(i.references),i.onDelete)this.append(" on delete "),this.append(i.onDelete);if(i.onUpdate)this.append(" on update "),this.append(i.onUpdate);this.buildDeferrable(i)}visitList(i){this.compileList(i.items)}visitWith(i){if(this.append("with "),i.recursive)this.append("recursive ");this.compileList(i.expressions)}visitCommonTableExpression(i){if(this.visitNode(i.name),this.append(" as "),vs(i.materialized)){if(!i.materialized)this.append("not ");this.append("materialized ")}this.visitNode(i.expression)}visitCommonTableExpressionName(i){if(this.visitNode(i.table),i.columns)this.append("("),this.compileList(i.columns),this.append(")")}visitAlterTable(i){if(this.append("alter table "),this.visitNode(i.table),this.append(" "),i.renameTo)this.append("rename to "),this.visitNode(i.renameTo);if(i.setSchema)this.append("set schema "),this.visitNode(i.setSchema);if(i.addConstraint)this.visitNode(i.addConstraint);if(i.dropConstraint)this.visitNode(i.dropConstraint);if(i.renameConstraint)this.visitNode(i.renameConstraint);if(i.columnAlterations)this.compileColumnAlterations(i.columnAlterations);if(i.addIndex)this.visitNode(i.addIndex);if(i.dropIndex)this.visitNode(i.dropIndex)}visitAddColumn(i){this.append("add column "),this.visitNode(i.column)}visitRenameColumn(i){this.append("rename column "),this.visitNode(i.column),this.append(" to "),this.visitNode(i.renameTo)}visitDropColumn(i){this.append("drop column "),this.visitNode(i.column)}visitAlterColumn(i){if(this.append("alter column "),this.visitNode(i.column),this.append(" "),i.dataType){if(this.announcesNewColumnDataType())this.append("type ");if(this.visitNode(i.dataType),i.dataTypeExpression)this.append("using "),this.visitNode(i.dataTypeExpression)}if(i.setDefault)this.append("set default "),this.visitNode(i.setDefault);if(i.dropDefault)this.append("drop default");if(i.setNotNull)this.append("set not null");if(i.dropNotNull)this.append("drop not null")}visitModifyColumn(i){this.append("modify column "),this.visitNode(i.column)}visitAddConstraint(i){this.append("add "),this.visitNode(i.constraint)}visitDropConstraint(i){if(this.append("drop constraint "),i.ifExists)this.append("if exists ");if(this.visitNode(i.constraintName),i.modifier==="cascade")this.append(" cascade");else if(i.modifier==="restrict")this.append(" restrict")}visitRenameConstraint(i){this.append("rename constraint "),this.visitNode(i.oldName),this.append(" to "),this.visitNode(i.newName)}visitSetOperation(i){if(this.append(i.operator),this.append(" "),i.all)this.append("all ");this.visitNode(i.expression)}visitCreateView(i){if(this.append("create "),i.orReplace)this.append("or replace ");if(i.materialized)this.append("materialized ");if(i.temporary)this.append("temporary ");if(this.append("view "),i.ifNotExists)this.append("if not exists ");if(this.visitNode(i.name),this.append(" "),i.columns)this.append("("),this.compileList(i.columns),this.append(") ");if(i.as)this.append("as "),this.visitNode(i.as)}visitRefreshMaterializedView(i){if(this.append("refresh materialized view "),i.concurrently)this.append("concurrently ");if(this.visitNode(i.name),i.withNoData)this.append(" with no data");else this.append(" with data")}visitDropView(i){if(this.append("drop "),i.materialized)this.append("materialized ");if(this.append("view "),i.ifExists)this.append("if exists ");if(this.visitNode(i.name),i.cascade)this.append(" cascade")}visitGenerated(i){if(this.append("generated "),i.always)this.append("always ");if(i.byDefault)this.append("by default ");if(this.append("as "),i.identity)this.append("identity");if(i.expression)this.append("("),this.visitNode(i.expression),this.append(")");if(i.stored)this.append(" stored")}visitDefaultValue(i){this.append("default "),this.visitNode(i.defaultValue)}visitSelectModifier(i){if(i.rawModifier)this.visitNode(i.rawModifier);else this.append(v[i.modifier]);if(i.of)this.append(" of "),this.compileList(i.of,", ")}visitCreateType(i){if(this.append("create type "),this.visitNode(i.name),i.enum)this.append(" as enum "),this.visitNode(i.enum)}visitDropType(i){if(this.append("drop type "),i.ifExists)this.append("if exists ");this.visitNode(i.name)}visitExplain(i){if(this.append("explain"),i.options||i.format){if(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),i.options){if(this.visitNode(i.options),i.format)this.append(this.getExplainOptionsDelimiter())}if(i.format)this.append("format"),this.append(this.getExplainOptionAssignment()),this.append(i.format);this.append(this.getRightExplainOptionsWrapper())}}visitDefaultInsertValue(i){this.append("default")}visitAggregateFunction(i){if(this.append(i.func),this.append("("),i.distinct)this.append("distinct ");if(this.compileList(i.aggregated),i.orderBy)this.append(" "),this.visitNode(i.orderBy);if(this.append(")"),i.withinGroup)this.append(" within group ("),this.visitNode(i.withinGroup),this.append(")");if(i.filter)this.append(" filter("),this.visitNode(i.filter),this.append(")");if(i.over)this.append(" "),this.visitNode(i.over)}visitOver(i){if(this.append("over("),i.partitionBy){if(this.visitNode(i.partitionBy),i.orderBy)this.append(" ")}if(i.orderBy)this.visitNode(i.orderBy);this.append(")")}visitPartitionBy(i){this.append("partition by "),this.compileList(i.items)}visitPartitionByItem(i){this.visitNode(i.partitionBy)}visitBinaryOperation(i){this.visitNode(i.leftOperand),this.append(" "),this.visitNode(i.operator),this.append(" "),this.visitNode(i.rightOperand)}visitUnaryOperation(i){if(this.visitNode(i.operator),!this.isMinusOperator(i.operator))this.append(" ");this.visitNode(i.operand)}isMinusOperator(i){return Mo.is(i)&&i.operator==="-"}visitUsing(i){this.append("using "),this.compileList(i.tables)}visitFunction(i){this.append(i.func),this.append("("),this.compileList(i.arguments),this.append(")")}visitCase(i){if(this.append("case"),i.value)this.append(" "),this.visitNode(i.value);if(i.when)this.append(" "),this.compileList(i.when," ");if(i.else)this.append(" else "),this.visitNode(i.else);if(this.append(" end"),i.isStatement)this.append(" case")}visitWhen(i){if(this.append("when "),this.visitNode(i.condition),i.result)this.append(" then "),this.visitNode(i.result)}visitJSONReference(i){this.visitNode(i.reference),this.visitNode(i.traversal)}visitJSONPath(i){if(i.inOperator)this.visitNode(i.inOperator);this.append("'$");for(let t of i.pathLegs)this.visitNode(t);this.append("'")}visitJSONPathLeg(i){let t=i.type==="ArrayLocation",e=String(i.value);if(t)this.append("["),this.append(this.sanitizeStringLiteral(e)),this.append("]");else this.append('."'),this.append(this.sanitizeJSONPathMemberValue(e)),this.append('"')}visitJSONOperatorChain(i){for(let t=0,e=i.values.length;t<e;t++){if(t===e-1)this.visitNode(i.operator);else this.append("->");this.visitNode(i.values[t])}}visitMergeQuery(i){if(i.with)this.visitNode(i.with),this.append(" ");if(this.append("merge "),i.top)this.visitNode(i.top),this.append(" ");if(this.append("into "),this.visitNode(i.into),i.using)this.append(" "),this.visitNode(i.using);if(i.whens)this.append(" "),this.compileList(i.whens," ");if(i.returning)this.append(" "),this.visitNode(i.returning);if(i.output)this.append(" "),this.visitNode(i.output);if(i.endModifiers?.length)this.append(" "),this.compileList(i.endModifiers," ")}visitMatched(i){if(i.not)this.append("not ");if(this.append("matched"),i.bySource)this.append(" by source")}visitAddIndex(i){if(this.append("add "),i.unique)this.append("unique ");if(this.append("index "),this.visitNode(i.name),i.columns)this.append(" ("),this.compileList(i.columns),this.append(")");if(i.using)this.append(" using "),this.visitNode(i.using)}visitCast(i){this.append("cast("),this.visitNode(i.expression),this.append(" as "),this.visitNode(i.dataType),this.append(")")}visitFetch(i){this.append("fetch next "),this.visitNode(i.rowCount),this.append(` rows ${i.modifier}`)}visitOutput(i){this.append("output "),this.compileList(i.selections)}visitTop(i){if(this.append(`top(${i.expression})`),i.modifiers)this.append(` ${i.modifiers}`)}visitOrAction(i){this.append(i.action)}visitCollate(i){this.append("collate "),this.visitNode(i.collation)}append(i){this.#i+=i}appendValue(i){this.addParameter(i),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier(i){let t=this.getLeftIdentifierWrapper(),e=this.getRightIdentifierWrapper(),s="";for(let n of i)if(s+=n,n===t)s+=t;else if(n===e)s+=e;return s}sanitizeStringLiteral(i){return i.replace(m,"''")}sanitizeJSONPathMemberValue(i){return i.replace(N,(t)=>t==="'"?"''":"\\\"")}addParameter(i){this.#t.push(i)}appendImmediateValue(i){if(Vt(i))this.appendStringLiteral(i);else if(jo(i)||vs(i)||ea(i))this.append(i.toString());else if(Xs(i))this.append("null");else if(Su(i))this.appendImmediateValue(i.toISOString());else throw Error(`invalid immediate value ${i}`)}appendStringLiteral(i){this.append("'"),this.append(this.sanitizeStringLiteral(i)),this.append("'")}sortSelectModifiers(i){return i.sort((t,e)=>t.modifier&&e.modifier?o[t.modifier]-o[e.modifier]:1),f(i)}compileColumnAlterations(i){this.compileList(i)}announcesNewColumnDataType(){return!0}}var v=f({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),o=f({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),g=f({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"});var Yr="kysely_migration",An="kysely_migration_lock";var ai=f({__noMigrations__:!0});
3
+ export{Pn,Vt,jo,vs,Xs,Su,ea,nm,Kt,Er,f,pc,Nn,Gn,ze,om,On,gn,sm,Mo,lf,Bt,os,Ro,Ir,qo,Cu,ss,Dn,Yr,An};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ var k=Object.create;var{getPrototypeOf:l,defineProperty:f,getOwnPropertyNames:m}=Object;var j=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,z=(a,b,c)=>{var d=a!=null&&typeof a==="object";if(d){var h=b?o??=new WeakMap:p??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?k(l(a)):{};let e=b||!a||!a.__esModule||!j.call(a,"default")?f(c,"default",{value:a,enumerable:!0}):c;if(a&&typeof a==="object"||typeof a==="function"){for(let g of m(a))if(!j.call(e,g))f(e,g,{get:n.bind(a,g),enumerable:!0})}if(d)h.set(a,e);return e};var v=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var q=(a)=>a;function r(a,b){this[a]=q.bind(null,b)}var Oe=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:r.bind(b,c)})};var lm=(a,b,c)=>()=>{if(a)try{b=a(a=0)}catch(d){c=[d]}if(c)throw c[0];return b};var cm=(a)=>JSON.parse(a);var um=(a,b,c)=>{for(var d in b)f(a,d,{get:b[d],set:c[d],enumerable:!0,configurable:!0})},G=import.meta.require;
3
+ export{z,v,Oe,lm,cm,um,G};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{uf}from"./chunk-vap4k11j.js";import{v}from"./chunk-fnmwksnb.js";var yi=v(function(d){var{SignatureV4:l,signatureV4aContainer:o}=uf(),r={CrtSignerV4:null},g="X-Amz-S3session-Token".toLowerCase();class a extends l{async signWithCredentials(e,i,n){let s=c(i);e.headers[g]=i.sessionToken;let t=this;return u(t,s),t.signRequest(e,n??{})}async presignWithCredentials(e,i,n){let s=c(i);return delete e.headers[g],e.headers["X-Amz-S3session-Token"]=i.sessionToken,e.query=e.query??{},e.query["X-Amz-S3session-Token"]=i.sessionToken,u(this,s),this.presign(e,n)}}function c(e){return{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,expiration:e.expiration}}function u(e,i){let n=e.credentialProvider;e.credentialProvider=()=>(e.credentialProvider=n,Promise.resolve(i))}class h{sigv4aSigner;sigv4Signer;signerOptions;static sigv4aDependency(){if(typeof r.CrtSignerV4==="function")return"crt";else if(typeof o.SignatureV4a==="function")return"js";return"none"}constructor(e){this.sigv4Signer=new a(e),this.signerOptions=e}async sign(e,i={}){if(i.signingRegion==="*")return this.getSigv4aSigner().sign(e,i);return this.sigv4Signer.sign(e,i)}async signWithCredentials(e,i,n={}){if(n.signingRegion==="*"){let s=this.getSigv4aSigner(),t=r.CrtSignerV4;if(t&&s instanceof t)return s.signWithCredentials(e,i,n);else throw Error(`signWithCredentials with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`)}return this.sigv4Signer.signWithCredentials(e,i,n)}async presign(e,i={}){if(i.signingRegion==="*"){let n=this.getSigv4aSigner(),s=r.CrtSignerV4;if(s&&n instanceof s)return n.presign(e,i);else throw Error(`presign with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`)}return this.sigv4Signer.presign(e,i)}async presignWithCredentials(e,i,n={}){if(n.signingRegion==="*")throw Error("Method presignWithCredentials is not supported for [signingRegion=*].");return this.sigv4Signer.presignWithCredentials(e,i,n)}getSigv4aSigner(){if(!this.sigv4aSigner){let e=r.CrtSignerV4,i=o.SignatureV4a;if(this.signerOptions.runtime==="node"){if(!e&&!i)throw Error("Neither CRT nor JS SigV4a implementation is available. Please load either @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt");if(e&&typeof e==="function")this.sigv4aSigner=new e({...this.signerOptions,signingAlgorithm:1});else if(i&&typeof i==="function")this.sigv4aSigner=new i({...this.signerOptions});else throw Error("Available SigV4a implementation is not a valid constructor. Please ensure you've properly imported @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a.For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt")}else{if(!i||typeof i!=="function")throw Error("JS SigV4a implementation is not available or not a valid constructor. Please check whether you have installed the @aws-sdk/signature-v4a package explicitly. The CRT implementation is not available for browsers. You must also register the package by calling [require('@aws-sdk/signature-v4a');] or an ESM equivalent such as [import '@aws-sdk/signature-v4a';]. For more information please go to https://github.com/aws/aws-sdk-js-v3#using-javascript-non-crt-implementation-of-sigv4a");this.sigv4aSigner=new i({...this.signerOptions})}}return this.sigv4aSigner}}d.SignatureV4MultiRegion=h;d.SignatureV4SignWithCredentials=a;d.signatureV4CrtContainer=r});
3
+ export{yi};
@@ -0,0 +1 @@
1
+ import{N,h,O,w,u,C,B,t,o,K,Z,U,ut,Fe,A,T,L,Me,Gr,pt,Yn,Jn,Po,fe,ve,De,S,ge,Ae,ye,W,Qr,Gt,df,pm,pf,yy,_y,Ey,mf,ke,m0,Wa,R0,N0,Qm,at,xf,B_,W_,oh,nb,ab,ib,lb,cb,ub,Ii,ca,Dc,Mf,Ti,Db,qb,aw,pw,hw,Rw,Pw,Nw,pd,Dv,bx,vx,Mx,kx,Jf,Hh,Xf,fS,pS,vl,_C,MC,Oo,NC,jC,$C,Ig,Rg,Bc,xl,bp,wp,vp,Sl,Uc,Fc,xp,Sp,zc,oI,sI,aI,iI,lI,cn,Np,ZI,BI,Op,Gg,$I,GI,QI,VI,KI,pe,ue,me,$e,de,H,ie,it,kr,un,jn,qc,R,Ar,en,V,qe,Le,Ze,Be,Ue,ne,ma,Qt,Lo,_t,$p}from"./chunk-7rhz2gze.js";import{Bi,Bs}from"./chunk-7kjgvxqa.js";import{Wc,Aa}from"./chunk-tm7f32c7.js";import"./chunk-gc5sbfa5.js";import"./chunk-rssgmj7x.js";import{Sr}from"./chunk-0qaq0sp8.js";import{oi,Dl}from"./chunk-7pw1550a.js";import{ri}from"./chunk-3ttrhqy3.js";import{kl}from"./chunk-kswvyqq1.js";import{Pl}from"./chunk-453ykvaw.js";import{er}from"./chunk-5vzrpz50.js";import"./chunk-98715kc3.js";import"./chunk-m9pr03kn.js";import{zl}from"./chunk-yfnem6se.js";import"./chunk-cbgq517y.js";import"./chunk-gk2q9a3f.js";import{so}from"./chunk-9t8n2des.js";import"./chunk-ytdwk2fq.js";import{ao}from"./chunk-rq0n0vcc.js";import{Rr}from"./chunk-0zv3bks2.js";C();var Ct=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],lt=T("folder-open",Ct);var It=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],dt=T("list-filter",It);var Ft=[["path",{d:"M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z",key:"e79jfc"}],["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}]],ct=T("palette",Ft);C();function Dt({ratio:a}){switch(a){case"16:9":return t("span",{className:"inline-block w-4 h-2.5 border border-current rounded-[1px] shrink-0"});case"9:16":return t("span",{className:"inline-block w-2.5 h-4 border border-current rounded-[1px] shrink-0"});case"4:3":return t("span",{className:"inline-block w-3.5 h-2.5 border border-current rounded-[1px] shrink-0"});case"3:4":return t("span",{className:"inline-block w-2.5 h-3.5 border border-current rounded-[1px] shrink-0"});case"1:1":return t("span",{className:"inline-block w-3 h-3 border border-current rounded-[1px] shrink-0"});default:return t("span",{className:"inline-block w-4 h-2.5 border border-current rounded-[1px] shrink-0"})}}function rt(){return Math.random().toString(36).substring(2,9)}function mt(){return{id:rt(),type:"text",text:"CONFIDENTIAL",x:0.5,y:0.5,size:0.05,color:"#999999",opacity:0.5,rotation:-30}}function Mt(){return{id:rt(),type:"image",imageAssetKey:"",x:0.5,y:0.5,size:0.15,opacity:0.5,rotation:0}}var tt=[{id:"dark",label:"Dark Slate",bg:"#1e293b",dot:"#475569"},{id:"black",label:"Black",bg:"#000000",dot:"#404040"},{id:"gray",label:"Slate Gray",bg:"#64748b",dot:"#cbd5e1"},{id:"white",label:"White",bg:"#ffffff",dot:"#94a3b8"},{id:"green",label:"Chroma Green",bg:"#059669",dot:"#047857"}],Bt={"16:9":1.7777777777777777,"9:16":0.5625,"4:3":1.3333333333333333,"3:4":0.75,"1:1":1};function gt({open:a,onOpenChange:b,initialConfig:g,shareId:p,teamId:k,onSaveSuccess:x}){let P=K(),[d,v]=u([]),[c,f]=u(null),[j,z]=u(null),[_,he]=u("16:9"),[Ne,Se]=u("grid"),[Ce,X]=u(!1),[we,oe]=u("new"),[ce,Y]=u(""),[J,ee]=u(null),I=w(null),te=w(null),[ae,Ie]=u({w:0,h:0}),[F,q]=u(!1),s=N((e)=>{if(te.current=e,!e)return;let l=()=>{let{clientWidth:M,clientHeight:y}=e;if(M<=0||y<=0)return;let E=Bt[_],et=M,We=et/E;if(We>y)We=y,et=We*E;Ie({w:Math.round(et),h:Math.round(We)})};l();let n=new ResizeObserver(l);return n.observe(e),()=>{n.disconnect(),te.current=null}},[_]),G=it((e)=>e.teamId),_e=k||G,[Oe,Te]=u(!1),[re,je]=u({}),le=w(null),Pe=A.api.teams[":teamId"].files.$post,xe=async(e,l)=>{let n=e.target.files?.[0];if(!n)return;if(n.size>1048576){if(R.error(Db()),le.current)le.current.value="";return}if(!_e){R.error(Dc());return}Te(!0);let M=URL.createObjectURL(n);je((y)=>({...y,[l]:M}));try{let y=await Pe({param:{teamId:_e},form:{file:n}});if(!y.ok)throw Error(Dc());let E=await y.json();D(l,{imageAssetKey:E.key,imageAssetUrl:E.url})}catch(y){let E=y instanceof Error?y.message:Dc();R.error(E)}finally{if(Te(!1),le.current)le.current.value=""}};h(()=>{if(a){if(g?.blocks&&g.blocks.length>0)v(g.blocks),f(g.blocks[0].id);else{let e=mt();v([e]),f(e.id)}z(null)}},[a,g]);let{data:se=[]}=Z({queryKey:["watermark-templates",k],queryFn:async()=>{let e=await A.api["watermark-templates"].$get({query:k?{teamId:k}:{}});if(!e.ok)return[];return await e.json()},enabled:a}),Ke=A.api.shares[":shareId"].watermark.$put,{mutate:Qe,isPending:Ve}=U({mutationFn:async(e)=>{let l=await Ke({param:{shareId:p},json:{enabled:!0,config:e}});if(!l.ok){let n=await l.json().catch(()=>null);throw Error(n?.error||ca())}return await l.json()},onSuccess:()=>{P.invalidateQueries({queryKey:["share",p]}),P.invalidateQueries({queryKey:["shares"]}),R.success(KI()),b(!1),x?.()},onError:(e)=>{R.error(e.message||ca())}}),He=A.api["watermark-templates"].$post,{mutate:Ge,isPending:Ee}=U({mutationFn:async({name:e,config:l})=>{let n=await He({json:{name:e,teamId:k||void 0,config:l}});if(!n.ok)throw Error(ca());return await n.json()},onSuccess:(e)=>{P.invalidateQueries({queryKey:["watermark-templates"]}),z(e.id),X(!1),R.success(aI())},onError:()=>{R.error(ca())}}),Xe=A.api["watermark-templates"][":templateId"].$put,{mutate:r,isPending:m}=U({mutationFn:async({templateId:e,config:l})=>{let n=await Xe({param:{templateId:e},json:{config:l}});if(!n.ok)throw Error(ca());return await n.json()},onSuccess:()=>{P.invalidateQueries({queryKey:["watermark-templates"]}),X(!1),R.success(iI())},onError:()=>{R.error(ca())}}),Q=A.api["watermark-templates"][":templateId"].$delete,{mutate:ht}=U({mutationFn:async(e)=>{if(!(await Q({param:{templateId:e}})).ok)throw Error(Ii())},onSuccess:(e,l)=>{if(P.invalidateQueries({queryKey:["watermark-templates"]}),j===l)z(null);R.success(oI())},onError:()=>{R.error(Ii())}}),be=d.findIndex((e)=>e.id===c),i=be>=0?d[be]:null,ot=()=>{let e=mt();v((l)=>[...l,e]),f(e.id)},vt=()=>{let e=Mt();v((l)=>[...l,e]),f(e.id)},nt=(e)=>{if(!e)return;v((l)=>{let n=l.filter((M)=>M.id!==e);if(c===e)f(n.length>0?n[Math.max(0,be-1)].id:null);return n})},D=(e,l)=>{v((n)=>n.map((M)=>M.id===e?{...M,...l}:M))},wt=()=>{if(d.length===0)return;let e=(be-1+d.length)%d.length;f(d[e].id)},yt=()=>{if(d.length===0)return;let e=(be+1)%d.length;f(d[e].id)},bt=(e,l)=>{e.stopPropagation(),f(l),q(!0)},Ye=N((e)=>{if(!F||!c||!I.current)return;let l=I.current.getBoundingClientRect(),n=(e.clientX-l.left)/l.width,M=(e.clientY-l.top)/l.height,y=Math.max(0,Math.min(1,Math.round(n*100)/100)),E=Math.max(0,Math.min(1,Math.round(M*100)/100));D(c,{x:y,y:E})},[F,c]),Je=N(()=>{q(!1)},[]);h(()=>{if(F)window.addEventListener("mousemove",Ye),window.addEventListener("mouseup",Je);return()=>{window.removeEventListener("mousemove",Ye),window.removeEventListener("mouseup",Je)}},[F,Ye,Je]),h(()=>{let e=(l)=>{if(!a||!c)return;let n=l.target?.tagName?.toLowerCase();if(n==="input"||n==="textarea"||n==="select")return;if(l.key==="Delete"||l.key==="Backspace")l.preventDefault(),nt(c)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[a,c,be]);let Nt=(e)=>{if(e.config?.blocks&&e.config.blocks.length>0){let l=e.config.blocks.map((n)=>({...n,id:rt()}));v(l),f(l[0].id),z(e.id)}},kt=()=>{if(d.length===0){R.error(vx());return}Qe({blocks:d})},St=()=>{if(we==="new"){if(!ce.trim()){R.error(oh());return}Ge({name:ce.trim(),config:{blocks:d}})}else{let e=J||j;if(!e){R.error(Ig());return}r({templateId:e,config:{blocks:d}})}};return o(B,{children:[t(pe,{open:a,onOpenChange:b,children:o(ue,{showCloseButton:!1,className:"sm:max-w-[1400px] max-w-[95vw] w-[95vw] h-[88vh] flex flex-col p-0 gap-0 overflow-hidden",onPointerDownOutside:(e)=>e.preventDefault(),children:[o("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border bg-card",children:[t("div",{className:"flex items-center gap-3",children:t(de,{className:"text-base font-semibold",children:GI()})}),o("div",{className:"flex items-center gap-2",children:[o(ge,{modal:!1,children:[t(Ae,{asChild:!0,children:o(S,{variant:"outline",size:"sm",className:"gap-2 text-xs",children:[t(lt,{className:"h-4 w-4 text-muted-foreground"}),QI()]})}),o(ye,{align:"end",className:"w-56",children:[t(Qr,{className:"text-xs font-semibold text-muted-foreground",children:Nw()}),se.length===0?t("div",{className:"px-2 py-1.5 text-xs text-muted-foreground italic",children:bx()}):se.map((e)=>o(W,{onClick:()=>Nt(e),className:"flex items-center justify-between text-xs cursor-pointer",children:[t("span",{className:"truncate flex-1",children:e.name}),j===e.id&&t(Me,{className:"h-3.5 w-3.5 text-primary ml-2 flex-shrink-0"}),t(S,{variant:"ghost",size:"icon",className:"h-5 w-5 hover:bg-destructive/10 hover:text-destructive ml-1",onClick:(l)=>{l.stopPropagation(),ht(e.id)},children:t(ve,{className:"h-3 w-3"})})]},e.id)),t(Gt,{}),o(W,{onClick:()=>{oe("new"),Y(""),X(!0)},className:"text-xs gap-2 cursor-pointer",children:[t(fe,{className:"h-3.5 w-3.5 text-primary"}),Qm()]}),se.length>0&&o(W,{onClick:()=>{oe("overwrite"),ee(j||se[0].id),X(!0)},className:"text-xs gap-2 cursor-pointer",children:[t(ri,{className:"h-3.5 w-3.5 text-muted-foreground"}),Hh()]})]})]}),t(S,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>b(!1),children:ke()}),o(S,{size:"sm",className:"text-xs bg-primary hover:bg-primary/90 text-primary-foreground gap-1.5",disabled:Ve,onClick:kt,children:[t(ri,{className:"h-3.5 w-3.5"}),NC()]})]})]}),o("div",{className:"flex-1 flex overflow-hidden",children:[o("div",{className:"w-[65%] flex flex-col p-4 bg-muted/20 border-r border-border overflow-hidden select-none",children:[o("div",{className:"flex items-center justify-between mb-3",children:[t("div",{className:"flex items-center gap-1 bg-muted/60 p-1 rounded-md border border-border/60",children:["16:9","9:16","4:3","3:4","1:1"].map((e)=>o(S,{variant:_===e?"secondary":"ghost",size:"sm",className:ze("h-7 px-2.5 text-xs gap-1.5 font-mono transition-all",_===e?"bg-background shadow-xs font-semibold text-foreground border border-border/50":"text-muted-foreground hover:text-foreground"),onClick:()=>he(e),children:[t(Dt,{ratio:e}),t("span",{children:e})]},e))}),t("div",{className:"flex items-center gap-1.5 bg-background border border-border/60 rounded-md p-1",children:tt.map((e)=>t("button",{type:"button",onClick:()=>Se(e.id),style:{backgroundColor:e.bg},className:ze("w-5 h-5 rounded-full border border-border/80 transition-all cursor-pointer relative",Ne===e.id?"ring-2 ring-primary ring-offset-1 scale-110":"hover:scale-105 opacity-80 hover:opacity-100"),title:e.label},e.id))})]}),t("div",{ref:s,className:"flex-1 flex items-center justify-center overflow-hidden",children:(()=>{let e=tt.find((n)=>n.id===Ne)||tt[0],l=ae.w>0&&ae.h>0;return t("div",{ref:I,onClick:()=>f(null),style:{backgroundColor:e.bg,backgroundImage:`radial-gradient(${e.dot} 1px, transparent 1px)`,backgroundSize:"16px 16px",...l?{width:ae.w,height:ae.h}:{}},className:ze("relative rounded-lg border border-border overflow-hidden shadow-inner transition-all",_==="16:9"&&"aspect-[16/9] w-full max-h-full",_==="9:16"&&"aspect-[9/16] h-full max-w-full",_==="4:3"&&"aspect-[4/3] w-full max-h-full",_==="3:4"&&"aspect-[3/4] h-full max-w-full",_==="1:1"&&"aspect-square h-full max-w-full"),children:d.map((n)=>{let M=n.id===c,y=n.size*(ae.w||640);return t("div",{onMouseDown:(E)=>bt(E,n.id),onClick:(E)=>{E.stopPropagation(),f(n.id)},style:{left:`${n.x*100}%`,top:`${n.y*100}%`,transform:`translate(-50%, -50%) rotate(${n.rotation}deg)`,opacity:n.opacity},className:ze("absolute cursor-move select-none transition-shadow rounded p-1.5 flex items-center justify-center",M?"ring-2 ring-primary ring-offset-2 ring-offset-background/80 bg-primary/10":"hover:ring-1 hover:ring-muted-foreground/50"),children:n.type==="text"?t("span",{style:{fontSize:`${y}px`,color:n.color,lineHeight:1,whiteSpace:"nowrap",fontWeight:700,textShadow:"0 1px 3px rgba(0,0,0,0.5)"},children:n.text||"Text"}):t("div",{style:{width:`${y}px`,height:`${y}px`},className:"bg-primary/20 border border-primary/40 rounded flex items-center justify-center p-1 overflow-hidden",children:re[n.id]||n.imageAssetUrl?t("img",{src:re[n.id]||n.imageAssetUrl,alt:"Watermark logo",className:"w-full h-full object-contain pointer-events-none"}):t(Yn,{className:"h-1/2 w-1/2 opacity-70 text-primary"})})},n.id)})})})()})]}),o("div",{className:"w-[35%] flex flex-col bg-card overflow-hidden border-l border-border",children:[t("div",{className:"p-4 border-b border-border bg-muted/10 flex items-center justify-between",children:o("div",{className:"flex items-center gap-2",children:[t(Jn,{className:"h-4 w-4 text-muted-foreground"}),t("span",{className:"text-xs font-semibold",children:Gg()})]})}),o("div",{className:"p-3 border-b border-border bg-background flex items-center justify-between gap-2",children:[o("div",{className:"flex items-center gap-1",children:[t(S,{variant:"outline",size:"icon",className:"h-7 w-7",disabled:d.length<=1,onClick:wt,children:t(Gr,{className:"h-4 w-4"})}),o(ge,{modal:!1,children:[t(Ae,{asChild:!0,children:t(S,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs font-mono",children:d.length===0?"0 / 0":`${be+1} / ${d.length}`})}),t(ye,{align:"start",className:"w-48",children:d.map((e,l)=>o(W,{onClick:()=>f(e.id),className:"text-xs flex items-center justify-between cursor-pointer",children:[o("span",{className:"flex items-center gap-2 truncate",children:[e.type==="text"?t(Bi,{className:"h-3.5 w-3.5 text-muted-foreground"}):t(Yn,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.type==="text"?e.text||"Text":e.imageAssetKey||"Image"]}),o("span",{className:"text-[10px] font-mono text-muted-foreground ml-2",children:["#",l+1]})]},e.id))})]}),t(S,{variant:"outline",size:"icon",className:"h-7 w-7",disabled:d.length<=1,onClick:yt,children:t(pt,{className:"h-4 w-4"})})]}),o("div",{className:"flex items-center gap-1",children:[i&&t(S,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive hover:bg-destructive/10",title:at(),onClick:()=>nt(i.id),children:t(ve,{className:"h-4 w-4"})}),o(ge,{modal:!1,children:[t(Ae,{asChild:!0,children:o(S,{size:"sm",className:"h-7 text-xs gap-1",children:[t(fe,{className:"h-3.5 w-3.5"}),df()]})}),o(ye,{align:"end",children:[o(W,{onClick:ot,className:"text-xs gap-2 cursor-pointer",children:[t(Bi,{className:"h-3.5 w-3.5"}),pf()]}),o(W,{onClick:vt,className:"text-xs gap-2 cursor-pointer",children:[t(Yn,{className:"h-3.5 w-3.5"}),pm()]})]})]})]})]}),t(ie,{className:"flex-1 min-h-0 p-4",children:i?o("div",{className:"space-y-5 text-xs",children:[o("div",{className:"flex items-center justify-between pb-2 border-b border-border",children:[o("span",{className:"font-semibold text-muted-foreground flex items-center gap-1.5",children:[i.type==="text"?t(Bi,{className:"h-4 w-4 text-primary"}):t(Yn,{className:"h-4 w-4 text-primary"}),i.type==="text"?pf():pm()]}),o("span",{className:"text-[10px] font-mono text-muted-foreground",children:["ID: ",i.id.slice(0,6)]})]}),i.type==="text"&&o("div",{className:"space-y-2",children:[t(V,{className:"text-xs",children:lI()}),t(H,{type:"text",value:i.text,onChange:(e)=>D(i.id,{text:e.target.value}),className:"text-xs h-8"})]}),i.type==="image"&&o("div",{className:"space-y-2",children:[o("div",{className:"flex items-center justify-between",children:[t(V,{className:"text-xs",children:pw()}),i.imageAssetKey&&o("button",{type:"button",onClick:()=>D(i.id,{imageAssetKey:"",imageAssetUrl:void 0}),className:"text-xs text-muted-foreground hover:text-destructive flex items-center gap-1 font-medium transition-colors cursor-pointer",children:[t(De,{className:"w-3.5 h-3.5"}),vl?vl():"Remove"]})]}),t("input",{type:"file",ref:le,className:"hidden",accept:"image/*",onChange:(e)=>xe(e,i.id)}),o("div",{onClick:()=>le.current?.click(),className:"relative aspect-square w-full rounded-xl border border-dashed border-border flex items-center justify-center cursor-pointer overflow-hidden group shadow-inner bg-muted/20 hover:border-primary/50 hover:bg-muted/40 transition-all p-2",children:[Oe&&t("div",{className:"absolute inset-0 bg-background/70 backdrop-blur-xs flex flex-col items-center justify-center gap-2 z-20",children:o("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-background border rounded-full shadow-lg",children:[t(L,{className:"w-4 h-4 animate-spin text-primary"}),t("span",{className:"text-xs font-semibold",children:Op()})]})}),re[i.id]||i.imageAssetUrl?o(B,{children:[t("img",{src:re[i.id]||i.imageAssetUrl,alt:"Uploaded logo preview",className:"max-w-full max-h-full object-contain transition-transform duration-300 group-hover:scale-105"}),o("div",{className:"absolute inset-0 bg-black/45 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex flex-col items-center justify-center gap-1 text-white z-10",children:[t(so,{className:"w-5 h-5 transform translate-y-1 group-hover:translate-y-0 transition-transform duration-300"}),t("span",{className:"text-xs font-semibold",children:Np()})]})]}):o("div",{className:"flex flex-col items-center gap-1.5 text-center p-3",children:[t("div",{className:"p-2 rounded-full bg-background border shadow-xs group-hover:scale-110 transition-transform duration-300",children:t(so,{className:"w-4 h-4 text-muted-foreground"})}),o("div",{children:[t("p",{className:"text-xs font-medium text-foreground",children:ZI()}),t("p",{className:"text-[10px] text-muted-foreground mt-0.5 max-w-[150px] mx-auto leading-normal",children:BI()})]})]})]})]}),o("div",{className:"space-y-2",children:[o("div",{className:"flex items-center justify-between",children:[t(V,{className:"text-xs",children:i.type==="text"?qb():hw()}),o("span",{className:"font-mono text-[11px] text-muted-foreground",children:[Math.round(i.size*100),"%"]})]}),o("div",{className:"flex items-center gap-3",children:[t(Bs,{min:i.type==="text"?0.01:0.02,max:i.type==="text"?0.12:0.5,step:0.005,value:[i.size],onValueChange:([e])=>D(i.id,{size:e}),className:"flex-1"}),t(H,{type:"number",min:1,max:100,value:Math.round(i.size*100),onChange:(e)=>D(i.id,{size:Math.min(1,Math.max(0.001,Number(e.target.value)/100))}),className:"w-16 h-7 text-xs font-mono text-right"})]})]}),i.type==="text"&&o("div",{className:"space-y-2",children:[o("div",{className:"flex items-center justify-between",children:[t(V,{className:"text-xs",children:m0()}),t("span",{className:"font-mono text-[11px] text-muted-foreground uppercase",children:i.color})]}),o("div",{className:"flex items-center gap-2",children:[t("input",{type:"color",value:i.color,onChange:(e)=>D(i.id,{color:e.target.value}),className:"w-8 h-8 rounded border border-border cursor-pointer bg-transparent p-0"}),t(H,{type:"text",value:i.color,onChange:(e)=>D(i.id,{color:e.target.value}),className:"flex-1 h-8 text-xs font-mono"})]}),t("div",{className:"flex items-center gap-1.5 pt-1",children:["#FFFFFF","#000000","#999999","#EF4444","#3B82F6","#10B981","#F59E0B"].map((e)=>t("button",{type:"button",onClick:()=>D(i.id,{color:e}),style:{backgroundColor:e},className:"w-5 h-5 rounded-full border border-border hover:scale-110 transition-transform"},e))})]}),o("div",{className:"space-y-2",children:[o("div",{className:"flex items-center justify-between",children:[t(V,{className:"text-xs",children:Mx()}),o("span",{className:"font-mono text-[11px] text-muted-foreground",children:[Math.round(i.opacity*100),"%"]})]}),t(Bs,{min:0,max:1,step:0.01,value:[i.opacity],onValueChange:([e])=>D(i.id,{opacity:e})})]}),o("div",{className:"space-y-2",children:[o("div",{className:"flex items-center justify-between",children:[t(V,{className:"text-xs",children:MC()}),o("span",{className:"font-mono text-[11px] text-muted-foreground",children:[i.rotation,"°"]})]}),t(Bs,{min:-180,max:180,step:1,value:[i.rotation],onValueChange:([e])=>D(i.id,{rotation:e})}),t("div",{className:"flex items-center gap-1.5 pt-1",children:[-45,-30,0,30,45].map((e)=>o(S,{variant:"outline",size:"sm",className:"h-6 text-[10px] flex-1 px-1 font-mono",onClick:()=>D(i.id,{rotation:e}),children:[e,"°"]},e))})]}),o("div",{className:"space-y-2",children:[o("div",{className:"flex items-center justify-between",children:[t(V,{className:"text-xs",children:fS()}),o("span",{className:"font-mono text-[11px] text-muted-foreground",children:[Math.round(i.x*100),"%"]})]}),t(Bs,{min:0,max:1,step:0.01,value:[i.x],onValueChange:([e])=>D(i.id,{x:e})})]}),o("div",{className:"space-y-2",children:[o("div",{className:"flex items-center justify-between",children:[t(V,{className:"text-xs",children:pS()}),o("span",{className:"font-mono text-[11px] text-muted-foreground",children:[Math.round(i.y*100),"%"]})]}),t(Bs,{min:0,max:1,step:0.01,value:[i.y],onValueChange:([e])=>D(i.id,{y:e})})]})]}):o("div",{className:"py-12 text-center text-xs text-muted-foreground space-y-3",children:[t("p",{children:$C()}),o(S,{size:"sm",variant:"outline",onClick:ot,children:[t(fe,{className:"h-3.5 w-3.5 mr-1"}),pf()]})]})})]})]})]})}),t(pe,{open:Ce,onOpenChange:X,children:o(ue,{className:"max-w-md",children:[t(me,{children:t(de,{className:"text-sm font-semibold",children:we==="new"?Qm():Hh()})}),t("div",{className:"py-3 space-y-4 text-xs",children:we==="new"?o("div",{className:"space-y-2",children:[t(V,{children:sI()}),t(H,{type:"text",value:ce,onChange:(e)=>Y(e.target.value),placeholder:oh(),className:"text-xs"})]}):o("div",{className:"space-y-2",children:[t(V,{children:Ig()}),t("select",{value:J||"",onChange:(e)=>ee(e.target.value),className:"w-full h-9 rounded-md border border-input bg-background px-3 text-xs",children:se.map((e)=>t("option",{value:e.id,children:e.name},e.id))})]})}),o($e,{children:[t(S,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>X(!1),children:ke()}),t(S,{size:"sm",className:"text-xs",disabled:Ee||m,onClick:St,children:Wa()})]})]})})]})}function ze(...a){return a.filter(Boolean).join(" ")}C();function xt({shareLink:a,viewMode:b,onViewModeChange:g,defaultSortOrder:p,onSortOrderChange:k}){let x=K(),[P,d]=u(a.password||""),[v,c]=u(a.expireAt?new Date(a.expireAt):void 0),[f,j]=u(!1);h(()=>{d(a.password||"")},[a.password]);let[z,_]=u(a.hasPassword),[he,Ne]=u(!!a.expireAt),{data:Se,refetch:Ce}=Z({queryKey:["share-watermark",a.id],queryFn:async()=>{let s=await A.api.shares[":shareId"].watermark.$get({param:{shareId:a.id}});if(!s.ok)return null;return await s.json()},refetchInterval:(s)=>(s.state.data?.watermarkStatus||a.watermarkStatus)==="processing"?3000:!1}),X=A.api.shares[":shareId"].watermark.$put,{mutate:we}=U({mutationFn:async()=>{let s=await X({param:{shareId:a.id},json:{enabled:!1}});if(!s.ok)throw Error(ca());return await s.json()},onSuccess:()=>{x.invalidateQueries({queryKey:["shares",a.projectId]}),x.invalidateQueries({queryKey:["share",a.id]}),x.invalidateQueries({queryKey:["share-watermark",a.id]}),R.success($I())}}),oe=Se?.watermarkStatus??a.watermarkStatus??(a.watermarkConfigId?"ready":"disabled"),ce=Se?.watermarkConfig?.config??a.watermarkConfig?.config??null,Y=ce!==null&&oe!=="disabled",{data:J}=Z({queryKey:["fields",a.projectId],queryFn:async()=>{let s=await A.api.projects[":projectId"].fields.$get({param:{projectId:a.projectId}});if(!s.ok)throw Error(ab());return await s.json()},enabled:!!a.projectId}),ee=A.api.shares[":shareId"].$put,{mutate:I}=U({mutationFn:async(s)=>{let G=await ee({param:{shareId:a.id},json:s});if(!G.ok)throw Error(ca());return await G.json()},onSuccess:()=>{x.invalidateQueries({queryKey:["shares",a.projectId]}),x.invalidateQueries({queryKey:["share",a.id]}),R.success(Rg())}}),te=`${window.location.origin}/share/${a.id}`,ae=async(s)=>{if(await ao(s))R.success(R0())},Ie=(s)=>{let G=a.fieldVisibility||{},_e={...G,[s]:!G[s]};I({fieldVisibility:_e})},F="index",q="asc";if(p){let s=p.split(":");F=s[0],q=s[1]||"asc"}return o("div",{className:"flex flex-col h-full bg-background border-l border-border",children:[t("div",{className:"flex-1 overflow-y-auto",children:o("div",{className:"p-4 space-y-6",children:[o("div",{className:"space-y-4",children:[o("div",{className:"flex items-center justify-between",children:[t("h3",{className:"text-sm font-medium",children:Rw()}),t(qe,{checked:!a.isDisabled,onCheckedChange:(s)=>I({isDisabled:!s})})]}),o("div",{className:"relative w-full",children:[t(H,{value:te,readOnly:!0,className:"pr-10 bg-muted/50 text-xs"}),t(S,{variant:"ghost",size:"icon",className:"absolute right-0 top-0 h-full",onClick:()=>ae(te),children:t(Rr,{className:"h-4 w-4"})})]})]}),o("div",{className:"space-y-1",children:[t(Re,{title:jC(),icon:t(zl,{className:"h-4 w-4"}),children:o("div",{className:"p-3 space-y-4 pt-2",children:[o("div",{className:"space-y-2",children:[o("div",{className:"flex items-center justify-between",children:[t(V,{className:"text-xs",children:Xf()}),t(qe,{checked:z,onCheckedChange:(s)=>{if(_(s),!s)I({password:null})}})]}),z&&o("div",{className:"flex gap-2 animate-in fade-in slide-in-from-top-1 duration-200",children:[t(H,{type:"text",value:P,onChange:(s)=>d(s.target.value),placeholder:W_(),className:"text-xs"}),t(S,{size:"sm",onClick:()=>I({password:P}),children:Oo()})]})]}),o("div",{className:"space-y-2",children:[o("div",{className:"flex items-center justify-between",children:[t(V,{className:"text-xs",children:nb()}),t(qe,{checked:he,onCheckedChange:(s)=>{if(Ne(s),!s)c(void 0),I({expireAt:null})}})]}),he&&t("div",{className:"animate-in fade-in slide-in-from-top-1 duration-200",children:t(ma,{value:v,onChange:(s)=>{c(s),I({expireAt:s?s.toISOString():null})},className:"text-xs"})})]}),o("div",{className:"space-y-2",children:[o("div",{className:"flex items-center justify-between",children:[t(V,{className:"text-xs",children:yy()}),t(qe,{checked:a.allowDownload,onCheckedChange:(s)=>I({allowDownload:s})})]}),t("p",{className:"text-xs text-muted-foreground",children:_y()})]}),o("div",{className:"space-y-2 pt-2 border-t border-border/50",children:[o("div",{className:"flex items-center justify-between",children:[t(V,{className:"text-xs",children:Gg()}),t(qe,{checked:Y,disabled:oe==="processing",onCheckedChange:(s)=>{if(!s)we();else j(!0)}})]}),Y&&oe==="processing"&&o("div",{className:"flex items-center gap-2 text-xs text-amber-600 dark:text-amber-400 font-medium py-1 animate-pulse",children:[t(L,{className:"h-3.5 w-3.5 animate-spin"}),t("span",{children:VI()})]}),Y&&oe!=="processing"&&t(S,{variant:"outline",size:"sm",className:"w-full text-xs gap-1.5 mt-1",onClick:()=>j(!0),children:B_()})]})]})}),t(Re,{title:Ey(),icon:t(ct,{className:"h-4 w-4"}),children:o("div",{className:"p-3 space-y-3 pt-2 flex gap-2",children:[o(S,{variant:b==="card"?"secondary":"outline",size:"sm",className:"flex-1 gap-2 text-xs",onClick:()=>g("card"),children:[t(Jn,{className:"h-4 w-4"}),aw()]}),o(S,{variant:b==="list"?"secondary":"outline",size:"sm",className:"flex-1 gap-2 text-xs",onClick:()=>g("list"),children:[t(Po,{className:"h-4 w-4"}),Pw()]})]})}),t(Re,{title:Ti(),icon:t(dt,{className:"h-4 w-4"}),children:t("div",{className:"p-3 space-y-3 pt-2",children:J?.map((s)=>o("div",{className:"flex items-center justify-between",children:[t(V,{className:"text-xs",children:s.config?.name}),t(qe,{checked:a.fieldVisibility?.[s.id]??!1,onCheckedChange:()=>Ie(s.id)})]},s.id))})}),t(Re,{title:xl(),icon:t(Pl,{className:"h-4 w-4"}),children:o("div",{className:"p-3 space-y-4 pt-2",children:[o("div",{className:"space-y-2",children:[t(V,{className:"text-xs text-muted-foreground",children:Mf()}),o(Le,{value:F,onValueChange:(s)=>{if(s==="index")k(null);else k(`${s}:${q}`)},children:[t(Be,{className:"w-full text-xs h-9",children:t(Ze,{})}),o(Ue,{children:[t(ne,{value:"index",children:bp()}),t(ne,{value:"name",children:Sl()}),t(ne,{value:"createdAt",children:wp()}),t(ne,{value:"size",children:xp()})]})]})]}),o("div",{className:"space-y-2",children:[t(V,{className:"text-xs text-muted-foreground",children:Jf()}),o(S,{variant:"outline",className:"w-full justify-between font-normal text-xs h-9",disabled:F==="index",onClick:()=>{k(`${F}:${q==="asc"?"desc":"asc"}`)},children:[t("span",{children:F==="name"?q==="asc"?Bc():zc():F==="createdAt"?q==="asc"?Fc():Uc():F==="size"?q==="asc"?Sp():vp():q==="asc"?mf():xf()}),t(Wc,{className:"h-4 w-4 opacity-50"})]})]})]})})]})]})}),o("div",{className:"p-4 border-t border-border space-y-2",children:[o(S,{variant:"outline",className:"w-full justify-center",onClick:()=>window.open(te,"_blank"),children:[t(kl,{className:"h-4 w-4 mr-2"}),kx()]}),o(S,{className:"w-full justify-center bg-blue-600 hover:bg-blue-700 text-white",onClick:()=>ae(te),children:[t(Rr,{className:"h-4 w-4 mr-2"}),N0()]})]}),t(gt,{open:f,onOpenChange:j,initialConfig:ce,shareId:a.id,onSaveSuccess:()=>{Ce(),x.invalidateQueries({queryKey:["share",a.id]}),x.invalidateQueries({queryKey:["shares",a.projectId]})}})]})}function Re({title:a,icon:b,children:g}){let[p,k]=u(!1);return o("div",{className:"border-b border-border last:border-0",children:[o("button",{onClick:()=>k(!p),className:"w-full flex items-center justify-between py-3 px-2 hover:bg-muted/50 transition-colors",children:[o("div",{className:"flex items-center gap-3",children:[b,t("span",{className:"text-sm font-medium",children:a})]}),t(pt,{className:Pt("h-4 w-4 transition-transform",p&&"rotate-90")})]}),p&&g&&t("div",{className:"animate-in fade-in slide-in-from-top-1 duration-200",children:g})]})}function Pt(...a){return a.filter(Boolean).join(" ")}function st({teamId:a,projectId:b,projectName:g,shareId:p,rootFolderId:k}){let x=K(),{fetchMetadata:P}=Lo();h(()=>{if(a)P(a)},[a,P]);let{data:d}=Z({queryKey:["share",p],queryFn:async()=>{let r=await A.api.shares[":shareId"].$get({param:{shareId:p}});if(!r.ok)throw Error(cb());return await r.json()}}),v=d?.rootFolderId,[c,f]=u(null),[j,z]=u([]);h(()=>{if(v)f(v),z([]),xe(new Set)},[v,p]);let _=en((r)=>r.setProjectState),he=en((r)=>r.clearProjectState),Ne=(r)=>{if(r===c)return;if(r===v)f(v),z([]);else{let m=j.findIndex((Q)=>Q.id===r);if(m!==-1)f(r),z(j.slice(m+1))}xe(new Set)},[Se,Ce]=u(240),[X,we]=u(360),{shareConfigLeftSidebarCollapsed:oe,shareConfigRightSidebarCollapsed:ce}=Qt(),Y=d?.defaultSortOrder||null,J,ee;if(Y){let r=Y.split(":");J=r[0],ee=r[1]}let I=d?.viewMode??"card",{data:te,fetchNextPage:ae,hasNextPage:Ie,isFetchingNextPage:F,isLoading:q}=ut({queryKey:["folder-children",a,c,"folder",J,ee],queryFn:async({pageParam:r})=>{let m=await A.api.folders[":folderId"].children.$get({param:{folderId:c},query:{assetType:"folder",after:r,sort:J,order:ee}});if(!m.ok)throw Error(lb());return await m.json()},enabled:!!c,initialPageParam:"",getNextPageParam:(r)=>r.pageInfo?.cursor||void 0}),{data:s,fetchNextPage:G,hasNextPage:_e,isFetchingNextPage:Oe,isLoading:Te}=ut({queryKey:["folder-children",a,c,"file",J,ee],queryFn:async({pageParam:r})=>{let m=await A.api.folders[":folderId"].children.$get({param:{folderId:c},query:{assetType:"file",after:r,sort:J,order:ee}});if(!m.ok)throw Error(ib());return await m.json()},enabled:!!c,initialPageParam:"",getNextPageParam:(r)=>r.pageInfo?.cursor||void 0}),re=O(()=>te?.pages.flatMap((r)=>r.data??[])??[],[te]),je=O(()=>s?.pages.flatMap((r)=>r.data??[])??[],[s]);h(()=>{if(d)_({teamId:a,projectId:b,projectName:g,ancestorFolders:j,currentAsset:{name:c===v?d.name:re.find((r)=>r.id===c)?.name||d.name,type:"folder"},isRootFolder:!1,shareId:p,onFolderClick:Ne});return()=>he()},[a,b,g,j,c,v,d,p,re,_,he]);let le=()=>{xe(new Set)},[Pe,xe]=u(new Set),{dragState:se,handleDragStart:Ke,handleDragEnd:Qe}=Dl({teamId:a,projectId:b,assetId:c||"",folders:re,files:je,selectedIds:Pe,onClearSelection:le}),Ve=A.api.shares[":shareId"].assets[":assetId"].$delete,{mutate:He}=U({mutationFn:async(r)=>{if(!(await Ve({param:{shareId:p,assetId:r}})).ok)throw Error(ub())},onSuccess:()=>{x.invalidateQueries({queryKey:["folder-children",a,c]}),R.success(_C())}}),Ge=A.api.shares[":shareId"].$put,{mutate:Ee}=U({mutationFn:async(r)=>{let m=await Ge({param:{shareId:p},json:r});if(!m.ok)throw Error(ca());return await m.json()},onSuccess:()=>{x.invalidateQueries({queryKey:["share",p]}),R.success(Rg())}}),Xe=(r)=>{if(r.type==="folder"||r.targetType==="folder"){let m=c===v?d?.name||"":re.find((Q)=>Q.id===c)?.name||cn();z((Q)=>[{id:c,name:m},...Q]),f(r.id),xe(new Set)}};if(!d)return t("div",{children:pd()});return o(jn,{modifiers:[oi.configure({anchor:{x:0,y:0}})],sensors:[un.configure({activationConstraints:[new kr.Distance({value:10})]})],onDragStart:Ke,onDragEnd:Qe,children:[t("div",{className:"flex flex-1 flex-col bg-background min-h-0",children:o("div",{className:"flex flex-1 overflow-hidden relative",children:[!oe&&o(B,{children:[t("div",{className:"bg-background",style:{width:Se},children:t(Ar,{teamId:a,projectId:b,projectName:g,rootFolderId:k,dragState:se})}),t(Sr,{onResize:(r)=>Ce((m)=>Math.max(180,Math.min(400,m+r)))})]}),t(Aa,{teamId:a,projectId:b,assetId:c||"",folders:re,files:je,selectedItem:null,selectedIds:Pe,onItemSelect:(r,m)=>{if(m.metaKey||m.ctrlKey){let Q=new Set(Pe);if(Q.has(r.id))Q.delete(r.id);else Q.add(r.id);xe(Q)}else xe(new Set([r.id]))},onItemDoubleClick:Xe,onSaveField:()=>{},displayStyle:I,onClearSelection:le,fetchNextFoldersPage:ae,hasNextFoldersPage:Ie,isFetchingNextFoldersPage:F,fetchNextFilesPage:G,hasNextFilesPage:_e,isFetchingNextFilesPage:Oe,isLoading:q||Te,filterConditions:[],onFilterChange:()=>{},dragState:se,isShareView:!0,onRemoveFromShare:(r)=>{r.forEach((m)=>He(m.id))},fieldVisibility:d.fieldVisibility}),!ce&&o(B,{children:[t(Sr,{onResize:(r)=>we((m)=>Math.max(240,Math.min(600,m-r)))}),t("div",{style:{width:X},className:"flex-shrink-0 h-full",children:t(xt,{shareLink:d,viewMode:I,onViewModeChange:(r)=>Ee({viewMode:r}),defaultSortOrder:Y,onSortOrderChange:(r)=>Ee({defaultSortOrder:r})})})]})]})}),t(qc,{children:se?.isActive?t("div",{className:"flex items-center gap-2 rounded-md bg-popover px-3 py-2 text-sm font-medium shadow-md",children:Dv({count:se.itemCount})}):null})]})}C();function Tt(){let{projectId:a,shareId:b}=jt.useParams(),{teamId:g,ensureTeamIdForProject:p}=it();h(()=>{p(a)},[a,p]);let{data:k}=er($p(a)),x=k?.rootFolder,{data:P}=Z({queryKey:["folders",x],queryFn:async()=>{let d=await A.api.folders[":folderId"].$get({param:{folderId:x}});if(!d.ok)throw Error("Failed to fetch folder");return await d.json()},enabled:!!x});if(!g||!x||!P)return t(_t,{});return t(st,{teamId:g,projectId:a,projectName:k.name??"",shareId:b,rootFolderId:x})}var jt=Fe("/projects/$projectId/shares/$shareId")({component:Tt});export{jt as Route};
@@ -0,0 +1 @@
1
+ import{h,w,u,C,B,t,o,K,wi,Z,U,Re,Zn,Fe,A,L,Xt,E,S,ke,at,Nc,Oc,C_,id,Ii,_b,dh,No,bC,Oo,Je,Xe,et,tt,rt,nt,ot,st,pe,ue,me,$e,de,H,it,Mt,R,en,Ur,Qt,yr,Do,Xg}from"./chunk-7rhz2gze.js";import{Zo,ps}from"./chunk-7kjgvxqa.js";import"./chunk-gc5sbfa5.js";import{tn}from"./chunk-77fmkpdz.js";import{ga}from"./chunk-1j27fzy1.js";import{Zl,ba}from"./chunk-snhsjs4x.js";import{ni,Nl,Ol}from"./chunk-f6svp4dp.js";import"./chunk-914bp49r.js";import{Sr}from"./chunk-0qaq0sp8.js";import"./chunk-m9pr03kn.js";import"./chunk-5adsx8x4.js";import"./chunk-j2bvj2yn.js";import"./chunk-cbgq517y.js";import"./chunk-ytdwk2fq.js";import"./chunk-0zv3bks2.js";C();var Ft=({item:n})=>{if(n.preview?.thumbnailUrl)return t("img",{src:n.preview.thumbnailUrl,alt:"Preview",className:"w-full h-full object-cover"});if(n.preview?.proxyType==="audio"||n.proxyType==="audio")return t("div",{className:"w-full h-full flex items-center justify-center bg-muted",children:t(Zo,{className:"w-5 h-5 text-muted-foreground"})});return t("div",{className:"w-full h-full flex items-center justify-center bg-muted",children:t(Xt,{className:"w-5 h-5 text-muted-foreground"})})},Ne=({projectId:n,currentAssetId:s,parentFolderId:x,initialFiles:d,initialNextCursor:k})=>{let{ref:a,inView:M}=Mt({threshold:0,rootMargin:"200px"}),b=w(null),N=w(!0),[c,p]=u(d),[f,W]=u(k),[X,J]=u(!!k),[V,g]=u(!1);return h(()=>{p(d),W(k),J(!!k),N.current=!0},[d,k]),h(()=>{(async()=>{if(!f||V||!M||!X)return;g(!0);try{let y=await A.api.folders[":folderId"].search.$post({param:{folderId:x},json:{assetType:"file",after:f,first:200,recursively:!1,conditions:[]}});if(!y.ok)throw Error("Failed to fetch next page");let q=await y.json(),P=q.data||[];p((Y)=>[...Y,...P]),W(q.pageInfo?.cursor||void 0),J(!!q.pageInfo?.cursor&&P.length>0)}catch(y){console.error("Error fetching next page:",y)}finally{g(!1)}})()},[M,f,X,V,x]),h(()=>{if(c.some((y)=>y?.id===s)&&b.current)if(N.current)b.current.scrollIntoView({block:"center",inline:"center",behavior:"auto"}),N.current=!1;else b.current.scrollIntoView({block:"nearest",inline:"nearest",behavior:"smooth"})},[c,s]),t("div",{className:"h-24 md:h-full w-full md:w-24 bg-gray-100 dark:bg-gray-950 flex flex-row md:flex-col flex-shrink-0 select-none",children:o("div",{className:"flex-1 overflow-x-auto overflow-y-hidden md:overflow-y-auto md:overflow-x-hidden px-4 md:px-0 py-2 md:py-4 flex flex-row md:flex-col items-center gap-3 no-scrollbar",children:[c.map((m)=>{if(!m)return null;let y=m.id===s;return t("div",{ref:m.id===s?b:null,className:"flex-shrink-0",children:o(Zn,{to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:m.id},search:{version:void 0},className:E("rounded-lg border overflow-hidden flex items-center justify-center transition-all bg-muted/30 block relative",y?"w-[62px] h-[62px] opacity-100":"w-[52px] h-[52px] opacity-60 hover:opacity-100"),children:[t(Ft,{item:m}),m.agent&&t("span",{className:"absolute top-1 right-1 z-10 pointer-events-none select-none rounded bg-black/60 px-1 py-0.5 text-[10px] font-medium leading-none text-white",title:m.agent.name,"data-testid":"carousel-agent-badge",children:"AI"})]})},m.id)}),X&&t("div",{ref:a,className:"px-2 md:px-0 py-2 md:py-4 flex justify-center items-center h-full md:w-full flex-shrink-0",children:V&&t(L,{className:"h-5 w-5 animate-spin text-muted-foreground"})})]})})};C();function kt(){let{projectId:n,fileId:s}=Le.useParams(),x=Le.useSearch(),{version:d,start:k}=x,a=d||s,{cmpLeft:M,cmpRight:b}=x,N=x.cmpActive??"left",c=!!x.compare&&!!M&&!!b,p=w(null),{teamId:f,ensureTeamIdForProject:W}=it(),[X,J]=u(360),[V,g]=u([]),{fileViewRightSidebarCollapsed:m}=Qt(),{isChatbotOpen:y}=yr(),[q,P]=u(0),[Y,z]=u(null),[he,Ee]=u(null),[Ve,ge]=u(void 0),[_,ne]=u({show:!1,files:[],nextCursor:void 0,folderId:void 0}),qe=A.api.files[":fileId"].metadata.$patch,{mutate:Pe}=U({mutationFn:async(e)=>{let r=await qe(e);if(!r.ok)throw Error("Failed to patch metadata");return await r.json()}}),G=K(),{members:ze,fetchProjectMembers:ye}=Ur(),_e=Do();h(()=>{W(n)},[n,W]),h(()=>{if(n)ye(n,!0)},[n,ye]),h(()=>{if(n&&s)A.api.projects[":projectId"].recents.view.$post({param:{projectId:n},json:{assetId:s}}).catch(()=>{})},[n,s]);let{data:Ie,isLoading:Ke,isError:Oe,isFetching:He}=Z({queryKey:["files",s],queryFn:async()=>{let e=await A.api.files[":fileId"].$get({param:{fileId:s}});if(!e.ok)throw Error("Failed to fetch stack");return await e.json()},enabled:!!f,placeholderData:wi}),{data:Qe,isLoading:Be,isError:Ue,isFetching:We}=Z({queryKey:["files",d],queryFn:async()=>{let e=await A.api.files[":fileId"].$get({param:{fileId:d}});if(!e.ok)throw Error("Failed to fetch version");return await e.json()},enabled:!!f&&!!d,placeholderData:wi}),{data:Ge}=Z({queryKey:["version_stacks",s,"versions"],queryFn:async()=>{let e=await A.api.version_stacks[":stackId"].versions.$get({param:{stackId:s}});if(!e.ok)throw Error("Failed to fetch versions");return await e.json()},enabled:!!n&&!!s&&(!!d||c)}),{data:j}=Z({queryKey:["projects",n],queryFn:async()=>{let e=await A.api.projects[":projectId"].$get({param:{projectId:n}});if(!e.ok)throw Error("Failed to fetch project");return await e.json()}}),I=Re(),{setProjectState:ve,clearProjectState:we}=en(),Ye=Ke||!!d&&Be,Ze=Oe||!!d&&Ue,lt=He||!!d&&We,i=Qe||Ie,F=d?Ge:Ie?.versionStack?.versions,l=i?.ancestorFolders?.[0]?.id??j?.rootFolder??"",[re,ee]=u(!1),[te,xe]=u(""),se=w(null),ae=w(!1),[ct,ie]=u(!1),dt=A.api.files[":fileId"].$put,{mutate:ft,mutateAsync:pt,isPending:be}=U({mutationFn:async(e)=>{let r=await dt(e);if(!r.ok)throw Error("Failed to rename file");return await r.json()},onSuccess:()=>{G.invalidateQueries({queryKey:["files"]}),G.invalidateQueries({queryKey:["version_stacks"]}),R.success(bC?.()||"Renamed successfully"),ee(!1)},onError:()=>{R.error(_b?.()||"Failed to rename")}}),ut=A.api.files.$delete,{mutate:mt,mutateAsync:ht,isPending:je}=U({mutationFn:async(e)=>{if(!(await ut(e)).ok)throw Error("Failed to delete file")},onSuccess:()=>{if(G.invalidateQueries({queryKey:["files"]}),G.invalidateQueries({queryKey:["version_stacks"]}),R.success(C_?.()||"Deleted"),ie(!1),l&&l!==j?.rootFolder)I({to:"/projects/$projectId/folders/$folderId",params:{projectId:n,folderId:l}});else I({to:"/projects/$projectId",params:{projectId:n}})},onError:()=>{R.error(Ii?.()||"Failed to delete")}}),gt=(e)=>{if(e?.preventDefault(),!te.trim()||!a)return;ft({param:{fileId:a},json:{name:te.trim()}})},yt=()=>{if(!a)return;mt({json:{ids:[a]}})};h(()=>{if(i&&j&&f)ve({teamId:f,projectId:n,projectName:j.name??"",ancestorFolders:i.ancestorFolders??[],currentAsset:{id:a||s,name:i.name,type:"file",version:F?F.find((e)=>e.id===a)?.version??F.length:void 0,proxyType:i.proxyType},isRootFolder:!1,fileId:s,downloadInfo:{originalKey:i.media?.original?.key,videoTranscodes:i.media?.videoTranscodes?.map((e)=>({key:e.key,width:e.width,height:e.height}))},versions:F,compareMode:c,canCompareVersions:(F?.length??0)>=2,onCompareVersions:()=>{let e=Zl(F);if(!e)return;I({to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:s},search:(r)=>({...r,version:void 0,compare:!0,cmpLeft:e.left.id,cmpRight:e.right.id,cmpActive:"left"})})},onFolderClick:(e)=>{I({to:"/projects/$projectId/folders/$folderId",params:{projectId:n,folderId:e}})},onRename:()=>{ae.current=!1,xe(i?.name??""),ee(!0)},onDelete:()=>{ie(!0)}});return()=>we()},[f,n,j,i,F,a,s,c,ve,we,I]),h(()=>{if(!re)return;let e=setTimeout(()=>{ae.current=!0},1000);return()=>clearTimeout(e)},[re]);let It=()=>{if(ae.current)return;setTimeout(()=>{if(se.current)ps(se.current)},0)};if(h(()=>{if(!l||!a)return;if(_.folderId===l)return;let e=!0;return(async()=>{try{let v="",D=!1,T=[],ce=void 0;for(let Se=0;Se<5;Se++){let Te=await A.api.folders[":folderId"].search.$post({param:{folderId:l},json:{assetType:"file",after:v,first:200,recursively:!1,conditions:[]}});if(!Te.ok)throw Error("Failed to search parent folder for carousel");let Q=await Te.json(),fe=Q.data||[];if(T.push(...fe),fe.some((oe)=>oe.id===a)){if(D=!0,ce=Q.pageInfo?.cursor||void 0,Q.pageInfo?.cursor)try{let oe=await A.api.folders[":folderId"].search.$post({param:{folderId:l},json:{assetType:"file",after:Q.pageInfo.cursor,first:200,recursively:!1,conditions:[]}});if(oe.ok){let Me=await oe.json(),bt=Me.data||[];T.push(...bt),ce=Me.pageInfo?.cursor||void 0}}catch{}break}if(!Q.pageInfo?.cursor||fe.length<200)break;v=Q.pageInfo.cursor}if(e)if(D)ne({show:!0,files:T,nextCursor:ce,folderId:l});else ne({show:!1,files:[],nextCursor:void 0,folderId:l})}catch(v){if(console.error(v),e)ne({show:!1,files:[],nextCursor:void 0,folderId:l})}})(),()=>{e=!1}},[l,a,_.folderId]),h(()=>{P(0),z(null),g([])},[i?.id]),h(()=>{z(null),g([])},[he?.id]),h(()=>{tn.getState().reset(),tn.getState().setIsDrawing(!1),g([]),z(null)},[a]),Ye&&!i)return t(Xg,{});if(Ze||!i||!j||!f)return t("div",{children:dh()});let O=c?he:i,Ae=O?.id??a,Ce=(e,r)=>{if(!f)return;Pe({param:{fileId:Ae},json:[{key:e,value:r}]},{onSuccess:()=>{G.invalidateQueries({queryKey:["files",Ae]})}})},le=(e)=>{I({to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:s},search:(r)=>({...r,...e})})},vt=()=>{le({compare:void 0,cmpLeft:void 0,cmpRight:void 0,cmpActive:void 0,version:N==="left"?M:b})},wt=(e)=>{z(e.id||null);let r=e.annotations;if(r&&r.length>0)g(r);else g([]);if(c){if(e.second!==null&&e.second!==void 0)ge({second:e.second,nonce:Date.now()});return}if(e.second!==null&&e.second!==void 0)p.current?.seekTo(e.second),p.current?.pause();else if(r&&r.length>0)p.current?.pause()},xt=(e)=>{z(e.id||null);let v=e.details,D=v?.annotations;if(D&&D.length>0)g(D);else g([]);let T=v?.position?.type==="time"?v.position.seconds:v?.position?.type==="page"?v.position.page:void 0;if(c){if(T!==void 0)ge({second:T,nonce:Date.now()});return}if(T!==void 0)p.current?.seekTo(T),p.current?.pause();else if(D&&D.length>0)p.current?.pause()},De=()=>{g([]),z(null)};if(_e&&!c)return t(Nl,{projectId:n,teamId:f,fileId:s,file:i,projectInfo:j,ancestorFolders:i.ancestorFolders??[],parentFolderId:l,versions:F,activeFileId:a,startTime:k,siblingFiles:_.files,onNavigateToFile:(e)=>{I({to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:e}})},onNavigateBack:()=>{if(l&&l!==j?.rootFolder)I({to:"/projects/$projectId/folders/$folderId",params:{projectId:n,folderId:l}});else I({to:"/projects/$projectId",params:{projectId:n}})},onSelectVersion:(e)=>{I({to:"/projects/$projectId/files/$fileId",params:{projectId:n,fileId:s},search:(r)=>({...r,version:e})})},onRenameFile:async(e)=>{await pt({param:{fileId:a},json:{name:e}})},onDeleteFile:async()=>{await ht({json:{ids:[a]}})},onSaveField:Ce});return o("div",{className:"h-full flex flex-1 flex-col bg-background",children:[o("div",{className:"h-full flex flex-1 overflow-hidden",children:[o("div",{className:"flex-1 relative",children:[lt&&!c&&t("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:t(L,{className:"h-8 w-8 animate-spin text-foreground"})}),c&&M&&b?t(Ol,{versions:F??[],leftId:M,rightId:b,activeSide:N,annotations:V,seekRequest:Ve,onActiveSideChange:(e)=>le({cmpActive:e}),onSwitchVersion:(e,r)=>le(e==="left"?{cmpLeft:r}:{cmpRight:r}),onExit:vt,onActiveAssetChange:Ee,onPlay:De,onTimeUpdate:P}):t(ni,{file:i,mediaControllerRef:p,onPlay:De,onTimeUpdate:P,annotations:V,startTime:k,children:_.show&&t(Ne,{projectId:n,currentAssetId:a,parentFolderId:l,initialFiles:_.files,initialNextCursor:_.nextCursor})})]}),(!m||y)&&o(B,{children:[t(Sr,{onResize:(e)=>{J((r)=>Math.max(300,Math.min(600,r-e)))},className:"hidden md:block"}),t("div",{style:{width:X},className:"flex-shrink-0 bg-background flex flex-col",children:y?t(ga,{projectId:n,contextAssetId:a,file:O,currentTime:q,frameRate:O?.media?.metadata?.frameRate||30,startTimecode:O?.media?.metadata?.startTimecode,onTyping:()=>{if(c)return;p.current?.pause()},onSelectMessage:xt,selectedMessageId:Y}):t(ba,{teamId:f,projectId:n,file:O,onSaveField:Ce,members:ze,onCommentSelect:wt,currentTime:q,onTyping:()=>{if(c)return;p.current?.pause()},selectedCommentId:Y,hideAnnotationControl:O?.proxyType==="audio"})})]})]}),t(pe,{open:re,onOpenChange:ee,children:t(ue,{children:o("form",{onSubmit:gt,children:[t(me,{children:t(de,{children:No()})}),t("div",{className:"py-4",children:t(H,{ref:se,value:te,onChange:(e)=>xe(e.target.value),placeholder:id?.()||"Enter new name",onFocus:It,autoFocus:!0})}),o($e,{children:[t(S,{type:"button",variant:"outline",onClick:()=>ee(!1),children:ke()}),o(S,{type:"submit",disabled:be||!te.trim(),children:[be&&t(L,{className:"mr-2 h-4 w-4 animate-spin"}),Oo()]})]})]})})}),t(Je,{open:ct,onOpenChange:ie,children:o(Xe,{children:[o(et,{children:[t(rt,{children:Oc?.()||"Delete Asset?"}),t(nt,{children:Nc?.()||"Deleted items can be recovered for 30 days before being permanently deleted."})]}),o(tt,{children:[t(st,{children:ke()}),o(ot,{onClick:yt,disabled:je,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:[je&&t(L,{className:"mr-2 h-4 w-4 animate-spin"}),at()]})]})]})})]})}var Le=Fe("/projects/$projectId/files/$fileId")({component:kt});export{Le as Route};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ function As(i){let t=3735928559,h=1103547991;for(let e=0;e<i.length;e++){let l=i.charCodeAt(e);t=Math.imul(t^l,2654435761),h=Math.imul(h^l,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(h^h>>>13,3266489909),h=Math.imul(h^h>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),(h>>>0).toString(36)+(t>>>0).toString(36)}
3
+ export{As};
@@ -0,0 +1,2 @@
1
+ import{xt,D,N,St,O,w,C,t,E,as,dt,Y,Lt,se,zn,aa,cl,ul}from"./chunk-7rhz2gze.js";C();C();var S=Object.defineProperty,z=(s,e)=>S(s,"name",{value:e,configurable:!0}),M="Toggle",T=D(z(function(e,o){let{pressed:r,defaultPressed:n,onPressedChange:a,...g}=e,[l,i]=Lt({prop:r,onChange:a,defaultProp:n??!1,caller:M});return t(se.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":e.disabled?"":void 0,...g,ref:o,onClick:Y(e.onClick,()=>{if(!e.disabled)i(!l)})})},"Toggle"));C();var k=Object.defineProperty,p=(s,e)=>k(s,"name",{value:e,configurable:!0}),m="ToggleGroup",[b,ie]=dt(m,[aa]),R=aa(),F=D(p(function(e,o){let{type:r,...n}=e;if(r==="single")return t(A,{role:"radiogroup",...n,ref:o});if(r==="multiple")return t(j,{role:"toolbar",...n,ref:o});throw Error(`Missing prop \`type\` expected on \`${m}\``)},"ToggleGroup")),[h,x]=b(m),A=D(p(function(e,o){let{value:r,defaultValue:n,onValueChange:a=p(()=>{},"onValueChange"),...g}=e,[l,i]=Lt({prop:r,defaultProp:n??"",onChange:a,caller:m});return t(h,{scope:e.__scopeToggleGroup,type:"single",value:O(()=>l?[l]:[],[l]),onItemActivate:i,onItemDeactivate:N(()=>i(""),[i]),children:t(I,{...g,ref:o})})},"ToggleGroupImplSingle")),j=D(p(function(e,o){let{value:r,defaultValue:n,onValueChange:a=p(()=>{},"onValueChange"),...g}=e,[l,i]=Lt({prop:r,defaultProp:n??[],onChange:a,caller:m}),u=N((c)=>i((d=[])=>[...d,c]),[i]),f=N((c)=>i((d=[])=>d.filter((y)=>y!==c)),[i]);return t(h,{scope:e.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:u,onItemDeactivate:f,children:t(I,{...g,ref:o})})},"ToggleGroupImplMultiple")),[B,H]=b(m),I=D(p(function(e,o){let{__scopeToggleGroup:r,disabled:n=!1,rovingFocus:a=!0,orientation:g,dir:l,loop:i=!0,...u}=e,f=R(r),c=zn(l),d={dir:c,...u};return t(B,{scope:r,rovingFocus:a,disabled:n,children:a?t(cl,{asChild:!0,...f,orientation:g,dir:c,loop:i,children:t(se.div,{...d,ref:o})}):t(se.div,{...d,ref:o})})},"ToggleGroupImpl")),v="ToggleGroupItem",L=D(p(function(e,o){let r=x(v,e.__scopeToggleGroup),n=H(v,e.__scopeToggleGroup),a=R(e.__scopeToggleGroup),g=r.value.includes(e.value),l=n.disabled||e.disabled,i={...e,pressed:g,disabled:l},u=w(null);return n.rovingFocus?t(ul,{asChild:!0,...a,focusable:!l,active:g,ref:u,children:t(P,{...i,ref:o})}):t(P,{...i,ref:o})},"ToggleGroupItem")),P=D(p(function(e,o){let{__scopeToggleGroup:r,value:n,...a}=e,g=x(v,r),l={role:"radio","aria-checked":e.pressed,"aria-pressed":void 0},i=g.type==="single"?l:void 0;return t(T,{...i,...a,ref:o,onPressedChange:(u)=>{if(u)g.onItemActivate(n);else g.onItemDeactivate(n)}})},"ToggleGroupItemImpl"));var _=as("inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[color,box-shadow] outline-none hover:bg-muted hover:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground"},size:{default:"h-9 min-w-9 px-2",sm:"h-8 min-w-8 px-1.5",lg:"h-10 min-w-10 px-2.5"}},defaultVariants:{variant:"default",size:"default"}});var V=xt({size:"default",variant:"default",spacing:0});function Eo({className:s,variant:e,size:o,spacing:r=0,children:n,...a}){return t(F,{"data-slot":"toggle-group","data-variant":e,"data-size":o,"data-spacing":r,style:{"--gap":r},className:E("group/toggle-group flex w-fit items-center gap-[--spacing(var(--gap))] rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",s),...a,children:t(V.Provider,{value:{variant:e,size:o,spacing:r},children:n})})}function pr({className:s,children:e,variant:o,size:r,...n}){let a=St(V);return t(L,{"data-slot":"toggle-group-item","data-variant":a.variant||o,"data-size":a.size||r,"data-spacing":a.spacing,className:E(_({variant:a.variant||o,size:a.size||r}),"w-auto min-w-0 shrink-0 px-3 focus:z-10 focus-visible:z-10","data-[spacing=0]:rounded-none data-[spacing=0]:shadow-none data-[spacing=0]:first:rounded-l-md data-[spacing=0]:last:rounded-r-md data-[spacing=0]:data-[variant=outline]:border-l-0 data-[spacing=0]:data-[variant=outline]:first:border-l",s),...n,children:e})}
2
+ export{Eo,pr};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Jd,kn,nc,oc,sc,ac,mu,hu,em,nA,ys,zo,Fr}from"./chunk-nkdk229f.js";export{sc as EncryptJWT,oc as SignJWT,em as UnsecuredJWT,Jd as base64url,ac as calculateJwkThumbprint,mu as createLocalJWKSet,hu as createRemoteJWKSet,Fr as decodeJwt,zo as decodeProtectedHeader,ys as importJWK,nA as importPKCS8,nc as jwtDecrypt,kn as jwtVerify};
@@ -0,0 +1,2 @@
1
+ import{T}from"./chunk-7rhz2gze.js";var e=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],pn=T("circle-alert",e);
2
+ export{pn};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ function c(e){if(!(e instanceof Error)||!("status"in e)||!("headers"in e))return!1;return(e.status===void 0||typeof e.status==="number")&&(e.headers===void 0||e.headers instanceof Headers)}function d(e){let t=e.headers?.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===void 0)return!0;return e.status===408||e.status===409||e.status===429||typeof e.status==="number"&&e.status>=500}function o(e,t,a){let r=t??60000;if(r>0&&e>r)throw Error(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(r/1000)}s). ${a}`);return e}function l(e,t,a){let r=e.headers?.get("retry-after-ms");if(r){let s=Number.parseFloat(r);if(!Number.isNaN(s))return o(s,a,e.message)}let n=e.headers?.get("retry-after");if(n){let s=Number.parseFloat(n),f=Number.isNaN(s)?Date.parse(n)-Date.now():s*1000;return o(f,a,e.message)}return Math.min(0.5*2**t,8)*1000*(1-Math.random()*0.25)}function i(){let e=Error("Request aborted");return e.name="AbortError",e}function m(e,t){return new Promise((a,r)=>{if(t?.aborted){r(i());return}let n=()=>{clearTimeout(u),r(i())},u=setTimeout(()=>{t?.removeEventListener("abort",n),a()},Math.max(0,e));t?.addEventListener("abort",n,{once:!0})})}async function ts(e,t={}){let a=t.maxRetries??0,r=a;for(;;)try{return await e()}catch(n){if(t.signal?.aborted)throw i();if(r<=0||!c(n)||!d(n))throw n;let u=a-r;r--,await m(l(n,u,t.maxRetryDelayMs),t.signal)}}
3
+ export{ts};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{yc,_c,Pu}from"./chunk-9ccw540k.js";export{yc as ENV_KEY,_c as ENV_SECRET,Pu as fromEnv};
@@ -0,0 +1,24 @@
1
+ // @bun
2
+ function b(e,t,r,s,n){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!n)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!n:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r}function i(e,t,r,s){if(r==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(e):s?s.value:t.get(e)}var Hr=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Hr=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,(s)=>(+s^r()&15>>+s/4).toString(16))};function dt(e){return typeof e==="object"&&e!==null&&(("name"in e)&&e.name==="AbortError"||("message"in e)&&String(e.message).includes("FetchRequestCanceledException"))}var pt=(e)=>{if(e instanceof Error)return e;if(typeof e==="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=Error(e.message,e.cause?{cause:e.cause}:{});if(e.stack)t.stack=e.stack;if(e.cause&&!t.cause)t.cause=e.cause;if(e.name)t.name=e.name;return t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};class m extends Error{}class O extends m{constructor(e,t,r,s){super(`${O.makeMessage(e,t,r)}`);this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let n=t;this.code=n?.code,this.param=n?.param,this.type=n?.type}static makeMessage(e,t,r){let s=t?.message?typeof t.message==="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;if(e&&s)return`${e} ${s}`;if(e)return`${e} status code (no body)`;if(s)return s;return"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new xe({message:r,cause:pt(t)});let n=t?.error;if(e===400)return new mt(e,n,r,s);if(e===401)return new _t(e,n,r,s);if(e===403)return new gt(e,n,r,s);if(e===404)return new yt(e,n,r,s);if(e===409)return new bt(e,n,r,s);if(e===422)return new wt(e,n,r,s);if(e===429)return new xt(e,n,r,s);if(e>=500)return new At(e,n,r,s);return new O(e,n,r,s)}}class F extends O{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class xe extends O{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);if(t)this.cause=t}}class Ae extends xe{constructor({message:e}={}){super({message:e??"Request timed out."})}}class mt extends O{}class _t extends O{}class gt extends O{}class yt extends O{}class bt extends O{}class wt extends O{}class xt extends O{}class At extends O{}class It extends m{constructor(){super("Could not parse response content as the length limit was reached")}}class Pt extends m{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class se extends Error{constructor(e){super(e)}}var jn=/^[a-z][a-z0-9+.-]*:/i,Cs=(e)=>jn.test(e),U=(e)=>(U=Array.isArray,U(e)),Jr=U;function Xr(e){if(typeof e!=="object")return{};return e??{}}function Es(e){if(!e)return!0;for(let t in e)return!1;return!0}function vs(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Be(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)}var $s=(e,t)=>{if(typeof t!=="number"||!Number.isInteger(t))throw new m(`${e} must be an integer`);if(t<0)throw new m(`${e} must be a positive integer`);return t};var ks=(e)=>{try{return JSON.parse(e)}catch(t){return}};var z=(e)=>new Promise((t)=>setTimeout(t,e));var fe="6.26.0";var Ns=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Dn(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var Wn=()=>{let e=Dn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"X-Stainless-OS":Ts(Deno.build.os),"X-Stainless-Arch":Os(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":fe,"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":fe,"X-Stainless-OS":Ts(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Os(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=qn();if(t)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function qn(){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 s=r.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,a=s[3]||0;return{browser:t,version:`${n}.${o}.${a}`}}}return null}var Os=(e)=>{if(e==="x32")return"x32";if(e==="x86_64"||e==="x64")return"x64";if(e==="arm")return"arm";if(e==="aarch64"||e==="arm64")return"arm64";if(e)return`other:${e}`;return"unknown"},Ts=(e)=>{if(e=e.toLowerCase(),e.includes("ios"))return"iOS";if(e==="android")return"Android";if(e==="darwin")return"MacOS";if(e==="win32")return"Windows";if(e==="freebsd")return"FreeBSD";if(e==="openbsd")return"OpenBSD";if(e==="linux")return"Linux";if(e)return`Other:${e}`;return"Unknown"},Fs,Ms=()=>Fs??(Fs=Wn());function Ls(){if(typeof fetch<"u")return fetch;throw 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 Vr(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function pr(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Vr({start(){},async pull(r){let{done:s,value:n}=await t.next();if(s)r.close();else r.enqueue(n)},async cancel(){await t.return?.()}})}function Kr(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();if(r?.done)t.releaseLock();return 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 Bs(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 Us=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var Gr="RFC3986",zr=(e)=>String(e),Qr={RFC1738:(e)=>String(e).replace(/%20/g,"+"),RFC3986:zr},js="RFC1738";var mr=(e,t)=>(mr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),mr(e,t)),Q=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();var Yr=1024,Ds=(e,t,r,s,n)=>{if(e.length===0)return e;let o=e;if(typeof e==="symbol")o=Symbol.prototype.toString.call(e);else if(typeof e!=="string")o=String(e);if(r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(f){return"%26%23"+parseInt(f.slice(2),16)+"%3B"});let a="";for(let f=0;f<o.length;f+=Yr){let d=o.length>=Yr?o.slice(f,f+Yr):o,_=[];for(let y=0;y<d.length;++y){let p=d.charCodeAt(y);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||n===js&&(p===40||p===41)){_[_.length]=d.charAt(y);continue}if(p<128){_[_.length]=Q[p];continue}if(p<2048){_[_.length]=Q[192|p>>6]+Q[128|p&63];continue}if(p<55296||p>=57344){_[_.length]=Q[224|p>>12]+Q[128|p>>6&63]+Q[128|p&63];continue}y+=1,p=65536+((p&1023)<<10|d.charCodeAt(y)&1023),_[_.length]=Q[240|p>>18]+Q[128|p>>12&63]+Q[128|p>>6&63]+Q[128|p&63]}a+=_.join("")}return a};function Ws(e){if(!e||typeof e!=="object")return!1;return!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Zr(e,t){if(U(e)){let r=[];for(let s=0;s<e.length;s+=1)r.push(t(e[s]));return r}return t(e)}var Hs={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Js=function(e,t){Array.prototype.push.apply(e,U(t)?t:[t])},qs,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ds,encodeValuesOnly:!1,format:Gr,formatter:zr,indices:!1,serializeDate(e){return(qs??(qs=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Xn(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="symbol"||typeof e==="bigint"}var es={};function Xs(e,t,r,s,n,o,a,f,d,_,y,p,u,w,g,R,S,I){let A=e,k=I,E=0,W=!1;while((k=k.get(es))!==void 0&&!W){let P=k.get(e);if(E+=1,typeof P<"u")if(P===E)throw RangeError("Cyclic object value");else W=!0;if(typeof k.get(es)>"u")E=0}if(typeof _==="function")A=_(t,A);else if(A instanceof Date)A=u?.(A);else if(r==="comma"&&U(A))A=Zr(A,function(P){if(P instanceof Date)return u?.(P);return P});if(A===null){if(o)return d&&!R?d(t,N.encoder,S,"key",w):t;A=""}if(Xn(A)||Ws(A)){if(d){let P=R?t:d(t,N.encoder,S,"key",w);return[g?.(P)+"="+g?.(d(A,N.encoder,S,"value",w))]}return[g?.(t)+"="+g?.(String(A))]}let T=[];if(typeof A>"u")return T;let C;if(r==="comma"&&U(A)){if(R&&d)A=Zr(A,d);C=[{value:A.length>0?A.join(",")||null:void 0}]}else if(U(_))C=_;else{let P=Object.keys(A);C=y?P.sort(y):P}let j=f?String(t).replace(/\./g,"%2E"):String(t),re=s&&U(A)&&A.length===1?j+"[]":j;if(n&&U(A)&&A.length===0)return re+"[]";for(let P=0;P<C.length;++P){let ue=C[P],Ss=typeof ue==="object"&&typeof ue.value<"u"?ue.value:A[ue];if(a&&Ss===null)continue;let qr=p&&f?ue.replace(/\./g,"%2E"):ue,Bn=U(A)?typeof r==="function"?r(re,qr):re:re+(p?"."+qr:"["+qr+"]");I.set(e,E);let Rs=new WeakMap;Rs.set(es,I),Js(T,Xs(Ss,Bn,r,s,n,o,a,f,r==="comma"&&R&&U(A)?null:d,_,y,p,u,w,g,R,S,Rs))}return T}function Vn(e=N){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!=="function")throw TypeError("Encoder has to be a function.");let t=e.charset||N.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Gr;if(typeof e.format<"u"){if(!mr(Qr,e.format))throw TypeError("Unknown format option provided.");r=e.format}let s=Qr[r],n=N.filter;if(typeof e.filter==="function"||U(e.filter))n=e.filter;let o;if(e.arrayFormat&&e.arrayFormat in Hs)o=e.arrayFormat;else if("indices"in e)o=e.indices?"indices":"repeat";else o=N.arrayFormat;if("commaRoundTrip"in e&&typeof e.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof e.allowDots>"u"?!!e.encodeDotInKeys===!0?!0:N.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==="boolean"?e.addQueryPrefix:N.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof e.allowEmptyArrays==="boolean"?!!e.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:o,charset:t,charsetSentinel:typeof e.charsetSentinel==="boolean"?e.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?N.delimiter:e.delimiter,encode:typeof e.encode==="boolean"?e.encode:N.encode,encodeDotInKeys:typeof e.encodeDotInKeys==="boolean"?e.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof e.encoder==="function"?e.encoder:N.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==="boolean"?e.encodeValuesOnly:N.encodeValuesOnly,filter:n,format:r,formatter:s,serializeDate:typeof e.serializeDate==="function"?e.serializeDate:N.serializeDate,skipNulls:typeof e.skipNulls==="boolean"?e.skipNulls:N.skipNulls,sort:typeof e.sort==="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling==="boolean"?e.strictNullHandling:N.strictNullHandling}}function Vs(e,t={}){let r=e,s=Vn(t),n,o;if(typeof s.filter==="function")o=s.filter,r=o("",r);else if(U(s.filter))o=s.filter,n=o;let a=[];if(typeof r!=="object"||r===null)return"";let f=Hs[s.arrayFormat],d=f==="comma"&&s.commaRoundTrip;if(!n)n=Object.keys(r);if(s.sort)n.sort(s.sort);let _=new WeakMap;for(let u=0;u<n.length;++u){let w=n[u];if(s.skipNulls&&r[w]===null)continue;Js(a,Xs(r[w],w,f,d,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,_))}let y=a.join(s.delimiter),p=s.addQueryPrefix===!0?"?":"";if(s.charsetSentinel)if(s.charset==="iso-8859-1")p+="utf8=%26%2310003%3B&";else p+="utf8=%E2%9C%93&";return y.length>0?p+y:""}function Ks(e){return Vs(e,{arrayFormat:"brackets"})}function Qs(e){let t=0;for(let n of e)t+=n.length;let r=new Uint8Array(t),s=0;for(let n of e)r.set(n,s),s+=n.length;return r}var Gs;function Ue(e){let t;return(Gs??(t=new globalThis.TextEncoder,Gs=t.encode.bind(t)))(e)}var zs;function ts(e){let t;return(zs??(t=new globalThis.TextDecoder,zs=t.decode.bind(t)))(e)}var q,H;class je{constructor(){q.set(this,void 0),H.set(this,void 0),b(this,q,new Uint8Array,"f"),b(this,H,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?Ue(e):e;b(this,q,Qs([i(this,q,"f"),t]),"f");let r=[],s;while((s=Gn(i(this,q,"f"),i(this,H,"f")))!=null){if(s.carriage&&i(this,H,"f")==null){b(this,H,s.index,"f");continue}if(i(this,H,"f")!=null&&(s.index!==i(this,H,"f")+1||s.carriage)){r.push(ts(i(this,q,"f").subarray(0,i(this,H,"f")-1))),b(this,q,i(this,q,"f").subarray(i(this,H,"f")),"f"),b(this,H,null,"f");continue}let n=i(this,H,"f")!==null?s.preceding-1:s.preceding,o=ts(i(this,q,"f").subarray(0,n));r.push(o),b(this,q,i(this,q,"f").subarray(s.index),"f"),b(this,H,null,"f")}return r}flush(){if(!i(this,q,"f").length)return[];return this.decode(`
3
+ `)}}q=new WeakMap,H=new WeakMap;je.NEWLINE_CHARS=new Set([`
4
+ `,"\r"]);je.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Gn(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Ys(e){for(let s=0;s<e.length-1;s++){if(e[s]===10&&e[s+1]===10)return s+2;if(e[s]===13&&e[s+1]===13)return s+2;if(e[s]===13&&e[s+1]===10&&s+3<e.length&&e[s+2]===13&&e[s+3]===10)return s+4}return-1}var gr={off:0,error:200,warn:300,info:400,debug:500},rs=(e,t,r)=>{if(!e)return;if(vs(gr,e))return e;v(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(gr))}`);return};function St(){}function _r(e,t,r){if(!t||gr[e]>gr[r])return St;else return t[e].bind(t)}var zn={error:St,warn:St,info:St,debug:St},Zs=new WeakMap;function v(e){let t=e.logger,r=e.logLevel??"off";if(!t)return zn;let s=Zs.get(t);if(s&&s[0]===r)return s[1];let n={error:_r("error",t,r),warn:_r("warn",t,r),info:_r("info",t,r),debug:_r("debug",t,r)};return Zs.set(t,[r,n]),n}var ne=(e)=>{if(e.options)e.options={...e.options},delete e.options.headers;if(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]));if("retryOfRequestLogID"in e){if(e.retryOfRequestLogID)e.retryOf=e.retryOfRequestLogID;delete e.retryOfRequestLogID}return e};var Rt;class J{constructor(e,t,r){this.iterator=e,Rt.set(this,void 0),this.controller=t,b(this,Rt,r,"f")}static fromSSEResponse(e,t,r,s){let n=!1,o=r?v(r):console;async function*a(){if(n)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let f=!1;try{for await(let d of Qn(e,t)){if(f)continue;if(d.data.startsWith("[DONE]")){f=!0;continue}if(d.event===null||!d.event.startsWith("thread.")){let _;try{_=JSON.parse(d.data)}catch(y){throw o.error("Could not parse message into JSON:",d.data),o.error("From chunk:",d.raw),y}if(_&&_.error)throw new O(void 0,_.error,void 0,e.headers);yield s?{event:d.event,data:_}:_}else{let _;try{_=JSON.parse(d.data)}catch(y){throw console.error("Could not parse message into JSON:",d.data),console.error("From chunk:",d.raw),y}if(d.event=="error")throw new O(void 0,_.error,_.message,void 0);yield{event:d.event,data:_}}}f=!0}catch(d){if(dt(d))return;throw d}finally{if(!f)t.abort()}}return new J(a,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*n(){let a=new je,f=Kr(e);for await(let d of f)for(let _ of a.decode(d))yield _;for(let d of a.flush())yield d}async function*o(){if(s)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(let f of n()){if(a)continue;if(f)yield JSON.parse(f)}a=!0}catch(f){if(dt(f))return;throw f}finally{if(!a)t.abort()}}return new J(o,t,r)}[(Rt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=(n)=>({next:()=>{if(n.length===0){let o=r.next();e.push(o),t.push(o)}return n.shift()}});return[new J(()=>s(e),this.controller,i(this,Rt,"f")),new J(()=>s(t),this.controller,i(this,Rt,"f"))]}toReadableStream(){let e=this,t;return Vr({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:n}=await t.next();if(n)return r.close();let o=Ue(JSON.stringify(s)+`
5
+ `);r.enqueue(o)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*Qn(e,t){if(!e.body){if(t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new m("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new m("Attempted to iterate over a response with no body")}let r=new en,s=new je,n=Kr(e.body);for await(let o of Yn(n))for(let a of s.decode(o)){let f=r.decode(a);if(f)yield f}for(let o of s.flush()){let a=r.decode(o);if(a)yield a}}async function*Yn(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let s=r instanceof ArrayBuffer?new Uint8Array(r):typeof r==="string"?Ue(r):r,n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),t=n;let o;while((o=Ys(t))!==-1)yield t.slice(0,o),t=t.slice(o)}if(t.length>0)yield t}class en{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r"))e=e.substring(0,e.length-1);if(!e){if(!this.event&&!this.data.length)return null;let n={event:this.event,data:this.data.join(`
6
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],n}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=Zn(e,":");if(s.startsWith(" "))s=s.substring(1);if(t==="event")this.event=s;else if(t==="data")this.data.push(s);return null}}function Zn(e,t){let r=e.indexOf(t);if(r!==-1)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}async function yr(e,t){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=t,a=await(async()=>{if(t.options.stream){if(v(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)return t.options.__streamClass.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData);return J.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData)}if(r.status===204)return null;if(t.options.__binaryResponse)return r;let d=r.headers.get("content-type")?.split(";")[0]?.trim();if(d?.includes("application/json")||d?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let u=await r.json();return ss(u,r)}return await r.text()})();return v(e).debug(`[${s}] response parsed`,ne({retryOfRequestLogID:n,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}function ss(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return e;return Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var Ct;class Ie extends Promise{constructor(e,t,r=yr){super((s)=>{s(null)});this.responsePromise=t,this.parseResponse=r,Ct.set(this,void 0),b(this,Ct,e,"f")}_thenUnwrap(e){return new Ie(i(this,Ct,"f"),this.responsePromise,async(t,r)=>ss(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then((e)=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((e)=>this.parseResponse(i(this,Ct,"f"),e));return this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Ct=new WeakMap;var br;class wr{constructor(e,t,r,s){br.set(this,void 0),b(this,br,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new m("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await i(this,br,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;yield e;while(e.hasNextPage())e=await e.getNextPage(),yield e}async*[(br=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class xr extends Ie{constructor(e,t,r){super(e,t,async(s,n)=>new r(s,n.response,await yr(s,n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}}class oe extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class x extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;if(!t)return null;return{...this.options,query:{...Xr(this.options.query),after:t}}}}class Y extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;if(!e)return null;return{...this.options,query:{...Xr(this.options.query),after:e}}}}var is=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node==="string"&&parseInt(e.versions.node.split("."))<20;throw 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 De(e,t,r){return is(),new File(e,t??"unknown_file",r)}function Et(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 Ar=(e)=>e!=null&&typeof e==="object"&&typeof e[Symbol.asyncIterator]==="function",ie=async(e,t)=>{if(!ns(e.body))return e;return{...e,body:await rn(e.body,t)}},V=async(e,t)=>({...e,body:await rn(e.body,t)}),tn=new WeakMap;function to(e){let t=typeof e==="function"?e:e.fetch,r=tn.get(t);if(r)return r;let s=(async()=>{try{let n="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;if(o.toString()===await new n(o).text())return!1;return!0}catch{return!0}})();return tn.set(t,s),s}var rn=async(e,t)=>{if(!await to(t))throw 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(([s,n])=>os(r,s,n))),r},sn=(e)=>e instanceof Blob&&("name"in e),ro=(e)=>typeof e==="object"&&e!==null&&(e instanceof Response||Ar(e)||sn(e)),ns=(e)=>{if(ro(e))return!0;if(Array.isArray(e))return e.some(ns);if(e&&typeof e==="object"){for(let t in e)if(ns(e[t]))return!0}return!1},os=async(e,t,r)=>{if(r===void 0)return;if(r==null)throw 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,De([await r.blob()],Et(r)));else if(Ar(r))e.append(t,De([await new Response(pr(r)).blob()],Et(r)));else if(sn(r))e.append(t,r,Et(r));else if(Array.isArray(r))await Promise.all(r.map((s)=>os(e,t+"[]",s)));else if(typeof r==="object")await Promise.all(Object.entries(r).map(([s,n])=>os(e,`${t}[${s}]`,n)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)};var nn=(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",so=(e)=>e!=null&&typeof e==="object"&&typeof e.name==="string"&&typeof e.lastModified==="number"&&nn(e),no=(e)=>e!=null&&typeof e==="object"&&typeof e.url==="string"&&typeof e.blob==="function";async function Ir(e,t,r){if(is(),e=await e,so(e)){if(e instanceof File)return e;return De([await e.arrayBuffer()],e.name)}if(no(e)){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),De(await as(n),t,r)}let s=await as(e);if(t||(t=Et(e)),!r?.type){let n=s.find((o)=>typeof o==="object"&&("type"in o)&&o.type);if(typeof n==="string")r={...r,type:n}}return De(s,t,r)}async function as(e){let t=[];if(typeof e==="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(nn(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ar(e))for await(let r of e)t.push(...await as(r));else{let r=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${oo(e)}`)}return t}function oo(e){if(typeof e!=="object"||e===null)return"";return`; props: [${Object.getOwnPropertyNames(e).map((r)=>`"${r}"`).join(", ")}]`}class c{constructor(e){this._client=e}}function an(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var on=Object.freeze(Object.create(null)),ao=(e=an)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],a=r.reduce((y,p,u)=>{if(/[?#]/.test(p))n=!0;let w=s[u],g=(n?encodeURIComponent:e)(""+w);if(u!==s.length&&(w==null||typeof w==="object"&&w.toString===Object.getPrototypeOf(Object.getPrototypeOf(w.hasOwnProperty??on)??on)?.toString))g=w+"",o.push({start:y.length+p.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`});return y+p+(u===s.length?"":g)},""),f=a.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,_;while((_=d.exec(f))!==null)o.push({start:_.index,length:_[0].length,error:`Value "${_[0]}" can't be safely passed as a path parameter`});if(o.sort((y,p)=>y.start-p.start),o.length>0){let y=0,p=o.reduce((u,w)=>{let g=" ".repeat(w.start-y),R="^".repeat(w.length);return y=w.start+w.length,u+g+R},"");throw new m(`Path parameters result in path with invalid segments:
7
+ ${o.map((u)=>u.error).join(`
8
+ `)}
9
+ ${a}
10
+ ${p}`)}return a},l=ao(an);class We extends c{list(e,t={},r){return this._client.getAPIList(l`/chat/completions/${e}/messages`,x,{query:t,...r})}}function vt(e){return e!==void 0&&"function"in e&&e.function!==void 0}function $t(e){return e?.$brand==="auto-parseable-response-format"}function Pe(e){return e?.$brand==="auto-parseable-tool"}function ln(e,t){if(!t||!ls(t))return{...e,choices:e.choices.map((r)=>(un(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))};return kt(e,t)}function kt(e,t){let r=e.choices.map((s)=>{if(s.finish_reason==="length")throw new It;if(s.finish_reason==="content_filter")throw new Pt;return un(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map((n)=>fo(t,n))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?uo(t,s.message.content):null}}});return{...e,choices:r}}function uo(e,t){if(e.response_format?.type!=="json_schema")return null;if(e.response_format?.type==="json_schema"){if("$parseRaw"in e.response_format)return e.response_format.$parseRaw(t);return JSON.parse(t)}return null}function fo(e,t){let r=e.tools?.find((s)=>vt(s)&&s.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Pe(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}}function cn(e,t){if(!e||!("tools"in e)||!e.tools)return!1;let r=e.tools?.find((s)=>vt(s)&&s.function?.name===t.function.name);return vt(r)&&(Pe(r)||r?.function.strict||!1)}function ls(e){if($t(e.response_format))return!0;return e.tools?.some((t)=>Pe(t)||t.type==="function"&&t.function.strict===!0)??!1}function un(e){for(let t of e||[])if(t.type!=="function")throw new m(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function fn(e){for(let t of e??[]){if(t.type!=="function")throw new m(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new m(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var qe=(e)=>e?.role==="assistant",cs=(e)=>e?.role==="tool";var us,Pr,Sr,Ot,Tt,Rr,Ft,ae,Nt,Cr,Er,He,hn;class Se{constructor(){us.add(this),this.controller=new AbortController,Pr.set(this,void 0),Sr.set(this,()=>{}),Ot.set(this,()=>{}),Tt.set(this,void 0),Rr.set(this,()=>{}),Ft.set(this,()=>{}),ae.set(this,{}),Nt.set(this,!1),Cr.set(this,!1),Er.set(this,!1),He.set(this,!1),b(this,Pr,new Promise((e,t)=>{b(this,Sr,e,"f"),b(this,Ot,t,"f")}),"f"),b(this,Tt,new Promise((e,t)=>{b(this,Rr,e,"f"),b(this,Ft,t,"f")}),"f"),i(this,Pr,"f").catch(()=>{}),i(this,Tt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},i(this,us,"m",hn).bind(this))},0)}_connected(){if(this.ended)return;i(this,Sr,"f").call(this),this._emit("connect")}get ended(){return i(this,Nt,"f")}get errored(){return i(this,Cr,"f")}get aborted(){return i(this,Er,"f")}abort(){this.controller.abort()}on(e,t){return(i(this,ae,"f")[e]||(i(this,ae,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=i(this,ae,"f")[e];if(!r)return this;let s=r.findIndex((n)=>n.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){return(i(this,ae,"f")[e]||(i(this,ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(b(this,He,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){b(this,He,!0,"f"),await i(this,Tt,"f")}_emit(e,...t){if(i(this,Nt,"f"))return;if(e==="end")b(this,Nt,!0,"f"),i(this,Rr,"f").call(this);let r=i(this,ae,"f")[e];if(r)i(this,ae,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!i(this,He,"f")&&!r?.length)Promise.reject(s);i(this,Ot,"f").call(this,s),i(this,Ft,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!i(this,He,"f")&&!r?.length)Promise.reject(s);i(this,Ot,"f").call(this,s),i(this,Ft,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Pr=new WeakMap,Sr=new WeakMap,Ot=new WeakMap,Tt=new WeakMap,Rr=new WeakMap,Ft=new WeakMap,ae=new WeakMap,Nt=new WeakMap,Cr=new WeakMap,Er=new WeakMap,He=new WeakMap,us=new WeakSet,hn=function(t){if(b(this,Cr,!0,"f"),t instanceof Error&&t.name==="AbortError")t=new F;if(t instanceof F)return b(this,Er,!0,"f"),this._emit("abort",t);if(t instanceof m)return this._emit("error",t);if(t instanceof Error){let r=new m(t.message);return r.cause=t,this._emit("error",r)}return this._emit("error",new m(String(t)))};function dn(e){return typeof e.parse==="function"}var D,fs,vr,hs,ds,ps,pn,mn,ho=10;class Mt extends Se{constructor(){super(...arguments);D.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;if(t)this._addMessage(t);return e}_addMessage(e,t=!0){if(!("content"in e))e.content=null;if(this.messages.push(e),t){if(this._emit("message",e),cs(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(qe(e)&&e.tool_calls){for(let r of e.tool_calls)if(r.type==="function")this._emit("functionToolCall",r.function)}}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new m("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),i(this,D,"m",fs).call(this)}async finalMessage(){return await this.done(),i(this,D,"m",vr).call(this)}async finalFunctionToolCall(){return await this.done(),i(this,D,"m",hs).call(this)}async finalFunctionToolCallResult(){return await this.done(),i(this,D,"m",ds).call(this)}async totalUsage(){return await this.done(),i(this,D,"m",ps).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];if(e)this._emit("finalChatCompletion",e);let t=i(this,D,"m",vr).call(this);if(t)this._emit("finalMessage",t);let r=i(this,D,"m",fs).call(this);if(r)this._emit("finalContent",r);let s=i(this,D,"m",hs).call(this);if(s)this._emit("finalFunctionToolCall",s);let n=i(this,D,"m",ds).call(this);if(n!=null)this._emit("finalFunctionToolCallResult",n);if(this._chatCompletions.some((o)=>o.usage))this._emit("totalUsage",i(this,D,"m",ps).call(this))}async _createChatCompletion(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,D,"m",pn).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(kt(n,t))}async _runChatCompletion(e,t,r){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let{tool_choice:n="auto",stream:o,...a}=t,f=typeof n!=="string"&&n.type==="function"&&n?.function?.name,{maxChatCompletions:d=ho}=r||{},_=t.tools.map((u)=>{if(Pe(u)){if(!u.$callback)throw new m("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:u.$callback,name:u.function.name,description:u.function.description||"",parameters:u.function.parameters,parse:u.$parseRaw,strict:!0}}}return u}),y={};for(let u of _)if(u.type==="function")y[u.function.name||u.function.function.name]=u.function;let p="tools"in t?_.map((u)=>u.type==="function"?{type:"function",function:{name:u.function.name||u.function.function.name,parameters:u.function.parameters,description:u.function.description,strict:u.function.strict}}:u):void 0;for(let u of t.messages)this._addMessage(u,!1);for(let u=0;u<d;++u){let g=(await this._createChatCompletion(e,{...a,tool_choice:n,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!g)throw new m("missing message in ChatCompletion response");if(!g.tool_calls?.length)return;for(let R of g.tool_calls){if(R.type!=="function")continue;let S=R.id,{name:I,arguments:A}=R.function,k=y[I];if(!k){let C=`Invalid tool_call: ${JSON.stringify(I)}. Available options are: ${Object.keys(y).map((j)=>JSON.stringify(j)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:S,content:C});continue}else if(f&&f!==I){let C=`Invalid tool_call: ${JSON.stringify(I)}. ${JSON.stringify(f)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:S,content:C});continue}let E;try{E=dn(k)?await k.parse(A):A}catch(C){let j=C instanceof Error?C.message:String(C);this._addMessage({role:"tool",tool_call_id:S,content:j});continue}let W=await k.function(E,this),T=i(this,D,"m",mn).call(this,W);if(this._addMessage({role:"tool",tool_call_id:S,content:T}),f)return}}return}}D=new WeakSet,fs=function(){return i(this,D,"m",vr).call(this).content??null},vr=function(){let t=this.messages.length;while(t-- >0){let r=this.messages[t];if(qe(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new m("stream ended without producing a ChatCompletionMessage with role=assistant")},hs=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(qe(r)&&r?.tool_calls?.length)return r.tool_calls.filter((s)=>s.type==="function").at(-1)?.function}return},ds=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(cs(r)&&r.content!=null&&typeof r.content==="string"&&this.messages.some((s)=>s.role==="assistant"&&s.tool_calls?.some((n)=>n.type==="function"&&n.id===r.tool_call_id)))return r.content}return},ps=function(){let t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)if(r)t.completion_tokens+=r.completion_tokens,t.prompt_tokens+=r.prompt_tokens,t.total_tokens+=r.total_tokens;return t},pn=function(t){if(t.n!=null&&t.n>1)throw new m("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},mn=function(t){return typeof t==="string"?t:t===void 0?"undefined":JSON.stringify(t)};class Lt extends Mt{static runTools(e,t,r){let s=new Lt,n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}_addMessage(e,t=!0){if(super._addMessage(e,t),qe(e)&&e.content)this._emit("content",e.content)}}var L={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};class _n extends Error{}class gn extends Error{}function po(e,t=L.ALL){if(typeof e!=="string")throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return mo(e.trim(),t)}var mo=(e,t)=>{let r=e.length,s=0,n=(u)=>{throw new _n(`${u} at position ${s}`)},o=(u)=>{throw new gn(`${u} at position ${s}`)},a=()=>{if(p(),s>=r)n("Unexpected end of input");if(e[s]==='"')return f();if(e[s]==="{")return d();if(e[s]==="[")return _();if(e.substring(s,s+4)==="null"||L.NULL&t&&r-s<4&&"null".startsWith(e.substring(s)))return s+=4,null;if(e.substring(s,s+4)==="true"||L.BOOL&t&&r-s<4&&"true".startsWith(e.substring(s)))return s+=4,!0;if(e.substring(s,s+5)==="false"||L.BOOL&t&&r-s<5&&"false".startsWith(e.substring(s)))return s+=5,!1;if(e.substring(s,s+8)==="Infinity"||L.INFINITY&t&&r-s<8&&"Infinity".startsWith(e.substring(s)))return s+=8,1/0;if(e.substring(s,s+9)==="-Infinity"||L.MINUS_INFINITY&t&&1<r-s&&r-s<9&&"-Infinity".startsWith(e.substring(s)))return s+=9,-1/0;if(e.substring(s,s+3)==="NaN"||L.NAN&t&&r-s<3&&"NaN".startsWith(e.substring(s)))return s+=3,NaN;return y()},f=()=>{let u=s,w=!1;s++;while(s<r&&(e[s]!=='"'||w&&e[s-1]==="\\"))w=e[s]==="\\"?!w:!1,s++;if(e.charAt(s)=='"')try{return JSON.parse(e.substring(u,++s-Number(w)))}catch(g){o(String(g))}else if(L.STR&t)try{return JSON.parse(e.substring(u,s-Number(w))+'"')}catch(g){return JSON.parse(e.substring(u,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},d=()=>{s++,p();let u={};try{while(e[s]!=="}"){if(p(),s>=r&&L.OBJ&t)return u;let w=f();p(),s++;try{let g=a();Object.defineProperty(u,w,{value:g,writable:!0,enumerable:!0,configurable:!0})}catch(g){if(L.OBJ&t)return u;else throw g}if(p(),e[s]===",")s++}}catch(w){if(L.OBJ&t)return u;else n("Expected '}' at end of object")}return s++,u},_=()=>{s++;let u=[];try{while(e[s]!=="]")if(u.push(a()),p(),e[s]===",")s++}catch(w){if(L.ARR&t)return u;n("Expected ']' at end of array")}return s++,u},y=()=>{if(s===0){if(e==="-"&&L.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e)}catch(w){if(L.NUM&t)try{if(e[e.length-1]===".")return JSON.parse(e.substring(0,e.lastIndexOf(".")));return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(g){}o(String(w))}}let u=s;if(e[s]==="-")s++;while(e[s]&&!",]}".includes(e[s]))s++;if(s==r&&!(L.NUM&t))n("Unterminated number literal");try{return JSON.parse(e.substring(u,s))}catch(w){if(e.substring(u,s)==="-"&&L.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e.substring(u,e.lastIndexOf("e")))}catch(g){o(String(g))}}},p=()=>{while(s<r&&`
11
+ \r `.includes(e[s]))s++};return a()},ms=(e)=>po(e,L.ALL^L.NUM);var M,le,Je,he,_s,$r,gs,ys,bs,kr,ws,yn;class de extends Mt{constructor(e){super();M.add(this),le.set(this,void 0),Je.set(this,void 0),he.set(this,void 0),b(this,le,e,"f"),b(this,Je,[],"f")}get currentChatCompletionSnapshot(){return i(this,he,"f")}static fromReadableStream(e){let t=new de(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let s=new de(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){super._createChatCompletion;let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,M,"m",_s).call(this);let n=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let o of n)i(this,M,"m",gs).call(this,o);if(n.controller.signal?.aborted)throw new F;return this._addChatCompletion(i(this,M,"m",kr).call(this))}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}i(this,M,"m",_s).call(this),this._connected();let s=J.fromReadableStream(e,this.controller),n;for await(let o of s){if(n&&n!==o.id)this._addChatCompletion(i(this,M,"m",kr).call(this));i(this,M,"m",gs).call(this,o),n=o.id}if(s.controller.signal?.aborted)throw new F;return this._addChatCompletion(i(this,M,"m",kr).call(this))}[(le=new WeakMap,Je=new WeakMap,he=new WeakMap,M=new WeakSet,_s=function(){if(this.ended)return;b(this,he,void 0,"f")},$r=function(t){let r=i(this,Je,"f")[t.index];if(r)return r;return r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},i(this,Je,"f")[t.index]=r,r},gs=function(t){if(this.ended)return;let r=i(this,M,"m",yn).call(this,t);this._emit("chunk",t,r);for(let s of t.choices){let n=r.choices[s.index];if(s.delta.content!=null&&n.message?.role==="assistant"&&n.message?.content)this._emit("content",s.delta.content,n.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:n.message.content,parsed:n.message.parsed});if(s.delta.refusal!=null&&n.message?.role==="assistant"&&n.message?.refusal)this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:n.message.refusal});if(s.logprobs?.content!=null&&n.message?.role==="assistant")this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:n.logprobs?.content??[]});if(s.logprobs?.refusal!=null&&n.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:n.logprobs?.refusal??[]});let o=i(this,M,"m",$r).call(this,n);if(n.finish_reason){if(i(this,M,"m",bs).call(this,n),o.current_tool_call_index!=null)i(this,M,"m",ys).call(this,n,o.current_tool_call_index)}for(let a of s.delta.tool_calls??[]){if(o.current_tool_call_index!==a.index){if(i(this,M,"m",bs).call(this,n),o.current_tool_call_index!=null)i(this,M,"m",ys).call(this,n,o.current_tool_call_index)}o.current_tool_call_index=a.index}for(let a of s.delta.tool_calls??[]){let f=n.message.tool_calls?.[a.index];if(!f?.type)continue;if(f?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:f.function?.name,index:a.index,arguments:f.function.arguments,parsed_arguments:f.function.parsed_arguments,arguments_delta:a.function?.arguments??""});else wn(f?.type)}}},ys=function(t,r){if(i(this,M,"m",$r).call(this,t).done_tool_calls.has(r))return;let n=t.message.tool_calls?.[r];if(!n)throw Error("no tool call snapshot");if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type==="function"){let o=i(this,le,"f")?.tools?.find((a)=>vt(a)&&a.function.name===n.function.name);this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:r,arguments:n.function.arguments,parsed_arguments:Pe(o)?o.$parseRaw(n.function.arguments):o?.function.strict?JSON.parse(n.function.arguments):null})}else wn(n.type)},bs=function(t){let r=i(this,M,"m",$r).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let s=i(this,M,"m",ws).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}if(t.message.refusal&&!r.refusal_done)r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal});if(t.logprobs?.content&&!r.logprobs_content_done)r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content});if(t.logprobs?.refusal&&!r.logprobs_refusal_done)r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal})},kr=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,he,"f");if(!t)throw new m("request ended without sending any chunks");return b(this,he,void 0,"f"),b(this,Je,[],"f"),_o(t,i(this,le,"f"))},ws=function(){let t=i(this,le,"f")?.response_format;if($t(t))return t;return null},yn=function(t){var r,s,n,o;let a=i(this,he,"f"),{choices:f,...d}=t;if(!a)a=b(this,he,{...d,choices:[]},"f");else Object.assign(a,d);for(let{delta:_,finish_reason:y,index:p,logprobs:u=null,...w}of t.choices){let g=a.choices[p];if(!g)g=a.choices[p]={finish_reason:y,index:p,message:{},logprobs:u,...w};if(u)if(!g.logprobs)g.logprobs=Object.assign({},u);else{let{content:W,refusal:T,...C}=u;if(bn(C),Object.assign(g.logprobs,C),W)(r=g.logprobs).content??(r.content=[]),g.logprobs.content.push(...W);if(T)(s=g.logprobs).refusal??(s.refusal=[]),g.logprobs.refusal.push(...T)}if(y){if(g.finish_reason=y,i(this,le,"f")&&ls(i(this,le,"f"))){if(y==="length")throw new It;if(y==="content_filter")throw new Pt}}if(Object.assign(g,w),!_)continue;let{content:R,refusal:S,function_call:I,role:A,tool_calls:k,...E}=_;if(bn(E),Object.assign(g.message,E),S)g.message.refusal=(g.message.refusal||"")+S;if(A)g.message.role=A;if(I)if(!g.message.function_call)g.message.function_call=I;else{if(I.name)g.message.function_call.name=I.name;if(I.arguments)(n=g.message.function_call).arguments??(n.arguments=""),g.message.function_call.arguments+=I.arguments}if(R){if(g.message.content=(g.message.content||"")+R,!g.message.refusal&&i(this,M,"m",ws).call(this))g.message.parsed=ms(g.message.content)}if(k){if(!g.message.tool_calls)g.message.tool_calls=[];for(let{index:W,id:T,type:C,function:j,...re}of k){let P=(o=g.message.tool_calls)[W]??(o[W]={});if(Object.assign(P,re),T)P.id=T;if(C)P.type=C;if(j)P.function??(P.function={name:j.name??"",arguments:""});if(j?.name)P.function.name=j.name;if(j?.arguments){if(P.function.arguments+=j.arguments,cn(i(this,le,"f"),P))P.function.parsed_arguments=ms(P.function.arguments)}}}}return a},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new J(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function _o(e,t){let{id:r,choices:s,created:n,model:o,system_fingerprint:a,...f}=e,d={...f,id:r,choices:s.map(({message:_,finish_reason:y,index:p,logprobs:u,...w})=>{if(!y)throw new m(`missing finish_reason for choice ${p}`);let{content:g=null,function_call:R,tool_calls:S,...I}=_,A=_.role;if(!A)throw new m(`missing role for choice ${p}`);if(R){let{arguments:k,name:E}=R;if(k==null)throw new m(`missing function_call.arguments for choice ${p}`);if(!E)throw new m(`missing function_call.name for choice ${p}`);return{...w,message:{content:g,function_call:{arguments:k,name:E},role:A,refusal:_.refusal??null},finish_reason:y,index:p,logprobs:u}}if(S)return{...w,index:p,finish_reason:y,logprobs:u,message:{...I,role:A,content:g,refusal:_.refusal??null,tool_calls:S.map((k,E)=>{let{function:W,type:T,id:C,...j}=k,{arguments:re,name:P,...ue}=W||{};if(C==null)throw new m(`missing choices[${p}].tool_calls[${E}].id
12
+ ${Or(e)}`);if(T==null)throw new m(`missing choices[${p}].tool_calls[${E}].type
13
+ ${Or(e)}`);if(P==null)throw new m(`missing choices[${p}].tool_calls[${E}].function.name
14
+ ${Or(e)}`);if(re==null)throw new m(`missing choices[${p}].tool_calls[${E}].function.arguments
15
+ ${Or(e)}`);return{...j,id:C,type:T,function:{...ue,name:P,arguments:re}}})}};return{...w,message:{...I,content:g,role:A,refusal:_.refusal??null},finish_reason:y,index:p,logprobs:u}}),created:n,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return ln(d,t)}function Or(e){return JSON.stringify(e)}function bn(e){return}function wn(e){}class Xe extends de{static fromReadableStream(e){let t=new Xe(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new Xe(t),n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}}class pe extends c{constructor(){super(...arguments);this.messages=new We(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(l`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(l`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/chat/completions/${e}`,t)}parse(e,t){return fn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((r)=>kt(r,e))}runTools(e,t){if(e.stream)return Xe.runTools(this._client,e,t);return Lt.runTools(this._client,e,t)}stream(e,t){return de.createChatCompletion(this._client,e,t)}}pe.Messages=We;class Re extends c{constructor(){super(...arguments);this.completions=new pe(this._client)}}Re.Completions=pe;var xn=Symbol("brand.privateNullableHeaders");function*yo(e){if(!e)return;if(xn in e){let{values:s,nulls:n}=e;yield*s.entries();for(let o of n)yield[o,null];return}let t=!1,r;if(e instanceof Headers)r=e.entries();else if(Jr(e))r=e;else t=!0,r=Object.entries(e??{});for(let s of r){let n=s[0];if(typeof n!=="string")throw TypeError("expected header name to be a string");let o=Jr(s[1])?s[1]:[s[1]],a=!1;for(let f of o){if(f===void 0)continue;if(t&&!a)a=!0,yield[n,null];yield[n,f]}}}var h=(e)=>{let t=new Headers,r=new Set;for(let s of e){let n=new Set;for(let[o,a]of yo(s)){let f=o.toLowerCase();if(!n.has(f))t.delete(o),n.add(f);if(a===null)t.delete(o),r.add(f);else t.append(o,a),r.delete(f)}}return{[xn]:!0,values:t,nulls:r}};class Bt extends c{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:h([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Ut extends c{create(e,t){return this._client.post("/audio/transcriptions",V({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class jt extends c{create(e,t){return this._client.post("/audio/translations",V({body:e,...t,__metadata:{model:e.model}},this._client))}}class ce extends c{constructor(){super(...arguments);this.transcriptions=new Ut(this._client),this.translations=new jt(this._client),this.speech=new Bt(this._client)}}ce.Transcriptions=Ut;ce.Translations=jt;ce.Speech=Bt;class Ve extends c{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(l`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",x,{query:e,...t})}cancel(e,t){return this._client.post(l`/batches/${e}/cancel`,t)}}class Dt extends c{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/assistants/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",x,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Wt extends c{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class qt extends c{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ce extends c{constructor(){super(...arguments);this.sessions=new Wt(this._client),this.transcriptionSessions=new qt(this._client)}}Ce.Sessions=Wt;Ce.TranscriptionSessions=qt;class Ht extends c{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(l`/chatkit/sessions/${e}/cancel`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}class Jt extends c{retrieve(e,t){return this._client.get(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",Y,{query:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(l`/chatkit/threads/${e}/items`,Y,{query:t,...r,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}}class Ee extends c{constructor(){super(...arguments);this.sessions=new Ht(this._client),this.threads=new Jt(this._client)}}Ee.Sessions=Ht;Ee.Threads=Jt;class Xt extends c{create(e,t,r){return this._client.post(l`/threads/${e}/messages`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/messages/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/messages`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:s}=t;return this._client.delete(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class Vt extends c{retrieve(e,t,r){let{thread_id:s,run_id:n,...o}=t;return this._client.get(l`/threads/${s}/runs/${n}/steps/${e}`,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:s,...n}=t;return this._client.getAPIList(l`/threads/${s}/runs/${e}/steps`,x,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}var An=(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,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=t.charCodeAt(n);return Array.from(new Float32Array(s.buffer))}};var K=(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();return};var B,$e,xs,Z,Tr,G,ke,Ge,ve,Mr,X,Fr,Nr,zt,Kt,Gt,In,Pn,Sn,Rn,Cn,En,vn;class me extends Se{constructor(){super(...arguments);B.add(this),xs.set(this,[]),Z.set(this,{}),Tr.set(this,{}),G.set(this,void 0),ke.set(this,void 0),Ge.set(this,void 0),ve.set(this,void 0),Mr.set(this,void 0),X.set(this,void 0),Fr.set(this,void 0),Nr.set(this,void 0),zt.set(this,void 0)}[(xs=new WeakMap,Z=new WeakMap,Tr=new WeakMap,G=new WeakMap,ke=new WeakMap,Ge=new WeakMap,ve=new WeakMap,Mr=new WeakMap,X=new WeakMap,Fr=new WeakMap,Nr=new WeakMap,zt=new WeakMap,B=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new $e;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}this._connected();let s=J.fromReadableStream(e,this.controller);for await(let n of s)i(this,B,"m",Kt).call(this,n);if(s.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}toReadableStream(){return new J(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let n=new $e;return n._run(()=>n._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createToolAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.submitToolOutputs(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,B,"m",Kt).call(this,f);if(a.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}static createThreadAssistantStream(e,t,r){let s=new $e;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let n=new $e;return n._run(()=>n._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}currentEvent(){return i(this,Fr,"f")}currentRun(){return i(this,Nr,"f")}currentMessageSnapshot(){return i(this,G,"f")}currentRunStepSnapshot(){return i(this,zt,"f")}async finalRunSteps(){return await this.done(),Object.values(i(this,Z,"f"))}async finalMessages(){return await this.done(),Object.values(i(this,Tr,"f"))}async finalRun(){if(await this.done(),!i(this,ke,"f"))throw Error("Final run was not received.");return i(this,ke,"f")}async _createThreadAssistantStream(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let a of o)i(this,B,"m",Kt).call(this,a);if(o.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}async _createAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,B,"m",Kt).call(this,f);if(a.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let n=e[r];if(n===null||n===void 0){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof n==="string"&&typeof s==="string")n+=s;else if(typeof n==="number"&&typeof s==="number")n+=s;else if(Be(n)&&Be(s))n=this.accumulateDelta(n,s);else if(Array.isArray(n)&&Array.isArray(s)){if(n.every((o)=>typeof o==="string"||typeof o==="number")){n.push(...s);continue}for(let o of s){if(!Be(o))throw Error(`Expected array delta entry to be an object but got: ${o}`);let a=o.index;if(a==null)throw console.error(o),Error("Expected array delta entry to have an `index` property");if(typeof a!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let f=n[a];if(f==null)n.push(o);else n[a]=this.accumulateDelta(f,o)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${n}`);e[r]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}}$e=me,Kt=function(t){if(this.ended)return;switch(b(this,Fr,t,"f"),i(this,B,"m",Sn).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":i(this,B,"m",vn).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":i(this,B,"m",Pn).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":i(this,B,"m",In).call(this,t);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:ko(t)}},Gt=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");if(!i(this,ke,"f"))throw Error("Final run has not been received");return i(this,ke,"f")},In=function(t){let[r,s]=i(this,B,"m",Cn).call(this,t,i(this,G,"f"));b(this,G,r,"f"),i(this,Tr,"f")[r.id]=r;for(let n of s){let o=r.content[n.index];if(o?.type=="text")this._emit("textCreated",o.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 n of t.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,a=r.content[n.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=i(this,Ge,"f")){if(i(this,ve,"f"))switch(i(this,ve,"f").type){case"text":this._emit("textDone",i(this,ve,"f").text,i(this,G,"f"));break;case"image_file":this._emit("imageFileDone",i(this,ve,"f").image_file,i(this,G,"f"));break}b(this,Ge,n.index,"f")}b(this,ve,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(i(this,Ge,"f")!==void 0){let n=t.data.content[i(this,Ge,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,i(this,G,"f"));break;case"text":this._emit("textDone",n.text,i(this,G,"f"));break}}if(i(this,G,"f"))this._emit("messageDone",t.data);b(this,G,void 0,"f")}},Pn=function(t){let r=i(this,B,"m",Rn).call(this,t);switch(b(this,zt,r,"f"),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":let s=t.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of s.step_details.tool_calls)if(o.index==i(this,Mr,"f"))this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]);else{if(i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f"));if(b(this,Mr,o.index,"f"),b(this,X,r.step_details.tool_calls[o.index],"f"),i(this,X,"f"))this._emit("toolCallCreated",i(this,X,"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":if(b(this,zt,void 0,"f"),t.data.step_details.type=="tool_calls"){if(i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f")),b(this,X,void 0,"f")}this._emit("runStepDone",t.data,r);break;case"thread.run.step.in_progress":break}},Sn=function(t){i(this,xs,"f").push(t),this._emit("event",t)},Rn=function(t){switch(t.event){case"thread.run.step.created":return i(this,Z,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let r=i(this,Z,"f")[t.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let s=t.data;if(s.delta){let n=$e.accumulateDelta(r,s.delta);i(this,Z,"f")[t.data.id]=n}return i(this,Z,"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":i(this,Z,"f")[t.data.id]=t.data;break}if(i(this,Z,"f")[t.data.id])return i(this,Z,"f")[t.data.id];throw Error("No snapshot available")},Cn=function(t,r){let s=[];switch(t.event){case"thread.message.created":return[t.data,s];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=t.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in r.content){let a=r.content[o.index];r.content[o.index]=i(this,B,"m",En).call(this,o,a)}else r.content[o.index]=o,s.push(o);return[r,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,s];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},En=function(t,r){return $e.accumulateDelta(r,t)},vn=function(t){switch(b(this,Nr,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":if(b(this,ke,t.data,"f"),i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f")),b(this,X,void 0,"f");break;case"thread.run.cancelling":break}};function ko(e){}class ze extends c{constructor(){super(...arguments);this.steps=new Vt(this._client)}create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/threads/${e}/runs`,{query:{include:s},body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/runs/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/runs`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:s}=t;return this._client.post(l`/threads/${s}/runs/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return me.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(n.status){case"queued":case"in_progress":case"cancelling":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return n}}}stream(e,t,r){return me.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,r){let s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return me.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}}ze.Steps=Vt;class Oe extends c{constructor(){super(...arguments);this.runs=new ze(this._client),this.messages=new Xt(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/threads/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return me.createThreadAssistantStream(e,this._client.beta.threads,t)}}Oe.Runs=ze;Oe.Messages=Xt;class ee extends c{constructor(){super(...arguments);this.realtime=new Ce(this._client),this.chatkit=new Ee(this._client),this.assistants=new Dt(this._client),this.threads=new Oe(this._client)}}ee.Realtime=Ce;ee.ChatKit=Ee;ee.Assistants=Dt;ee.Threads=Oe;class Qe extends c{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Qt extends c{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class Ye extends c{constructor(){super(...arguments);this.content=new Qt(this._client)}create(e,t,r){return this._client.post(l`/containers/${e}/files`,ie({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/containers/${e}/files`,x,{query:t,...r})}delete(e,t,r){let{container_id:s}=t;return this._client.delete(l`/containers/${s}/files/${e}`,{...r,headers:h([{Accept:"*/*"},r?.headers])})}}Ye.Content=Qt;class Te extends c{constructor(){super(...arguments);this.files=new Ye(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(l`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/containers/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}}Te.Files=Ye;class Yt extends c{create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/conversations/${e}/items`,{query:{include:s},body:n,...r})}retrieve(e,t,r){let{conversation_id:s,...n}=t;return this._client.get(l`/conversations/${s}/items/${e}`,{query:n,...r})}list(e,t={},r){return this._client.getAPIList(l`/conversations/${e}/items`,Y,{query:t,...r})}delete(e,t,r){let{conversation_id:s}=t;return this._client.delete(l`/conversations/${s}/items/${e}`,r)}}class Fe extends c{constructor(){super(...arguments);this.items=new Yt(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(l`/conversations/${e}`,t)}update(e,t,r){return this._client.post(l`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(l`/conversations/${e}`,t)}}Fe.Items=Yt;class Ze extends c{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";if(r)v(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let n=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});if(r)return n;return v(this._client).debug("embeddings/decoding base64 embeddings from base64"),n._thenUnwrap((o)=>{if(o&&o.data)o.data.forEach((a)=>{let f=a.embedding;a.embedding=An(f)});return o})}}class Zt extends c{retrieve(e,t,r){let{eval_id:s,run_id:n}=t;return this._client.get(l`/evals/${s}/runs/${n}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...n}=t;return this._client.getAPIList(l`/evals/${s}/runs/${e}/output_items`,x,{query:n,...r})}}class et extends c{constructor(){super(...arguments);this.outputItems=new Zt(this._client)}create(e,t,r){return this._client.post(l`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(l`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/evals/${e}/runs`,x,{query:t,...r})}delete(e,t,r){let{eval_id:s}=t;return this._client.delete(l`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:s}=t;return this._client.post(l`/evals/${s}/runs/${e}`,r)}}et.OutputItems=Zt;class Ne extends c{constructor(){super(...arguments);this.runs=new et(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(l`/evals/${e}`,t)}update(e,t,r){return this._client.post(l`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/evals/${e}`,t)}}Ne.Runs=et;class tt extends c{create(e,t){return this._client.post("/files",V({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/files/${e}`,t)}content(e,t){return this._client.get(l`/files/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5000,maxWait:r=1800000}={}){let s=new Set(["processed","error","deleted"]),n=Date.now(),o=await this.retrieve(e);while(!o.status||!s.has(o.status))if(await z(t),o=await this.retrieve(e),Date.now()-n>r)throw new Ae({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return o}}class er extends c{}class tr extends c{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}}class rt extends c{constructor(){super(...arguments);this.graders=new tr(this._client)}}rt.Graders=tr;class rr extends c{create(e,t,r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,oe,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,Y,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(l`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}class st extends c{constructor(){super(...arguments);this.permissions=new rr(this._client)}}st.Permissions=rr;class sr extends c{list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,x,{query:t,...r})}}class nt extends c{constructor(){super(...arguments);this.checkpoints=new sr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(l`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",x,{query:e,...t})}cancel(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/events`,x,{query:t,...r})}pause(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/resume`,t)}}nt.Checkpoints=sr;class te extends c{constructor(){super(...arguments);this.methods=new er(this._client),this.jobs=new nt(this._client),this.checkpoints=new st(this._client),this.alpha=new rt(this._client)}}te.Methods=er;te.Jobs=nt;te.Checkpoints=st;te.Alpha=rt;class nr extends c{}class Me extends c{constructor(){super(...arguments);this.graderModels=new nr(this._client)}}Me.GraderModels=nr;class ot extends c{createVariation(e,t){return this._client.post("/images/variations",V({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",V({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class it extends c{retrieve(e,t){return this._client.get(l`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",oe,e)}delete(e,t){return this._client.delete(l`/models/${e}`,t)}}class at extends c{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class or extends c{accept(e,t,r){return this._client.post(l`/realtime/calls/${e}/accept`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(l`/realtime/calls/${e}/hangup`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(l`/realtime/calls/${e}/refer`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(l`/realtime/calls/${e}/reject`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}}class ir extends c{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class _e extends c{constructor(){super(...arguments);this.clientSecrets=new ir(this._client),this.calls=new or(this._client)}}_e.ClientSecrets=ir;_e.Calls=or;function $n(e,t){if(!t||!zo(t))return{...e,output_parsed:null,output:e.output.map((r)=>{if(r.type==="function_call")return{...r,parsed_arguments:null};if(r.type==="message")return{...r,content:r.content.map((s)=>({...s,parsed:null}))};else return r})};return As(e,t)}function As(e,t){let r=e.output.map((n)=>{if(n.type==="function_call")return{...n,parsed_arguments:Zo(t,n)};if(n.type==="message"){let o=n.content.map((a)=>{if(a.type==="output_text")return{...a,parsed:Go(t,a.text)};return a});return{...n,content:o}}return n}),s=Object.assign({},e,{output:r});if(!Object.getOwnPropertyDescriptor(e,"output_text"))Lr(s);return Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(let n of s.output){if(n.type!=="message")continue;for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),s}function Go(e,t){if(e.text?.format?.type!=="json_schema")return null;if("$parseRaw"in e.text?.format)return(e.text?.format).$parseRaw(t);return JSON.parse(t)}function zo(e){if($t(e.text?.format))return!0;return!1}function Qo(e){return e?.$brand==="auto-parseable-tool"}function Yo(e,t){return e.find((r)=>r.type==="function"&&r.name===t)}function Zo(e,t){let r=Yo(e.tools??[],t.name);return{...t,...t,parsed_arguments:Qo(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function Lr(e){let t=[];for(let r of e.output){if(r.type!=="message")continue;for(let s of r.content)if(s.type==="output_text")t.push(s.text)}e.output_text=t.join("")}var lt,Br,ge,Ur,kn,On,Tn,Fn;class jr extends Se{constructor(e){super();lt.add(this),Br.set(this,void 0),ge.set(this,void 0),Ur.set(this,void 0),b(this,Br,e,"f")}static createResponse(e,t,r){let s=new jr(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,lt,"m",kn).call(this);let n,o=null;if("response_id"in t)n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null;else n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let a of n)i(this,lt,"m",On).call(this,a,o);if(n.controller.signal?.aborted)throw new F;return i(this,lt,"m",Tn).call(this)}[(Br=new WeakMap,ge=new WeakMap,Ur=new WeakMap,lt=new WeakSet,kn=function(){if(this.ended)return;b(this,ge,void 0,"f")},On=function(t,r){if(this.ended)return;let s=(o,a)=>{if(r==null||a.sequence_number>r)this._emit(o,a)},n=i(this,lt,"m",Fn).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let o=n.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="message"){let a=o.content[t.content_index];if(!a)throw new m(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new m(`expected content to be 'output_text', got ${a.type}`);s("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let o=n.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="function_call")s("response.function_call_arguments.delta",{...t,snapshot:o.arguments});break}default:s(t.type,t);break}},Tn=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,ge,"f");if(!t)throw new m("request ended without sending any events");b(this,ge,void 0,"f");let r=ei(t,i(this,Br,"f"));return b(this,Ur,r,"f"),r},Fn=function(t){let r=i(this,ge,"f");if(!r){if(t.type!=="response.created")throw new m(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=b(this,ge,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);let n=s.type,o=t.part;if(n==="message"&&o.type!=="reasoning_text")s.content.push(o);else if(n==="reasoning"&&o.type==="reasoning_text"){if(!s.content)s.content=[];s.content.push(o)}break}case"response.output_text.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="message"){let n=s.content[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="output_text")throw new m(`expected content to be 'output_text', got ${n.type}`);n.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="function_call")s.arguments+=t.delta;break}case"response.reasoning_text.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="reasoning"){let n=s.content?.[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="reasoning_text")throw new m(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=t.delta}break}case"response.completed":{b(this,ge,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=i(this,Ur,"f");if(!e)throw new m("stream ended without producing a ChatCompletion");return e}}function ei(e,t){return $n(e,t)}class ar extends c{list(e,t={},r){return this._client.getAPIList(l`/responses/${e}/input_items`,x,{query:t,...r})}}class lr extends c{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class ye extends c{constructor(){super(...arguments);this.inputItems=new ar(this._client),this.inputTokens=new lr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap((r)=>{if("object"in r&&r.object==="response")Lr(r);return r})}retrieve(e,t={},r){return this._client.get(l`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap((s)=>{if("object"in s&&s.object==="response")Lr(s);return s})}delete(e,t){return this._client.delete(l`/responses/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((r)=>As(r,e))}stream(e,t){return jr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(l`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}}ye.InputItems=ar;ye.InputTokens=lr;class cr extends c{retrieve(e,t){return this._client.get(l`/skills/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}}class ur extends c{retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class ct extends c{constructor(){super(...arguments);this.content=new ur(this._client)}create(e,t={},r){return this._client.post(l`/skills/${e}/versions`,ie({body:t,...r},this._client))}retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/skills/${e}/versions`,x,{query:t,...r})}delete(e,t,r){let{skill_id:s}=t;return this._client.delete(l`/skills/${s}/versions/${e}`,r)}}ct.Content=ur;class be extends c{constructor(){super(...arguments);this.content=new cr(this._client),this.versions=new ct(this._client)}create(e={},t){return this._client.post("/skills",ie({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/skills/${e}`,t)}update(e,t,r){return this._client.post(l`/skills/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/skills",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/skills/${e}`,t)}}be.Content=cr;be.Versions=ct;class fr extends c{create(e,t,r){return this._client.post(l`/uploads/${e}/parts`,V({body:t,...r},this._client))}}class Le extends c{constructor(){super(...arguments);this.parts=new fr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(l`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(l`/uploads/${e}/complete`,{body:t,...r})}}Le.Parts=fr;var Nn=async(e)=>{let t=await Promise.allSettled(e),r=t.filter((n)=>n.status==="rejected");if(r.length){for(let n of r)console.error(n.reason);throw Error(`${r.length} promise(s) failed - see the above errors`)}let s=[];for(let n of t)if(n.status==="fulfilled")s.push(n.value);return s};class hr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/file_batches`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/file_batches/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:s}=t;return this._client.post(l`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){let{vector_store_id:s,...n}=t;return this._client.getAPIList(l`/vector_stores/${s}/file_batches/${e}/files`,x,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(n.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"failed":case"cancelled":case"completed":return n}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let n=s?.maxConcurrency??5,o=Math.min(n,t.length),a=this._client,f=t.values(),d=[...r];async function _(p){for(let u of p){let w=await a.files.create({file:u,purpose:"assistants"},s);d.push(w.id)}}let y=Array(o).fill(f).map(_);return await Nn(y),await this.createAndPoll(e,{file_ids:d})}}class dr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/files`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:s,...n}=t;return this._client.post(l`/vector_stores/${s}/files/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/vector_stores/${e}/files`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:s}=t;return this._client.delete(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let n=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),o=n.data;switch(o.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=n.response.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"failed":case"completed":return o}}}async upload(e,t,r){let s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){let s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){let{vector_store_id:s}=t;return this._client.getAPIList(l`/vector_stores/${s}/files/${e}/content`,oe,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class we extends c{constructor(){super(...arguments);this.files=new dr(this._client),this.fileBatches=new hr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/vector_stores/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",x,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(l`/vector_stores/${e}/search`,oe,{body:t,method:"post",...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}we.Files=dr;we.FileBatches=hr;class ut extends c{create(e,t){return this._client.post("/videos",ie({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",Y,{query:e,...t})}delete(e,t){return this._client.delete(l`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(l`/videos/${e}/content`,{query:t,...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(l`/videos/${e}/remix`,ie({body:t,...r},this._client))}}var ft,Mn,Dr;class ht extends c{constructor(){super(...arguments);ft.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");i(this,ft,"m",Mn).call(this,r);let n=h([t]).values,o=i(this,ft,"m",Dr).call(this,n,"webhook-signature"),a=i(this,ft,"m",Dr).call(this,n,"webhook-timestamp"),f=i(this,ft,"m",Dr).call(this,n,"webhook-id"),d=parseInt(a,10);if(isNaN(d))throw new se("Invalid webhook timestamp format");let _=Math.floor(Date.now()/1000);if(_-d>s)throw new se("Webhook timestamp is too old");if(d>_+s)throw new se("Webhook timestamp is too new");let y=o.split(" ").map((g)=>g.startsWith("v1,")?g.substring(3):g),p=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),u=f?`${f}.${a}.${e}`:`${a}.${e}`,w=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let g of y)try{let R=Buffer.from(g,"base64");if(await crypto.subtle.verify("HMAC",w,R,new TextEncoder().encode(u)))return}catch{continue}throw new se("The given webhook signature does not match the expected signature")}}ft=new WeakSet,Mn=function(t){if(typeof t!=="string"||t.length===0)throw 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")},Dr=function(t,r){if(!t)throw Error("Headers are required");let s=t.get(r);if(s===null||s===void 0)throw Error(`Missing required header: ${r}`);return s};var Is,Ps,Wr,Ln;class Ke{constructor({baseURL:e=K("OPENAI_BASE_URL"),apiKey:t=K("OPENAI_API_KEY"),organization:r=K("OPENAI_ORG_ID")??null,project:s=K("OPENAI_PROJECT_ID")??null,webhookSecret:n=K("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(Is.add(this),Wr.set(this,void 0),this.completions=new Qe(this),this.chat=new Re(this),this.embeddings=new Ze(this),this.files=new tt(this),this.images=new ot(this),this.audio=new ce(this),this.moderations=new at(this),this.models=new it(this),this.fineTuning=new te(this),this.graders=new Me(this),this.vectorStores=new we(this),this.webhooks=new ht(this),this.beta=new ee(this),this.batches=new Ve(this),this.uploads=new Le(this),this.responses=new ye(this),this.realtime=new _e(this),this.conversations=new Fe(this),this.evals=new Ne(this),this.containers=new Te(this),this.skills=new be(this),this.videos=new ut(this),t===void 0)throw new m("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:t,organization:r,project:s,webhookSecret:n,...o,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&Ns())throw new m(`It looks like you're running in a browser-like environment.
16
+
17
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
18
+ If you understand the risks and have appropriate mitigations in place,
19
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
20
+
21
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
22
+
23
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
24
+ `);this.baseURL=a.baseURL,this.timeout=a.timeout??Ps.DEFAULT_TIMEOUT,this.logger=a.logger??console;let f="warn";this.logLevel=f,this.logLevel=rs(a.logLevel,"ClientOptions.logLevel",this)??rs(K("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??f,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Ls(),b(this,Wr,Us,"f"),this._options=a,this.apiKey=typeof t==="string"?t:"Missing Key",this.organization=r,this.project=s,this.webhookSecret=n}withOptions(e){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,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){return}async authHeaders(e){return h([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Ks(e)}getUserAgent(){return`${this.constructor.name}/JS ${fe}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hr()}`}makeStatusError(e,t,r,s){return O.generate(e,t,r,s)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=="function")return!1;let t;try{t=await e()}catch(r){if(r instanceof m)throw r;throw new m(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!=="string"||!t)throw new m(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let s=!i(this,Is,"m",Ln).call(this)&&r||this.baseURL,n=Cs(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();if(!Es(o))t={...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Ie(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:a,timeout:f}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:a,options:s});let d="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),_=r===void 0?"":`, retryOf: ${r}`,y=Date.now();if(v(this).debug(`[${d}] sending request`,ne({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:o.headers})),s.signal?.aborted)throw new F;let p=new AbortController,u=await this.fetchWithTimeout(a,o,f,p).catch(pt),w=Date.now();if(u instanceof globalThis.Error){let S=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new F;let I=dt(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return v(this).info(`[${d}] connection ${I?"timed out":"failed"} - ${S}`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (${S})`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),this.retryRequest(s,t,r??d);if(v(this).info(`[${d}] connection ${I?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (error; no more retries left)`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),I)throw new Ae;throw new xe({cause:u})}let g=[...u.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,I])=>", "+S+": "+JSON.stringify(I)).join(""),R=`[${d}${_}${g}] ${o.method} ${a} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${w-y}ms`;if(!u.ok){let S=await this.shouldRetry(u);if(t&&S){let T=`retrying, ${t} attempts remaining`;return await Bs(u.body),v(this).info(`${R} - ${T}`),v(this).debug(`[${d}] response error (${T})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),this.retryRequest(s,t,r??d,u.headers)}let I=S?"error; no more retries left":"error; not retryable";v(this).info(`${R} - ${I}`);let A=await u.text().catch((T)=>pt(T).message),k=ks(A),E=k?void 0:A;throw v(this).debug(`[${d}] response error (${I})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,message:E,durationMs:Date.now()-y})),this.makeStatusError(u.status,k,E,u.headers)}return v(this).info(R),v(this).debug(`[${d}] response start`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),{response:u,options:s,controller:p,requestLogID:d,retryOfRequestLogID:r,startTime:y}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new xr(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...a}=t||{},f=this._makeAbort(s);if(n)n.addEventListener("abort",f,{once:!0});let d=setTimeout(f,r),_=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body==="object"&&a.body!==null&&Symbol.asyncIterator in a.body,y={signal:s.signal,..._?{duplex:"half"}:{},method:"GET",...a};if(o)y.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,y)}finally{clearTimeout(d)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,r,s){let n,o=s?.get("retry-after-ms");if(o){let f=parseFloat(o);if(!Number.isNaN(f))n=f}let a=s?.get("retry-after");if(a&&!n){let f=parseFloat(a);if(!Number.isNaN(f))n=f*1000;else n=Date.parse(a)-Date.now()}if(n===void 0){let f=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,f)}return await z(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),a=1-Math.random()*0.25;return o*a*1000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:a}=r,f=this.buildURL(n,o,a);if("timeout"in r)$s("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:_}=this.buildBody({options:r}),y=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:y,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...r.fetchOptions??{}},url:f,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let o=h([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Ms(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=h([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:pr(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return i(this,Wr,"f").call(this,{body:e,headers:r})}}Ps=Ke,Wr=new WeakMap,Is=new WeakSet,Ln=function(){return this.baseURL!=="https://api.openai.com/v1"};Ke.OpenAI=Ps;Ke.DEFAULT_TIMEOUT=600000;Ke.OpenAIError=m;Ke.APIError=O;Ke.APIConnectionError=xe;Ke.APIConnectionTimeoutError=Ae;Ke.APIUserAbortError=F;Ke.NotFoundError=yt;Ke.ConflictError=bt;Ke.RateLimitError=xt;Ke.BadRequestError=mt;Ke.AuthenticationError=_t;Ke.InternalServerError=At;Ke.PermissionDeniedError=gt;Ke.UnprocessableEntityError=wt;Ke.InvalidWebhookSignatureError=se;Ke.toFile=Ir;Ke.Completions=Qe;Ke.Chat=Re;Ke.Embeddings=Ze;Ke.Files=tt;Ke.Images=ot;Ke.Audio=ce;Ke.Moderations=at;Ke.Models=it;Ke.FineTuning=te;Ke.Graders=Me;Ke.VectorStores=we;Ke.Webhooks=ht;Ke.Beta=ee;Ke.Batches=Ve;Ke.Uploads=Le;Ke.Responses=ye;Ke.Realtime=_e;Ke.Conversations=Fe;Ke.Evals=Ne;Ke.Containers=Te;Ke.Skills=be;Ke.Videos=ut;class pu extends Ke{constructor({baseURL:e=K("OPENAI_BASE_URL"),apiKey:t=K("AZURE_OPENAI_API_KEY"),apiVersion:r=K("OPENAI_API_VERSION"),endpoint:s,deployment:n,azureADTokenProvider:o,dangerouslyAllowBrowser:a,...f}={}){if(!r)throw new m("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof o==="function")a=!0;if(!o&&!t)throw new m("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&t)throw new m("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(f.defaultQuery={...f.defaultQuery,"api-version":r},!e){if(!s)s=process.env.AZURE_OPENAI_ENDPOINT;if(!s)throw new m("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}else if(s)throw new m("baseURL and endpoint are mutually exclusive");super({apiKey:o??t,baseURL:e,...f,...a!==void 0?{dangerouslyAllowBrowser:a}:{}});this.apiVersion="",this.apiVersion=r,this.deploymentName=n}async buildRequest(e,t={}){if(ui.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!Be(e.body))throw Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;if(r!==void 0&&!this.baseURL.includes("/deployments"))e.path=`/deployments/${r}${e.path}`}return super.buildRequest(e,t)}async authHeaders(e){if(typeof this._options.apiKey==="string")return h([{"api-key":this.apiKey}]);return super.authHeaders(e)}}var ui=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);export{Ke,pu};