@cortex-agent/server 2026.11.17 → 2026.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (338) hide show
  1. package/README.md +5 -5
  2. package/THIRD_PARTY_NOTICES.txt +860 -294
  3. package/defaults/hooks/quota-stop.mjs +37 -0
  4. package/defaults/prompts/clean-workspace.md +5 -0
  5. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  6. package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
  7. package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
  8. package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
  9. package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
  10. package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
  11. package/dist/chunks/chunk-24DH4IR5.js +4 -0
  12. package/dist/chunks/chunk-25XKBRDT.js +70 -0
  13. package/dist/chunks/{chunk-VTL3Z2OP.js → chunk-2ABET62E.js} +1 -1
  14. package/dist/chunks/chunk-2BVUA256.js +4 -0
  15. package/dist/chunks/{chunk-4YLAGSDM.js → chunk-2WFL62UO.js} +1 -1
  16. package/dist/chunks/{chunk-LQTFDC67.js → chunk-335SSANX.js} +1 -1
  17. package/dist/chunks/chunk-377OPTXX.js +17 -0
  18. package/dist/chunks/chunk-3EZNVLBF.js +129 -0
  19. package/dist/chunks/{chunk-V6X7Y62J.js → chunk-3O6ZG5HA.js} +1 -1
  20. package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
  21. package/dist/chunks/{chunk-2ATTYCRJ.js → chunk-4HRI75GU.js} +1 -1
  22. package/dist/chunks/chunk-4JBYLRPM.js +57 -0
  23. package/dist/chunks/chunk-4KKV7VKE.js +4 -0
  24. package/dist/chunks/chunk-4KQHDDC5.js +4 -0
  25. package/dist/chunks/chunk-4SWD4JMP.js +33 -0
  26. package/dist/chunks/chunk-52VCLZS5.js +4 -0
  27. package/dist/chunks/chunk-54P7TSY3.js +10 -0
  28. package/dist/chunks/chunk-5DVSAXOI.js +7 -0
  29. package/dist/chunks/chunk-5F3A62YS.js +4 -0
  30. package/dist/chunks/{chunk-S3MR37DL.js → chunk-5FHETFZM.js} +1 -1
  31. package/dist/chunks/{chunk-CEGSDGYQ.js → chunk-5LBLRAHS.js} +1 -1
  32. package/dist/chunks/chunk-5UYVNA3W.js +4 -0
  33. package/dist/chunks/chunk-6G3OYMCV.js +21 -0
  34. package/dist/chunks/chunk-7GGPYU5E.js +30 -0
  35. package/dist/chunks/chunk-7TYSMLUV.js +4 -0
  36. package/dist/chunks/chunk-7W7VYUTK.js +5 -0
  37. package/dist/chunks/chunk-AXYAZTTN.js +6 -0
  38. package/dist/chunks/chunk-B3NB243Z.js +4 -0
  39. package/dist/chunks/{chunk-XPPZ6Y3X.js → chunk-BKYP6AGM.js} +1 -1
  40. package/dist/chunks/{chunk-QUXPMNFQ.js → chunk-BVEDNESB.js} +1 -1
  41. package/dist/chunks/chunk-BWDJS6A4.js +12 -0
  42. package/dist/chunks/chunk-C6YVF7EI.js +4 -0
  43. package/dist/chunks/chunk-CEJIYYVE.js +15 -0
  44. package/dist/chunks/{chunk-5PAW3DEU.js → chunk-CI2RHH74.js} +4 -4
  45. package/dist/chunks/{chunk-OFEPDNRB.js → chunk-CMSOOLJB.js} +1 -1
  46. package/dist/chunks/chunk-CSVTYYLP.js +4 -0
  47. package/dist/chunks/chunk-DE5EGVKG.js +6 -0
  48. package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
  49. package/dist/chunks/{chunk-ROVKOIHF.js → chunk-DK4UCK7L.js} +1 -1
  50. package/dist/chunks/chunk-DYLBVUAU.js +4 -0
  51. package/dist/chunks/{chunk-WBSE3EF3.js → chunk-FDC2GRBK.js} +1 -1
  52. package/dist/chunks/chunk-FE7HH5JS.js +18 -0
  53. package/dist/chunks/chunk-FYD57YRO.js +436 -0
  54. package/dist/chunks/chunk-G264APQN.js +5 -0
  55. package/dist/chunks/chunk-G4JYZFEO.js +11 -0
  56. package/dist/chunks/chunk-GFFM56U2.js +4 -0
  57. package/dist/chunks/chunk-GOS3P7KS.js +132 -0
  58. package/dist/chunks/{chunk-2VVRTJQN.js → chunk-HVN37UXD.js} +1 -1
  59. package/dist/chunks/{chunk-53TQNK7Z.js → chunk-IGZWZP7Z.js} +1 -1
  60. package/dist/chunks/{chunk-AFTBQRPN.js → chunk-IJ7XFQMI.js} +1 -1
  61. package/dist/chunks/{chunk-U23S37TT.js → chunk-IMMGYDAB.js} +1 -1
  62. package/dist/chunks/chunk-IOWBF7UK.js +10 -0
  63. package/dist/chunks/{chunk-MGYYSX7Y.js → chunk-ITGCWQFK.js} +1 -1
  64. package/dist/chunks/{chunk-QEL6CMLE.js → chunk-IVZ7QUEG.js} +1 -1
  65. package/dist/chunks/{chunk-EE3WT25T.js → chunk-IWY2HIFK.js} +1 -1
  66. package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
  67. package/dist/chunks/{chunk-NXZS5PEW.js → chunk-JGUEIW2W.js} +1 -1
  68. package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
  69. package/dist/chunks/{chunk-VIMHSW6J.js → chunk-KJUQCCB5.js} +1 -1
  70. package/dist/chunks/{chunk-BUZQBTV2.js → chunk-KST6OY76.js} +1 -1
  71. package/dist/chunks/{chunk-KDPY2YA3.js → chunk-KZSAFVSY.js} +2 -2
  72. package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
  73. package/dist/chunks/{chunk-RYLSRII6.js → chunk-LE6QPXN6.js} +1 -1
  74. package/dist/chunks/{chunk-TX46YMGI.js → chunk-LIIZI3HY.js} +1 -1
  75. package/dist/chunks/{chunk-3CZPBLB3.js → chunk-MJQ2D2OP.js} +1 -1
  76. package/dist/chunks/{chunk-P7TVR4GY.js → chunk-NHHR4DCF.js} +1 -1
  77. package/dist/chunks/chunk-NW4GW47L.js +4 -0
  78. package/dist/chunks/chunk-OALEJ6FG.js +60 -0
  79. package/dist/chunks/chunk-OIV4DIMB.js +4 -0
  80. package/dist/chunks/{chunk-T73GHMFB.js → chunk-OJ37ZWBG.js} +1 -1
  81. package/dist/chunks/{chunk-7GEBDPTT.js → chunk-OZXMPBUX.js} +1 -1
  82. package/dist/chunks/chunk-PG7452XE.js +4 -0
  83. package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
  84. package/dist/chunks/{chunk-RA2BUYI3.js → chunk-PTS3J4DQ.js} +1 -1
  85. package/dist/chunks/{chunk-2ROGTDM2.js → chunk-PVVEEBUU.js} +1 -1
  86. package/dist/chunks/{chunk-W6AKCEYF.js → chunk-Q7BZLPBU.js} +1 -1
  87. package/dist/chunks/{chunk-SY2HV3V5.js → chunk-QC66ZXPP.js} +1 -1
  88. package/dist/chunks/chunk-QXFWIL4C.js +4 -0
  89. package/dist/chunks/{chunk-NRD57ICT.js → chunk-R2CCD4OF.js} +1 -1
  90. package/dist/chunks/{chunk-R52AVUQB.js → chunk-RG5GP4RB.js} +1 -1
  91. package/dist/chunks/{chunk-IKLTEWA3.js → chunk-RW2F2QNP.js} +1 -1
  92. package/dist/chunks/{chunk-XEBEWR6Y.js → chunk-RWPO3NZ3.js} +1 -1
  93. package/dist/chunks/chunk-SDUS2H3E.js +4 -0
  94. package/dist/chunks/chunk-SIHGKM4E.js +4 -0
  95. package/dist/chunks/{chunk-NNBSSISP.js → chunk-SKHFU5DI.js} +1 -1
  96. package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
  97. package/dist/chunks/chunk-T54CZKNJ.js +6 -0
  98. package/dist/chunks/chunk-TRXLIL7V.js +4 -0
  99. package/dist/chunks/{chunk-KUDK7GPS.js → chunk-UEEW2R4E.js} +1 -1
  100. package/dist/chunks/chunk-UHXPRU6G.js +10 -0
  101. package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
  102. package/dist/chunks/{chunk-BDLKI2NT.js → chunk-VHX2GHBF.js} +1 -1
  103. package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
  104. package/dist/chunks/{chunk-FP7ML72L.js → chunk-WU7RNAZD.js} +1 -1
  105. package/dist/chunks/chunk-WZC4TDDM.js +6 -0
  106. package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
  107. package/dist/chunks/{chunk-H4QZ2P3Z.js → chunk-X5ND4H4P.js} +1 -1
  108. package/dist/chunks/{chunk-5A6CA5TM.js → chunk-Y3AOGNDT.js} +1 -1
  109. package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
  110. package/dist/chunks/{chunk-LP7T32PW.js → chunk-YAEHSSR4.js} +1 -1
  111. package/dist/chunks/chunk-YWPBE5LP.js +4 -0
  112. package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
  113. package/dist/chunks/chunk-ZD2M73XA.js +19 -0
  114. package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
  115. package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
  116. package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
  117. package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
  118. package/dist/chunks/cli-VB2N7HEK.js +55 -0
  119. package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
  120. package/dist/chunks/context-CI2FKEQE.js +4 -0
  121. package/dist/chunks/cost-CZRRSIUF.js +5 -0
  122. package/dist/chunks/dist-QCNQN6DY.js +4 -0
  123. package/dist/chunks/{easter-egg-3d-CZH7AYZ7.js → easter-egg-3d-XR5S2O3T.js} +1 -1
  124. package/dist/chunks/execution-repo-5TLV2NM4.js +4 -0
  125. package/dist/chunks/{executions-BN6OLLVM.js → executions-I3UUIGSL.js} +1 -1
  126. package/dist/chunks/file-Y5G56IUT.js +4 -0
  127. package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
  128. package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
  129. package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
  130. package/dist/chunks/init-A6GY656J.js +4 -0
  131. package/dist/chunks/{install-cli-ABBD7DO5.js → install-cli-FALWKQYO.js} +1 -1
  132. package/dist/chunks/{interaction-ask-EE2UPR3Q.js → interaction-ask-O5HGF6CH.js} +1 -1
  133. package/dist/chunks/{interaction-plan-C446T2GZ.js → interaction-plan-JTVDN3BC.js} +1 -1
  134. package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
  135. package/dist/chunks/{llama-cpp-classify-IA2F2H7A.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
  136. package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
  137. package/dist/chunks/memory-cli-DIT4DQF3.js +11 -0
  138. package/dist/chunks/meta-JQH66YU7.js +4 -0
  139. package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
  140. package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
  141. package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
  142. package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
  143. package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
  144. package/dist/chunks/{openai-decisions-P5UX7BWY.js → openai-decisions-JU6QQKEM.js} +1 -1
  145. package/dist/chunks/openai-responses-2SG757TL.js +6 -0
  146. package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
  147. package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
  148. package/dist/chunks/radius-THYKWV4E.js +4 -0
  149. package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
  150. package/dist/chunks/runner-5MKMRTIN.js +4 -0
  151. package/dist/chunks/runtime-DST3H5JP.js +4 -0
  152. package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
  153. package/dist/chunks/slack-R7SEJYMY.js +4 -0
  154. package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
  155. package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
  156. package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
  157. package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
  158. package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
  159. package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
  160. package/dist/chunks/{ui-file-6PLXHSTB.js → ui-file-SRD4ILBS.js} +1 -1
  161. package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
  162. package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
  163. package/dist/chunks/{waitpoint-W5M3BE55.js → waitpoint-M6JZBSLT.js} +1 -1
  164. package/dist/chunks/workers-SQ2R32TK.js +4 -0
  165. package/dist/client-bundle/client.mjs +229 -62
  166. package/dist/client-bundle/manifest.json +2 -2
  167. package/dist/core/pi-sdk.js +1 -1
  168. package/dist/domain/auth/cc-auth-cli.js +1 -1
  169. package/dist/domain/mcp/bundled-server.js +1 -1
  170. package/dist/domain/mcp/feishu/client.js +1 -1
  171. package/dist/entry/app.js +138 -556
  172. package/dist/entry/browser-cli.js +1 -1
  173. package/dist/entry/cli.js +1 -1
  174. package/dist/entry/cortex-cli.js +1 -1
  175. package/dist/entry/daemon.js +3 -3
  176. package/dist/entry/hook-cli.js +1 -1
  177. package/dist/entry/production-app-bootstrap.js +1 -1
  178. package/dist/entry/production-evidence-export-cli.js +1 -1
  179. package/dist/entry/signal-cli.js +1 -1
  180. package/dist/tui/index.js +1 -1
  181. package/package.json +1 -1
  182. package/vendor/pi/CHANGELOG.md +330 -0
  183. package/vendor/pi/dist/codemode-worker.js +2 -0
  184. package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
  185. package/vendor/pi/dist/core/export-html/template.css +9 -0
  186. package/vendor/pi/dist/core/export-html/template.js +166 -46
  187. package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
  188. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  189. package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
  190. package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
  191. package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
  192. package/vendor/pi/dist/utils/image-resize.js +1 -1
  193. package/vendor/pi/docs/cli.md +35 -12
  194. package/vendor/pi/docs/custom-provider.md +2 -0
  195. package/vendor/pi/docs/environment-variables.md +2 -0
  196. package/vendor/pi/docs/extensions.md +3192 -225
  197. package/vendor/pi/docs/keybindings.md +2 -2
  198. package/vendor/pi/docs/llama-cpp.md +27 -19
  199. package/vendor/pi/docs/mcp.md +6 -4
  200. package/vendor/pi/docs/message-types.md +1 -1
  201. package/vendor/pi/docs/models-configuration.md +9 -3
  202. package/vendor/pi/docs/models.md +2 -1
  203. package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
  204. package/vendor/pi/docs/packages.md +24 -0
  205. package/vendor/pi/docs/prompt-templates.md +1 -1
  206. package/vendor/pi/docs/providers.md +4 -2
  207. package/vendor/pi/docs/quickstart.md +7 -3
  208. package/vendor/pi/docs/rpc-commands.md +1 -1
  209. package/vendor/pi/docs/rpc.md +4 -2
  210. package/vendor/pi/docs/sessions.md +17 -3
  211. package/vendor/pi/docs/settings.md +6 -5
  212. package/vendor/pi/docs/slash-commands.md +3 -2
  213. package/vendor/pi/docs/terminal-setup.md +3 -1
  214. package/vendor/pi/docs/tmux.md +6 -0
  215. package/vendor/pi/docs/tui.md +4 -0
  216. package/vendor/pi/docs/windows.md +27 -0
  217. package/vendor/pi/examples/extensions/README.md +2 -1
  218. package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  219. package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  220. package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
  221. package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  222. package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
  223. package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
  224. package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
  225. package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
  226. package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
  227. package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
  228. package/vendor/pi/examples/extensions/preset.ts +2 -0
  229. package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
  230. package/vendor/pi/examples/extensions/subagent/README.md +14 -11
  231. package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
  232. package/vendor/pi/examples/extensions/todo.ts +7 -0
  233. package/vendor/pi/examples/extensions/tools.ts +2 -0
  234. package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
  235. package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
  236. package/vendor/pi/examples/tsconfig.json +208 -0
  237. package/vendor/pi/package.json +15 -16
  238. package/vendor/pi/schemas/models.schema.json +66 -37
  239. package/vendor/pi/schemas/settings.schema.json +18 -1
  240. package/vendor/pi-ai/bedrock.js +1 -1
  241. package/vendor/pi-ai/oauth-load.js +1 -1
  242. package/web/dist/assets/{board-math-css-BgIyUG-C.js → board-math-css-DKX6FcUS.js} +1 -1
  243. package/web/dist/assets/index-D11wi0uG.js +540 -0
  244. package/web/dist/assets/index-JedYumhY.css +1 -0
  245. package/web/dist/assets/{index-C2eMpcuI.js → index-jl30Gy8P.js} +1 -1
  246. package/web/dist/index.html +2 -2
  247. package/dist/chunks/anthropic-messages-M732OMEE.js +0 -8
  248. package/dist/chunks/azure-openai-responses-RAKTV6JY.js +0 -4
  249. package/dist/chunks/bedrock-converse-stream-WNUGNZ27.js +0 -62
  250. package/dist/chunks/child-runner-MO5RT6FH.js +0 -4
  251. package/dist/chunks/chunk-3CPIMAYX.js +0 -30
  252. package/dist/chunks/chunk-3ORG56I5.js +0 -8
  253. package/dist/chunks/chunk-4EX2JJWB.js +0 -4
  254. package/dist/chunks/chunk-5DF5WJNM.js +0 -60
  255. package/dist/chunks/chunk-7GAYFN52.js +0 -18
  256. package/dist/chunks/chunk-AVXDF7AG.js +0 -4
  257. package/dist/chunks/chunk-BJGYGEZO.js +0 -6
  258. package/dist/chunks/chunk-BZDIAI5M.js +0 -125
  259. package/dist/chunks/chunk-CK3P345X.js +0 -133
  260. package/dist/chunks/chunk-CVC66CFV.js +0 -33
  261. package/dist/chunks/chunk-ETIBCA2S.js +0 -4
  262. package/dist/chunks/chunk-FF7UELTU.js +0 -4
  263. package/dist/chunks/chunk-FX6MOGLR.js +0 -11
  264. package/dist/chunks/chunk-G2V65UBA.js +0 -4
  265. package/dist/chunks/chunk-HGPBHTVD.js +0 -6
  266. package/dist/chunks/chunk-IYVZHGUQ.js +0 -5
  267. package/dist/chunks/chunk-JJDEQ6N2.js +0 -4
  268. package/dist/chunks/chunk-KDYEGGMW.js +0 -4
  269. package/dist/chunks/chunk-L6VCIGWS.js +0 -11
  270. package/dist/chunks/chunk-LACGULCN.js +0 -10
  271. package/dist/chunks/chunk-LAWOWPZX.js +0 -363
  272. package/dist/chunks/chunk-NNTQUHLO.js +0 -877
  273. package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
  274. package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
  275. package/dist/chunks/chunk-PZMGBKUR.js +0 -13
  276. package/dist/chunks/chunk-QBKCAIJG.js +0 -4
  277. package/dist/chunks/chunk-QMSSIDRQ.js +0 -70
  278. package/dist/chunks/chunk-QUUEQRIT.js +0 -4
  279. package/dist/chunks/chunk-RA6HKFBV.js +0 -4
  280. package/dist/chunks/chunk-RDW6FRF5.js +0 -4
  281. package/dist/chunks/chunk-RF4JLYBX.js +0 -6
  282. package/dist/chunks/chunk-SFX7V5O2.js +0 -10
  283. package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
  284. package/dist/chunks/chunk-STCNHXPJ.js +0 -6
  285. package/dist/chunks/chunk-UT6DGZDO.js +0 -4
  286. package/dist/chunks/chunk-VBN2JSER.js +0 -5
  287. package/dist/chunks/chunk-VK5J556O.js +0 -4
  288. package/dist/chunks/chunk-VPVSKJGX.js +0 -6
  289. package/dist/chunks/chunk-VQUPKMDR.js +0 -4
  290. package/dist/chunks/chunk-WEZWKMYU.js +0 -4
  291. package/dist/chunks/chunk-XYSXL3KX.js +0 -4
  292. package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
  293. package/dist/chunks/chunk-YAAKL3QS.js +0 -80
  294. package/dist/chunks/chunk-YB5LUJHS.js +0 -65
  295. package/dist/chunks/chunk-YKKEI5GI.js +0 -4
  296. package/dist/chunks/chunk-Z24SBRJK.js +0 -4
  297. package/dist/chunks/cli-5DBTRMHU.js +0 -53
  298. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
  299. package/dist/chunks/context-GQKWKFRM.js +0 -4
  300. package/dist/chunks/cost-OOO32GLC.js +0 -5
  301. package/dist/chunks/dist-V5FRMUFH.js +0 -4
  302. package/dist/chunks/execution-repo-XXL4FXC6.js +0 -4
  303. package/dist/chunks/file-H572PL2Z.js +0 -4
  304. package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
  305. package/dist/chunks/google-generative-ai-2G4ITOZL.js +0 -4
  306. package/dist/chunks/google-vertex-PACHCMRZ.js +0 -4
  307. package/dist/chunks/init-75F4V7SK.js +0 -4
  308. package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
  309. package/dist/chunks/local-client-stop-5YOLXGYT.js +0 -4
  310. package/dist/chunks/memory-cli-5SSF6YJM.js +0 -11
  311. package/dist/chunks/meta-KY3LNFV2.js +0 -4
  312. package/dist/chunks/mistral-conversations-VHP63CDS.js +0 -7
  313. package/dist/chunks/model-resolver-FVJNZ6NA.js +0 -4
  314. package/dist/chunks/openai-codex-responses-EHJ4AZBE.js +0 -12
  315. package/dist/chunks/openai-completions-CRAGQFCE.js +0 -9
  316. package/dist/chunks/openai-responses-IZ22NVQ7.js +0 -6
  317. package/dist/chunks/openrouter-images-W2JAMSRH.js +0 -4
  318. package/dist/chunks/pi-messages-MJEEQU2R.js +0 -10
  319. package/dist/chunks/radius-ZM7ZRMXF.js +0 -4
  320. package/dist/chunks/remote-ops-O5CR4RGA.js +0 -14
  321. package/dist/chunks/runner-S6R3US24.js +0 -4
  322. package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
  323. package/dist/chunks/schedule-cli-4T4YC5V5.js +0 -4
  324. package/dist/chunks/slack-2CGM4SMY.js +0 -4
  325. package/dist/chunks/start-ui-http-3D7QNHGB.js +0 -43
  326. package/dist/chunks/subagent-OZGUOV3J.js +0 -4
  327. package/dist/chunks/tool-shims-IA2WELXJ.js +0 -4
  328. package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
  329. package/dist/chunks/ui-board-H4INJD6C.js +0 -5
  330. package/dist/chunks/ui-decision-6HHNROIT.js +0 -4
  331. package/dist/chunks/ui-view-6MDU4GXY.js +0 -4
  332. package/dist/chunks/virtual-modules-OFI7QKYH.js +0 -4
  333. package/dist/chunks/workers-GTFP75MS.js +0 -4
  334. package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
  335. package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
  336. package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
  337. package/web/dist/assets/index-9lyu2S6W.css +0 -1
  338. package/web/dist/assets/index-C-hpzey7.js +0 -532
@@ -1,65 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as ul}from"./chunk-23PRJECN.js";import{a as cl,d as go,o as dl}from"./chunk-QBKCAIJG.js";import{L as ll,t as sl,x as al}from"./chunk-PZMGBKUR.js";import{a as qt}from"./chunk-USBJFDJ6.js";import{a as Mp,b as ol}from"./chunk-QN44UXQR.js";import{a as xp}from"./chunk-I6OPDRVF.js";import{a as rl}from"./chunk-2YTYYG4K.js";import{a as ne,c as X,e as il}from"./chunk-WHC7AYZD.js";var _o=X((H0,El)=>{"use strict";var Vn=Object.prototype.hasOwnProperty,yl=Object.prototype.toString,fl=Object.defineProperty,pl=Object.getOwnPropertyDescriptor,hl=function(e){return typeof Array.isArray=="function"?Array.isArray(e):yl.call(e)==="[object Array]"},ml=function(e){if(!e||yl.call(e)!=="[object Object]")return!1;var n=Vn.call(e,"constructor"),i=e.constructor&&e.constructor.prototype&&Vn.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!i)return!1;var o;for(o in e);return typeof o>"u"||Vn.call(e,o)},gl=function(e,n){fl&&n.name==="__proto__"?fl(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},_l=function(e,n){if(n==="__proto__")if(Vn.call(e,n)){if(pl)return pl(e,n).value}else return;return e[n]};El.exports=function t(){var e,n,i,o,r,a,u=arguments[0],c=1,d=arguments.length,f=!1;for(typeof u=="boolean"&&(f=u,u=arguments[1]||{},c=2),(u==null||typeof u!="object"&&typeof u!="function")&&(u={});c<d;++c)if(e=arguments[c],e!=null)for(n in e)i=_l(u,n),o=_l(e,n),u!==o&&(f&&o&&(ml(o)||(r=hl(o)))?(r?(r=!1,a=i&&hl(i)?i:[]):a=i&&ml(i)?i:{},gl(u,{name:n,newValue:t(f,a,o)})):typeof o<"u"&&gl(u,{name:n,newValue:o}));return u}});var vl=X((V0,Up)=>{Up.exports={name:"gaxios",version:"7.3.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var Al=X((B0,Tl)=>{"use strict";var Gp=vl();Tl.exports={pkg:Gp}});var vo=X(Je=>{"use strict";var Il=Je&&Je.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Je,"__esModule",{value:!0});Je.GaxiosError=Je.GAXIOS_ERROR_SYMBOL=void 0;Je.defaultErrorRedactor=Sl;var Cl=Il(_o()),Lp=Il(Al()),yo=Lp.default.pkg;Je.GAXIOS_ERROR_SYMBOL=Symbol.for(`${yo.name}-gaxios-error`);var Eo=class t extends Error{config;response;code;status;error;[Je.GAXIOS_ERROR_SYMBOL]=yo.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&Je.GAXIOS_ERROR_SYMBOL in e&&e[Je.GAXIOS_ERROR_SYMBOL]===yo.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,i,o){if(super(e,{cause:o}),this.config=n,this.response=i,this.error=o instanceof Error?o:void 0,this.config=(0,Cl.default)(!0,{},n),this.response&&(this.response.config=(0,Cl.default)(!0,{},this.response.config)),this.response){try{this.response.data=bp(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let i=n;if(typeof e.data=="string"&&(i=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){i="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:i;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,r="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let a=[];for(let u of e.data.error.errors)typeof u=="object"&&"message"in u&&typeof u.message=="string"&&a.push(u.message);return Object.assign({message:a.join(`
5
- `)||i,code:r,status:o},e.data.error)}return Object.assign({message:i,code:r,status:o},e.data.error)}}return{message:i,code:e.status,status:e.statusText}}};Je.GaxiosError=Eo;function bp(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function Sl(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(r){r&&r.forEach((a,u)=>{(/^authentication$/i.test(u)||/^authorization$/i.test(u)||/secret/i.test(u))&&r.set(u,e)})}function i(r,a){if(typeof r=="object"&&r!==null&&typeof r[a]=="string"){let u=r[a];(/grant_type=/i.test(u)||/assertion=/i.test(u)||/secret/i.test(u))&&(r[a]=e)}}function o(r){!r||typeof r!="object"||(r instanceof FormData||r instanceof URLSearchParams||"forEach"in r&&"set"in r?r.forEach((a,u)=>{(["grant_type","assertion"].includes(u)||/secret/.test(u))&&r.set(u,e)}):("grant_type"in r&&(r.grant_type=e),"assertion"in r&&(r.assertion=e),"client_secret"in r&&(r.client_secret=e)))}return t.config&&(n(t.config.headers),i(t.config,"data"),o(t.config.data),i(t.config,"body"),o(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(Sl({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(i(t.response,"data"),o(t.response.data))),t}});var Rl=X(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.getRetryConfig=Op;async function Op(t){let e=wl(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||qp)(t))return{shouldRetry:!1,config:t.config};let o=Fp(e);t.config.retryConfig.currentRetryAttempt+=1;let r=e.retryBackoff?e.retryBackoff(t,o):new Promise(a=>{setTimeout(a,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await r,{shouldRetry:!0,config:t.config}}function qp(t){let e=wl(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let n=!1;for(let[i,o]of e.statusCodesToRetry){let r=t.response.status;if(r>=i&&r<=o){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function wl(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function Fp(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,i=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,i,t.maxRetryDelay)}});var Co=X(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.GaxiosInterceptorManager=void 0;var Ao=class extends Set{};Bn.GaxiosInterceptorManager=Ao});var kl=X(Kt=>{"use strict";var Hp=Kt&&Kt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Xt;Object.defineProperty(Kt,"__esModule",{value:!0});Kt.Gaxios=void 0;var Vp=Hp(_o()),Bp=ne("https"),Ft=vo(),$p=Rl(),Pl=ne("stream"),Nl=Co(),Jp=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),Xp=204,$n=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Nl.GaxiosInterceptorManager,response:new Nl.GaxiosInterceptorManager}}fetch(...e){let n=e[0],i=e[1],o,r=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&Xt.mergeHeaders(r,n.headers),i&&Xt.mergeHeaders(r,new Headers(i.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...i,...n,headers:r,url:o}):this.request({...i,headers:r,url:o})}async request(e={}){let n=await this.#i(e);return n=await this.#t(n),this.#n(this._request(n))}async _defaultAdapter(e){let n=e.fetchImplementation||this.defaults.fetchImplementation||await Xt.#l(),i={...e};delete i.data;let o=await n(e.url,i),r=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:r}}),Object.assign(o,{config:e,data:r})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let o=[];for await(let r of n.data)o.push(r);n.data=Buffer.concat(o.map(r=>typeof r=="string"?Buffer.from(r):r)).toString("utf8")}let i=Ft.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new Ft.GaxiosError(i?.message,e,n,i)}return n}catch(n){let i;n instanceof Ft.GaxiosError?i=n:n instanceof Error?i=new Ft.GaxiosError(n.message,e,void 0,n):i=new Ft.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:r}=await(0,$p.getRetryConfig)(i);if(o&&r)return i.config.retryConfig.currentRetryAttempt=r.retryConfig.currentRetryAttempt,e.retryConfig=i.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(i),i}}async getResponseData(e,n){if(n.status===Xp)return"";if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new Ft.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":{let i=await n.text();try{return JSON.parse(i)}catch{return i}}case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let i=new URL(e),o=[...n],r=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let a of r)o.push(a.trim());for(let a of o)if(a instanceof RegExp){if(a.test(i.toString()))return!1}else if(a instanceof URL){if(a.origin===i.origin)return!1}else if(a.startsWith("*.")||a.startsWith(".")){let u=a.replace(/^\*\./,".");if(i.hostname.endsWith(u))return!1}else if(a===i.origin||a===i.hostname||a===i.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let i of this.interceptors.request.values())i&&(n=n.then(i.resolved,i.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let i of this.interceptors.response.values())i&&(n=n.then(i.resolved,i.rejected));return n}async#i(e){let n=new Headers(this.defaults.headers);Xt.mergeHeaders(n,e.headers);let i=(0,Vp.default)(!0,{},this.defaults,e);if(!i.url)throw new Error("URL is required.");if(i.baseURL&&(i.url=new URL(i.url,i.baseURL)),i.url=new URL(i.url),i.params)if(i.paramsSerializer){let a=i.paramsSerializer(i.params);a.startsWith("?")&&(a=a.slice(1));let u=i.url.toString().includes("?")?"&":"?";i.url=i.url+u+a}else{let a=i.url instanceof URL?i.url:new URL(i.url);for(let[u,c]of new URLSearchParams(i.params))a.searchParams.append(u,c);i.url=a}typeof e.maxContentLength=="number"&&(i.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(i.follow=e.maxRedirects);let o=typeof i.data=="string"||i.data instanceof ArrayBuffer||i.data instanceof Blob||globalThis.File&&i.data instanceof File||i.data instanceof FormData||i.data instanceof Pl.Readable||i.data instanceof ReadableStream||i.data instanceof String||i.data instanceof URLSearchParams||ArrayBuffer.isView(i.data)||["Blob","File","FormData"].includes(i.data?.constructor?.name||"");if(i.multipart?.length){let a=await Jp();n.set("content-type",`multipart/related; boundary=${a}`),i.body=Pl.Readable.from(this.getMultipartRequest(i.multipart,a))}else o?i.body=i.data:typeof i.data=="object"?n.get("Content-Type")==="application/x-www-form-urlencoded"?i.body=i.paramsSerializer?i.paramsSerializer(i.data):new URLSearchParams(i.data):(n.has("content-type")||n.set("content-type","application/json"),i.body=JSON.stringify(i.data)):i.data&&(i.body=i.data);i.validateStatus=i.validateStatus||this.validateStatus,i.responseType=i.responseType||"unknown",!n.has("accept")&&i.responseType==="json"&&n.set("accept","application/json");let r=i.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!i.agent)if(r&&this.#e(i.url,i.noProxy)){let a=await Xt.#a();this.agentCache.has(r)?i.agent=this.agentCache.get(r):(i.agent=new a(r,{cert:i.cert,key:i.key}),this.agentCache.set(r,i.agent))}else i.cert&&i.key&&(this.agentCache.has(i.key)?i.agent=this.agentCache.get(i.key):(i.agent=new Bp.Agent({cert:i.cert,key:i.key}),this.agentCache.set(i.key,i.agent)));return typeof i.errorRedactor!="function"&&i.errorRedactor!==!1&&(i.errorRedactor=Ft.defaultErrorRedactor),i.body&&!("duplex"in i)&&(i.duplex="half"),this.#o(i),Object.assign(i,{headers:n,url:i.url instanceof URL?i.url:new URL(i.url)})}#o(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let i=await e.text();try{i=JSON.parse(i)}catch{}return i}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let i=`--${n}--`;for(let o of e){let r=o.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
6
- Content-Type: ${r}\r
7
- \r
8
- `,typeof o.content=="string"?yield o.content:yield*o.content,yield`\r
9
- `}yield i}static#r;static#s;static async#a(){return this.#r||=(await import("./dist-7RWW7YH4.js")).HttpsProxyAgent,this.#r}static async#l(){let e=typeof window<"u"&&!!window;return this.#s||=e?window.fetch:(await import("./src-CCI7P7AI.js")).default,this.#s}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let i of n)(i instanceof Headers?i:new Headers(i)).forEach((r,a)=>{a==="set-cookie"?e.append(a,r):e.set(a,r)});return e}};Kt.Gaxios=$n;Xt=$n});var ke=X(Ge=>{"use strict";var Kp=Ge&&Ge.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,o)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),Yp=Ge&&Ge.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Kp(e,t,n)};Object.defineProperty(Ge,"__esModule",{value:!0});Ge.instance=Ge.Gaxios=Ge.GaxiosError=void 0;Ge.request=zp;var Dl=kl();Object.defineProperty(Ge,"Gaxios",{enumerable:!0,get:function(){return Dl.Gaxios}});var Wp=vo();Object.defineProperty(Ge,"GaxiosError",{enumerable:!0,get:function(){return Wp.GaxiosError}});Yp(Co(),Ge);Ge.instance=new Dl.Gaxios;async function zp(t){return Ge.instance.request(t)}});var Io=X((xl,Jn)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,i=Math.ceil,o=Math.floor,r="[BigNumber Error] ",a=r+"Number primitive has more than 15 significant digits: ",u=1e14,c=14,d=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,h=1e9;function m(R){var L,O,H,U=V.prototype={constructor:V,toString:null,valueOf:null},F=new V(1),J=20,Q=4,te=-7,D=21,K=-1e7,Z=1e7,Ee=!1,Re=1,Te=0,Pe={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Oe="0123456789abcdefghijklmnopqrstuvwxyz",co=!0;function V(E,T){var I,M,P,k,b,w,N,G,x=this;if(!(x instanceof V))return new V(E,T);if(T==null){if(E&&E._isBigNumber===!0){x.s=E.s,!E.c||E.e>Z?x.c=x.e=null:E.e<K?x.c=[x.e=0]:(x.e=E.e,x.c=E.c.slice());return}if((w=typeof E=="number")&&E*0==0){if(x.s=1/E<0?(E=-E,-1):1,E===~~E){for(k=0,b=E;b>=10;b/=10,k++);k>Z?x.c=x.e=null:(x.e=k,x.c=[E]);return}G=String(E)}else{if(!n.test(G=String(E)))return H(x,G,w);x.s=G.charCodeAt(0)==45?(G=G.slice(1),-1):1}(k=G.indexOf("."))>-1&&(G=G.replace(".","")),(b=G.search(/e/i))>0?(k<0&&(k=b),k+=+G.slice(b+1),G=G.substring(0,b)):k<0&&(k=G.length)}else{if(y(T,2,Oe.length,"Base"),T==10&&co)return x=new V(E),Be(x,J+x.e+1,Q);if(G=String(E),w=typeof E=="number"){if(E*0!=0)return H(x,G,w,T);if(x.s=1/E<0?(G=G.slice(1),-1):1,V.DEBUG&&G.replace(/^0\.0*|\./,"").length>15)throw Error(a+E)}else x.s=G.charCodeAt(0)===45?(G=G.slice(1),-1):1;for(I=Oe.slice(0,T),k=b=0,N=G.length;b<N;b++)if(I.indexOf(M=G.charAt(b))<0){if(M=="."){if(b>k){k=N;continue}}else if(!P&&(G==G.toUpperCase()&&(G=G.toLowerCase())||G==G.toLowerCase()&&(G=G.toUpperCase()))){P=!0,b=-1,k=0;continue}return H(x,String(E),w,T)}w=!1,G=O(G,T,10,x.s),(k=G.indexOf("."))>-1?G=G.replace(".",""):k=G.length}for(b=0;G.charCodeAt(b)===48;b++);for(N=G.length;G.charCodeAt(--N)===48;);if(G=G.slice(b,++N)){if(N-=b,w&&V.DEBUG&&N>15&&(E>d||E!==o(E)))throw Error(a+x.s*E);if((k=k-b-1)>Z)x.c=x.e=null;else if(k<K)x.c=[x.e=0];else{if(x.e=k,x.c=[],b=(k+1)%c,k<0&&(b+=c),b<N){for(b&&x.c.push(+G.slice(0,b)),N-=c;b<N;)x.c.push(+G.slice(b,b+=c));b=c-(G=G.slice(b)).length}else b-=N;for(;b--;G+="0");x.c.push(+G)}}else x.c=[x.e=0]}V.clone=m,V.ROUND_UP=0,V.ROUND_DOWN=1,V.ROUND_CEIL=2,V.ROUND_FLOOR=3,V.ROUND_HALF_UP=4,V.ROUND_HALF_DOWN=5,V.ROUND_HALF_EVEN=6,V.ROUND_HALF_CEIL=7,V.ROUND_HALF_FLOOR=8,V.EUCLID=9,V.config=V.set=function(E){var T,I;if(E!=null)if(typeof E=="object"){if(E.hasOwnProperty(T="DECIMAL_PLACES")&&(I=E[T],y(I,0,h,T),J=I),E.hasOwnProperty(T="ROUNDING_MODE")&&(I=E[T],y(I,0,8,T),Q=I),E.hasOwnProperty(T="EXPONENTIAL_AT")&&(I=E[T],I&&I.pop?(y(I[0],-h,0,T),y(I[1],0,h,T),te=I[0],D=I[1]):(y(I,-h,h,T),te=-(D=I<0?-I:I))),E.hasOwnProperty(T="RANGE"))if(I=E[T],I&&I.pop)y(I[0],-h,-1,T),y(I[1],1,h,T),K=I[0],Z=I[1];else if(y(I,-h,h,T),I)K=-(Z=I<0?-I:I);else throw Error(r+T+" cannot be zero: "+I);if(E.hasOwnProperty(T="CRYPTO"))if(I=E[T],I===!!I)if(I)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))Ee=I;else throw Ee=!I,Error(r+"crypto unavailable");else Ee=I;else throw Error(r+T+" not true or false: "+I);if(E.hasOwnProperty(T="MODULO_MODE")&&(I=E[T],y(I,0,9,T),Re=I),E.hasOwnProperty(T="POW_PRECISION")&&(I=E[T],y(I,0,h,T),Te=I),E.hasOwnProperty(T="FORMAT"))if(I=E[T],typeof I=="object")Pe=I;else throw Error(r+T+" not an object: "+I);if(E.hasOwnProperty(T="ALPHABET"))if(I=E[T],typeof I=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(I))co=I.slice(0,10)=="0123456789",Oe=I;else throw Error(r+T+" invalid: "+I)}else throw Error(r+"Object expected: "+E);return{DECIMAL_PLACES:J,ROUNDING_MODE:Q,EXPONENTIAL_AT:[te,D],RANGE:[K,Z],CRYPTO:Ee,MODULO_MODE:Re,POW_PRECISION:Te,FORMAT:Pe,ALPHABET:Oe}},V.isBigNumber=function(E){if(!E||E._isBigNumber!==!0)return!1;if(!V.DEBUG)return!0;var T,I,M=E.c,P=E.e,k=E.s;e:if({}.toString.call(M)=="[object Array]"){if((k===1||k===-1)&&P>=-h&&P<=h&&P===o(P)){if(M[0]===0){if(P===0&&M.length===1)return!0;break e}if(T=(P+1)%c,T<1&&(T+=c),String(M[0]).length==T){for(T=0;T<M.length;T++)if(I=M[T],I<0||I>=u||I!==o(I))break e;if(I!==0)return!0}}}else if(M===null&&P===null&&(k===null||k===1||k===-1))return!0;throw Error(r+"Invalid BigNumber: "+E)},V.maximum=V.max=function(){return nl(arguments,-1)},V.minimum=V.min=function(){return nl(arguments,1)},V.random=(function(){var E=9007199254740992,T=Math.random()*E&2097151?function(){return o(Math.random()*E)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(I){var M,P,k,b,w,N=0,G=[],x=new V(F);if(I==null?I=J:y(I,0,h),b=i(I/c),Ee)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(b*=2));N<b;)w=M[N]*131072+(M[N+1]>>>11),w>=9e15?(P=crypto.getRandomValues(new Uint32Array(2)),M[N]=P[0],M[N+1]=P[1]):(G.push(w%1e14),N+=2);N=b/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(b*=7);N<b;)w=(M[N]&31)*281474976710656+M[N+1]*1099511627776+M[N+2]*4294967296+M[N+3]*16777216+(M[N+4]<<16)+(M[N+5]<<8)+M[N+6],w>=9e15?crypto.randomBytes(7).copy(M,N):(G.push(w%1e14),N+=7);N=b/7}else throw Ee=!1,Error(r+"crypto unavailable");if(!Ee)for(;N<b;)w=T(),w<9e15&&(G[N++]=w%1e14);for(b=G[--N],I%=c,b&&I&&(w=f[c-I],G[N]=o(b/w)*w);G[N]===0;G.pop(),N--);if(N<0)G=[k=0];else{for(k=-1;G[0]===0;G.splice(0,1),k-=c);for(N=1,w=G[0];w>=10;w/=10,N++);N<c&&(k-=c-N)}return x.e=k,x.c=G,x}})(),V.sum=function(){for(var E=1,T=arguments,I=new V(T[0]);E<T.length;)I=I.plus(T[E++]);return I},O=(function(){var E="0123456789";function T(I,M,P,k){for(var b,w=[0],N,G=0,x=I.length;G<x;){for(N=w.length;N--;w[N]*=M);for(w[0]+=k.indexOf(I.charAt(G++)),b=0;b<w.length;b++)w[b]>P-1&&(w[b+1]==null&&(w[b+1]=0),w[b+1]+=w[b]/P|0,w[b]%=P)}return w.reverse()}return function(I,M,P,k,b){var w,N,G,x,q,Y,W,oe,Ae=I.indexOf("."),we=J,ie=Q;for(Ae>=0&&(x=Te,Te=0,I=I.replace(".",""),oe=new V(M),Y=oe.pow(I.length-Ae),Te=x,oe.c=T(S(g(Y.c),Y.e,"0"),10,P,E),oe.e=oe.c.length),W=T(I,M,P,b?(w=Oe,E):(w=E,Oe)),G=x=W.length;W[--x]==0;W.pop());if(!W[0])return w.charAt(0);if(Ae<0?--G:(Y.c=W,Y.e=G,Y.s=k,Y=L(Y,oe,we,ie,P),W=Y.c,q=Y.r,G=Y.e),N=G+we+1,Ae=W[N],x=P/2,q=q||N<0||W[N+1]!=null,q=ie<4?(Ae!=null||q)&&(ie==0||ie==(Y.s<0?3:2)):Ae>x||Ae==x&&(ie==4||q||ie==6&&W[N-1]&1||ie==(Y.s<0?8:7)),N<1||!W[0])I=q?S(w.charAt(1),-we,w.charAt(0)):w.charAt(0);else{if(W.length=N,q)for(--P;++W[--N]>P;)W[N]=0,N||(++G,W=[1].concat(W));for(x=W.length;!W[--x];);for(Ae=0,I="";Ae<=x;I+=w.charAt(W[Ae++]));I=S(I,G,w.charAt(0))}return I}})(),L=(function(){function E(M,P,k){var b,w,N,G,x=0,q=M.length,Y=P%p,W=P/p|0;for(M=M.slice();q--;)N=M[q]%p,G=M[q]/p|0,b=W*N+G*Y,w=Y*N+b%p*p+x,x=(w/k|0)+(b/p|0)+W*G,M[q]=w%k;return x&&(M=[x].concat(M)),M}function T(M,P,k,b){var w,N;if(k!=b)N=k>b?1:-1;else for(w=N=0;w<k;w++)if(M[w]!=P[w]){N=M[w]>P[w]?1:-1;break}return N}function I(M,P,k,b){for(var w=0;k--;)M[k]-=w,w=M[k]<P[k]?1:0,M[k]=w*b+M[k]-P[k];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,P,k,b,w){var N,G,x,q,Y,W,oe,Ae,we,ie,ue,De,Hn,ho,mo,rt,Tn,$e=M.s==P.s?1:-1,Ue=M.c,Ce=P.c;if(!Ue||!Ue[0]||!Ce||!Ce[0])return new V(!M.s||!P.s||(Ue?Ce&&Ue[0]==Ce[0]:!Ce)?NaN:Ue&&Ue[0]==0||!Ce?$e*0:$e/0);for(Ae=new V($e),we=Ae.c=[],G=M.e-P.e,$e=k+G+1,w||(w=u,G=_(M.e/c)-_(P.e/c),$e=$e/c|0),x=0;Ce[x]==(Ue[x]||0);x++);if(Ce[x]>(Ue[x]||0)&&G--,$e<0)we.push(1),q=!0;else{for(ho=Ue.length,rt=Ce.length,x=0,$e+=2,Y=o(w/(Ce[0]+1)),Y>1&&(Ce=E(Ce,Y,w),Ue=E(Ue,Y,w),rt=Ce.length,ho=Ue.length),Hn=rt,ie=Ue.slice(0,rt),ue=ie.length;ue<rt;ie[ue++]=0);Tn=Ce.slice(),Tn=[0].concat(Tn),mo=Ce[0],Ce[1]>=w/2&&mo++;do{if(Y=0,N=T(Ce,ie,rt,ue),N<0){if(De=ie[0],rt!=ue&&(De=De*w+(ie[1]||0)),Y=o(De/mo),Y>1)for(Y>=w&&(Y=w-1),W=E(Ce,Y,w),oe=W.length,ue=ie.length;T(W,ie,oe,ue)==1;)Y--,I(W,rt<oe?Tn:Ce,oe,w),oe=W.length,N=1;else Y==0&&(N=Y=1),W=Ce.slice(),oe=W.length;if(oe<ue&&(W=[0].concat(W)),I(ie,W,ue,w),ue=ie.length,N==-1)for(;T(Ce,ie,rt,ue)<1;)Y++,I(ie,rt<ue?Tn:Ce,ue,w),ue=ie.length}else N===0&&(Y++,ie=[0]);we[x++]=Y,ie[0]?ie[ue++]=Ue[Hn]||0:(ie=[Ue[Hn]],ue=1)}while((Hn++<ho||ie[0]!=null)&&$e--);q=ie[0]!=null,we[0]||we.splice(0,1)}if(w==u){for(x=1,$e=we[0];$e>=10;$e/=10,x++);Be(Ae,k+(Ae.e=x+G*c-1)+1,b,q)}else Ae.e=G,Ae.r=+q;return Ae}})();function fo(E,T,I,M){var P,k,b,w,N;if(I==null?I=Q:y(I,0,8),!E.c)return E.toString();if(P=E.c[0],b=E.e,T==null)N=g(E.c),N=M==1||M==2&&(b<=te||b>=D)?C(N,b):S(N,b,"0");else if(E=Be(new V(E),T,I),k=E.e,N=g(E.c),w=N.length,M==1||M==2&&(T<=k||k<=te)){for(;w<T;N+="0",w++);N=C(N,k)}else if(T-=b+(M===2&&k>b),N=S(N,k,"0"),k+1>w){if(--T>0)for(N+=".";T--;N+="0");}else if(T+=k-w,T>0)for(k+1==w&&(N+=".");T--;N+="0");return E.s<0&&P?"-"+N:N}function nl(E,T){for(var I,M,P=1,k=new V(E[0]);P<E.length;P++)M=new V(E[P]),(!M.s||(I=v(k,M))===T||I===0&&k.s===T)&&(k=M);return k}function po(E,T,I){for(var M=1,P=T.length;!T[--P];T.pop());for(P=T[0];P>=10;P/=10,M++);return(I=M+I*c-1)>Z?E.c=E.e=null:I<K?E.c=[E.e=0]:(E.e=I,E.c=T),E}H=(function(){var E=/^(-?)0([xbo])(?=\w[\w.]*$)/i,T=/^([^.]+)\.$/,I=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,P=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(k,b,w,N){var G,x=w?b:b.replace(P,"");if(M.test(x))k.s=isNaN(x)?null:x<0?-1:1;else{if(!w&&(x=x.replace(E,function(q,Y,W){return G=(W=W.toLowerCase())=="x"?16:W=="b"?2:8,!N||N==G?Y:q}),N&&(G=N,x=x.replace(T,"$1").replace(I,"0.$1")),b!=x))return new V(x,G);if(V.DEBUG)throw Error(r+"Not a"+(N?" base "+N:"")+" number: "+b);k.s=null}k.c=k.e=null}})();function Be(E,T,I,M){var P,k,b,w,N,G,x,q=E.c,Y=f;if(q){e:{for(P=1,w=q[0];w>=10;w/=10,P++);if(k=T-P,k<0)k+=c,b=T,N=q[G=0],x=o(N/Y[P-b-1]%10);else if(G=i((k+1)/c),G>=q.length)if(M){for(;q.length<=G;q.push(0));N=x=0,P=1,k%=c,b=k-c+1}else break e;else{for(N=w=q[G],P=1;w>=10;w/=10,P++);k%=c,b=k-c+P,x=b<0?0:o(N/Y[P-b-1]%10)}if(M=M||T<0||q[G+1]!=null||(b<0?N:N%Y[P-b-1]),M=I<4?(x||M)&&(I==0||I==(E.s<0?3:2)):x>5||x==5&&(I==4||M||I==6&&(k>0?b>0?N/Y[P-b]:0:q[G-1])%10&1||I==(E.s<0?8:7)),T<1||!q[0])return q.length=0,M?(T-=E.e+1,q[0]=Y[(c-T%c)%c],E.e=-T||0):q[0]=E.e=0,E;if(k==0?(q.length=G,w=1,G--):(q.length=G+1,w=Y[c-k],q[G]=b>0?o(N/Y[P-b]%Y[b])*w:0),M)for(;;)if(G==0){for(k=1,b=q[0];b>=10;b/=10,k++);for(b=q[0]+=w,w=1;b>=10;b/=10,w++);k!=w&&(E.e++,q[0]==u&&(q[0]=1));break}else{if(q[G]+=w,q[G]!=u)break;q[G--]=0,w=1}for(k=q.length;q[--k]===0;q.pop());}E.e>Z?E.c=E.e=null:E.e<K&&(E.c=[E.e=0])}return E}function pt(E){var T,I=E.e;return I===null?E.toString():(T=g(E.c),T=I<=te||I>=D?C(T,I):S(T,I,"0"),E.s<0?"-"+T:T)}return U.absoluteValue=U.abs=function(){var E=new V(this);return E.s<0&&(E.s=1),E},U.comparedTo=function(E,T){return v(this,new V(E,T))},U.decimalPlaces=U.dp=function(E,T){var I,M,P,k=this;if(E!=null)return y(E,0,h),T==null?T=Q:y(T,0,8),Be(new V(k),E+k.e+1,T);if(!(I=k.c))return null;if(M=((P=I.length-1)-_(this.e/c))*c,P=I[P])for(;P%10==0;P/=10,M--);return M<0&&(M=0),M},U.dividedBy=U.div=function(E,T){return L(this,new V(E,T),J,Q)},U.dividedToIntegerBy=U.idiv=function(E,T){return L(this,new V(E,T),0,1)},U.exponentiatedBy=U.pow=function(E,T){var I,M,P,k,b,w,N,G,x,q=this;if(E=new V(E),E.c&&!E.isInteger())throw Error(r+"Exponent not an integer: "+pt(E));if(T!=null&&(T=new V(T)),w=E.e>14,!q.c||!q.c[0]||q.c[0]==1&&!q.e&&q.c.length==1||!E.c||!E.c[0])return x=new V(Math.pow(+pt(q),w?E.s*(2-A(E)):+pt(E))),T?x.mod(T):x;if(N=E.s<0,T){if(T.c?!T.c[0]:!T.s)return new V(NaN);M=!N&&q.isInteger()&&T.isInteger(),M&&(q=q.mod(T))}else{if(E.e>9&&(q.e>0||q.e<-1||(q.e==0?q.c[0]>1||w&&q.c[1]>=24e7:q.c[0]<8e13||w&&q.c[0]<=9999975e7)))return k=q.s<0&&A(E)?-0:0,q.e>-1&&(k=1/k),new V(N?1/k:k);Te&&(k=i(Te/c+2))}for(w?(I=new V(.5),N&&(E.s=1),G=A(E)):(P=Math.abs(+pt(E)),G=P%2),x=new V(F);;){if(G){if(x=x.times(q),!x.c)break;k?x.c.length>k&&(x.c.length=k):M&&(x=x.mod(T))}if(P){if(P=o(P/2),P===0)break;G=P%2}else if(E=E.times(I),Be(E,E.e+1,1),E.e>14)G=A(E);else{if(P=+pt(E),P===0)break;G=P%2}q=q.times(q),k?q.c&&q.c.length>k&&(q.c.length=k):M&&(q=q.mod(T))}return M?x:(N&&(x=F.div(x)),T?x.mod(T):k?Be(x,Te,Q,b):x)},U.integerValue=function(E){var T=new V(this);return E==null?E=Q:y(E,0,8),Be(T,T.e+1,E)},U.isEqualTo=U.eq=function(E,T){return v(this,new V(E,T))===0},U.isFinite=function(){return!!this.c},U.isGreaterThan=U.gt=function(E,T){return v(this,new V(E,T))>0},U.isGreaterThanOrEqualTo=U.gte=function(E,T){return(T=v(this,new V(E,T)))===1||T===0},U.isInteger=function(){return!!this.c&&_(this.e/c)>this.c.length-2},U.isLessThan=U.lt=function(E,T){return v(this,new V(E,T))<0},U.isLessThanOrEqualTo=U.lte=function(E,T){return(T=v(this,new V(E,T)))===-1||T===0},U.isNaN=function(){return!this.s},U.isNegative=function(){return this.s<0},U.isPositive=function(){return this.s>0},U.isZero=function(){return!!this.c&&this.c[0]==0},U.minus=function(E,T){var I,M,P,k,b=this,w=b.s;if(E=new V(E,T),T=E.s,!w||!T)return new V(NaN);if(w!=T)return E.s=-T,b.plus(E);var N=b.e/c,G=E.e/c,x=b.c,q=E.c;if(!N||!G){if(!x||!q)return x?(E.s=-T,E):new V(q?b:NaN);if(!x[0]||!q[0])return q[0]?(E.s=-T,E):new V(x[0]?b:Q==3?-0:0)}if(N=_(N),G=_(G),x=x.slice(),w=N-G){for((k=w<0)?(w=-w,P=x):(G=N,P=q),P.reverse(),T=w;T--;P.push(0));P.reverse()}else for(M=(k=(w=x.length)<(T=q.length))?w:T,w=T=0;T<M;T++)if(x[T]!=q[T]){k=x[T]<q[T];break}if(k&&(P=x,x=q,q=P,E.s=-E.s),T=(M=q.length)-(I=x.length),T>0)for(;T--;x[I++]=0);for(T=u-1;M>w;){if(x[--M]<q[M]){for(I=M;I&&!x[--I];x[I]=T);--x[I],x[M]+=u}x[M]-=q[M]}for(;x[0]==0;x.splice(0,1),--G);return x[0]?po(E,x,G):(E.s=Q==3?-1:1,E.c=[E.e=0],E)},U.modulo=U.mod=function(E,T){var I,M,P=this;return E=new V(E,T),!P.c||!E.s||E.c&&!E.c[0]?new V(NaN):!E.c||P.c&&!P.c[0]?new V(P):(Re==9?(M=E.s,E.s=1,I=L(P,E,0,3),E.s=M,I.s*=M):I=L(P,E,0,Re),E=P.minus(I.times(E)),!E.c[0]&&Re==1&&(E.s=P.s),E)},U.multipliedBy=U.times=function(E,T){var I,M,P,k,b,w,N,G,x,q,Y,W,oe,Ae,we,ie=this,ue=ie.c,De=(E=new V(E,T)).c;if(!ue||!De||!ue[0]||!De[0])return!ie.s||!E.s||ue&&!ue[0]&&!De||De&&!De[0]&&!ue?E.c=E.e=E.s=null:(E.s*=ie.s,!ue||!De?E.c=E.e=null:(E.c=[0],E.e=0)),E;for(M=_(ie.e/c)+_(E.e/c),E.s*=ie.s,N=ue.length,q=De.length,N<q&&(oe=ue,ue=De,De=oe,P=N,N=q,q=P),P=N+q,oe=[];P--;oe.push(0));for(Ae=u,we=p,P=q;--P>=0;){for(I=0,Y=De[P]%we,W=De[P]/we|0,b=N,k=P+b;k>P;)G=ue[--b]%we,x=ue[b]/we|0,w=W*G+x*Y,G=Y*G+w%we*we+oe[k]+I,I=(G/Ae|0)+(w/we|0)+W*x,oe[k--]=G%Ae;oe[k]=I}return I?++M:oe.splice(0,1),po(E,oe,M)},U.negated=function(){var E=new V(this);return E.s=-E.s||null,E},U.plus=function(E,T){var I,M=this,P=M.s;if(E=new V(E,T),T=E.s,!P||!T)return new V(NaN);if(P!=T)return E.s=-T,M.minus(E);var k=M.e/c,b=E.e/c,w=M.c,N=E.c;if(!k||!b){if(!w||!N)return new V(P/0);if(!w[0]||!N[0])return N[0]?E:new V(w[0]?M:P*0)}if(k=_(k),b=_(b),w=w.slice(),P=k-b){for(P>0?(b=k,I=N):(P=-P,I=w),I.reverse();P--;I.push(0));I.reverse()}for(P=w.length,T=N.length,P-T<0&&(I=N,N=w,w=I,T=P),P=0;T;)P=(w[--T]=w[T]+N[T]+P)/u|0,w[T]=u===w[T]?0:w[T]%u;return P&&(w=[P].concat(w),++b),po(E,w,b)},U.precision=U.sd=function(E,T){var I,M,P,k=this;if(E!=null&&E!==!!E)return y(E,1,h),T==null?T=Q:y(T,0,8),Be(new V(k),E,T);if(!(I=k.c))return null;if(P=I.length-1,M=P*c+1,P=I[P]){for(;P%10==0;P/=10,M--);for(P=I[0];P>=10;P/=10,M++);}return E&&k.e+1>M&&(M=k.e+1),M},U.shiftedBy=function(E){return y(E,-d,d),this.times("1e"+E)},U.squareRoot=U.sqrt=function(){var E,T,I,M,P,k=this,b=k.c,w=k.s,N=k.e,G=J+4,x=new V("0.5");if(w!==1||!b||!b[0])return new V(!w||w<0&&(!b||b[0])?NaN:b?k:1/0);if(w=Math.sqrt(+pt(k)),w==0||w==1/0?(T=g(b),(T.length+N)%2==0&&(T+="0"),w=Math.sqrt(+T),N=_((N+1)/2)-(N<0||N%2),w==1/0?T="5e"+N:(T=w.toExponential(),T=T.slice(0,T.indexOf("e")+1)+N),I=new V(T)):I=new V(w+""),I.c[0]){for(N=I.e,w=N+G,w<3&&(w=0);;)if(P=I,I=x.times(P.plus(L(k,P,G,1))),g(P.c).slice(0,w)===(T=g(I.c)).slice(0,w))if(I.e<N&&--w,T=T.slice(w-3,w+1),T=="9999"||!M&&T=="4999"){if(!M&&(Be(P,P.e+J+2,0),P.times(P).eq(k))){I=P;break}G+=4,w+=4,M=1}else{(!+T||!+T.slice(1)&&T.charAt(0)=="5")&&(Be(I,I.e+J+2,1),E=!I.times(I).eq(k));break}}return Be(I,I.e+J+1,Q,E)},U.toExponential=function(E,T){return E!=null&&(y(E,0,h),E++),fo(this,E,T,1)},U.toFixed=function(E,T){return E!=null&&(y(E,0,h),E=E+this.e+1),fo(this,E,T)},U.toFormat=function(E,T,I){var M,P=this;if(I==null)E!=null&&T&&typeof T=="object"?(I=T,T=null):E&&typeof E=="object"?(I=E,E=T=null):I=Pe;else if(typeof I!="object")throw Error(r+"Argument not an object: "+I);if(M=P.toFixed(E,T),P.c){var k,b=M.split("."),w=+I.groupSize,N=+I.secondaryGroupSize,G=I.groupSeparator||"",x=b[0],q=b[1],Y=P.s<0,W=Y?x.slice(1):x,oe=W.length;if(N&&(k=w,w=N,N=k,oe-=k),w>0&&oe>0){for(k=oe%w||w,x=W.substr(0,k);k<oe;k+=w)x+=G+W.substr(k,w);N>0&&(x+=G+W.slice(k)),Y&&(x="-"+x)}M=q?x+(I.decimalSeparator||"")+((N=+I.fractionGroupSize)?q.replace(new RegExp("\\d{"+N+"}\\B","g"),"$&"+(I.fractionGroupSeparator||"")):q):x}return(I.prefix||"")+M+(I.suffix||"")},U.toFraction=function(E){var T,I,M,P,k,b,w,N,G,x,q,Y,W=this,oe=W.c;if(E!=null&&(w=new V(E),!w.isInteger()&&(w.c||w.s!==1)||w.lt(F)))throw Error(r+"Argument "+(w.isInteger()?"out of range: ":"not an integer: ")+pt(w));if(!oe)return new V(W);for(T=new V(F),G=I=new V(F),M=N=new V(F),Y=g(oe),k=T.e=Y.length-W.e-1,T.c[0]=f[(b=k%c)<0?c+b:b],E=!E||w.comparedTo(T)>0?k>0?T:G:w,b=Z,Z=1/0,w=new V(Y),N.c[0]=0;x=L(w,T,0,1),P=I.plus(x.times(M)),P.comparedTo(E)!=1;)I=M,M=P,G=N.plus(x.times(P=G)),N=P,T=w.minus(x.times(P=T)),w=P;return P=L(E.minus(I),M,0,1),N=N.plus(P.times(G)),I=I.plus(P.times(M)),N.s=G.s=W.s,k=k*2,q=L(G,M,k,Q).minus(W).abs().comparedTo(L(N,I,k,Q).minus(W).abs())<1?[G,M]:[N,I],Z=b,q},U.toNumber=function(){return+pt(this)},U.toPrecision=function(E,T){return E!=null&&y(E,1,h),fo(this,E,T,2)},U.toString=function(E){var T,I=this,M=I.s,P=I.e;return P===null?M?(T="Infinity",M<0&&(T="-"+T)):T="NaN":(E==null?T=P<=te||P>=D?C(g(I.c),P):S(g(I.c),P,"0"):E===10&&co?(I=Be(new V(I),J+P+1,Q),T=S(g(I.c),I.e,"0")):(y(E,2,Oe.length,"Base"),T=O(S(g(I.c),P,"0"),10,E,M,!0)),M<0&&I.c[0]&&(T="-"+T)),T},U.valueOf=U.toJSON=function(){return pt(this)},U._isBigNumber=!0,R!=null&&V.set(R),V}function _(R){var L=R|0;return R>0||R===L?L:L-1}function g(R){for(var L,O,H=1,U=R.length,F=R[0]+"";H<U;){for(L=R[H++]+"",O=c-L.length;O--;L="0"+L);F+=L}for(U=F.length;F.charCodeAt(--U)===48;);return F.slice(0,U+1||1)}function v(R,L){var O,H,U=R.c,F=L.c,J=R.s,Q=L.s,te=R.e,D=L.e;if(!J||!Q)return null;if(O=U&&!U[0],H=F&&!F[0],O||H)return O?H?0:-Q:J;if(J!=Q)return J;if(O=J<0,H=te==D,!U||!F)return H?0:!U^O?1:-1;if(!H)return te>D^O?1:-1;for(Q=(te=U.length)<(D=F.length)?te:D,J=0;J<Q;J++)if(U[J]!=F[J])return U[J]>F[J]^O?1:-1;return te==D?0:te>D^O?1:-1}function y(R,L,O,H){if(R<L||R>O||R!==o(R))throw Error(r+(H||"Argument")+(typeof R=="number"?R<L||R>O?" out of range: ":" not an integer: ":" not a primitive number: ")+String(R))}function A(R){var L=R.c.length-1;return _(R.e/c)==L&&R.c[L]%2!=0}function C(R,L){return(R.length>1?R.charAt(0)+"."+R.slice(1):R)+(L<0?"e":"e+")+L}function S(R,L,O){var H,U;if(L<0){for(U=O+".";++L;U+=O);R=U+R}else if(H=R.length,++L>H){for(U=O,L-=H;--L;U+=O);R+=U}else L<H&&(R=R.slice(0,L)+"."+R.slice(L));return R}e=m(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof Jn<"u"&&Jn.exports?Jn.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(xl)});var Ll=X((W0,Gl)=>{var Ml=Io(),Ul=Gl.exports;(function(){"use strict";function t(d){return d<10?"0"+d:d}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,i,o,r={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function u(d){return n.lastIndex=0,n.test(d)?'"'+d.replace(n,function(f){var p=r[f];return typeof p=="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+d+'"'}function c(d,f){var p,h,m,_,g=i,v,y=f[d],A=y!=null&&(y instanceof Ml||Ml.isBigNumber(y));switch(y&&typeof y=="object"&&typeof y.toJSON=="function"&&(y=y.toJSON(d)),typeof a=="function"&&(y=a.call(f,d,y)),typeof y){case"string":return A?y:u(y);case"number":return isFinite(y)?String(y):"null";case"boolean":case"null":case"bigint":return String(y);case"object":if(!y)return"null";if(i+=o,v=[],Object.prototype.toString.apply(y)==="[object Array]"){for(_=y.length,p=0;p<_;p+=1)v[p]=c(p,y)||"null";return m=v.length===0?"[]":i?`[
10
- `+i+v.join(`,
11
- `+i)+`
12
- `+g+"]":"["+v.join(",")+"]",i=g,m}if(a&&typeof a=="object")for(_=a.length,p=0;p<_;p+=1)typeof a[p]=="string"&&(h=a[p],m=c(h,y),m&&v.push(u(h)+(i?": ":":")+m));else Object.keys(y).forEach(function(C){var S=c(C,y);S&&v.push(u(C)+(i?": ":":")+S)});return m=v.length===0?"{}":i?`{
13
- `+i+v.join(`,
14
- `+i)+`
15
- `+g+"}":"{"+v.join(",")+"}",i=g,m}}typeof Ul.stringify!="function"&&(Ul.stringify=function(d,f,p){var h;if(i="",o="",typeof p=="number")for(h=0;h<p;h+=1)o+=" ";else typeof p=="string"&&(o=p);if(a=f,f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return c("",{"":d})})})()});var Ol=X((z0,bl)=>{var Xn=null,Qp=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,Zp=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,jp=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var n,i,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
16
- `,r:"\r",t:" "},r,a=function(g){throw{name:"SyntaxError",message:g,at:n,text:r}},u=function(g){return g&&g!==i&&a("Expected '"+g+"' instead of '"+i+"'"),i=r.charAt(n),n+=1,i},c=function(){var g,v="";for(i==="-"&&(v="-",u("-"));i>="0"&&i<="9";)v+=i,u();if(i===".")for(v+=".";u()&&i>="0"&&i<="9";)v+=i;if(i==="e"||i==="E")for(v+=i,u(),(i==="-"||i==="+")&&(v+=i,u());i>="0"&&i<="9";)v+=i,u();if(g=+v,!isFinite(g))a("Bad number");else return Xn==null&&(Xn=Io()),v.length>15?e.storeAsString?v:e.useNativeBigInt?BigInt(v):new Xn(v):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(g):new Xn(g):g},d=function(){var g,v,y="",A;if(i==='"')for(var C=n;u();){if(i==='"')return n-1>C&&(y+=r.substring(C,n-1)),u(),y;if(i==="\\"){if(n-1>C&&(y+=r.substring(C,n-1)),u(),i==="u"){for(A=0,v=0;v<4&&(g=parseInt(u(),16),!!isFinite(g));v+=1)A=A*16+g;y+=String.fromCharCode(A)}else if(typeof o[i]=="string")y+=o[i];else break;C=n}}a("Bad string")},f=function(){for(;i&&i<=" ";)u()},p=function(){switch(i){case"t":return u("t"),u("r"),u("u"),u("e"),!0;case"f":return u("f"),u("a"),u("l"),u("s"),u("e"),!1;case"n":return u("n"),u("u"),u("l"),u("l"),null}a("Unexpected '"+i+"'")},h,m=function(){var g=[];if(i==="["){if(u("["),f(),i==="]")return u("]"),g;for(;i;){if(g.push(h()),f(),i==="]")return u("]"),g;u(","),f()}}a("Bad array")},_=function(){var g,v=Object.create(null);if(i==="{"){if(u("{"),f(),i==="}")return u("}"),v;for(;i;){if(g=d(),f(),u(":"),e.strict===!0&&Object.hasOwnProperty.call(v,g)&&a('Duplicate key "'+g+'"'),Qp.test(g)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?h():v[g]=h():Zp.test(g)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?h():v[g]=h():v[g]=h(),f(),i==="}")return u("}"),v;u(","),f()}}a("Bad object")};return h=function(){switch(f(),i){case"{":return _();case"[":return m();case'"':return d();case"-":return c();default:return i>="0"&&i<="9"?c():p()}},function(g,v){var y;return r=g+"",n=0,i=" ",y=h(),f(),i&&a("Syntax error"),typeof v=="function"?(function A(C,S){var R,L,O=C[S];return O&&typeof O=="object"&&Object.keys(O).forEach(function(H){L=A(O,H),L!==void 0?O[H]=L:delete O[H]}),v.call(C,S,O)})({"":y},""):y}};bl.exports=jp});var Hl=X((Q0,Kn)=>{var ql=Ll().stringify,Fl=Ol();Kn.exports=function(t){return{parse:Fl(t),stringify:ql}};Kn.exports.parse=Fl();Kn.exports.stringify=ql});var So=X(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.GCE_LINUX_BIOS_PATHS=void 0;Ze.isGoogleCloudServerless=$l;Ze.isGoogleComputeEngineLinux=Jl;Ze.isGoogleComputeEngineMACAddress=Xl;Ze.isGoogleComputeEngine=Kl;Ze.detectGCPResidency=th;var Vl=ne("fs"),Bl=ne("os");Ze.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var eh=/^42:01/;function $l(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Jl(){if((0,Bl.platform)()!=="linux")return!1;try{(0,Vl.statSync)(Ze.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Vl.readFileSync)(Ze.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Xl(){let t=(0,Bl.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(eh.test(n))return!0}return!1}function Kl(){return Jl()||Xl()}function th(){return $l()||Kl()}});var Yl=X(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.Colours=void 0;var xe=class t{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process==null?void 0:process.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};Yn.Colours=xe;xe.enabled=!1;xe.reset="";xe.bright="";xe.dim="";xe.red="";xe.green="";xe.yellow="";xe.blue="";xe.magenta="";xe.cyan="";xe.white="";xe.grey="";xe.refresh()});var Zl=X(ce=>{"use strict";var nh=ce&&ce.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,o)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),ih=ce&&ce.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Wl=ce&&ce.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(i[i.length]=o);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),o=0;o<i.length;o++)i[o]!=="default"&&nh(n,e,i[o]);return ih(n,e),n}})();Object.defineProperty(ce,"__esModule",{value:!0});ce.env=ce.DebugLogBackendBase=ce.placeholder=ce.AdhocDebugLogger=ce.LogSeverity=void 0;ce.getNodeBackend=Ro;ce.getDebugBackend=rh;ce.getStructuredBackend=sh;ce.setBackend=ah;ce.log=Ql;var oh=ne("events"),An=Wl(ne("process")),zl=Wl(ne("util")),qe=Yl(),je;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(je||(ce.LogSeverity=je={}));var Cn=class extends oh.EventEmitter{constructor(e,n){super(),this.namespace=e,this.upstream=n,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(i,o)=>this.on(i,o)}),this.func.debug=(...i)=>this.invokeSeverity(je.DEBUG,...i),this.func.info=(...i)=>this.invokeSeverity(je.INFO,...i),this.func.warn=(...i)=>this.invokeSeverity(je.WARNING,...i),this.func.error=(...i)=>this.invokeSeverity(je.ERROR,...i),this.func.sublog=i=>Ql(i,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};ce.AdhocDebugLogger=Cn;ce.placeholder=new Cn("",()=>{}).func;var Yt=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=An.env[ce.env.nodeEnables])!==null&&e!==void 0?e:"*";n==="all"&&(n="*"),this.filters=n.split(",")}log(e,n,...i){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(n,...i)}catch(o){console.error(o)}}};ce.DebugLogBackendBase=Yt;var wo=class extends Yt{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...i)=>{var o;let r=`${qe.Colours.green}${e}${qe.Colours.reset}`,a=`${qe.Colours.yellow}${An.pid}${qe.Colours.reset}`,u;switch(n.severity){case je.ERROR:u=`${qe.Colours.red}${n.severity}${qe.Colours.reset}`;break;case je.INFO:u=`${qe.Colours.magenta}${n.severity}${qe.Colours.reset}`;break;case je.WARNING:u=`${qe.Colours.yellow}${n.severity}${qe.Colours.reset}`;break;default:u=(o=n.severity)!==null&&o!==void 0?o:je.DEFAULT;break}let c=zl.formatWithOptions({colors:qe.Colours.enabled},...i),d=Object.assign({},n);delete d.severity;let f=Object.getOwnPropertyNames(d).length?JSON.stringify(d):"",p=f?`${qe.Colours.grey}${f}${qe.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,r,u,c,f?` ${p}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function Ro(){return new wo}var Po=class extends Yt{constructor(e){super(),this.debugPkg=e}makeLogger(e){let n=this.debugPkg(e);return(i,...o)=>{n(o[0],...o.slice(1))}}setFilters(){var e;let n=(e=An.env.NODE_DEBUG)!==null&&e!==void 0?e:"";An.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function rh(t){return new Po(t)}var No=class extends Yt{constructor(e){var n;super(),this.upstream=(n=e)!==null&&n!==void 0?n:void 0}makeLogger(e){var n;let i=(n=this.upstream)===null||n===void 0?void 0:n.makeLogger(e);return(o,...r)=>{var a;let u=(a=o.severity)!==null&&a!==void 0?a:je.INFO,c=Object.assign({severity:u,message:zl.format(...r)},o),d=JSON.stringify(c);i?i(o,d):console.log("%s",d)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function sh(t){return new No(t)}ce.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var ko=new Map,Fe;function ah(t){Fe=t,ko.clear()}function Ql(t,e){if(!Fe&&!An.env[ce.env.nodeEnables]||!t)return ce.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=ko.get(t);if(n)return n.func;if(Fe===null)return ce.placeholder;Fe===void 0&&(Fe=Ro());let i=(()=>{let o;return new Cn(t,(a,...u)=>{if(o!==Fe){if(Fe===null)return;Fe===void 0&&(Fe=Ro()),o=Fe}Fe?.log(t,a,...u)})})();return ko.set(t,i),i.func}});var Do=X(Ht=>{"use strict";var lh=Ht&&Ht.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,o)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),uh=Ht&&Ht.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&lh(e,t,n)};Object.defineProperty(Ht,"__esModule",{value:!0});uh(Zl(),Ht)});var Sn=X(z=>{"use strict";var eu=z&&z.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,o)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),ch=z&&z.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),dh=z&&z.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(i[i.length]=o);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),o=0;o<i.length;o++)i[o]!=="default"&&eu(n,e,i[o]);return ch(n,e),n}})(),fh=z&&z.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&eu(e,t,n)};Object.defineProperty(z,"__esModule",{value:!0});z.gcpResidencyCache=z.METADATA_SERVER_DETECTION=z.HEADERS=z.HEADER_VALUE=z.HEADER_NAME=z.SECONDARY_HOST_ADDRESS=z.HOST_ADDRESS=z.BASE_PATH=void 0;z.instance=yh;z.project=Eh;z.universe=vh;z.bulk=Th;z.isAvailable=Ch;z.resetIsAvailableCache=Ih;z.getGCPResidency=Uo;z.setGCPResidency=tu;z.requestTimeout=nu;var xo=ke(),ph=Hl(),hh=So(),mh=dh(Do());z.BASE_PATH="/computeMetadata/v1";z.HOST_ADDRESS="http://169.254.169.254";z.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";z.HEADER_NAME="Metadata-Flavor";z.HEADER_VALUE="Google";z.HEADERS=Object.freeze({[z.HEADER_NAME]:z.HEADER_VALUE});var jl=mh.log("gcp-metadata");z.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function Mo(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||z.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(z.BASE_PATH,t).href}function gh(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function In(t,e={},n=3,i=!1){let o=new Headers(z.HEADERS),r="",a={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((h,m)=>o.set(m,h)),r=p.metadataKey,a=p.params||a,n=p.noResponseRetries||n,i=p.fastFail||i}else r=t;typeof e=="string"?r+=`/${e}`:(gh(e),e.property&&(r+=`/${e.property}`),new Headers(e.headers).forEach((p,h)=>o.set(h,p)),a=e.params||a);let u=i?_h:xo.request,c={url:`${Mo()}/${r}`,headers:o,retryConfig:{noResponseRetries:n},params:a,responseType:"text",timeout:nu()};jl.info("instance request %j",c);let d=await u(c);jl.info("instance metadata is %s",d.data);let f=d.headers.get(z.HEADER_NAME);if(f!==z.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${z.HEADER_NAME} header. Expected '${z.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return ph.parse(d.data)}catch{}return d.data}async function _h(t){let e={...t,url:t.url?.toString().replace(Mo(),Mo(z.SECONDARY_HOST_ADDRESS))},n=(0,xo.request)(t),i=(0,xo.request)(e);return Promise.any([n,i])}function yh(t){return In("instance",t)}function Eh(t){return In("project",t)}function vh(t){return In("universe",t)}async function Th(t){let e={};return await Promise.all(t.map(n=>(async()=>{let i=await In(n),o=n.metadataKey;e[o]=i})())),e}function Ah(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Wn;async function Ch(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in z.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(z.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return Uo();case"ping-only":}}try{return Wn===void 0&&(Wn=In("instance",void 0,Ah(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await Wn,!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let n="UNKNOWN";e.code&&(n=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${n}`,"MetadataLookupWarning")}return!1}}function Ih(){Wn=void 0}z.gcpResidencyCache=null;function Uo(){return z.gcpResidencyCache===null&&tu(),z.gcpResidencyCache}function tu(t=null){z.gcpResidencyCache=t!==null?t:(0,hh.detectGCPResidency)()}function nu(){return Uo()?0:3e3}fh(So(),z)});var ru=X(zn=>{"use strict";zn.byteLength=wh;zn.toByteArray=Ph;zn.fromByteArray=Dh;var st=[],Xe=[],Sh=typeof Uint8Array<"u"?Uint8Array:Array,Go="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Vt=0,iu=Go.length;Vt<iu;++Vt)st[Vt]=Go[Vt],Xe[Go.charCodeAt(Vt)]=Vt;var Vt,iu;Xe[45]=62;Xe[95]=63;function ou(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var i=n===e?0:4-n%4;return[n,i]}function wh(t){var e=ou(t),n=e[0],i=e[1];return(n+i)*3/4-i}function Rh(t,e,n){return(e+n)*3/4-n}function Ph(t){var e,n=ou(t),i=n[0],o=n[1],r=new Sh(Rh(t,i,o)),a=0,u=o>0?i-4:i,c;for(c=0;c<u;c+=4)e=Xe[t.charCodeAt(c)]<<18|Xe[t.charCodeAt(c+1)]<<12|Xe[t.charCodeAt(c+2)]<<6|Xe[t.charCodeAt(c+3)],r[a++]=e>>16&255,r[a++]=e>>8&255,r[a++]=e&255;return o===2&&(e=Xe[t.charCodeAt(c)]<<2|Xe[t.charCodeAt(c+1)]>>4,r[a++]=e&255),o===1&&(e=Xe[t.charCodeAt(c)]<<10|Xe[t.charCodeAt(c+1)]<<4|Xe[t.charCodeAt(c+2)]>>2,r[a++]=e>>8&255,r[a++]=e&255),r}function Nh(t){return st[t>>18&63]+st[t>>12&63]+st[t>>6&63]+st[t&63]}function kh(t,e,n){for(var i,o=[],r=e;r<n;r+=3)i=(t[r]<<16&16711680)+(t[r+1]<<8&65280)+(t[r+2]&255),o.push(Nh(i));return o.join("")}function Dh(t){for(var e,n=t.length,i=n%3,o=[],r=16383,a=0,u=n-i;a<u;a+=r)o.push(kh(t,a,a+r>u?u:a+r));return i===1?(e=t[n-1],o.push(st[e>>2]+st[e<<4&63]+"==")):i===2&&(e=(t[n-2]<<8)+t[n-1],o.push(st[e>>10]+st[e>>4&63]+st[e<<2&63]+"=")),o.join("")}});var bo=X(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.fromArrayBufferToHex=xh;function xh(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var su=X(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.BrowserCrypto=void 0;var Wt=ru(),Mh=bo(),Oo=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let n=new TextEncoder().encode(e),i=await window.crypto.subtle.digest("SHA-256",n);return Wt.fromByteArray(new Uint8Array(i))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),Wt.fromByteArray(n)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,n,i){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},r=new TextEncoder().encode(n),a=Wt.toByteArray(t.padBase64(i)),u=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,u,Buffer.from(a),r)}async sign(e,n){let i={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(n),r=await window.crypto.subtle.importKey("jwk",e,i,!0,["sign"]),a=await window.crypto.subtle.sign(i,r,o);return Wt.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let n=Wt.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return Wt.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),i=await window.crypto.subtle.digest("SHA-256",n);return(0,Mh.fromArrayBufferToHex)(i)}async signWithHmacSha256(e,n){let i=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,r=await window.crypto.subtle.importKey("raw",o.encode(i),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",r,o.encode(n))}};Qn.BrowserCrypto=Oo});var au=X(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.NodeCrypto=void 0;var zt=ne("crypto"),qo=class{async sha256DigestBase64(e){return zt.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return zt.randomBytes(e).toString("base64")}async verify(e,n,i){let o=zt.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,i,"base64")}async sign(e,n){let i=zt.createSign("RSA-SHA256");return i.update(n),i.end(),i.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return zt.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let i=typeof e=="string"?e:Gh(e);return Uh(zt.createHmac("sha256",i).update(n).digest())}};Zn.NodeCrypto=qo;function Uh(t){let e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let i=0;i<t.length;++i)n[i]=t[i];return e}function Gh(t){return Buffer.from(t)}});var wn=X(ht=>{"use strict";var Lh=ht&&ht.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,o)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),bh=ht&&ht.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Lh(e,t,n)};Object.defineProperty(ht,"__esModule",{value:!0});ht.createCrypto=Fh;ht.hasBrowserCrypto=lu;var Oh=su(),qh=au();bh(bo(),ht);function Fh(){return lu()?new Oh.BrowserCrypto:new qh.NodeCrypto}function lu(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var et=X(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.LRUCache=void 0;mt.snakeToCamel=cu;mt.originalOrCamelOptions=$h;mt.removeUndefinedValuesInObject=Jh;mt.isValidFile=Xh;mt.getWellKnownCertificateConfigFileLocation=Kh;var Hh=ne("fs"),Vh=ne("os"),Fo=ne("path"),Bh="certificate_config.json",uu="gcloud";function cu(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function $h(t){function e(n){let i=t||{};return i[n]??i[cu(n)]}return{get:e}}var Ho=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};mt.LRUCache=Ho;function Jh(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function Xh(t){try{return(await Hh.promises.lstat(t)).isFile()}catch{return!1}}function Kh(){let t=process.env.CLOUDSDK_CONFIG||(Yh()?Fo.join(process.env.APPDATA||"",uu):Fo.join(process.env.HOME||"",".config",uu));return Fo.join(t,Bh)}function Yh(){return Vh.platform().startsWith("win")}});var du=X((uS,Wh)=>{Wh.exports={name:"google-auth-library",version:"10.9.1",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"core/packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"21.0.3","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs"}});var Vo=X(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.USER_AGENT=Ct.PRODUCT_NAME=Ct.pkg=void 0;var fu=du();Ct.pkg=fu;var pu="google-api-nodejs-client";Ct.PRODUCT_NAME=pu;var zh=`${pu}/${fu.version}`;Ct.USER_AGENT=zh});var He=X(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.AuthClient=tt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=tt.DEFAULT_UNIVERSE=void 0;var Qh=ne("events"),Bo=ke(),Zh=et(),jh=Do(),$o=Vo();tt.DEFAULT_UNIVERSE="googleapis.com";tt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Jo=class t extends Qh.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=tt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=tt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,Zh.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??tt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Bo.Gaxios(e.transporterOptions),n.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let n=e[0],i=e[1],o,r=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&Bo.Gaxios.mergeHeaders(r,n.headers),i&&Bo.Gaxios.mergeHeaders(r,new Headers(i.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...i,...n,headers:r,url:o}):this.request({...i,headers:r,url:o})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,n){let i=n.get("x-goog-user-project"),o=n.get("authorization");return i&&e.set("x-goog-user-project",i),o&&e.set("authorization",o),e}static log=(0,jh.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let i=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${i}`)}let n=e.headers.get("User-Agent");n?n.includes(`${$o.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${$o.USER_AGENT}`):e.headers.set("User-Agent",$o.USER_AGENT);try{let i=e,o=i[t.RequestMethodNameSymbol],r=`${Math.floor(Math.random()*1e3)}`;i[t.RequestLogIdSymbol]=r;let a={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,r,a):t.log.info("[%s] request %j",r,a)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,i=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];i?t.log.info("%s [%s] response %j",i,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,i=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];i?t.log.info("%s [%s] error %j",i,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let i=e;i[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};tt.AuthClient=Jo});var Ko=X(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.LoginTicket=void 0;var Xo=class{envelope;payload;constructor(e,n){this.envelope=e,this.payload=n}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};jn.LoginTicket=Xo});var It=X(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.OAuth2Client=at.ClientAuthentication=at.CertificateFormat=at.CodeChallengeMethod=void 0;var hu=ke(),em=ne("querystring"),tm=ne("stream"),nm=Mp(),mu=et(),Yo=wn(),Qt=He(),im=Ko(),gu;(function(t){t.Plain="plain",t.S256="S256"})(gu||(at.CodeChallengeMethod=gu={}));var gt;(function(t){t.PEM="PEM",t.JWK="JWK"})(gt||(at.CertificateFormat=gt={}));var Rn;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Rn||(at.ClientAuthentication=Rn={}));var Wo=class t extends Qt.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=gt.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,i){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:n,redirectUri:i}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||Rn.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+em.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Yo.createCrypto)(),i=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),r=(await e.sha256DigestBase64(i)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:i,codeChallenge:r}}getToken(e,n){let i=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(i).then(o=>n(null,o.tokens,o.res),o=>n(o,null,o.response));else return this.getTokenAsync(i)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),i=new Headers,o={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===Rn.ClientSecretBasic){let c=Buffer.from(`${this._clientId}:${this._clientSecret}`);i.set("authorization",`Basic ${c.toString("base64")}`)}this.clientAuthentication===Rn.ClientSecretPost&&(o.client_secret=this._clientSecret);let r={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,mu.removeUndefinedValuesInObject)(o)),headers:i};Qt.AuthClient.setMethodName(r,"getTokenAsync");let a=await this.transporter.request(r),u=a.data;return a.data&&a.data.expires_in&&(u.expiry_date=new Date().getTime()+a.data.expires_in*1e3,delete u.expires_in),this.emit("tokens",u),{tokens:u,res:a}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let n=this.refreshTokenNoCache(e).then(i=>(this.refreshTokenPromises.delete(e),i),i=>{throw this.refreshTokenPromises.delete(e),i});return this.refreshTokenPromises.set(e,n),n}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let n=this.endpoints.oauth2TokenUrl.toString(),i={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let a={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,mu.removeUndefinedValuesInObject)(i))};Qt.AuthClient.setMethodName(a,"refreshTokenNoCache"),o=await this.transporter.request(a)}catch(a){throw a instanceof hu.GaxiosError&&a.message==="invalid_grant"&&a.response?.data&&/ReAuth/i.test(a.response.data.error_description)&&(a.message=JSON.stringify(a.response.data)),a}let r=o.data;return o.data&&o.data.expires_in&&(r.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(n=>e(null,n.credentials,n.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),n=e.tokens;return n.refresh_token=this.credentials.refresh_token,this.credentials=n,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let i=await this.processAndValidateRefreshHandler();if(i?.access_token)return this.setCredentials(i),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token)throw new Error("Could not refresh access token.");return{token:n.credentials.access_token,res:n.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";let u=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(u)}}if(this.refreshHandler){let u=await this.processAndValidateRefreshHandler();if(u?.access_token){this.setCredentials(u);let c=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(c)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let i=null,o=null;try{i=await this.refreshToken(n.refresh_token),o=i.tokens}catch(u){let c=u;throw c.response&&(c.response.status===403||c.response.status===404)&&(c.message=`Could not refresh access token: ${c.message}`),c}let r=this.credentials;r.token_type=r.token_type||"Bearer",o.refresh_token=r.refresh_token,this.credentials=o;let a=new Headers({authorization:r.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(a),res:i.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let n=new URL(this.endpoints.oauth2RevokeUrl);return n.searchParams.append("token",e),n}revokeToken(e,n){let i={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(Qt.AuthClient.setMethodName(i,"revokeToken"),n)this.transporter.request(i).then(o=>n(null,o),n);else return this.transporter.request(i)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(n=>e(null,n),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,n){if(n)this.requestAsync(e).then(i=>n(null,i),i=>n(i,i.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){try{let i=await this.getRequestMetadataAsync();return e.headers=hu.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,i.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(i){let o=i.response;if(o){let r=o.status,a=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),u=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,c=o.config.data instanceof tm.Readable,d=r===401||r===403;if(!n&&d&&!c&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&d&&!c&&u){let f=await this.processAndValidateRefreshHandler();return f?.access_token&&this.setCredentials(f),this.requestAsync(e,!0)}}throw i}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(i=>n(null,i),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),i=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete i.expires_in,delete i.scope,i}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,Yo.hasBrowserCrypto)()?gt.JWK:gt.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let i,o;switch(n){case gt.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case gt.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:o};Qt.AuthClient.setMethodName(d,"getFederatedSignonCertsAsync"),i=await this.transporter.request(d)}catch(d){throw d instanceof Error&&(d.message=`Failed to retrieve verification certificates: ${d.message}`),d}let r=i?.headers.get("cache-control"),a=-1;if(r){let d=/max-age=(?<maxAge>[0-9]+)/.exec(r)?.groups?.maxAge;d&&(a=Number(d)*1e3)}let u={};switch(n){case gt.PEM:u=i.data;break;case gt.JWK:for(let d of i.data.keys)u[d.kid]=d;break;default:throw new Error(`Unsupported certificate format ${n}`)}let c=new Date;return this.certificateExpiry=a===-1?null:new Date(c.getTime()+a),this.certificateCache=u,this.certificateCacheFormat=n,{certs:u,format:n,res:i}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let i={...t.RETRY_CONFIG,url:n};Qt.AuthClient.setMethodName(i,"getIapPublicKeysAsync"),e=await this.transporter.request(i)}catch(i){throw i instanceof Error&&(i.message=`Failed to retrieve verification certificates: ${i.message}`),i}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,i,o,r){let a=(0,Yo.createCrypto)();r||(r=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let u=e.split(".");if(u.length!==3)throw new Error("Wrong number of segments in token: "+e);let c=u[0]+"."+u[1],d=u[2],f,p;try{f=JSON.parse(a.decodeBase64StringUtf8(u[0]))}catch(C){throw C instanceof Error&&(C.message=`Can't parse token envelope: ${u[0]}': ${C.message}`),C}if(!f)throw new Error("Can't parse token envelope: "+u[0]);try{p=JSON.parse(a.decodeBase64StringUtf8(u[1]))}catch(C){throw C instanceof Error&&(C.message=`Can't parse token payload '${u[0]}`),C}if(!p)throw new Error("Can't parse token payload: "+u[1]);if(!Object.prototype.hasOwnProperty.call(n,f.kid))throw new Error("No pem found for envelope: "+JSON.stringify(f));let h=n[f.kid];if(f.alg==="ES256"&&(d=nm.joseToDer(d,"ES256").toString("base64")),!await a.verify(h,c,d))throw new Error("Invalid token signature: "+e);if(!p.iat)throw new Error("No issue time in token: "+JSON.stringify(p));if(!p.exp)throw new Error("No expiration time in token: "+JSON.stringify(p));let _=Number(p.iat);if(isNaN(_))throw new Error("iat field using invalid format");let g=Number(p.exp);if(isNaN(g))throw new Error("exp field using invalid format");let v=new Date().getTime()/1e3;if(g>=v+r)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let y=_-t.CLOCK_SKEW_SECS_,A=g+t.CLOCK_SKEW_SECS_;if(v<y)throw new Error("Token used too early, "+v+" < "+y+": "+JSON.stringify(p));if(v>A)throw new Error("Token used too late, "+v+" > "+A+": "+JSON.stringify(p));if(o&&o.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+p.iss);if(typeof i<"u"&&i!==null){let C=p.aud,S=!1;if(i.constructor===Array?S=i.indexOf(C)>-1:S=C===i,!S)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new im.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};at.OAuth2Client=Wo});var Qo=X(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.Compute=void 0;var om=ke(),_u=Sn(),rm=It(),zo=class extends rm.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,n;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),n=await _u.instance(o)}catch(o){throw o instanceof om.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let i=n;return n&&n.expires_in&&(i.expiry_date=new Date().getTime()+n.expires_in*1e3,delete i.expires_in),this.emit("tokens",i),{tokens:i,res:null}}async fetchIdToken(e){let n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,i;try{let o={property:n};i=await _u.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return i}wrapError(e){let n=e.response;n&&n.status&&(e.status=n.status,n.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:n.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};ei.Compute=zo});var jo=X(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.IdTokenClient=void 0;var sm=It(),Zo=class extends sm.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let n=e.split(".")[1];if(n)return JSON.parse(Buffer.from(n,"base64").toString("ascii")).exp*1e3}};ti.IdTokenClient=Zo});var er=X(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.GCPEnv=void 0;Zt.clear=am;Zt.getEnv=lm;var yu=Sn(),lt;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(lt||(Zt.GCPEnv=lt={}));var Pn;function am(){Pn=void 0}async function lm(){return Pn||(Pn=um(),Pn)}async function um(){let t=lt.NONE;return cm()?t=lt.APP_ENGINE:dm()?t=lt.CLOUD_FUNCTIONS:await mm()?await hm()?t=lt.KUBERNETES_ENGINE:fm()?t=lt.CLOUD_RUN:pm()?t=lt.CLOUD_RUN_JOBS:t=lt.COMPUTE_ENGINE:t=lt.NONE,t}function cm(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function dm(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function fm(){return!!process.env.K_CONFIGURATION}function pm(){return!!process.env.CLOUD_RUN_JOB}async function hm(){try{return await yu.instance("attributes/cluster-name"),!0}catch{return!1}}async function mm(){return yu.isAvailable()}});var vu=X(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.buildPayloadForJwsSign=Eu;ni.getJwsSign=Em;var gm=ol(),_m="RS256",ym="https://oauth2.googleapis.com/token";function Eu(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:ym,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function Em(t){let e=Eu(t);return(0,gm.sign)({header:{alg:_m},payload:e,secret:t.key})}});var Tu=X(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.getToken=Im;var vm=vu(),Tm="https://oauth2.googleapis.com/token",Am="urn:ietf:params:oauth:grant-type:jwt-bearer",Cm=t=>({method:"POST",url:Tm,data:new URLSearchParams({grant_type:Am,assertion:(0,vm.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function Im(t){if(!t.transporter)throw new Error("No transporter set.");try{let e=Cm(t);return(await t.transporter.request(e)).data}catch(e){let n=e,i=n.response?.data;throw i?.error&&(n.message=`${i.error}: ${i.error_description}`),n}}});var Au=X(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.ErrorWithCode=void 0;var nr=class extends Error{code;constructor(e,n){super(e),this.code=n}};ii.ErrorWithCode=nr});var lr=X(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.getCredentials=Rm;var Sm=ne("path"),Cu=ne("fs"),wm=ne("util"),oi=Au(),Iu=Cu.readFile?(0,wm.promisify)(Cu.readFile):async()=>{throw new oi.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},St;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(St||(St={}));var ir=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await Iu(this.keyFilePath,"utf8"),n;try{n=JSON.parse(e)}catch(r){let a=r;throw new Error(`Invalid JSON key file: ${a.message}`)}let i=n.private_key,o=n.client_email;if(!i||!o)throw new oi.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:i,clientEmail:o}}},or=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await Iu(this.keyFilePath,"utf8")}}},rr=class{async getCredentials(){throw new oi.ErrorWithCode("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE")}},sr=class{static create(e){switch(Sm.extname(e)){case St.JSON:return new ir(e);case St.DER:case St.CRT:case St.PEM:return new or(e);case St.P12:case St.PFX:return new rr;default:throw new oi.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function Rm(t){return sr.create(t).getCredentials()}});var Su=X(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.TokenHandler=void 0;var Pm=Tu(),Nm=lr(),ur=class{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw new Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let e=await(0,Nm.getCredentials)(this.tokenOptions.keyFile);this.tokenOptions.key=e.privateKey,this.tokenOptions.email=e.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;let e=new Date().getTime(),n=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+n}hasExpired(){let e=new Date().getTime();return this.token&&this.tokenExpiresAt?new Date().getTime()>=this.tokenExpiresAt:!0}async getToken(e){if(await this.processCredentials(),this.inFlightRequest&&!e)return this.inFlightRequest;if(this.token&&!this.isTokenExpiring()&&!e)return this.token;try{this.inFlightRequest=(0,Pm.getToken)(this.tokenOptions);let n=await this.inFlightRequest;return this.token=n,this.tokenExpiresAt=new Date().getTime()+(n.expires_in??0)*1e3,n}finally{this.inFlightRequest=void 0}}};ri.TokenHandler=ur});var wu=X(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.revokeToken=xm;var km="https://oauth2.googleapis.com/revoke?token=",Dm=!0;async function xm(t,e){let n=km+t;return await e.request({url:n,retry:Dm})}});var fr=X(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.GoogleToken=void 0;var Mm=ke(),Ru=Su(),Um=wu(),dr=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,Mm.request)(n)},this.tokenOptions.iss||(this.tokenOptions.iss=this.tokenOptions.email),typeof this.tokenOptions.scope=="object"&&(this.tokenOptions.scope=this.tokenOptions.scope.join(" ")),this.tokenHandler=new Ru.TokenHandler(this.tokenOptions)}get expiresAt(){return this.tokenHandler.tokenExpiresAt}get accessToken(){return this.tokenHandler.token?.access_token}get idToken(){return this.tokenHandler.token?.id_token}get tokenType(){return this.tokenHandler.token?.token_type}get refreshToken(){return this.tokenHandler.token?.refresh_token}hasExpired(){return this.tokenHandler.hasExpired()}isTokenExpiring(){return this.tokenHandler.isTokenExpiring()}getToken(e,n={forceRefresh:!1}){let i;typeof e=="function"?i=e:typeof e=="object"&&(n=e);let o=this.tokenHandler.getToken(n.forceRefresh??!1);return i&&o.then(r=>i(null,r),i),o}revokeToken(e){if(!this.accessToken)return Promise.reject(new Error("No token to revoke."));let n=(0,Um.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new Ru.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};si.GoogleToken=dr});var hr=X(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.JWTAccess=void 0;var Gm=ol(),Lm=et(),Pu={alg:"RS256",typ:"JWT"},pr=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new Lm.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,n,i,o){this.email=e,this.key=n,this.keyId=i,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,n){let i=e;if(n&&Array.isArray(n)&&n.length?i=e?`${e}_${n.join("_")}`:`${n.join("_")}`:typeof n=="string"&&(i=e?`${e}_${n}`:n),!i)throw Error("Scopes or url must be provided");return i}getRequestHeaders(e,n,i){let o=this.getCachedKey(e,i),r=this.cache.get(o),a=Date.now();if(r&&r.expiration-a>this.eagerRefreshThresholdMillis)return new Headers(r.headers);let u=Math.floor(Date.now()/1e3),c=t.getExpirationTime(u),d;if(Array.isArray(i)&&(i=i.join(" ")),i?d={iss:this.email,sub:this.email,scope:i,exp:c,iat:u}:d={iss:this.email,sub:this.email,aud:e,exp:c,iat:u},n){for(let _ in d)if(n[_])throw new Error(`The '${_}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...Pu,kid:this.keyId}:Pu,p=Object.assign(d,n),h=Gm.sign({header:f,payload:p,secret:this.key}),m=new Headers({authorization:`Bearer ${h}`});return this.cache.set(o,{expiration:c*1e3,headers:m}),m}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,i)=>{e||i(new Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",r=>o+=r).on("error",i).on("end",()=>{try{let r=JSON.parse(o);this.fromJSON(r),n()}catch(r){i(r)}})})}};ai.JWTAccess=pr});var gr=X(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.JWT=void 0;var Nu=fr(),bm=lr(),Om=hr(),qm=It(),li=He(),mr=class t extends qm.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let n=new t(this);return n.scopes=e,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==li.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==li.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${li.DEFAULT_UNIVERSE}`);if(!this.apiKey&&n)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:i}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${i.id_token}`}))}}else{this.access||(this.access=new Om.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let i;this.hasUserScopes()?i=this.scopes:e||(i=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==li.DEFAULT_UNIVERSE,r=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?i:void 0);return{headers:this.addSharedMetadataHeaders(r)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new Nu.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await n.getToken({forceRefresh:!0}),!n.idToken)throw new Error("Unknown error: Failed to fetch ID token");return n.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(n=>e(null,n),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),i={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",i),{res:null,tokens:i}}createGToken(){return this.gtoken||(this.gtoken=new Nu.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,i)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",i).on("data",r=>o+=r).on("end",()=>{try{let r=JSON.parse(o);this.fromJSON(r),n()}catch(r){i(r)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let e=this.createGToken(),n=await(0,bm.getCredentials)(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};ui.JWT=mr});var yr=X(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.UserRefreshClient=jt.USER_REFRESH_ACCOUNT_TYPE=void 0;var Fm=It(),Hm=He();jt.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var _r=class t extends Fm.OAuth2Client{_refreshToken;constructor(e,n,i,o,r){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:i,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:r};super(a),this._refreshToken=a.refreshToken,this.credentials.refresh_token=a.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let n={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e}),responseType:"json"};return Hm.AuthClient.setMethodName(n,"fetchIdToken"),(await this.transporter.request(n)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((n,i)=>{if(!e)return i(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",i).on("data",r=>o+=r).on("end",()=>{try{let r=JSON.parse(o);return this.fromJSON(r),n()}catch(r){return i(r)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};jt.UserRefreshClient=_r});var vr=X(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.Impersonated=en.IMPERSONATED_ACCOUNT_TYPE=void 0;var ku=It(),Vm=ke(),Bm=et();en.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Er=class t extends ku.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new ku.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,Bm.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,i=`${this.endpoint}/v1/${n}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:i,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,n=`${this.endpoint}/v1/${e}:generateAccessToken`,i={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:i,method:"POST"}),r=o.data;return this.credentials.access_token=r.accessToken,this.credentials.expiry_date=Date.parse(r.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let n=0,i="";throw e instanceof Vm.GaxiosError&&(n=e?.response?.data?.error?.status,i=e?.response?.data?.error?.message),n&&i?(e.message=`${n}: unable to impersonate: ${i}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();let i=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${i}:generateIdToken`,r={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:r,method:"POST"})).data.token}};en.Impersonated=Er});var Ar=X(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.OAuthClientAuthHandler=void 0;Nn.getErrorFromOAuthErrorResponse=Xm;var tn=ke(),$m=wn(),Jm=["PUT","POST","PATCH"],Tr=class{#e=(0,$m.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new tn.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new tn.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=tn.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=tn.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=tn.Gaxios.mergeHeaders(e.headers);let i=this.#t.clientId,o=this.#t.clientSecret||"",r=this.#e.encodeBase64StringUtf8(`${i}:${o}`);tn.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${r}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!Jm.includes(n))throw new Error(`${n} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let r=new URLSearchParams(e.data??"");r.append("client_id",this.#t.clientId),r.append("client_secret",this.#t.clientSecret||""),e.data=r}else if(o?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${o} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Nn.OAuthClientAuthHandler=Tr;function Xm(t,e){let n=t.error,i=t.error_description,o=t.error_uri,r=`Error code ${n}`;typeof i<"u"&&(r+=`: ${i}`),typeof o<"u"&&(r+=` - ${o}`);let a=new Error(r);if(e){let u=Object.keys(e);e.stack&&u.push("stack"),u.forEach(c=>{c!=="message"&&Object.defineProperty(a,c,{value:e[c],writable:!1,enumerable:!0})})}return a}});var di=X(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.StsCredentials=void 0;var Km=ke(),Ym=He(),Du=Ar(),Wm=et(),Cr=class t extends Du.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:n}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,i){let o={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:i&&JSON.stringify(i)},r={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,Wm.removeUndefinedValuesInObject)(o)),responseType:"json"};Ym.AuthClient.setMethodName(r,"exchangeToken"),this.applyClientAuthenticationOptions(r);try{let a=await this.transporter.request(r),u=a.data;return u.res=a,u}catch(a){throw a instanceof Km.GaxiosError&&a.response?(0,Du.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};ci.StsCredentials=Cr});var wt=X(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.BaseExternalAccountClient=Ke.CLOUD_RESOURCE_MANAGER=Ke.EXTERNAL_ACCOUNT_TYPE=Ke.EXPIRATION_TIME_OFFSET=void 0;var zm=ke(),Qm=ne("stream"),Ir=He(),Zm=di(),xu=et(),jm=Vo(),eg="urn:ietf:params:oauth:grant-type:token-exchange",tg="urn:ietf:params:oauth:token-type:access_token",Sr="https://www.googleapis.com/auth/cloud-platform",ng=3600;Ke.EXPIRATION_TIME_OFFSET=300*1e3;Ke.EXTERNAL_ACCOUNT_TYPE="external_account";Ke.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var ig="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",og="https://sts.{universeDomain}/v1/token",wr=class t extends Ir.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,xu.originalOrCamelOptions)(e),i=n.get("type");if(i&&i!==Ke.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Ke.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=n.get("client_id"),r=n.get("client_secret");this.tokenUrl=n.get("token_url")??og.replace("{universeDomain}",this.universeDomain);let a=n.get("subject_token_type"),u=n.get("workforce_pool_user_project"),c=n.get("service_account_impersonation_url"),d=n.get("service_account_impersonation"),f=(0,xu.originalOrCamelOptions)(d).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:r}),this.stsCredential=new Zm.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[Sr],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=u;let p=new RegExp(ig);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=c,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=ng),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(i=>n(null,i),i=>n(i,i.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),i={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};Ir.AuthClient.setMethodName(i,"getProjectId");let o=await this.transporter.request(i);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let i;try{let o=await this.getRequestHeaders();e.headers=zm.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),i=await this.transporter.request(e)}catch(o){let r=o.response;if(r){let a=r.status,u=r.config.data instanceof Qm.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return i}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:eg,audience:this.audience,requestedTokenType:tg,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Sr]:this.getScopesArray()},i=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),r=await this.stsCredential.exchangeToken(n,o,i);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(r.access_token):r.expires_in?this.cachedAccessToken={access_token:r.access_token,expiry_date:new Date().getTime()+r.expires_in*1e3,res:r.res}:this.cachedAccessToken={access_token:r.access_token,res:r.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};Ir.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let i=await this.transporter.request(n),o=i.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:i}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[Sr]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,i=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${jm.pkg.version} google-byoid-sdk source/${i} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Ke.BaseExternalAccountClient=wr});var Mu=X(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.FileSubjectTokenSupplier=void 0;var Pr=ne("util"),Nr=ne("fs"),rg=(0,Pr.promisify)(Nr.readFile??(()=>{})),sg=(0,Pr.promisify)(Nr.realpath??(()=>{})),ag=(0,Pr.promisify)(Nr.lstat??(()=>{})),Rr=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await sg(e),!(await ag(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n,i=await rg(e,{encoding:"utf8"});if(this.formatType==="text"?n=i:this.formatType==="json"&&this.subjectTokenFieldName&&(n=JSON.parse(i)[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source file");return n}};fi.FileSubjectTokenSupplier=Rr});var Uu=X(pi=>{"use strict";Object.defineProperty(pi,"__esModule",{value:!0});pi.UrlSubjectTokenSupplier=void 0;var lg=He(),kr=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};lg.AuthClient.setMethodName(n,"getSubjectToken");let i;if(this.formatType==="text"?i=(await e.transporter.request(n)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(i=(await e.transporter.request(n)).data[this.subjectTokenFieldName]),!i)throw new Error("Unable to parse the subject_token from the credential_source URL");return i}};pi.UrlSubjectTokenSupplier=kr});var Gu=X(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.CertificateSubjectTokenSupplier=Ve.InvalidConfigurationError=Ve.CertificateSourceUnavailableError=Ve.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var hi=et(),mi=ne("fs"),gi=ne("crypto"),ug=ne("https");Ve.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var ut=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Ve.CertificateSourceUnavailableError=ut;var Ye=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Ve.InvalidConfigurationError=Ye;var Dr=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Ye("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Ye("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Ye("Cannot create mTLS Agent with missing certificate or key");return new ug.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:n}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,n),await this.#i(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,hi.isValidFile)(e))return e;throw new ut(`Provided certificate config path is invalid: ${e}`)}let n=process.env[Ve.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,hi.isValidFile)(n))return n;throw new ut(`Path from environment variable "${Ve.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let i=(0,hi.getWellKnownCertificateConfigFileLocation)();if(await(0,hi.isValidFile)(i))return i;throw new ut(`Could not find certificate configuration file. Searched override path, the "${Ve.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${i}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await mi.promises.readFile(e,"utf8")}catch{throw new ut(`Failed to read certificate config file at: ${e}`)}try{let i=JSON.parse(n),o=i?.cert_configs?.workload?.cert_path,r=i?.cert_configs?.workload?.key_path;if(!o||!r)throw new Ye(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:r}}catch(i){throw i instanceof Ye?i:new Ye(`Failed to parse certificate config from ${e}: ${i.message}`)}}async#n(e,n){let i,o;try{i=await mi.promises.readFile(e),new gi.X509Certificate(i)}catch(r){let a=r instanceof Error?r.message:String(r);throw new ut(`Failed to read certificate file at ${e}: ${a}`)}try{o=await mi.promises.readFile(n),(0,gi.createPrivateKey)(o)}catch(r){let a=r instanceof Error?r.message:String(r);throw new ut(`Failed to read private key file at ${n}: ${a}`)}return{cert:i,key:o}}async#i(e){let n=new gi.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let r=((await mi.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((c,d)=>{try{return new gi.X509Certificate(c)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Ye(`Failed to parse certificate at index ${d} in trust chain file ${this.trustChainPath}: ${p}`)}}),a=r.findIndex(c=>n.raw.equals(c.raw)),u;if(a===-1)u=[n,...r];else if(a===0)u=r;else throw new Ye(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${a}).`);return JSON.stringify(u.map(c=>c.raw.toString("base64")))}catch(i){if(i instanceof Ye)throw i;let o=i instanceof Error?i.message:String(i);throw new ut(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};Ve.CertificateSubjectTokenSupplier=Dr});var Ur=X(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.IdentityPoolClient=void 0;var cg=wt(),xr=et(),dg=Mu(),fg=Uu(),Lu=Gu(),pg=di(),bu=ke(),Mr=class t extends cg.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,xr.originalOrCamelOptions)(e),i=n.get("credential_source"),o=n.get("subject_token_supplier");if(!i&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(i&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let r=(0,xr.originalOrCamelOptions)(i),a=(0,xr.originalOrCamelOptions)(r.get("format")),u=a.get("type")||"text",c=a.get("subject_token_field_name");if(u!=="json"&&u!=="text")throw new Error(`Invalid credential_source format "${u}"`);if(u==="json"&&!c)throw new Error("Missing subject_token_field_name for JSON credential_source format");let d=r.get("file"),f=r.get("url"),p=r.get("certificate"),h=r.get("headers");if(d&&f||f&&p||d&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(d)this.credentialSourceType="file",this.subjectTokenSupplier=new dg.FileSubjectTokenSupplier({filePath:d,formatType:u,subjectTokenFieldName:c});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new fg.UrlSubjectTokenSupplier({url:f,formatType:u,subjectTokenFieldName:c,headers:h,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let m=new Lu.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=m}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof Lu.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new pg.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new bu.Gaxios({agent:n})}),this.transporter=new bu.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};_i.IdentityPoolClient=Mr});var Lr=X(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.AwsRequestSigner=void 0;var yi=ke(),qu=wn(),Ou="AWS4-HMAC-SHA256",hg="aws4_request",Gr=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,qu.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let n=typeof e.data=="object"?JSON.stringify(e.data):e.data,i=e.url,o=e.method||"GET",r=e.body||n,a=e.headers,u=await this.getCredentials(),c=new URL(i);if(typeof r!="string"&&r!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${r}`);let d=await gg({crypto:this.crypto,host:c.host,canonicalUri:c.pathname,canonicalQuerystring:c.search.slice(1),method:o,region:this.region,securityCredentials:u,requestPayload:r,additionalAmzHeaders:a}),f=yi.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:c.host},a||{});u.token&&yi.Gaxios.mergeHeaders(f,{"x-amz-security-token":u.token});let p={url:i,method:o,headers:f};return r!==void 0&&(p.body=r),p}};Ei.AwsRequestSigner=Gr;async function kn(t,e,n){return await t.signWithHmacSha256(e,n)}async function mg(t,e,n,i,o){let r=await kn(t,`AWS4${e}`,n),a=await kn(t,r,i),u=await kn(t,a,o);return await kn(t,u,"aws4_request")}async function gg(t){let e=yi.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",i=t.host.split(".")[0],o=new Date,r=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),a=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let u=yi.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":r},e),c="",d=[...u.keys()].sort();d.forEach(A=>{c+=`${A}:${u.get(A)}
17
- `});let f=d.join(";"),p=await t.crypto.sha256DigestHex(n),h=`${t.method.toUpperCase()}
18
- ${t.canonicalUri}
19
- ${t.canonicalQuerystring}
20
- ${c}
21
- ${f}
22
- ${p}`,m=`${a}/${t.region}/${i}/${hg}`,_=`${Ou}
23
- ${r}
24
- ${m}
25
- `+await t.crypto.sha256DigestHex(h),g=await mg(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,i),v=await kn(t.crypto,g,_),y=`${Ou} Credential=${t.securityCredentials.accessKeyId}/${m}, SignedHeaders=${f}, Signature=${(0,qu.fromArrayBufferToHex)(v)}`;return{amzDate:e.has("date")?void 0:r,authorizationHeader:y,canonicalQuerystring:t.canonicalQuerystring}}});var Fu=X(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.DefaultAwsSecurityCredentialsSupplier=void 0;var vi=He(),br=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#i)return this.#i;let n=new Headers;if(!this.#i&&this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let i={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:n};vi.AuthClient.setMethodName(i,"getAwsRegion");let o=await e.transporter.request(i);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let n=new Headers;this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let i=await this.#t(n,e.transporter),o=await this.#n(i,n,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return vi.AuthClient.setMethodName(n,"#getImdsV2SessionToken"),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let i={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:e};return vi.AuthClient.setMethodName(i,"#getAwsRoleName"),(await n.request(i)).data}async#n(e,n,i){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n,responseType:"json"};return vi.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await i.request(o)).data}get#i(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#o(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};Ti.DefaultAwsSecurityCredentialsSupplier=br});var qr=X(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.AwsClient=void 0;var _g=Lr(),yg=wt(),Eg=Fu(),Hu=et(),vg=ke(),Or=class t extends yg.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let n=(0,Hu.originalOrCamelOptions)(e),i=n.get("credential_source"),o=n.get("aws_security_credentials_supplier");if(!i&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(i&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let r=(0,Hu.originalOrCamelOptions)(i);this.environmentId=r.get("environment_id");let a=r.get("region_url"),u=r.get("url"),c=r.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new Eg.DefaultAwsSecurityCredentialsSupplier({regionUrl:a,securityCredentialsUrl:u,imdsV2SessionTokenUrl:c}),this.regionalCredVerificationUrl=r.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new _g.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),n=[];return vg.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,r)=>n.push({key:r,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};Ai.AwsClient=Or});var $r=X(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.InvalidSubjectTokenError=Se.InvalidMessageFieldError=Se.InvalidCodeFieldError=Se.InvalidTokenTypeFieldError=Se.InvalidExpirationTimeFieldError=Se.InvalidSuccessFieldError=Se.InvalidVersionFieldError=Se.ExecutableResponseError=Se.ExecutableResponse=void 0;var Ci="urn:ietf:params:oauth:token-type:saml2",Fr="urn:ietf:params:oauth:token-type:id_token",Hr="urn:ietf:params:oauth:token-type:jwt",Vr=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Ii("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Si("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==Ci&&this.tokenType!==Fr&&this.tokenType!==Hr)throw new wi(`Executable response must contain a 'token_type' field when successful and it must be one of ${Fr}, ${Hr}, or ${Ci}.`);if(this.tokenType===Ci){if(!e.saml_response)throw new Dn(`Executable response must contain a 'saml_response' field when token_type=${Ci}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Dn(`Executable response must contain a 'id_token' field when token_type=${Fr} or ${Hr}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new Ri("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new Pi("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Se.ExecutableResponse=Vr;var ct=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Se.ExecutableResponseError=ct;var Ii=class extends ct{};Se.InvalidVersionFieldError=Ii;var Si=class extends ct{};Se.InvalidSuccessFieldError=Si;var Br=class extends ct{};Se.InvalidExpirationTimeFieldError=Br;var wi=class extends ct{};Se.InvalidTokenTypeFieldError=wi;var Ri=class extends ct{};Se.InvalidCodeFieldError=Ri;var Pi=class extends ct{};Se.InvalidMessageFieldError=Pi;var Dn=class extends ct{};Se.InvalidSubjectTokenError=Dn});var Kr=X(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.PluggableAuthHandler=nn.ExecutableError=void 0;var Bt=$r(),Tg=ne("child_process"),Jr=ne("fs"),Ni=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`),this.code=n,Object.setPrototypeOf(this,new.target.prototype)}};nn.ExecutableError=Ni;var Xr=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((n,i)=>{let o=Tg.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),r="";o.stdout.on("data",u=>{r+=u}),o.stderr.on("data",u=>{r+=u});let a=setTimeout(()=>(o.removeAllListeners(),o.kill(),i(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",u=>{if(clearTimeout(a),u===0)try{let c=JSON.parse(r),d=new Bt.ExecutableResponse(c);return n(d)}catch(c){return c instanceof Bt.ExecutableResponseError?i(c):i(new Bt.ExecutableResponseError(`The executable returned an invalid response: ${r}`))}else return i(new Ni(r,u.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Jr.promises.realpath(this.outputFile)}catch{return}if(!(await Jr.promises.lstat(e)).isFile())return;let n=await Jr.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let i=JSON.parse(n);return new Bt.ExecutableResponse(i).isValid()?new Bt.ExecutableResponse(i):void 0}catch(i){throw i instanceof Bt.ExecutableResponseError?i:new Bt.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let i=0;i<n.length;i++)n[i][0]==='"'&&n[i].slice(-1)==='"'&&(n[i]=n[i].slice(1,-1));return n}};nn.PluggableAuthHandler=Xr});var Wr=X(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.PluggableAuthClient=on.ExecutableError=void 0;var Ag=wt(),Cg=$r(),Vu=Kr(),Ig=Kr();Object.defineProperty(on,"ExecutableError",{enumerable:!0,get:function(){return Ig.ExecutableError}});var Sg=30*1e3,Bu=5*1e3,$u=120*1e3,wg="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",Ju=1,Yr=class extends Ag.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=Sg;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<Bu||this.timeoutMillis>$u)throw new Error(`Timeout must be between ${Bu} and ${$u} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new Vu.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[wg]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let i=this.getServiceAccountEmail();i&&n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",i),e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>Ju)throw new Error(`Version of executable is not currently supported, maximum supported version is ${Ju}.`);if(!e.success)throw new Vu.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new Cg.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};on.PluggableAuthClient=Yr});var Qr=X(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.ExternalAccountClient=void 0;var Rg=wt(),Pg=Ur(),Ng=qr(),kg=Wr(),zr=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===Rg.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new Ng.AwsClient(e):e.credential_source?.executable?new kg.PluggableAuthClient(e):new Pg.IdentityPoolClient(e):null}};ki.ExternalAccountClient=zr});var es=X(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.ExternalAccountAuthorizedUserClient=rn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Ku=He(),Xu=Ar(),Yu=ke(),Dg=ne("stream"),xg=wt();rn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var Mg="https://sts.{universeDomain}/v1/oauthtoken",Zr=class t extends Xu.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){let i={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e}),responseType:"json"};Ku.AuthClient.setMethodName(i,"refreshToken"),this.applyClientAuthenticationOptions(i);try{let o=await this.transporter.request(i),r=o.data;return r.res=o,r}catch(o){throw o instanceof Yu.GaxiosError&&o.response?(0,Xu.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},jr=class extends Ku.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Zr({tokenRefreshEndpoint:e.token_url??Mg.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=xg.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(i=>n(null,i),i=>n(i,i.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let i;try{let o=await this.getRequestHeaders();e.headers=Yu.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),i=await this.transporter.request(e)}catch(o){let r=o.response;if(r){let a=r.status,u=r.config.data instanceof Dg.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return i}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};rn.ExternalAccountAuthorizedUserClient=jr});var ns=X(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.GdchClient=Rt.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var Ug=ne("crypto"),Gg=ne("fs"),Lg=ne("https"),bg=It(),Og=3600;Rt.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var ts=class t extends bg.OAuth2Client{projectId;privateKeyId;privateKey;serviceIdentityName;tokenServerUri;caCertPath;apiAudience;lifetime;gdchOptions;caAgentPromise;cachedCaCertPath;lastCaCertReadTime=0;CA_CERT_TTL_MS=300*1e3;constructor(e={}){super(e),this.gdchOptions=e,this.projectId=e.projectId||void 0,this.privateKeyId=e.privateKeyId,this.privateKey=e.privateKey,this.serviceIdentityName=e.serviceIdentityName,this.tokenServerUri=e.tokenServerUri,this.caCertPath=e.caCertPath,this.apiAudience=e.apiAudience,this.lifetime=e.lifetime||Og,this.credentials={refresh_token:"gdch-placeholder",expiry_date:1}}createWithGdchAudience(e){if(!e)throw new Error("Audience cannot be null or empty for GDCH service account credentials.");return new t({...this.gdchOptions,projectId:this.projectId,privateKeyId:this.privateKeyId,privateKey:this.privateKey,serviceIdentityName:this.serviceIdentityName,tokenServerUri:this.tokenServerUri,caCertPath:this.caCertPath,lifetime:this.lifetime,apiAudience:e})}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the GDCH credentials settings.");if(e.type!==Rt.GDCH_SERVICE_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Rt.GDCH_SERVICE_ACCOUNT_TYPE}" type`);if(e.format_version!=="1")throw new Error("Only format version 1 is supported.");if(!e.project)throw new Error("The incoming JSON object does not contain a project field");if(!e.private_key_id)throw new Error("The incoming JSON object does not contain a private_key_id field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");if(!e.name)throw new Error("The incoming JSON object does not contain a name field");if(!e.token_uri)throw new Error("The incoming JSON object does not contain a token_uri field");this.projectId=e.project,this.privateKeyId=e.private_key_id,this.privateKey=e.private_key,this.serviceIdentityName=e.name,this.tokenServerUri=e.token_uri,this.caCertPath=e.ca_cert_path,this.gdchOptions={...this.gdchOptions,projectId:e.project,privateKeyId:e.private_key_id,privateKey:e.private_key,serviceIdentityName:e.name,tokenServerUri:e.token_uri,caCertPath:e.ca_cert_path}}async refreshTokenNoCache(){if(!this.apiAudience)throw new Error("Audience cannot be null or empty for GDCH service account credentials. Specify the audience by calling createWithGdchAudience.");if(!this.privateKey)throw new Error("Private key is not configured for GDCH credentials.");if(!this.privateKeyId)throw new Error("Private key ID is not configured for GDCH credentials.");if(!this.projectId)throw new Error("Project is not configured for GDCH credentials.");if(!this.serviceIdentityName)throw new Error("Service identity name is not configured for GDCH credentials.");if(!this.tokenServerUri)throw new Error("Token server URI is not configured for GDCH credentials.");let e=this.createAssertion(),n={audience:this.apiAudience,grant_type:"urn:ietf:params:oauth:token-type:token-exchange",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,subject_token_type:"urn:k8s:params:oauth:token-type:serviceaccount"},i={url:this.tokenServerUri,method:"POST",headers:{"Content-Type":"application/json"},data:n,responseType:"json",timeout:1e4,retry:!0,retryConfig:{httpMethodsToRetry:["POST"],statusCodesToRetry:[[500,599]],noResponseRetries:3}};this.caCertPath&&(i.agent=await this.getCaAgent());try{let o=await this.transporter.request(i),r=o.data;if(!r.access_token)throw new Error("Token response did not contain an access_token.");if(!r.expires_in)throw new Error("Token response did not contain an expires_in field.");let a={access_token:r.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+r.expires_in*1e3};return this.emit("tokens",a),{res:o,tokens:a}}catch(o){if(o&&o.config&&o.config.data)try{if(typeof o.config.data=="string"){let r=JSON.parse(o.config.data);r.subject_token&&(r.subject_token="***REDACTED***",o.config.data=JSON.stringify(r))}else typeof o.config.data=="object"&&o.config.data.subject_token&&(o.config.data.subject_token="***REDACTED***")}catch{}throw o instanceof Error&&(o.message=`Error getting access token for GDCH service account: ${o.message}, iss: ${this.serviceIdentityName}`),o}}createAssertion(){let e={alg:"ES256",typ:"JWT",kid:this.privateKeyId},n=`system:serviceaccount:${this.projectId}:${this.serviceIdentityName}`,i=Math.floor(Date.now()/1e3),o={iss:n,sub:n,iat:i,exp:i+this.lifetime,aud:this.tokenServerUri},r=this.base64UrlEncode(JSON.stringify(e)),a=this.base64UrlEncode(JSON.stringify(o)),u=`${r}.${a}`,c=Ug.sign("sha256",Buffer.from(u),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),d=this.base64UrlEncode(c);return`${u}.${d}`}async requestAsync(e,n=!1){if(this.caCertPath&&!e.agent){let i=(e.url||"").toString();!i.includes("googleapis.com")&&!i.includes("google.com")&&(e.agent=await this.getCaAgent())}return super.requestAsync(e,n)}getCaAgent(){if(!this.caCertPath){this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;return}let e=Date.now(),n=e-this.lastCaCertReadTime>this.CA_CERT_TTL_MS;if(this.caAgentPromise&&this.caCertPath===this.cachedCaCertPath&&!n)return this.caAgentPromise;this.cachedCaCertPath=this.caCertPath,this.lastCaCertReadTime=e;let i=this.caCertPath;return this.caAgentPromise=(async()=>{try{let o=await Gg.promises.readFile(i);return new Lg.Agent({ca:o})}catch(o){throw this.cachedCaCertPath===i&&(this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0),o instanceof Error&&(o.message=`Error reading certificate file from CA cert path, value '${i}': ${o.message}`),o}})(),this.caAgentPromise}toJSON(){return{...this,privateKey:this.privateKey?"***REDACTED***":void 0,_clientSecret:this._clientSecret?"***REDACTED***":void 0,apiKey:this.apiKey?"***REDACTED***":void 0,gdchOptions:this.gdchOptions?{...this.gdchOptions,privateKey:this.gdchOptions.privateKey?"***REDACTED***":void 0,clientSecret:this.gdchOptions.clientSecret?"***REDACTED***":void 0,client_secret:this.gdchOptions.client_secret?"***REDACTED***":void 0,apiKey:this.gdchOptions.apiKey?"***REDACTED***":void 0,credentials:this.gdchOptions.credentials?{...this.gdchOptions.credentials,access_token:this.gdchOptions.credentials.access_token?"***REDACTED***":void 0,refresh_token:this.gdchOptions.credentials.refresh_token?"***REDACTED***":void 0}:void 0}:void 0,credentials:{...this.credentials,access_token:this.credentials?.access_token?"***REDACTED***":void 0,refresh_token:this.credentials?.refresh_token?"***REDACTED***":void 0}}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}base64UrlEncode(e){return(typeof e=="string"?Buffer.from(e):e).toString("base64url")}};Rt.GdchClient=ts});var Zu=X(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.GoogleAuth=nt.GoogleAuthExceptionMessages=void 0;var qg=ne("child_process"),xn=ne("fs"),Fg=ke(),Mn=Sn(),Hg=ne("os"),Di=ne("path"),Vg=wn(),Bg=Qo(),$g=jo(),Jg=er(),sn=gr(),Wu=yr(),an=vr(),Xg=Qr(),Un=wt(),is=He(),zu=es(),os=ns(),Qu=et();nt.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
26
- To learn more about authentication and Google APIs, visit:
27
- https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
28
- To learn more about authentication and Google APIs, visit:
29
- https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment.
30
- To learn more about Universe Domain retrieval, visit:
31
- https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var rs=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(nt.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(n=>e(null,n),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===nt.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(nt.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await Mn.universe("universe-domain"),e||=is.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=is.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,Qu.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=is.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},n){let i;if(typeof e=="function"?n=e:i=e,n)this.getApplicationDefaultAsync(i).then(o=>n(null,o.credential,o.projectId),n);else return this.getApplicationDefaultAsync(i)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),n)return n instanceof sn.JWT?n.scopes=this.scopes:n instanceof Un.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof sn.JWT?n.scopes=this.scopes:n instanceof Un.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new Bg.Compute(e));throw new Error(nt.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let i=await this.getProjectIdOptional();return n&&(e.quotaProjectId=n),this.cachedCredential=e,{credential:e,projectId:i}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=Mn.getGCPResidency()||await Mn.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let n=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!n||n.length===0)return null;try{return await this._getApplicationCredentialsFromFilePath(n,e)}catch(i){throw i instanceof Error&&(i.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${i.message}`),i}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let n=process.env.CLOUDSDK_CONFIG;if(!n)if(this._isWindows())process.env.APPDATA&&(n=Di.join(process.env.APPDATA,"gcloud"));else{let r=process.env.HOME;r&&(n=Di.join(r,".config","gcloud"))}if(!n)return null;let i=Di.join(n,"application_default_credentials.json");return xn.existsSync(i)?await this._getApplicationCredentialsFromFilePath(i,e):null}async _getApplicationCredentialsFromFilePath(e,n={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=xn.realpathSync(e),!xn.lstatSync(e).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let i=xn.createReadStream(e);return this.fromStream(i,n)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==an.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${an.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let n=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let i=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!i)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=(this.scopes||e.scopes||this.defaultScopes)??[];return new an.Impersonated({...e,sourceClient:n,targetPrincipal:i,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,n={}){let i,o=(0,Qu.originalOrCamelOptions)(n).get("universe_domain");return e.type===Wu.USER_REFRESH_ACCOUNT_TYPE?(i=new Wu.UserRefreshClient(n),i.fromJSON(e)):e.type===an.IMPERSONATED_ACCOUNT_TYPE?i=this.fromImpersonatedJSON(e):e.type===Un.EXTERNAL_ACCOUNT_TYPE?(i=Xg.ExternalAccountClient.fromJSON({...e,...n}),i.scopes=this.getAnyScopes()):e.type===zu.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?i=new zu.ExternalAccountAuthorizedUserClient({...e,...n}):e.type===os.GDCH_SERVICE_ACCOUNT_TYPE?(i=new os.GdchClient(n),i.fromJSON(e)):(n.scopes=this.scopes,i=new sn.JWT(n),this.setGapicJWTValues(i),i.fromJSON(e)),o&&(i.universeDomain=o),i}_cacheClientFromJSON(e,n){let i=this.fromJSON(e,n);return this.jsonContent=e,this.cachedCredential=i,i}fromStream(e,n={},i){let o={};if(typeof n=="function"?i=n:o=n,i)this.fromStreamAsync(e,o).then(r=>i(null,r),i);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,n){return new Promise((i,o)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let r=[];e.setEncoding("utf8").on("error",o).on("data",a=>r.push(a)).on("end",()=>{try{try{let a=JSON.parse(r.join("")),u=this._cacheClientFromJSON(a,n);return i(u)}catch(a){if(!this.keyFilename)throw a;let u=new sn.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=u,this.setGapicJWTValues(u),i(u)}}catch(a){return o(a)}})})}fromAPIKey(e,n={}){return new sn.JWT({...n,apiKey:e})}_isWindows(){let e=Hg.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,qg.exec)("gcloud config config-helper --format json",(n,i)=>{if(!n&&i)try{let o=JSON.parse(i).configuration.properties.core.project;e(o);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let n=await this.getClient();if(n&&n.projectId)return n.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==Un.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Mn.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(n=>e(null,n),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof an.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Un.BaseExternalAccountClient){let n=e.getServiceAccountEmail();if(n)return{client_email:n,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[n,i]=await Promise.all([Mn.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:i}}throw new Error(nt.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{let e=await this.#e;if(e instanceof os.GdchClient&&!e.apiAudience){let n=this.clientOptions,i=n.apiEndpoint||n.servicePath;if(i){let r=`${i.startsWith("http")?"":"https://"}${i}`.replace(/\/+$/,""),a=e.createWithGdchAudience(r);return this.cachedCredential=a,a}}return e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Di.resolve(this.keyFilename),n=xn.createReadStream(e);return await this.fromStreamAsync(n,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:n}=await this.#t(e);return n}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let n=await this.getClient();if(!("fetchIdToken"in n))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new $g.IdTokenClient({targetAudience:e,idTokenProvider:n})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let n=e.url,o=await(await this.getClient()).getRequestHeaders(n);return e.headers=Fg.Gaxios.mergeHeaders(e.headers,o),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,Jg.getEnv)()}async sign(e,n){let i=await this.getClient(),o=await this.getUniverseDomain();if(n=n||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,i instanceof an.Impersonated)return(await i.sign(e)).signedBlob;let r=(0,Vg.createCrypto)();if(i instanceof sn.JWT&&i.key)return await r.sign(i.key,e);let a=await this.getCredentials();if(!a.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(r,a.client_email,e,n)}async signBlob(e,n,i,o){let r=new URL(o+`${n}:signBlob`);return(await this.request({method:"POST",url:r.href,data:{payload:e.encodeBase64StringUtf8(i)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};nt.GoogleAuth=rs});var ju=X(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});xi.IAMAuth=void 0;var ss=class{selector;token;constructor(e,n){this.selector=e,this.token=n,this.selector=e,this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};xi.IAMAuth=ss});var ec=X(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.DownscopedClient=dt.EXPIRATION_TIME_OFFSET=dt.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var Kg=ke(),Yg=ne("stream"),as=He(),Wg=di(),zg="urn:ietf:params:oauth:grant-type:token-exchange",Qg="urn:ietf:params:oauth:token-type:access_token",Zg="urn:ietf:params:oauth:token-type:access_token";dt.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;dt.EXPIRATION_TIME_OFFSET=300*1e3;var ls=class extends as.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof as.AuthClient?{}:e),e instanceof as.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>dt.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${dt.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let i of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(i.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new Wg.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(i=>n(null,i),i=>n(i,i.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let i;try{let o=await this.getRequestHeaders();e.headers=Kg.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),i=await this.transporter.request(e)}catch(o){let r=o.response;if(r){let a=r.status,u=r.config.data instanceof Yg.Readable;if(!n&&(a===401||a===403)&&!u&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return i}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,n={grantType:zg,requestedTokenType:Qg,subjectToken:e,subjectTokenType:Zg},i=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,r=i.expires_in?new Date().getTime()+i.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:i.access_token,expiry_date:r,res:i.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};dt.DownscopedClient=ls});var tc=X(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.PassThroughClient=void 0;var jg=He(),us=class extends jg.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};Mi.PassThroughClient=us});var ac=X($=>{"use strict";var e_=$&&$.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,o)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),t_=$&&$.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&e_(e,t,n)};Object.defineProperty($,"__esModule",{value:!0});$.GoogleAuth=$.auth=$.GDCH_SERVICE_ACCOUNT_TYPE=$.GdchClient=$.PassThroughClient=$.ExternalAccountAuthorizedUserClient=$.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=$.ExecutableError=$.PluggableAuthClient=$.DownscopedClient=$.BaseExternalAccountClient=$.ExternalAccountClient=$.IdentityPoolClient=$.AwsRequestSigner=$.AwsClient=$.UserRefreshClient=$.LoginTicket=$.ClientAuthentication=$.OAuth2Client=$.CodeChallengeMethod=$.Impersonated=$.JWT=$.JWTAccess=$.IdTokenClient=$.IAMAuth=$.GCPEnv=$.Compute=$.DEFAULT_UNIVERSE=$.AuthClient=$.gaxios=$.gcpMetadata=void 0;var nc=Zu();Object.defineProperty($,"GoogleAuth",{enumerable:!0,get:function(){return nc.GoogleAuth}});$.gcpMetadata=Sn();$.gaxios=ke();var ic=He();Object.defineProperty($,"AuthClient",{enumerable:!0,get:function(){return ic.AuthClient}});Object.defineProperty($,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return ic.DEFAULT_UNIVERSE}});var n_=Qo();Object.defineProperty($,"Compute",{enumerable:!0,get:function(){return n_.Compute}});var i_=er();Object.defineProperty($,"GCPEnv",{enumerable:!0,get:function(){return i_.GCPEnv}});var o_=ju();Object.defineProperty($,"IAMAuth",{enumerable:!0,get:function(){return o_.IAMAuth}});var r_=jo();Object.defineProperty($,"IdTokenClient",{enumerable:!0,get:function(){return r_.IdTokenClient}});var s_=hr();Object.defineProperty($,"JWTAccess",{enumerable:!0,get:function(){return s_.JWTAccess}});var a_=gr();Object.defineProperty($,"JWT",{enumerable:!0,get:function(){return a_.JWT}});var l_=vr();Object.defineProperty($,"Impersonated",{enumerable:!0,get:function(){return l_.Impersonated}});var cs=It();Object.defineProperty($,"CodeChallengeMethod",{enumerable:!0,get:function(){return cs.CodeChallengeMethod}});Object.defineProperty($,"OAuth2Client",{enumerable:!0,get:function(){return cs.OAuth2Client}});Object.defineProperty($,"ClientAuthentication",{enumerable:!0,get:function(){return cs.ClientAuthentication}});var u_=Ko();Object.defineProperty($,"LoginTicket",{enumerable:!0,get:function(){return u_.LoginTicket}});var c_=yr();Object.defineProperty($,"UserRefreshClient",{enumerable:!0,get:function(){return c_.UserRefreshClient}});var d_=qr();Object.defineProperty($,"AwsClient",{enumerable:!0,get:function(){return d_.AwsClient}});var f_=Lr();Object.defineProperty($,"AwsRequestSigner",{enumerable:!0,get:function(){return f_.AwsRequestSigner}});var p_=Ur();Object.defineProperty($,"IdentityPoolClient",{enumerable:!0,get:function(){return p_.IdentityPoolClient}});var h_=Qr();Object.defineProperty($,"ExternalAccountClient",{enumerable:!0,get:function(){return h_.ExternalAccountClient}});var m_=wt();Object.defineProperty($,"BaseExternalAccountClient",{enumerable:!0,get:function(){return m_.BaseExternalAccountClient}});var g_=ec();Object.defineProperty($,"DownscopedClient",{enumerable:!0,get:function(){return g_.DownscopedClient}});var oc=Wr();Object.defineProperty($,"PluggableAuthClient",{enumerable:!0,get:function(){return oc.PluggableAuthClient}});Object.defineProperty($,"ExecutableError",{enumerable:!0,get:function(){return oc.ExecutableError}});var rc=es();Object.defineProperty($,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return rc.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty($,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return rc.ExternalAccountAuthorizedUserClient}});var __=tc();Object.defineProperty($,"PassThroughClient",{enumerable:!0,get:function(){return __.PassThroughClient}});var sc=ns();Object.defineProperty($,"GdchClient",{enumerable:!0,get:function(){return sc.GdchClient}});Object.defineProperty($,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return sc.GDCH_SERVICE_ACCOUNT_TYPE}});t_(fr(),$);var y_=new nc.GoogleAuth;$.auth=y_});var of=il(xp(),1),rf=il(ac(),1);import{createWriteStream as E_}from"fs";import*as ao from"fs/promises";import{writeFile as v_}from"fs/promises";import{Readable as T_}from"node:stream";import{finished as A_}from"node:stream/promises";import*as sf from"path";var C_,I_;function S_(){return{geminiUrl:C_,vertexUrl:I_}}function w_(t,e,n,i){var o,r;if(!t?.baseUrl){let a=S_();return e?(o=a.vertexUrl)!==null&&o!==void 0?o:n:(r=a.geminiUrl)!==null&&r!==void 0?r:i}return t.baseUrl}var it=class{};function B(t,e){let n=/\{([^}]+)\}/g;return t.replace(n,(i,o)=>{if(Object.prototype.hasOwnProperty.call(e,o)){let r=e[o];return r!=null?String(r):""}else throw new Error(`Key '${o}' not found in valueMap.`)})}function l(t,e,n){for(let r=0;r<e.length-1;r++){let a=e[r];if(a.endsWith("[]")){let u=a.slice(0,-2);if(!(u in t))if(Array.isArray(n))t[u]=Array.from({length:n.length},()=>({}));else throw new Error(`Value must be a list given an array path ${a}`);if(Array.isArray(t[u])){let c=t[u];if(Array.isArray(n))for(let d=0;d<c.length;d++){let f=c[d];l(f,e.slice(r+1),n[d])}else for(let d of c)l(d,e.slice(r+1),n)}return}else if(a.endsWith("[0]")){let u=a.slice(0,-3);u in t||(t[u]=[{}]);let c=t[u];l(c[0],e.slice(r+1),n);return}(!t[a]||typeof t[a]!="object")&&(t[a]={}),t=t[a]}let i=e[e.length-1],o=t[i];if(o!==void 0){if(!n||typeof n=="object"&&Object.keys(n).length===0||n===o)return;if(typeof o=="object"&&typeof n=="object"&&o!==null&&n!==null)Object.assign(o,n);else throw new Error(`Cannot set value for an existing key. Key: ${i}`)}else i==="_self"&&typeof n=="object"&&n!==null&&!Array.isArray(n)?Object.assign(t,n):t[i]=n}function s(t,e,n=void 0){try{if(e.length===1&&e[0]==="_self")return t;for(let i=0;i<e.length;i++){if(typeof t!="object"||t===null)return n;let o=e[i];if(o.endsWith("[]")){let r=o.slice(0,-2);if(r in t){let a=t[r];return Array.isArray(a)?a.map(u=>s(u,e.slice(i+1),n)):n}else return n}else t=t[o]}return t}catch(i){if(i instanceof TypeError)return n;throw i}}function R_(t,e){for(let[n,i]of Object.entries(e)){let o=n.split("."),r=i.split("."),a=new Set,u=-1;for(let c=0;c<o.length;c++)if(o[c]==="*"){u=c;break}if(u!==-1&&r.length>u)for(let c=u;c<r.length;c++){let d=r[c];d!=="*"&&!d.endsWith("[]")&&!d.endsWith("[0]")&&a.add(d)}hs(t,o,r,0,a)}}function hs(t,e,n,i,o){if(i>=e.length||typeof t!="object"||t===null)return;let r=e[i];if(r.endsWith("[]")){let a=r.slice(0,-2),u=t;if(a in u&&Array.isArray(u[a]))for(let c of u[a])hs(c,e,n,i+1,o)}else if(r==="*"){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let a=t,u=Object.keys(a).filter(d=>!d.startsWith("_")&&!o.has(d)),c={};for(let d of u)c[d]=a[d];for(let[d,f]of Object.entries(c)){let p=[];for(let h of n.slice(i))h==="*"?p.push(d):p.push(h);l(a,p,f)}for(let d of u)delete a[d]}}else{let a=t;r in a&&hs(a[r],e,n,i+1,o)}}function Ja(t){if(typeof t!="string")throw new Error("fromImageBytes must be a string");return t}function P_(t){let e={},n=s(t,["operationName"]);n!=null&&l(e,["operationName"],n);let i=s(t,["resourceName"]);return i!=null&&l(e,["_url","resourceName"],i),e}function N_(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let i=s(t,["metadata"]);i!=null&&l(e,["metadata"],i);let o=s(t,["done"]);o!=null&&l(e,["done"],o);let r=s(t,["error"]);r!=null&&l(e,["error"],r);let a=s(t,["response","generateVideoResponse"]);return a!=null&&l(e,["response"],D_(a)),e}function k_(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let i=s(t,["metadata"]);i!=null&&l(e,["metadata"],i);let o=s(t,["done"]);o!=null&&l(e,["done"],o);let r=s(t,["error"]);r!=null&&l(e,["error"],r);let a=s(t,["response"]);return a!=null&&l(e,["response"],x_(a)),e}function D_(t){let e={},n=s(t,["generatedSamples"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(a=>M_(a))),l(e,["generatedVideos"],r)}let i=s(t,["raiMediaFilteredCount"]);i!=null&&l(e,["raiMediaFilteredCount"],i);let o=s(t,["raiMediaFilteredReasons"]);return o!=null&&l(e,["raiMediaFilteredReasons"],o),e}function x_(t){let e={},n=s(t,["videos"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(a=>U_(a))),l(e,["generatedVideos"],r)}let i=s(t,["raiMediaFilteredCount"]);i!=null&&l(e,["raiMediaFilteredCount"],i);let o=s(t,["raiMediaFilteredReasons"]);return o!=null&&l(e,["raiMediaFilteredReasons"],o),e}function M_(t){let e={},n=s(t,["video"]);return n!=null&&l(e,["video"],F_(n)),e}function U_(t){let e={},n=s(t,["_self"]);return n!=null&&l(e,["video"],H_(n)),e}function G_(t){let e={},n=s(t,["operationName"]);return n!=null&&l(e,["_url","operationName"],n),e}function L_(t){let e={},n=s(t,["operationName"]);return n!=null&&l(e,["_url","operationName"],n),e}function b_(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let i=s(t,["metadata"]);i!=null&&l(e,["metadata"],i);let o=s(t,["done"]);o!=null&&l(e,["done"],o);let r=s(t,["error"]);r!=null&&l(e,["error"],r);let a=s(t,["response"]);return a!=null&&l(e,["response"],O_(a)),e}function O_(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let i=s(t,["parent"]);i!=null&&l(e,["parent"],i);let o=s(t,["documentName"]);return o!=null&&l(e,["documentName"],o),e}function Xa(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let i=s(t,["metadata"]);i!=null&&l(e,["metadata"],i);let o=s(t,["done"]);o!=null&&l(e,["done"],o);let r=s(t,["error"]);r!=null&&l(e,["error"],r);let a=s(t,["response"]);return a!=null&&l(e,["response"],q_(a)),e}function q_(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let i=s(t,["parent"]);i!=null&&l(e,["parent"],i);let o=s(t,["documentName"]);return o!=null&&l(e,["documentName"],o),e}function F_(t){let e={},n=s(t,["uri"]);n!=null&&l(e,["uri"],n);let i=s(t,["encodedVideo"]);i!=null&&l(e,["videoBytes"],Ja(i));let o=s(t,["encoding"]);return o!=null&&l(e,["mimeType"],o),e}function H_(t){let e={},n=s(t,["gcsUri"]);n!=null&&l(e,["uri"],n);let i=s(t,["bytesBase64Encoded"]);i!=null&&l(e,["videoBytes"],Ja(i));let o=s(t,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}var lc;(function(t){t.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",t.OUTCOME_OK="OUTCOME_OK",t.OUTCOME_FAILED="OUTCOME_FAILED",t.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(lc||(lc={}));var uc;(function(t){t.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",t.PYTHON="PYTHON"})(uc||(uc={}));var cc;(function(t){t.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",t.SILENT="SILENT",t.WHEN_IDLE="WHEN_IDLE",t.INTERRUPT="INTERRUPT"})(cc||(cc={}));var Pt;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.STRING="STRING",t.NUMBER="NUMBER",t.INTEGER="INTEGER",t.BOOLEAN="BOOLEAN",t.ARRAY="ARRAY",t.OBJECT="OBJECT",t.NULL="NULL"})(Pt||(Pt={}));var dc;(function(t){t.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",t.NO_AUTH="NO_AUTH",t.API_KEY_AUTH="API_KEY_AUTH",t.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",t.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",t.OAUTH="OAUTH",t.OIDC_AUTH="OIDC_AUTH"})(dc||(dc={}));var fc;(function(t){t.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",t.HTTP_IN_QUERY="HTTP_IN_QUERY",t.HTTP_IN_HEADER="HTTP_IN_HEADER",t.HTTP_IN_PATH="HTTP_IN_PATH",t.HTTP_IN_BODY="HTTP_IN_BODY",t.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(fc||(fc={}));var pc;(function(t){t.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",t.SIMPLE_SEARCH="SIMPLE_SEARCH",t.ELASTIC_SEARCH="ELASTIC_SEARCH"})(pc||(pc={}));var hc;(function(t){t.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",t.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",t.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",t.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(hc||(hc={}));var mc;(function(t){t.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",t.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",t.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",t.COMMUNICATION_TOOL="COMMUNICATION_TOOL",t.ACCOUNT_CREATION="ACCOUNT_CREATION",t.DATA_MODIFICATION="DATA_MODIFICATION",t.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",t.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"})(mc||(mc={}));var gc;(function(t){t.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",t.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",t.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",t.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(gc||(gc={}));var _c;(function(t){t.UNSPECIFIED="UNSPECIFIED",t.BLOCKING="BLOCKING",t.NON_BLOCKING="NON_BLOCKING"})(_c||(_c={}));var yc;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(yc||(yc={}));var Dt;(function(t){t.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Dt||(Dt={}));var Ec;(function(t){t.DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL"})(Ec||(Ec={}));var vc;(function(t){t.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",t.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",t.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(vc||(vc={}));var Tc;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",t.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",t.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",t.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",t.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",t.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"})(Tc||(Tc={}));var Ac;(function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"})(Ac||(Ac={}));var Cc;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE",t.OFF="OFF"})(Cc||(Cc={}));var xt;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE",t.VALIDATED="VALIDATED"})(xt||(xt={}));var Ie;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.IMAGE_SAFETY="IMAGE_SAFETY",t.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",t.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",t.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",t.NO_IMAGE="NO_IMAGE",t.IMAGE_RECITATION="IMAGE_RECITATION",t.IMAGE_OTHER="IMAGE_OTHER"})(Ie||(Ie={}));var Ic;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Ic||(Ic={}));var Sc;(function(t){t.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",t.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",t.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",t.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",t.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(Sc||(Sc={}));var wc;(function(t){t.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",t.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",t.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",t.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",t.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(wc||(wc={}));var Rc;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.IMAGE_SAFETY="IMAGE_SAFETY",t.MODEL_ARMOR="MODEL_ARMOR",t.JAILBREAK="JAILBREAK"})(Rc||(Rc={}));var Pc;(function(t){t.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",t.ON_DEMAND="ON_DEMAND",t.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",t.ON_DEMAND_FLEX="ON_DEMAND_FLEX",t.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(Pc||(Pc={}));var Nc;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.VIDEO="VIDEO",t.AUDIO="AUDIO",t.DOCUMENT="DOCUMENT"})(Nc||(Nc={}));var kc;(function(t){t.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",t.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",t.EXPERIMENTAL="EXPERIMENTAL",t.PREVIEW="PREVIEW",t.STABLE="STABLE",t.LEGACY="LEGACY",t.DEPRECATED="DEPRECATED",t.RETIRED="RETIRED"})(kc||(kc={}));var Dc;(function(t){t.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",t.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",t.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",t.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(Dc||(Dc={}));var Fi;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.AUDIO="AUDIO",t.VIDEO="VIDEO"})(Fi||(Fi={}));var xc;(function(t){t.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",t.INLINE="INLINE",t.URI="URI"})(xc||(xc={}));var Mc;(function(t){t.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",t.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",t.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",t.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",t.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",t.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",t.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",t.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",t.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",t.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",t.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",t.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",t.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",t.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",t.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"})(Mc||(Mc={}));var Uc;(function(t){t.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",t.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",t.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",t.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",t.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"})(Uc||(Uc={}));var Gc;(function(t){t.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",t.TUNING_MODE_FULL="TUNING_MODE_FULL",t.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(Gc||(Gc={}));var Lc;(function(t){t.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",t.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",t.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",t.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",t.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",t.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",t.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(Lc||(Lc={}));var bc;(function(t){t.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",t.IDENTITY="IDENTITY",t.REGEX_EXTRACT="REGEX_EXTRACT"})(bc||(bc={}));var Oc;(function(t){t.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",t.REGEX_CONTAINS="REGEX_CONTAINS",t.PARTIAL_MATCH="PARTIAL_MATCH",t.EXACT_MATCH="EXACT_MATCH"})(Oc||(Oc={}));var qc;(function(t){t.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.HIGH="HIGH"})(qc||(qc={}));var ms;(function(t){t.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",t.JOB_STATE_QUEUED="JOB_STATE_QUEUED",t.JOB_STATE_PENDING="JOB_STATE_PENDING",t.JOB_STATE_RUNNING="JOB_STATE_RUNNING",t.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",t.JOB_STATE_FAILED="JOB_STATE_FAILED",t.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",t.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",t.JOB_STATE_PAUSED="JOB_STATE_PAUSED",t.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",t.JOB_STATE_UPDATING="JOB_STATE_UPDATING",t.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(ms||(ms={}));var Fc;(function(t){t.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",t.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",t.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",t.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",t.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",t.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(Fc||(Fc={}));var Hc;(function(t){t.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",t.AVERAGE="AVERAGE",t.MODE="MODE",t.STANDARD_DEVIATION="STANDARD_DEVIATION",t.VARIANCE="VARIANCE",t.MINIMUM="MINIMUM",t.MAXIMUM="MAXIMUM",t.MEDIAN="MEDIAN",t.PERCENTILE_P90="PERCENTILE_P90",t.PERCENTILE_P95="PERCENTILE_P95",t.PERCENTILE_P99="PERCENTILE_P99"})(Hc||(Hc={}));var Vc;(function(t){t.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",t.BASELINE="BASELINE",t.CANDIDATE="CANDIDATE",t.TIE="TIE"})(Vc||(Vc={}));var Bc;(function(t){t.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",t.LANDSCAPE="LANDSCAPE",t.PORTRAIT="PORTRAIT"})(Bc||(Bc={}));var $c;(function(t){t.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",t.REGULAR="REGULAR",t.FAST="FAST"})($c||($c={}));var Jc;(function(t){t.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",t.TUNING_TASK_I2V="TUNING_TASK_I2V",t.TUNING_TASK_T2V="TUNING_TASK_T2V",t.TUNING_TASK_R2V="TUNING_TASK_R2V"})(Jc||(Jc={}));var Xc;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.STATE_PENDING="STATE_PENDING",t.STATE_ACTIVE="STATE_ACTIVE",t.STATE_FAILED="STATE_FAILED"})(Xc||(Xc={}));var Kc;(function(t){t.UNSPECIFIED="unspecified",t.FLEX="flex",t.STANDARD="standard",t.PRIORITY="priority"})(Kc||(Kc={}));var Yc;(function(t){t.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",t.STATIC="STATIC",t.AGENTIC="AGENTIC"})(Yc||(Yc={}));var Wc;(function(t){t.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",t.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",t.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",t.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",t.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(Wc||(Wc={}));var zc;(function(t){t.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",t.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",t.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",t.URL_CONTEXT="URL_CONTEXT",t.GOOGLE_MAPS="GOOGLE_MAPS",t.FILE_SEARCH="FILE_SEARCH",t.MEDIA_PROCESSING="MEDIA_PROCESSING"})(zc||(zc={}));var gs;(function(t){t.COLLECTION="COLLECTION"})(gs||(gs={}));var Qc;(function(t){t.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",t.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",t.BALANCED="BALANCED",t.PRIORITIZE_COST="PRIORITIZE_COST"})(Qc||(Qc={}));var Hi;(function(t){t.PREDICT="PREDICT",t.EMBED_CONTENT="EMBED_CONTENT"})(Hi||(Hi={}));var Zc;(function(t){t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(Zc||(Zc={}));var jc;(function(t){t.auto="auto",t.en="en",t.ja="ja",t.ko="ko",t.hi="hi",t.zh="zh",t.pt="pt",t.es="es"})(jc||(jc={}));var ed;(function(t){t.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",t.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",t.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",t.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",t.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(ed||(ed={}));var td;(function(t){t.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",t.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",t.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",t.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(td||(td={}));var nd;(function(t){t.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",t.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",t.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",t.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(nd||(nd={}));var id;(function(t){t.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",t.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",t.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",t.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",t.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",t.EDIT_MODE_STYLE="EDIT_MODE_STYLE",t.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",t.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(id||(id={}));var od;(function(t){t.FOREGROUND="FOREGROUND",t.BACKGROUND="BACKGROUND",t.PROMPT="PROMPT",t.SEMANTIC="SEMANTIC",t.INTERACTIVE="INTERACTIVE"})(od||(od={}));var rd;(function(t){t.ASSET="ASSET",t.STYLE="STYLE"})(rd||(rd={}));var sd;(function(t){t.INSERT="INSERT",t.REMOVE="REMOVE",t.REMOVE_STATIC="REMOVE_STATIC",t.OUTPAINT="OUTPAINT"})(sd||(sd={}));var ad;(function(t){t.OPTIMIZED="OPTIMIZED",t.LOSSLESS="LOSSLESS"})(ad||(ad={}));var ld;(function(t){t.CROP="CROP",t.PAD="PAD"})(ld||(ld={}));var ud;(function(t){t.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",t.PREFERENCE_TUNING="PREFERENCE_TUNING",t.DISTILLATION="DISTILLATION",t.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(ud||(ud={}));var cd;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.PROCESSING="PROCESSING",t.ACTIVE="ACTIVE",t.FAILED="FAILED"})(cd||(cd={}));var dd;(function(t){t.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",t.UPLOADED="UPLOADED",t.GENERATED="GENERATED",t.REGISTERED="REGISTERED"})(dd||(dd={}));var fd;(function(t){t.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.RESPONSE_REJECTED="RESPONSE_REJECTED",t.NEED_MORE_INPUT="NEED_MORE_INPUT",t.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",t.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",t.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",t.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",t.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",t.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",t.INPUT_OTHER="INPUT_OTHER",t.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",t.BLOCKLIST="BLOCKLIST",t.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",t.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",t.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",t.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",t.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",t.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",t.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",t.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",t.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",t.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",t.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",t.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",t.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",t.GENERATED_OTHER="GENERATED_OTHER",t.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(fd||(fd={}));var pd;(function(t){t.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",t.IN_PROGRESS="IN_PROGRESS",t.REQUIRES_ACTION="REQUIRES_ACTION",t.IDLE="IDLE"})(pd||(pd={}));var hd;(function(t){t.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",t.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",t.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(hd||(hd={}));var md;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.ACTIVITY_START="ACTIVITY_START",t.ACTIVITY_END="ACTIVITY_END"})(md||(md={}));var gd;(function(t){t.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",t.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",t.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(gd||(gd={}));var _d;(function(t){t.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",t.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",t.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(_d||(_d={}));var yd;(function(t){t.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",t.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",t.NO_INTERRUPTION="NO_INTERRUPTION"})(yd||(yd={}));var Ed;(function(t){t.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",t.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",t.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",t.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(Ed||(Ed={}));var vd;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.VERBATIM="VERBATIM",t.SMART="SMART"})(vd||(vd={}));var Td;(function(t){t.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",t.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",t.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",t.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",t.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",t.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",t.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",t.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",t.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",t.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",t.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",t.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",t.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(Td||(Td={}));var Ad;(function(t){t.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",t.QUALITY="QUALITY",t.DIVERSITY="DIVERSITY",t.VOCALIZATION="VOCALIZATION"})(Ad||(Ad={}));var un;(function(t){t.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",t.PLAY="PLAY",t.PAUSE="PAUSE",t.STOP="STOP",t.RESET_CONTEXT="RESET_CONTEXT"})(un||(un={}));var Mt=class{constructor(e){let n={};for(let i of e.headers.entries())n[i[0]]=i[1];this.headers=n,this.responseInternal=e}json(){return this.responseInternal.json()}};var $t=class{get text(){var e,n,i,o,r,a,u,c;if(((o=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let d="",f=!1,p=[];for(let h of(c=(u=(a=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(let[m,_]of Object.entries(h))m!=="text"&&m!=="thought"&&m!=="thoughtSignature"&&(_!==null||_!==void 0)&&p.push(m);if(typeof h.text=="string"){if(typeof h.thought=="boolean"&&h.thought)continue;f=!0,d+=h.text}}return p.length>0&&console.warn(`there are non-text parts ${p} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),f?d:void 0}get data(){var e,n,i,o,r,a,u,c;if(((o=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let d="",f=[];for(let p of(c=(u=(a=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(let[h,m]of Object.entries(p))h!=="inlineData"&&(m!==null||m!==void 0)&&f.push(h);p.inlineData&&typeof p.inlineData.data=="string"&&(d+=atob(p.inlineData.data))}return f.length>0&&console.warn(`there are non-data parts ${f} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),d.length>0?btoa(d):void 0}get functionCalls(){var e,n,i,o,r,a,u,c;if(((o=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let d=(c=(u=(a=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(f=>f.functionCall).map(f=>f.functionCall).filter(f=>f!==void 0);if(d?.length!==0)return d}get executableCode(){var e,n,i,o,r,a,u,c,d;if(((o=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");let f=(c=(u=(a=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(p=>p.executableCode).map(p=>p.executableCode).filter(p=>p!==void 0);if(f?.length!==0)return(d=f?.[0])===null||d===void 0?void 0:d.code}get codeExecutionResult(){var e,n,i,o,r,a,u,c,d;if(((o=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||o===void 0?void 0:o.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let f=(c=(u=(a=(r=this.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(p=>p.codeExecutionResult).map(p=>p.codeExecutionResult).filter(p=>p!==void 0);if(f?.length!==0)return(d=f?.[0])===null||d===void 0?void 0:d.output}},Vi=class{},_s=class{},ys=class{},Es=class{},vs=class{},Ts=class{},Bi=class{},$i=class{};var Ji=class{},As=class{};var Xi=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let i=new t,o,r=e;return n?o=k_(r):o=N_(r),Object.assign(i,o),i}};var Cs=class{},Ki=class{},Is=class{},Yi=class{},Wi=class{},Ss=class{},ws=class{},Rs=class{};var Ps=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let i=new t,r=b_(e);return Object.assign(i,r),i}},Ns=class{},ks=class{},Ds=class{},xs=class{};var zi=class{};var Ms=class{get text(){var e,n,i;let o="",r=!1,a=[];for(let u of(i=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&i!==void 0?i:[]){for(let[c,d]of Object.entries(u))c!=="text"&&c!=="thought"&&d!==null&&a.push(c);if(typeof u.text=="string"){if(typeof u.thought=="boolean"&&u.thought)continue;r=!0,o+=u.text}}return a.length>0&&console.warn(`there are non-text parts ${a} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),r?o:void 0}get data(){var e,n,i;let o="",r=[];for(let a of(i=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&i!==void 0?i:[]){for(let[u,c]of Object.entries(a))u!=="inlineData"&&c!==null&&r.push(u);a.inlineData&&typeof a.inlineData.data=="string"&&(o+=atob(a.inlineData.data))}return r.length>0&&console.warn(`there are non-data parts ${r} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),o.length>0?btoa(o):void 0}};var Us=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}};var Qi=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let i=new t,r=Xa(e);return Object.assign(i,r),i}};function re(t,e){if(!e||typeof e!="string")throw new Error("model is required and must be a string");if(e.includes("..")||e.includes("?")||e.includes("&"))throw new Error("invalid model parameter");if(t.isVertexAI()){if(e.startsWith("publishers/")||e.startsWith("projects/")||e.startsWith("models/"))return e;if(e.indexOf("/")>=0){let n=e.split("/",2);return`publishers/${n[0]}/models/${n[1]}`}else return`publishers/google/models/${e}`}else return e.startsWith("models/")||e.startsWith("tunedModels/")?e:`models/${e}`}function af(t,e){let n=re(t,e);return n?n.startsWith("publishers/")&&t.isVertexAI()?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}`:n.startsWith("models/")&&t.isVertexAI()?`projects/${t.getProject()}/locations/${t.getLocation()}/publishers/google/${n}`:n:""}function lf(t){return Array.isArray(t)?t.map(e=>Zi(e)):[Zi(t)]}function Zi(t){if(typeof t=="object"&&t!==null)return t;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof t}`)}function uf(t){let e=Zi(t);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function cf(t){let e=Zi(t);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function Cd(t){if(t==null)throw new Error("PartUnion is required");if(typeof t=="object")return t;if(typeof t=="string")return{text:t};throw new Error(`Unsupported part type: ${typeof t}`)}function df(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("PartListUnion is required");return Array.isArray(t)?t.map(e=>Cd(e)):[Cd(t)]}function Gs(t){return t!=null&&typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)}function Id(t){return t!=null&&typeof t=="object"&&"functionCall"in t}function Sd(t){return t!=null&&typeof t=="object"&&"functionResponse"in t}function Ne(t){if(t==null)throw new Error("ContentUnion is required");return Gs(t)?t:{role:"user",parts:df(t)}}function Ka(t,e){if(!e)return[];if(t.isVertexAI()&&Array.isArray(e))return e.flatMap(n=>{let i=Ne(n);return i.parts&&i.parts.length>0&&i.parts[0].text!==void 0?[i.parts[0].text]:[]});if(t.isVertexAI()){let n=Ne(e);return n.parts&&n.parts.length>0&&n.parts[0].text!==void 0?[n.parts[0].text]:[]}return Array.isArray(e)?e.map(n=>Ne(n)):[Ne(e)]}function Le(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("contents are required");if(!Array.isArray(t)){if(Id(t)||Sd(t))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[Ne(t)]}let e=[],n=[],i=Gs(t[0]);for(let o of t){let r=Gs(o);if(r!=i)throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(r)e.push(o);else{if(Id(o)||Sd(o))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");n.push(o)}}return i||e.push({role:"user",parts:df(n)}),e}function V_(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(i=>i!=="null");if(n.length===1)e.type=Object.values(Pt).includes(n[0].toUpperCase())?n[0].toUpperCase():Pt.TYPE_UNSPECIFIED;else{e.anyOf=[];for(let i of n)e.anyOf.push({type:Object.values(Pt).includes(i.toUpperCase())?i.toUpperCase():Pt.TYPE_UNSPECIFIED})}}function fn(t){let e={},n=["items"],i=["anyOf"],o=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let r=t.anyOf;r!=null&&r.length==2&&(r[0].type==="null"?(e.nullable=!0,t=r[1]):r[1].type==="null"&&(e.nullable=!0,t=r[0])),t.type instanceof Array&&V_(t.type,e);for(let[a,u]of Object.entries(t))if(u!=null)if(a=="type"){if(u==="null")throw new Error("type: null can not be the only possible type for the field.");if(u instanceof Array)continue;e.type=Object.values(Pt).includes(u.toUpperCase())?u.toUpperCase():Pt.TYPE_UNSPECIFIED}else if(n.includes(a))e[a]=fn(u);else if(i.includes(a)){let c=[];for(let d of u){if(d.type=="null"){e.nullable=!0;continue}c.push(fn(d))}e[a]=c}else if(o.includes(a)){let c={};for(let[d,f]of Object.entries(u))c[d]=fn(f);e[a]=c}else{if(a==="additionalProperties")continue;e[a]=u}return e}function Ya(t){return fn(t)}function Wa(t){if(typeof t=="object")return t;if(typeof t=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:t}}};throw new Error(`Unsupported speechConfig type: ${typeof t}`)}function za(t){if("multiSpeakerVoiceConfig"in t)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return t}function _n(t){if(t.functionDeclarations)for(let e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=fn(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=fn(e.response));return t}function yn(t){if(t==null)throw new Error("tools is required");if(!Array.isArray(t))throw new Error("tools is required and must be an array of Tools");let e=[];for(let n of t)e.push(n);return e}function B_(t,e,n,i=1){let o=!e.startsWith(`${n}/`)&&e.split("/").length===i;return t.isVertexAI()?e.startsWith("projects/")?e:e.startsWith("locations/")?`projects/${t.getProject()}/${e}`:e.startsWith(`${n}/`)?`projects/${t.getProject()}/locations/${t.getLocation()}/${e}`:o?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}/${e}`:e:o?`${n}/${e}`:e}function Tt(t,e){if(typeof e!="string")throw new Error("name must be a string");return B_(t,e,"cachedContents")}function ff(t){switch(t){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return t}}function Jt(t){return Ja(t)}function $_(t){return t!=null&&typeof t=="object"&&"name"in t}function pf(t){return t!=null&&typeof t=="object"&&"video"in t}function hf(t){return t!=null&&typeof t=="object"&&"uri"in t}function Qa(t){var e;let n;if($_(t)&&(n=t.name),!(hf(t)&&(n=t.uri,n===void 0))&&!(pf(t)&&(n=(e=t.video)===null||e===void 0?void 0:e.uri,n===void 0))){if(typeof t=="string"&&(n=t),n===void 0)throw new Error("Could not extract file name from the provided input.");if(n.startsWith("https://")){let o=n.split("files/")[1].match(/[a-z0-9]+/);if(o===null)throw new Error(`Could not extract file name from URI ${n}`);n=o[0]}else n.startsWith("files/")&&(n=n.split("files/")[1]);return n}}function mf(t,e){let n;return t.isVertexAI()?n=e?"publishers/google/models":"models":n=e?"models":"tunedModels",n}function gf(t){for(let e of["models","tunedModels","publisherModels"])if(J_(t,e))return t[e];return[]}function J_(t,e){return t!==null&&typeof t=="object"&&e in t}function X_(t,e={}){let n=t,i={name:n.name,description:n.description,parametersJsonSchema:n.inputSchema};return n.outputSchema&&(i.responseJsonSchema=n.outputSchema),e.behavior&&(i.behavior=e.behavior),{functionDeclarations:[i]}}function K_(t,e={}){let n=[],i=new Set;for(let o of t){let r=o.name;if(i.has(r))throw new Error(`Duplicate function name ${r} found in MCP tools. Please ensure function names are unique.`);i.add(r);let a=X_(o,e);a.functionDeclarations&&n.push(...a.functionDeclarations)}return{functionDeclarations:n}}function _f(t,e){let n;if(typeof e=="string")if(t.isVertexAI())if(e.startsWith("gs://"))n={format:"jsonl",gcsUri:[e]};else if(e.startsWith("bq://"))n={format:"bigquery",bigqueryUri:e};else if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(e))n={format:"vertex-dataset",vertexDatasetName:e};else throw new Error(`Unsupported string source for Vertex AI: ${e}`);else if(e.startsWith("files/"))n={fileName:e};else throw new Error(`Unsupported string source for Gemini API: ${e}`);else if(Array.isArray(e)){if(t.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");n={inlinedRequests:e}}else n=e;let i=[n.gcsUri,n.bigqueryUri,n.vertexDatasetName].filter(Boolean).length,o=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(t.isVertexAI()){if(o>0||i!==1)throw new Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(i>0||o!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function Y_(t){if(typeof t!="string")return t;let e=t;if(e.startsWith("gs://"))return{format:"jsonl",gcsUri:e};if(e.startsWith("bq://"))return{format:"bigquery",bigqueryUri:e};throw new Error(`Unsupported destination: ${e}`)}function yf(t){if(typeof t!="object"||t===null)return{};let e=t,n=e.inlinedResponses;if(typeof n!="object"||n===null)return t;let o=n.inlinedResponses;if(!Array.isArray(o)||o.length===0)return t;let r=!1;for(let a of o){if(typeof a!="object"||a===null)continue;let c=a.response;if(typeof c!="object"||c===null)continue;if(c.embedding!==void 0){r=!0;break}}return r&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),t}function En(t,e){let n=e;if(!t.isVertexAI()){if(/batches\/[^/]+$/.test(n))return n.split("/").pop();throw new Error(`Invalid batch job name: ${n}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(n))return n.split("/").pop();if(/^\d+$/.test(n))return n;throw new Error(`Invalid batch job name: ${n}.`)}function Ef(t){let e=t;return e==="BATCH_STATE_UNSPECIFIED"?"JOB_STATE_UNSPECIFIED":e==="BATCH_STATE_PENDING"?"JOB_STATE_PENDING":e==="BATCH_STATE_RUNNING"?"JOB_STATE_RUNNING":e==="BATCH_STATE_SUCCEEDED"?"JOB_STATE_SUCCEEDED":e==="BATCH_STATE_FAILED"?"JOB_STATE_FAILED":e==="BATCH_STATE_CANCELLED"?"JOB_STATE_CANCELLED":e==="BATCH_STATE_EXPIRED"?"JOB_STATE_EXPIRED":e}function W_(t){return t.includes("gemini")&&t!=="gemini-embedding-001"||t.includes("maas")}function z_(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Q_(t){let e={},n=s(t,["responsesFile"]);n!=null&&l(e,["fileName"],n);let i=s(t,["inlinedResponses","inlinedResponses"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>Dy(a))),l(e,["inlinedResponses"],r)}let o=s(t,["inlinedEmbedContentResponses","inlinedResponses"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["inlinedEmbedContentResponses"],r)}return e}function Z_(t){let e={},n=s(t,["predictionsFormat"]);n!=null&&l(e,["format"],n);let i=s(t,["gcsDestination","outputUriPrefix"]);i!=null&&l(e,["gcsUri"],i);let o=s(t,["bigqueryDestination","outputUri"]);o!=null&&l(e,["bigqueryUri"],o);let r=s(t,["vertexMultimodalDatasetDestination"]);return r!=null&&l(e,["vertexDataset"],Vy(r)),e}function j_(t){let e={},n=s(t,["format"]);n!=null&&l(e,["predictionsFormat"],n);let i=s(t,["gcsUri"]);i!=null&&l(e,["gcsDestination","outputUriPrefix"],i);let o=s(t,["bigqueryUri"]);o!=null&&l(e,["bigqueryDestination","outputUri"],o);let r=s(t,["vertexDataset"]);if(r!=null&&l(e,["vertexMultimodalDatasetDestination"],By(r)),s(t,["fileName"])!==void 0)throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function Oi(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let i=s(t,["metadata","displayName"]);i!=null&&l(e,["displayName"],i);let o=s(t,["metadata","state"]);o!=null&&l(e,["state"],Ef(o));let r=s(t,["metadata","createTime"]);r!=null&&l(e,["createTime"],r);let a=s(t,["metadata","endTime"]);a!=null&&l(e,["endTime"],a);let u=s(t,["metadata","updateTime"]);u!=null&&l(e,["updateTime"],u);let c=s(t,["metadata","model"]);c!=null&&l(e,["model"],c);let d=s(t,["metadata","output"]);return d!=null&&l(e,["dest"],Q_(yf(d))),e}function Ls(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let i=s(t,["displayName"]);i!=null&&l(e,["displayName"],i);let o=s(t,["state"]);o!=null&&l(e,["state"],Ef(o));let r=s(t,["error"]);r!=null&&l(e,["error"],r);let a=s(t,["createTime"]);a!=null&&l(e,["createTime"],a);let u=s(t,["startTime"]);u!=null&&l(e,["startTime"],u);let c=s(t,["endTime"]);c!=null&&l(e,["endTime"],c);let d=s(t,["updateTime"]);d!=null&&l(e,["updateTime"],d);let f=s(t,["model"]);f!=null&&l(e,["model"],f);let p=s(t,["inputConfig"]);p!=null&&l(e,["src"],ey(p));let h=s(t,["outputConfig"]);h!=null&&l(e,["dest"],Z_(yf(h)));let m=s(t,["outputInfo"]);m!=null&&l(e,["outputInfo"],m);let _=s(t,["completionStats"]);return _!=null&&l(e,["completionStats"],_),e}function ey(t){let e={},n=s(t,["instancesFormat"]);n!=null&&l(e,["format"],n);let i=s(t,["gcsSource","uris"]);i!=null&&l(e,["gcsUri"],i);let o=s(t,["bigquerySource","inputUri"]);o!=null&&l(e,["bigqueryUri"],o);let r=s(t,["vertexMultimodalDatasetSource","datasetName"]);return r!=null&&l(e,["vertexDatasetName"],r),e}function ty(t,e){let n={};if(s(e,["format"])!==void 0)throw new Error("format parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["vertexDatasetName"])!==void 0)throw new Error("vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(e,["fileName"]);i!=null&&l(n,["fileName"],i);let o=s(e,["inlinedRequests"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>ky(t,a))),l(n,["requests","requests"],r)}return n}function ny(t){let e={},n=s(t,["format"]);n!=null&&l(e,["instancesFormat"],n);let i=s(t,["gcsUri"]);i!=null&&l(e,["gcsSource","uris"],i);let o=s(t,["bigqueryUri"]);o!=null&&l(e,["bigquerySource","inputUri"],o);let r=s(t,["vertexDatasetName"]);if(r!=null&&l(e,["vertexMultimodalDatasetSource","datasetName"],r),s(t,["fileName"])!==void 0)throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function iy(t){let e={},n=s(t,["data"]);if(n!=null&&l(e,["data"],n),s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}function oy(t,e){let n={},i=s(e,["name"]);return i!=null&&l(n,["_url","name"],En(t,i)),n}function ry(t,e){let n={},i=s(e,["name"]);return i!=null&&l(n,["_url","name"],En(t,i)),n}function sy(t){let e={},n=s(t,["content"]);n!=null&&l(e,["content"],n);let i=s(t,["citationMetadata"]);i!=null&&l(e,["citationMetadata"],ay(i));let o=s(t,["tokenCount"]);o!=null&&l(e,["tokenCount"],o);let r=s(t,["finishReason"]);r!=null&&l(e,["finishReason"],r);let a=s(t,["groundingMetadata"]);a!=null&&l(e,["groundingMetadata"],a);let u=s(t,["avgLogprobs"]);u!=null&&l(e,["avgLogprobs"],u);let c=s(t,["index"]);c!=null&&l(e,["index"],c);let d=s(t,["logprobsResult"]);d!=null&&l(e,["logprobsResult"],d);let f=s(t,["safetyRatings"]);if(f!=null){let h=f;Array.isArray(h)&&(h=h.map(m=>m)),l(e,["safetyRatings"],h)}let p=s(t,["urlContextMetadata"]);return p!=null&&l(e,["urlContextMetadata"],p),e}function ay(t){let e={},n=s(t,["citationSources"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>o)),l(e,["citations"],i)}return e}function vf(t){let e={},n=s(t,["parts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(r=>Oy(r))),l(e,["parts"],o)}let i=s(t,["role"]);return i!=null&&l(e,["role"],i),e}function ly(t,e){let n={},i=s(t,["displayName"]);if(e!==void 0&&i!=null&&l(e,["batch","displayName"],i),s(t,["dest"])!==void 0)throw new Error("dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(t,["webhookConfig"]);return e!==void 0&&o!=null&&l(e,["batch","webhookConfig"],o),n}function uy(t,e){let n={},i=s(t,["displayName"]);e!==void 0&&i!=null&&l(e,["displayName"],i);let o=s(t,["dest"]);if(e!==void 0&&o!=null&&l(e,["outputConfig"],j_(Y_(o))),s(t,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function wd(t,e){let n={},i=s(e,["model"]);i!=null&&l(n,["_url","model"],re(t,i));let o=s(e,["src"]);o!=null&&l(n,["batch","inputConfig"],ty(t,_f(t,o)));let r=s(e,["config"]);return r!=null&&ly(r,n),n}function cy(t,e){let n={},i=s(e,["model"]);i!=null&&l(n,["model"],re(t,i));let o=s(e,["src"]);o!=null&&l(n,["inputConfig"],ny(_f(t,o)));let r=s(e,["config"]);return r!=null&&uy(r,n),n}function dy(t,e){let n={},i=s(t,["displayName"]);return e!==void 0&&i!=null&&l(e,["batch","displayName"],i),n}function fy(t,e){let n={},i=s(e,["model"]);i!=null&&l(n,["_url","model"],re(t,i));let o=s(e,["src"]);o!=null&&l(n,["batch","inputConfig"],Ey(t,o));let r=s(e,["config"]);return r!=null&&dy(r,n),n}function py(t,e){let n={},i=s(e,["name"]);return i!=null&&l(n,["_url","name"],En(t,i)),n}function hy(t,e){let n={},i=s(e,["name"]);return i!=null&&l(n,["_url","name"],En(t,i)),n}function my(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let i=s(t,["name"]);i!=null&&l(e,["name"],i);let o=s(t,["done"]);o!=null&&l(e,["done"],o);let r=s(t,["error"]);return r!=null&&l(e,["error"],r),e}function gy(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let i=s(t,["name"]);i!=null&&l(e,["name"],i);let o=s(t,["done"]);o!=null&&l(e,["done"],o);let r=s(t,["error"]);return r!=null&&l(e,["error"],r),e}function _y(t,e){let n={},i=s(e,["contents"]);if(i!=null){let r=Ka(t,i);Array.isArray(r)&&(r=r.map(a=>a)),l(n,["requests[]","request","content"],r)}let o=s(e,["config"]);return o!=null&&(l(n,["_self"],yy(o,n)),R_(n,{"requests[].*":"requests[].request.*"})),n}function yy(t,e){let n={},i=s(t,["taskType"]);e!==void 0&&i!=null&&l(e,["requests[]","taskType"],i);let o=s(t,["title"]);e!==void 0&&o!=null&&l(e,["requests[]","title"],o);let r=s(t,["outputDimensionality"]);if(e!==void 0&&r!=null&&l(e,["requests[]","outputDimensionality"],r),s(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function Ey(t,e){let n={},i=s(e,["fileName"]);i!=null&&l(n,["file_name"],i);let o=s(e,["inlinedRequests"]);return o!=null&&l(n,["requests"],_y(t,o)),n}function vy(t){let e={};if(s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["fileUri"]);n!=null&&l(e,["fileUri"],n);let i=s(t,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}function Ty(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let i=s(t,["id"]);i!=null&&l(e,["id"],i);let o=s(t,["name"]);if(o!=null&&l(e,["name"],o),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Ay(t){let e={},n=s(t,["allowedFunctionNames"]);n!=null&&l(e,["allowedFunctionNames"],n);let i=s(t,["mode"]);if(i!=null&&l(e,["mode"],i),s(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Cy(t,e,n){let i={},o=s(e,["serviceTier"]);n!==void 0&&o!=null&&l(n,["serviceTier"],o);let r=s(e,["systemInstruction"]);n!==void 0&&r!=null&&l(n,["systemInstruction"],vf(Ne(r)));let a=s(e,["temperature"]);a!=null&&l(i,["temperature"],a);let u=s(e,["topP"]);u!=null&&l(i,["topP"],u);let c=s(e,["topK"]);c!=null&&l(i,["topK"],c);let d=s(e,["candidateCount"]);d!=null&&l(i,["candidateCount"],d);let f=s(e,["maxOutputTokens"]);f!=null&&l(i,["maxOutputTokens"],f);let p=s(e,["stopSequences"]);p!=null&&l(i,["stopSequences"],p);let h=s(e,["responseLogprobs"]);h!=null&&l(i,["responseLogprobs"],h);let m=s(e,["logprobs"]);m!=null&&l(i,["logprobs"],m);let _=s(e,["presencePenalty"]);_!=null&&l(i,["presencePenalty"],_);let g=s(e,["frequencyPenalty"]);g!=null&&l(i,["frequencyPenalty"],g);let v=s(e,["seed"]);v!=null&&l(i,["seed"],v);let y=s(e,["responseMimeType"]);y!=null&&l(i,["responseMimeType"],y);let A=s(e,["responseSchema"]);A!=null&&l(i,["responseSchema"],Ya(A));let C=s(e,["responseJsonSchema"]);if(C!=null&&l(i,["responseJsonSchema"],C),s(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let S=s(e,["safetySettings"]);if(n!==void 0&&S!=null){let K=S;Array.isArray(K)&&(K=K.map(Z=>qy(Z))),l(n,["safetySettings"],K)}let R=s(e,["tools"]);if(n!==void 0&&R!=null){let K=yn(R);Array.isArray(K)&&(K=K.map(Z=>Hy(_n(Z)))),l(n,["tools"],K)}let L=s(e,["toolConfig"]);if(n!==void 0&&L!=null&&l(n,["toolConfig"],Fy(L)),s(e,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let O=s(e,["cachedContent"]);n!==void 0&&O!=null&&l(n,["cachedContent"],Tt(t,O));let H=s(e,["responseModalities"]);H!=null&&l(i,["responseModalities"],H);let U=s(e,["mediaResolution"]);U!=null&&l(i,["mediaResolution"],U);let F=s(e,["speechConfig"]);if(F!=null&&l(i,["speechConfig"],Wa(F)),s(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let J=s(e,["thinkingConfig"]);J!=null&&l(i,["thinkingConfig"],J);let Q=s(e,["audioTranscriptionConfig"]);Q!=null&&l(i,["audioTranscriptionConfig"],Q);let te=s(e,["imageConfig"]);te!=null&&l(i,["imageConfig"],Ny(te));let D=s(e,["enableEnhancedCivicAnswers"]);if(D!=null&&l(i,["enableEnhancedCivicAnswers"],D),s(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}function Iy(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let i=s(t,["candidates"]);if(i!=null){let d=i;Array.isArray(d)&&(d=d.map(f=>sy(f))),l(e,["candidates"],d)}let o=s(t,["modelVersion"]);o!=null&&l(e,["modelVersion"],o);let r=s(t,["promptFeedback"]);r!=null&&l(e,["promptFeedback"],r);let a=s(t,["responseId"]);a!=null&&l(e,["responseId"],a);let u=s(t,["usageMetadata"]);u!=null&&l(e,["usageMetadata"],u);let c=s(t,["modelStatus"]);return c!=null&&l(e,["modelStatus"],c),e}function Sy(t,e){let n={},i=s(e,["name"]);return i!=null&&l(n,["_url","name"],En(t,i)),n}function wy(t,e){let n={},i=s(e,["name"]);return i!=null&&l(n,["_url","name"],En(t,i)),n}function Ry(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],z_(n));let i=s(t,["enableWidget"]);if(i!=null&&l(e,["enableWidget"],i),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Py(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let i=s(t,["timeRangeFilter"]);return i!=null&&l(e,["timeRangeFilter"],i),e}function Ny(t){let e={},n=s(t,["aspectRatio"]);n!=null&&l(e,["aspectRatio"],n);let i=s(t,["imageSize"]);if(i!=null&&l(e,["imageSize"],i),s(t,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function ky(t,e){let n={},i=s(e,["model"]);i!=null&&l(n,["request","model"],re(t,i));let o=s(e,["contents"]);if(o!=null){let u=Le(o);Array.isArray(u)&&(u=u.map(c=>vf(c))),l(n,["request","contents"],u)}let r=s(e,["metadata"]);r!=null&&l(n,["metadata"],r);let a=s(e,["config"]);return a!=null&&l(n,["request","generationConfig"],Cy(t,a,s(n,["request"],{}))),n}function Dy(t){let e={},n=s(t,["response"]);n!=null&&l(e,["response"],Iy(n));let i=s(t,["metadata"]);i!=null&&l(e,["metadata"],i);let o=s(t,["error"]);return o!=null&&l(e,["error"],o),e}function xy(t,e){let n={},i=s(t,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=s(t,["pageToken"]);if(e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),s(t,["filter"])!==void 0)throw new Error("filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function My(t,e){let n={},i=s(t,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=s(t,["pageToken"]);e!==void 0&&o!=null&&l(e,["_query","pageToken"],o);let r=s(t,["filter"]);return e!==void 0&&r!=null&&l(e,["_query","filter"],r),n}function Uy(t){let e={},n=s(t,["config"]);return n!=null&&xy(n,e),e}function Gy(t){let e={},n=s(t,["config"]);return n!=null&&My(n,e),e}function Ly(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let i=s(t,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=s(t,["operations"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>Oi(a))),l(e,["batchJobs"],r)}return e}function by(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let i=s(t,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=s(t,["batchPredictionJobs"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>Ls(a))),l(e,["batchJobs"],r)}return e}function Oy(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let i=s(t,["toolCall"]);i!=null&&l(e,["toolCall"],i);let o=s(t,["toolResponse"]);o!=null&&l(e,["toolResponse"],o);let r=s(t,["audioTranscription"]);r!=null&&l(e,["audioTranscription"],r);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],vy(c));let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],Ty(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],iy(p));let h=s(t,["text"]);h!=null&&l(e,["text"],h);let m=s(t,["thought"]);m!=null&&l(e,["thought"],m);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let g=s(t,["videoMetadata"]);g!=null&&l(e,["videoMetadata"],g);let v=s(t,["partMetadata"]);v!=null&&l(e,["partMetadata"],v);let y=s(t,["mediaProcessing"]);return y!=null&&l(e,["mediaProcessing"],y),e}function qy(t){let e={},n=s(t,["category"]);if(n!=null&&l(e,["category"],n),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["threshold"]);return i!=null&&l(e,["threshold"],i),e}function Fy(t){let e={},n=s(t,["functionCallingConfig"]);n!=null&&l(e,["functionCallingConfig"],Ay(n));let i=s(t,["retrievalConfig"]);i!=null&&l(e,["retrievalConfig"],i);let o=s(t,["includeServerSideToolInvocations"]);return o!=null&&l(e,["includeServerSideToolInvocations"],o),e}function Hy(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],Ry(n));let i=s(t,["mcpServers"]);if(i!=null){let p=i;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let o=s(t,["codeExecution"]);o!=null&&l(e,["codeExecution"],o);let r=s(t,["computerUse"]);if(r!=null&&l(e,["computerUse"],r),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],Py(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function Vy(t){let e={},n=s(t,["bigqueryDestination","outputUri"]);n!=null&&l(e,["bigqueryDestination"],n);let i=s(t,["displayName"]);return i!=null&&l(e,["displayName"],i),e}function By(t){let e={},n=s(t,["bigqueryDestination"]);n!=null&&l(e,["bigqueryDestination","outputUri"],n);let i=s(t,["displayName"]);return i!=null&&l(e,["displayName"],i),e}var yt;(function(t){t.PAGED_ITEM_BATCH_JOBS="batchJobs",t.PAGED_ITEM_MODELS="models",t.PAGED_ITEM_TUNING_JOBS="tuningJobs",t.PAGED_ITEM_FILES="files",t.PAGED_ITEM_CACHED_CONTENTS="cachedContents",t.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",t.PAGED_ITEM_DOCUMENTS="documents",t.PAGED_ITEM_SKILLS="skills"})(yt||(yt={}));var Et=class{constructor(e,n,i,o){this.pageInternal=[],this.paramsInternal={},this.requestInternal=n,this.init(e,i,o)}init(e,n,i){var o,r;this.nameInternal=e,this.pageInternal=n[this.nameInternal]||[],this.sdkHttpResponseInternal=n?.sdkHttpResponse,this.idxInternal=0;let a={config:{}};!i||Object.keys(i).length===0?a={config:{}}:typeof i=="object"?a=Object.assign({},i):a=i,a.config&&(a.config.pageToken=n.nextPageToken),this.paramsInternal=a,this.pageInternalSize=(r=(o=a.config)===null||o===void 0?void 0:o.pageSize)!==null&&r!==void 0?r:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};let e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");let e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0}};var bs=class extends it{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Et(yt.PAGED_ITEM_BATCH_JOBS,i=>this.listInternal(i),await this.listInternal(n),n),this.create=async n=>(this.apiClient.isVertexAI()&&(n.config=this.formatDestination(n.src,n.config)),this.createInternal(n)),this.createEmbeddings=async n=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(n)}}createInlinedGenerateContentRequest(e){let n=wd(this.apiClient,e),i=n._url,o=B("{model}:batchGenerateContent",i),u=n.batch.inputConfig.requests,c=u.requests,d=[];for(let f of c){let p=Object.assign({},f);if(p.systemInstruction){let h=p.systemInstruction;delete p.systemInstruction;let m=p.request;m.systemInstruction=h,p.request=m}d.push(p)}return u.requests=d,delete n.config,delete n._url,delete n._query,{path:o,body:n}}getGcsUri(e){if(typeof e=="string")return e.startsWith("gs://")?e:void 0;if(!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0)return e.gcsUri[0]}getBigqueryUri(e){if(typeof e=="string")return e.startsWith("bq://")?e:void 0;if(!Array.isArray(e))return e.bigqueryUri}formatDestination(e,n){let i=n?Object.assign({},n):{},o=Date.now().toString();if(i.displayName||(i.displayName=`genaiBatchJob_${o}`),i.dest===void 0){let r=this.getGcsUri(e),a=this.getBigqueryUri(e);if(r)r.endsWith(".jsonl")?i.dest=`${r.slice(0,-6)}/dest`:i.dest=`${r}_dest_${o}`;else if(a)i.dest=`${a}_dest_${o}`;else throw new Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return i}async createInternal(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=cy(this.apiClient,e);return u=B("batchPredictionJobs",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>Ls(f))}else{let d=wd(this.apiClient,e);return u=B("{model}:batchGenerateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>Oi(f))}}async createEmbeddingsInternal(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=fy(this.apiClient,e);return r=B("{model}:asyncBatchEmbedContent",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json()),o.then(c=>Oi(c))}}async get(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=wy(this.apiClient,e);return u=B("batchPredictionJobs/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>Ls(f))}else{let d=Sy(this.apiClient,e);return u=B("batches/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>Oi(f))}}async cancel(e){var n,i,o,r;let a="",u={};if(this.apiClient.isVertexAI()){let c=ry(this.apiClient,e);a=B("batchPredictionJobs/{name}:cancel",c._url),u=c._query,delete c._url,delete c._query,await this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}else{let c=oy(this.apiClient,e);a=B("batches/{name}:cancel",c._url),u=c._query,delete c._url,delete c._query,await this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal})}}async listInternal(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=Gy(e);return u=B("batchPredictionJobs",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=by(f),h=new zi;return Object.assign(h,p),h})}else{let d=Uy(e);return u=B("batches",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=Ly(f),h=new zi;return Object.assign(h,p),h})}}async delete(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=hy(this.apiClient,e);return u=B("batchPredictionJobs/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>gy(f))}else{let d=py(this.apiClient,e);return u=B("batches/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>my(f))}}};function $y(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Jy(t){let e={},n=s(t,["data"]);if(n!=null&&l(e,["data"],n),s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}function Xy(t){let e={},n=s(t,["enablePromptInjectionDetection"]);n!=null&&l(e,["enablePromptInjectionDetection"],n);let i=s(t,["environment"]);i!=null&&l(e,["environment"],i);let o=s(t,["excludedPredefinedFunctions"]);if(o!=null&&l(e,["excludedPredefinedFunctions"],o),s(t,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function Rd(t){let e={},n=s(t,["parts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(r=>mE(r))),l(e,["parts"],o)}let i=s(t,["role"]);return i!=null&&l(e,["role"],i),e}function Pd(t){let e={},n=s(t,["parts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(r=>gE(r))),l(e,["parts"],o)}let i=s(t,["role"]);return i!=null&&l(e,["role"],i),e}function Ky(t,e){let n={},i=s(t,["ttl"]);e!==void 0&&i!=null&&l(e,["ttl"],i);let o=s(t,["expireTime"]);e!==void 0&&o!=null&&l(e,["expireTime"],o);let r=s(t,["displayName"]);e!==void 0&&r!=null&&l(e,["displayName"],r);let a=s(t,["contents"]);if(e!==void 0&&a!=null){let f=Le(a);Array.isArray(f)&&(f=f.map(p=>Rd(p))),l(e,["contents"],f)}let u=s(t,["systemInstruction"]);e!==void 0&&u!=null&&l(e,["systemInstruction"],Rd(Ne(u)));let c=s(t,["tools"]);if(e!==void 0&&c!=null){let f=c;Array.isArray(f)&&(f=f.map(p=>EE(p))),l(e,["tools"],f)}let d=s(t,["toolConfig"]);if(e!==void 0&&d!=null&&l(e,["toolConfig"],_E(d)),s(t,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function Yy(t,e){let n={},i=s(t,["ttl"]);e!==void 0&&i!=null&&l(e,["ttl"],i);let o=s(t,["expireTime"]);e!==void 0&&o!=null&&l(e,["expireTime"],o);let r=s(t,["displayName"]);e!==void 0&&r!=null&&l(e,["displayName"],r);let a=s(t,["contents"]);if(e!==void 0&&a!=null){let p=Le(a);Array.isArray(p)&&(p=p.map(h=>Pd(h))),l(e,["contents"],p)}let u=s(t,["systemInstruction"]);e!==void 0&&u!=null&&l(e,["systemInstruction"],Pd(Ne(u)));let c=s(t,["tools"]);if(e!==void 0&&c!=null){let p=c;Array.isArray(p)&&(p=p.map(h=>vE(h))),l(e,["tools"],p)}let d=s(t,["toolConfig"]);e!==void 0&&d!=null&&l(e,["toolConfig"],yE(d));let f=s(t,["kmsKeyName"]);return e!==void 0&&f!=null&&l(e,["encryption_spec","kmsKeyName"],f),n}function Wy(t,e){let n={},i=s(e,["model"]);i!=null&&l(n,["model"],af(t,i));let o=s(e,["config"]);return o!=null&&Ky(o,n),n}function zy(t,e){let n={},i=s(e,["model"]);i!=null&&l(n,["model"],af(t,i));let o=s(e,["config"]);return o!=null&&Yy(o,n),n}function Qy(t,e){let n={},i=s(e,["name"]);return i!=null&&l(n,["_url","name"],Tt(t,i)),n}function Zy(t,e){let n={},i=s(e,["name"]);return i!=null&&l(n,["_url","name"],Tt(t,i)),n}function jy(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function eE(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function tE(t){let e={};if(s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["fileUri"]);n!=null&&l(e,["fileUri"],n);let i=s(t,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}function nE(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let i=s(t,["id"]);i!=null&&l(e,["id"],i);let o=s(t,["name"]);if(o!=null&&l(e,["name"],o),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function iE(t){let e={},n=s(t,["allowedFunctionNames"]);n!=null&&l(e,["allowedFunctionNames"],n);let i=s(t,["mode"]);if(i!=null&&l(e,["mode"],i),s(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function oE(t,e){let n={},i=s(e,["name"]);return i!=null&&l(n,["_url","name"],Tt(t,i)),n}function rE(t,e){let n={},i=s(e,["name"]);return i!=null&&l(n,["_url","name"],Tt(t,i)),n}function sE(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],$y(n));let i=s(t,["enableWidget"]);if(i!=null&&l(e,["enableWidget"],i),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function aE(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let i=s(t,["timeRangeFilter"]);return i!=null&&l(e,["timeRangeFilter"],i),e}function lE(t,e){let n={},i=s(t,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=s(t,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),n}function uE(t,e){let n={},i=s(t,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=s(t,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),n}function cE(t){let e={},n=s(t,["config"]);return n!=null&&lE(n,e),e}function dE(t){let e={},n=s(t,["config"]);return n!=null&&uE(n,e),e}function fE(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let i=s(t,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=s(t,["cachedContents"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["cachedContents"],r)}return e}function pE(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let i=s(t,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=s(t,["cachedContents"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["cachedContents"],r)}return e}function hE(t){let e={};if(s(t,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function mE(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let i=s(t,["toolCall"]);i!=null&&l(e,["toolCall"],i);let o=s(t,["toolResponse"]);o!=null&&l(e,["toolResponse"],o);let r=s(t,["audioTranscription"]);r!=null&&l(e,["audioTranscription"],r);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],tE(c));let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],nE(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],Jy(p));let h=s(t,["text"]);h!=null&&l(e,["text"],h);let m=s(t,["thought"]);m!=null&&l(e,["thought"],m);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let g=s(t,["videoMetadata"]);g!=null&&l(e,["videoMetadata"],g);let v=s(t,["partMetadata"]);v!=null&&l(e,["partMetadata"],v);let y=s(t,["mediaProcessing"]);return y!=null&&l(e,["mediaProcessing"],y),e}function gE(t){let e={},n=s(t,["mediaResolution"]);if(n!=null&&l(e,["mediaResolution"],n),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let i=s(t,["audioTranscription"]);i!=null&&l(e,["audioTranscription"],i);let o=s(t,["codeExecutionResult"]);o!=null&&l(e,["codeExecutionResult"],o);let r=s(t,["executableCode"]);r!=null&&l(e,["executableCode"],r);let a=s(t,["fileData"]);a!=null&&l(e,["fileData"],a);let u=s(t,["functionCall"]);u!=null&&l(e,["functionCall"],u);let c=s(t,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=s(t,["inlineData"]);d!=null&&l(e,["inlineData"],d);let f=s(t,["text"]);f!=null&&l(e,["text"],f);let p=s(t,["thought"]);p!=null&&l(e,["thought"],p);let h=s(t,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let m=s(t,["videoMetadata"]);if(m!=null&&l(e,["videoMetadata"],m),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let _=s(t,["mediaProcessing"]);return _!=null&&l(e,["mediaProcessing"],_),e}function _E(t){let e={},n=s(t,["functionCallingConfig"]);n!=null&&l(e,["functionCallingConfig"],iE(n));let i=s(t,["retrievalConfig"]);i!=null&&l(e,["retrievalConfig"],i);let o=s(t,["includeServerSideToolInvocations"]);return o!=null&&l(e,["includeServerSideToolInvocations"],o),e}function yE(t){let e={},n=s(t,["functionCallingConfig"]);n!=null&&l(e,["functionCallingConfig"],n);let i=s(t,["retrievalConfig"]);if(i!=null&&l(e,["retrievalConfig"],i),s(t,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function EE(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],sE(n));let i=s(t,["mcpServers"]);if(i!=null){let p=i;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let o=s(t,["codeExecution"]);o!=null&&l(e,["codeExecution"],o);let r=s(t,["computerUse"]);if(r!=null&&l(e,["computerUse"],r),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],aE(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function vE(t){let e={},n=s(t,["retrieval"]);n!=null&&l(e,["retrieval"],n);let i=s(t,["googleMaps"]);i!=null&&l(e,["googleMaps"],i);let o=s(t,["mcpServers"]);if(o!=null){let _=o;Array.isArray(_)&&(_=_.map(g=>hE(g))),l(e,["mcpServers"],_)}let r=s(t,["codeExecution"]);r!=null&&l(e,["codeExecution"],r);let a=s(t,["computerUse"]);a!=null&&l(e,["computerUse"],Xy(a));let u=s(t,["enterpriseWebSearch"]);u!=null&&l(e,["enterpriseWebSearch"],u);let c=s(t,["exaAiSearch"]);c!=null&&l(e,["exaAiSearch"],c);let d=s(t,["functionDeclarations"]);if(d!=null){let _=d;Array.isArray(_)&&(_=_.map(g=>g)),l(e,["functionDeclarations"],_)}let f=s(t,["googleSearch"]);f!=null&&l(e,["googleSearch"],f);let p=s(t,["googleSearchRetrieval"]);p!=null&&l(e,["googleSearchRetrieval"],p);let h=s(t,["parallelAiSearch"]);h!=null&&l(e,["parallelAiSearch"],h);let m=s(t,["urlContext"]);if(m!=null&&l(e,["urlContext"],m),s(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function TE(t,e){let n={},i=s(t,["ttl"]);e!==void 0&&i!=null&&l(e,["ttl"],i);let o=s(t,["expireTime"]);return e!==void 0&&o!=null&&l(e,["expireTime"],o),n}function AE(t,e){let n={},i=s(t,["ttl"]);e!==void 0&&i!=null&&l(e,["ttl"],i);let o=s(t,["expireTime"]);return e!==void 0&&o!=null&&l(e,["expireTime"],o),n}function CE(t,e){let n={},i=s(e,["name"]);i!=null&&l(n,["_url","name"],Tt(t,i));let o=s(e,["config"]);return o!=null&&TE(o,n),n}function IE(t,e){let n={},i=s(e,["name"]);i!=null&&l(n,["_url","name"],Tt(t,i));let o=s(e,["config"]);return o!=null&&AE(o,n),n}var Os=class extends it{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Et(yt.PAGED_ITEM_CACHED_CONTENTS,i=>this.listInternal(i),await this.listInternal(n),n)}async create(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=zy(this.apiClient,e);return u=B("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let d=Wy(this.apiClient,e);return u=B("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async get(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=rE(this.apiClient,e);return u=B("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let d=oE(this.apiClient,e);return u=B("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async delete(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=Zy(this.apiClient,e);return u=B("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=eE(f),h=new Yi;return Object.assign(h,p),h})}else{let d=Qy(this.apiClient,e);return u=B("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=jy(f),h=new Yi;return Object.assign(h,p),h})}}async update(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=IE(this.apiClient,e);return u=B("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{let d=CE(this.apiClient,e);return u=B("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async listInternal(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=dE(e);return u=B("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=pE(f),h=new Wi;return Object.assign(h,p),h})}else{let d=cE(e);return u=B("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=fE(f),h=new Wi;return Object.assign(h,p),h})}}};function Me(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,i=Object.getOwnPropertySymbols(t);o<i.length;o++)e.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(t,i[o])&&(n[i[o]]=t[i[o]]);return n}function Nd(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function ve(t){return this instanceof ve?(this.v=t,this):new ve(t)}function pn(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),o,r=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),u("next"),u("throw"),u("return",a),o[Symbol.asyncIterator]=function(){return this},o;function a(m){return function(_){return Promise.resolve(_).then(m,p)}}function u(m,_){i[m]&&(o[m]=function(g){return new Promise(function(v,y){r.push([m,g,v,y])>1||c(m,g)})},_&&(o[m]=_(o[m])))}function c(m,_){try{d(i[m](_))}catch(g){h(r[0][3],g)}}function d(m){m.value instanceof ve?Promise.resolve(m.value.v).then(f,p):h(r[0][2],m)}function f(m){c("next",m)}function p(m){c("throw",m)}function h(m,_){m(_),r.shift(),r.length&&c(r[0][0],r[0][1])}}function bn(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Nd=="function"?Nd(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(r){n[r]=t[r]&&function(a){return new Promise(function(u,c){a=t[r](a),o(u,c,a.done,a.value)})}}function o(r,a,u,c){Promise.resolve(c).then(function(d){r({value:d,done:u})},a)}}function SE(t){var e;if(t.candidates==null||t.candidates.length===0)return!1;let n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;return n===void 0?!1:Tf(n)}function Tf(t){if(t.parts===void 0||t.parts.length===0)return!1;for(let e of t.parts)if(e===void 0||Object.keys(e).length===0)return!1;return!0}function wE(t){if(t.length!==0){for(let e of t)if(e.role!=="user"&&e.role!=="model")throw new Error(`Role must be user or model, but got ${e.role}.`)}}function kd(t){if(t===void 0||t.length===0)return[];let e=[],n=t.length,i=0;for(;i<n;)if(t[i].role==="user")e.push(t[i]),i++;else{let o=[],r=!0;for(;i<n&&t[i].role==="model";)o.push(t[i]),r&&!Tf(t[i])&&(r=!1),i++;r?e.push(...o):e.pop()}return e}var qs=class{constructor(e,n){this.modelsModule=e,this.apiClient=n}create(e){return new Fs(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},Fs=class{constructor(e,n,i,o={},r=[]){this.apiClient=e,this.modelsModule=n,this.model=i,this.config=o,this.history=r,this.sendPromise=Promise.resolve(),wE(r)}async sendMessage(e){var n;await this.sendPromise;let i=Ne(e.message),o=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(i),config:(n=e.config)!==null&&n!==void 0?n:this.config});return this.sendPromise=(async()=>{var r,a,u;let c=await o,d=(a=(r=c.candidates)===null||r===void 0?void 0:r[0])===null||a===void 0?void 0:a.content,f=c.automaticFunctionCallingHistory,p=this.getHistory(!0).length,h=[];f!=null&&(h=(u=f.slice(p))!==null&&u!==void 0?u:[]);let m=d?[d]:[];this.recordHistory(i,m,h)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),o}async sendMessageStream(e){var n;await this.sendPromise;let i=Ne(e.message),o=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(i),config:(n=e.config)!==null&&n!==void 0?n:this.config});this.sendPromise=o.then(()=>{}).catch(()=>{});let r=await o;return this.processStreamResponse(r,i)}getHistory(e=!1){let n=e?kd(this.history):this.history;return structuredClone(n)}processStreamResponse(e,n){return pn(this,arguments,function*(){var o,r,a,u,c,d;let f=[];try{for(var p=!0,h=bn(e),m;m=yield ve(h.next()),o=m.done,!o;p=!0){u=m.value,p=!1;let _=u;if(SE(_)){let g=(d=(c=_.candidates)===null||c===void 0?void 0:c[0])===null||d===void 0?void 0:d.content;g!==void 0&&f.push(g)}yield yield ve(_)}}catch(_){r={error:_}}finally{try{!p&&!o&&(a=h.return)&&(yield ve(a.call(h)))}finally{if(r)throw r.error}}this.recordHistory(n,f)})}recordHistory(e,n,i){let o=[];n.length>0&&n.every(r=>r.role!==void 0)?o=n:o.push({role:"model",parts:[]}),i&&i.length>0?this.history.push(...kd(i)):this.history.push(e),this.history.push(...o)}};var ji=class t extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,t.prototype)}};function RE(t){let e={},n=s(t,["file"]);return n!=null&&l(e,["file"],n),e}function PE(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function NE(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","file"],Qa(n)),e}function kE(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}function DE(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","file"],Qa(n)),e}function xE(t){let e={},n=s(t,["uris"]);return n!=null&&l(e,["uris"],n),e}function ME(t,e){let n={},i=s(t,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=s(t,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),n}function UE(t){let e={},n=s(t,["config"]);return n!=null&&ME(n,e),e}function GE(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let i=s(t,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=s(t,["files"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["files"],r)}return e}function LE(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let i=s(t,["files"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(r=>r)),l(e,["files"],o)}return e}var bE=class extends it{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Et(yt.PAGED_ITEM_FILES,i=>this.listInternal(i),await this.listInternal(n),n)}async upload(e){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(e.file,e.config).then(n=>n)}async download(e){await this.apiClient.downloadFile(e)}async registerFiles(e){throw new Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(e){return this.registerFilesInternal(e)}async listInternal(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=UE(e);return r=B("files",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>{let d=GE(c),f=new Ns;return Object.assign(f,d),f})}}async createInternal(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=RE(e);return r=B("upload/v1beta/files",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json()),o.then(c=>{let d=PE(c),f=new ks;return Object.assign(f,d),f})}}async get(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=DE(e);return r=B("files/{file}",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json()),o.then(c=>c)}}async delete(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=NE(e);return r=B("files/{file}",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>{let d=kE(c),f=new Ds;return Object.assign(f,d),f})}}async registerFilesInternal(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=xE(e);return r=B("files:register",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json()),o.then(c=>{let d=LE(c),f=new xs;return Object.assign(f,d),f})}}};function OE(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function qi(t){let e={},n=s(t,["data"]);if(n!=null&&l(e,["data"],n),s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}function qE(t){let e={},n=s(t,["enablePromptInjectionDetection"]);n!=null&&l(e,["enablePromptInjectionDetection"],n);let i=s(t,["environment"]);i!=null&&l(e,["environment"],i);let o=s(t,["excludedPredefinedFunctions"]);if(o!=null&&l(e,["excludedPredefinedFunctions"],o),s(t,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function FE(t){let e={},n=s(t,["parts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(r=>ov(r))),l(e,["parts"],o)}let i=s(t,["role"]);return i!=null&&l(e,["role"],i),e}function HE(t){let e={},n=s(t,["parts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(r=>rv(r))),l(e,["parts"],o)}let i=s(t,["role"]);return i!=null&&l(e,["role"],i),e}function VE(t){let e={};if(s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["fileUri"]);n!=null&&l(e,["fileUri"],n);let i=s(t,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}function BE(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let i=s(t,["id"]);i!=null&&l(e,["id"],i);let o=s(t,["name"]);if(o!=null&&l(e,["name"],o),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function $E(t){let e={},n=s(t,["modelSelectionConfig"]);n!=null&&l(e,["modelConfig"],n);let i=s(t,["responseJsonSchema"]);i!=null&&l(e,["responseJsonSchema"],i);let o=s(t,["audioTranscriptionConfig"]);o!=null&&l(e,["audioTranscriptionConfig"],o);let r=s(t,["audioTimestamp"]);r!=null&&l(e,["audioTimestamp"],r);let a=s(t,["candidateCount"]);a!=null&&l(e,["candidateCount"],a);let u=s(t,["enableAffectiveDialog"]);u!=null&&l(e,["enableAffectiveDialog"],u);let c=s(t,["frequencyPenalty"]);c!=null&&l(e,["frequencyPenalty"],c);let d=s(t,["logprobs"]);d!=null&&l(e,["logprobs"],d);let f=s(t,["maxOutputTokens"]);f!=null&&l(e,["maxOutputTokens"],f);let p=s(t,["mediaResolution"]);p!=null&&l(e,["mediaResolution"],p);let h=s(t,["presencePenalty"]);h!=null&&l(e,["presencePenalty"],h);let m=s(t,["responseFormat"]);if(m!=null){let F=m;Array.isArray(F)&&(F=F.map(J=>J)),l(e,["responseFormat"],F)}let _=s(t,["responseLogprobs"]);_!=null&&l(e,["responseLogprobs"],_);let g=s(t,["responseMimeType"]);g!=null&&l(e,["responseMimeType"],g);let v=s(t,["responseModalities"]);v!=null&&l(e,["responseModalities"],v);let y=s(t,["responseSchema"]);y!=null&&l(e,["responseSchema"],y);let A=s(t,["routingConfig"]);A!=null&&l(e,["routingConfig"],A);let C=s(t,["seed"]);C!=null&&l(e,["seed"],C);let S=s(t,["speechConfig"]);S!=null&&l(e,["speechConfig"],Af(S));let R=s(t,["stopSequences"]);R!=null&&l(e,["stopSequences"],R);let L=s(t,["temperature"]);L!=null&&l(e,["temperature"],L);let O=s(t,["thinkingConfig"]);O!=null&&l(e,["thinkingConfig"],O);let H=s(t,["topK"]);H!=null&&l(e,["topK"],H);let U=s(t,["topP"]);if(U!=null&&l(e,["topP"],U),s(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function JE(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],OE(n));let i=s(t,["enableWidget"]);if(i!=null&&l(e,["enableWidget"],i),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function XE(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let i=s(t,["timeRangeFilter"]);return i!=null&&l(e,["timeRangeFilter"],i),e}function KE(t,e){let n={},i=s(t,["generationConfig"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig"],i);let o=s(t,["responseModalities"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","responseModalities"],o);let r=s(t,["temperature"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig","temperature"],r);let a=s(t,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let u=s(t,["topK"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","topK"],u);let c=s(t,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);let d=s(t,["mediaResolution"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","mediaResolution"],d);let f=s(t,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let p=s(t,["speechConfig"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","speechConfig"],za(p));let h=s(t,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let m=s(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],m);let _=s(t,["systemInstruction"]);e!==void 0&&_!=null&&l(e,["setup","systemInstruction"],FE(Ne(_)));let g=s(t,["tools"]);if(e!==void 0&&g!=null){let U=yn(g);Array.isArray(U)&&(U=U.map(F=>cv(_n(F)))),l(e,["setup","tools"],U)}let v=s(t,["sessionResumption"]);e!==void 0&&v!=null&&l(e,["setup","sessionResumption"],lv(v));let y=s(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&l(e,["setup","inputAudioTranscription"],y);let A=s(t,["outputAudioTranscription"]);e!==void 0&&A!=null&&l(e,["setup","outputAudioTranscription"],A);let C=s(t,["realtimeInputConfig"]);e!==void 0&&C!=null&&l(e,["setup","realtimeInputConfig"],C);let S=s(t,["contextWindowCompression"]);e!==void 0&&S!=null&&l(e,["setup","contextWindowCompression"],S);let R=s(t,["proactivity"]);if(e!==void 0&&R!=null&&l(e,["setup","proactivity"],R),s(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let L=s(t,["avatarConfig"]);e!==void 0&&L!=null&&l(e,["setup","avatarConfig"],L);let O=s(t,["safetySettings"]);if(e!==void 0&&O!=null){let U=O;Array.isArray(U)&&(U=U.map(F=>av(F))),l(e,["setup","safetySettings"],U)}let H=s(t,["translationConfig"]);return e!==void 0&&H!=null&&l(e,["setup","generationConfig","translationConfig"],H),n}function YE(t,e){let n={},i=s(t,["generationConfig"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig"],$E(i));let o=s(t,["responseModalities"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","responseModalities"],o);let r=s(t,["temperature"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig","temperature"],r);let a=s(t,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let u=s(t,["topK"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","topK"],u);let c=s(t,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);let d=s(t,["mediaResolution"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","mediaResolution"],d);let f=s(t,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let p=s(t,["speechConfig"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","speechConfig"],Af(za(p)));let h=s(t,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let m=s(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],m);let _=s(t,["systemInstruction"]);e!==void 0&&_!=null&&l(e,["setup","systemInstruction"],HE(Ne(_)));let g=s(t,["tools"]);if(e!==void 0&&g!=null){let F=yn(g);Array.isArray(F)&&(F=F.map(J=>dv(_n(J)))),l(e,["setup","tools"],F)}let v=s(t,["sessionResumption"]);e!==void 0&&v!=null&&l(e,["setup","sessionResumption"],v);let y=s(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&l(e,["setup","inputAudioTranscription"],y);let A=s(t,["outputAudioTranscription"]);e!==void 0&&A!=null&&l(e,["setup","outputAudioTranscription"],A);let C=s(t,["realtimeInputConfig"]);e!==void 0&&C!=null&&l(e,["setup","realtimeInputConfig"],C);let S=s(t,["contextWindowCompression"]);e!==void 0&&S!=null&&l(e,["setup","contextWindowCompression"],S);let R=s(t,["proactivity"]);e!==void 0&&R!=null&&l(e,["setup","proactivity"],R);let L=s(t,["explicitVadSignal"]);e!==void 0&&L!=null&&l(e,["setup","explicitVadSignal"],L);let O=s(t,["avatarConfig"]);e!==void 0&&O!=null&&l(e,["setup","avatarConfig"],O);let H=s(t,["safetySettings"]);if(e!==void 0&&H!=null){let F=H;Array.isArray(F)&&(F=F.map(J=>J)),l(e,["setup","safetySettings"],F)}let U=s(t,["translationConfig"]);return e!==void 0&&U!=null&&l(e,["setup","generationConfig","translationConfig"],U),n}function WE(t,e){let n={},i=s(e,["model"]);i!=null&&l(n,["setup","model"],re(t,i));let o=s(e,["config"]);return o!=null&&l(n,["config"],KE(o,n)),n}function zE(t,e){let n={},i=s(e,["model"]);i!=null&&l(n,["setup","model"],re(t,i));let o=s(e,["config"]);return o!=null&&l(n,["config"],YE(o,n)),n}function QE(t){let e={},n=s(t,["musicGenerationConfig"]);return n!=null&&l(e,["musicGenerationConfig"],n),e}function ZE(t){let e={},n=s(t,["weightedPrompts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>o)),l(e,["weightedPrompts"],i)}return e}function jE(t){let e={},n=s(t,["media"]);if(n!=null){let d=lf(n);Array.isArray(d)&&(d=d.map(f=>qi(f))),l(e,["mediaChunks"],d)}let i=s(t,["audio"]);i!=null&&l(e,["audio"],qi(cf(i)));let o=s(t,["audioStreamEnd"]);o!=null&&l(e,["audioStreamEnd"],o);let r=s(t,["video"]);r!=null&&l(e,["video"],qi(uf(r)));let a=s(t,["text"]);a!=null&&l(e,["text"],a);let u=s(t,["activityStart"]);u!=null&&l(e,["activityStart"],u);let c=s(t,["activityEnd"]);return c!=null&&l(e,["activityEnd"],c),e}function ev(t){let e={},n=s(t,["media"]);if(n!=null){let d=lf(n);Array.isArray(d)&&(d=d.map(f=>f)),l(e,["mediaChunks"],d)}let i=s(t,["audio"]);i!=null&&l(e,["audio"],cf(i));let o=s(t,["audioStreamEnd"]);o!=null&&l(e,["audioStreamEnd"],o);let r=s(t,["video"]);r!=null&&l(e,["video"],uf(r));let a=s(t,["text"]);a!=null&&l(e,["text"],a);let u=s(t,["activityStart"]);u!=null&&l(e,["activityStart"],u);let c=s(t,["activityEnd"]);return c!=null&&l(e,["activityEnd"],c),e}function tv(t){let e={},n=s(t,["setupComplete"]);n!=null&&l(e,["setupComplete"],n);let i=s(t,["serverContent"]);i!=null&&l(e,["serverContent"],i);let o=s(t,["toolCall"]);o!=null&&l(e,["toolCall"],o);let r=s(t,["toolCallCancellation"]);r!=null&&l(e,["toolCallCancellation"],r);let a=s(t,["usageMetadata"]);a!=null&&l(e,["usageMetadata"],fv(a));let u=s(t,["goAway"]);u!=null&&l(e,["goAway"],u);let c=s(t,["sessionResumptionUpdate"]);c!=null&&l(e,["sessionResumptionUpdate"],c);let d=s(t,["voiceActivityDetectionSignal"]);d!=null&&l(e,["voiceActivityDetectionSignal"],d);let f=s(t,["voiceActivity"]);return f!=null&&l(e,["voiceActivity"],pv(f)),e}function nv(t){let e={};if(s(t,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function iv(t){let e={},n=s(t,["speakerVoiceConfigs"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>uv(o))),l(e,["speakerVoiceConfigs"],i)}return e}function ov(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let i=s(t,["toolCall"]);i!=null&&l(e,["toolCall"],i);let o=s(t,["toolResponse"]);o!=null&&l(e,["toolResponse"],o);let r=s(t,["audioTranscription"]);r!=null&&l(e,["audioTranscription"],r);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],VE(c));let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],BE(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],qi(p));let h=s(t,["text"]);h!=null&&l(e,["text"],h);let m=s(t,["thought"]);m!=null&&l(e,["thought"],m);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let g=s(t,["videoMetadata"]);g!=null&&l(e,["videoMetadata"],g);let v=s(t,["partMetadata"]);v!=null&&l(e,["partMetadata"],v);let y=s(t,["mediaProcessing"]);return y!=null&&l(e,["mediaProcessing"],y),e}function rv(t){let e={},n=s(t,["mediaResolution"]);if(n!=null&&l(e,["mediaResolution"],n),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let i=s(t,["audioTranscription"]);i!=null&&l(e,["audioTranscription"],i);let o=s(t,["codeExecutionResult"]);o!=null&&l(e,["codeExecutionResult"],o);let r=s(t,["executableCode"]);r!=null&&l(e,["executableCode"],r);let a=s(t,["fileData"]);a!=null&&l(e,["fileData"],a);let u=s(t,["functionCall"]);u!=null&&l(e,["functionCall"],u);let c=s(t,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=s(t,["inlineData"]);d!=null&&l(e,["inlineData"],d);let f=s(t,["text"]);f!=null&&l(e,["text"],f);let p=s(t,["thought"]);p!=null&&l(e,["thought"],p);let h=s(t,["thoughtSignature"]);h!=null&&l(e,["thoughtSignature"],h);let m=s(t,["videoMetadata"]);if(m!=null&&l(e,["videoMetadata"],m),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let _=s(t,["mediaProcessing"]);return _!=null&&l(e,["mediaProcessing"],_),e}function sv(t){let e={},n=s(t,["mimeType"]);n!=null&&l(e,["mimeType"],n);let i=s(t,["voiceSampleAudio"]);if(i!=null&&l(e,["voiceSampleAudio"],i),s(t,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function av(t){let e={},n=s(t,["category"]);if(n!=null&&l(e,["category"],n),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["threshold"]);return i!=null&&l(e,["threshold"],i),e}function lv(t){let e={},n=s(t,["handle"]);if(n!=null&&l(e,["handle"],n),s(t,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function uv(t){let e={},n=s(t,["speaker"]);n!=null&&l(e,["speaker"],n);let i=s(t,["voiceConfig"]);return i!=null&&l(e,["voiceConfig"],Cf(i)),e}function Af(t){let e={},n=s(t,["voiceConfig"]);n!=null&&l(e,["voiceConfig"],Cf(n));let i=s(t,["languageCode"]);i!=null&&l(e,["languageCode"],i);let o=s(t,["multiSpeakerVoiceConfig"]);return o!=null&&l(e,["multiSpeakerVoiceConfig"],iv(o)),e}function cv(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],JE(n));let i=s(t,["mcpServers"]);if(i!=null){let p=i;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let o=s(t,["codeExecution"]);o!=null&&l(e,["codeExecution"],o);let r=s(t,["computerUse"]);if(r!=null&&l(e,["computerUse"],r),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],XE(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function dv(t){let e={},n=s(t,["retrieval"]);n!=null&&l(e,["retrieval"],n);let i=s(t,["googleMaps"]);i!=null&&l(e,["googleMaps"],i);let o=s(t,["mcpServers"]);if(o!=null){let _=o;Array.isArray(_)&&(_=_.map(g=>nv(g))),l(e,["mcpServers"],_)}let r=s(t,["codeExecution"]);r!=null&&l(e,["codeExecution"],r);let a=s(t,["computerUse"]);a!=null&&l(e,["computerUse"],qE(a));let u=s(t,["enterpriseWebSearch"]);u!=null&&l(e,["enterpriseWebSearch"],u);let c=s(t,["exaAiSearch"]);c!=null&&l(e,["exaAiSearch"],c);let d=s(t,["functionDeclarations"]);if(d!=null){let _=d;Array.isArray(_)&&(_=_.map(g=>g)),l(e,["functionDeclarations"],_)}let f=s(t,["googleSearch"]);f!=null&&l(e,["googleSearch"],f);let p=s(t,["googleSearchRetrieval"]);p!=null&&l(e,["googleSearchRetrieval"],p);let h=s(t,["parallelAiSearch"]);h!=null&&l(e,["parallelAiSearch"],h);let m=s(t,["urlContext"]);if(m!=null&&l(e,["urlContext"],m),s(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function fv(t){let e={},n=s(t,["candidatesTokenCount"]);n!=null&&l(e,["responseTokenCount"],n);let i=s(t,["candidatesTokensDetails"]);if(i!=null){let m=i;Array.isArray(m)&&(m=m.map(_=>_)),l(e,["responseTokensDetails"],m)}let o=s(t,["cacheTokensDetails"]);if(o!=null){let m=o;Array.isArray(m)&&(m=m.map(_=>_)),l(e,["cacheTokensDetails"],m)}let r=s(t,["cachedContentTokenCount"]);r!=null&&l(e,["cachedContentTokenCount"],r);let a=s(t,["promptTokenCount"]);a!=null&&l(e,["promptTokenCount"],a);let u=s(t,["promptTokensDetails"]);if(u!=null){let m=u;Array.isArray(m)&&(m=m.map(_=>_)),l(e,["promptTokensDetails"],m)}let c=s(t,["thoughtsTokenCount"]);c!=null&&l(e,["thoughtsTokenCount"],c);let d=s(t,["toolUsePromptTokenCount"]);d!=null&&l(e,["toolUsePromptTokenCount"],d);let f=s(t,["toolUsePromptTokensDetails"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(_=>_)),l(e,["toolUsePromptTokensDetails"],m)}let p=s(t,["totalTokenCount"]);p!=null&&l(e,["totalTokenCount"],p);let h=s(t,["trafficType"]);return h!=null&&l(e,["trafficType"],h),e}function pv(t){let e={},n=s(t,["type"]);n!=null&&l(e,["voiceActivityType"],n);let i=s(t,["audioOffset"]);return i!=null&&l(e,["audioOffset"],i),e}function Cf(t){let e={},n=s(t,["replicatedVoiceConfig"]);n!=null&&l(e,["replicatedVoiceConfig"],sv(n));let i=s(t,["prebuiltVoiceConfig"]);return i!=null&&l(e,["prebuiltVoiceConfig"],i),e}function hv(t,e){let n={},i=s(t,["apiKey"]);if(i!=null&&l(n,["apiKey"],i),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function mv(t,e){let n={},i=s(t,["data"]);if(i!=null&&l(n,["data"],i),s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(t,["mimeType"]);return o!=null&&l(n,["mimeType"],o),n}function gv(t,e){let n={},i=s(t,["content"]);i!=null&&l(n,["content"],i);let o=s(t,["citationMetadata"]);o!=null&&l(n,["citationMetadata"],_v(o));let r=s(t,["tokenCount"]);r!=null&&l(n,["tokenCount"],r);let a=s(t,["finishReason"]);a!=null&&l(n,["finishReason"],a);let u=s(t,["groundingMetadata"]);u!=null&&l(n,["groundingMetadata"],u);let c=s(t,["avgLogprobs"]);c!=null&&l(n,["avgLogprobs"],c);let d=s(t,["index"]);d!=null&&l(n,["index"],d);let f=s(t,["logprobsResult"]);f!=null&&l(n,["logprobsResult"],f);let p=s(t,["safetyRatings"]);if(p!=null){let m=p;Array.isArray(m)&&(m=m.map(_=>_)),l(n,["safetyRatings"],m)}let h=s(t,["urlContextMetadata"]);return h!=null&&l(n,["urlContextMetadata"],h),n}function _v(t,e){let n={},i=s(t,["citationSources"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(r=>r)),l(n,["citations"],o)}return n}function yv(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(e,["contents"]);if(r!=null){let a=Le(r);Array.isArray(a)&&(a=a.map(u=>vn(u))),l(i,["contents"],a)}return i}function Ev(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["tokensInfo"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>a)),l(n,["tokensInfo"],r)}return n}function vv(t,e){let n={},i=s(t,["enablePromptInjectionDetection"]);i!=null&&l(n,["enablePromptInjectionDetection"],i);let o=s(t,["environment"]);o!=null&&l(n,["environment"],o);let r=s(t,["excludedPredefinedFunctions"]);if(r!=null&&l(n,["excludedPredefinedFunctions"],r),s(t,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Tv(t,e){let n={},i=s(t,["values"]);i!=null&&l(n,["values"],i);let o=s(t,["statistics"]);return o!=null&&l(n,["statistics"],Av(o)),n}function Av(t,e){let n={},i=s(t,["truncated"]);i!=null&&l(n,["truncated"],i);let o=s(t,["token_count"]);o!=null&&l(n,["tokenCount"],o);let r=s(t,["tokensDetails"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(u=>u)),l(n,["tokensDetails"],a)}return n}function Fn(t,e){let n={},i=s(t,["parts"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>RT(a))),l(n,["parts"],r)}let o=s(t,["role"]);return o!=null&&l(n,["role"],o),n}function vn(t,e){let n={},i=s(t,["parts"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>PT(a))),l(n,["parts"],r)}let o=s(t,["role"]);return o!=null&&l(n,["role"],o),n}function Cv(t,e){let n={},i=s(t,["controlType"]);i!=null&&l(n,["controlType"],i);let o=s(t,["enableControlImageComputation"]);return o!=null&&l(n,["computeControl"],o),n}function Iv(t,e){let n={};if(s(t,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["tools"])!==void 0)throw new Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function Sv(t,e,n){let i={},o=s(t,["systemInstruction"]);e!==void 0&&o!=null&&l(e,["systemInstruction"],vn(Ne(o)));let r=s(t,["tools"]);if(e!==void 0&&r!=null){let u=r;Array.isArray(u)&&(u=u.map(c=>Rf(c))),l(e,["tools"],u)}let a=s(t,["generationConfig"]);return e!==void 0&&a!=null&&l(e,["generationConfig"],dT(a)),i}function wv(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(e,["contents"]);if(r!=null){let u=Le(r);Array.isArray(u)&&(u=u.map(c=>Fn(c))),l(i,["contents"],u)}let a=s(e,["config"]);return a!=null&&Iv(a),i}function Rv(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(e,["contents"]);if(r!=null){let u=Le(r);Array.isArray(u)&&(u=u.map(c=>vn(c))),l(i,["contents"],u)}let a=s(e,["config"]);return a!=null&&Sv(a,i),i}function Pv(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["totalTokens"]);o!=null&&l(n,["totalTokens"],o);let r=s(t,["cachedContentTokenCount"]);return r!=null&&l(n,["cachedContentTokenCount"],r),n}function Nv(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["totalTokens"]);return o!=null&&l(n,["totalTokens"],o),n}function kv(t,e,n){let i={},o=s(e,["model"]);return o!=null&&l(i,["_url","name"],re(t,o)),i}function Dv(t,e,n){let i={},o=s(e,["model"]);return o!=null&&l(i,["_url","name"],re(t,o)),i}function xv(t,e){let n={},i=s(t,["sdkHttpResponse"]);return i!=null&&l(n,["sdkHttpResponse"],i),n}function Mv(t,e){let n={},i=s(t,["sdkHttpResponse"]);return i!=null&&l(n,["sdkHttpResponse"],i),n}function Uv(t,e,n){let i={},o=s(t,["outputGcsUri"]);e!==void 0&&o!=null&&l(e,["parameters","storageUri"],o);let r=s(t,["negativePrompt"]);e!==void 0&&r!=null&&l(e,["parameters","negativePrompt"],r);let a=s(t,["numberOfImages"]);e!==void 0&&a!=null&&l(e,["parameters","sampleCount"],a);let u=s(t,["aspectRatio"]);e!==void 0&&u!=null&&l(e,["parameters","aspectRatio"],u);let c=s(t,["guidanceScale"]);e!==void 0&&c!=null&&l(e,["parameters","guidanceScale"],c);let d=s(t,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let f=s(t,["safetyFilterLevel"]);e!==void 0&&f!=null&&l(e,["parameters","safetySetting"],f);let p=s(t,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let h=s(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&l(e,["parameters","includeSafetyAttributes"],h);let m=s(t,["includeRaiReason"]);e!==void 0&&m!=null&&l(e,["parameters","includeRaiReason"],m);let _=s(t,["language"]);e!==void 0&&_!=null&&l(e,["parameters","language"],_);let g=s(t,["outputMimeType"]);e!==void 0&&g!=null&&l(e,["parameters","outputOptions","mimeType"],g);let v=s(t,["outputCompressionQuality"]);e!==void 0&&v!=null&&l(e,["parameters","outputOptions","compressionQuality"],v);let y=s(t,["addWatermark"]);e!==void 0&&y!=null&&l(e,["parameters","addWatermark"],y);let A=s(t,["labels"]);e!==void 0&&A!=null&&l(e,["labels"],A);let C=s(t,["editMode"]);e!==void 0&&C!=null&&l(e,["parameters","editMode"],C);let S=s(t,["baseSteps"]);return e!==void 0&&S!=null&&l(e,["parameters","editConfig","baseSteps"],S),i}function Gv(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(e,["prompt"]);r!=null&&l(i,["instances[0]","prompt"],r);let a=s(e,["referenceImages"]);if(a!=null){let c=a;Array.isArray(c)&&(c=c.map(d=>UT(d))),l(i,["instances[0]","referenceImages"],c)}let u=s(e,["config"]);return u!=null&&Uv(u,i),i}function Lv(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["predictions"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>lo(a))),l(n,["generatedImages"],r)}return n}function bv(t,e,n){let i={},o=s(t,["taskType"]);e!==void 0&&o!=null&&l(e,["requests[]","taskType"],o);let r=s(t,["title"]);e!==void 0&&r!=null&&l(e,["requests[]","title"],r);let a=s(t,["outputDimensionality"]);if(e!==void 0&&a!=null&&l(e,["requests[]","outputDimensionality"],a),s(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}function Ov(t,e,n){let i={},o=s(n,["embeddingApiType"]);if(o===void 0&&(o="PREDICT"),o==="PREDICT"){let p=s(t,["taskType"]);e!==void 0&&p!=null&&l(e,["instances[]","task_type"],p)}else if(o==="EMBED_CONTENT"){let p=s(t,["taskType"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","taskType"],p)}let r=s(n,["embeddingApiType"]);if(r===void 0&&(r="PREDICT"),r==="PREDICT"){let p=s(t,["title"]);e!==void 0&&p!=null&&l(e,["instances[]","title"],p)}else if(r==="EMBED_CONTENT"){let p=s(t,["title"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","title"],p)}let a=s(n,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="PREDICT"){let p=s(t,["outputDimensionality"]);e!==void 0&&p!=null&&l(e,["parameters","outputDimensionality"],p)}else if(a==="EMBED_CONTENT"){let p=s(t,["outputDimensionality"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","outputDimensionality"],p)}let u=s(n,["embeddingApiType"]);if(u===void 0&&(u="PREDICT"),u==="PREDICT"){let p=s(t,["mimeType"]);e!==void 0&&p!=null&&l(e,["instances[]","mimeType"],p)}let c=s(n,["embeddingApiType"]);if(c===void 0&&(c="PREDICT"),c==="PREDICT"){let p=s(t,["autoTruncate"]);e!==void 0&&p!=null&&l(e,["parameters","autoTruncate"],p)}else if(c==="EMBED_CONTENT"){let p=s(t,["autoTruncate"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","autoTruncate"],p)}let d=s(n,["embeddingApiType"]);if(d===void 0&&(d="PREDICT"),d==="EMBED_CONTENT"){let p=s(t,["documentOcr"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","documentOcr"],p)}let f=s(n,["embeddingApiType"]);if(f===void 0&&(f="PREDICT"),f==="EMBED_CONTENT"){let p=s(t,["audioTrackExtraction"]);e!==void 0&&p!=null&&l(e,["embedContentConfig","audioTrackExtraction"],p)}return i}function qv(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(e,["contents"]);if(r!=null){let d=Ka(t,r);Array.isArray(d)&&(d=d.map(f=>f)),l(i,["requests[]","content"],d)}let a=s(e,["content"]);a!=null&&Fn(Ne(a));let u=s(e,["config"]);u!=null&&bv(u,i);let c=s(e,["model"]);return c!==void 0&&l(i,["requests[]","model"],re(t,c)),i}function Fv(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(n,["embeddingApiType"]);if(r===void 0&&(r="PREDICT"),r==="PREDICT"){let c=s(e,["contents"]);if(c!=null){let d=Ka(t,c);Array.isArray(d)&&(d=d.map(f=>f)),l(i,["instances[]","content"],d)}}let a=s(n,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="EMBED_CONTENT"){let c=s(e,["content"]);c!=null&&l(i,["content"],vn(Ne(c)))}let u=s(e,["config"]);return u!=null&&Ov(u,i,n),i}function Hv(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["embeddings"]);if(o!=null){let a=o;Array.isArray(a)&&(a=a.map(u=>u)),l(n,["embeddings"],a)}let r=s(t,["metadata"]);return r!=null&&l(n,["metadata"],r),n}function Vv(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["predictions[]","embeddings"]);if(o!=null){let a=o;Array.isArray(a)&&(a=a.map(u=>Tv(u))),l(n,["embeddings"],a)}let r=s(t,["metadata"]);if(r!=null&&l(n,["metadata"],r),e&&s(e,["embeddingApiType"])==="EMBED_CONTENT"){let a=s(t,["embedding"]),u=s(t,["usageMetadata"]),c=s(t,["truncated"]);if(a){let d={};u&&u.promptTokenCount&&(d.tokenCount=u.promptTokenCount),u&&u.promptTokensDetails&&(d.tokensDetails=u.promptTokensDetails),c&&(d.truncated=c),a.statistics=d,l(n,["embeddings"],[a])}}return n}function Bv(t,e){let n={},i=s(t,["endpoint"]);i!=null&&l(n,["name"],i);let o=s(t,["deployedModelId"]);return o!=null&&l(n,["deployedModelId"],o),n}function $v(t,e){let n={};if(s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["fileUri"]);i!=null&&l(n,["fileUri"],i);let o=s(t,["mimeType"]);return o!=null&&l(n,["mimeType"],o),n}function Jv(t,e){let n={},i=s(t,["args"]);i!=null&&l(n,["args"],i);let o=s(t,["id"]);o!=null&&l(n,["id"],o);let r=s(t,["name"]);if(r!=null&&l(n,["name"],r),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function Xv(t,e){let n={},i=s(t,["allowedFunctionNames"]);i!=null&&l(n,["allowedFunctionNames"],i);let o=s(t,["mode"]);if(o!=null&&l(n,["mode"],o),s(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function Kv(t,e,n,i){let o={},r=s(e,["serviceTier"]);n!==void 0&&r!=null&&l(n,["serviceTier"],r);let a=s(e,["systemInstruction"]);n!==void 0&&a!=null&&l(n,["systemInstruction"],Fn(Ne(a)));let u=s(e,["temperature"]);u!=null&&l(o,["temperature"],u);let c=s(e,["topP"]);c!=null&&l(o,["topP"],c);let d=s(e,["topK"]);d!=null&&l(o,["topK"],d);let f=s(e,["candidateCount"]);f!=null&&l(o,["candidateCount"],f);let p=s(e,["maxOutputTokens"]);p!=null&&l(o,["maxOutputTokens"],p);let h=s(e,["stopSequences"]);h!=null&&l(o,["stopSequences"],h);let m=s(e,["responseLogprobs"]);m!=null&&l(o,["responseLogprobs"],m);let _=s(e,["logprobs"]);_!=null&&l(o,["logprobs"],_);let g=s(e,["presencePenalty"]);g!=null&&l(o,["presencePenalty"],g);let v=s(e,["frequencyPenalty"]);v!=null&&l(o,["frequencyPenalty"],v);let y=s(e,["seed"]);y!=null&&l(o,["seed"],y);let A=s(e,["responseMimeType"]);A!=null&&l(o,["responseMimeType"],A);let C=s(e,["responseSchema"]);C!=null&&l(o,["responseSchema"],Ya(C));let S=s(e,["responseJsonSchema"]);if(S!=null&&l(o,["responseJsonSchema"],S),s(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let R=s(e,["safetySettings"]);if(n!==void 0&&R!=null){let Z=R;Array.isArray(Z)&&(Z=Z.map(Ee=>LT(Ee))),l(n,["safetySettings"],Z)}let L=s(e,["tools"]);if(n!==void 0&&L!=null){let Z=yn(L);Array.isArray(Z)&&(Z=Z.map(Ee=>JT(_n(Ee)))),l(n,["tools"],Z)}let O=s(e,["toolConfig"]);if(n!==void 0&&O!=null&&l(n,["toolConfig"],BT(O)),s(e,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let H=s(e,["cachedContent"]);n!==void 0&&H!=null&&l(n,["cachedContent"],Tt(t,H));let U=s(e,["responseModalities"]);U!=null&&l(o,["responseModalities"],U);let F=s(e,["mediaResolution"]);F!=null&&l(o,["mediaResolution"],F);let J=s(e,["speechConfig"]);if(J!=null&&l(o,["speechConfig"],Wa(J)),s(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let Q=s(e,["thinkingConfig"]);Q!=null&&l(o,["thinkingConfig"],Q);let te=s(e,["audioTranscriptionConfig"]);te!=null&&l(o,["audioTranscriptionConfig"],te);let D=s(e,["imageConfig"]);D!=null&&l(o,["imageConfig"],gT(D));let K=s(e,["enableEnhancedCivicAnswers"]);if(K!=null&&l(o,["enableEnhancedCivicAnswers"],K),s(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return o}function Yv(t,e,n,i){let o={},r=s(e,["serviceTier"]);n!==void 0&&r!=null&&l(n,["serviceTier"],r);let a=s(e,["systemInstruction"]);n!==void 0&&a!=null&&l(n,["systemInstruction"],vn(Ne(a)));let u=s(e,["temperature"]);u!=null&&l(o,["temperature"],u);let c=s(e,["topP"]);c!=null&&l(o,["topP"],c);let d=s(e,["topK"]);d!=null&&l(o,["topK"],d);let f=s(e,["candidateCount"]);f!=null&&l(o,["candidateCount"],f);let p=s(e,["maxOutputTokens"]);p!=null&&l(o,["maxOutputTokens"],p);let h=s(e,["stopSequences"]);h!=null&&l(o,["stopSequences"],h);let m=s(e,["responseLogprobs"]);m!=null&&l(o,["responseLogprobs"],m);let _=s(e,["logprobs"]);_!=null&&l(o,["logprobs"],_);let g=s(e,["presencePenalty"]);g!=null&&l(o,["presencePenalty"],g);let v=s(e,["frequencyPenalty"]);v!=null&&l(o,["frequencyPenalty"],v);let y=s(e,["seed"]);y!=null&&l(o,["seed"],y);let A=s(e,["responseMimeType"]);A!=null&&l(o,["responseMimeType"],A);let C=s(e,["responseSchema"]);C!=null&&l(o,["responseSchema"],Ya(C));let S=s(e,["responseJsonSchema"]);S!=null&&l(o,["responseJsonSchema"],S);let R=s(e,["routingConfig"]);R!=null&&l(o,["routingConfig"],R);let L=s(e,["modelSelectionConfig"]);L!=null&&l(o,["modelConfig"],L);let O=s(e,["safetySettings"]);if(n!==void 0&&O!=null){let Pe=O;Array.isArray(Pe)&&(Pe=Pe.map(Oe=>Oe)),l(n,["safetySettings"],Pe)}let H=s(e,["tools"]);if(n!==void 0&&H!=null){let Pe=yn(H);Array.isArray(Pe)&&(Pe=Pe.map(Oe=>Rf(_n(Oe)))),l(n,["tools"],Pe)}let U=s(e,["toolConfig"]);n!==void 0&&U!=null&&l(n,["toolConfig"],$T(U));let F=s(e,["labels"]);n!==void 0&&F!=null&&l(n,["labels"],F);let J=s(e,["cachedContent"]);n!==void 0&&J!=null&&l(n,["cachedContent"],Tt(t,J));let Q=s(e,["responseModalities"]);Q!=null&&l(o,["responseModalities"],Q);let te=s(e,["mediaResolution"]);te!=null&&l(o,["mediaResolution"],te);let D=s(e,["speechConfig"]);D!=null&&l(o,["speechConfig"],wf(Wa(D)));let K=s(e,["audioTimestamp"]);K!=null&&l(o,["audioTimestamp"],K);let Z=s(e,["thinkingConfig"]);Z!=null&&l(o,["thinkingConfig"],Z);let Ee=s(e,["audioTranscriptionConfig"]);Ee!=null&&l(o,["audioTranscriptionConfig"],Ee);let Re=s(e,["imageConfig"]);if(Re!=null&&l(o,["imageConfig"],_T(Re)),s(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let Te=s(e,["modelArmorConfig"]);return n!==void 0&&Te!=null&&l(n,["modelArmorConfig"],Te),o}function Dd(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(e,["contents"]);if(r!=null){let u=Le(r);Array.isArray(u)&&(u=u.map(c=>Fn(c))),l(i,["contents"],u)}let a=s(e,["config"]);return a!=null&&l(i,["generationConfig"],Kv(t,a,i)),i}function xd(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(e,["contents"]);if(r!=null){let u=Le(r);Array.isArray(u)&&(u=u.map(c=>vn(c))),l(i,["contents"],u)}let a=s(e,["config"]);return a!=null&&l(i,["generationConfig"],Yv(t,a,i)),i}function Md(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["candidates"]);if(o!=null){let f=o;Array.isArray(f)&&(f=f.map(p=>gv(p))),l(n,["candidates"],f)}let r=s(t,["modelVersion"]);r!=null&&l(n,["modelVersion"],r);let a=s(t,["promptFeedback"]);a!=null&&l(n,["promptFeedback"],a);let u=s(t,["responseId"]);u!=null&&l(n,["responseId"],u);let c=s(t,["usageMetadata"]);c!=null&&l(n,["usageMetadata"],c);let d=s(t,["modelStatus"]);return d!=null&&l(n,["modelStatus"],d),n}function Ud(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["candidates"]);if(o!=null){let f=o;Array.isArray(f)&&(f=f.map(p=>p)),l(n,["candidates"],f)}let r=s(t,["createTime"]);r!=null&&l(n,["createTime"],r);let a=s(t,["modelVersion"]);a!=null&&l(n,["modelVersion"],a);let u=s(t,["promptFeedback"]);u!=null&&l(n,["promptFeedback"],u);let c=s(t,["responseId"]);c!=null&&l(n,["responseId"],c);let d=s(t,["usageMetadata"]);return d!=null&&l(n,["usageMetadata"],d),n}function Wv(t,e,n){let i={},o=s(t,["outputGcsUri"]);e!==void 0&&o!=null&&l(e,["parameters","storageUri"],o);let r=s(t,["negativePrompt"]);e!==void 0&&r!=null&&l(e,["parameters","negativePrompt"],r);let a=s(t,["numberOfImages"]);e!==void 0&&a!=null&&l(e,["parameters","sampleCount"],a);let u=s(t,["aspectRatio"]);e!==void 0&&u!=null&&l(e,["parameters","aspectRatio"],u);let c=s(t,["guidanceScale"]);e!==void 0&&c!=null&&l(e,["parameters","guidanceScale"],c);let d=s(t,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let f=s(t,["safetyFilterLevel"]);e!==void 0&&f!=null&&l(e,["parameters","safetySetting"],f);let p=s(t,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let h=s(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&l(e,["parameters","includeSafetyAttributes"],h);let m=s(t,["includeRaiReason"]);e!==void 0&&m!=null&&l(e,["parameters","includeRaiReason"],m);let _=s(t,["language"]);e!==void 0&&_!=null&&l(e,["parameters","language"],_);let g=s(t,["outputMimeType"]);e!==void 0&&g!=null&&l(e,["parameters","outputOptions","mimeType"],g);let v=s(t,["outputCompressionQuality"]);e!==void 0&&v!=null&&l(e,["parameters","outputOptions","compressionQuality"],v);let y=s(t,["addWatermark"]);e!==void 0&&y!=null&&l(e,["parameters","addWatermark"],y);let A=s(t,["labels"]);e!==void 0&&A!=null&&l(e,["labels"],A);let C=s(t,["imageSize"]);e!==void 0&&C!=null&&l(e,["parameters","sampleImageSize"],C);let S=s(t,["enhancePrompt"]);return e!==void 0&&S!=null&&l(e,["parameters","enhancePrompt"],S),i}function zv(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(e,["prompt"]);r!=null&&l(i,["instances[0]","prompt"],r);let a=s(e,["config"]);return a!=null&&Wv(a,i),i}function Qv(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["predictions"]);if(o!=null){let a=o;Array.isArray(a)&&(a=a.map(u=>lo(u))),l(n,["generatedImages"],a)}let r=s(t,["positivePromptSafetyAttributes"]);return r!=null&&l(n,["positivePromptSafetyAttributes"],Sf(r)),n}function Zv(t,e,n){let i={},o=s(t,["numberOfVideos"]);if(e!==void 0&&o!=null&&l(e,["parameters","sampleCount"],o),s(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["fps"])!==void 0)throw new Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["durationSeconds"]);if(e!==void 0&&r!=null&&l(e,["parameters","durationSeconds"],r),s(t,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["aspectRatio"]);e!==void 0&&a!=null&&l(e,["parameters","aspectRatio"],a);let u=s(t,["resolution"]);e!==void 0&&u!=null&&l(e,["parameters","resolution"],u);let c=s(t,["personGeneration"]);if(e!==void 0&&c!=null&&l(e,["parameters","personGeneration"],c),s(t,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["negativePrompt"]);e!==void 0&&d!=null&&l(e,["parameters","negativePrompt"],d);let f=s(t,["enhancePrompt"]);if(e!==void 0&&f!=null&&l(e,["parameters","enhancePrompt"],f),s(t,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let p=s(t,["lastFrame"]);e!==void 0&&p!=null&&l(e,["instances[0]","lastFrame"],uo(p));let h=s(t,["referenceImages"]);if(e!==void 0&&h!=null){let _=h;Array.isArray(_)&&(_=_.map(g=>oA(g))),l(e,["instances[0]","referenceImages"],_)}if(s(t,["mask"])!==void 0)throw new Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let m=s(t,["webhookConfig"]);if(e!==void 0&&m!=null&&l(e,["webhookConfig"],m),s(t,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}function jv(t,e,n){let i={},o=s(t,["numberOfVideos"]);e!==void 0&&o!=null&&l(e,["parameters","sampleCount"],o);let r=s(t,["outputGcsUri"]);e!==void 0&&r!=null&&l(e,["parameters","storageUri"],r);let a=s(t,["fps"]);e!==void 0&&a!=null&&l(e,["parameters","fps"],a);let u=s(t,["durationSeconds"]);e!==void 0&&u!=null&&l(e,["parameters","durationSeconds"],u);let c=s(t,["seed"]);e!==void 0&&c!=null&&l(e,["parameters","seed"],c);let d=s(t,["aspectRatio"]);e!==void 0&&d!=null&&l(e,["parameters","aspectRatio"],d);let f=s(t,["resolution"]);e!==void 0&&f!=null&&l(e,["parameters","resolution"],f);let p=s(t,["personGeneration"]);e!==void 0&&p!=null&&l(e,["parameters","personGeneration"],p);let h=s(t,["pubsubTopic"]);e!==void 0&&h!=null&&l(e,["parameters","pubsubTopic"],h);let m=s(t,["negativePrompt"]);e!==void 0&&m!=null&&l(e,["parameters","negativePrompt"],m);let _=s(t,["enhancePrompt"]);e!==void 0&&_!=null&&l(e,["parameters","enhancePrompt"],_);let g=s(t,["generateAudio"]);e!==void 0&&g!=null&&l(e,["parameters","generateAudio"],g);let v=s(t,["lastFrame"]);e!==void 0&&v!=null&&l(e,["instances[0]","lastFrame"],ot(v));let y=s(t,["referenceImages"]);if(e!==void 0&&y!=null){let L=y;Array.isArray(L)&&(L=L.map(O=>rA(O))),l(e,["instances[0]","referenceImages"],L)}let A=s(t,["mask"]);e!==void 0&&A!=null&&l(e,["instances[0]","mask"],iA(A));let C=s(t,["compressionQuality"]);e!==void 0&&C!=null&&l(e,["parameters","compressionQuality"],C);let S=s(t,["labels"]);if(e!==void 0&&S!=null&&l(e,["labels"],S),s(t,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let R=s(t,["resizeMode"]);return e!==void 0&&R!=null&&l(e,["parameters","resizeMode"],R),i}function eT(t,e){let n={},i=s(t,["name"]);i!=null&&l(n,["name"],i);let o=s(t,["metadata"]);o!=null&&l(n,["metadata"],o);let r=s(t,["done"]);r!=null&&l(n,["done"],r);let a=s(t,["error"]);a!=null&&l(n,["error"],a);let u=s(t,["response","generateVideoResponse"]);return u!=null&&l(n,["response"],oT(u)),n}function tT(t,e){let n={},i=s(t,["name"]);i!=null&&l(n,["name"],i);let o=s(t,["metadata"]);o!=null&&l(n,["metadata"],o);let r=s(t,["done"]);r!=null&&l(n,["done"],r);let a=s(t,["error"]);a!=null&&l(n,["error"],a);let u=s(t,["response"]);return u!=null&&l(n,["response"],rT(u)),n}function nT(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(e,["prompt"]);r!=null&&l(i,["instances[0]","prompt"],r);let a=s(e,["image"]);a!=null&&l(i,["instances[0]","image"],uo(a));let u=s(e,["video"]);u!=null&&l(i,["instances[0]","video"],Pf(u));let c=s(e,["source"]);c!=null&&sT(c,i);let d=s(e,["config"]);return d!=null&&Zv(d,i),i}function iT(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(e,["prompt"]);r!=null&&l(i,["instances[0]","prompt"],r);let a=s(e,["image"]);a!=null&&l(i,["instances[0]","image"],ot(a));let u=s(e,["video"]);u!=null&&l(i,["instances[0]","video"],Nf(u));let c=s(e,["source"]);c!=null&&aT(c,i);let d=s(e,["config"]);return d!=null&&jv(d,i),i}function oT(t,e){let n={},i=s(t,["generatedSamples"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>uT(u))),l(n,["generatedVideos"],a)}let o=s(t,["raiMediaFilteredCount"]);o!=null&&l(n,["raiMediaFilteredCount"],o);let r=s(t,["raiMediaFilteredReasons"]);return r!=null&&l(n,["raiMediaFilteredReasons"],r),n}function rT(t,e){let n={},i=s(t,["videos"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(u=>cT(u))),l(n,["generatedVideos"],a)}let o=s(t,["raiMediaFilteredCount"]);o!=null&&l(n,["raiMediaFilteredCount"],o);let r=s(t,["raiMediaFilteredReasons"]);return r!=null&&l(n,["raiMediaFilteredReasons"],r),n}function sT(t,e,n){let i={},o=s(t,["prompt"]);e!==void 0&&o!=null&&l(e,["instances[0]","prompt"],o);let r=s(t,["image"]);e!==void 0&&r!=null&&l(e,["instances[0]","image"],uo(r));let a=s(t,["video"]);return e!==void 0&&a!=null&&l(e,["instances[0]","video"],Pf(a)),i}function aT(t,e,n){let i={},o=s(t,["prompt"]);e!==void 0&&o!=null&&l(e,["instances[0]","prompt"],o);let r=s(t,["image"]);e!==void 0&&r!=null&&l(e,["instances[0]","image"],ot(r));let a=s(t,["video"]);return e!==void 0&&a!=null&&l(e,["instances[0]","video"],Nf(a)),i}function lo(t,e){let n={},i=s(t,["_self"]);i!=null&&l(n,["image"],If(i));let o=s(t,["raiFilteredReason"]);o!=null&&l(n,["raiFilteredReason"],o);let r=s(t,["_self"]);r!=null&&l(n,["safetyAttributes"],Sf(r));let a=s(t,["prompt"]);return a!=null&&l(n,["enhancedPrompt"],a),n}function lT(t,e){let n={},i=s(t,["_self"]);i!=null&&l(n,["mask"],If(i));let o=s(t,["labels"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>a)),l(n,["labels"],r)}return n}function uT(t,e){let n={},i=s(t,["video"]);return i!=null&&l(n,["video"],tA(i)),n}function cT(t,e){let n={},i=s(t,["_self"]);return i!=null&&l(n,["video"],nA(i)),n}function dT(t,e){let n={},i=s(t,["modelSelectionConfig"]);i!=null&&l(n,["modelConfig"],i);let o=s(t,["responseJsonSchema"]);o!=null&&l(n,["responseJsonSchema"],o);let r=s(t,["audioTranscriptionConfig"]);r!=null&&l(n,["audioTranscriptionConfig"],r);let a=s(t,["audioTimestamp"]);a!=null&&l(n,["audioTimestamp"],a);let u=s(t,["candidateCount"]);u!=null&&l(n,["candidateCount"],u);let c=s(t,["enableAffectiveDialog"]);c!=null&&l(n,["enableAffectiveDialog"],c);let d=s(t,["frequencyPenalty"]);d!=null&&l(n,["frequencyPenalty"],d);let f=s(t,["logprobs"]);f!=null&&l(n,["logprobs"],f);let p=s(t,["maxOutputTokens"]);p!=null&&l(n,["maxOutputTokens"],p);let h=s(t,["mediaResolution"]);h!=null&&l(n,["mediaResolution"],h);let m=s(t,["presencePenalty"]);m!=null&&l(n,["presencePenalty"],m);let _=s(t,["responseFormat"]);if(_!=null){let J=_;Array.isArray(J)&&(J=J.map(Q=>Q)),l(n,["responseFormat"],J)}let g=s(t,["responseLogprobs"]);g!=null&&l(n,["responseLogprobs"],g);let v=s(t,["responseMimeType"]);v!=null&&l(n,["responseMimeType"],v);let y=s(t,["responseModalities"]);y!=null&&l(n,["responseModalities"],y);let A=s(t,["responseSchema"]);A!=null&&l(n,["responseSchema"],A);let C=s(t,["routingConfig"]);C!=null&&l(n,["routingConfig"],C);let S=s(t,["seed"]);S!=null&&l(n,["seed"],S);let R=s(t,["speechConfig"]);R!=null&&l(n,["speechConfig"],wf(R));let L=s(t,["stopSequences"]);L!=null&&l(n,["stopSequences"],L);let O=s(t,["temperature"]);O!=null&&l(n,["temperature"],O);let H=s(t,["thinkingConfig"]);H!=null&&l(n,["thinkingConfig"],H);let U=s(t,["topK"]);U!=null&&l(n,["topK"],U);let F=s(t,["topP"]);if(F!=null&&l(n,["topP"],F),s(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function fT(t,e,n){let i={},o=s(e,["model"]);return o!=null&&l(i,["_url","name"],re(t,o)),i}function pT(t,e,n){let i={},o=s(e,["model"]);return o!=null&&l(i,["_url","name"],re(t,o)),i}function hT(t,e){let n={},i=s(t,["authConfig"]);i!=null&&l(n,["authConfig"],hv(i));let o=s(t,["enableWidget"]);if(o!=null&&l(n,["enableWidget"],o),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function mT(t,e){let n={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["searchTypes"]);i!=null&&l(n,["searchTypes"],i);let o=s(t,["timeRangeFilter"]);return o!=null&&l(n,["timeRangeFilter"],o),n}function gT(t,e){let n={},i=s(t,["aspectRatio"]);i!=null&&l(n,["aspectRatio"],i);let o=s(t,["imageSize"]);if(o!=null&&l(n,["imageSize"],o),s(t,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function _T(t,e){let n={},i=s(t,["aspectRatio"]);i!=null&&l(n,["aspectRatio"],i);let o=s(t,["imageSize"]);o!=null&&l(n,["imageSize"],o);let r=s(t,["personGeneration"]);r!=null&&l(n,["personGeneration"],r);let a=s(t,["outputMimeType"]);a!=null&&l(n,["imageOutputOptions","mimeType"],a);let u=s(t,["outputCompressionQuality"]);u!=null&&l(n,["imageOutputOptions","compressionQuality"],u);let c=s(t,["imageOutputOptions"]);c!=null&&l(n,["imageOutputOptions"],c);let d=s(t,["prominentPeople"]);return d!=null&&l(n,["prominentPeople"],d),n}function If(t,e){let n={},i=s(t,["gcsUri"]);i!=null&&l(n,["gcsUri"],i);let o=s(t,["bytesBase64Encoded"]);o!=null&&l(n,["imageBytes"],Jt(o));let r=s(t,["mimeType"]);return r!=null&&l(n,["mimeType"],r),n}function uo(t,e){let n={};if(s(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["imageBytes"]);i!=null&&l(n,["bytesBase64Encoded"],Jt(i));let o=s(t,["mimeType"]);return o!=null&&l(n,["mimeType"],o),n}function ot(t,e){let n={},i=s(t,["gcsUri"]);i!=null&&l(n,["gcsUri"],i);let o=s(t,["imageBytes"]);o!=null&&l(n,["bytesBase64Encoded"],Jt(o));let r=s(t,["mimeType"]);return r!=null&&l(n,["mimeType"],r),n}function yT(t,e,n,i){let o={},r=s(e,["pageSize"]);n!==void 0&&r!=null&&l(n,["_query","pageSize"],r);let a=s(e,["pageToken"]);n!==void 0&&a!=null&&l(n,["_query","pageToken"],a);let u=s(e,["filter"]);n!==void 0&&u!=null&&l(n,["_query","filter"],u);let c=s(e,["queryBase"]);return n!==void 0&&c!=null&&l(n,["_url","models_url"],mf(t,c)),o}function ET(t,e,n,i){let o={},r=s(e,["pageSize"]);n!==void 0&&r!=null&&l(n,["_query","pageSize"],r);let a=s(e,["pageToken"]);n!==void 0&&a!=null&&l(n,["_query","pageToken"],a);let u=s(e,["filter"]);n!==void 0&&u!=null&&l(n,["_query","filter"],u);let c=s(e,["queryBase"]);return n!==void 0&&c!=null&&l(n,["_url","models_url"],mf(t,c)),o}function vT(t,e,n){let i={},o=s(e,["config"]);return o!=null&&yT(t,o,i),i}function TT(t,e,n){let i={},o=s(e,["config"]);return o!=null&&ET(t,o,i),i}function AT(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["nextPageToken"]);o!=null&&l(n,["nextPageToken"],o);let r=s(t,["_self"]);if(r!=null){let a=gf(r);Array.isArray(a)&&(a=a.map(u=>Hs(u))),l(n,["models"],a)}return n}function CT(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["nextPageToken"]);o!=null&&l(n,["nextPageToken"],o);let r=s(t,["_self"]);if(r!=null){let a=gf(r);Array.isArray(a)&&(a=a.map(u=>Vs(u))),l(n,["models"],a)}return n}function IT(t,e){let n={},i=s(t,["maskMode"]);i!=null&&l(n,["maskMode"],i);let o=s(t,["segmentationClasses"]);o!=null&&l(n,["maskClasses"],o);let r=s(t,["maskDilation"]);return r!=null&&l(n,["dilation"],r),n}function ST(t,e){let n={};if(s(t,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Hs(t,e){let n={},i=s(t,["name"]);i!=null&&l(n,["name"],i);let o=s(t,["displayName"]);o!=null&&l(n,["displayName"],o);let r=s(t,["description"]);r!=null&&l(n,["description"],r);let a=s(t,["version"]);a!=null&&l(n,["version"],a);let u=s(t,["_self"]);u!=null&&l(n,["tunedModelInfo"],XT(u));let c=s(t,["inputTokenLimit"]);c!=null&&l(n,["inputTokenLimit"],c);let d=s(t,["outputTokenLimit"]);d!=null&&l(n,["outputTokenLimit"],d);let f=s(t,["supportedGenerationMethods"]);f!=null&&l(n,["supportedActions"],f);let p=s(t,["temperature"]);p!=null&&l(n,["temperature"],p);let h=s(t,["maxTemperature"]);h!=null&&l(n,["maxTemperature"],h);let m=s(t,["topP"]);m!=null&&l(n,["topP"],m);let _=s(t,["topK"]);_!=null&&l(n,["topK"],_);let g=s(t,["thinking"]);return g!=null&&l(n,["thinking"],g),n}function Vs(t,e){let n={},i=s(t,["name"]);i!=null&&l(n,["name"],i);let o=s(t,["displayName"]);o!=null&&l(n,["displayName"],o);let r=s(t,["description"]);r!=null&&l(n,["description"],r);let a=s(t,["versionId"]);a!=null&&l(n,["version"],a);let u=s(t,["deployedModels"]);if(u!=null){let h=u;Array.isArray(h)&&(h=h.map(m=>Bv(m))),l(n,["endpoints"],h)}let c=s(t,["labels"]);c!=null&&l(n,["labels"],c);let d=s(t,["_self"]);d!=null&&l(n,["tunedModelInfo"],KT(d));let f=s(t,["defaultCheckpointId"]);f!=null&&l(n,["defaultCheckpointId"],f);let p=s(t,["checkpoints"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(m=>m)),l(n,["checkpoints"],h)}return n}function wT(t,e){let n={},i=s(t,["speakerVoiceConfigs"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(r=>VT(r))),l(n,["speakerVoiceConfigs"],o)}return n}function RT(t,e){let n={},i=s(t,["mediaResolution"]);i!=null&&l(n,["mediaResolution"],i);let o=s(t,["toolCall"]);o!=null&&l(n,["toolCall"],o);let r=s(t,["toolResponse"]);r!=null&&l(n,["toolResponse"],r);let a=s(t,["audioTranscription"]);a!=null&&l(n,["audioTranscription"],a);let u=s(t,["codeExecutionResult"]);u!=null&&l(n,["codeExecutionResult"],u);let c=s(t,["executableCode"]);c!=null&&l(n,["executableCode"],c);let d=s(t,["fileData"]);d!=null&&l(n,["fileData"],$v(d));let f=s(t,["functionCall"]);f!=null&&l(n,["functionCall"],Jv(f));let p=s(t,["functionResponse"]);p!=null&&l(n,["functionResponse"],p);let h=s(t,["inlineData"]);h!=null&&l(n,["inlineData"],mv(h));let m=s(t,["text"]);m!=null&&l(n,["text"],m);let _=s(t,["thought"]);_!=null&&l(n,["thought"],_);let g=s(t,["thoughtSignature"]);g!=null&&l(n,["thoughtSignature"],g);let v=s(t,["videoMetadata"]);v!=null&&l(n,["videoMetadata"],v);let y=s(t,["partMetadata"]);y!=null&&l(n,["partMetadata"],y);let A=s(t,["mediaProcessing"]);return A!=null&&l(n,["mediaProcessing"],A),n}function PT(t,e){let n={},i=s(t,["mediaResolution"]);if(i!=null&&l(n,["mediaResolution"],i),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let o=s(t,["audioTranscription"]);o!=null&&l(n,["audioTranscription"],o);let r=s(t,["codeExecutionResult"]);r!=null&&l(n,["codeExecutionResult"],r);let a=s(t,["executableCode"]);a!=null&&l(n,["executableCode"],a);let u=s(t,["fileData"]);u!=null&&l(n,["fileData"],u);let c=s(t,["functionCall"]);c!=null&&l(n,["functionCall"],c);let d=s(t,["functionResponse"]);d!=null&&l(n,["functionResponse"],d);let f=s(t,["inlineData"]);f!=null&&l(n,["inlineData"],f);let p=s(t,["text"]);p!=null&&l(n,["text"],p);let h=s(t,["thought"]);h!=null&&l(n,["thought"],h);let m=s(t,["thoughtSignature"]);m!=null&&l(n,["thoughtSignature"],m);let _=s(t,["videoMetadata"]);if(_!=null&&l(n,["videoMetadata"],_),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let g=s(t,["mediaProcessing"]);return g!=null&&l(n,["mediaProcessing"],g),n}function NT(t,e){let n={},i=s(t,["productImage"]);return i!=null&&l(n,["image"],ot(i)),n}function kT(t,e,n){let i={},o=s(t,["numberOfImages"]);e!==void 0&&o!=null&&l(e,["parameters","sampleCount"],o);let r=s(t,["baseSteps"]);e!==void 0&&r!=null&&l(e,["parameters","baseSteps"],r);let a=s(t,["outputGcsUri"]);e!==void 0&&a!=null&&l(e,["parameters","storageUri"],a);let u=s(t,["seed"]);e!==void 0&&u!=null&&l(e,["parameters","seed"],u);let c=s(t,["safetyFilterLevel"]);e!==void 0&&c!=null&&l(e,["parameters","safetySetting"],c);let d=s(t,["personGeneration"]);e!==void 0&&d!=null&&l(e,["parameters","personGeneration"],d);let f=s(t,["addWatermark"]);e!==void 0&&f!=null&&l(e,["parameters","addWatermark"],f);let p=s(t,["outputMimeType"]);e!==void 0&&p!=null&&l(e,["parameters","outputOptions","mimeType"],p);let h=s(t,["outputCompressionQuality"]);e!==void 0&&h!=null&&l(e,["parameters","outputOptions","compressionQuality"],h);let m=s(t,["enhancePrompt"]);e!==void 0&&m!=null&&l(e,["parameters","enhancePrompt"],m);let _=s(t,["labels"]);return e!==void 0&&_!=null&&l(e,["labels"],_),i}function DT(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(e,["source"]);r!=null&&MT(r,i);let a=s(e,["config"]);return a!=null&&kT(a,i),i}function xT(t,e){let n={},i=s(t,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(r=>lo(r))),l(n,["generatedImages"],o)}return n}function MT(t,e,n){let i={},o=s(t,["prompt"]);e!==void 0&&o!=null&&l(e,["instances[0]","prompt"],o);let r=s(t,["personImage"]);e!==void 0&&r!=null&&l(e,["instances[0]","personImage","image"],ot(r));let a=s(t,["productImages"]);if(e!==void 0&&a!=null){let u=a;Array.isArray(u)&&(u=u.map(c=>NT(c))),l(e,["instances[0]","productImages"],u)}return i}function UT(t,e){let n={},i=s(t,["referenceImage"]);i!=null&&l(n,["referenceImage"],ot(i));let o=s(t,["referenceId"]);o!=null&&l(n,["referenceId"],o);let r=s(t,["referenceType"]);r!=null&&l(n,["referenceType"],r);let a=s(t,["maskImageConfig"]);a!=null&&l(n,["maskImageConfig"],IT(a));let u=s(t,["controlImageConfig"]);u!=null&&l(n,["controlImageConfig"],Cv(u));let c=s(t,["styleImageConfig"]);c!=null&&l(n,["styleImageConfig"],c);let d=s(t,["subjectImageConfig"]);return d!=null&&l(n,["subjectImageConfig"],d),n}function GT(t,e){let n={},i=s(t,["mimeType"]);i!=null&&l(n,["mimeType"],i);let o=s(t,["voiceSampleAudio"]);if(o!=null&&l(n,["voiceSampleAudio"],o),s(t,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function Sf(t,e){let n={},i=s(t,["safetyAttributes","categories"]);i!=null&&l(n,["categories"],i);let o=s(t,["safetyAttributes","scores"]);o!=null&&l(n,["scores"],o);let r=s(t,["contentType"]);return r!=null&&l(n,["contentType"],r),n}function LT(t,e){let n={},i=s(t,["category"]);if(i!=null&&l(n,["category"],i),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(t,["threshold"]);return o!=null&&l(n,["threshold"],o),n}function bT(t,e){let n={},i=s(t,["image"]);return i!=null&&l(n,["image"],ot(i)),n}function OT(t,e,n){let i={},o=s(t,["mode"]);e!==void 0&&o!=null&&l(e,["parameters","mode"],o);let r=s(t,["maxPredictions"]);e!==void 0&&r!=null&&l(e,["parameters","maxPredictions"],r);let a=s(t,["confidenceThreshold"]);e!==void 0&&a!=null&&l(e,["parameters","confidenceThreshold"],a);let u=s(t,["maskDilation"]);e!==void 0&&u!=null&&l(e,["parameters","maskDilation"],u);let c=s(t,["binaryColorThreshold"]);e!==void 0&&c!=null&&l(e,["parameters","binaryColorThreshold"],c);let d=s(t,["labels"]);return e!==void 0&&d!=null&&l(e,["labels"],d),i}function qT(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(e,["source"]);r!=null&&HT(r,i);let a=s(e,["config"]);return a!=null&&OT(a,i),i}function FT(t,e){let n={},i=s(t,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(r=>lT(r))),l(n,["generatedMasks"],o)}return n}function HT(t,e,n){let i={},o=s(t,["prompt"]);e!==void 0&&o!=null&&l(e,["instances[0]","prompt"],o);let r=s(t,["image"]);e!==void 0&&r!=null&&l(e,["instances[0]","image"],ot(r));let a=s(t,["scribbleImage"]);return e!==void 0&&a!=null&&l(e,["instances[0]","scribble"],bT(a)),i}function VT(t,e){let n={},i=s(t,["speaker"]);i!=null&&l(n,["speaker"],i);let o=s(t,["voiceConfig"]);return o!=null&&l(n,["voiceConfig"],kf(o)),n}function wf(t,e){let n={},i=s(t,["voiceConfig"]);i!=null&&l(n,["voiceConfig"],kf(i));let o=s(t,["languageCode"]);o!=null&&l(n,["languageCode"],o);let r=s(t,["multiSpeakerVoiceConfig"]);return r!=null&&l(n,["multiSpeakerVoiceConfig"],wT(r)),n}function BT(t,e){let n={},i=s(t,["functionCallingConfig"]);i!=null&&l(n,["functionCallingConfig"],Xv(i));let o=s(t,["retrievalConfig"]);o!=null&&l(n,["retrievalConfig"],o);let r=s(t,["includeServerSideToolInvocations"]);return r!=null&&l(n,["includeServerSideToolInvocations"],r),n}function $T(t,e){let n={},i=s(t,["functionCallingConfig"]);i!=null&&l(n,["functionCallingConfig"],i);let o=s(t,["retrievalConfig"]);if(o!=null&&l(n,["retrievalConfig"],o),s(t,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function JT(t,e){let n={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["googleMaps"]);i!=null&&l(n,["googleMaps"],hT(i));let o=s(t,["mcpServers"]);if(o!=null){let h=o;Array.isArray(h)&&(h=h.map(m=>m)),l(n,["mcpServers"],h)}let r=s(t,["codeExecution"]);r!=null&&l(n,["codeExecution"],r);let a=s(t,["computerUse"]);if(a!=null&&l(n,["computerUse"],a),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let u=s(t,["functionDeclarations"]);if(u!=null){let h=u;Array.isArray(h)&&(h=h.map(m=>m)),l(n,["functionDeclarations"],h)}let c=s(t,["googleSearch"]);c!=null&&l(n,["googleSearch"],mT(c));let d=s(t,["googleSearchRetrieval"]);if(d!=null&&l(n,["googleSearchRetrieval"],d),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let f=s(t,["urlContext"]);f!=null&&l(n,["urlContext"],f);let p=s(t,["fileSearch"]);return p!=null&&l(n,["fileSearch"],p),n}function Rf(t,e){let n={},i=s(t,["retrieval"]);i!=null&&l(n,["retrieval"],i);let o=s(t,["googleMaps"]);o!=null&&l(n,["googleMaps"],o);let r=s(t,["mcpServers"]);if(r!=null){let g=r;Array.isArray(g)&&(g=g.map(v=>ST(v))),l(n,["mcpServers"],g)}let a=s(t,["codeExecution"]);a!=null&&l(n,["codeExecution"],a);let u=s(t,["computerUse"]);u!=null&&l(n,["computerUse"],vv(u));let c=s(t,["enterpriseWebSearch"]);c!=null&&l(n,["enterpriseWebSearch"],c);let d=s(t,["exaAiSearch"]);d!=null&&l(n,["exaAiSearch"],d);let f=s(t,["functionDeclarations"]);if(f!=null){let g=f;Array.isArray(g)&&(g=g.map(v=>v)),l(n,["functionDeclarations"],g)}let p=s(t,["googleSearch"]);p!=null&&l(n,["googleSearch"],p);let h=s(t,["googleSearchRetrieval"]);h!=null&&l(n,["googleSearchRetrieval"],h);let m=s(t,["parallelAiSearch"]);m!=null&&l(n,["parallelAiSearch"],m);let _=s(t,["urlContext"]);if(_!=null&&l(n,["urlContext"],_),s(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function XT(t,e){let n={},i=s(t,["baseModel"]);i!=null&&l(n,["baseModel"],i);let o=s(t,["createTime"]);o!=null&&l(n,["createTime"],o);let r=s(t,["updateTime"]);return r!=null&&l(n,["updateTime"],r),n}function KT(t,e){let n={},i=s(t,["labels","google-vertex-llm-tuning-base-model-id"]);i!=null&&l(n,["baseModel"],i);let o=s(t,["createTime"]);o!=null&&l(n,["createTime"],o);let r=s(t,["updateTime"]);return r!=null&&l(n,["updateTime"],r),n}function YT(t,e,n){let i={},o=s(t,["displayName"]);e!==void 0&&o!=null&&l(e,["displayName"],o);let r=s(t,["description"]);e!==void 0&&r!=null&&l(e,["description"],r);let a=s(t,["defaultCheckpointId"]);return e!==void 0&&a!=null&&l(e,["defaultCheckpointId"],a),i}function WT(t,e,n){let i={},o=s(t,["displayName"]);e!==void 0&&o!=null&&l(e,["displayName"],o);let r=s(t,["description"]);e!==void 0&&r!=null&&l(e,["description"],r);let a=s(t,["defaultCheckpointId"]);return e!==void 0&&a!=null&&l(e,["defaultCheckpointId"],a),i}function zT(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","name"],re(t,o));let r=s(e,["config"]);return r!=null&&YT(r,i),i}function QT(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(e,["config"]);return r!=null&&WT(r,i),i}function ZT(t,e,n){let i={},o=s(t,["outputGcsUri"]);e!==void 0&&o!=null&&l(e,["parameters","storageUri"],o);let r=s(t,["safetyFilterLevel"]);e!==void 0&&r!=null&&l(e,["parameters","safetySetting"],r);let a=s(t,["personGeneration"]);e!==void 0&&a!=null&&l(e,["parameters","personGeneration"],a);let u=s(t,["includeRaiReason"]);e!==void 0&&u!=null&&l(e,["parameters","includeRaiReason"],u);let c=s(t,["outputMimeType"]);e!==void 0&&c!=null&&l(e,["parameters","outputOptions","mimeType"],c);let d=s(t,["outputCompressionQuality"]);e!==void 0&&d!=null&&l(e,["parameters","outputOptions","compressionQuality"],d);let f=s(t,["enhanceInputImage"]);e!==void 0&&f!=null&&l(e,["parameters","upscaleConfig","enhanceInputImage"],f);let p=s(t,["imagePreservationFactor"]);e!==void 0&&p!=null&&l(e,["parameters","upscaleConfig","imagePreservationFactor"],p);let h=s(t,["labels"]);e!==void 0&&h!=null&&l(e,["labels"],h);let m=s(t,["numberOfImages"]);e!==void 0&&m!=null&&l(e,["parameters","sampleCount"],m);let _=s(t,["mode"]);return e!==void 0&&_!=null&&l(e,["parameters","mode"],_),i}function jT(t,e,n){let i={},o=s(e,["model"]);o!=null&&l(i,["_url","model"],re(t,o));let r=s(e,["image"]);r!=null&&l(i,["instances[0]","image"],ot(r));let a=s(e,["upscaleFactor"]);a!=null&&l(i,["parameters","upscaleConfig","upscaleFactor"],a);let u=s(e,["config"]);return u!=null&&ZT(u,i),i}function eA(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["predictions"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>lo(a))),l(n,["generatedImages"],r)}return n}function tA(t,e){let n={},i=s(t,["uri"]);i!=null&&l(n,["uri"],i);let o=s(t,["encodedVideo"]);o!=null&&l(n,["videoBytes"],Jt(o));let r=s(t,["encoding"]);return r!=null&&l(n,["mimeType"],r),n}function nA(t,e){let n={},i=s(t,["gcsUri"]);i!=null&&l(n,["uri"],i);let o=s(t,["bytesBase64Encoded"]);o!=null&&l(n,["videoBytes"],Jt(o));let r=s(t,["mimeType"]);return r!=null&&l(n,["mimeType"],r),n}function iA(t,e){let n={},i=s(t,["image"]);i!=null&&l(n,["_self"],ot(i));let o=s(t,["maskMode"]);return o!=null&&l(n,["maskMode"],o),n}function oA(t,e){let n={},i=s(t,["image"]);i!=null&&l(n,["image"],uo(i));let o=s(t,["referenceType"]);return o!=null&&l(n,["referenceType"],o),n}function rA(t,e){let n={},i=s(t,["image"]);i!=null&&l(n,["image"],ot(i));let o=s(t,["referenceType"]);return o!=null&&l(n,["referenceType"],o),n}function Pf(t,e){let n={},i=s(t,["uri"]);i!=null&&l(n,["uri"],i);let o=s(t,["videoBytes"]);o!=null&&l(n,["encodedVideo"],Jt(o));let r=s(t,["mimeType"]);return r!=null&&l(n,["encoding"],r),n}function Nf(t,e){let n={},i=s(t,["uri"]);i!=null&&l(n,["gcsUri"],i);let o=s(t,["videoBytes"]);o!=null&&l(n,["bytesBase64Encoded"],Jt(o));let r=s(t,["mimeType"]);return r!=null&&l(n,["mimeType"],r),n}function kf(t,e){let n={},i=s(t,["replicatedVoiceConfig"]);i!=null&&l(n,["replicatedVoiceConfig"],GT(i));let o=s(t,["prebuiltVoiceConfig"]);return o!=null&&l(n,["prebuiltVoiceConfig"],o),n}function sA(t,e,n){let i={},o=s(e,["displayName"]);n!==void 0&&o!=null&&l(n,["displayName"],o);let r=s(e,["embeddingModel"]);return n!==void 0&&r!=null&&l(n,["embeddingModel"],re(t,r)),i}function aA(t,e){let n={},i=s(e,["config"]);return i!=null&&sA(t,i,n),n}function lA(t,e){let n={},i=s(t,["force"]);return e!==void 0&&i!=null&&l(e,["_query","force"],i),n}function uA(t){let e={},n=s(t,["name"]);n!=null&&l(e,["_url","name"],n);let i=s(t,["config"]);return i!=null&&lA(i,e),e}function cA(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","name"],n),e}function dA(t,e){let n={},i=s(t,["customMetadata"]);if(e!==void 0&&i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["customMetadata"],r)}let o=s(t,["chunkingConfig"]);return e!==void 0&&o!=null&&l(e,["chunkingConfig"],o),n}function fA(t){let e={},n=s(t,["name"]);n!=null&&l(e,["name"],n);let i=s(t,["metadata"]);i!=null&&l(e,["metadata"],i);let o=s(t,["done"]);o!=null&&l(e,["done"],o);let r=s(t,["error"]);r!=null&&l(e,["error"],r);let a=s(t,["response"]);return a!=null&&l(e,["response"],hA(a)),e}function pA(t){let e={},n=s(t,["fileSearchStoreName"]);n!=null&&l(e,["_url","file_search_store_name"],n);let i=s(t,["fileName"]);i!=null&&l(e,["fileName"],i);let o=s(t,["config"]);return o!=null&&dA(o,e),e}function hA(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let i=s(t,["parent"]);i!=null&&l(e,["parent"],i);let o=s(t,["documentName"]);return o!=null&&l(e,["documentName"],o),e}function mA(t,e){let n={},i=s(t,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=s(t,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),n}function gA(t){let e={},n=s(t,["config"]);return n!=null&&mA(n,e),e}function _A(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let i=s(t,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=s(t,["fileSearchStores"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["fileSearchStores"],r)}return e}function Df(t,e){let n={},i=s(t,["mimeType"]);e!==void 0&&i!=null&&l(e,["mimeType"],i);let o=s(t,["displayName"]);e!==void 0&&o!=null&&l(e,["displayName"],o);let r=s(t,["customMetadata"]);if(e!==void 0&&r!=null){let u=r;Array.isArray(u)&&(u=u.map(c=>c)),l(e,["customMetadata"],u)}let a=s(t,["chunkingConfig"]);return e!==void 0&&a!=null&&l(e,["chunkingConfig"],a),n}function yA(t){let e={},n=s(t,["fileSearchStoreName"]);n!=null&&l(e,["_url","file_search_store_name"],n);let i=s(t,["config"]);return i!=null&&Df(i,e),e}function EA(t){let e={},n=s(t,["sdkHttpResponse"]);return n!=null&&l(e,["sdkHttpResponse"],n),e}var vA="Content-Type",TA="X-Server-Timeout",AA="User-Agent",Bs="x-goog-api-client",CA="2.21.0",IA=`google-genai-sdk/${CA}`,SA="v1beta1",wA="v1beta",RA=new Set(["us","eu"]);function PA(t){let n=globalThis[Symbol.for("undici.globalDispatcher.1")];if(n)for(let i of Object.getOwnPropertySymbols(n)){let o=i.description;if(o?.includes("headers timeout")||o?.includes("body timeout")){let r=n[i];typeof r=="number"&&(n[i]=Math.max(r,t))}}}function NA(t,e){let n=()=>{};if(!(t&&t>0)&&!e)return{signal:void 0,dispose:n};let i=new AbortController,o;t&&t>0&&(o=setTimeout(()=>i.abort(),t),o&&typeof o.unref=="function"&&o.unref());let r=()=>i.abort();return e&&(e.aborted?i.abort():e.addEventListener("abort",r)),{signal:i.signal,dispose:()=>{o!==void 0&&clearTimeout(o),e?.removeEventListener("abort",r)}}}var kA=5,DA=1,xA=60,MA=2,UA=1,GA=[408,429,500,502,503,504],$s=class{constructor(e){var n,i,o;this.clientOptions=Object.assign({},e),this.customBaseUrl=(n=e.httpOptions)===null||n===void 0?void 0:n.baseUrl;let r={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");let u=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!u?(r.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||this.clientOptions.location==="global"?r.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&RA.has(this.clientOptions.location)?r.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(r.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),r.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:SA}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),r.apiVersion=(o=this.clientOptions.apiVersion)!==null&&o!==void 0?o:wA,r.baseUrl="https://generativelanguage.googleapis.com/";r.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=r,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(r,e.httpOptions))}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){let e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");let i=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&e.apiVersion!==""&&i.push(e.apiVersion),i.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let e=this.getBaseUrl(),n=new URL(e);return n.protocol=n.protocol=="http:"?"ws":"wss",n.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw new Error("HTTP options are not correctly set.")}constructUrl(e,n,i){let o=[this.getRequestUrlInternal(n)];return i&&o.push(this.getBaseResourcePath()),e!==""&&o.push(e),new URL(`${o.join("/")}`)}shouldPrependVertexProjectPath(e,n){return!(n.baseUrl&&n.baseUrlResourceScope===gs.COLLECTION||!this.clientOptions.vertexai||!this.clientOptions.project||!this.clientOptions.location||e.path.startsWith("projects/")||e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models"))}async request(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let i=this.shouldPrependVertexProjectPath(e,n),o=this.constructUrl(e.path,n,i);if(e.queryParams)for(let[a,u]of Object.entries(e.queryParams))o.searchParams.append(a,String(u));let r={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else r.body=e.body;return r=await this.includeExtraHttpOptionsToRequestInit(r,n,o.toString()),this.unaryApiCall(o,r,e.httpMethod,n.retryOptions,n.timeout,e.abortSignal)}patchHttpOptions(e,n){let i=JSON.parse(JSON.stringify(e));for(let[o,r]of Object.entries(n))typeof r=="object"?i[o]=Object.assign(Object.assign({},i[o]),r):r!==void 0&&(i[o]=r);return i}async requestStream(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let i=this.shouldPrependVertexProjectPath(e,n),o=this.constructUrl(e.path,n,i);(!o.searchParams.has("alt")||o.searchParams.get("alt")!=="sse")&&o.searchParams.set("alt","sse");let r={};return r.body=e.body,r=await this.includeExtraHttpOptionsToRequestInit(r,n,o.toString()),this.streamApiCall(o,r,e.httpMethod,n.retryOptions,n.timeout,e.abortSignal)}async includeExtraHttpOptionsToRequestInit(e,n,i){return n?.timeout&&n.timeout>0&&PA(n.timeout),n&&n.extraBody!==null&&LA(e,n.extraBody),e.headers=await this.getHeadersInternal(n,i),e}async unaryApiCall(e,n,i,o,r,a){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:i}),o,r,a).then(async u=>(await ds(u),new Mt(u))).catch(u=>{throw u instanceof Error?u:new Error(`exception ${u} sending request`,{cause:u})})}async streamApiCall(e,n,i,o,r,a){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:i}),o,r,a).then(async u=>(await ds(u),this.processStreamResponse(u))).catch(u=>{throw u instanceof Error?u:new Error(`exception ${u} sending request`,{cause:u})})}processStreamResponse(e){return pn(this,arguments,function*(){var i;let o=(i=e?.body)===null||i===void 0?void 0:i.getReader(),r=new TextDecoder("utf-8");if(!o)throw new Error("Response body is empty");try{let a="",u="data:",c=[`
32
-
33
- `,"\r\r",`\r
34
- \r
35
- `];for(;;){let{done:d,value:f}=yield ve(o.read());if(d){if(a.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let p=r.decode(f,{stream:!0});try{let _=JSON.parse(p);if("error"in _){let g=JSON.parse(JSON.stringify(_.error)),v=g.status,y=g.code,A=`got status: ${v}. ${JSON.stringify(_)}`;if(y>=400&&y<600)throw new ji({message:A,status:y})}}catch(_){if(_.name==="ApiError")throw _}a+=p;let h=-1,m=0;for(;;){h=-1,m=0;for(let v of c){let y=a.indexOf(v);y!==-1&&(h===-1||y<h)&&(h=y,m=v.length)}if(h===-1)break;let _=a.substring(0,h);a=a.substring(h+m);let g=_.trim();if(g.startsWith(u)){let v=g.substring(u.length).trim();try{let y=new Response(v,{headers:e?.headers,status:e?.status,statusText:e?.statusText});yield yield ve(new Mt(y))}catch(y){throw new Error(`exception parsing stream chunk ${v}. ${y}`)}}}}}finally{o.releaseLock()}})}async apiCall(e,n,i,o,r){var a,u,c,d,f,p;let h=(a=i?.httpStatusCodes)!==null&&a!==void 0?a:GA,m=async()=>{let y=NA(o,r),A;try{A=await fetch(e,Object.assign(Object.assign({},n),{signal:y.signal}))}catch(C){throw y.dispose(),C}if(!i||A.ok||!h.includes(A.status))return A;try{await ds(A)}finally{y.dispose()}return A};if(!i)return m();let _=Math.max(1,(u=i.attempts)!==null&&u!==void 0?u:kA),g=Math.round(((c=i.initialDelay)!==null&&c!==void 0?c:DA)*1e3),v=Math.max(g,Math.round(((d=i.maxDelay)!==null&&d!==void 0?d:xA)*1e3));return(0,of.default)(m,{retries:_-1,factor:(f=i.expBase)!==null&&f!==void 0?f:MA,minTimeout:g,maxTimeout:v,randomize:((p=i.jitter)!==null&&p!==void 0?p:UA)>0,onFailedAttempt:y=>{var A;if(r?.aborted)throw(A=y.error)!==null&&A!==void 0?A:y}})}getDefaultHeaders(){let e={},n=IA+" "+this.clientOptions.userAgentExtra;return e[AA]=n,e[Bs]=n,e[vA]="application/json",e}async getHeadersInternal(e,n){let i=new Headers;if(e&&e.headers)for(let[o,r]of Object.entries(e.headers))i.append(o,r);return e?.timeout&&e.timeout>0&&i.append(TA,String(Math.ceil(e.timeout/1e3))),await this.clientOptions.auth.addAuthHeaders(i,n),i}getFileName(e){var n;let i="";return typeof e=="string"&&(i=e.replace(/[/\\]+$/,""),i=(n=i.split(/[/\\]/).pop())!==null&&n!==void 0?n:""),i}async uploadFile(e,n){var i;let o={};n!=null&&(o.mimeType=n.mimeType,o.name=n.name,o.displayName=n.displayName),o.name&&!o.name.startsWith("files/")&&(o.name=`files/${o.name}`);let r=this.clientOptions.uploader,a=await r.stat(e);o.sizeBytes=String(a.size);let u=(i=n?.mimeType)!==null&&i!==void 0?i:a.type;if(u===void 0||u==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");o.mimeType=u;let c={file:o},d=this.getFileName(e),f=B("upload/v1beta/files",c._url),p=await this.fetchUploadUrl(f,o.sizeBytes,o.mimeType,d,c,n?.httpOptions);return r.upload(e,p,this)}async uploadFileToFileSearchStore(e,n,i){var o;let r=this.clientOptions.uploader,a=await r.stat(n),u=String(a.size),c=(o=i?.mimeType)!==null&&o!==void 0?o:a.type;if(c===void 0||c==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");let d=`upload/v1beta/${e}:uploadToFileSearchStore`,f=this.getFileName(n),p={};i!=null&&Df(i,p);let h=await this.fetchUploadUrl(d,u,c,f,p,i?.httpOptions);return r.uploadToFileSearchStore(n,h,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,n,i,o,r,a){var u;let c={};a?c=a:c={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n}`,"X-Goog-Upload-Header-Content-Type":`${i}`},o?{"X-Goog-Upload-File-Name":o}:{})};let d=await this.request({path:e,body:JSON.stringify(r),httpMethod:"POST",httpOptions:c});if(!d||!d?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let f=(u=d?.headers)===null||u===void 0?void 0:u["x-goog-upload-url"];if(f===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return f}};async function ds(t){var e;if(t===void 0)throw new Error("response is undefined");if(!t.ok){let n=t.status,i;!((e=t.headers.get("content-type"))===null||e===void 0)&&e.includes("application/json")?i=await t.json():i={error:{message:await t.text(),code:t.status,status:t.statusText}};let o=JSON.stringify(i);throw n>=400&&n<600?new ji({message:o,status:n}):new Error(o)}}function LA(t,e){if(!e||Object.keys(e).length===0)return;if(t.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let n={};if(typeof t.body=="string"&&t.body.length>0)try{let r=JSON.parse(t.body);if(typeof r=="object"&&r!==null&&!Array.isArray(r))n=r;else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch{console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function i(r,a){let u=Object.assign({},r);for(let c in a)if(Object.prototype.hasOwnProperty.call(a,c)){let d=a[c],f=u[c];d&&typeof d=="object"&&!Array.isArray(d)&&f&&typeof f=="object"&&!Array.isArray(f)?u[c]=i(f,d):(f&&d&&typeof f!=typeof d&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${c}". Original type: ${typeof f}, New type: ${typeof d}. Overwriting.`),u[c]=d)}return u}let o=i(n,e);t.body=JSON.stringify(o)}var bA="mcp_used/unknown",OA=!1;function xf(t){for(let e of t)if(qA(e)||typeof e=="object"&&"inputSchema"in e)return!0;return OA}function Mf(t){var e;let n=(e=t[Bs])!==null&&e!==void 0?e:"";t[Bs]=(n+` ${bA}`).trimStart()}function qA(t){return t!==null&&typeof t=="object"&&t instanceof Js}function FA(t){return pn(this,arguments,function*(n,i=100){let o,r=0;for(;r<i;){let a=yield ve(n.listTools({cursor:o}));for(let u of a.tools)yield yield ve(u),r++;if(!a.nextCursor)break;o=a.nextCursor}})}var Js=class t{constructor(e=[],n){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=n}static create(e,n){return new t(e,n)}async initialize(){var e,n,i,o;if(this.mcpTools.length>0)return;let r={},a=[];for(let f of this.mcpClients)try{for(var u=!0,c=(n=void 0,bn(FA(f))),d;d=await c.next(),e=d.done,!e;u=!0){o=d.value,u=!1;let p=o;a.push(p);let h=p.name;if(r[h])throw new Error(`Duplicate function name ${h} found in MCP tools. Please ensure function names are unique.`);r[h]=f}}catch(p){n={error:p}}finally{try{!u&&!e&&(i=c.return)&&await i.call(c)}finally{if(n)throw n.error}}this.mcpTools=a,this.functionNameToMcpClient=r}async tool(){return await this.initialize(),K_(this.mcpTools,this.config)}async callTool(e){await this.initialize();let n=[];for(let i of e)if(i.name in this.functionNameToMcpClient){let o=this.functionNameToMcpClient[i.name],r;this.config.timeout&&(r={timeout:this.config.timeout});let a=await o.callTool({name:i.name,arguments:i.args},void 0,r);n.push({functionResponse:{name:i.name,response:a.isError?{error:a}:a}})}return n}};async function HA(t,e,n){let i=new Us,o;n.data instanceof Blob?o=JSON.parse(await n.data.text()):o=JSON.parse(n.data),Object.assign(i,o),e(i)}var Xs=class{constructor(e,n,i){this.apiClient=e,this.auth=n,this.webSocketFactory=i}async connect(e){var n,i;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");let o=this.apiClient.getWebsocketBaseUrl(),r=this.apiClient.getApiVersion(),a=BA(this.apiClient.getDefaultHeaders()),u=this.apiClient.getApiKey(),c=`${o}/ws/google.ai.generativelanguage.${r}.GenerativeService.BidiGenerateMusic?key=${u}`,d=()=>{},f=new Promise(C=>{d=C}),p=e.callbacks,h=function(){d({})},m=this.apiClient,_={onopen:h,onmessage:C=>{HA(m,p.onmessage,C)},onerror:(n=p?.onerror)!==null&&n!==void 0?n:function(C){},onclose:(i=p?.onclose)!==null&&i!==void 0?i:function(C){}},g=this.webSocketFactory.create(c,VA(a),_);g.connect(),await f;let A={setup:{model:re(this.apiClient,e.model)}};return g.send(JSON.stringify(A)),new Ks(g,this.apiClient)}},Ks=class{constructor(e,n){this.conn=e,this.apiClient=n}async setWeightedPrompts(e){if(!e.weightedPrompts||Object.keys(e.weightedPrompts).length===0)throw new Error("Weighted prompts must be set and contain at least one entry.");let n=ZE(e);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});let n=QE(e);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){let n={playbackControl:e};this.conn.send(JSON.stringify(n))}play(){this.sendPlaybackControl(un.PLAY)}pause(){this.sendPlaybackControl(un.PAUSE)}stop(){this.sendPlaybackControl(un.STOP)}resetContext(){this.sendPlaybackControl(un.RESET_CONTEXT)}close(){this.conn.close()}};function VA(t){let e={};return t.forEach((n,i)=>{e[i]=n}),e}function BA(t){let e=new Headers;for(let[n,i]of Object.entries(t))e.append(n,i);return e}var $A="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function JA(t,e,n){let i=new Ms,o;n.data instanceof Blob?o=await n.data.text():n.data instanceof ArrayBuffer?o=new TextDecoder().decode(n.data):o=n.data;let r=JSON.parse(o);if(t.isVertexAI()){let a=tv(r);Object.assign(i,a)}else Object.assign(i,r);e(i)}var Ys=class{constructor(e,n,i){this.apiClient=e,this.auth=n,this.webSocketFactory=i,this.music=new Xs(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var n,i,o,r,a,u;if(e.config&&e.config.httpOptions)throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let c=this.apiClient.getWebsocketBaseUrl(),d=this.apiClient.getApiVersion(),f,p=this.apiClient.getHeaders();e.config&&e.config.tools&&xf(e.config.tools)&&Mf(p);let h=YA(p);if(this.apiClient.isVertexAI()){let D=this.apiClient.getProject(),K=this.apiClient.getLocation(),Z=this.apiClient.getApiKey(),Ee=!!D&&!!K||!!Z;this.apiClient.getCustomBaseUrl()&&!Ee?f=c:(f=`${c}/ws/google.cloud.aiplatform.${d}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(h,f))}else{let D=this.apiClient.getApiKey(),K="BidiGenerateContent",Z="key";D?.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),d!=="v1alpha"&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),K="BidiGenerateContentConstrained",Z="access_token"),f=`${c}/ws/google.ai.generativelanguage.${d}.GenerativeService.${K}?${Z}=${D}`}let m=()=>{},_=new Promise(D=>{m=D}),g=e.callbacks,v=function(){var D;(D=g?.onopen)===null||D===void 0||D.call(g),m({})},y=this.apiClient,A=!1,C=[],S=()=>{},R=new Promise(D=>{S=D}),L={onopen:v,onmessage:D=>{JA(y,K=>{K.setupComplete&&!te.setupComplete&&(te.setupComplete=K.setupComplete,S({})),A?g.onmessage(K):C.push(K)},D)},onerror:(n=g?.onerror)!==null&&n!==void 0?n:function(D){},onclose:(i=g?.onclose)!==null&&i!==void 0?i:function(D){}},O=this.webSocketFactory.create(f,KA(h),L);O.connect(),await _;let H=re(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&H.startsWith("publishers/")){let D=this.apiClient.getProject(),K=this.apiClient.getLocation();D&&K&&(H=`projects/${D}/locations/${K}/`+H)}let U={};this.apiClient.isVertexAI()&&((o=e.config)===null||o===void 0?void 0:o.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[Fi.AUDIO]}:e.config.responseModalities=[Fi.AUDIO]),!((r=e.config)===null||r===void 0)&&r.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. It will be removed in the next major version (not before 7/31/2026).");let F=(u=(a=e.config)===null||a===void 0?void 0:a.tools)!==null&&u!==void 0?u:[],J=[];for(let D of F)if(this.isCallableTool(D)){let K=D;J.push(await K.tool())}else J.push(D);J.length>0&&(e.config.tools=J);let Q={model:H,config:e.config,callbacks:e.callbacks};this.apiClient.isVertexAI()?U=zE(this.apiClient,Q):U=WE(this.apiClient,Q),delete U.config;let te=new Ws(O,this.apiClient);O.send(JSON.stringify(U)),await R,A=!0;for(let D of C)g.onmessage(D);return te}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}},XA={turnComplete:!0},Ws=class{constructor(e,n){this.conn=e,this.apiClient=n}tLiveClientContent(e,n){if(n.turns!==null&&n.turns!==void 0){let i=[];try{i=Le(n.turns),e.isVertexAI()||(i=i.map(o=>Fn(o)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof n.turns}'`)}return{clientContent:{turns:i,turnComplete:n.turnComplete}}}return{clientContent:{turnComplete:n.turnComplete}}}tLiveClienttToolResponse(e,n){let i=[];if(n.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(n.functionResponses)?i=n.functionResponses:i=[n.functionResponses],i.length===0)throw new Error("functionResponses is required.");for(let r of i){if(typeof r!="object"||r===null||!("name"in r)||!("response"in r))throw new Error(`Could not parse function response, type '${typeof r}'.`);if(!e.isVertexAI()&&!("id"in r))throw new Error($A)}return{toolResponse:{functionResponses:i}}}sendClientContent(e){e=Object.assign(Object.assign({},XA),e);let n=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendRealtimeInput(e){let n={};this.apiClient.isVertexAI()?n={realtimeInput:ev(e)}:n={realtimeInput:jE(e)},this.conn.send(JSON.stringify(n))}sendToolResponse(e){if(e.functionResponses==null)throw new Error("Tool response parameters are required.");let n=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(n))}close(){this.conn.close()}};function KA(t){let e={};return t.forEach((n,i)=>{e[i]=n}),e}function YA(t){let e=new Headers;for(let[n,i]of Object.entries(t))e.append(n,i);return e}var Gd=10;function Ld(t){var e,n,i;if(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let o=!1;for(let a of(n=t?.tools)!==null&&n!==void 0?n:[])if(hn(a)){o=!0;break}if(!o)return!0;let r=(i=t?.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls;return r&&(r<0||!Number.isInteger(r))||r==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",r),!0):!1}function hn(t){return"callTool"in t&&typeof t.callTool=="function"}function WA(t){var e,n,i;return(i=(n=(e=t.config)===null||e===void 0?void 0:e.tools)===null||n===void 0?void 0:n.some(o=>hn(o)))!==null&&i!==void 0?i:!1}function bd(t){var e;let n=[];return!((e=t?.config)===null||e===void 0)&&e.tools&&t.config.tools.forEach((i,o)=>{if(hn(i))return;let r=i;r.functionDeclarations&&r.functionDeclarations.length>0&&n.push(o)}),n}function Od(t){var e;return!(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}var mn=class t extends it{constructor(e){super(),this.apiClient=e,this.embedContent=async n=>{if(!this.apiClient.isVertexAI())return n.model.includes("gemini-embedding-2")&&(n.contents=Le(n.contents)),await this.embedContentInternal(n);if(n.model.includes("gemini")&&n.model!=="gemini-embedding-001"||n.model.includes("maas")){let o=Le(n.contents);if(o.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");let r=Object.assign(Object.assign({},n),{content:o[0],embeddingApiType:Hi.EMBED_CONTENT});return await this.embedContentInternal(r)}else{let o=Object.assign(Object.assign({},n),{embeddingApiType:Hi.PREDICT});return await this.embedContentInternal(o)}},this.generateContent=async n=>{var i,o,r,a,u;let c=await this.processParamsMaybeAddMcpUsage(n);if(this.maybeMoveToResponseJsonSchema(n),!WA(n)||Ld(n.config))return await this.generateContentInternal(c);let d=bd(n);if(d.length>0){let g=d.map(v=>`tools[${v}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${g}.`)}let f,p,h=Le(c.contents),m=(r=(o=(i=c.config)===null||i===void 0?void 0:i.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls)!==null&&r!==void 0?r:Gd,_=0;for(;_<m&&(f=await this.generateContentInternal(c),!(!f.functionCalls||f.functionCalls.length===0));){let g=f.candidates[0].content,v=[];for(let y of(u=(a=n.config)===null||a===void 0?void 0:a.tools)!==null&&u!==void 0?u:[])if(hn(y)){let C=await y.callTool(f.functionCalls);v.push(...C)}_++,p={role:"user",parts:v},c.contents=Le(c.contents),c.contents.push(g),c.contents.push(p),Od(c.config)&&(h.push(g),h.push(p))}return Od(c.config)&&(f.automaticFunctionCallingHistory=h),f},this.generateContentStream=async n=>{var i,o,r,a,u;if(this.maybeMoveToResponseJsonSchema(n),Ld(n.config)){let p=await this.processParamsMaybeAddMcpUsage(n);return await this.generateContentStreamInternal(p)}let c=bd(n);if(c.length>0){let p=c.map(h=>`tools[${h}]`).join(", ");throw new Error(`Incompatible tools found at ${p}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let d=(r=(o=(i=n?.config)===null||i===void 0?void 0:i.toolConfig)===null||o===void 0?void 0:o.functionCallingConfig)===null||r===void 0?void 0:r.streamFunctionCallArguments,f=(u=(a=n?.config)===null||a===void 0?void 0:a.automaticFunctionCalling)===null||u===void 0?void 0:u.disable;if(d&&!f)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(n)},this.generateImages=async n=>(t.loggedGenerateImagesWarning||(t.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images")),await this.generateImagesInternal(n).then(i=>{var o;let r,a=[];if(i?.generatedImages)for(let c of i.generatedImages)c&&c?.safetyAttributes&&((o=c?.safetyAttributes)===null||o===void 0?void 0:o.contentType)==="Positive Prompt"?r=c?.safetyAttributes:a.push(c);let u;return r?u={generatedImages:a,positivePromptSafetyAttributes:r,sdkHttpResponse:i.sdkHttpResponse}:u={generatedImages:a,sdkHttpResponse:i.sdkHttpResponse},u})),this.list=async n=>{var i;let a={config:Object.assign(Object.assign({},{queryBase:!0}),n?.config)};if(this.apiClient.isVertexAI()&&!a.config.queryBase){if(!((i=a.config)===null||i===void 0)&&i.filter)throw new Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");a.config.filter="labels.tune-type:*"}return new Et(yt.PAGED_ITEM_MODELS,u=>this.listInternal(u),await this.listInternal(a),a)},this.editImage=async n=>{t.loggedEditImageWarning||(t.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image"));let i={model:n.model,prompt:n.prompt,referenceImages:[],config:n.config};return n.referenceImages&&n.referenceImages&&(i.referenceImages=n.referenceImages.map(o=>o.toReferenceImageAPI())),await this.editImageInternal(i)},this.upscaleImage=async n=>{let i={numberOfImages:1,mode:"upscale"};n.config&&(i=Object.assign(Object.assign({},i),n.config));let o={model:n.model,image:n.image,upscaleFactor:n.upscaleFactor,config:i};return await this.upscaleImageInternal(o)},this.generateVideos=async n=>{var i,o,r,a,u,c;if((n.prompt||n.image||n.video)&&n.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return(n.prompt||n.image||n.video)&&(t.loggedGenerateVideosWarning||(t.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead."))),this.apiClient.isVertexAI()||(!((i=n.video)===null||i===void 0)&&i.uri&&(!((o=n.video)===null||o===void 0)&&o.videoBytes)?n.video={uri:n.video.uri,mimeType:n.video.mimeType}:!((a=(r=n.source)===null||r===void 0?void 0:r.video)===null||a===void 0)&&a.uri&&(!((c=(u=n.source)===null||u===void 0?void 0:u.video)===null||c===void 0)&&c.videoBytes)&&(n.source.video={uri:n.source.video.uri,mimeType:n.source.video.mimeType})),await this.generateVideosInternal(n)}}maybeMoveToResponseJsonSchema(e){e.config&&e.config.responseSchema&&(e.config.responseJsonSchema||Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema))}async processParamsMaybeAddMcpUsage(e){var n,i,o;let r=(n=e.config)===null||n===void 0?void 0:n.tools;if(!r)return e;let a=await Promise.all(r.map(async c=>hn(c)?await c.tool():c)),u={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:a})};if(u.config.tools=a,e.config&&e.config.tools&&xf(e.config.tools)){let c=(o=(i=e.config.httpOptions)===null||i===void 0?void 0:i.headers)!==null&&o!==void 0?o:{},d=Object.assign({},c);Object.keys(d).length===0&&(d=this.apiClient.getDefaultHeaders()),Mf(d),u.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:d})}return u}async initAfcToolsMap(e){var n,i,o;let r=new Map;for(let a of(i=(n=e.config)===null||n===void 0?void 0:n.tools)!==null&&i!==void 0?i:[])if(hn(a)){let u=a,c=await u.tool();for(let d of(o=c.functionDeclarations)!==null&&o!==void 0?o:[]){if(!d.name)throw new Error("Function declaration name is required.");if(r.has(d.name))throw new Error(`Duplicate tool declaration name: ${d.name}`);r.set(d.name,u)}}return r}async processAfcStream(e){var n,i,o;let r=(o=(i=(n=e.config)===null||n===void 0?void 0:n.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&o!==void 0?o:Gd,a=!1,u=0,c=await this.initAfcToolsMap(e);return(function(d,f,p){return pn(this,arguments,function*(){for(var h,m,_,g,v,y;u<r;){a&&(u++,a=!1);let R=yield ve(d.processParamsMaybeAddMcpUsage(p)),L=yield ve(d.generateContentStreamInternal(R)),O=[],H=[];try{for(var A=!0,C=(m=void 0,bn(L)),S;S=yield ve(C.next()),h=S.done,!h;A=!0){g=S.value,A=!1;let U=g;if(yield yield ve(U),U.candidates&&(!((v=U.candidates[0])===null||v===void 0)&&v.content)){H.push(U.candidates[0].content);for(let F of(y=U.candidates[0].content.parts)!==null&&y!==void 0?y:[])if(u<r&&F.functionCall){if(!F.functionCall.name)throw new Error("Function call name was not returned by the model.");if(f.has(F.functionCall.name)){let J=yield ve(f.get(F.functionCall.name).callTool([F.functionCall]));O.push(...J)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${f.keys()}, missing tool: ${F.functionCall.name}`)}}}}catch(U){m={error:U}}finally{try{!A&&!h&&(_=C.return)&&(yield ve(_.call(C)))}finally{if(m)throw m.error}}if(O.length>0){a=!0;let U=new $t;U.candidates=[{content:{role:"user",parts:O}}],yield yield ve(U);let F=[];F.push(...H),F.push({role:"user",parts:O});let J=Le(p.contents).concat(F);p.contents=J}else break}})})(this,c,e)}async generateContentInternal(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=xd(this.apiClient,e);return u=B("{model}:generateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=Ud(f),h=new $t;return Object.assign(h,p),h})}else{let d=Dd(this.apiClient,e);return u=B("{model}:generateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=Md(f),h=new $t;return Object.assign(h,p),h})}}async generateContentStreamInternal(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=xd(this.apiClient,e);return u=B("{model}:streamGenerateContent?alt=sse",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.requestStream({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}),a.then(function(p){return pn(this,arguments,function*(){var h,m,_,g;try{for(var v=!0,y=bn(p),A;A=yield ve(y.next()),h=A.done,!h;v=!0){g=A.value,v=!1;let C=g,S=Ud(yield ve(C.json()),e);S.sdkHttpResponse={headers:C.headers};let R=new $t;Object.assign(R,S),yield yield ve(R)}}catch(C){m={error:C}}finally{try{!v&&!h&&(_=y.return)&&(yield ve(_.call(y)))}finally{if(m)throw m.error}}})})}else{let d=Dd(this.apiClient,e);return u=B("{model}:streamGenerateContent?alt=sse",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.requestStream({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}),a.then(function(p){return pn(this,arguments,function*(){var h,m,_,g;try{for(var v=!0,y=bn(p),A;A=yield ve(y.next()),h=A.done,!h;v=!0){g=A.value,v=!1;let C=g,S=Md(yield ve(C.json()),e);S.sdkHttpResponse={headers:C.headers};let R=new $t;Object.assign(R,S),yield yield ve(R)}}catch(C){m={error:C}}finally{try{!v&&!h&&(_=y.return)&&(yield ve(_.call(y)))}finally{if(m)throw m.error}}})})}}async embedContentInternal(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=Fv(this.apiClient,e,e),f=W_(e.model)?"{model}:embedContent":"{model}:predict";return u=B(f,d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(p=>p.json().then(h=>{let m=h;return m.sdkHttpResponse={headers:p.headers},m})),a.then(p=>{let h=Vv(p,e),m=new Vi;return Object.assign(m,h),m})}else{let d=qv(this.apiClient,e);return u=B("{model}:batchEmbedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=Hv(f),h=new Vi;return Object.assign(h,p),h})}}async generateImagesInternal(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI()){let u=zv(this.apiClient,e);return r=B("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>{let d=Qv(c),f=new _s;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async editImageInternal(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI()){let u=Gv(this.apiClient,e);return r=B("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>{let d=Lv(c),f=new ys;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI()){let u=jT(this.apiClient,e);return r=B("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>{let d=eA(c),f=new Es;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI()){let u=DT(this.apiClient,e);return r=B("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json()),o.then(c=>{let d=xT(c),f=new vs;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI()){let u=qT(this.apiClient,e);return r=B("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json()),o.then(c=>{let d=FT(c),f=new Ts;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=pT(this.apiClient,e);return u=B("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>Vs(f))}else{let d=fT(this.apiClient,e);return u=B("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>Hs(f))}}async listInternal(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=TT(this.apiClient,e);return u=B("{models_url}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=CT(f),h=new Bi;return Object.assign(h,p),h})}else{let d=vT(this.apiClient,e);return u=B("{models_url}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=AT(f),h=new Bi;return Object.assign(h,p),h})}}async update(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=QT(this.apiClient,e);return u=B("{model}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>Vs(f))}else{let d=zT(this.apiClient,e);return u=B("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>Hs(f))}}async delete(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=Dv(this.apiClient,e);return u=B("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=Mv(f),h=new $i;return Object.assign(h,p),h})}else{let d=kv(this.apiClient,e);return u=B("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=xv(f),h=new $i;return Object.assign(h,p),h})}}async countTokens(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=Rv(this.apiClient,e);return u=B("{model}:countTokens",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=Nv(f),h=new Ji;return Object.assign(h,p),h})}else{let d=wv(this.apiClient,e);return u=B("{model}:countTokens",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=Pv(f),h=new Ji;return Object.assign(h,p),h})}}async computeTokens(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI()){let u=yv(this.apiClient,e);return r=B("{model}:computeTokens",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>{let d=Ev(c),f=new As;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=iT(this.apiClient,e);return u=B("{model}:predictLongRunning",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a.then(f=>{let p=tT(f),h=new Xi;return Object.assign(h,p),h})}else{let d=nT(this.apiClient,e);return u=B("{model}:predictLongRunning",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a.then(f=>{let p=eT(f),h=new Xi;return Object.assign(h,p),h})}}};mn.loggedGenerateImagesWarning=!1;mn.loggedEditImageWarning=!1;mn.loggedGenerateVideosWarning=!1;var zs=class extends it{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){let n=e.operation,i=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let o=n.name.split("/operations/")[0],r;i&&"httpOptions"in i&&(r=i.httpOptions);let a=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:o,config:{httpOptions:r}});return n._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let o=await this.getVideosOperationInternal({operationName:n.name,config:i});return n._fromAPIResponse({apiResponse:o,_isVertexAI:!1})}}async get(e){let n=e.operation,i=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let o=n.name.split("/operations/")[0],r;i&&"httpOptions"in i&&(r=i.httpOptions);let a=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:o,config:{httpOptions:r}});return n._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{let o=await this.getVideosOperationInternal({operationName:n.name,config:i});return n._fromAPIResponse({apiResponse:o,_isVertexAI:!1})}}async getVideosOperationInternal(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=L_(e);return u=B("{operationName}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json()),a}else{let d=G_(e);return u=B("{operationName}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json()),a}}async fetchPredictVideosOperationInternal(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI()){let u=P_(e);return r=B("{resourceName}:fetchPredictOperation",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json()),o}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};function zA(t){let e={},n=s(t,["apiKey"]);if(n!=null&&l(e,["apiKey"],n),s(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function QA(t){let e={},n=s(t,["data"]);if(n!=null&&l(e,["data"],n),s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}function ZA(t){let e={},n=s(t,["parts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(r=>aC(r))),l(e,["parts"],o)}let i=s(t,["role"]);return i!=null&&l(e,["role"],i),e}function jA(t,e,n){let i={},o=s(e,["expireTime"]);n!==void 0&&o!=null&&l(n,["expireTime"],o);let r=s(e,["newSessionExpireTime"]);n!==void 0&&r!=null&&l(n,["newSessionExpireTime"],r);let a=s(e,["uses"]);n!==void 0&&a!=null&&l(n,["uses"],a);let u=s(e,["liveConnectConstraints"]);n!==void 0&&u!=null&&l(n,["bidiGenerateContentSetup"],sC(t,u));let c=s(e,["lockAdditionalFields"]);return n!==void 0&&c!=null&&l(n,["fieldMask"],c),i}function eC(t,e){let n={},i=s(e,["config"]);return i!=null&&l(n,["config"],jA(t,i,n)),n}function tC(t){let e={};if(s(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["fileUri"]);n!=null&&l(e,["fileUri"],n);let i=s(t,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}function nC(t){let e={},n=s(t,["args"]);n!=null&&l(e,["args"],n);let i=s(t,["id"]);i!=null&&l(e,["id"],i);let o=s(t,["name"]);if(o!=null&&l(e,["name"],o),s(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function iC(t){let e={},n=s(t,["authConfig"]);n!=null&&l(e,["authConfig"],zA(n));let i=s(t,["enableWidget"]);if(i!=null&&l(e,["enableWidget"],i),s(t,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function oC(t){let e={};if(s(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["searchTypes"]);n!=null&&l(e,["searchTypes"],n);let i=s(t,["timeRangeFilter"]);return i!=null&&l(e,["timeRangeFilter"],i),e}function rC(t,e){let n={},i=s(t,["generationConfig"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig"],i);let o=s(t,["responseModalities"]);e!==void 0&&o!=null&&l(e,["setup","generationConfig","responseModalities"],o);let r=s(t,["temperature"]);e!==void 0&&r!=null&&l(e,["setup","generationConfig","temperature"],r);let a=s(t,["topP"]);e!==void 0&&a!=null&&l(e,["setup","generationConfig","topP"],a);let u=s(t,["topK"]);e!==void 0&&u!=null&&l(e,["setup","generationConfig","topK"],u);let c=s(t,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);let d=s(t,["mediaResolution"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","mediaResolution"],d);let f=s(t,["seed"]);e!==void 0&&f!=null&&l(e,["setup","generationConfig","seed"],f);let p=s(t,["speechConfig"]);e!==void 0&&p!=null&&l(e,["setup","generationConfig","speechConfig"],za(p));let h=s(t,["thinkingConfig"]);e!==void 0&&h!=null&&l(e,["setup","generationConfig","thinkingConfig"],h);let m=s(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&l(e,["setup","generationConfig","enableAffectiveDialog"],m);let _=s(t,["systemInstruction"]);e!==void 0&&_!=null&&l(e,["setup","systemInstruction"],ZA(Ne(_)));let g=s(t,["tools"]);if(e!==void 0&&g!=null){let U=yn(g);Array.isArray(U)&&(U=U.map(F=>cC(_n(F)))),l(e,["setup","tools"],U)}let v=s(t,["sessionResumption"]);e!==void 0&&v!=null&&l(e,["setup","sessionResumption"],uC(v));let y=s(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&l(e,["setup","inputAudioTranscription"],y);let A=s(t,["outputAudioTranscription"]);e!==void 0&&A!=null&&l(e,["setup","outputAudioTranscription"],A);let C=s(t,["realtimeInputConfig"]);e!==void 0&&C!=null&&l(e,["setup","realtimeInputConfig"],C);let S=s(t,["contextWindowCompression"]);e!==void 0&&S!=null&&l(e,["setup","contextWindowCompression"],S);let R=s(t,["proactivity"]);if(e!==void 0&&R!=null&&l(e,["setup","proactivity"],R),s(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let L=s(t,["avatarConfig"]);e!==void 0&&L!=null&&l(e,["setup","avatarConfig"],L);let O=s(t,["safetySettings"]);if(e!==void 0&&O!=null){let U=O;Array.isArray(U)&&(U=U.map(F=>lC(F))),l(e,["setup","safetySettings"],U)}let H=s(t,["translationConfig"]);return e!==void 0&&H!=null&&l(e,["setup","generationConfig","translationConfig"],H),n}function sC(t,e){let n={},i=s(e,["model"]);i!=null&&l(n,["setup","model"],re(t,i));let o=s(e,["config"]);return o!=null&&l(n,["config"],rC(o,n)),n}function aC(t){let e={},n=s(t,["mediaResolution"]);n!=null&&l(e,["mediaResolution"],n);let i=s(t,["toolCall"]);i!=null&&l(e,["toolCall"],i);let o=s(t,["toolResponse"]);o!=null&&l(e,["toolResponse"],o);let r=s(t,["audioTranscription"]);r!=null&&l(e,["audioTranscription"],r);let a=s(t,["codeExecutionResult"]);a!=null&&l(e,["codeExecutionResult"],a);let u=s(t,["executableCode"]);u!=null&&l(e,["executableCode"],u);let c=s(t,["fileData"]);c!=null&&l(e,["fileData"],tC(c));let d=s(t,["functionCall"]);d!=null&&l(e,["functionCall"],nC(d));let f=s(t,["functionResponse"]);f!=null&&l(e,["functionResponse"],f);let p=s(t,["inlineData"]);p!=null&&l(e,["inlineData"],QA(p));let h=s(t,["text"]);h!=null&&l(e,["text"],h);let m=s(t,["thought"]);m!=null&&l(e,["thought"],m);let _=s(t,["thoughtSignature"]);_!=null&&l(e,["thoughtSignature"],_);let g=s(t,["videoMetadata"]);g!=null&&l(e,["videoMetadata"],g);let v=s(t,["partMetadata"]);v!=null&&l(e,["partMetadata"],v);let y=s(t,["mediaProcessing"]);return y!=null&&l(e,["mediaProcessing"],y),e}function lC(t){let e={},n=s(t,["category"]);if(n!=null&&l(e,["category"],n),s(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["threshold"]);return i!=null&&l(e,["threshold"],i),e}function uC(t){let e={},n=s(t,["handle"]);if(n!=null&&l(e,["handle"],n),s(t,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function cC(t){let e={};if(s(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let n=s(t,["googleMaps"]);n!=null&&l(e,["googleMaps"],iC(n));let i=s(t,["mcpServers"]);if(i!=null){let p=i;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["mcpServers"],p)}let o=s(t,["codeExecution"]);o!=null&&l(e,["codeExecution"],o);let r=s(t,["computerUse"]);if(r!=null&&l(e,["computerUse"],r),s(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let a=s(t,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(h=>h)),l(e,["functionDeclarations"],p)}let u=s(t,["googleSearch"]);u!=null&&l(e,["googleSearch"],oC(u));let c=s(t,["googleSearchRetrieval"]);if(c!=null&&l(e,["googleSearchRetrieval"],c),s(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let d=s(t,["urlContext"]);d!=null&&l(e,["urlContext"],d);let f=s(t,["fileSearch"]);return f!=null&&l(e,["fileSearch"],f),e}function dC(t){let e=[];for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(typeof i=="object"&&i!=null&&Object.keys(i).length>0){let o=Object.keys(i).map(r=>`${n}.${r}`);e.push(...o)}else e.push(n)}return e.join(",")}function fC(t,e){let n=null,i=t.bidiGenerateContentSetup;if(typeof i=="object"&&i!==null&&"setup"in i){let r=i.setup;typeof r=="object"&&r!==null?(t.bidiGenerateContentSetup=r,n=r):delete t.bidiGenerateContentSetup}else i!==void 0&&delete t.bidiGenerateContentSetup;let o=t.fieldMask;if(n){let r=dC(n);if(Array.isArray(e?.lockAdditionalFields)&&e?.lockAdditionalFields.length===0)r?t.fieldMask=r:delete t.fieldMask;else if(e?.lockAdditionalFields&&e.lockAdditionalFields.length>0&&o!==null&&Array.isArray(o)&&o.length>0){let a=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],u=[];o.length>0&&(u=o.map(d=>a.includes(d)?`generationConfig.${d}`:d));let c=[];r&&c.push(r),u.length>0&&c.push(...u),c.length>0?t.fieldMask=c.join(","):delete t.fieldMask}else delete t.fieldMask}else o!==null&&Array.isArray(o)&&o.length>0?t.fieldMask=o.join(","):delete t.fieldMask;return t}var Qs=class extends it{constructor(e){super(),this.apiClient=e}async create(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let u=eC(this.apiClient,e);r=B("auth_tokens",u._url),a=u._query,delete u.config,delete u._url,delete u._query;let c=fC(u,e.config);return o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),o.then(d=>d)}}};function pC(t,e){let n={},i=s(t,["force"]);return e!==void 0&&i!=null&&l(e,["_query","force"],i),n}function hC(t){let e={},n=s(t,["name"]);n!=null&&l(e,["_url","name"],n);let i=s(t,["config"]);return i!=null&&pC(i,e),e}function mC(t){let e={},n=s(t,["name"]);return n!=null&&l(e,["_url","name"],n),e}function gC(t,e){let n={},i=s(t,["pageSize"]);e!==void 0&&i!=null&&l(e,["_query","pageSize"],i);let o=s(t,["pageToken"]);return e!==void 0&&o!=null&&l(e,["_query","pageToken"],o),n}function _C(t){let e={},n=s(t,["parent"]);n!=null&&l(e,["_url","parent"],n);let i=s(t,["config"]);return i!=null&&gC(i,e),e}function yC(t){let e={},n=s(t,["sdkHttpResponse"]);n!=null&&l(e,["sdkHttpResponse"],n);let i=s(t,["nextPageToken"]);i!=null&&l(e,["nextPageToken"],i);let o=s(t,["documents"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>a)),l(e,["documents"],r)}return e}var Zs=class extends it{constructor(e){super(),this.apiClient=e,this.list=async n=>new Et(yt.PAGED_ITEM_DOCUMENTS,i=>this.listInternal({parent:n.parent,config:i.config}),await this.listInternal(n),n)}async get(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=mC(e);return r=B("{name}",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json()),o.then(c=>c)}}async delete(e){var n,i;let o="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=hC(e);o=B("{name}",a._url),r=a._query,delete a._url,delete a._query,await this.apiClient.request({path:o,queryParams:r,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}}async listInternal(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=_C(e);return r=B("{parent}/documents",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json()),o.then(c=>{let d=yC(c),f=new Ss;return Object.assign(f,d),f})}}};var js=class extends it{constructor(e,n=new Zs(e)){super(),this.apiClient=e,this.documents=n,this.list=async(i={})=>new Et(yt.PAGED_ITEM_FILE_SEARCH_STORES,o=>this.listInternal(o),await this.listInternal(i),i)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async downloadMedia(e,n){if(this.apiClient.isVertexAI())throw new Error("This method is only supported in the Gemini Developer client.");let i=new URL(e,"http://dummy.com"),o=i.pathname;if(o.startsWith("/")&&(o=o.slice(1)),!o.includes("/media/"))throw new Error(`Invalid uri format: ${e}. Expected to contain /media/`);let r={};i.searchParams.forEach((c,d)=>{r[d]=c}),r.alt="media";let a=Object.assign({},n?.httpOptions),u=await this.apiClient.request({path:o,httpMethod:"GET",queryParams:r,httpOptions:a});if(u instanceof Mt){let c=await u.responseInternal.arrayBuffer();return new Uint8Array(c)}else throw new Error("Unexpected response type from downloadMedia")}async create(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=aA(this.apiClient,e);return r=B("fileSearchStores",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json()),o.then(c=>c)}}async get(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=cA(e);return r=B("{name}",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json()),o.then(c=>c)}}async delete(e){var n,i;let o="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let a=uA(e);o=B("{name}",a._url),r=a._query,delete a._url,delete a._query,await this.apiClient.request({path:o,queryParams:r,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}}async listInternal(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=gA(e);return r=B("fileSearchStores",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json()),o.then(c=>{let d=_A(c),f=new ws;return Object.assign(f,d),f})}}async uploadToFileSearchStoreInternal(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=yA(e);return r=B("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json()),o.then(c=>{let d=EA(c),f=new Rs;return Object.assign(f,d),f})}}async importFile(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=pA(e);return r=B("{file_search_store_name}:importFile",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json()),o.then(c=>{let d=fA(c),f=new Ps;return Object.assign(f,d),f})}}};function EC(){return"Deno"in globalThis}var Ui;function On(){var t,e,n,i,o,r;if(Ui)return Ui;let a=globalThis,u={};return EC()?u=(i=(n=(e=(t=a.Deno)===null||t===void 0?void 0:t.env)===null||e===void 0?void 0:e.toObject)===null||n===void 0?void 0:n.call(e))!==null&&i!==void 0?i:{}:u=(r=(o=a.process)===null||o===void 0?void 0:o.env)!==null&&r!==void 0?r:{},Ui=u,Ui}function vC(t){var e,n;let i=Object.assign({},t),o=On();return typeof o.GOOGLE_GENAI_API_VERSION<"u"&&((e=i.api_version)!==null&&e!==void 0||(i.api_version=o.GOOGLE_GENAI_API_VERSION)),typeof o.GOOGLE_GENAI_USER_PROJECT<"u"&&((n=i.user_project)!==null&&n!==void 0||(i.user_project=o.GOOGLE_GENAI_USER_PROJECT)),i}var ea=class{constructor(e){this.options=e}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(e){return IC(await this.options.getAuthHeaders(e))}},ta=class{beforeCreateRequest(e,n){return Object.assign(Object.assign({},n),{url:TC(n.url)})}async beforeRequest(e,n){if(Fd(n.headers,CC(e.security_source)),SC(e,n.headers),RC(n.headers))return n;let i=await AC(e.security_source,n.url);return Fd(n.headers,i?.default_headers),wC(n.headers,i),n}};function TC(t){let[,e,...n]=t.pathname.split("/");if(!e)return t;let i=decodeURIComponent(e);if(!i.includes("/"))return t;let o=new URL(t);return o.pathname=`/${i}/${n.join("/")}`,o}async function AC(t,e){if(Gf(t))return t.resolveGoogleGenAISecurity(e);let n=typeof t=="function"?await t():t;return Uf(n)?qd(n):qd(void 0)}function CC(t){var e,n;if(Gf(t))return(n=(e=t.getDefaultHeaders)===null||e===void 0?void 0:e.call(t))!==null&&n!==void 0?n:t.defaultHeaders;if(Uf(t))return t.default_headers}function qd(t){var e,n;let i=On(),o=Object.assign(Object.assign({},t),{api_key:(e=t?.api_key)!==null&&e!==void 0?e:i.GOOGLE_GENAI_API_KEY,access_token:(n=t?.access_token)!==null&&n!==void 0?n:i.GOOGLE_GENAI_ACCESS_TOKEN});return Lf(o)?o:void 0}function IC(t){var e,n;let i={};for(let[r,a]of t){let u=r.toLowerCase();u!=="authorization"&&u!=="x-goog-api-key"&&(i[r]=a)}let o={access_token:(e=t.get("authorization"))!==null&&e!==void 0?e:void 0,api_key:(n=t.get("x-goog-api-key"))!==null&&n!==void 0?n:void 0,default_headers:Object.keys(i).length?i:void 0};return Lf(o)?o:void 0}function Fd(t,e){if(e)for(let[n,i]of new Headers(e))t.get(n)===null&&t.set(n,i)}function SC(t,e){t.options.user_project!==void 0&&e.get("x-goog-user-project")===null&&e.set("x-goog-user-project",t.options.user_project)}function wC(t,e){if(e){if(e.api_key){t.set("x-goog-api-key",e.api_key);return}e.access_token&&t.set("Authorization",PC(e.access_token))}}function RC(t){return t.get("authorization")!==null||t.get("x-goog-api-key")!==null}function PC(t){return t.slice(0,7).toLowerCase()==="bearer "?t:`Bearer ${t}`}function Uf(t){return typeof t=="object"&&t!==null}function Gf(t){return typeof t=="object"&&t!==null&&"resolveGoogleGenAISecurity"in t&&typeof t.resolveGoogleGenAISecurity=="function"}function Lf(t){return t.api_key!==void 0||t.access_token!==void 0||t.default_headers!==void 0}var Ut=class extends Error{constructor(e,n){let i=e;n?.cause&&(i+=`: ${n.cause}`),super(i,n),this.name="HTTPClientError",typeof this.cause>"u"&&(this.cause=n?.cause)}},eo=class extends Ut{constructor(){super(...arguments),this.name="UnexpectedClientError"}},cn=class extends Ut{constructor(){super(...arguments),this.name="InvalidRequestError"}},to=class extends Ut{constructor(){super(...arguments),this.name="RequestAbortedError"}},no=class extends Ut{constructor(){super(...arguments),this.name="RequestTimeoutError"}},io=class extends Ut{constructor(){super(...arguments),this.name="ConnectionError"}};var Qe=class extends Error{constructor(e,n){var i,o,r,a;super(e),this.statusCode=(i=n?.response)===null||i===void 0?void 0:i.status,this.body=(o=n?.body)!==null&&o!==void 0?o:"",this.headers=(r=n?.response)===null||r===void 0?void 0:r.headers,this.contentType=((a=n?.response)===null||a===void 0?void 0:a.headers.get("content-type"))||"",this.rawResponse=n?.response,this.name="GoogleGenAiError"}};var na=class extends Error{},be=class t extends na{constructor(e,n,i,o){super(t.makeMessage(e,n,i)),this.status=e,this.headers=o,this.error=n,this.statusCode=e,this.body=Vd(n),this.contentType=o?.get("content-type")||"",this.rawResponse=void 0,this.cause=void 0,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}static makeMessage(e,n,i){var o;let r=n&&xC(n)&&typeof n.message=="string"?n.message:void 0,a=Vd(n),u=(o=r??i)!==null&&o!==void 0?o:a||"An error occurred";return`${e?`${e} `:""}${u}`}static generate(e,n,i,o){return!e||!o?new gn({message:i,cause:n instanceof Error?n:void 0}):e===400?new ra(e,n,i,o):e===401?new sa(e,n,i,o):e===403?new aa(e,n,i,o):e===404?new la(e,n,i,o):e===409?new ua(e,n,i,o):e===422?new ca(e,n,i,o):e===429?new da(e,n,i,o):e>=500?new fa(e,n,i,o):new t(e,n,i,o)}},ia=class extends be{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},gn=class extends be{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),this.cause=n}},oa=class extends gn{constructor({message:e}={}){super({message:e||"Request timed out. This is a client-side timeout. You can increase the timeout by setting the `timeout` argument in your request or client http options."})}},ra=class extends be{},sa=class extends be{},aa=class extends be{},la=class extends be{},ua=class extends be{},ca=class extends be{},da=class extends be{},fa=class extends be{};function dn(t){return MC(t)?t:t instanceof Qe?NC(t):t instanceof Ut?kC(t):t}function NC(t){let e=DC(t),n=be.generate(t.statusCode,e,t.message,t.headers);return Gn(n,"body",t.body),Gn(n,"contentType",t.contentType),Gn(n,"rawResponse",t.rawResponse),Gn(n,"statusCode",t.statusCode),Gn(n,"cause",t),n}function kC(t){return t instanceof no?new oa({message:t.message}):t instanceof to?new ia({message:t.message}):t instanceof io?new gn({message:t.message,cause:t}):new gn({message:t.message,cause:t})}function DC(t){let e=Hd(t,"data$");if(e&&typeof e=="object")return e;try{let i=JSON.parse(t.body);if(i&&typeof i=="object")return i}catch{}let n=Hd(t,"error");return n&&typeof n=="object"?n:void 0}function Hd(t,e){return t&&typeof t=="object"?t[e]:void 0}function Vd(t){if(!t)return"";try{return JSON.stringify(t)}catch{return String(t)}}function xC(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function MC(t){return typeof t=="object"&&t!==null?be.prototype.isPrototypeOf(t):!1}function Gn(t,e,n){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n,writable:!1})}function UC(t){let e=new ta;t.registerBeforeCreateRequestHook(e),t.registerBeforeRequestHook(e)}var oo=class{constructor(){this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[];let e=[];for(let n of e)"sdkInit"in n&&this.registerSDKInitHook(n),"beforeCreateRequest"in n&&this.registerBeforeCreateRequestHook(n),"beforeRequest"in n&&this.registerBeforeRequestHook(n),"afterSuccess"in n&&this.registerAfterSuccessHook(n),"afterError"in n&&this.registerAfterErrorHook(n);UC(this)}registerSDKInitHook(e){this.sdkInitHooks.push(e)}registerBeforeCreateRequestHook(e){this.beforeCreateRequestHooks.push(e)}registerBeforeRequestHook(e){this.beforeRequestHooks.push(e)}registerAfterSuccessHook(e){this.afterSuccessHooks.push(e)}registerAfterErrorHook(e){this.afterErrorHooks.push(e)}sdkInit(e){return this.sdkInitHooks.reduce((n,i)=>i.sdkInit(n),e)}beforeCreateRequest(e,n){let i=n;for(let o of this.beforeCreateRequestHooks)i=o.beforeCreateRequest(e,i);return i}async beforeRequest(e,n){let i=n;for(let o of this.beforeRequestHooks)i=await o.beforeRequest(e,i);return i}async afterSuccess(e,n){let i=n;for(let o of this.afterSuccessHooks)i=await o.afterSuccess(e,i);return i}async afterError(e,n,i){let o=n,r=i;for(let a of this.afterErrorHooks){let u=await a.afterError(e,o,r);o=u.response,r=u.error}return{response:o,error:r}}};function Bd(t){return{ok:!0,value:t}}function _t(t){return{ok:!1,error:t}}function Za(t){return btoa(String.fromCodePoint(...t))}function GC(t){return new TextEncoder().encode(t)}function LC(t){return Za(GC(t))}var bC=Object.prototype.hasOwnProperty;function de(t,e){let n=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(o={}){return t.replace(n,function(r,a){if(!bC.call(o,a))throw new Error(`Parameter '${a}' is required`);let u=o[a];if(typeof u!="string"&&typeof u!="number")throw new Error(`Parameter '${a}' must be a string or number`);return`${u}`}).replace(/^\/+/,"")}}var $d=["https://generativelanguage.googleapis.com"];function OC(t){var e;let n=t.server_url,i={};if(!n){let r=(e=t.server_idx)!==null&&e!==void 0?e:0;if(r<0||r>=$d.length)throw new Error(`Invalid server index ${r}`);n=$d[r]||""}let o=de(n)(i);return new URL(o)}var qC={userAgent:"speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai"};function FC(...t){let e=[];for(let n of t)n&&e.push(n);switch(e.length){case 0:case 1:return e[0]||null;default:return"any"in AbortSignal&&typeof AbortSignal.any=="function"?AbortSignal.any(e):HC(e)}}function HC(t){let e=new AbortController,n=e.signal;if(!t.length)return e.signal;if(t.length===1)return t[0]||e.signal;for(let a of t)if(a.aborted)return a;function i(){e.abort(this.reason),r()}let o=[];function r(){for(let a of o){let u=a.deref();u&&u.removeEventListener("abort",i)}}for(let a of t)o.push(new WeakRef(a)),a.addEventListener("abort",i);return n}function pe(t){let e={};for(let[n,i]of Object.entries(t))typeof i<"u"&&(e[n]=i);return e}function Gt(t){if(t===null||typeof t!="object"||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);if(e===null||e===Object.prototype)return!0;try{return Object.getPrototypeOf(e)===null}catch{return!1}}function VC(t){return(e,n,i)=>{let o="",r=i?.explode?Of(e,n):[[e,n]];if(r.every(([d,f])=>f==null))return;let a=d=>i?.charEncoding==="percent"?encodeURIComponent(d):d,u=d=>a(qf(d)),c=a(t);return r.forEach(([d,f])=>{var p,h;let m="",_=null;f!=null&&(Array.isArray(f)?_=(p=Hf(f,g=>`${u(g)}`))===null||p===void 0?void 0:p.join(c):Gt(f)?_=(h=Vf(Object.entries(f),([g,v])=>`${a(g)}${c}${u(v)}`))===null||h===void 0?void 0:h.join(c):_=`${u(f)}`,_!=null&&(m=`${a(d)}=${_}`,!(!m||m==="=")&&(o+=`&${m}`)))}),o.slice(1)}}var bf=VC(",");function At(t,e,n){if(typeof e>"u")return;let i=r=>n?.charEncoding==="percent"?encodeURIComponent(r):r,o=i(JSON.stringify(e,Ff));return n?.explode?o:`${i(t)}=${o}`}var j=(t,e,n)=>{let i="",o=n?.explode?Of(t,e):[[t,e]];if(o.every(([u,c])=>c==null))return;let r=u=>n?.charEncoding==="percent"?encodeURIComponent(u):u,a=u=>r(qf(u));return o.forEach(([u,c])=>{var d;let f="";if(c!=null){if(Array.isArray(c))f=(d=Hf(c,p=>`${a(p)}`))===null||d===void 0?void 0:d.join(",");else if(Gt(c)){let p=Vf(Object.entries(c),([h,m])=>`,${r(h)},${a(m)}`);f=p?.join("").slice(1)}else f=`${n?.explode&&Gt(e)?`${u}=`:""}${a(c)}`;i+=f?`,${f}`:""}}),i.slice(1)};function Of(t,e){return Array.isArray(e)?e.map(n=>[t,n]):Gt(e)?Object.entries(e??{}).map(([i,o])=>[i,o]):[[t,e]]}function qf(t){return t==null?"":t instanceof Date?t.toISOString():t instanceof Uint8Array?Za(t):typeof t=="object"?JSON.stringify(t,Ff):`${t}`}function Ff(t,e){return e instanceof Uint8Array?Za(e):e}function Hf(t,e){let n=t.reduce((i,o)=>{if(o==null)return i;let r=e(o);return r==null||i.push(r),i},[]);return n.length?n:null}function Vf(t,e){let n=[];for(let[i,o]of t){if(o==null)continue;let r=e([i,o]);r!=null&&n.push(r)}return n.length?n:null}function BC(...t){return t.filter(Boolean).join("&")}function $C(t){return function(n,i){var o,r,a;let u=Object.assign(Object.assign({},i),{explode:(o=i?.explode)!==null&&o!==void 0?o:!0,charEncoding:(r=i?.charEncoding)!==null&&r!==void 0?r:"percent"}),c=new Set((a=i?.allowEmptyValue)!==null&&a!==void 0?a:[]),d=Object.entries(n).map(([f,p])=>c.has(f)&&(p==null||p===""||Array.isArray(p)&&p.length===0)?`${encodeURIComponent(f)}=`:t(f,p,u));return BC(...d)}}var Ot=$C(bf);var JC=(t,e)=>e==null?fetch(t):fetch(t,e),pa=class t{constructor(e={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=e,this.fetcher=e.fetcher||JC}async request(e){let n=e;for(let i of this.requestHooks){let o=await i(n);o&&(n=o)}try{let i=await this.fetcher(n);for(let o of this.responseHooks)await o(i,n);return i}catch(i){for(let o of this.requestErrorHooks)await o(i,n);throw i}}addHook(...e){if(e[0]==="beforeRequest")this.requestHooks.push(e[1]);else if(e[0]==="requestError")this.requestErrorHooks.push(e[1]);else if(e[0]==="response")this.responseHooks.push(e[1]);else throw new Error(`Invalid hook type: ${e[0]}`);return this}removeHook(...e){let n;if(e[0]==="beforeRequest")n=this.requestHooks;else if(e[0]==="requestError")n=this.requestErrorHooks;else if(e[0]==="response")n=this.responseHooks;else throw new Error(`Invalid hook type: ${e[0]}`);let i=n.findIndex(o=>o===e[1]);return i>=0&&n.splice(i,1),this}clone(){let e=new t(this.options);return e.requestHooks=this.requestHooks.slice(),e.requestErrorHooks=this.requestErrorHooks.slice(),e.responseHooks=this.responseHooks.slice(),e}},Jd=/\s*;\s*/g;function ln(t,e){var n;if(e==="*")return!0;let i=((n=t.headers.get("content-type"))===null||n===void 0?void 0:n.trim())||"application/octet-stream";i=i.toLowerCase();let o=e.toLowerCase().trim().split(Jd),[r="",...a]=o;if(r.split("/").length!==2)return!1;let u=i.split(Jd),[c="",...d]=u,[f="",p=""]=c.split("/");if(!f||!p||r!=="*/*"&&c!==r&&`${f}/*`!==r&&`*/${p}`!==r||d.length<a.length)return!1;let h=new Set(d);for(let m of a)if(!h.has(m))return!1;return!0}var XC=new RegExp("^[0-9]xx$","i");function le(t,e){let n=`${t.status}`,i=Array.isArray(e)?e:[e];return i.length?i.some(o=>{let r=`${o}`;if(r==="default")return!0;if(!XC.test(`${r}`))return r===n;let a=r.charAt(0);if(!a)throw new Error("Invalid status code range");let u=n.charAt(0);if(!u)throw new Error(`Invalid response status code: ${n}`);return u===a}):!1}function KC(t,e,n){return le(t,e)&&ln(t,n)}function Bf(t){if(typeof t!="object"||t==null)return!1;let e=t instanceof TypeError&&t.message.toLowerCase().startsWith("failed to fetch"),n=t instanceof TypeError&&t.message.toLowerCase().startsWith("fetch failed"),i="name"in t&&t.name==="ConnectionError",o="code"in t&&typeof t.code=="string"&&t.code.toLowerCase()==="econnreset";return e||n||o||i}function $f(t){if(typeof t!="object"||t==null)return!1;let e="name"in t&&t.name==="TimeoutError",n="code"in t&&t.code===23,i="code"in t&&typeof t.code=="string"&&t.code.toLowerCase()==="econnaborted";return e||n||i}function YC(t){if(typeof t!="object"||t==null)return!1;let e="name"in t&&t.name==="AbortError",n="code"in t&&t.code===20,i="code"in t&&typeof t.code=="string"&&t.code.toLowerCase()==="econnaborted";return e||n||i}var Xd={initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5},qn=class t extends Error{constructor(e,n){let i=e;n?.cause&&(i+=`: ${n.cause}`),super(i,n),this.name="PermanentError",typeof this.cause>"u"&&(this.cause=n?.cause),Object.setPrototypeOf(this,t.prototype)}},Lt=class t extends Error{constructor(e,n){super(e),this.response=n,this.name="TemporaryError",Object.setPrototypeOf(this,t.prototype)}};async function WC(t,e){var n;switch(e.config.strategy){case"backoff":return ZC(Kd(t,{statusCodes:e.statusCodes,retryConnectionErrors:!!e.config.retryConnectionErrors}),(n=e.config.backoff)!==null&&n!==void 0?n:Xd);case"attempt-count-backoff":return jC(Kd(t,{statusCodes:e.statusCodes,retryConnectionErrors:!!e.config.retryConnectionErrors}),Object.assign(Object.assign({},Xd),e.config.backoff),e.config);default:return await t(0)}}function Kd(t,e){return async n=>{try{let i=await t(n);if(QC(i,e.statusCodes))throw new Lt("Response failed with retryable status code",i);return i}catch(i){throw i instanceof Lt||e.retryConnectionErrors&&($f(i)||Bf(i))?i:new qn("Permanent error",{cause:i})}}}var zC=new RegExp("^[0-9]xx$","i");function QC(t,e){let n=`${t.status}`;return e.some(i=>{if(!zC.test(i))return i===n;let o=i.charAt(0);if(!o)throw new Error("Invalid status code range");let r=n.charAt(0);if(!r)throw new Error(`Invalid response status code: ${n}`);return r===o})}async function ZC(t,e){let{maxElapsedTime:n,initialInterval:i,exponent:o,maxInterval:r}=e,a=Date.now(),u=0;for(;;)try{return await t(u)}catch(c){if(c instanceof qn)throw c.cause;if(Date.now()-a>n){if(c instanceof Lt)return c.response;throw c}let f=0;c instanceof Lt&&(f=Jf(c.response)),f<=0&&(f=i*Math.pow(u,o)+Math.random()*1e3);let p=Math.min(f,r);await Xf(p),u++}}async function jC(t,e,n){let i=0;for(;;)try{return await t(i)}catch(o){if(o instanceof qn)throw o.cause;if(i>=n.maxRetries){if(o instanceof Lt)return o.response;throw o}let r=0;o instanceof Lt&&(r=Jf(o.response)),r<=0&&(r=e.initialInterval*Math.pow(e.exponent,i)*(1-Math.random()*.25));let a=Math.min(r,e.maxInterval);await Xf(a),i++}}function Jf(t){let e=t.headers.get("retry-after-ms");if(e){let r=Number(e);if(Number.isFinite(r)&&r>=0)return r}let n=t.headers.get("retry-after")||"";if(!n)return 0;let i=Number(n);if(Number.isInteger(i))return i*1e3;let o=Date.parse(n);if(Number.isInteger(o)){let r=o-Date.now();return r>0?Math.ceil(r):0}return 0}async function Xf(t){return new Promise(e=>setTimeout(e,t))}var Gi=typeof globalThis>"u"?null:globalThis,eI=typeof Gi=="object"&&Gi!=null&&"importScripts"in Gi&&typeof Gi.importScripts=="function",tI=eI||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u",vt=class{constructor(e={}){let n=e;typeof n=="object"&&n!=null&&"hooks"in n&&n.hooks instanceof oo?this._hooks=n.hooks:this._hooks=new oo;let i=new pa;e.http_client=e.http_client||i,e=this._hooks.sdkInit(e);let o=OC(e);o&&(o.pathname=o.pathname.replace(/\/+$/,"")+"/"),this._baseURL=o,this._httpClient=e.http_client||i,this._options=Object.assign(Object.assign({},vC(e)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&On().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(e,n,i){var o,r,a,u,c;let{method:d,path:f,query:p,headers:h,security:m}=n,_=(o=n.baseURL)!==null&&o!==void 0?o:this._baseURL;if(!_)return _t(new cn("No base URL provided for operation"));let g=new URL(_),v;f?(g.pathname=g.pathname.replace(/\/+$/,"")+"/",v=new URL(f,g),!v.search&&g.search&&(v.search=g.search)):v=g,v.hash="";let y=(D,K)=>{if(!K)return D;let Z=new Set(K.split("&").filter(Re=>Re!=="").map(Re=>{var Te;return(Te=Re.split("=")[0])!==null&&Te!==void 0?Te:""}));return[...D.split("&").filter(Re=>{var Te;return Re!==""&&!Z.has((Te=Re.split("=")[0])!==null&&Te!==void 0?Te:"")}),K].join("&")},A=D=>Object.entries(D).map(([K,Z])=>{if(Z==null)return;let Ee=Gt(Z)?JSON.stringify(Z):Z;return bf(K,Ee,{explode:Array.isArray(Ee),charEncoding:"percent"})}).filter(K=>typeof K<"u").join("&"),C=[p||"",A(i?.extra_query||{}),A(m?.queryParams||{})].reduce(y,v.search.slice(1));C&&(v.search=`?${C}`);let S=new Headers(h),R=m?.basic.username,L=m?.basic.password;if(R!=null||L!=null){let D=LC([R||"",L||""].join(":"));S.set("Authorization",`Basic ${D}`)}let O=new Headers(m?.headers||{});for(let[D,K]of O)S.set(D,K);let H=S.get("cookie")||"";for(let[D,K]of Object.entries(m?.cookies||{}))H+=`; ${D}=${K}`;H=H.startsWith("; ")?H.slice(2):H,S.set("cookie",H);let U=new Headers((r=i?.headers)!==null&&r!==void 0?r:(a=i?.fetch_options)===null||a===void 0?void 0:a.headers);for(let[D,K]of U)S.set(D,K);tI||S.set((u=n.uaHeader)!==null&&u!==void 0?u:"user-agent",(c=n.userAgent)!==null&&c!==void 0?c:qC.userAgent);let F=n.body,J=Object.fromEntries(Object.entries(i?.extra_body||{}).filter(([,D])=>typeof D<"u"));if(Object.keys(J).length>0){let D=new Headers(h).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(D)||typeof F!="string"&&F!=null)return _t(new cn("extra_body can only be merged into JSON object request bodies"));let Z;try{Z=F?JSON.parse(F):{}}catch(Ee){return _t(new cn("extra_body can only be merged into JSON object request bodies",{cause:Ee}))}if(!Gt(Z))return _t(new cn("extra_body can only be merged into JSON object request bodies"));F=JSON.stringify(Object.assign(Object.assign({},Z),J)),S.delete("content-length")}let Q=Object.assign(Object.assign({},i?.fetch_options),i);!Q?.signal&&n.timeout_ms!=null&&n.timeout_ms>0&&(e.timeout_ms=n.timeout_ms),n.body instanceof ReadableStream&&Object.assign(Q,{duplex:"half"});let te;try{te=this._hooks.beforeCreateRequest(e,{url:v,options:Object.assign(Object.assign({},Q),{body:F??null,headers:S,method:d})})}catch(D){return _t(new eo("Create request hook failed to execute",{cause:D}))}return Bd(new Request(te.url,te.options))}async _do(e,n){let{context:i,isErrorStatusCode:o}=n,r=i.timeout_ms;return WC(async()=>{var a;let u=e.clone(),c=u;if(r!=null&&r>0){let p=AbortSignal.timeout(r),h=(a=FC(u.signal,p))!==null&&a!==void 0?a:p;c=new Request(u,{signal:h})}let d=await this._hooks.beforeRequest(i,c);await nI(this._logger,d).catch(p=>{var h;return(h=this._logger)===null||h===void 0?void 0:h.log("Failed to log request:",p)});let f=await this._httpClient.request(d);try{if(o(f.status)){let p=await this._hooks.afterError(i,f,null);if(p.error)throw p.error;f=p.response||f}else f=await this._hooks.afterSuccess(i,f)}finally{await iI(this._logger,f,d).catch(p=>{var h;return(h=this._logger)===null||h===void 0?void 0:h.log("Failed to log response:",p)})}return f},{config:n.retryConfig,statusCodes:n.retryCodes}).then(a=>Bd(a),a=>{switch(!0){case YC(a):return _t(new to("Request aborted by client",{cause:a}));case $f(a):return _t(new no("Request timed out",{cause:a}));case Bf(a):return _t(new io("Unable to make request",{cause:a}));default:return _t(new eo("Unexpected HTTP client error",{cause:a}))}})}},Kf=/^(application|text)\/([^+]+\+)*json.*/,Yd=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;async function nI(t,e){if(!t)return;let n=e.headers.get("content-type"),i=n?.split(";")[0]||"";t.group(`> Request: ${e.method} ${e.url}`),t.group("Headers:");for(let[o,r]of e.headers.entries())t.log(`${o}: ${r}`);switch(t.groupEnd(),t.group("Body:"),!0){case Kf.test(i):t.log(await e.clone().json());break;case i.startsWith("text/"):t.log(await e.clone().text());break;case i==="multipart/form-data":{let o=await e.clone().formData();for(let[r,a]of o){let u=a instanceof Blob?"<Blob>":a;t.log(`${r}: ${u}`)}break}default:t.log(`<${n}>`);break}t.groupEnd(),t.groupEnd()}async function iI(t,e,n){if(!t)return;let i=e.headers.get("content-type"),o=i?.split(";")[0]||"";t.group(`< Response: ${n.method} ${n.url}`),t.log("Status Code:",e.status,e.statusText),t.group("Headers:");for(let[r,a]of e.headers.entries())t.log(`${r}: ${a}`);switch(t.groupEnd(),t.group("Body:"),!0){case(ln(e,"application/json")||Kf.test(o)&&!Yd.test(o)):t.log(await e.clone().json());break;case(ln(e,"application/jsonl")||Yd.test(o)):case ln(e,"text/event-stream"):t.log(`<${i}>`);break;case ln(e,"text/*"):t.log(await e.clone().text());break;case ln(e,"multipart/form-data"):{let r=await e.clone().formData();for(let[a,u]of r){let c=u instanceof Blob?"<Blob>":u;t.log(`${a}: ${c}`)}break}default:t.log(`<${i}>`);break}t.groupEnd(),t.groupEnd()}var ro=class extends Qe{constructor(e,n){e&&(e+=": "),e+=`Status ${n.response.status}`;let i=n.response.headers.get("content-type")||'""';i!=="application/json"&&(e+=` Content-Type ${i.includes(" ")?`"${i}"`:i}`);let o=n.body||'""';e+=o.length>100?`
36
- `:". ";let r=o;if(o.length>1e4){let a=o.substring(0,1e4),u=o.length-1e4;r=`${a}...and ${u} more chars`}e+=`Body: ${r}`,e=e.trim(),super(e,n),this.name="GoogleGenAiDefaultError"}};function Wd(t){try{return JSON.parse(t)}catch{return t}}function oI(t,e={}){var n,i;let o=e.flattened===!0,r=(n=e.sentinel)!==null&&n!==void 0?n:"";return new ha(t,a=>r!==""&&a.data===r?{done:!0,value:void 0}:o?{done:!1,value:a.data==null?void 0:Wd(a.data)}:{done:!1,value:Object.assign(Object.assign({},a),{data:a.data==null?a.data:Wd(a.data)})},{dataRequired:(i=e.dataRequired)!==null&&i!==void 0?i:!0})}var ha=class extends ReadableStream{constructor(e,n,i){var o;let r=e.getReader(),a=new Uint8Array(4096),u=0,c=0,d={eventId:void 0},f=(o=i?.dataRequired)!==null&&o!==void 0?o:!0;super({async pull(p){try{for(;;){let h=sI(a,u,c);if(!h){c=Math.max(0,u-rI+1);let g=await r.read();if(g.done)return p.close();if(u+g.value.length>a.length){let v=new Uint8Array(Math.max(a.length*2,u+g.value.length));v.set(a.subarray(0,u)),a=v}a.set(g.value,u),u+=g.value.length;continue}let m=a.slice(0,h.index);if(a.copyWithin(0,h.index+h.length,u),u-=h.index+h.length,a.length>4096&&u<=a.length>>2){let g=new Uint8Array(Math.max(4096,u*2));g.set(a.subarray(0,u)),a=g}c=0;let _=aI(m,n,d,f);if(_&&!_.done)return p.enqueue(_.value);if(_?.done)return await r.cancel("done"),p.close()}}catch(h){p.error(h),await r.cancel(h)}},cancel:p=>r.cancel(p)})}[Symbol.asyncIterator](e){let n=ReadableStream.prototype[Symbol.asyncIterator];if(typeof n=="function")return n.call(this,e);let i=this.getReader(),o={next:async()=>{let a=await i.read();return a.done?(i.releaseLock(),{done:!0,value:void 0}):{done:!1,value:a.value}},throw:async a=>(await i.cancel(a),i.releaseLock(),{done:!0,value:void 0}),return:async()=>(await i.cancel("done"),i.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},r=Symbol.asyncDispose;return r&&(o[r]=async()=>{var a;await((a=o.return)===null||a===void 0?void 0:a.call(o))}),o}values(e){return this[Symbol.asyncIterator](e)}},We=13,ze=10,Yf=[[We,ze,We,ze],[We,ze,We],[We,ze,ze],[We,We,ze],[ze,We,ze],[We,We],[ze,We],[ze,ze]],rI=Yf.reduce((t,e)=>Math.max(t,e.length),0);function sI(t,e,n){for(let i=n;i<e;i++)if(!(t[i]!==We&&t[i]!==ze))for(let o of Yf){if(i+o.length>e)continue;let r=!0;for(let a=0;a<o.length;a++)if(t[i+a]!==o[a]){r=!1;break}if(r)return{index:i,length:o.length}}return null}function aI(t,e,n,i){let r=new TextDecoder().decode(t).split(/\r\n|\r|\n/),a=[],u={},c=!0;for(let d of r){if(!d||d.startsWith(":"))continue;c=!1;let f=d.indexOf(":"),p=d,h="";f>0&&(p=d.slice(0,f),h=d[f+1]===" "?d.slice(f+2):d.slice(f+1)),p==="data"?a.push(h):p==="event"?u.event=h:p==="id"&&!h.includes("\0")?n.eventId=h:p==="retry"&&/^\d+$/.test(h)&&(u.retry=Number(h))}if(!c){if(u.id=n.eventId,a.length)u.data=a.join(`
37
- `);else if(i)return;return e(u)}}var lI={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function bt(t,e,n){return Object.assign(Object.assign({},n),{err:!0,enc:"json",codes:t,errorClass:e})}function ye(t,e){return Object.assign(Object.assign({},e),{enc:"json",codes:t})}function Wf(t,e,n){return Object.assign(Object.assign(Object.assign({},n),{enc:"sse",codes:t}),e?{sse:e}:{})}function uI(t,e){return Object.assign(Object.assign({},e),{enc:"nil",codes:t})}function ee(t){return{enc:"fail",codes:t}}function he(...t){return async function(n,i,o){let r,a;for(let h of t){let{codes:m}=h,_="ctype"in h?h.ctype:lI[h.enc];if(_&&KC(n,m,_)){a=h;break}else if(!_&&le(n,m)){a=h;break}}if(!a)return[{ok:!1,error:new ro("Unexpected Status or Content-Type",{response:n,request:i,body:await n.text().catch(()=>"")})},r];let u=a.enc,c="";switch(u){case"json":c=await n.text();try{r=JSON.parse(c)}catch(h){if(!("err"in a))throw h;r=c}break;case"jsonl":r=n.body;break;case"bytes":r=new Uint8Array(await n.arrayBuffer());break;case"stream":r=n.body;break;case"text":c=await n.text(),r=c;break;case"sse":if(n.body){let h="sse"in a&&a.sse||{};r=oI(n.body,h)}else r=null;break;case"nil":c=await n.text(),r=void 0;break;case"fail":c=await n.text(),r=c;break;default:throw new Error(`Unsupported response type: ${u}`)}if(a.enc==="fail")return[{ok:!1,error:new ro("API error occurred",{request:i,response:n,body:c})},r];let d=a.key||o?.resultKey,f,p=a.hdrs?{headers:dI(n.headers)}:null;return"err"in a?f=Object.assign(Object.assign(Object.assign({},o?.extraFields),p),Gt(r)?r:null):d?f=Object.assign(Object.assign(Object.assign({},o?.extraFields),p),{[d]:r}):a.hdrs?f=Object.assign(Object.assign(Object.assign({},o?.extraFields),p),Gt(r)?r:null):f=r,"err"in a?[{ok:!1,error:a.errorClass?new a.errorClass(f,{request:i,response:n,body:c}):f},r]:[{ok:!0,value:f},r]}}var cI=/, */;function dI(t){let e={};for(let[n,i]of t.entries())e[n]=i.split(cI);return e}var zd={Incomplete:"incomplete",UnrecognisedSecurityType:"unrecognized_security_type"},ma=class t extends Error{constructor(e,n){super(n),this.code=e,this.name="SecurityError"}static incomplete(){return new t(zd.Incomplete,"Security requirements not met in order to perform the operation")}static unrecognizedType(e){return new t(zd.UnrecognisedSecurityType,`Unrecognised security type: ${e}`)}};function fI(...t){let e={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},n=t.find(i=>i.every(o=>{if(o.value==null)return!1;if(o.type==="http:basic")return o.value.username!=null||o.value.password!=null;if(o.type==="http:custom")return null;if(o.type==="oauth2:password")return typeof o.value=="string"&&!!o.value;if(o.type==="oauth2:client_credentials")return typeof o.value=="string"?!!o.value:o.value.client_id!=null||o.value.client_secret!=null;if(typeof o.value=="string")return!!o.value;throw new Error(`Unrecognized security type: ${o.type} (value type: ${typeof o.value})`)}));return n==null?null:(n.forEach(i=>{if(i.value==null)return;let{type:o}=i;switch(o){case"apiKey:header":e.headers[i.fieldName]=i.value;break;case"apiKey:query":e.queryParams[i.fieldName]=i.value;break;case"apiKey:cookie":e.cookies[i.fieldName]=i.value;break;case"http:basic":pI(e,i);break;case"http:custom":break;case"http:bearer":Li(e,i);break;case"oauth2":Li(e,i);break;case"oauth2:password":Li(e,i);break;case"oauth2:client_credentials":break;case"openIdConnect":Li(e,i);break;default:throw ma.unrecognizedType(o)}}),e)}function pI(t,e){e.value!=null&&(t.basic=e.value)}function Li(t,e){if(typeof e.value!="string"||!e.value)return;let n=e.value;n.slice(0,7).toLowerCase()!=="bearer "&&(n=`Bearer ${n}`),e.fieldName!==void 0&&(t.headers[e.fieldName]=n)}function me(t,e){var n,i;let o=[[{fieldName:"accessToken",type:"http:custom",value:(n=t?.access_token)!==null&&n!==void 0?n:On().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:(i=t?.api_key)!==null&&i!==void 0?i:On().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:t?.default_headers}]];return fI(...o)}async function ge(t){if(t!=null)return typeof t=="function"?t():t}var zf,se=class t{constructor(e,n){this[zf]="APIPromise",this._promise=e instanceof Promise?e:Promise.resolve(e),this._unwrapped=e instanceof Promise?null:Promise.resolve(e[0]),this._callSource=n??null}_getUnwrapped(){var e;return(e=this._unwrapped)!==null&&e!==void 0?e:this._unwrapped=this._promise.then(([n])=>n)}then(e,n){return this._promise.then(e?([i])=>e(i):void 0,n)}catch(e){return this._getUnwrapped().catch(e)}finally(e){return this._getUnwrapped().finally(e)}$inspect(){return this._promise}asResponse(){var e;return((e=this._callSource)!==null&&e!==void 0?e:this._callSource=this._promise.then(([,i])=>i)).then(i=>{if(!i.response)throw new Error("APIPromise.asResponse: response unavailable");return i.response})}async withResponse(){let[[e],n]=await Promise.all([this._promise,this.asResponse()]);return{data:e,response:n}}_thenUnwrap(e){var n;let i=this._promise.then(([o,r])=>[e(o),r]);return i.catch(()=>{}),new t(i,(n=this._callSource)!==null&&n!==void 0?n:void 0)}};zf=Symbol.toStringTag;function fe(t){let e=t.$inspect(),n=e.then(([o,r])=>{if(!o.ok)throw o.error;return[o.value,r]}),i=e.then(([o,r])=>{var a;if(!o.ok&&!(!((a=r.response)===null||a===void 0)&&a.ok))throw o.error;return r});return n.catch(()=>{}),i.catch(()=>{}),new se(n,i)}function Qf(t,e,n,i){return new se(hI(t,e,n,i))}async function hI(t,e,n,i){var o,r,a;let c={body:e,api_version:n},d=At("body",c.body,{explode:!0}),f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/agents")(f),h=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"POST",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:R=>le({status:R},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,[S]=await he(ee("4XX"),ee("5XX"),ye("default"))(C,y);return S.ok?[S,{status:"complete",request:y,response:C}]:[S,{status:"complete",request:y,response:C}]}function Zf(t,e,n,i){return new se(mI(t,e,n,i))}async function mI(t,e,n,i){var o,r,a;let c={id:e,api_version:n},d=null,f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/agents/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"DELETE",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:R=>le({status:R},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,[S]=await he(ee("4XX"),ee("5XX"),ye("default"))(C,y);return S.ok?[S,{status:"complete",request:y,response:C}]:[S,{status:"complete",request:y,response:C}]}function jf(t,e,n,i){return new se(gI(t,e,n,i))}async function gI(t,e,n,i){var o,r,a;let c={id:e,api_version:n},d=null,f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/agents/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"GET",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:R=>le({status:R},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,[S]=await he(ee("4XX"),ee("5XX"),ye("default"))(C,y);return S.ok?[S,{status:"complete",request:y,response:C}]:[S,{status:"complete",request:y,response:C}]}function ep(t,e,n,i,o,r){return new se(_I(t,e,n,i,o,r))}async function _I(t,e,n,i,o,r){var a,u,c;let f={api_version:e,page_size:n,page_token:i,parent:o},p=null,h={api_version:j("api_version",(a=f?.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"})},m=de("/{api_version}/agents")(h),_=Ot({page_size:f?.page_size,page_token:f?.page_token,parent:f?.parent}),g=new Headers(pe({Accept:"application/json"})),v=await ge(t._options.security),y=me(v),A={options:t._options,base_url:(c=(u=r?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},C=t._createRequest(A,{security:y,method:"GET",baseURL:r?.server_url,path:m,headers:g,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!C.ok)return[C,{status:"invalid"}];let S=C.value,R=await t._do(S,{context:A,isErrorStatusCode:H=>le({status:H},["4XX","5XX"]),retryConfig:A.retry_config,retryCodes:A.retry_codes});if(!R.ok)return[R,{status:"request-error",request:S}];let L=R.value,[O]=await he(ee("4XX"),ee("5XX"),ye("default"))(L,S);return O.ok?[O,{status:"complete",request:S,response:L}]:[O,{status:"complete",request:S,response:L}]}var ga=class extends vt{list(e,n){return fe(ep(this,e?.api_version,e?.page_size,e?.page_token,e?.parent,n))}create(e,n){let{api_version:i}=e,o=Me(e,["api_version"]);return fe(Qf(this,o,i,n))}delete(e,n,i){return fe(Zf(this,e,n?.api_version,i))}get(e,n,i){return fe(jf(this,e,n?.api_version,i))}};function tp(t,e,n,i){return new se(yI(t,e,n,i))}async function yI(t,e,n,i){var o,r,a;let c={body:e,api_version:n},d=At("body",c.body,{explode:!0}),f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/environments")(f),h=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"POST",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:R=>le({status:R},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,[S]=await he(ee("4XX"),ee("5XX"),ye("default"))(C,y);return S.ok?[S,{status:"complete",request:y,response:C}]:[S,{status:"complete",request:y,response:C}]}function np(t,e,n,i){return new se(EI(t,e,n,i))}async function EI(t,e,n,i){var o,r,a;let c={id:e,api_version:n},d=null,f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/environments/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"DELETE",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:R=>le({status:R},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,[S]=await he(ee("4XX"),ee("5XX"),ye("default"))(C,y);return S.ok?[S,{status:"complete",request:y,response:C}]:[S,{status:"complete",request:y,response:C}]}function ip(t,e,n,i){return new se(vI(t,e,n,i))}async function vI(t,e,n,i){var o,r,a;let c={id:e,api_version:n},d=null,f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/environments/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"GET",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:R=>le({status:R},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,[S]=await he(ee("4XX"),ee("5XX"),ye("default"))(C,y);return S.ok?[S,{status:"complete",request:y,response:C}]:[S,{status:"complete",request:y,response:C}]}function op(t,e,n,i,o){return new se(TI(t,e,n,i,o))}async function TI(t,e,n,i,o){var r,a,u;let d={api_version:e,page_size:n,page_token:i},f=null,p={api_version:j("api_version",(r=d?.api_version)!==null&&r!==void 0?r:t._options.api_version,{explode:!1,charEncoding:"percent"})},h=de("/{api_version}/environments")(p),m=Ot({page_size:d?.page_size,page_token:d?.page_token}),_=new Headers(pe({Accept:"application/json"})),g=await ge(t._options.security),v=me(g),y={options:t._options,base_url:(u=(a=o?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:v,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},A=t._createRequest(y,{security:v,method:"GET",baseURL:o?.server_url,path:h,headers:_,query:m,body:f,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!A.ok)return[A,{status:"invalid"}];let C=A.value,S=await t._do(C,{context:y,isErrorStatusCode:O=>le({status:O},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!S.ok)return[S,{status:"request-error",request:C}];let R=S.value,[L]=await he(ee("4XX"),ee("5XX"),ye("default"))(R,C);return L.ok?[L,{status:"complete",request:C,response:R}]:[L,{status:"complete",request:C,response:R}]}function rp(t,e,n,i,o,r,a,u){return new se(AI(t,e,n,i,o,r,a,u))}async function AI(t,e,n,i,o,r,a,u){var c,d,f;let h={environment:e,path:n,api_version:i,page_size:o,page_token:r,recursive:a},m=null,_={api_version:j("api_version",(c=h.api_version)!==null&&c!==void 0?c:t._options.api_version,{explode:!1,charEncoding:"percent"}),environment:j("environment",h.environment,{explode:!1,charEncoding:"percent"}),path:j("path",h.path,{explode:!1,charEncoding:"percent"})},g=de("/{api_version}/environments/{environment}/files/{path}")(_),v=Ot({page_size:h.page_size,page_token:h.page_token,recursive:h.recursive}),y=new Headers(pe({Accept:"application/json"})),A=await ge(t._options.security),C=me(A),S={options:t._options,base_url:(f=(d=u?.server_url)!==null&&d!==void 0?d:t._baseURL)!==null&&f!==void 0?f:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:C,security_source:t._options.security,retry_config:u?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:u?.retry_codes||["408","409","429","5XX"]},R=t._createRequest(S,{security:C,method:"GET",baseURL:u?.server_url,path:g,headers:y,query:v,body:m,userAgent:t._options.user_agent,timeout_ms:u?.timeout_ms||t._options.timeout_ms||-1},u);if(!R.ok)return[R,{status:"invalid"}];let L=R.value,O=await t._do(L,{context:S,isErrorStatusCode:F=>le({status:F},["4XX","5XX"]),retryConfig:S.retry_config,retryCodes:S.retry_codes});if(!O.ok)return[O,{status:"request-error",request:L}];let H=O.value,[U]=await he(ye(200),ee("4XX"),ee("5XX"))(H,L);return U.ok?[U,{status:"complete",request:L,response:H}]:[U,{status:"complete",request:L,response:H}]}var _a=class extends vt{list(e,n,i,o){return fe(rp(this,e,n,i?.api_version,i?.page_size,i?.page_token,i?.recursive,o))}};var ya=class extends vt{get files(){var e;return(e=this._files)!==null&&e!==void 0?e:this._files=new _a(this._options)}listEnvironments(e,n){return fe(op(this,e?.api_version,e?.page_size,e?.page_token,n))}createEnvironment(e,n,i){return fe(tp(this,e,n,i))}deleteEnvironment(e,n,i){return fe(np(this,e,n?.api_version,i))}getEnvironment(e,n,i){return fe(ip(this,e,n?.api_version,i))}};var Ea=class extends Qe{constructor(e,n){var i;let o=((i=e.error)===null||i===void 0?void 0:i.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,n),this.data$=e,this.error=e.error,this.name="CancelInteractionByIdServerError"}},va=class extends Qe{constructor(e,n){var i;let o=((i=e.error)===null||i===void 0?void 0:i.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,n),this.data$=e,this.error=e.error,this.name="CancelInteractionByIdClientError"}};var Ta=class extends Qe{constructor(e,n){var i;let o=((i=e.error)===null||i===void 0?void 0:i.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,n),this.data$=e,this.error=e.error,this.name="CreateInteractionServerError"}},Aa=class extends Qe{constructor(e,n){var i;let o=((i=e.error)===null||i===void 0?void 0:i.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,n),this.data$=e,this.error=e.error,this.name="CreateInteractionClientError"}};var Ca=class extends Qe{constructor(e,n){var i;let o=((i=e.error)===null||i===void 0?void 0:i.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,n),this.data$=e,this.error=e.error,this.name="DeleteInteractionServerError"}},Ia=class extends Qe{constructor(e,n){var i;let o=((i=e.error)===null||i===void 0?void 0:i.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,n),this.data$=e,this.error=e.error,this.name="DeleteInteractionClientError"}};var Sa=class extends Qe{constructor(e,n){var i;let o=((i=e.error)===null||i===void 0?void 0:i.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,n),this.data$=e,this.error=e.error,this.name="GetInteractionByIdServerError"}},wa=class extends Qe{constructor(e,n){var i;let o=((i=e.error)===null||i===void 0?void 0:i.message)||`API error occurred: ${JSON.stringify(e)}`;super(o,n),this.data$=e,this.error=e.error,this.name="GetInteractionByIdClientError"}};function sp(t,e,n,i){return new se(CI(t,e,n,i))}async function CI(t,e,n,i){var o,r,a;let c={id:e,api_version:n},d=null,f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/interactions/{id}/cancel")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"POST",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:L=>le({status:L},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,S={httpMeta:{response:C,request:y}},[R]=await he(ye(200),bt("4XX",va),bt("5XX",Ea))(C,y,{extraFields:S});return R.ok?[R,{status:"complete",request:y,response:C}]:[R,{status:"complete",request:y,response:C}]}function ap(t,e,n,i){return new se(II(t,e,n,i))}async function II(t,e,n,i){var o,r,a,u;let c={body:e,api_version:n},d=c,f=At("body",d.body,{explode:!0}),p={api_version:j("api_version",(o=d.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"})},h=de("/{api_version}/interactions")(p),m=new Headers(pe({"Content-Type":"application/json",Accept:!((r=c?.body)===null||r===void 0)&&r.stream?"text/event-stream":"application/json"})),_=await ge(t._options.security),g=me(_),v={options:t._options,base_url:(u=(a=i?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:g,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(v,{security:g,method:"POST",baseURL:i?.server_url,path:h,headers:m,body:f,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!y.ok)return[y,{status:"invalid"}];let A=y.value,C=await t._do(A,{context:v,isErrorStatusCode:O=>le({status:O},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!C.ok)return[C,{status:"request-error",request:A}];let S=C.value,R={httpMeta:{response:S,request:A}},[L]=await he(ye(200),Wf(200,{sentinel:"[DONE]",flattened:!0}),bt("4XX",Aa),bt("5XX",Ta))(S,A,{extraFields:R});return L.ok?[L,{status:"complete",request:A,response:S}]:[L,{status:"complete",request:A,response:S}]}function SI(t,e,n,i){return new se(wI(t,e,n,i))}async function wI(t,e,n,i){var o,r,a;let c={id:e,api_version:n},d=null,f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/interactions/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"DELETE",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:L=>le({status:L},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,S={httpMeta:{response:C,request:y}},[R]=await he(uI(200),bt("4XX",Ia),bt("5XX",Ca))(C,y,{extraFields:S});return R.ok?[R,{status:"complete",request:y,response:C}]:[R,{status:"complete",request:y,response:C}]}function lp(t,e,n,i,o,r,a){return new se(RI(t,e,n,i,o,r,a))}async function RI(t,e,n,i,o,r,a){var u,c,d;let f={id:e,api_version:n,include_input:i,last_event_id:o,stream:r},p=f,h=null,m={api_version:j("api_version",(u=p.api_version)!==null&&u!==void 0?u:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",p.id,{explode:!1,charEncoding:"percent"})},_=de("/{api_version}/interactions/{id}")(m),g=Ot({include_input:p.include_input,last_event_id:p.last_event_id,stream:p.stream}),v=new Headers(pe({Accept:f?.stream?"text/event-stream":"application/json"})),y=await ge(t._options.security),A=me(y),C={options:t._options,base_url:(d=(c=a?.server_url)!==null&&c!==void 0?c:t._baseURL)!==null&&d!==void 0?d:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:A,security_source:t._options.security,retry_config:a?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:a?.retry_codes||["408","409","429","5XX"]},S=t._createRequest(C,{security:A,method:"GET",baseURL:a?.server_url,path:_,headers:v,query:g,body:h,userAgent:t._options.user_agent,timeout_ms:a?.timeout_ms||t._options.timeout_ms||-1},a);if(!S.ok)return[S,{status:"invalid"}];let R=S.value,L=await t._do(R,{context:C,isErrorStatusCode:F=>le({status:F},["4XX","5XX"]),retryConfig:C.retry_config,retryCodes:C.retry_codes});if(!L.ok)return[L,{status:"request-error",request:R}];let O=L.value,H={httpMeta:{response:O,request:R}},[U]=await he(ye(200),Wf(200,{sentinel:"[DONE]",flattened:!0}),bt("4XX",wa),bt("5XX",Sa))(O,R,{extraFields:H});return U.ok?[U,{status:"complete",request:R,response:O}]:[U,{status:"complete",request:R,response:O}]}var Ra=class extends vt{create(e,n){let{api_version:i}=e,o=Me(e,["api_version"]);return fe(ap(this,o,i,n))}delete(e,n,i){return fe(SI(this,e,n?.api_version,i))}get(e,n,i){return fe(lp(this,e,n?.api_version,n?.include_input,n?.last_event_id,n?.stream,i))}cancel(e,n,i){return fe(sp(this,e,n?.api_version,i))}};function up(t,e,n,i){return new se(PI(t,e,n,i))}async function PI(t,e,n,i){var o,r,a;let c={body:e,api_version:n},d=At("body",c.body,{explode:!0}),f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/triggers")(f),h=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"POST",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:R=>le({status:R},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,[S]=await he(ye(200),ee("4XX"),ee("5XX"))(C,y);return S.ok?[S,{status:"complete",request:y,response:C}]:[S,{status:"complete",request:y,response:C}]}function cp(t,e,n,i){return new se(NI(t,e,n,i))}async function NI(t,e,n,i){var o,r,a;let c={id:e,api_version:n},d=null,f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/triggers/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"DELETE",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:R=>le({status:R},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,[S]=await he(ye(200),ee("4XX"),ee("5XX"))(C,y);return S.ok?[S,{status:"complete",request:y,response:C}]:[S,{status:"complete",request:y,response:C}]}function dp(t,e,n,i){return new se(kI(t,e,n,i))}async function kI(t,e,n,i){var o,r,a;let c={id:e,api_version:n},d=null,f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/triggers/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"GET",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:R=>le({status:R},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,[S]=await he(ye(200),ee("4XX"),ee("5XX"))(C,y);return S.ok?[S,{status:"complete",request:y,response:C}]:[S,{status:"complete",request:y,response:C}]}function fp(t,e,n,i,o,r){return new se(DI(t,e,n,i,o,r))}async function DI(t,e,n,i,o,r){var a,u,c;let f={trigger_id:e,api_version:n,page_size:i,page_token:o},p=null,h={api_version:j("api_version",(a=f.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:j("trigger_id",f.trigger_id,{explode:!1,charEncoding:"percent"})},m=de("/{api_version}/triggers/{trigger_id}/executions")(h),_=Ot({page_size:f.page_size,page_token:f.page_token}),g=new Headers(pe({Accept:"application/json"})),v=await ge(t._options.security),y=me(v),A={options:t._options,base_url:(c=(u=r?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},C=t._createRequest(A,{security:y,method:"GET",baseURL:r?.server_url,path:m,headers:g,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!C.ok)return[C,{status:"invalid"}];let S=C.value,R=await t._do(S,{context:A,isErrorStatusCode:H=>le({status:H},["4XX","5XX"]),retryConfig:A.retry_config,retryCodes:A.retry_codes});if(!R.ok)return[R,{status:"request-error",request:S}];let L=R.value,[O]=await he(ye(200),ee("4XX"),ee("5XX"))(L,S);return O.ok?[O,{status:"complete",request:S,response:L}]:[O,{status:"complete",request:S,response:L}]}function pp(t,e,n,i,o,r){return new se(xI(t,e,n,i,o,r))}async function xI(t,e,n,i,o,r){var a,u,c;let f={api_version:e,filter:n,page_size:i,page_token:o},p=null,h={api_version:j("api_version",(a=f?.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"})},m=de("/{api_version}/triggers")(h),_=Ot({filter:f?.filter,page_size:f?.page_size,page_token:f?.page_token}),g=new Headers(pe({Accept:"application/json"})),v=await ge(t._options.security),y=me(v),A={options:t._options,base_url:(c=(u=r?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},C=t._createRequest(A,{security:y,method:"GET",baseURL:r?.server_url,path:m,headers:g,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!C.ok)return[C,{status:"invalid"}];let S=C.value,R=await t._do(S,{context:A,isErrorStatusCode:H=>le({status:H},["4XX","5XX"]),retryConfig:A.retry_config,retryCodes:A.retry_codes});if(!R.ok)return[R,{status:"request-error",request:S}];let L=R.value,[O]=await he(ye(200),ee("4XX"),ee("5XX"))(L,S);return O.ok?[O,{status:"complete",request:S,response:L}]:[O,{status:"complete",request:S,response:L}]}function hp(t,e,n,i){return new se(MI(t,e,n,i))}async function MI(t,e,n,i){var o,r,a;let c={trigger_id:e,api_version:n},d=null,f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:j("trigger_id",c.trigger_id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/triggers/{trigger_id}/executions")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"POST",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:R=>le({status:R},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,[S]=await he(ye(200),ee("4XX"),ee("5XX"))(C,y);return S.ok?[S,{status:"complete",request:y,response:C}]:[S,{status:"complete",request:y,response:C}]}function mp(t,e,n,i,o){return new se(UI(t,e,n,i,o))}async function UI(t,e,n,i,o){var r,a,u;let d={id:e,body:n,api_version:i},f=At("body",d.body,{explode:!0}),p={api_version:j("api_version",(r=d.api_version)!==null&&r!==void 0?r:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",d.id,{explode:!1,charEncoding:"percent"})},h=de("/{api_version}/triggers/{id}")(p),m=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),_=await ge(t._options.security),g=me(_),v={options:t._options,base_url:(u=(a=o?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:g,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(v,{security:g,method:"PATCH",baseURL:o?.server_url,path:h,headers:m,body:f,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!y.ok)return[y,{status:"invalid"}];let A=y.value,C=await t._do(A,{context:v,isErrorStatusCode:L=>le({status:L},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!C.ok)return[C,{status:"request-error",request:A}];let S=C.value,[R]=await he(ye(200),ee("4XX"),ee("5XX"))(S,A);return R.ok?[R,{status:"complete",request:A,response:S}]:[R,{status:"complete",request:A,response:S}]}var Pa=class extends vt{list(e,n){return fe(pp(this,e?.api_version,e?.filter,e?.page_size,e?.page_token,n))}create(e,n){let{api_version:i}=e,o=Me(e,["api_version"]);return fe(up(this,o,i,n))}delete(e,n,i){return fe(cp(this,e,n?.api_version,i))}get(e,n,i){return fe(dp(this,e,n?.api_version,i))}update(e,n,i){let{api_version:o}=n,r=Me(n,["api_version"]);return fe(mp(this,e,r,o,i))}listExecutions(e,n,i){return fe(fp(this,e,n?.api_version,n?.page_size,n?.page_token,i))}run(e,n,i){return fe(hp(this,e,n?.api_version,i))}};function gp(t,e,n,i){return new se(GI(t,e,n,i))}async function GI(t,e,n,i){var o,r,a;let c={body:e,api_version:n},d=At("body",c.body,{explode:!0}),f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/webhooks")(f),h=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"POST",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:R=>le({status:R},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,[S]=await he(ee("4XX"),ee("5XX"),ye("default"))(C,y);return S.ok?[S,{status:"complete",request:y,response:C}]:[S,{status:"complete",request:y,response:C}]}function _p(t,e,n,i){return new se(LI(t,e,n,i))}async function LI(t,e,n,i){var o,r,a;let c={id:e,api_version:n},d=null,f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/webhooks/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"DELETE",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:R=>le({status:R},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,[S]=await he(ee("4XX"),ee("5XX"),ye("default"))(C,y);return S.ok?[S,{status:"complete",request:y,response:C}]:[S,{status:"complete",request:y,response:C}]}function yp(t,e,n,i){return new se(bI(t,e,n,i))}async function bI(t,e,n,i){var o,r,a;let c={id:e,api_version:n},d=null,f={api_version:j("api_version",(o=c.api_version)!==null&&o!==void 0?o:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",c.id,{explode:!1,charEncoding:"percent"})},p=de("/{api_version}/webhooks/{id}")(f),h=new Headers(pe({Accept:"application/json"})),m=await ge(t._options.security),_=me(m),g={options:t._options,base_url:(a=(r=i?.server_url)!==null&&r!==void 0?r:t._baseURL)!==null&&a!==void 0?a:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:_,security_source:t._options.security,retry_config:i?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:i?.retry_codes||["408","409","429","5XX"]},v=t._createRequest(g,{security:_,method:"GET",baseURL:i?.server_url,path:p,headers:h,body:d,userAgent:t._options.user_agent,timeout_ms:i?.timeout_ms||t._options.timeout_ms||-1},i);if(!v.ok)return[v,{status:"invalid"}];let y=v.value,A=await t._do(y,{context:g,isErrorStatusCode:R=>le({status:R},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!A.ok)return[A,{status:"request-error",request:y}];let C=A.value,[S]=await he(ee("4XX"),ee("5XX"),ye("default"))(C,y);return S.ok?[S,{status:"complete",request:y,response:C}]:[S,{status:"complete",request:y,response:C}]}function Ep(t,e,n,i,o){return new se(OI(t,e,n,i,o))}async function OI(t,e,n,i,o){var r,a,u;let d={api_version:e,page_size:n,page_token:i},f=null,p={api_version:j("api_version",(r=d?.api_version)!==null&&r!==void 0?r:t._options.api_version,{explode:!1,charEncoding:"percent"})},h=de("/{api_version}/webhooks")(p),m=Ot({page_size:d?.page_size,page_token:d?.page_token}),_=new Headers(pe({Accept:"application/json"})),g=await ge(t._options.security),v=me(g),y={options:t._options,base_url:(u=(a=o?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:v,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},A=t._createRequest(y,{security:v,method:"GET",baseURL:o?.server_url,path:h,headers:_,query:m,body:f,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!A.ok)return[A,{status:"invalid"}];let C=A.value,S=await t._do(C,{context:y,isErrorStatusCode:O=>le({status:O},["4XX","5XX"]),retryConfig:y.retry_config,retryCodes:y.retry_codes});if(!S.ok)return[S,{status:"request-error",request:C}];let R=S.value,[L]=await he(ee("4XX"),ee("5XX"),ye("default"))(R,C);return L.ok?[L,{status:"complete",request:C,response:R}]:[L,{status:"complete",request:C,response:R}]}function vp(t,e,n,i,o){return new se(qI(t,e,n,i,o))}async function qI(t,e,n,i,o){var r,a,u;let d={id:e,api_version:n,body:i},f=At("body",d.body,{explode:!0}),p={api_version:j("api_version",(r=d.api_version)!==null&&r!==void 0?r:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",d.id,{explode:!1,charEncoding:"percent"})},h=de("/{api_version}/webhooks/{id}:ping")(p),m=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),_=await ge(t._options.security),g=me(_),v={options:t._options,base_url:(u=(a=o?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:g,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(v,{security:g,method:"POST",baseURL:o?.server_url,path:h,headers:m,body:f,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!y.ok)return[y,{status:"invalid"}];let A=y.value,C=await t._do(A,{context:v,isErrorStatusCode:L=>le({status:L},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!C.ok)return[C,{status:"request-error",request:A}];let S=C.value,[R]=await he(ee("4XX"),ee("5XX"),ye("default"))(S,A);return R.ok?[R,{status:"complete",request:A,response:S}]:[R,{status:"complete",request:A,response:S}]}function Tp(t,e,n,i,o){return new se(FI(t,e,n,i,o))}async function FI(t,e,n,i,o){var r,a,u;let d={id:e,api_version:n,body:i},f=At("body",d.body,{explode:!0}),p={api_version:j("api_version",(r=d.api_version)!==null&&r!==void 0?r:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",d.id,{explode:!1,charEncoding:"percent"})},h=de("/{api_version}/webhooks/{id}:rotateSigningSecret")(p),m=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),_=await ge(t._options.security),g=me(_),v={options:t._options,base_url:(u=(a=o?.server_url)!==null&&a!==void 0?a:t._baseURL)!==null&&u!==void 0?u:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:g,security_source:t._options.security,retry_config:o?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:o?.retry_codes||["408","409","429","5XX"]},y=t._createRequest(v,{security:g,method:"POST",baseURL:o?.server_url,path:h,headers:m,body:f,userAgent:t._options.user_agent,timeout_ms:o?.timeout_ms||t._options.timeout_ms||-1},o);if(!y.ok)return[y,{status:"invalid"}];let A=y.value,C=await t._do(A,{context:v,isErrorStatusCode:L=>le({status:L},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!C.ok)return[C,{status:"request-error",request:A}];let S=C.value,[R]=await he(ee("4XX"),ee("5XX"),ye("default"))(S,A);return R.ok?[R,{status:"complete",request:A,response:S}]:[R,{status:"complete",request:A,response:S}]}function Ap(t,e,n,i,o,r){return new se(HI(t,e,n,i,o,r))}async function HI(t,e,n,i,o,r){var a,u,c;let f={id:e,api_version:n,update_mask:i,body:o},p=At("body",f.body,{explode:!0}),h={api_version:j("api_version",(a=f.api_version)!==null&&a!==void 0?a:t._options.api_version,{explode:!1,charEncoding:"percent"}),id:j("id",f.id,{explode:!1,charEncoding:"percent"})},m=de("/{api_version}/webhooks/{id}")(h),_=Ot({update_mask:f.update_mask}),g=new Headers(pe({"Content-Type":"application/json",Accept:"application/json"})),v=await ge(t._options.security),y=me(v),A={options:t._options,base_url:(c=(u=r?.server_url)!==null&&u!==void 0?u:t._baseURL)!==null&&c!==void 0?c:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:y,security_source:t._options.security,retry_config:r?.retries||t._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:r?.retry_codes||["408","409","429","5XX"]},C=t._createRequest(A,{security:y,method:"PATCH",baseURL:r?.server_url,path:m,headers:g,query:_,body:p,userAgent:t._options.user_agent,timeout_ms:r?.timeout_ms||t._options.timeout_ms||-1},r);if(!C.ok)return[C,{status:"invalid"}];let S=C.value,R=await t._do(S,{context:A,isErrorStatusCode:H=>le({status:H},["4XX","5XX"]),retryConfig:A.retry_config,retryCodes:A.retry_codes});if(!R.ok)return[R,{status:"request-error",request:S}];let L=R.value,[O]=await he(ee("4XX"),ee("5XX"),ye("default"))(L,S);return O.ok?[O,{status:"complete",request:S,response:L}]:[O,{status:"complete",request:S,response:L}]}var Na=class extends vt{list(e,n){return fe(Ep(this,e?.api_version,e?.page_size,e?.page_token,n))}create(e,n){let{api_version:i}=e,o=Me(e,["api_version"]);return fe(gp(this,o,i,n))}delete(e,n,i){return fe(_p(this,e,n?.api_version,i))}get(e,n,i){return fe(yp(this,e,n?.api_version,i))}update(e,n,i){let o=n??{},{api_version:r,update_mask:a}=o,u=Me(o,["api_version","update_mask"]),c=n===void 0||Object.keys(u).length===0?void 0:u;return fe(Ap(this,e,r,a,c,i))}ping(e,n,i,o){return fe(vp(this,e,n,i,o))}rotateSigningSecret(e,n,i,o){return fe(Tp(this,e,n,i,o))}};var VI=class extends vt{get agents(){var e;return(e=this._agents)!==null&&e!==void 0?e:this._agents=new ga(this._options)}get environments(){var e;return(e=this._environments)!==null&&e!==void 0?e:this._environments=new ya(this._options)}get interactions(){var e;return(e=this._interactions)!==null&&e!==void 0?e:this._interactions=new Ra(this._options)}get triggers(){var e;return(e=this._triggers)!==null&&e!==void 0?e:this._triggers=new Pa(this._options)}get webhooks(){var e;return(e=this._webhooks)!==null&&e!==void 0?e:this._webhooks=new Na(this._options)}};var BI=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function $I(t){let e=t.getBaseUrl();if(!e)throw new Error("Base URL must be set.");return e.replace(/\/+$/,"")}function JI(t){let e=XI(t.getApiVersion()),n=t.getProject(),i=t.getLocation();return t.isVertexAI()&&e&&n&&i?`${e}/projects/${encodeURIComponent(n)}/locations/${encodeURIComponent(i)}`:e}function ft(t,e={}){var n,i,o,r,a;return new VI(Object.assign(Object.assign({},e),{api_version:(n=e.api_version)!==null&&n!==void 0?n:JI(t),security:(i=e.security)!==null&&i!==void 0?i:new ea({defaultHeaders:Object.assign(Object.assign({},(o=t.getDefaultHeaders)===null||o===void 0?void 0:o.call(t)),(r=t.getHeaders)===null||r===void 0?void 0:r.call(t)),getAuthHeaders:c=>t.getAuthHeaders(c)}),server_url:(a=e.server_url)!==null&&a!==void 0?a:$I(t)}))}var ka=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:i}=e,o=Me(e,["api_version"]);if(o.stream===!0){let a=await fs(()=>this.getClient(i).interactions.create(Object.assign(Object.assign({},o),{stream:!0,api_version:i}),ae(n,!0)));return Zd(a)}let r=await _e(ap(this.getClient(i),o,i,ae(n)));return ps(r)}async get(e,n={},i){let{api_version:o,stream:r=!1,last_event_id:a,include_input:u}=n??{};if(r===!0){let d=await fs(()=>this.getClient(o).interactions.get(e,{stream:r,last_event_id:a,include_input:u,api_version:o},ae(i,!0)));return Zd(d)}let c=await _e(lp(this.getClient(o),e,o,u,a,r,ae(i)));return ps(c)}async delete(e,n={},i){return fs(()=>this.getClient(n?.api_version).interactions.delete(e,{api_version:n?.api_version},ae(i)))}async cancel(e,n={},i){return ps(await _e(sp(this.getClient(n?.api_version),e,n?.api_version,ae(i))))}getClient(e){var n;return e?ft(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=ft(this.parentClient)),this.sdk)}},Da=class{constructor(e){this.parentClient=e}async create(e={},n){let i=e??{},{api_version:o}=i,r=Me(i,["api_version"]);return _e(Qf(this.getClient(o),r,o,ae(n)))}async list(e={},n){let{api_version:i,pageSize:o,pageToken:r,parent:a}=e??{};return _e(ep(this.getClient(i),i,o,r,a,ae(n)))}async get(e,n={},i){return _e(jf(this.getClient(n?.api_version),e,n?.api_version,ae(i)))}async delete(e,n={},i){return _e(Zf(this.getClient(n?.api_version),e,n?.api_version,ae(i)))}getClient(e){var n;return e?ft(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=ft(this.parentClient)),this.sdk)}},xa=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:i}=e,o=Me(e,["api_version"]);return _e(gp(this.getClient(),o,i,ae(n)))}async list(e={},n){let{api_version:i,page_size:o,page_token:r}=e??{};return _e(Ep(this.getClient(),i,o,r,ae(n)))}async get(e,n={},i){return _e(yp(this.getClient(),e,n?.api_version,ae(i)))}async update(e,n={},i){let o=n??{},{api_version:r,update_mask:a}=o,u=Me(o,["api_version","update_mask"]);return _e(Ap(this.getClient(),e,r,a,u,ae(i)))}async delete(e,n={},i){return _e(_p(this.getClient(),e,n?.api_version,ae(i)))}async rotateSigningSecret(e,n={},i){let o=n??{},{api_version:r}=o,a=Me(o,["api_version"]);return _e(Tp(this.getClient(),e,r,a,ae(i)))}async ping(e,n=void 0,i){let{api_version:o,body:r}=n??{};return _e(vp(this.getClient(),e,o,r,ae(i)))}getClient(){var e;return(e=this.sdk)!==null&&e!==void 0||(this.sdk=ft(this.parentClient)),this.sdk}},Ma=class{constructor(e){this.parentClient=e}async create(e,n){let{api_version:i}=e,o=Me(e,["api_version"]);return _e(up(this.getClient(i),o,i,ae(n)))}async list(e={},n){let{api_version:i,filter:o,pageSize:r,pageToken:a}=e??{};return _e(pp(this.getClient(i),i,o,r,a,ae(n)))}async get(e,n={},i){return _e(dp(this.getClient(n?.api_version),e,n?.api_version,ae(i)))}async update(e,n,i){let{api_version:o}=n,r=Me(n,["api_version"]);return _e(mp(this.getClient(o),e,r,o,ae(i)))}async delete(e,n={},i){return _e(cp(this.getClient(n?.api_version),e,n?.api_version,ae(i)))}async run(e,n={},i){return _e(hp(this.getClient(n?.api_version),e,n?.api_version,ae(i)))}async listExecutions(e,n={},i){let{api_version:o,pageSize:r,pageToken:a}=n??{};return _e(fp(this.getClient(o),e,o,r,a,ae(i)))}getClient(e){var n;return e?ft(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=ft(this.parentClient)),this.sdk)}};function XI(t){return t.replace(/^\/+|\/+$/g,"")}function ae(t,e=!1){var n,i,o,r;if(!t&&!e)return;let a=t??{},{timeout:u,maxRetries:c,defaultBaseURL:d,query:f,body:p,fetchOptions:h}=a,m=Me(a,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),_=Object.assign({},m);so(f)?_.extra_query=f:Qd("query",f),so(p)?_.extra_body=p:Qd("body",p);let g=(n=m.fetch_options)!==null&&n!==void 0?n:h;g&&(_.fetch_options=g);let v=(i=m.server_url)!==null&&i!==void 0?i:d;v&&(_.server_url=v);let y=(o=m.timeout_ms)!==null&&o!==void 0?o:u;if(y!==void 0&&(_.timeout_ms=y),c!==void 0&&(_.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries:c}),e){let A=new Headers((r=_.headers)!==null&&r!==void 0?r:g?.headers);A.set("Accept","text/event-stream"),_.headers=A}return _}function Qd(t,e){e!=null&&console.warn(`GoogleGenAI.interactions: request option ${t} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function _e(t){let[e,n]=await t.$inspect();if(!e.ok)throw dn(e.error);return KI(e.value,n)}async function fs(t){try{return await t()}catch(e){throw dn(e)}}function Zd(t){let e=t;return new Proxy(t,{get(n,i){if(i!==Symbol.asyncIterator){let o=Reflect.get(n,i,n);return typeof o=="function"?o.bind(n):o}return function(){let r=e[Symbol.asyncIterator]();return{async next(...a){try{return await r.next(...a)}catch(u){throw dn(u)}},async return(a){if(!r.return)return{done:!0,value:a};try{return await r.return(a)}catch(u){throw dn(u)}},async throw(a){if(!r.throw)throw dn(a);try{return await r.throw(a)}catch(u){throw dn(u)}},[Symbol.asyncIterator](){return this}}}}})}function KI(t,e){return!so(t)||e.status!=="complete"?t:Object.assign(Object.assign({},t),{sdkHttpResponse:YI(e.response,t)})}function YI(t,e){let n={};for(let[i,o]of t.headers.entries())n[i]=o;return{headers:n,responseInternal:t,json:async()=>e}}function ps(t){let e=WI(t);return e?QI(e):t}function WI(t){if(so(t)){if(Array.isArray(t.steps))return t;if(zI(t)){let e=t.outputs;if(Array.isArray(e)){let{outputs:n}=t,i=Me(t,["outputs"]);return Object.assign(Object.assign({},i),{steps:[{type:"model_output",content:e}]})}}return Object.assign(Object.assign({},t),{steps:[]})}}function zI(t){let e=t.model;return typeof e=="string"&&BI.has(e)}function so(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function QI(t){var e,n;let i=ZI(t),o=(e=i.steps)!==null&&e!==void 0?e:[],r=[],a=!1;e:for(let p=o.length-1;p>=0;p--){let h=o[p];if(h.type==="user_input")break;if(h.type!=="model_output"||!h.content){if(a)break;continue}let m=h.content;for(let _=m.length-1;_>=0;_--){let g=m[_];if(g.type==="text")a=!0,r.push((n=g.text)!==null&&n!==void 0?n:"");else if(a)break e}}let u,c,d;for(let p=o.length-1;p>=0;p--){let h=o[p];if(h.type==="user_input")break;if(h.type==="model_output"&&h.content)for(let m=h.content.length-1;m>=0;m--){let _=h.content[m];_.type==="image"&&!u&&(u=_),_.type==="audio"&&!c&&(c=_),_.type==="video"&&!d&&(d=_)}}let f=r.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},i),f&&{output_text:f}),u?{output_image:u}:{}),c?{output_audio:c}:{}),d?{output_video:d}:{})}function ZI(t){return Object.assign(Object.assign({},t),{created:jd(t.created),updated:jd(t.updated)})}function jd(t){return t instanceof Date?t.toISOString():t}var Ua=class{constructor(e){this.resolveClient=e}async list(e,n){let{environment:i,path:o,page_size:r,page_token:a,recursive:u,api_version:c}=e;return _e(rp(this.resolveClient(c),i,o,c,r,a,u,ae(n)))}},Ga=class{constructor(e){this.parentClient=e,this.files=new Ua(n=>this.getClient(n))}async create(e,n){let{api_version:i}=e,o=Me(e,["api_version"]);return _e(tp(this.getClient(i),o,i,ae(n)))}async list(e={},n){let{api_version:i,page_size:o,page_token:r}=e??{};return _e(op(this.getClient(i),i,o,r,ae(n)))}async get(e,n={},i){return _e(ip(this.getClient(n?.api_version),e,n?.api_version,ae(i)))}async delete(e,n={},i){return _e(np(this.getClient(n?.api_version),e,n?.api_version,ae(i)))}getClient(e){var n;return e?ft(this.parentClient,{api_version:e}):((n=this.sdk)!==null&&n!==void 0||(this.sdk=ft(this.parentClient)),this.sdk)}};var ef="x-goog-api-key",Ln="https://www.googleapis.com/auth/cloud-platform",La=class{constructor(e){if(e.apiKey!==void 0){this.apiKey=e.apiKey;return}let n=jI(e.googleAuthOptions);this.googleAuth=new rf.GoogleAuth(n)}async addAuthHeaders(e,n){if(this.apiKey!==void 0){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(e);return}return this.addGoogleAuthHeaders(e,n)}addKeyHeader(e){if(e.get(ef)===null){if(this.apiKey===void 0)throw new Error("Trying to set API key header but apiKey is not set");e.append(ef,this.apiKey)}}async addGoogleAuthHeaders(e,n){if(this.googleAuth===void 0)throw new Error("Trying to set google-auth headers but googleAuth is unset");let i=await this.googleAuth.getRequestHeaders(n);for(let[o,r]of i)e.get(o)===null&&e.append(o,r)}};function jI(t){let e;if(t){if(e=t,e.scopes){if(typeof e.scopes=="string"&&e.scopes!==Ln||Array.isArray(e.scopes)&&e.scopes.indexOf(Ln)<0)throw new Error(`Invalid auth scopes. Scopes must include: ${Ln}`)}else return e.scopes=[Ln],e;return e}else return e={scopes:[Ln]},e}var ba=class{async download(e,n){if(e.downloadPath){let i=await e0(e,n);if(i instanceof Mt){let o=E_(e.downloadPath);T_.fromWeb(i.responseInternal.body).pipe(o),await A_(o)}else try{await v_(e.downloadPath,i,{encoding:"base64"})}catch(o){throw new Error(`Failed to write file to ${e.downloadPath}: ${o}`)}}}};async function e0(t,e){var n,i,o;let r=Qa(t.file);if(r!==void 0)return await e.request({path:`files/${r}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=t.config)===null||i===void 0?void 0:i.abortSignal});if(pf(t.file)){let a=(o=t.file.video)===null||o===void 0?void 0:o.videoBytes;if(typeof a=="string")return a;throw new Error("Failed to download generated video, Uri or videoBytes not found.")}else if(hf(t.file)){let a=t.file.videoBytes;if(typeof a=="string")return a;throw new Error("Failed to download video, Uri or videoBytes not found.")}else throw new Error("Unsupported file type")}var Oa=class{create(e,n,i){return new qa(e,n,i)}},qa=class{constructor(e,n,i){this.url=e,this.headers=n,this.callbacks=i}connect(){this.ws=new rl.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(e)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}};function t0(t,e){let n={},i=s(t,["name"]);return i!=null&&l(n,["_url","name"],i),n}function n0(t,e){let n={},i=s(t,["name"]);return i!=null&&l(n,["_url","name"],i),n}function i0(t,e){let n={},i=s(t,["sdkHttpResponse"]);return i!=null&&l(n,["sdkHttpResponse"],i),n}function o0(t,e){let n={},i=s(t,["sdkHttpResponse"]);return i!=null&&l(n,["sdkHttpResponse"],i),n}function Fa(t,e){let n={},i=s(t,["parts"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>_0(a))),l(n,["parts"],r)}let o=s(t,["role"]);return o!=null&&l(n,["role"],o),n}function r0(t,e,n){let i={};if(s(t,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=s(t,["tunedModelDisplayName"]);if(e!==void 0&&o!=null&&l(e,["displayName"],o),s(t,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let r=s(t,["epochCount"]);e!==void 0&&r!=null&&l(e,["tuningTask","hyperparameters","epochCount"],r);let a=s(t,["learningRateMultiplier"]);if(a!=null&&l(i,["tuningTask","hyperparameters","learningRateMultiplier"],a),s(t,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let u=s(t,["batchSize"]);e!==void 0&&u!=null&&l(e,["tuningTask","hyperparameters","batchSize"],u);let c=s(t,["learningRate"]);if(e!==void 0&&c!=null&&l(e,["tuningTask","hyperparameters","learningRate"],c),s(t,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["beta"])!==void 0)throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["outputUri"])!==void 0)throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["rewardConfig"])!==void 0)throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["compositeRewardConfig"])!==void 0)throw new Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["samplesPerPrompt"])!==void 0)throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["evaluateInterval"])!==void 0)throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["checkpointInterval"])!==void 0)throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["maxOutputTokens"])!==void 0)throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["thinkingLevel"])!==void 0)throw new Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["validationDatasetUri"])!==void 0)throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}function s0(t,e,n){let i={},o=s(n,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){let D=s(t,["validationDataset"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec"],bi(D))}else if(o==="PREFERENCE_TUNING"){let D=s(t,["validationDataset"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec"],bi(D))}else if(o==="DISTILLATION"){let D=s(t,["validationDataset"]);e!==void 0&&D!=null&&l(e,["distillationSpec"],bi(D))}else if(o==="REINFORCEMENT_TUNING"){let D=s(t,["validationDataset"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec"],bi(D))}let r=s(t,["tunedModelDisplayName"]);e!==void 0&&r!=null&&l(e,["tunedModelDisplayName"],r);let a=s(t,["description"]);e!==void 0&&a!=null&&l(e,["description"],a);let u=s(n,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){let D=s(t,["epochCount"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","epochCount"],D)}else if(u==="PREFERENCE_TUNING"){let D=s(t,["epochCount"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],D)}else if(u==="DISTILLATION"){let D=s(t,["epochCount"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","epochCount"],D)}else if(u==="REINFORCEMENT_TUNING"){let D=s(t,["epochCount"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec","hyperParameters","epochCount"],D)}let c=s(n,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){let D=s(t,["learningRateMultiplier"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],D)}else if(c==="PREFERENCE_TUNING"){let D=s(t,["learningRateMultiplier"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],D)}else if(c==="DISTILLATION"){let D=s(t,["learningRateMultiplier"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","learningRateMultiplier"],D)}else if(c==="REINFORCEMENT_TUNING"){let D=s(t,["learningRateMultiplier"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],D)}let d=s(n,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){let D=s(t,["exportLastCheckpointOnly"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","exportLastCheckpointOnly"],D)}else if(d==="PREFERENCE_TUNING"){let D=s(t,["exportLastCheckpointOnly"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],D)}else if(d==="DISTILLATION"){let D=s(t,["exportLastCheckpointOnly"]);e!==void 0&&D!=null&&l(e,["distillationSpec","exportLastCheckpointOnly"],D)}let f=s(n,["config","method"]);if(f===void 0&&(f="SUPERVISED_FINE_TUNING"),f==="SUPERVISED_FINE_TUNING"){let D=s(t,["adapterSize"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","adapterSize"],D)}else if(f==="PREFERENCE_TUNING"){let D=s(t,["adapterSize"]);e!==void 0&&D!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],D)}else if(f==="DISTILLATION"){let D=s(t,["adapterSize"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","adapterSize"],D)}else if(f==="REINFORCEMENT_TUNING"){let D=s(t,["adapterSize"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec","hyperParameters","adapterSize"],D)}let p=s(n,["config","method"]);if(p===void 0&&(p="SUPERVISED_FINE_TUNING"),p==="SUPERVISED_FINE_TUNING"){let D=s(t,["tuningMode"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","tuningMode"],D)}else if(p==="DISTILLATION"){let D=s(t,["tuningMode"]);e!==void 0&&D!=null&&l(e,["distillationSpec","tuningMode"],D)}let h=s(t,["customBaseModel"]);e!==void 0&&h!=null&&l(e,["customBaseModel"],h);let m=s(n,["config","method"]);if(m===void 0&&(m="SUPERVISED_FINE_TUNING"),m==="SUPERVISED_FINE_TUNING"){let D=s(t,["batchSize"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","batchSize"],D)}else if(m==="DISTILLATION"){let D=s(t,["batchSize"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","batchSize"],D)}else if(m==="REINFORCEMENT_TUNING"){let D=s(t,["batchSize"]);e!==void 0&&D!=null&&l(e,["reinforcementTuningSpec","hyperParameters","batchSize"],D)}let _=s(n,["config","method"]);if(_===void 0&&(_="SUPERVISED_FINE_TUNING"),_==="SUPERVISED_FINE_TUNING"){let D=s(t,["learningRate"]);e!==void 0&&D!=null&&l(e,["supervisedTuningSpec","hyperParameters","learningRate"],D)}else if(_==="DISTILLATION"){let D=s(t,["learningRate"]);e!==void 0&&D!=null&&l(e,["distillationSpec","hyperParameters","learningRate"],D)}let g=s(t,["labels"]);e!==void 0&&g!=null&&l(e,["labels"],g);let v=s(t,["beta"]);e!==void 0&&v!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","beta"],v);let y=s(t,["baseTeacherModel"]);e!==void 0&&y!=null&&l(e,["distillationSpec","baseTeacherModel"],y);let A=s(t,["tunedTeacherModelSource"]);e!==void 0&&A!=null&&l(e,["distillationSpec","tunedTeacherModelSource"],A);let C=s(t,["sftLossWeightMultiplier"]);e!==void 0&&C!=null&&l(e,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],C);let S=s(t,["outputUri"]);e!==void 0&&S!=null&&l(e,["outputUri"],S);let R=s(t,["rewardConfig"]);e!==void 0&&R!=null&&l(e,["reinforcementTuningSpec","singleRewardConfig"],R);let L=s(t,["compositeRewardConfig"]);e!==void 0&&L!=null&&l(e,["reinforcementTuningSpec","compositeRewardConfig"],L);let O=s(t,["samplesPerPrompt"]);e!==void 0&&O!=null&&l(e,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],O);let H=s(t,["evaluateInterval"]);e!==void 0&&H!=null&&l(e,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],H);let U=s(t,["checkpointInterval"]);e!==void 0&&U!=null&&l(e,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],U);let F=s(t,["maxOutputTokens"]);e!==void 0&&F!=null&&l(e,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],F);let J=s(t,["thinkingLevel"]);e!==void 0&&J!=null&&l(e,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],J);let Q=s(t,["validationDatasetUri"]);e!==void 0&&Q!=null&&l(e,["reinforcementTuningSpec","validationDatasetUri"],Q);let te=s(t,["encryptionSpec"]);return e!==void 0&&te!=null&&l(e,["encryptionSpec"],te),i}function a0(t,e){let n={},i=s(t,["baseModel"]);i!=null&&l(n,["baseModel"],i);let o=s(t,["preTunedModel"]);o!=null&&l(n,["preTunedModel"],o);let r=s(t,["trainingDataset"]);r!=null&&v0(r);let a=s(t,["config"]);return a!=null&&r0(a,n),n}function l0(t,e){let n={},i=s(t,["baseModel"]);i!=null&&l(n,["baseModel"],i);let o=s(t,["preTunedModel"]);o!=null&&l(n,["preTunedModel"],o);let r=s(t,["trainingDataset"]);r!=null&&T0(r,n,e);let a=s(t,["config"]);return a!=null&&s0(a,n,e),n}function Cp(t,e){let n={},i=s(t,["epochCount"]);i!=null&&l(n,["epochCount"],i);let o=s(t,["learningRateMultiplier"]);o!=null&&l(n,["learningRateMultiplier"],o);let r=s(t,["adapterSize"]);r!=null&&l(n,["adapterSize"],r);let a=s(t,["batchSize"]);a!=null&&l(n,["batchSize"],a);let u=s(t,["learningRate"]);u!=null&&l(n,["learningRate"],u);let c=s(t,["generationConfig"]);return c!=null&&l(n,["generationConfig"],d0(c)),n}function u0(t,e){let n={},i=s(t,["promptDatasetUri"]);i!=null&&l(n,["promptDatasetUri"],i);let o=s(t,["validationDatasetUri"]);o!=null&&l(n,["validationDatasetUri"],o);let r=s(t,["baseTeacherModel"]);r!=null&&l(n,["baseTeacherModel"],r);let a=s(t,["tunedTeacherModelSource"]);a!=null&&l(n,["tunedTeacherModelSource"],a);let u=s(t,["hyperparameters"]);return u!=null&&l(n,["hyperparameters"],Cp(u)),n}function c0(t,e){let n={},i=s(t,["baseTeacherModel"]);i!=null&&l(n,["baseTeacherModel"],i);let o=s(t,["hyperParameters"]);o!=null&&l(n,["hyperParameters"],Cp(o));let r=s(t,["pipelineRootDirectory"]);r!=null&&l(n,["pipelineRootDirectory"],r);let a=s(t,["promptDatasetUri"]);a!=null&&l(n,["promptDatasetUri"],a);let u=s(t,["studentModel"]);u!=null&&l(n,["studentModel"],u);let c=s(t,["trainingDatasetUri"]);c!=null&&l(n,["trainingDatasetUri"],c);let d=s(t,["tunedTeacherModelSource"]);d!=null&&l(n,["tunedTeacherModelSource"],d);let f=s(t,["tuningMode"]);f!=null&&l(n,["tuningMode"],f);let p=s(t,["validationDatasetUri"]);return p!=null&&l(n,["validationDatasetUri"],p),n}function d0(t,e){let n={},i=s(t,["modelConfig"]);i!=null&&l(n,["modelSelectionConfig"],i);let o=s(t,["responseJsonSchema"]);o!=null&&l(n,["responseJsonSchema"],o);let r=s(t,["audioTranscriptionConfig"]);r!=null&&l(n,["audioTranscriptionConfig"],r);let a=s(t,["audioTimestamp"]);a!=null&&l(n,["audioTimestamp"],a);let u=s(t,["candidateCount"]);u!=null&&l(n,["candidateCount"],u);let c=s(t,["enableAffectiveDialog"]);c!=null&&l(n,["enableAffectiveDialog"],c);let d=s(t,["frequencyPenalty"]);d!=null&&l(n,["frequencyPenalty"],d);let f=s(t,["logprobs"]);f!=null&&l(n,["logprobs"],f);let p=s(t,["maxOutputTokens"]);p!=null&&l(n,["maxOutputTokens"],p);let h=s(t,["mediaResolution"]);h!=null&&l(n,["mediaResolution"],h);let m=s(t,["presencePenalty"]);m!=null&&l(n,["presencePenalty"],m);let _=s(t,["responseFormat"]);if(_!=null){let J=_;Array.isArray(J)&&(J=J.map(Q=>Q)),l(n,["responseFormat"],J)}let g=s(t,["responseLogprobs"]);g!=null&&l(n,["responseLogprobs"],g);let v=s(t,["responseMimeType"]);v!=null&&l(n,["responseMimeType"],v);let y=s(t,["responseModalities"]);y!=null&&l(n,["responseModalities"],y);let A=s(t,["responseSchema"]);A!=null&&l(n,["responseSchema"],A);let C=s(t,["routingConfig"]);C!=null&&l(n,["routingConfig"],C);let S=s(t,["seed"]);S!=null&&l(n,["seed"],S);let R=s(t,["speechConfig"]);R!=null&&l(n,["speechConfig"],R);let L=s(t,["stopSequences"]);L!=null&&l(n,["stopSequences"],L);let O=s(t,["temperature"]);O!=null&&l(n,["temperature"],O);let H=s(t,["thinkingConfig"]);H!=null&&l(n,["thinkingConfig"],H);let U=s(t,["topK"]);U!=null&&l(n,["topK"],U);let F=s(t,["topP"]);return F!=null&&l(n,["topP"],F),n}function f0(t,e){let n={},i=s(t,["name"]);return i!=null&&l(n,["_url","name"],i),n}function p0(t,e){let n={},i=s(t,["name"]);return i!=null&&l(n,["_url","name"],i),n}function h0(t,e,n){let i={},o=s(t,["pageSize"]);e!==void 0&&o!=null&&l(e,["_query","pageSize"],o);let r=s(t,["pageToken"]);e!==void 0&&r!=null&&l(e,["_query","pageToken"],r);let a=s(t,["filter"]);return e!==void 0&&a!=null&&l(e,["_query","filter"],a),i}function m0(t,e){let n={},i=s(t,["config"]);return i!=null&&h0(i,n),n}function g0(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["nextPageToken"]);o!=null&&l(n,["nextPageToken"],o);let r=s(t,["tuningJobs"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(u=>Ha(u))),l(n,["tuningJobs"],a)}return n}function _0(t,e){let n={},i=s(t,["mediaResolution"]);if(i!=null&&l(n,["mediaResolution"],i),s(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(s(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let o=s(t,["audioTranscription"]);o!=null&&l(n,["audioTranscription"],o);let r=s(t,["codeExecutionResult"]);r!=null&&l(n,["codeExecutionResult"],r);let a=s(t,["executableCode"]);a!=null&&l(n,["executableCode"],a);let u=s(t,["fileData"]);u!=null&&l(n,["fileData"],u);let c=s(t,["functionCall"]);c!=null&&l(n,["functionCall"],c);let d=s(t,["functionResponse"]);d!=null&&l(n,["functionResponse"],d);let f=s(t,["inlineData"]);f!=null&&l(n,["inlineData"],f);let p=s(t,["text"]);p!=null&&l(n,["text"],p);let h=s(t,["thought"]);h!=null&&l(n,["thought"],h);let m=s(t,["thoughtSignature"]);m!=null&&l(n,["thoughtSignature"],m);let _=s(t,["videoMetadata"]);if(_!=null&&l(n,["videoMetadata"],_),s(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let g=s(t,["mediaProcessing"]);return g!=null&&l(n,["mediaProcessing"],g),n}function y0(t,e){let n={},i=s(t,["references"]);i!=null&&l(n,["references"],i);let o=s(t,["contents"]);if(o!=null){let a=o;Array.isArray(a)&&(a=a.map(u=>Fa(u))),l(n,["contents"],a)}let r=s(t,["systemInstruction"]);return r!=null&&l(n,["systemInstruction"],Fa(r)),n}function E0(t,e){let n={},i=s(t,["name"]);i!=null&&l(n,["model"],i);let o=s(t,["name"]);return o!=null&&l(n,["endpoint"],o),n}function v0(t,e){let n={};if(s(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(s(t,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=s(t,["examples"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(r=>r)),l(n,["examples","examples"],o)}return n}function T0(t,e,n){let i={},o=s(n,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(o==="PREFERENCE_TUNING"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}else if(o==="DISTILLATION"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["distillationSpec","promptDatasetUri"],a)}else if(o==="REINFORCEMENT_TUNING"){let a=s(t,["gcsUri"]);e!==void 0&&a!=null&&l(e,["reinforcementTuningSpec","trainingDatasetUri"],a)}let r=s(n,["config","method"]);if(r===void 0&&(r="SUPERVISED_FINE_TUNING"),r==="SUPERVISED_FINE_TUNING"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(r==="PREFERENCE_TUNING"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}else if(r==="DISTILLATION"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["distillationSpec","promptDatasetUri"],a)}else if(r==="REINFORCEMENT_TUNING"){let a=s(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&l(e,["reinforcementTuningSpec","trainingDatasetUri"],a)}if(s(t,["examples"])!==void 0)throw new Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return i}function A0(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["name"]);o!=null&&l(n,["name"],o);let r=s(t,["state"]);r!=null&&l(n,["state"],ff(r));let a=s(t,["createTime"]);a!=null&&l(n,["createTime"],a);let u=s(t,["tuningTask","startTime"]);u!=null&&l(n,["startTime"],u);let c=s(t,["tuningTask","completeTime"]);c!=null&&l(n,["endTime"],c);let d=s(t,["updateTime"]);d!=null&&l(n,["updateTime"],d);let f=s(t,["description"]);f!=null&&l(n,["description"],f);let p=s(t,["baseModel"]);p!=null&&l(n,["baseModel"],p);let h=s(t,["_self"]);return h!=null&&l(n,["tunedModel"],E0(h)),n}function Ha(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["name"]);o!=null&&l(n,["name"],o);let r=s(t,["state"]);r!=null&&l(n,["state"],ff(r));let a=s(t,["createTime"]);a!=null&&l(n,["createTime"],a);let u=s(t,["startTime"]);u!=null&&l(n,["startTime"],u);let c=s(t,["endTime"]);c!=null&&l(n,["endTime"],c);let d=s(t,["updateTime"]);d!=null&&l(n,["updateTime"],d);let f=s(t,["error"]);f!=null&&l(n,["error"],f);let p=s(t,["description"]);p!=null&&l(n,["description"],p);let h=s(t,["baseModel"]);h!=null&&l(n,["baseModel"],h);let m=s(t,["tunedModel"]);m!=null&&l(n,["tunedModel"],m);let _=s(t,["preTunedModel"]);_!=null&&l(n,["preTunedModel"],_);let g=s(t,["supervisedTuningSpec"]);g!=null&&l(n,["supervisedTuningSpec"],g);let v=s(t,["preferenceOptimizationSpec"]);v!=null&&l(n,["preferenceOptimizationSpec"],v);let y=s(t,["distillationSamplingSpec"]);y!=null&&l(n,["distillationSamplingSpec"],u0(y));let A=s(t,["distillationSpec"]);A!=null&&l(n,["distillationSpec"],c0(A));let C=s(t,["reinforcementTuningSpec"]);C!=null&&l(n,["reinforcementTuningSpec"],C);let S=s(t,["tuningDataStats"]);S!=null&&l(n,["tuningDataStats"],S);let R=s(t,["encryptionSpec"]);R!=null&&l(n,["encryptionSpec"],R);let L=s(t,["partnerModelTuningSpec"]);L!=null&&l(n,["partnerModelTuningSpec"],L);let O=s(t,["customBaseModel"]);O!=null&&l(n,["customBaseModel"],O);let H=s(t,["evaluateDatasetRuns"]);if(H!=null){let Pe=H;Array.isArray(Pe)&&(Pe=Pe.map(Oe=>Oe)),l(n,["evaluateDatasetRuns"],Pe)}let U=s(t,["experiment"]);U!=null&&l(n,["experiment"],U);let F=s(t,["fullFineTuningSpec"]);F!=null&&l(n,["fullFineTuningSpec"],F);let J=s(t,["labels"]);J!=null&&l(n,["labels"],J);let Q=s(t,["outputUri"]);Q!=null&&l(n,["outputUri"],Q);let te=s(t,["pipelineJob"]);te!=null&&l(n,["pipelineJob"],te);let D=s(t,["serviceAccount"]);D!=null&&l(n,["serviceAccount"],D);let K=s(t,["tunedModelDisplayName"]);K!=null&&l(n,["tunedModelDisplayName"],K);let Z=s(t,["tuningJobMetadata"]);Z!=null&&l(n,["tuningJobMetadata"],Z);let Ee=s(t,["tuningJobState"]);Ee!=null&&l(n,["tuningJobState"],Ee);let Re=s(t,["veoLoraTuningSpec"]);Re!=null&&l(n,["veoLoraTuningSpec"],Re);let Te=s(t,["veoTuningSpec"]);return Te!=null&&l(n,["veoTuningSpec"],Te),n}function C0(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["name"]);o!=null&&l(n,["name"],o);let r=s(t,["metadata"]);r!=null&&l(n,["metadata"],r);let a=s(t,["done"]);a!=null&&l(n,["done"],a);let u=s(t,["error"]);return u!=null&&l(n,["error"],u),n}function bi(t,e){let n={},i=s(t,["gcsUri"]);i!=null&&l(n,["validationDatasetUri"],i);let o=s(t,["vertexDatasetResource"]);return o!=null&&l(n,["validationDatasetUri"],o),n}function I0(t,e){let n={},i=s(t,["parent"]);i!=null&&l(n,["_url","parent"],i);let o=s(t,["sampleResponse"]);o!=null&&l(n,["sampleResponse"],Fa(o));let r=s(t,["example"]);r!=null&&l(n,["example"],y0(r));let a=s(t,["singleRewardConfig"]);a!=null&&l(n,["singleRewardConfig"],a);let u=s(t,["compositeRewardConfig"]);return u!=null&&l(n,["compositeRewardConfig"],u),n}function S0(t,e){let n={},i=s(t,["sdkHttpResponse"]);i!=null&&l(n,["sdkHttpResponse"],i);let o=s(t,["overallReward"]);o!=null&&l(n,["overallReward"],o);let r=s(t,["error"]);r!=null&&l(n,["error"],r);let a=s(t,["rewardInfoDetails"]);return a!=null&&l(n,["rewardInfoDetails"],a),n}var Va=class extends it{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Et(yt.PAGED_ITEM_TUNING_JOBS,i=>this.listInternal(i),await this.listInternal(n),n),this.get=async n=>await this.getInternal(n),this.tune=async n=>{var i;if(this.apiClient.isVertexAI())if(n.baseModel.startsWith("projects/")){let o={tunedModelName:n.baseModel};!((i=n.config)===null||i===void 0)&&i.preTunedModelCheckpointId&&(o.checkpointId=n.config.preTunedModelCheckpointId);let r=Object.assign(Object.assign({},n),{preTunedModel:o});return r.baseModel=void 0,await this.tuneInternal(r)}else{let o=Object.assign({},n);return await this.tuneInternal(o)}else{let o=Object.assign({},n),r=await this.tuneMldevInternal(o),a="";return r.metadata!==void 0&&r.metadata.tunedModel!==void 0?a=r.metadata.tunedModel:r.name!==void 0&&r.name.includes("/operations/")&&(a=r.name.split("/operations/")[0]),{name:a,state:ms.JOB_STATE_QUEUED}}}}async getInternal(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=p0(e);return u=B("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>Ha(f))}else{let d=f0(e);return u=B("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>A0(f))}}async listInternal(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI()){let u=m0(e);return r=B("tuningJobs",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>{let d=g0(c),f=new Cs;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(e){var n,i,o,r;let a,u="",c={};if(this.apiClient.isVertexAI()){let d=n0(e);return u=B("{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=o0(f),h=new Ki;return Object.assign(h,p),h})}else{let d=t0(e);return u=B("{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(r=e.config)===null||r===void 0?void 0:r.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{let p=i0(f),h=new Ki;return Object.assign(h,p),h})}}async tuneInternal(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI()){let u=l0(e,e);return r=B("tuningJobs",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>Ha(c))}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=a0(e);return r=B("tunedModels",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>C0(c))}}async validateReward(e){var n,i;let o,r="",a={};if(this.apiClient.isVertexAI()){let u=I0(e);return r=B("{parent}/tuningJobs:validateReinforcementTuningReward",u._url),a=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(c=>c.json().then(d=>{let f=d;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>{let d=S0(c),f=new Is;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}},Ip=1024*1024*8,Sp=3,wp=1e3,Rp=2,Nt="x-goog-upload-status";async function w0(t,e,n,i){var o;let r=await Pp(t,e,n,i),a=await r?.json();if(((o=r?.headers)===null||o===void 0?void 0:o[Nt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return a.file}async function R0(t,e,n,i){var o;let r=await Pp(t,e,n,i),a=await r?.json();if(((o=r?.headers)===null||o===void 0?void 0:o[Nt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let u=Xa(a),c=new Qi;return Object.assign(c,u),c}async function Pp(t,e,n,i){var o,r,a;let u=e,c=i?.baseUrl||((o=n.clientOptions.httpOptions)===null||o===void 0?void 0:o.baseUrl);if(c){let m=new URL(c),_=new URL(e);_.protocol=m.protocol,_.host=m.host,_.port=m.port,u=_.toString()}let d=0,f=0,p=new Mt(new Response),h="upload";for(d=t.size;f<d;){let m=Math.min(Ip,d-f),_=t.slice(f,f+m);f+m>=d&&(h+=", finalize");let g=0,v=wp;for(;g<Sp;){let y=Object.assign(Object.assign({},i?.headers||{}),{"X-Goog-Upload-Command":h,"X-Goog-Upload-Offset":String(f)});if(p=await n.request({path:"",body:_,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},i),{apiVersion:"",baseUrl:u,headers:y})}),!((r=p?.headers)===null||r===void 0)&&r[Nt])break;g++,await Np(v),v=v*Rp}if(f+=m,((a=p?.headers)===null||a===void 0?void 0:a[Nt])!=="active")break;if(d<=f)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return p}async function P0(t){return{size:t.size,type:t.type}}function Np(t){return new Promise(e=>setTimeout(e,t))}var Ba=class{async stat(e){let n={size:0,type:void 0};if(typeof e=="string"){let i=await ao.stat(e);return n.size=i.size,n.type=this.inferMimeType(e),n}else return await P0(e)}async upload(e,n,i,o){return typeof e=="string"?await this.uploadFileFromPath(e,n,i,o):w0(e,n,i,o)}async uploadToFileSearchStore(e,n,i,o){return typeof e=="string"?await this.uploadFileToFileSearchStoreFromPath(e,n,i,o):R0(e,n,i,o)}inferMimeType(e){let n=e.slice(e.lastIndexOf(".")+1);return{aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"}[n.toLowerCase()]}async uploadFileFromPath(e,n,i,o){var r;let a=await this.uploadFileFromPathInternal(e,n,i,o),u=await a?.json();if(((r=a?.headers)===null||r===void 0?void 0:r[Nt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return u.file}async uploadFileToFileSearchStoreFromPath(e,n,i,o){var r;let a=await this.uploadFileFromPathInternal(e,n,i,o),u=await a?.json();if(((r=a?.headers)===null||r===void 0?void 0:r[Nt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let c=Xa(u),d=new Qi;return Object.assign(d,c),d}async uploadFileFromPathInternal(e,n,i,o){var r,a,u;let c=n,d=o?.baseUrl||((r=i.clientOptions.httpOptions)===null||r===void 0?void 0:r.baseUrl);if(d){let v=new URL(d),y=new URL(n);y.protocol=v.protocol,y.host=v.host,y.port=v.port,c=y.toString()}let f=0,p=0,h=new Mt(new Response),m="upload",_,g=sf.basename(e);try{if(_=await ao.open(e,"r"),!_)throw new Error("Failed to open file");for(f=(await _.stat()).size;p<f;){let v=Math.min(Ip,f-p);p+v>=f&&(m+=", finalize");let y=new Uint8Array(v),{bytesRead:A}=await _.read(y,0,v,p);if(A!==v)throw new Error(`Failed to read ${v} bytes from file at offset ${p}. bytes actually read: ${A}`);let C=new Blob([y]),S=0,R=wp;for(;S<Sp;){let L=Object.assign(Object.assign({},o?.headers||{}),{"X-Goog-Upload-Command":m,"X-Goog-Upload-Offset":String(p),"X-Goog-Upload-File-Name":g});if(h=await i.request({path:"",body:C,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},o),{apiVersion:"",baseUrl:c,headers:L})}),!((a=h?.headers)===null||a===void 0)&&a[Nt])break;S++,await Np(R),R=R*Rp}if(p+=A,((u=h?.headers)===null||u===void 0?void 0:u[Nt])!=="active")break;if(f<=p)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return h}finally{_&&await _.close()}}};var $a=class extends bE{async registerFiles(e){if(typeof process>"u"||!process.versions||!process.versions.node)throw new Error("registerFiles is only supported in Node.js environments.");let i=await e.auth.getRequestHeaders(),o=e.config||{},r=o.httpOptions||{},a=Object.assign({},r.headers||{});if(i)if(typeof i[Symbol.iterator]=="function")for(let[u,c]of i)a[u]=c;else for(let[u,c]of Object.entries(i))a[u]=c;return this._registerFiles({uris:e.uris,config:Object.assign(Object.assign({},o),{httpOptions:Object.assign(Object.assign({},r),{headers:a})})})}};var N0="gl-node/";function k0(t){var e;if(t&&(t.enterprise!==void 0||t.vertexai!==void 0)){if(t.enterprise!==void 0&&t.vertexai!==void 0&&t.enterprise!==t.vertexai)throw new Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return(e=t.enterprise)!==null&&e!==void 0?e:t.vertexai}let n=kt("GOOGLE_GENAI_USE_ENTERPRISE"),i=kt("GOOGLE_GENAI_USE_VERTEXAI"),o=nf(n),r=nf(i);return n!==void 0&&i!==void 0&&o!==r&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),n!==void 0?o:i!==void 0?r:!1}var tf=class{getNextGenClient(){let e=this.httpOptions;return this._nextGenClient===void 0&&(this._nextGenClient=ft(this.apiClient,{timeout_ms:e?.timeout})),e?.extraBody&&console.warn("GoogleGenAI: Client level httpOptions.extraBody is not supported by the Gemini NextGen client and will be ignored."),this._nextGenClient}get interactions(){return this._interactions!==void 0?this._interactions:(this._interactions=new ka(this.apiClient),this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=new xa(this.apiClient),this._webhooks)}get agents(){return this._agents!==void 0?this._agents:(console.warn("GoogleGenAI.agents: Agents usage is experimental and may change in future versions."),this._agents=new Da(this.apiClient),this._agents)}get triggers(){return this._triggers!==void 0?this._triggers:(console.warn("GoogleGenAI.triggers: Triggers usage is experimental and may change in future versions."),this._triggers=new Ma(this.apiClient),this._triggers)}get environments(){return this._environments!==void 0?this._environments:(console.warn("GoogleGenAI.environments: Environments usage is experimental and may change in future versions."),this._environments=new Ga(this.apiClient),this._environments)}constructor(e={}){var n,i,o,r;if(this.vertexai=k0(e),(e.project||e.location)&&!this.vertexai)throw new Error("Project and location are not supported for Gemini API backend.");let a=D0(),u=kt("GOOGLE_CLOUD_PROJECT"),c=kt("GOOGLE_CLOUD_LOCATION");this.apiKey=(n=e.apiKey)!==null&&n!==void 0?n:a,this.project=(i=e.project)!==null&&i!==void 0?i:u,this.location=(o=e.location)!==null&&o!==void 0?o:c,!this.vertexai&&!this.apiKey&&console.warn("API key should be set when using the Gemini API."),this.vertexai&&(!((r=e.googleAuthOptions)===null||r===void 0)&&r.credentials&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),!e.project&&!e.location&&(u||c)&&e.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(e.project||e.location)&&!e.apiKey&&a?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):!e.project&&!e.location&&!e.apiKey&&(u||c)&&a&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),!this.location&&!this.apiKey&&(this.location="global"));let d=w_(e.httpOptions,this.vertexai,kt("GOOGLE_VERTEX_BASE_URL"),kt("GOOGLE_GEMINI_BASE_URL"));d&&(e.httpOptions?e.httpOptions.baseUrl=d:e.httpOptions={baseUrl:d}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let f=new La({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new $s({auth:f,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:N0+process.version,uploader:new Ba,downloader:new ba}),this.models=new mn(this.apiClient),this.live=new Ys(this.apiClient,f,new Oa),this.batches=new bs(this.apiClient),this.chats=new qs(this.models,this.apiClient),this.caches=new Os(this.apiClient),this.files=new $a(this.apiClient),this.operations=new zs(this.apiClient),this.authTokens=new Qs(this.apiClient),this.tunings=new Va(this.apiClient),this.fileSearchStores=new js(this.apiClient)}};function kt(t){var e,n,i;return(i=(n=(e=process==null?void 0:process.env)===null||e===void 0?void 0:e[t])===null||n===void 0?void 0:n.trim())!==null&&i!==void 0?i:void 0}function nf(t){return t===void 0?!1:t.toLowerCase()==="true"}function D0(){let t=kt("GOOGLE_API_KEY"),e=kt("GEMINI_API_KEY");return t&&e&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),t||e||void 0}var x0={THINKING_LEVEL_UNSPECIFIED:Dt.THINKING_LEVEL_UNSPECIFIED,MINIMAL:Dt.MINIMAL,LOW:Dt.LOW,MEDIUM:Dt.MEDIUM,HIGH:Dt.HIGH};function M0(t,e){let n=t.thinkingLevelMap?.[e],i=typeof n=="string"?n.toLowerCase():e;switch(i){case"minimal":case"low":case"medium":case"high":return i;default:throw new Error(`Unsupported Google thinking level mapping for ${t.provider}/${t.id}: ${e} -> ${String(n)}`)}}function U0(t){let e=t.id.toLowerCase();return/gemini-3(?:\.\d+)?-(?:pro|flash)/.test(e)||/gemini-(?:[4-9]|[1-9]\d)/.test(e)||e==="gemini-flash-latest"||e==="gemini-flash-lite-latest"||/gemma-?4/.test(e)}function G0(t){switch(t){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function L0(t){return x0[t]}function cw(t){if(!U0(t))return{thinkingBudget:0};let e=ll(t,"off");if(e==="off")return{thinkingBudget:0};let n=M0(t,e),i=G0(n);return{thinkingLevel:L0(i)}}function dw(t){return t.thought===!0}function fw(t,e){return typeof e=="string"&&e.length>0?e:t}var b0=/^[A-Za-z0-9+/]+={0,2}$/;function O0(t){return!t||t.length%4!==0?!1:b0.test(t)}function ja(t,e){return t&&O0(e)?e:void 0}function el(t){let e=tl(t);return t.startsWith("claude-")||t.startsWith("gpt-oss-")||e!==void 0&&e>=3}function tl(t){let e=t.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(e)return Number.parseInt(e[1],10)}function q0(t){let e=tl(t);return e!==void 0?e>=3:!0}function pw(t,e){let n=sl(al(e).messages),i=[],r=dl(n,t,a=>el(t.id)?a.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64):a);for(let a of r)if(a.role==="user")if(typeof a.content=="string")i.push({role:"user",parts:[{text:qt(a.content)}]});else{let u=a.content.map(c=>c.type==="text"?{text:qt(c.text)}:{inlineData:{mimeType:c.mimeType,data:c.data}});if(u.length===0)continue;i.push({role:"user",parts:u})}else if(a.role==="assistant"){let u=[],c=a.provider===t.provider&&a.model===t.id;for(let d of a.content)if(d.type==="text"){let f=ja(c,d.textSignature);if((!d.text||d.text.trim()==="")&&!f)continue;u.push({text:qt(d.text),...f&&{thoughtSignature:f}})}else if(d.type==="thinking")if(c){let f=ja(c,d.thinkingSignature);if((!d.thinking||d.thinking.trim()==="")&&!f)continue;u.push({thought:!0,text:qt(d.thinking),...f&&{thoughtSignature:f}})}else{if(!d.thinking||d.thinking.trim()==="")continue;u.push({text:qt(d.thinking)})}else if(d.type==="toolCall"){let f=ja(c,d.thoughtSignature),p={functionCall:{name:d.name,args:d.arguments??{},...el(t.id)?{id:d.id}:{}},...f&&{thoughtSignature:f}};u.push(p)}if(u.length===0)continue;i.push({role:"model",parts:u})}else if(a.role==="toolResult"){let c=a.content.filter(A=>A.type==="text").map(A=>A.text).join(`
38
- `),d=t.input.includes("image")?a.content.filter(A=>A.type==="image"):[],f=c.trim().length>0,p=d.length>0,h=q0(t.id),m=f?qt(c):p?"(see attached image)":"",_=d.map(A=>({inlineData:{mimeType:A.mimeType,data:A.data}})),g=el(t.id),v={functionResponse:{name:a.toolName,response:a.isError?{error:m}:{output:m},...p&&h&&{parts:_},...g?{id:a.toolCallId}:{}}},y=i[i.length-1];y?.role==="user"&&y.parts?.some(A=>A.functionResponse)?y.parts.push(v):i.push({role:"user",parts:[v]}),p&&!h&&i.push({role:"user",parts:[{text:"Tool result image:"},..._]})}return i}var F0=new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"]);function Dp(t){if(typeof t!="object"||t===null||Array.isArray(t))return t;let e={};for(let[n,i]of Object.entries(t))F0.has(n)||(e[n]=Dp(i));return e}function hw(t,e=!1,n=!0){if(t.length!==0)return[{functionDeclarations:t.map(i=>{let o=go(i,n),r=cl(i,o);return{name:i.name,description:i.description,...e?{parameters:Dp(r)}:{parametersJsonSchema:r}}})}]}function mw(t){let e=tl(t);return e!==void 0&&e>=3}function kp(t){switch(t){case"auto":return xt.AUTO;case"none":return xt.NONE;case"any":return xt.ANY;default:return xt.AUTO}}function gw(t,e,n){let i=t.some(o=>go(o,n)===!0);return e==="none"||e==="any"?kp(e):i?xt.VALIDATED:e?kp(e):void 0}function _w(t){switch(t){case Ie.STOP:return"stop";case Ie.MAX_TOKENS:return"length";case Ie.BLOCKLIST:case Ie.PROHIBITED_CONTENT:case Ie.SPII:case Ie.SAFETY:case Ie.IMAGE_SAFETY:case Ie.IMAGE_PROHIBITED_CONTENT:case Ie.IMAGE_RECITATION:case Ie.IMAGE_OTHER:case Ie.RECITATION:case Ie.FINISH_REASON_UNSPECIFIED:case Ie.OTHER:case Ie.LANGUAGE:case Ie.MALFORMED_FUNCTION_CALL:case Ie.UNEXPECTED_TOOL_CALL:case Ie.TOO_MANY_TOOL_CALLS:case Ie.NO_IMAGE:return"error";default:{let e=t;throw new Error(`Unhandled stop reason: ${e}`)}}}function yw(t,e){return ul(async()=>{try{return await t()}catch(n){throw n instanceof Error&&"status"in n&&!("headers"in n)&&(n.headers=void 0),n}},{maxRetries:e?.maxRetries,maxRetryDelayMs:e?.maxRetryDelayMs,signal:e?.signal})}export{gs as a,tf as b,M0 as c,U0 as d,G0 as e,L0 as f,cw as g,dw as h,fw as i,pw as j,hw as k,mw as l,gw as m,_w as n,yw as o};
39
- /*! Bundled license information:
40
-
41
- @google/genai/dist/node/index.mjs:
42
- @google/genai/dist/node/index.mjs:
43
- @google/genai/dist/node/index.mjs:
44
- @google/genai/dist/node/index.mjs:
45
- @google/genai/dist/node/index.mjs:
46
- (**
47
- * @license
48
- * Copyright 2025 Google LLC
49
- * SPDX-License-Identifier: Apache-2.0
50
- *)
51
-
52
- @google/genai/dist/node/index.mjs:
53
- (**
54
- * @license
55
- * Copyright 2025 Google LLC
56
- * SPDX-License-Identifier: Apache-2.0
57
- *)
58
- (**
59
- * @license
60
- * Copyright 2026 Google LLC
61
- * SPDX-License-Identifier: Apache-2.0
62
- *
63
- * g3-prettier-ignore-file
64
- *)
65
- */