@maincode-ai/matilda-code 0.21.13 → 0.22.0-nightly.20261102.db95a17c4

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 (252) hide show
  1. package/chunks/agent-4GIFJO5G.js +3 -0
  2. package/chunks/agent-headless-DXJESNI4.js +3 -0
  3. package/chunks/{askUserQuestion-BNSWGD26.js → askUserQuestion-7PM7G5YF.js} +3 -3
  4. package/chunks/ca-JKEHLTNL.js +23 -0
  5. package/chunks/chunk-225CZWD7.js +89 -0
  6. package/chunks/chunk-2QIC3OCV.js +9 -0
  7. package/chunks/chunk-33UVJMVE.js +120 -0
  8. package/chunks/chunk-35BBGAHD.js +2604 -0
  9. package/chunks/{chunk-DHDD5YJC.js → chunk-4KS2KEXK.js} +69 -69
  10. package/chunks/chunk-4MLFC664.js +3 -0
  11. package/chunks/{chunk-RNKDFE2S.js → chunk-5B2QERWR.js} +1 -1
  12. package/chunks/chunk-66WJUORA.js +8 -0
  13. package/chunks/chunk-6U5VOTWB.js +56 -0
  14. package/chunks/chunk-7MUWF4DK.js +80 -0
  15. package/chunks/{chunk-6M5G5FBH.js → chunk-BVTXZTL3.js} +1 -1
  16. package/chunks/chunk-CVGGYRNK.js +31 -0
  17. package/chunks/chunk-DUB7JMQV.js +13 -0
  18. package/chunks/chunk-ESNPNLMQ.js +8 -0
  19. package/chunks/chunk-GT6MSEK4.js +3 -0
  20. package/chunks/chunk-HEJO7OBH.js +3 -0
  21. package/chunks/chunk-JNHB73E3.js +9 -0
  22. package/chunks/chunk-JR5CSCG4.js +8 -0
  23. package/chunks/{chunk-EZDV7A76.js → chunk-KRVXBQRC.js} +1 -1
  24. package/chunks/{chunk-AOOZREGV.js → chunk-LBQNFSZ2.js} +1 -1
  25. package/chunks/{chunk-MEV5XQI2.js → chunk-QBXL5UBB.js} +1 -1
  26. package/chunks/{chunk-P5TG5CON.js → chunk-QDWS3VZT.js} +1 -1
  27. package/chunks/{chunk-QZI2ZGZY.js → chunk-QMZREVY3.js} +1 -1
  28. package/chunks/chunk-QUYQBKDE.js +8 -0
  29. package/chunks/chunk-QXSBPCBA.js +8 -0
  30. package/chunks/chunk-S2E5ZRPH.js +14 -0
  31. package/chunks/chunk-TUKNB5CQ.js +33 -0
  32. package/chunks/chunk-UM6CLO7D.js +7 -0
  33. package/chunks/{chunk-6T2GIM76.js → chunk-VVUY7VKR.js} +1 -1
  34. package/chunks/{chunk-5OHGYMKP.js → chunk-WENVHSCJ.js} +1 -1
  35. package/chunks/{chunk-27Q5KW3A.js → chunk-ZABH4QIL.js} +10 -10
  36. package/chunks/chunk-ZSGBDQXU.js +11 -0
  37. package/chunks/{computer-use-J4GAM4M6.js → computer-use-IZGLKENV.js} +1 -1
  38. package/chunks/{cron-create-IDWSZENI.js → cron-create-BTSJUVNT.js} +1 -1
  39. package/chunks/cron-delete-PTE3RC2W.js +3 -0
  40. package/chunks/cron-list-SINKHOIZ.js +5 -0
  41. package/chunks/de-GMGNR5CZ.js +23 -0
  42. package/chunks/{devtools-XRQ4YJ5S.js → devtools-7YNCRYZV.js} +1 -1
  43. package/chunks/{chunk-OOEH6ZSV.js → dist-UWUWLWTO.js} +2 -2
  44. package/chunks/{edit-X2S2ZXRN.js → edit-MDQEZ7BA.js} +1 -1
  45. package/chunks/en-3NQMLVKW.js +23 -0
  46. package/chunks/{enter-worktree-TUCGNCLO.js → enter-worktree-SZK65VXF.js} +1 -1
  47. package/chunks/enterPlanMode-5VWIIVHI.js +18 -0
  48. package/chunks/{exit-worktree-7FLITFZI.js → exit-worktree-OBHUK4TF.js} +1 -1
  49. package/chunks/{exitPlanMode-O5UUJ3GM.js → exitPlanMode-SXFQC4G2.js} +2 -2
  50. package/chunks/fr-WS3EBB36.js +23 -0
  51. package/chunks/{getMachineId-bsd-ZYBNK2JG.js → getMachineId-bsd-ETKQTB6C.js} +1 -1
  52. package/chunks/{getMachineId-darwin-CM2MQGUI.js → getMachineId-darwin-AKNRWOWB.js} +1 -1
  53. package/chunks/{getMachineId-linux-SYE2KMCW.js → getMachineId-linux-2QSD7FTP.js} +1 -1
  54. package/chunks/{getMachineId-unsupported-6IHVG2XO.js → getMachineId-unsupported-UXSV7I24.js} +1 -1
  55. package/chunks/{getMachineId-win-S3J3JSUM.js → getMachineId-win-4MTFXGP3.js} +1 -1
  56. package/chunks/glob-JKIZ3ZJQ.js +22 -0
  57. package/chunks/{goal-tools-YQOA6OKU.js → goal-tools-YJMECZYD.js} +3 -3
  58. package/chunks/{grep-VAB2VSXM.js → grep-Q4T5AE6K.js} +1 -1
  59. package/chunks/ja-GBCDQ43R.js +23 -0
  60. package/chunks/keychain-token-storage-4PY5J6U6.js +3 -0
  61. package/chunks/ls-BQCCCPIX.js +15 -0
  62. package/chunks/{lsp-NGLDRHZU.js → lsp-MHJJJ7K3.js} +1 -1
  63. package/chunks/mcp-client-CSF5QZEY.js +3 -0
  64. package/chunks/monitor-JUAVWVLY.js +32 -0
  65. package/chunks/{multipart-parser-JI75T2O5.js → multipart-parser-FKHYAVGR.js} +1 -1
  66. package/chunks/notebook-edit-NNOMEUER.js +17 -0
  67. package/chunks/openaiContentGenerator-DTKOYRBL.js +47 -0
  68. package/chunks/pt-VID6J2CM.js +23 -0
  69. package/chunks/read-file-4EX4B3TB.js +3 -0
  70. package/chunks/ripGrep-JL6UDNCR.js +3 -0
  71. package/chunks/ru-EB6V6EAN.js +23 -0
  72. package/chunks/scheduler-GCGZAI7D.js +8 -0
  73. package/chunks/send-message-S4P5QKSW.js +8 -0
  74. package/chunks/shell-J7EX7B57.js +3 -0
  75. package/chunks/{skill-ETQM5NI3.js → skill-V6NTJ4O4.js} +1 -1
  76. package/chunks/src-LZEU4AYF.js +5 -0
  77. package/chunks/symbol-search-5QJNW7PY.js +19 -0
  78. package/chunks/{syntheticOutput-WZDPECYS.js → syntheticOutput-3XIAIUIR.js} +1 -1
  79. package/chunks/task-create-KGPY7O4J.js +3 -0
  80. package/chunks/{task-detach-TBAVUOTC.js → task-detach-ZD3A7225.js} +1 -1
  81. package/chunks/task-list-P7GQWYAD.js +9 -0
  82. package/chunks/{task-stop-HDSARSJ6.js → task-stop-VFJRBA6P.js} +1 -1
  83. package/chunks/{task-update-MW2VT2XV.js → task-update-OOMH4WRA.js} +1 -1
  84. package/chunks/{team-create-VMYNLZCC.js → team-create-POMZOM44.js} +2 -2
  85. package/chunks/team-delete-ZJBEQDPE.js +8 -0
  86. package/chunks/todoWrite-EWYRFK7W.js +3 -0
  87. package/chunks/{tool-search-WX6FOE35.js → tool-search-5Z7MO565.js} +1 -1
  88. package/chunks/{web-fetch-CKYBHGLF.js → web-fetch-M4TUYAFG.js} +17 -17
  89. package/chunks/web-search-CBKF36JM.js +26 -0
  90. package/chunks/{workflow-WBSRQG3N.js → workflow-F57TWWPS.js} +2 -2
  91. package/chunks/write-file-UK4BVL3M.js +15 -0
  92. package/cli.js +642 -678
  93. package/examples/starter/README.md +0 -3
  94. package/locales/ca.js +3 -87
  95. package/locales/de.js +3 -91
  96. package/locales/en.js +3 -91
  97. package/locales/fr.js +3 -88
  98. package/locales/ja.js +3 -92
  99. package/locales/pt.js +3 -92
  100. package/locales/ru.js +3 -91
  101. package/package.json +2 -2
  102. package/sandbox-macos-permissive-proxied.sb +1 -1
  103. package/sandbox-macos-restrictive-closed.sb +14 -1
  104. package/sandbox-macos-restrictive-open.sb +14 -1
  105. package/sandbox-macos-restrictive-proxied.sb +15 -2
  106. package/bundled/mainy/SKILL.md +0 -157
  107. package/bundled/mainy/docs/_meta.ts +0 -32
  108. package/bundled/mainy/docs/common-workflow.md +0 -571
  109. package/bundled/mainy/docs/configuration/_meta.ts +0 -7
  110. package/bundled/mainy/docs/configuration/auth.md +0 -82
  111. package/bundled/mainy/docs/configuration/matilda-ignore.md +0 -55
  112. package/bundled/mainy/docs/configuration/model-providers.md +0 -516
  113. package/bundled/mainy/docs/configuration/settings.md +0 -818
  114. package/bundled/mainy/docs/configuration/themes.md +0 -199
  115. package/bundled/mainy/docs/configuration/trusted-folders.md +0 -67
  116. package/bundled/mainy/docs/extension/_meta.ts +0 -9
  117. package/bundled/mainy/docs/extension/extension-releasing.md +0 -204
  118. package/bundled/mainy/docs/extension/getting-started-extensions.md +0 -299
  119. package/bundled/mainy/docs/extension/introduction.md +0 -338
  120. package/bundled/mainy/docs/features/_meta.ts +0 -27
  121. package/bundled/mainy/docs/features/approval-mode.md +0 -388
  122. package/bundled/mainy/docs/features/arena.md +0 -219
  123. package/bundled/mainy/docs/features/auto-mode.md +0 -308
  124. package/bundled/mainy/docs/features/channels/_meta.ts +0 -5
  125. package/bundled/mainy/docs/features/channels/overview.md +0 -328
  126. package/bundled/mainy/docs/features/channels/plugins.md +0 -87
  127. package/bundled/mainy/docs/features/channels/telegram.md +0 -120
  128. package/bundled/mainy/docs/features/code-review.md +0 -291
  129. package/bundled/mainy/docs/features/commands.md +0 -528
  130. package/bundled/mainy/docs/features/dual-output.md +0 -627
  131. package/bundled/mainy/docs/features/followup-suggestions.md +0 -109
  132. package/bundled/mainy/docs/features/headless.md +0 -448
  133. package/bundled/mainy/docs/features/hooks.md +0 -1308
  134. package/bundled/mainy/docs/features/language.md +0 -144
  135. package/bundled/mainy/docs/features/lsp.md +0 -496
  136. package/bundled/mainy/docs/features/markdown-rendering.md +0 -183
  137. package/bundled/mainy/docs/features/mcp.md +0 -423
  138. package/bundled/mainy/docs/features/memory.md +0 -185
  139. package/bundled/mainy/docs/features/sandbox.md +0 -249
  140. package/bundled/mainy/docs/features/scheduled-tasks.md +0 -139
  141. package/bundled/mainy/docs/features/skills.md +0 -347
  142. package/bundled/mainy/docs/features/status-line.md +0 -397
  143. package/bundled/mainy/docs/features/structured-output.md +0 -309
  144. package/bundled/mainy/docs/features/sub-agents.md +0 -737
  145. package/bundled/mainy/docs/features/tips.md +0 -54
  146. package/bundled/mainy/docs/features/token-caching.md +0 -29
  147. package/bundled/mainy/docs/features/tool-use-summaries.md +0 -178
  148. package/bundled/mainy/docs/features/worktree.md +0 -343
  149. package/bundled/mainy/docs/ide-integration/_meta.ts +0 -4
  150. package/bundled/mainy/docs/ide-integration/ide-companion-spec.md +0 -182
  151. package/bundled/mainy/docs/ide-integration/ide-integration.md +0 -144
  152. package/bundled/mainy/docs/integration-github-action.md +0 -241
  153. package/bundled/mainy/docs/integration-jetbrains.md +0 -81
  154. package/bundled/mainy/docs/integration-vscode.md +0 -39
  155. package/bundled/mainy/docs/integration-zed.md +0 -72
  156. package/bundled/mainy/docs/matilda-serve-deploy-local.md +0 -221
  157. package/bundled/mainy/docs/matilda-serve.md +0 -661
  158. package/bundled/mainy/docs/overview.md +0 -64
  159. package/bundled/mainy/docs/quickstart.md +0 -234
  160. package/bundled/mainy/docs/reference/_meta.ts +0 -3
  161. package/bundled/mainy/docs/reference/keyboard-shortcuts.md +0 -91
  162. package/bundled/mainy/docs/support/Uninstall.md +0 -65
  163. package/bundled/mainy/docs/support/_meta.ts +0 -6
  164. package/bundled/mainy/docs/support/tos-privacy.md +0 -94
  165. package/bundled/mainy/docs/support/troubleshooting.md +0 -127
  166. package/chunks/agent-SRAIVZEE.js +0 -3
  167. package/chunks/agent-headless-XRDOZESG.js +0 -3
  168. package/chunks/anthropicContentGenerator-LLDIKDMQ.js +0 -39
  169. package/chunks/ca-NPYL24ME.js +0 -25
  170. package/chunks/chunk-27HUYW23.js +0 -22
  171. package/chunks/chunk-2HTPVSGT.js +0 -3
  172. package/chunks/chunk-3B2HABK7.js +0 -30
  173. package/chunks/chunk-3MTZTNAU.js +0 -101
  174. package/chunks/chunk-3YLXGE6T.js +0 -8
  175. package/chunks/chunk-47XR7IMP.js +0 -8
  176. package/chunks/chunk-4F4DA5UI.js +0 -8
  177. package/chunks/chunk-4Q2SNBUH.js +0 -18
  178. package/chunks/chunk-6EQMZNIY.js +0 -8
  179. package/chunks/chunk-6I6VGTKD.js +0 -8
  180. package/chunks/chunk-DC7LAFZZ.js +0 -8
  181. package/chunks/chunk-DE3HKC2W.js +0 -9
  182. package/chunks/chunk-FWDMPRKU.js +0 -3
  183. package/chunks/chunk-G7R2XEEF.js +0 -7
  184. package/chunks/chunk-GOJCMVJJ.js +0 -8
  185. package/chunks/chunk-GTVCJCHR.js +0 -8
  186. package/chunks/chunk-IJEGHQ7Z.js +0 -32
  187. package/chunks/chunk-JCE3JAVC.js +0 -25
  188. package/chunks/chunk-KHHJYBR5.js +0 -9
  189. package/chunks/chunk-LUNDTQ3G.js +0 -8
  190. package/chunks/chunk-LWARA7JY.js +0 -37
  191. package/chunks/chunk-M53RP3YP.js +0 -31
  192. package/chunks/chunk-MTMU7JYZ.js +0 -11
  193. package/chunks/chunk-O44XK65C.js +0 -8
  194. package/chunks/chunk-OA56BXPD.js +0 -3
  195. package/chunks/chunk-PEKAUGYV.js +0 -2621
  196. package/chunks/chunk-PGUG43HG.js +0 -24
  197. package/chunks/chunk-PGXQZVLX.js +0 -8
  198. package/chunks/chunk-QKYGQLWC.js +0 -8
  199. package/chunks/chunk-QN6Y6NPA.js +0 -3
  200. package/chunks/chunk-RI54U73U.js +0 -56
  201. package/chunks/chunk-RPFSFS7Z.js +0 -39
  202. package/chunks/chunk-SDTWBD62.js +0 -8
  203. package/chunks/chunk-SOEIVSM5.js +0 -113
  204. package/chunks/chunk-SVSY6AWS.js +0 -59
  205. package/chunks/chunk-T2T2UEPY.js +0 -4
  206. package/chunks/chunk-TISQNFB5.js +0 -3
  207. package/chunks/chunk-TWJLOEAI.js +0 -31
  208. package/chunks/chunk-VI74YQQO.js +0 -8
  209. package/chunks/chunk-VYZOOSMP.js +0 -30
  210. package/chunks/chunk-W4QSMIWO.js +0 -9
  211. package/chunks/chunk-WC2VTVCE.js +0 -27
  212. package/chunks/chunk-YV3PUOBU.js +0 -65
  213. package/chunks/chunk-ZX34M2GF.js +0 -14
  214. package/chunks/contextCommand-5F5M7NA4.js +0 -3
  215. package/chunks/cron-delete-NQCDZDUI.js +0 -3
  216. package/chunks/cron-list-Z4XMC3TO.js +0 -5
  217. package/chunks/de-34YZHGC6.js +0 -25
  218. package/chunks/dist-7UYRLSLE.js +0 -3
  219. package/chunks/dist-PH6JW7XD.js +0 -42
  220. package/chunks/en-QLGMD6OS.js +0 -25
  221. package/chunks/enterPlanMode-SQEZAAIR.js +0 -18
  222. package/chunks/fileFromPath-7UCWPD4W.js +0 -3
  223. package/chunks/fr-EDNBQACJ.js +0 -25
  224. package/chunks/geminiContentGenerator-FIZFLPU3.js +0 -8
  225. package/chunks/glob-GSFTYAS2.js +0 -22
  226. package/chunks/ja-LV4RLM3M.js +0 -25
  227. package/chunks/keychain-token-storage-KQK6MNOJ.js +0 -3
  228. package/chunks/ls-IZJ3CKZY.js +0 -15
  229. package/chunks/matildaAgentContentGenerator-QQHPCFJ5.js +0 -8
  230. package/chunks/matildaContentGenerator-W7Z33ONU.js +0 -8
  231. package/chunks/matildaOAuth2-7COTQQR2.js +0 -3
  232. package/chunks/mcp-client-DXUNIEIB.js +0 -3
  233. package/chunks/monitor-4PFIGAGG.js +0 -32
  234. package/chunks/notebook-edit-MWJYAATJ.js +0 -17
  235. package/chunks/openaiContentGenerator-NDVJL6QL.js +0 -3
  236. package/chunks/pt-5SQ4DGL7.js +0 -25
  237. package/chunks/read-file-WPZKPXWA.js +0 -3
  238. package/chunks/ripGrep-7LZDZFTX.js +0 -3
  239. package/chunks/ru-7K24S53N.js +0 -25
  240. package/chunks/scheduler-DK2MVKXX.js +0 -8
  241. package/chunks/send-message-TCPX5UDU.js +0 -8
  242. package/chunks/serve-GSZPJI2O.js +0 -1026
  243. package/chunks/shell-PRS47PDP.js +0 -3
  244. package/chunks/src-UB7DZRYK.js +0 -3
  245. package/chunks/src-WZTRMETQ.js +0 -5
  246. package/chunks/symbol-search-HARHZ5AH.js +0 -19
  247. package/chunks/task-create-XRNIDT4T.js +0 -3
  248. package/chunks/task-list-Z6BDZZID.js +0 -9
  249. package/chunks/team-delete-F7QDC2TE.js +0 -8
  250. package/chunks/todoWrite-SCF5M24M.js +0 -3
  251. package/chunks/web-search-67DFNS5V.js +0 -26
  252. package/chunks/write-file-S5FAX4JJ.js +0 -15
@@ -1,59 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{a as Ka}from"./chunk-AOOZREGV.js";import{b as D}from"./chunk-GZPNIYVZ.js";import{a as Q,d as B,f as Ja}from"./chunk-OWGSC52X.js";var Ya=B((OS,Wa)=>{D();function xe(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Wa.exports=xe;xe.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};xe.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};xe.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},n),this._options.unref&&this._timer.unref(),!0};xe.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};xe.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};xe.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};xe.prototype.start=xe.prototype.try;xe.prototype.errors=function(){return this._errors};xe.prototype.attempts=function(){return this._attempts};xe.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,n=0,i=0;i<this._errors.length;i++){var o=this._errors[i],s=o.message,l=(t[s]||0)+1;t[s]=l,l>=n&&(e=o,n=l)}return e}});var za=B(vt=>{D();var dp=Ya();vt.operation=function(t){var e=vt.timeouts(t);return new dp(e,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};vt.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in t)e[n]=t[n];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],o=0;o<e.retries;o++)i.push(this.createTimeout(o,e));return t&&t.forever&&!i.length&&i.push(this.createTimeout(o,e)),i.sort(function(s,l){return s-l}),i};vt.createTimeout=function(t,e){var n=e.randomize?Math.random()+1:1,i=Math.round(n*Math.max(e.minTimeout,1)*Math.pow(e.factor,t));return i=Math.min(i,e.maxTimeout),i};vt.wrap=function(t,e,n){if(e instanceof Array&&(n=e,e=null),!n){n=[];for(var i in t)typeof t[i]=="function"&&n.push(i)}for(var o=0;o<n.length;o++){var s=n[o],l=t[s];t[s]=function(c){var d=vt.operation(e),f=Array.prototype.slice.call(arguments,1),p=f.pop();f.push(function(h){d.retry(h)||(h&&(arguments[0]=d.mainError()),p.apply(this,arguments))}),d.attempt(function(){c.apply(t,f)})}.bind(t,l),t[s].options=e}}});var Qa=B((VS,Xa)=>{D();Xa.exports=za()});var ja=B((JS,kn)=>{"use strict";D();var fp=Qa(),pp=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],xn=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},hp=(t,e,n)=>{let i=n.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=i,t},mp=t=>pp.includes(t),Za=(t,e)=>new Promise((n,i)=>{e={onFailedAttempt:()=>{},retries:10,...e};let o=fp.operation(e);o.attempt(async s=>{try{n(await t(s))}catch(l){if(!(l instanceof Error)){i(new TypeError(`Non-error was thrown: "${l}". You should only throw errors.`));return}if(l instanceof xn)o.stop(),i(l.originalError);else if(l instanceof TypeError&&!mp(l.message))o.stop(),i(l);else{hp(l,s,e);try{await e.onFailedAttempt(l)}catch(u){i(u);return}o.retry(l)||i(o.mainError())}}})});kn.exports=Za;kn.exports.default=Za;kn.exports.AbortError=xn});var Po=B((WS,al)=>{"use strict";D();var Un=Object.prototype.hasOwnProperty,sl=Object.prototype.toString,el=Object.defineProperty,tl=Object.getOwnPropertyDescriptor,nl=function(e){return typeof Array.isArray=="function"?Array.isArray(e):sl.call(e)==="[object Array]"},il=function(e){if(!e||sl.call(e)!=="[object Object]")return!1;var n=Un.call(e,"constructor"),i=e.constructor&&e.constructor.prototype&&Un.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!i)return!1;var o;for(o in e);return typeof o>"u"||Un.call(e,o)},ol=function(e,n){el&&n.name==="__proto__"?el(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},rl=function(e,n){if(n==="__proto__")if(Un.call(e,n)){if(tl)return tl(e,n).value}else return;return e[n]};al.exports=function t(){var e,n,i,o,s,l,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=rl(u,n),o=rl(e,n),u!==o&&(f&&o&&(il(o)||(s=nl(o)))?(s?(s=!1,l=i&&nl(i)?i:[]):l=i&&il(i)?i:{},ol(u,{name:n,newValue:t(f,l,o)})):typeof o<"u"&&ol(u,{name:n,newValue:o}));return u}});var ll=B((zS,gp)=>{gp.exports={name:"gaxios",version:"7.1.4",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","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.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":"^22.13.1","@types/sinon":"^17.0.3","@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.1",linkinator:"^6.1.2",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.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",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-core/tree/main/packages/gaxios"}});var cl=B((XS,ul)=>{"use strict";D();var yp=ll();ul.exports={pkg:yp}});var Do=B(ke=>{"use strict";D();var fl=ke&&ke.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ke,"__esModule",{value:!0});ke.GaxiosError=ke.GAXIOS_ERROR_SYMBOL=void 0;ke.defaultErrorRedactor=pl;var dl=fl(Po()),Ep=fl(cl()),Ro=Ep.default.pkg;ke.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Ro.name}-gaxios-error`);var No=class t extends Error{config;response;code;status;error;[ke.GAXIOS_ERROR_SYMBOL]=Ro.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&ke.GAXIOS_ERROR_SYMBOL in e&&e[ke.GAXIOS_ERROR_SYMBOL]===Ro.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,dl.default)(!0,{},n),this.response&&(this.response.config=(0,dl.default)(!0,{},this.response.config)),this.response){try{this.response.data=_p(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,s="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 l=[];for(let u of e.data.error.errors)typeof u=="object"&&"message"in u&&typeof u.message=="string"&&l.push(u.message);return Object.assign({message:l.join(`
4
- `)||i,code:s,status:o},e.data.error)}return Object.assign({message:i,code:s,status:o},e.data.error)}}return{message:i,code:e.status,status:e.statusText}}};ke.GaxiosError=No;function _p(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 pl(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(s){s&&s.forEach((l,u)=>{(/^authentication$/i.test(u)||/^authorization$/i.test(u)||/secret/i.test(u))&&s.set(u,e)})}function i(s,l){if(typeof s=="object"&&s!==null&&typeof s[l]=="string"){let u=s[l];(/grant_type=/i.test(u)||/assertion=/i.test(u)||/secret/i.test(u))&&(s[l]=e)}}function o(s){!s||typeof s!="object"||(s instanceof FormData||s instanceof URLSearchParams||"forEach"in s&&"set"in s?s.forEach((l,u)=>{(["grant_type","assertion"].includes(u)||/secret/.test(u))&&s.set(u,e)}):("grant_type"in s&&(s.grant_type=e),"assertion"in s&&(s.assertion=e),"client_secret"in s&&(s.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&&(pl({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(i(t.response,"data"),o(t.response.data))),t}});var ml=B(Mo=>{"use strict";D();Object.defineProperty(Mo,"__esModule",{value:!0});Mo.getRetryConfig=Tp;async function Tp(t){let e=hl(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||Ap)(t))return{shouldRetry:!1,config:t.config};let o=vp(e);t.config.retryConfig.currentRetryAttempt+=1;let s=e.retryBackoff?e.retryBackoff(t,o):new Promise(l=>{setTimeout(l,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await s,{shouldRetry:!0,config:t.config}}function Ap(t){let e=hl(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 s=t.response.status;if(s>=i&&s<=o){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function hl(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function vp(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 ko=B(Gn=>{"use strict";D();Object.defineProperty(Gn,"__esModule",{value:!0});Gn.GaxiosInterceptorManager=void 0;var xo=class extends Set{};Gn.GaxiosInterceptorManager=xo});var El=B(xt=>{"use strict";D();var Cp=xt&&xt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Mt;Object.defineProperty(xt,"__esModule",{value:!0});xt.Gaxios=void 0;var Sp=Cp(Po()),Ip=Q("https"),Ct=Do(),wp=ml(),gl=Q("stream"),yl=ko(),Pp=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),Rp=204,Ln=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new yl.GaxiosInterceptorManager,response:new yl.GaxiosInterceptorManager}}fetch(...e){let n=e[0],i=e[1],o,s=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&&Mt.mergeHeaders(s,n.headers),i&&Mt.mergeHeaders(s,new Headers(i.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...i,...n,headers:s,url:o}):this.request({...i,headers:s,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 Mt.#l(),i={...e};delete i.data;let o=await n(e.url,i),s=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(o,{config:e,data:s})}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 s of n.data)o.push(s);n.data=o.toString()}let i=Ct.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new Ct.GaxiosError(i?.message,e,n,i)}return n}catch(n){let i;n instanceof Ct.GaxiosError?i=n:n instanceof Error?i=new Ct.GaxiosError(n.message,e,void 0,n):i=new Ct.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:s}=await(0,wp.getRetryConfig)(i);if(o&&s)return i.config.retryConfig.currentRetryAttempt=s.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===Rp)return"";if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new Ct.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],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let l of s)o.push(l.trim());for(let l of o)if(l instanceof RegExp){if(l.test(i.toString()))return!1}else if(l instanceof URL){if(l.origin===i.origin)return!1}else if(l.startsWith("*.")||l.startsWith(".")){let u=l.replace(/^\*\./,".");if(i.hostname.endsWith(u))return!1}else if(l===i.origin||l===i.hostname||l===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);Mt.mergeHeaders(n,e.headers);let i=(0,Sp.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 l=i.paramsSerializer(i.params);l.startsWith("?")&&(l=l.slice(1));let u=i.url.toString().includes("?")?"&":"?";i.url=i.url+u+l}else{let l=i.url instanceof URL?i.url:new URL(i.url);for(let[u,c]of new URLSearchParams(i.params))l.searchParams.append(u,c);i.url=l}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 gl.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 l=await Pp();n.set("content-type",`multipart/related; boundary=${l}`),i.body=gl.Readable.from(this.getMultipartRequest(i.multipart,l))}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 s=i.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!i.agent)if(s&&this.#e(i.url,i.noProxy)){let l=await Mt.#a();this.agentCache.has(s)?i.agent=this.agentCache.get(s):(i.agent=new l(s,{cert:i.cert,key:i.key}),this.agentCache.set(s,i.agent))}else i.cert&&i.key&&(this.agentCache.has(i.key)?i.agent=this.agentCache.get(i.key):(i.agent=new Ip.Agent({cert:i.cert,key:i.key}),this.agentCache.set(i.key,i.agent)));return typeof i.errorRedactor!="function"&&i.errorRedactor!==!1&&(i.errorRedactor=Ct.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 s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
5
- Content-Type: ${s}\r
6
- \r
7
- `,typeof o.content=="string"?yield o.content:yield*o.content,yield`\r
8
- `}yield i}static#r;static#s;static async#a(){return this.#r||=(await import("./dist-7UYRLSLE.js")).HttpsProxyAgent,this.#r}static async#l(){let e=typeof window<"u"&&!!window;return this.#s||=e?window.fetch:(await import("./src-WZTRMETQ.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((s,l)=>{l==="set-cookie"?e.append(l,s):e.set(l,s)});return e}};xt.Gaxios=Ln;Mt=Ln});var me=B(_e=>{"use strict";D();var Np=_e&&_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]}),Dp=_e&&_e.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Np(e,t,n)};Object.defineProperty(_e,"__esModule",{value:!0});_e.instance=_e.Gaxios=_e.GaxiosError=void 0;_e.request=xp;var _l=El();Object.defineProperty(_e,"Gaxios",{enumerable:!0,get:function(){return _l.Gaxios}});var Mp=Do();Object.defineProperty(_e,"GaxiosError",{enumerable:!0,get:function(){return Mp.GaxiosError}});Dp(ko(),_e);_e.instance=new _l.Gaxios;async function xp(t){return _e.instance.request(t)}});var Uo=B((Tl,bn)=>{D();(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,i=Math.ceil,o=Math.floor,s="[BigNumber Error] ",l=s+"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(L){var P,q,J,R=O.prototype={constructor:O,toString:null,valueOf:null},$=new O(1),X=20,Z=4,se=-7,te=21,re=-1e7,de=1e7,Ie=!1,Be=1,ae=0,ot={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},At="0123456789abcdefghijklmnopqrstuvwxyz",vo=!0;function O(g,y){var _,M,C,w,k,v,I,x,N=this;if(!(N instanceof O))return new O(g,y);if(y==null){if(g&&g._isBigNumber===!0){N.s=g.s,!g.c||g.e>de?N.c=N.e=null:g.e<re?N.c=[N.e=0]:(N.e=g.e,N.c=g.c.slice());return}if((v=typeof g=="number")&&g*0==0){if(N.s=1/g<0?(g=-g,-1):1,g===~~g){for(w=0,k=g;k>=10;k/=10,w++);w>de?N.c=N.e=null:(N.e=w,N.c=[g]);return}x=String(g)}else{if(!n.test(x=String(g)))return J(N,x,v);N.s=x.charCodeAt(0)==45?(x=x.slice(1),-1):1}(w=x.indexOf("."))>-1&&(x=x.replace(".","")),(k=x.search(/e/i))>0?(w<0&&(w=k),w+=+x.slice(k+1),x=x.substring(0,k)):w<0&&(w=x.length)}else{if(S(y,2,At.length,"Base"),y==10&&vo)return N=new O(g),De(N,X+N.e+1,Z);if(x=String(g),v=typeof g=="number"){if(g*0!=0)return J(N,x,v,y);if(N.s=1/g<0?(x=x.slice(1),-1):1,O.DEBUG&&x.replace(/^0\.0*|\./,"").length>15)throw Error(l+g)}else N.s=x.charCodeAt(0)===45?(x=x.slice(1),-1):1;for(_=At.slice(0,y),w=k=0,I=x.length;k<I;k++)if(_.indexOf(M=x.charAt(k))<0){if(M=="."){if(k>w){w=I;continue}}else if(!C&&(x==x.toUpperCase()&&(x=x.toLowerCase())||x==x.toLowerCase()&&(x=x.toUpperCase()))){C=!0,k=-1,w=0;continue}return J(N,String(g),v,y)}v=!1,x=q(x,y,10,N.s),(w=x.indexOf("."))>-1?x=x.replace(".",""):w=x.length}for(k=0;x.charCodeAt(k)===48;k++);for(I=x.length;x.charCodeAt(--I)===48;);if(x=x.slice(k,++I)){if(I-=k,v&&O.DEBUG&&I>15&&(g>d||g!==o(g)))throw Error(l+N.s*g);if((w=w-k-1)>de)N.c=N.e=null;else if(w<re)N.c=[N.e=0];else{if(N.e=w,N.c=[],k=(w+1)%c,w<0&&(k+=c),k<I){for(k&&N.c.push(+x.slice(0,k)),I-=c;k<I;)N.c.push(+x.slice(k,k+=c));k=c-(x=x.slice(k)).length}else k-=I;for(;k--;x+="0");N.c.push(+x)}}else N.c=[N.e=0]}O.clone=m,O.ROUND_UP=0,O.ROUND_DOWN=1,O.ROUND_CEIL=2,O.ROUND_FLOOR=3,O.ROUND_HALF_UP=4,O.ROUND_HALF_DOWN=5,O.ROUND_HALF_EVEN=6,O.ROUND_HALF_CEIL=7,O.ROUND_HALF_FLOOR=8,O.EUCLID=9,O.config=O.set=function(g){var y,_;if(g!=null)if(typeof g=="object"){if(g.hasOwnProperty(y="DECIMAL_PLACES")&&(_=g[y],S(_,0,h,y),X=_),g.hasOwnProperty(y="ROUNDING_MODE")&&(_=g[y],S(_,0,8,y),Z=_),g.hasOwnProperty(y="EXPONENTIAL_AT")&&(_=g[y],_&&_.pop?(S(_[0],-h,0,y),S(_[1],0,h,y),se=_[0],te=_[1]):(S(_,-h,h,y),se=-(te=_<0?-_:_))),g.hasOwnProperty(y="RANGE"))if(_=g[y],_&&_.pop)S(_[0],-h,-1,y),S(_[1],1,h,y),re=_[0],de=_[1];else if(S(_,-h,h,y),_)re=-(de=_<0?-_:_);else throw Error(s+y+" cannot be zero: "+_);if(g.hasOwnProperty(y="CRYPTO"))if(_=g[y],_===!!_)if(_)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))Ie=_;else throw Ie=!_,Error(s+"crypto unavailable");else Ie=_;else throw Error(s+y+" not true or false: "+_);if(g.hasOwnProperty(y="MODULO_MODE")&&(_=g[y],S(_,0,9,y),Be=_),g.hasOwnProperty(y="POW_PRECISION")&&(_=g[y],S(_,0,h,y),ae=_),g.hasOwnProperty(y="FORMAT"))if(_=g[y],typeof _=="object")ot=_;else throw Error(s+y+" not an object: "+_);if(g.hasOwnProperty(y="ALPHABET"))if(_=g[y],typeof _=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(_))vo=_.slice(0,10)=="0123456789",At=_;else throw Error(s+y+" invalid: "+_)}else throw Error(s+"Object expected: "+g);return{DECIMAL_PLACES:X,ROUNDING_MODE:Z,EXPONENTIAL_AT:[se,te],RANGE:[re,de],CRYPTO:Ie,MODULO_MODE:Be,POW_PRECISION:ae,FORMAT:ot,ALPHABET:At}},O.isBigNumber=function(g){if(!g||g._isBigNumber!==!0)return!1;if(!O.DEBUG)return!0;var y,_,M=g.c,C=g.e,w=g.s;e:if({}.toString.call(M)=="[object Array]"){if((w===1||w===-1)&&C>=-h&&C<=h&&C===o(C)){if(M[0]===0){if(C===0&&M.length===1)return!0;break e}if(y=(C+1)%c,y<1&&(y+=c),String(M[0]).length==y){for(y=0;y<M.length;y++)if(_=M[y],_<0||_>=u||_!==o(_))break e;if(_!==0)return!0}}}else if(M===null&&C===null&&(w===null||w===1||w===-1))return!0;throw Error(s+"Invalid BigNumber: "+g)},O.maximum=O.max=function(){return $a(arguments,-1)},O.minimum=O.min=function(){return $a(arguments,1)},O.random=function(){var g=9007199254740992,y=Math.random()*g&2097151?function(){return o(Math.random()*g)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(_){var M,C,w,k,v,I=0,x=[],N=new O($);if(_==null?_=X:S(_,0,h),k=i(_/c),Ie)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(k*=2));I<k;)v=M[I]*131072+(M[I+1]>>>11),v>=9e15?(C=crypto.getRandomValues(new Uint32Array(2)),M[I]=C[0],M[I+1]=C[1]):(x.push(v%1e14),I+=2);I=k/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(k*=7);I<k;)v=(M[I]&31)*281474976710656+M[I+1]*1099511627776+M[I+2]*4294967296+M[I+3]*16777216+(M[I+4]<<16)+(M[I+5]<<8)+M[I+6],v>=9e15?crypto.randomBytes(7).copy(M,I):(x.push(v%1e14),I+=7);I=k/7}else throw Ie=!1,Error(s+"crypto unavailable");if(!Ie)for(;I<k;)v=y(),v<9e15&&(x[I++]=v%1e14);for(k=x[--I],_%=c,k&&_&&(v=f[c-_],x[I]=o(k/v)*v);x[I]===0;x.pop(),I--);if(I<0)x=[w=0];else{for(w=-1;x[0]===0;x.splice(0,1),w-=c);for(I=1,v=x[0];v>=10;v/=10,I++);I<c&&(w-=c-I)}return N.e=w,N.c=x,N}}(),O.sum=function(){for(var g=1,y=arguments,_=new O(y[0]);g<y.length;)_=_.plus(y[g++]);return _},q=function(){var g="0123456789";function y(_,M,C,w){for(var k,v=[0],I,x=0,N=_.length;x<N;){for(I=v.length;I--;v[I]*=M);for(v[0]+=w.indexOf(_.charAt(x++)),k=0;k<v.length;k++)v[k]>C-1&&(v[k+1]==null&&(v[k+1]=0),v[k+1]+=v[k]/C|0,v[k]%=C)}return v.reverse()}return function(_,M,C,w,k){var v,I,x,N,G,K,W,ne,le=_.indexOf("."),pe=X,j=Z;for(le>=0&&(N=ae,ae=0,_=_.replace(".",""),ne=new O(M),K=ne.pow(_.length-le),ae=N,ne.c=y(F(A(K.c),K.e,"0"),10,C,g),ne.e=ne.c.length),W=y(_,M,C,k?(v=At,g):(v=g,At)),x=N=W.length;W[--N]==0;W.pop());if(!W[0])return v.charAt(0);if(le<0?--x:(K.c=W,K.e=x,K.s=w,K=P(K,ne,pe,j,C),W=K.c,G=K.r,x=K.e),I=x+pe+1,le=W[I],N=C/2,G=G||I<0||W[I+1]!=null,G=j<4?(le!=null||G)&&(j==0||j==(K.s<0?3:2)):le>N||le==N&&(j==4||G||j==6&&W[I-1]&1||j==(K.s<0?8:7)),I<1||!W[0])_=G?F(v.charAt(1),-pe,v.charAt(0)):v.charAt(0);else{if(W.length=I,G)for(--C;++W[--I]>C;)W[I]=0,I||(++x,W=[1].concat(W));for(N=W.length;!W[--N];);for(le=0,_="";le<=N;_+=v.charAt(W[le++]));_=F(_,x,v.charAt(0))}return _}}(),P=function(){function g(M,C,w){var k,v,I,x,N=0,G=M.length,K=C%p,W=C/p|0;for(M=M.slice();G--;)I=M[G]%p,x=M[G]/p|0,k=W*I+x*K,v=K*I+k%p*p+N,N=(v/w|0)+(k/p|0)+W*x,M[G]=v%w;return N&&(M=[N].concat(M)),M}function y(M,C,w,k){var v,I;if(w!=k)I=w>k?1:-1;else for(v=I=0;v<w;v++)if(M[v]!=C[v]){I=M[v]>C[v]?1:-1;break}return I}function _(M,C,w,k){for(var v=0;w--;)M[w]-=v,v=M[w]<C[w]?1:0,M[w]=v*k+M[w]-C[w];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,C,w,k,v){var I,x,N,G,K,W,ne,le,pe,j,ie,ge,Mn,Io,wo,Xe,an,Me=M.s==C.s?1:-1,Ee=M.c,ue=C.c;if(!Ee||!Ee[0]||!ue||!ue[0])return new O(!M.s||!C.s||(Ee?ue&&Ee[0]==ue[0]:!ue)?NaN:Ee&&Ee[0]==0||!ue?Me*0:Me/0);for(le=new O(Me),pe=le.c=[],x=M.e-C.e,Me=w+x+1,v||(v=u,x=E(M.e/c)-E(C.e/c),Me=Me/c|0),N=0;ue[N]==(Ee[N]||0);N++);if(ue[N]>(Ee[N]||0)&&x--,Me<0)pe.push(1),G=!0;else{for(Io=Ee.length,Xe=ue.length,N=0,Me+=2,K=o(v/(ue[0]+1)),K>1&&(ue=g(ue,K,v),Ee=g(Ee,K,v),Xe=ue.length,Io=Ee.length),Mn=Xe,j=Ee.slice(0,Xe),ie=j.length;ie<Xe;j[ie++]=0);an=ue.slice(),an=[0].concat(an),wo=ue[0],ue[1]>=v/2&&wo++;do{if(K=0,I=y(ue,j,Xe,ie),I<0){if(ge=j[0],Xe!=ie&&(ge=ge*v+(j[1]||0)),K=o(ge/wo),K>1)for(K>=v&&(K=v-1),W=g(ue,K,v),ne=W.length,ie=j.length;y(W,j,ne,ie)==1;)K--,_(W,Xe<ne?an:ue,ne,v),ne=W.length,I=1;else K==0&&(I=K=1),W=ue.slice(),ne=W.length;if(ne<ie&&(W=[0].concat(W)),_(j,W,ie,v),ie=j.length,I==-1)for(;y(ue,j,Xe,ie)<1;)K++,_(j,Xe<ie?an:ue,ie,v),ie=j.length}else I===0&&(K++,j=[0]);pe[N++]=K,j[0]?j[ie++]=Ee[Mn]||0:(j=[Ee[Mn]],ie=1)}while((Mn++<Io||j[0]!=null)&&Me--);G=j[0]!=null,pe[0]||pe.splice(0,1)}if(v==u){for(N=1,Me=pe[0];Me>=10;Me/=10,N++);De(le,w+(le.e=N+x*c-1)+1,k,G)}else le.e=x,le.r=+G;return le}}();function Co(g,y,_,M){var C,w,k,v,I;if(_==null?_=Z:S(_,0,8),!g.c)return g.toString();if(C=g.c[0],k=g.e,y==null)I=A(g.c),I=M==1||M==2&&(k<=se||k>=te)?U(I,k):F(I,k,"0");else if(g=De(new O(g),y,_),w=g.e,I=A(g.c),v=I.length,M==1||M==2&&(y<=w||w<=se)){for(;v<y;I+="0",v++);I=U(I,w)}else if(y-=k+(M===2&&w>k),I=F(I,w,"0"),w+1>v){if(--y>0)for(I+=".";y--;I+="0");}else if(y+=w-v,y>0)for(w+1==v&&(I+=".");y--;I+="0");return g.s<0&&C?"-"+I:I}function $a(g,y){for(var _,M,C=1,w=new O(g[0]);C<g.length;C++)M=new O(g[C]),(!M.s||(_=T(w,M))===y||_===0&&w.s===y)&&(w=M);return w}function So(g,y,_){for(var M=1,C=y.length;!y[--C];y.pop());for(C=y[0];C>=10;C/=10,M++);return(_=M+_*c-1)>de?g.c=g.e=null:_<re?g.c=[g.e=0]:(g.e=_,g.c=y),g}J=function(){var g=/^(-?)0([xbo])(?=\w[\w.]*$)/i,y=/^([^.]+)\.$/,_=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,C=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(w,k,v,I){var x,N=v?k:k.replace(C,"");if(M.test(N))w.s=isNaN(N)?null:N<0?-1:1;else{if(!v&&(N=N.replace(g,function(G,K,W){return x=(W=W.toLowerCase())=="x"?16:W=="b"?2:8,!I||I==x?K:G}),I&&(x=I,N=N.replace(y,"$1").replace(_,"0.$1")),k!=N))return new O(N,x);if(O.DEBUG)throw Error(s+"Not a"+(I?" base "+I:"")+" number: "+k);w.s=null}w.c=w.e=null}}();function De(g,y,_,M){var C,w,k,v,I,x,N,G=g.c,K=f;if(G){e:{for(C=1,v=G[0];v>=10;v/=10,C++);if(w=y-C,w<0)w+=c,k=y,I=G[x=0],N=o(I/K[C-k-1]%10);else if(x=i((w+1)/c),x>=G.length)if(M){for(;G.length<=x;G.push(0));I=N=0,C=1,w%=c,k=w-c+1}else break e;else{for(I=v=G[x],C=1;v>=10;v/=10,C++);w%=c,k=w-c+C,N=k<0?0:o(I/K[C-k-1]%10)}if(M=M||y<0||G[x+1]!=null||(k<0?I:I%K[C-k-1]),M=_<4?(N||M)&&(_==0||_==(g.s<0?3:2)):N>5||N==5&&(_==4||M||_==6&&(w>0?k>0?I/K[C-k]:0:G[x-1])%10&1||_==(g.s<0?8:7)),y<1||!G[0])return G.length=0,M?(y-=g.e+1,G[0]=K[(c-y%c)%c],g.e=-y||0):G[0]=g.e=0,g;if(w==0?(G.length=x,v=1,x--):(G.length=x+1,v=K[c-w],G[x]=k>0?o(I/K[C-k]%K[k])*v:0),M)for(;;)if(x==0){for(w=1,k=G[0];k>=10;k/=10,w++);for(k=G[0]+=v,v=1;k>=10;k/=10,v++);w!=v&&(g.e++,G[0]==u&&(G[0]=1));break}else{if(G[x]+=v,G[x]!=u)break;G[x--]=0,v=1}for(w=G.length;G[--w]===0;G.pop());}g.e>de?g.c=g.e=null:g.e<re&&(g.c=[g.e=0])}return g}function rt(g){var y,_=g.e;return _===null?g.toString():(y=A(g.c),y=_<=se||_>=te?U(y,_):F(y,_,"0"),g.s<0?"-"+y:y)}return R.absoluteValue=R.abs=function(){var g=new O(this);return g.s<0&&(g.s=1),g},R.comparedTo=function(g,y){return T(this,new O(g,y))},R.decimalPlaces=R.dp=function(g,y){var _,M,C,w=this;if(g!=null)return S(g,0,h),y==null?y=Z:S(y,0,8),De(new O(w),g+w.e+1,y);if(!(_=w.c))return null;if(M=((C=_.length-1)-E(this.e/c))*c,C=_[C])for(;C%10==0;C/=10,M--);return M<0&&(M=0),M},R.dividedBy=R.div=function(g,y){return P(this,new O(g,y),X,Z)},R.dividedToIntegerBy=R.idiv=function(g,y){return P(this,new O(g,y),0,1)},R.exponentiatedBy=R.pow=function(g,y){var _,M,C,w,k,v,I,x,N,G=this;if(g=new O(g),g.c&&!g.isInteger())throw Error(s+"Exponent not an integer: "+rt(g));if(y!=null&&(y=new O(y)),v=g.e>14,!G.c||!G.c[0]||G.c[0]==1&&!G.e&&G.c.length==1||!g.c||!g.c[0])return N=new O(Math.pow(+rt(G),v?g.s*(2-b(g)):+rt(g))),y?N.mod(y):N;if(I=g.s<0,y){if(y.c?!y.c[0]:!y.s)return new O(NaN);M=!I&&G.isInteger()&&y.isInteger(),M&&(G=G.mod(y))}else{if(g.e>9&&(G.e>0||G.e<-1||(G.e==0?G.c[0]>1||v&&G.c[1]>=24e7:G.c[0]<8e13||v&&G.c[0]<=9999975e7)))return w=G.s<0&&b(g)?-0:0,G.e>-1&&(w=1/w),new O(I?1/w:w);ae&&(w=i(ae/c+2))}for(v?(_=new O(.5),I&&(g.s=1),x=b(g)):(C=Math.abs(+rt(g)),x=C%2),N=new O($);;){if(x){if(N=N.times(G),!N.c)break;w?N.c.length>w&&(N.c.length=w):M&&(N=N.mod(y))}if(C){if(C=o(C/2),C===0)break;x=C%2}else if(g=g.times(_),De(g,g.e+1,1),g.e>14)x=b(g);else{if(C=+rt(g),C===0)break;x=C%2}G=G.times(G),w?G.c&&G.c.length>w&&(G.c.length=w):M&&(G=G.mod(y))}return M?N:(I&&(N=$.div(N)),y?N.mod(y):w?De(N,ae,Z,k):N)},R.integerValue=function(g){var y=new O(this);return g==null?g=Z:S(g,0,8),De(y,y.e+1,g)},R.isEqualTo=R.eq=function(g,y){return T(this,new O(g,y))===0},R.isFinite=function(){return!!this.c},R.isGreaterThan=R.gt=function(g,y){return T(this,new O(g,y))>0},R.isGreaterThanOrEqualTo=R.gte=function(g,y){return(y=T(this,new O(g,y)))===1||y===0},R.isInteger=function(){return!!this.c&&E(this.e/c)>this.c.length-2},R.isLessThan=R.lt=function(g,y){return T(this,new O(g,y))<0},R.isLessThanOrEqualTo=R.lte=function(g,y){return(y=T(this,new O(g,y)))===-1||y===0},R.isNaN=function(){return!this.s},R.isNegative=function(){return this.s<0},R.isPositive=function(){return this.s>0},R.isZero=function(){return!!this.c&&this.c[0]==0},R.minus=function(g,y){var _,M,C,w,k=this,v=k.s;if(g=new O(g,y),y=g.s,!v||!y)return new O(NaN);if(v!=y)return g.s=-y,k.plus(g);var I=k.e/c,x=g.e/c,N=k.c,G=g.c;if(!I||!x){if(!N||!G)return N?(g.s=-y,g):new O(G?k:NaN);if(!N[0]||!G[0])return G[0]?(g.s=-y,g):new O(N[0]?k:Z==3?-0:0)}if(I=E(I),x=E(x),N=N.slice(),v=I-x){for((w=v<0)?(v=-v,C=N):(x=I,C=G),C.reverse(),y=v;y--;C.push(0));C.reverse()}else for(M=(w=(v=N.length)<(y=G.length))?v:y,v=y=0;y<M;y++)if(N[y]!=G[y]){w=N[y]<G[y];break}if(w&&(C=N,N=G,G=C,g.s=-g.s),y=(M=G.length)-(_=N.length),y>0)for(;y--;N[_++]=0);for(y=u-1;M>v;){if(N[--M]<G[M]){for(_=M;_&&!N[--_];N[_]=y);--N[_],N[M]+=u}N[M]-=G[M]}for(;N[0]==0;N.splice(0,1),--x);return N[0]?So(g,N,x):(g.s=Z==3?-1:1,g.c=[g.e=0],g)},R.modulo=R.mod=function(g,y){var _,M,C=this;return g=new O(g,y),!C.c||!g.s||g.c&&!g.c[0]?new O(NaN):!g.c||C.c&&!C.c[0]?new O(C):(Be==9?(M=g.s,g.s=1,_=P(C,g,0,3),g.s=M,_.s*=M):_=P(C,g,0,Be),g=C.minus(_.times(g)),!g.c[0]&&Be==1&&(g.s=C.s),g)},R.multipliedBy=R.times=function(g,y){var _,M,C,w,k,v,I,x,N,G,K,W,ne,le,pe,j=this,ie=j.c,ge=(g=new O(g,y)).c;if(!ie||!ge||!ie[0]||!ge[0])return!j.s||!g.s||ie&&!ie[0]&&!ge||ge&&!ge[0]&&!ie?g.c=g.e=g.s=null:(g.s*=j.s,!ie||!ge?g.c=g.e=null:(g.c=[0],g.e=0)),g;for(M=E(j.e/c)+E(g.e/c),g.s*=j.s,I=ie.length,G=ge.length,I<G&&(ne=ie,ie=ge,ge=ne,C=I,I=G,G=C),C=I+G,ne=[];C--;ne.push(0));for(le=u,pe=p,C=G;--C>=0;){for(_=0,K=ge[C]%pe,W=ge[C]/pe|0,k=I,w=C+k;w>C;)x=ie[--k]%pe,N=ie[k]/pe|0,v=W*x+N*K,x=K*x+v%pe*pe+ne[w]+_,_=(x/le|0)+(v/pe|0)+W*N,ne[w--]=x%le;ne[w]=_}return _?++M:ne.splice(0,1),So(g,ne,M)},R.negated=function(){var g=new O(this);return g.s=-g.s||null,g},R.plus=function(g,y){var _,M=this,C=M.s;if(g=new O(g,y),y=g.s,!C||!y)return new O(NaN);if(C!=y)return g.s=-y,M.minus(g);var w=M.e/c,k=g.e/c,v=M.c,I=g.c;if(!w||!k){if(!v||!I)return new O(C/0);if(!v[0]||!I[0])return I[0]?g:new O(v[0]?M:C*0)}if(w=E(w),k=E(k),v=v.slice(),C=w-k){for(C>0?(k=w,_=I):(C=-C,_=v),_.reverse();C--;_.push(0));_.reverse()}for(C=v.length,y=I.length,C-y<0&&(_=I,I=v,v=_,y=C),C=0;y;)C=(v[--y]=v[y]+I[y]+C)/u|0,v[y]=u===v[y]?0:v[y]%u;return C&&(v=[C].concat(v),++k),So(g,v,k)},R.precision=R.sd=function(g,y){var _,M,C,w=this;if(g!=null&&g!==!!g)return S(g,1,h),y==null?y=Z:S(y,0,8),De(new O(w),g,y);if(!(_=w.c))return null;if(C=_.length-1,M=C*c+1,C=_[C]){for(;C%10==0;C/=10,M--);for(C=_[0];C>=10;C/=10,M++);}return g&&w.e+1>M&&(M=w.e+1),M},R.shiftedBy=function(g){return S(g,-d,d),this.times("1e"+g)},R.squareRoot=R.sqrt=function(){var g,y,_,M,C,w=this,k=w.c,v=w.s,I=w.e,x=X+4,N=new O("0.5");if(v!==1||!k||!k[0])return new O(!v||v<0&&(!k||k[0])?NaN:k?w:1/0);if(v=Math.sqrt(+rt(w)),v==0||v==1/0?(y=A(k),(y.length+I)%2==0&&(y+="0"),v=Math.sqrt(+y),I=E((I+1)/2)-(I<0||I%2),v==1/0?y="5e"+I:(y=v.toExponential(),y=y.slice(0,y.indexOf("e")+1)+I),_=new O(y)):_=new O(v+""),_.c[0]){for(I=_.e,v=I+x,v<3&&(v=0);;)if(C=_,_=N.times(C.plus(P(w,C,x,1))),A(C.c).slice(0,v)===(y=A(_.c)).slice(0,v))if(_.e<I&&--v,y=y.slice(v-3,v+1),y=="9999"||!M&&y=="4999"){if(!M&&(De(C,C.e+X+2,0),C.times(C).eq(w))){_=C;break}x+=4,v+=4,M=1}else{(!+y||!+y.slice(1)&&y.charAt(0)=="5")&&(De(_,_.e+X+2,1),g=!_.times(_).eq(w));break}}return De(_,_.e+X+1,Z,g)},R.toExponential=function(g,y){return g!=null&&(S(g,0,h),g++),Co(this,g,y,1)},R.toFixed=function(g,y){return g!=null&&(S(g,0,h),g=g+this.e+1),Co(this,g,y)},R.toFormat=function(g,y,_){var M,C=this;if(_==null)g!=null&&y&&typeof y=="object"?(_=y,y=null):g&&typeof g=="object"?(_=g,g=y=null):_=ot;else if(typeof _!="object")throw Error(s+"Argument not an object: "+_);if(M=C.toFixed(g,y),C.c){var w,k=M.split("."),v=+_.groupSize,I=+_.secondaryGroupSize,x=_.groupSeparator||"",N=k[0],G=k[1],K=C.s<0,W=K?N.slice(1):N,ne=W.length;if(I&&(w=v,v=I,I=w,ne-=w),v>0&&ne>0){for(w=ne%v||v,N=W.substr(0,w);w<ne;w+=v)N+=x+W.substr(w,v);I>0&&(N+=x+W.slice(w)),K&&(N="-"+N)}M=G?N+(_.decimalSeparator||"")+((I=+_.fractionGroupSize)?G.replace(new RegExp("\\d{"+I+"}\\B","g"),"$&"+(_.fractionGroupSeparator||"")):G):N}return(_.prefix||"")+M+(_.suffix||"")},R.toFraction=function(g){var y,_,M,C,w,k,v,I,x,N,G,K,W=this,ne=W.c;if(g!=null&&(v=new O(g),!v.isInteger()&&(v.c||v.s!==1)||v.lt($)))throw Error(s+"Argument "+(v.isInteger()?"out of range: ":"not an integer: ")+rt(v));if(!ne)return new O(W);for(y=new O($),x=_=new O($),M=I=new O($),K=A(ne),w=y.e=K.length-W.e-1,y.c[0]=f[(k=w%c)<0?c+k:k],g=!g||v.comparedTo(y)>0?w>0?y:x:v,k=de,de=1/0,v=new O(K),I.c[0]=0;N=P(v,y,0,1),C=_.plus(N.times(M)),C.comparedTo(g)!=1;)_=M,M=C,x=I.plus(N.times(C=x)),I=C,y=v.minus(N.times(C=y)),v=C;return C=P(g.minus(_),M,0,1),I=I.plus(C.times(x)),_=_.plus(C.times(M)),I.s=x.s=W.s,w=w*2,G=P(x,M,w,Z).minus(W).abs().comparedTo(P(I,_,w,Z).minus(W).abs())<1?[x,M]:[I,_],de=k,G},R.toNumber=function(){return+rt(this)},R.toPrecision=function(g,y){return g!=null&&S(g,1,h),Co(this,g,y,2)},R.toString=function(g){var y,_=this,M=_.s,C=_.e;return C===null?M?(y="Infinity",M<0&&(y="-"+y)):y="NaN":(g==null?y=C<=se||C>=te?U(A(_.c),C):F(A(_.c),C,"0"):g===10&&vo?(_=De(new O(_),X+C+1,Z),y=F(A(_.c),_.e,"0")):(S(g,2,At.length,"Base"),y=q(F(A(_.c),C,"0"),10,g,M,!0)),M<0&&_.c[0]&&(y="-"+y)),y},R.valueOf=R.toJSON=function(){return rt(this)},R._isBigNumber=!0,L!=null&&O.set(L),O}function E(L){var P=L|0;return L>0||L===P?P:P-1}function A(L){for(var P,q,J=1,R=L.length,$=L[0]+"";J<R;){for(P=L[J++]+"",q=c-P.length;q--;P="0"+P);$+=P}for(R=$.length;$.charCodeAt(--R)===48;);return $.slice(0,R+1||1)}function T(L,P){var q,J,R=L.c,$=P.c,X=L.s,Z=P.s,se=L.e,te=P.e;if(!X||!Z)return null;if(q=R&&!R[0],J=$&&!$[0],q||J)return q?J?0:-Z:X;if(X!=Z)return X;if(q=X<0,J=se==te,!R||!$)return J?0:!R^q?1:-1;if(!J)return se>te^q?1:-1;for(Z=(se=R.length)<(te=$.length)?se:te,X=0;X<Z;X++)if(R[X]!=$[X])return R[X]>$[X]^q?1:-1;return se==te?0:se>te^q?1:-1}function S(L,P,q,J){if(L<P||L>q||L!==o(L))throw Error(s+(J||"Argument")+(typeof L=="number"?L<P||L>q?" out of range: ":" not an integer: ":" not a primitive number: ")+String(L))}function b(L){var P=L.c.length-1;return E(L.e/c)==P&&L.c[P]%2!=0}function U(L,P){return(L.length>1?L.charAt(0)+"."+L.slice(1):L)+(P<0?"e":"e+")+P}function F(L,P,q){var J,R;if(P<0){for(R=q+".";++P;R+=q);L=R+L}else if(J=L.length,++P>J){for(R=q,P-=J;--P;R+=q);L+=R}else P<J&&(L=L.slice(0,P)+"."+L.slice(P));return L}e=m(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof bn<"u"&&bn.exports?bn.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(Tl)});var Sl=B((uI,Cl)=>{D();var Al=Uo(),vl=Cl.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,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},l;function u(d){return n.lastIndex=0,n.test(d)?'"'+d.replace(n,function(f){var p=s[f];return typeof p=="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+d+'"'}function c(d,f){var p,h,m,E,A=i,T,S=f[d],b=S!=null&&(S instanceof Al||Al.isBigNumber(S));switch(S&&typeof S=="object"&&typeof S.toJSON=="function"&&(S=S.toJSON(d)),typeof l=="function"&&(S=l.call(f,d,S)),typeof S){case"string":return b?S:u(S);case"number":return isFinite(S)?String(S):"null";case"boolean":case"null":case"bigint":return String(S);case"object":if(!S)return"null";if(i+=o,T=[],Object.prototype.toString.apply(S)==="[object Array]"){for(E=S.length,p=0;p<E;p+=1)T[p]=c(p,S)||"null";return m=T.length===0?"[]":i?`[
9
- `+i+T.join(`,
10
- `+i)+`
11
- `+A+"]":"["+T.join(",")+"]",i=A,m}if(l&&typeof l=="object")for(E=l.length,p=0;p<E;p+=1)typeof l[p]=="string"&&(h=l[p],m=c(h,S),m&&T.push(u(h)+(i?": ":":")+m));else Object.keys(S).forEach(function(U){var F=c(U,S);F&&T.push(u(U)+(i?": ":":")+F)});return m=T.length===0?"{}":i?`{
12
- `+i+T.join(`,
13
- `+i)+`
14
- `+A+"}":"{"+T.join(",")+"}",i=A,m}}typeof vl.stringify!="function"&&(vl.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(l=f,f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return c("",{"":d})})})()});var wl=B((dI,Il)=>{D();var Fn=null,kp=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,Up=/(?: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)/,Gp=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:`
15
- `,r:"\r",t:" "},s,l=function(A){throw{name:"SyntaxError",message:A,at:n,text:s}},u=function(A){return A&&A!==i&&l("Expected '"+A+"' instead of '"+i+"'"),i=s.charAt(n),n+=1,i},c=function(){var A,T="";for(i==="-"&&(T="-",u("-"));i>="0"&&i<="9";)T+=i,u();if(i===".")for(T+=".";u()&&i>="0"&&i<="9";)T+=i;if(i==="e"||i==="E")for(T+=i,u(),(i==="-"||i==="+")&&(T+=i,u());i>="0"&&i<="9";)T+=i,u();if(A=+T,!isFinite(A))l("Bad number");else return Fn==null&&(Fn=Uo()),T.length>15?e.storeAsString?T:e.useNativeBigInt?BigInt(T):new Fn(T):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(A):new Fn(A):A},d=function(){var A,T,S="",b;if(i==='"')for(var U=n;u();){if(i==='"')return n-1>U&&(S+=s.substring(U,n-1)),u(),S;if(i==="\\"){if(n-1>U&&(S+=s.substring(U,n-1)),u(),i==="u"){for(b=0,T=0;T<4&&(A=parseInt(u(),16),!!isFinite(A));T+=1)b=b*16+A;S+=String.fromCharCode(b)}else if(typeof o[i]=="string")S+=o[i];else break;U=n}}l("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}l("Unexpected '"+i+"'")},h,m=function(){var A=[];if(i==="["){if(u("["),f(),i==="]")return u("]"),A;for(;i;){if(A.push(h()),f(),i==="]")return u("]"),A;u(","),f()}}l("Bad array")},E=function(){var A,T=Object.create(null);if(i==="{"){if(u("{"),f(),i==="}")return u("}"),T;for(;i;){if(A=d(),f(),u(":"),e.strict===!0&&Object.hasOwnProperty.call(T,A)&&l('Duplicate key "'+A+'"'),kp.test(A)===!0?e.protoAction==="error"?l("Object contains forbidden prototype property"):e.protoAction==="ignore"?h():T[A]=h():Up.test(A)===!0?e.constructorAction==="error"?l("Object contains forbidden constructor property"):e.constructorAction==="ignore"?h():T[A]=h():T[A]=h(),f(),i==="}")return u("}"),T;u(","),f()}}l("Bad object")};return h=function(){switch(f(),i){case"{":return E();case"[":return m();case'"':return d();case"-":return c();default:return i>="0"&&i<="9"?c():p()}},function(A,T){var S;return s=A+"",n=0,i=" ",S=h(),f(),i&&l("Syntax error"),typeof T=="function"?function b(U,F){var L,P,q=U[F];return q&&typeof q=="object"&&Object.keys(q).forEach(function(J){P=b(q,J),P!==void 0?q[J]=P:delete q[J]}),T.call(U,F,q)}({"":S},""):S}};Il.exports=Gp});var Nl=B((pI,On)=>{D();var Pl=Sl().stringify,Rl=wl();On.exports=function(t){return{parse:Rl(t),stringify:Pl}};On.exports.parse=Rl();On.exports.stringify=Pl});var Go=B(He=>{"use strict";D();Object.defineProperty(He,"__esModule",{value:!0});He.GCE_LINUX_BIOS_PATHS=void 0;He.isGoogleCloudServerless=xl;He.isGoogleComputeEngineLinux=kl;He.isGoogleComputeEngineMACAddress=Ul;He.isGoogleComputeEngine=Gl;He.detectGCPResidency=bp;var Dl=Q("fs"),Ml=Q("os");He.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var Lp=/^42:01/;function xl(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function kl(){if((0,Ml.platform)()!=="linux")return!1;try{(0,Dl.statSync)(He.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Dl.readFileSync)(He.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Ul(){let t=(0,Ml.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(Lp.test(n))return!0}return!1}function Gl(){return kl()||Ul()}function bp(){return xl()||Gl()}});var Ll=B(qn=>{"use strict";D();Object.defineProperty(qn,"__esModule",{value:!0});qn.Colours=void 0;var ye=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="")}};qn.Colours=ye;ye.enabled=!1;ye.reset="";ye.bright="";ye.dim="";ye.red="";ye.green="";ye.yellow="";ye.blue="";ye.magenta="";ye.cyan="";ye.white="";ye.grey="";ye.refresh()});var ql=B(oe=>{"use strict";D();var Fp=oe&&oe.__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]}),Op=oe&&oe.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),bl=oe&&oe.__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"&&Fp(n,e,i[o]);return Op(n,e),n}}();Object.defineProperty(oe,"__esModule",{value:!0});oe.env=oe.DebugLogBackendBase=oe.placeholder=oe.AdhocDebugLogger=oe.LogSeverity=void 0;oe.getNodeBackend=bo;oe.getDebugBackend=Bp;oe.getStructuredBackend=Hp;oe.setBackend=Vp;oe.log=Ol;var qp=Q("events"),ln=bl(Q("process")),Fl=bl(Q("util")),we=Ll(),Ve;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Ve||(oe.LogSeverity=Ve={}));var un=class extends qp.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(Ve.DEBUG,...i),this.func.info=(...i)=>this.invokeSeverity(Ve.INFO,...i),this.func.warn=(...i)=>this.invokeSeverity(Ve.WARNING,...i),this.func.error=(...i)=>this.invokeSeverity(Ve.ERROR,...i),this.func.sublog=i=>Ol(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)}};oe.AdhocDebugLogger=un;oe.placeholder=new un("",()=>{}).func;var kt=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=ln.env[oe.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)}}};oe.DebugLogBackendBase=kt;var Lo=class extends kt{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 s=`${we.Colours.green}${e}${we.Colours.reset}`,l=`${we.Colours.yellow}${ln.pid}${we.Colours.reset}`,u;switch(n.severity){case Ve.ERROR:u=`${we.Colours.red}${n.severity}${we.Colours.reset}`;break;case Ve.INFO:u=`${we.Colours.magenta}${n.severity}${we.Colours.reset}`;break;case Ve.WARNING:u=`${we.Colours.yellow}${n.severity}${we.Colours.reset}`;break;default:u=(o=n.severity)!==null&&o!==void 0?o:Ve.DEFAULT;break}let c=Fl.formatWithOptions({colors:we.Colours.enabled},...i),d=Object.assign({},n);delete d.severity;let f=Object.getOwnPropertyNames(d).length?JSON.stringify(d):"",p=f?`${we.Colours.grey}${f}${we.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",l,s,u,c,f?` ${p}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function bo(){return new Lo}var Fo=class extends kt{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=ln.env.NODE_DEBUG)!==null&&e!==void 0?e:"";ln.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function Bp(t){return new Fo(t)}var Oo=class extends kt{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,...s)=>{var l;let u=(l=o.severity)!==null&&l!==void 0?l:Ve.INFO,c=Object.assign({severity:u,message:Fl.format(...s)},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 Hp(t){return new Oo(t)}oe.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var qo=new Map,Pe;function Vp(t){Pe=t,qo.clear()}function Ol(t,e){if(!Pe&&!ln.env[oe.env.nodeEnables]||!t)return oe.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=qo.get(t);if(n)return n.func;if(Pe===null)return oe.placeholder;Pe===void 0&&(Pe=bo());let i=(()=>{let o;return new un(t,(l,...u)=>{if(o!==Pe){if(Pe===null)return;Pe===void 0&&(Pe=bo()),o=Pe}Pe?.log(t,l,...u)})})();return qo.set(t,i),i.func}});var Bo=B(St=>{"use strict";D();var $p=St&&St.__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]}),Jp=St&&St.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&$p(e,t,n)};Object.defineProperty(St,"__esModule",{value:!0});Jp(ql(),St)});var dn=B(Y=>{"use strict";D();var Hl=Y&&Y.__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]}),Kp=Y&&Y.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Wp=Y&&Y.__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"&&Hl(n,e,i[o]);return Kp(n,e),n}}(),Yp=Y&&Y.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Hl(e,t,n)};Object.defineProperty(Y,"__esModule",{value:!0});Y.gcpResidencyCache=Y.METADATA_SERVER_DETECTION=Y.HEADERS=Y.HEADER_VALUE=Y.HEADER_NAME=Y.SECONDARY_HOST_ADDRESS=Y.HOST_ADDRESS=Y.BASE_PATH=void 0;Y.instance=eh;Y.project=th;Y.universe=nh;Y.bulk=ih;Y.isAvailable=rh;Y.resetIsAvailableCache=sh;Y.getGCPResidency=$o;Y.setGCPResidency=Vl;Y.requestTimeout=$l;var Ho=me(),zp=Nl(),Xp=Go(),Qp=Wp(Bo());Y.BASE_PATH="/computeMetadata/v1";Y.HOST_ADDRESS="http://169.254.169.254";Y.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";Y.HEADER_NAME="Metadata-Flavor";Y.HEADER_VALUE="Google";Y.HEADERS=Object.freeze({[Y.HEADER_NAME]:Y.HEADER_VALUE});var Bl=Qp.log("gcp-metadata");Y.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 Vo(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||Y.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(Y.BASE_PATH,t).href}function Zp(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 cn(t,e={},n=3,i=!1){let o=new Headers(Y.HEADERS),s="",l={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((h,m)=>o.set(m,h)),s=p.metadataKey,l=p.params||l,n=p.noResponseRetries||n,i=p.fastFail||i}else s=t;typeof e=="string"?s+=`/${e}`:(Zp(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,h)=>o.set(h,p)),l=e.params||l);let u=i?jp:Ho.request,c={url:`${Vo()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:l,responseType:"text",timeout:$l()};Bl.info("instance request %j",c);let d=await u(c);Bl.info("instance metadata is %s",d.data);let f=d.headers.get(Y.HEADER_NAME);if(f!==Y.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${Y.HEADER_NAME} header. Expected '${Y.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return zp.parse(d.data)}catch{}return d.data}async function jp(t){let e={...t,url:t.url?.toString().replace(Vo(),Vo(Y.SECONDARY_HOST_ADDRESS))},n=(0,Ho.request)(t),i=(0,Ho.request)(e);return Promise.any([n,i])}function eh(t){return cn("instance",t)}function th(t){return cn("project",t)}function nh(t){return cn("universe",t)}async function ih(t){let e={};return await Promise.all(t.map(n=>(async()=>{let i=await cn(n),o=n.metadataKey;e[o]=i})())),e}function oh(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Bn;async function rh(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in Y.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(Y.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return $o();case"ping-only":}}try{return Bn===void 0&&(Bn=cn("instance",void 0,oh(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await Bn,!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 sh(){Bn=void 0}Y.gcpResidencyCache=null;function $o(){return Y.gcpResidencyCache===null&&Vl(),Y.gcpResidencyCache}function Vl(t=null){Y.gcpResidencyCache=t!==null?t:(0,Xp.detectGCPResidency)()}function $l(){return $o()?0:3e3}Yp(Go(),Y)});var Wl=B(Hn=>{"use strict";D();Hn.byteLength=lh;Hn.toByteArray=ch;Hn.fromByteArray=ph;var Qe=[],Ue=[],ah=typeof Uint8Array<"u"?Uint8Array:Array,Jo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(It=0,Jl=Jo.length;It<Jl;++It)Qe[It]=Jo[It],Ue[Jo.charCodeAt(It)]=It;var It,Jl;Ue[45]=62;Ue[95]=63;function Kl(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 lh(t){var e=Kl(t),n=e[0],i=e[1];return(n+i)*3/4-i}function uh(t,e,n){return(e+n)*3/4-n}function ch(t){var e,n=Kl(t),i=n[0],o=n[1],s=new ah(uh(t,i,o)),l=0,u=o>0?i-4:i,c;for(c=0;c<u;c+=4)e=Ue[t.charCodeAt(c)]<<18|Ue[t.charCodeAt(c+1)]<<12|Ue[t.charCodeAt(c+2)]<<6|Ue[t.charCodeAt(c+3)],s[l++]=e>>16&255,s[l++]=e>>8&255,s[l++]=e&255;return o===2&&(e=Ue[t.charCodeAt(c)]<<2|Ue[t.charCodeAt(c+1)]>>4,s[l++]=e&255),o===1&&(e=Ue[t.charCodeAt(c)]<<10|Ue[t.charCodeAt(c+1)]<<4|Ue[t.charCodeAt(c+2)]>>2,s[l++]=e>>8&255,s[l++]=e&255),s}function dh(t){return Qe[t>>18&63]+Qe[t>>12&63]+Qe[t>>6&63]+Qe[t&63]}function fh(t,e,n){for(var i,o=[],s=e;s<n;s+=3)i=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(dh(i));return o.join("")}function ph(t){for(var e,n=t.length,i=n%3,o=[],s=16383,l=0,u=n-i;l<u;l+=s)o.push(fh(t,l,l+s>u?u:l+s));return i===1?(e=t[n-1],o.push(Qe[e>>2]+Qe[e<<4&63]+"==")):i===2&&(e=(t[n-2]<<8)+t[n-1],o.push(Qe[e>>10]+Qe[e>>4&63]+Qe[e<<2&63]+"=")),o.join("")}});var Wo=B(Ko=>{"use strict";D();Object.defineProperty(Ko,"__esModule",{value:!0});Ko.fromArrayBufferToHex=hh;function hh(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var Yl=B(Vn=>{"use strict";D();Object.defineProperty(Vn,"__esModule",{value:!0});Vn.BrowserCrypto=void 0;var Ut=Wl(),mh=Wo(),Yo=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 Ut.fromByteArray(new Uint8Array(i))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),Ut.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"}},s=new TextEncoder().encode(n),l=Ut.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(l),s)}async sign(e,n){let i={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(n),s=await window.crypto.subtle.importKey("jwk",e,i,!0,["sign"]),l=await window.crypto.subtle.sign(i,s,o);return Ut.fromByteArray(new Uint8Array(l))}decodeBase64StringUtf8(e){let n=Ut.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return Ut.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,s=await window.crypto.subtle.importKey("raw",o.encode(i),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(n))}};Vn.BrowserCrypto=Yo});var zl=B($n=>{"use strict";D();Object.defineProperty($n,"__esModule",{value:!0});$n.NodeCrypto=void 0;var Gt=Q("crypto"),zo=class{async sha256DigestBase64(e){return Gt.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Gt.randomBytes(e).toString("base64")}async verify(e,n,i){let o=Gt.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,i,"base64")}async sign(e,n){let i=Gt.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 Gt.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let i=typeof e=="string"?e:yh(e);return gh(Gt.createHmac("sha256",i).update(n).digest())}};$n.NodeCrypto=zo;function gh(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 yh(t){return Buffer.from(t)}});var fn=B(st=>{"use strict";D();var Eh=st&&st.__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]}),_h=st&&st.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Eh(e,t,n)};Object.defineProperty(st,"__esModule",{value:!0});st.createCrypto=vh;st.hasBrowserCrypto=Xl;var Th=Yl(),Ah=zl();_h(Wo(),st);function vh(){return Xl()?new Th.BrowserCrypto:new Ah.NodeCrypto}function Xl(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Lt=B((Xo,Zl)=>{D();var Jn=Q("buffer"),Ze=Jn.Buffer;function Ql(t,e){for(var n in t)e[n]=t[n]}Ze.from&&Ze.alloc&&Ze.allocUnsafe&&Ze.allocUnsafeSlow?Zl.exports=Jn:(Ql(Jn,Xo),Xo.Buffer=wt);function wt(t,e,n){return Ze(t,e,n)}wt.prototype=Object.create(Ze.prototype);Ql(Ze,wt);wt.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Ze(t,e,n)};wt.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var i=Ze(t);return e!==void 0?typeof n=="string"?i.fill(e,n):i.fill(e):i.fill(0),i};wt.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Ze(t)};wt.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Jn.SlowBuffer(t)}});var eu=B((LI,jl)=>{"use strict";D();function Qo(t){var e=(t/8|0)+(t%8===0?0:1);return e}var Ch={ES256:Qo(256),ES384:Qo(384),ES512:Qo(521)};function Sh(t){var e=Ch[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}jl.exports=Sh});var Zo=B((FI,su)=>{"use strict";D();var Kn=Lt().Buffer,nu=eu(),Wn=128,iu=0,Ih=32,wh=16,Ph=2,ou=wh|Ih|iu<<6,Yn=Ph|iu<<6;function Rh(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function ru(t){if(Kn.isBuffer(t))return t;if(typeof t=="string")return Kn.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Nh(t,e){t=ru(t);var n=nu(e),i=n+1,o=t.length,s=0;if(t[s++]!==ou)throw new Error('Could not find expected "seq"');var l=t[s++];if(l===(Wn|1)&&(l=t[s++]),o-s<l)throw new Error('"seq" specified length of "'+l+'", only "'+(o-s)+'" remaining');if(t[s++]!==Yn)throw new Error('Could not find expected "int" for "r"');var u=t[s++];if(o-s-2<u)throw new Error('"r" specified length of "'+u+'", only "'+(o-s-2)+'" available');if(i<u)throw new Error('"r" specified length of "'+u+'", max of "'+i+'" is acceptable');var c=s;if(s+=u,t[s++]!==Yn)throw new Error('Could not find expected "int" for "s"');var d=t[s++];if(o-s!==d)throw new Error('"s" specified length of "'+d+'", expected "'+(o-s)+'"');if(i<d)throw new Error('"s" specified length of "'+d+'", max of "'+i+'" is acceptable');var f=s;if(s+=d,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var p=n-u,h=n-d,m=Kn.allocUnsafe(p+u+h+d);for(s=0;s<p;++s)m[s]=0;t.copy(m,s,c+Math.max(-p,0),c+u),s=n;for(var E=s;s<E+h;++s)m[s]=0;return t.copy(m,s,f+Math.max(-h,0),f+d),m=m.toString("base64"),m=Rh(m),m}function tu(t,e,n){for(var i=0;e+i<n&&t[e+i]===0;)++i;var o=t[e+i]>=Wn;return o&&--i,i}function Dh(t,e){t=ru(t);var n=nu(e),i=t.length;if(i!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+i+'"');var o=tu(t,0,n),s=tu(t,n,t.length),l=n-o,u=n-s,c=2+l+1+1+u,d=c<Wn,f=Kn.allocUnsafe((d?2:3)+c),p=0;return f[p++]=ou,d?f[p++]=c:(f[p++]=Wn|1,f[p++]=c&255),f[p++]=Yn,f[p++]=l,o<0?(f[p++]=0,p+=t.copy(f,p,0,n)):p+=t.copy(f,p,o,n),f[p++]=Yn,f[p++]=u,s<0?(f[p++]=0,t.copy(f,p,n)):t.copy(f,p,n+s),f}su.exports={derToJose:Nh,joseToDer:Dh}});var $e=B(at=>{"use strict";D();Object.defineProperty(at,"__esModule",{value:!0});at.LRUCache=void 0;at.snakeToCamel=lu;at.originalOrCamelOptions=Uh;at.removeUndefinedValuesInObject=Gh;at.isValidFile=Lh;at.getWellKnownCertificateConfigFileLocation=bh;var Mh=Q("fs"),xh=Q("os"),jo=Q("path"),kh="certificate_config.json",au="gcloud";function lu(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function Uh(t){function e(n){let i=t||{};return i[n]??i[lu(n)]}return{get:e}}var er=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()}};at.LRUCache=er;function Gh(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function Lh(t){try{return(await Mh.promises.lstat(t)).isFile()}catch{return!1}}function bh(){let t=process.env.CLOUDSDK_CONFIG||(Fh()?jo.join(process.env.APPDATA||"",au):jo.join(process.env.HOME||"",".config",au));return jo.join(t,kh)}function Fh(){return xh.platform().startsWith("win")}});var uu=B((HI,Oh)=>{Oh.exports={name:"google-auth-library",version:"10.6.2",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:"packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node-core.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.0","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","docs-test":"echo 'disabled until linkinator is fixed'","predocs-test":"npm run docs",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/google-auth-library-nodejs"}});var tr=B(ft=>{"use strict";D();Object.defineProperty(ft,"__esModule",{value:!0});ft.USER_AGENT=ft.PRODUCT_NAME=ft.pkg=void 0;var cu=uu();ft.pkg=cu;var du="google-api-nodejs-client";ft.PRODUCT_NAME=du;var qh=`${du}/${cu.version}`;ft.USER_AGENT=qh});var Re=B(Je=>{"use strict";D();Object.defineProperty(Je,"__esModule",{value:!0});Je.AuthClient=Je.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Je.DEFAULT_UNIVERSE=void 0;var Bh=Q("events"),nr=me(),Hh=$e(),Vh=Bo(),ir=tr();Je.DEFAULT_UNIVERSE="googleapis.com";Je.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=5*60*1e3;var or=class t extends Bh.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Je.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Je.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,Hh.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")??Je.DEFAULT_UNIVERSE,this.transporter=e.transporter??new nr.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,s=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&&nr.Gaxios.mergeHeaders(s,n.headers),i&&nr.Gaxios.mergeHeaders(s,new Headers(i.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...i,...n,headers:s,url:o}):this.request({...i,headers:s,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,Vh.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(`${ir.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${ir.USER_AGENT}`):e.headers.set("User-Agent",ir.USER_AGENT);try{let i=e,o=i[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;i[t.RequestLogIdSymbol]=s;let l={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,s,l):t.log.info("[%s] request %j",s,l)}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"]}}}};Je.AuthClient=or});var sr=B(zn=>{"use strict";D();Object.defineProperty(zn,"__esModule",{value:!0});zn.LoginTicket=void 0;var rr=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()}}};zn.LoginTicket=rr});var Pt=B(je=>{"use strict";D();Object.defineProperty(je,"__esModule",{value:!0});je.OAuth2Client=je.ClientAuthentication=je.CertificateFormat=je.CodeChallengeMethod=void 0;var fu=me(),$h=Q("querystring"),Jh=Q("stream"),Kh=Zo(),pu=$e(),ar=fn(),bt=Re(),Wh=sr(),hu;(function(t){t.Plain="plain",t.S256="S256"})(hu||(je.CodeChallengeMethod=hu={}));var lt;(function(t){t.PEM="PEM",t.JWK="JWK"})(lt||(je.CertificateFormat=lt={}));var pn;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(pn||(je.ClientAuthentication=pn={}));var lr=class t extends bt.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=lt.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||pn.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()+"?"+$h.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,ar.createCrypto)(),i=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(i)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:i,codeChallenge:s}}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===pn.ClientSecretBasic){let c=Buffer.from(`${this._clientId}:${this._clientSecret}`);i.set("authorization",`Basic ${c.toString("base64")}`)}this.clientAuthentication===pn.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,pu.removeUndefinedValuesInObject)(o)),headers:i};bt.AuthClient.setMethodName(s,"getTokenAsync");let l=await this.transporter.request(s),u=l.data;return l.data&&l.data.expires_in&&(u.expiry_date=new Date().getTime()+l.data.expires_in*1e3,delete u.expires_in),this.emit("tokens",u),{tokens:u,res:l}}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 l={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,pu.removeUndefinedValuesInObject)(i))};bt.AuthClient.setMethodName(l,"refreshTokenNoCache"),o=await this.transporter.request(l)}catch(l){throw l instanceof fu.GaxiosError&&l.message==="invalid_grant"&&l.response?.data&&/ReAuth/i.test(l.response.data.error_description)&&(l.message=JSON.stringify(l.response.data)),l}let s=o.data;return o.data&&o.data.expires_in&&(s.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,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 s=this.credentials;s.token_type=s.token_type||"Bearer",o.refresh_token=s.refresh_token,this.credentials=o;let l=new Headers({authorization:s.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(l),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(bt.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=fu.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 s=o.status,l=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 Jh.Readable,d=s===401||s===403;if(!n&&d&&!c&&l)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,ar.hasBrowserCrypto)()?lt.JWK:lt.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let i,o;switch(n){case lt.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case lt.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:o};bt.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 s=i?.headers.get("cache-control"),l=-1;if(s){let d=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;d&&(l=Number(d)*1e3)}let u={};switch(n){case lt.PEM:u=i.data;break;case lt.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=l===-1?null:new Date(c.getTime()+l),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};bt.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,s){let l=(0,ar.createCrypto)();s||(s=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(l.decodeBase64StringUtf8(u[0]))}catch(U){throw U instanceof Error&&(U.message=`Can't parse token envelope: ${u[0]}': ${U.message}`),U}if(!f)throw new Error("Can't parse token envelope: "+u[0]);try{p=JSON.parse(l.decodeBase64StringUtf8(u[1]))}catch(U){throw U instanceof Error&&(U.message=`Can't parse token payload '${u[0]}`),U}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=Kh.joseToDer(d,"ES256").toString("base64")),!await l.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 E=Number(p.iat);if(isNaN(E))throw new Error("iat field using invalid format");let A=Number(p.exp);if(isNaN(A))throw new Error("exp field using invalid format");let T=new Date().getTime()/1e3;if(A>=T+s)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let S=E-t.CLOCK_SKEW_SECS_,b=A+t.CLOCK_SKEW_SECS_;if(T<S)throw new Error("Token used too early, "+T+" < "+S+": "+JSON.stringify(p));if(T>b)throw new Error("Token used too late, "+T+" > "+b+": "+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 U=p.aud,F=!1;if(i.constructor===Array?F=i.indexOf(U)>-1:F=U===i,!F)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new Wh.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}};je.OAuth2Client=lr});var cr=B(Xn=>{"use strict";D();Object.defineProperty(Xn,"__esModule",{value:!0});Xn.Compute=void 0;var Yh=me(),mu=dn(),zh=Pt(),ur=class extends zh.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 mu.instance(o)}catch(o){throw o instanceof Yh.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 mu.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))}};Xn.Compute=ur});var fr=B(Qn=>{"use strict";D();Object.defineProperty(Qn,"__esModule",{value:!0});Qn.IdTokenClient=void 0;var Xh=Pt(),dr=class extends Xh.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}};Qn.IdTokenClient=dr});var pr=B(Ft=>{"use strict";D();Object.defineProperty(Ft,"__esModule",{value:!0});Ft.GCPEnv=void 0;Ft.clear=Qh;Ft.getEnv=Zh;var gu=dn(),et;(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"})(et||(Ft.GCPEnv=et={}));var hn;function Qh(){hn=void 0}async function Zh(){return hn||(hn=jh(),hn)}async function jh(){let t=et.NONE;return em()?t=et.APP_ENGINE:tm()?t=et.CLOUD_FUNCTIONS:await rm()?await om()?t=et.KUBERNETES_ENGINE:nm()?t=et.CLOUD_RUN:im()?t=et.CLOUD_RUN_JOBS:t=et.COMPUTE_ENGINE:t=et.NONE,t}function em(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function tm(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function nm(){return!!process.env.K_CONFIGURATION}function im(){return!!process.env.CLOUD_RUN_JOB}async function om(){try{return await gu.instance("attributes/cluster-name"),!0}catch{return!1}}async function rm(){return gu.isAvailable()}});var hr=B((iw,yu)=>{D();var Zn=Lt().Buffer,sm=Q("stream"),am=Q("util");function jn(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Zn.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Zn.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}am.inherits(jn,sm);jn.prototype.write=function(e){this.buffer=Zn.concat([this.buffer,Zn.from(e)]),this.emit("data",e)};jn.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};yu.exports=jn});var _u=B((rw,Eu)=>{"use strict";D();var mn=Q("buffer").Buffer,mr=Q("buffer").SlowBuffer;Eu.exports=ei;function ei(t,e){if(!mn.isBuffer(t)||!mn.isBuffer(e)||t.length!==e.length)return!1;for(var n=0,i=0;i<t.length;i++)n|=t[i]^e[i];return n===0}ei.install=function(){mn.prototype.equal=mr.prototype.equal=function(e){return ei(this,e)}};var lm=mn.prototype.equal,um=mr.prototype.equal;ei.restore=function(){mn.prototype.equal=lm,mr.prototype.equal=um}});var _r=B((aw,Ru)=>{D();var qt=Lt().Buffer,Ge=Q("crypto"),Au=Zo(),Tu=Q("util"),cm=`"%s" is not a valid algorithm.
16
- Supported algorithms are:
17
- "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,gn="secret must be a string or buffer",Ot="key must be a string or a buffer",dm="key must be a string, a buffer or an object",yr=typeof Ge.createPublicKey=="function";yr&&(Ot+=" or a KeyObject",gn+="or a KeyObject");function vu(t){if(!qt.isBuffer(t)&&typeof t!="string"&&(!yr||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw Ke(Ot)}function Cu(t){if(!qt.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw Ke(dm)}function fm(t){if(!qt.isBuffer(t)){if(typeof t=="string")return t;if(!yr||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw Ke(gn)}}function Er(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Su(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function Ke(t){var e=[].slice.call(arguments,1),n=Tu.format.bind(Tu,t).apply(null,e);return new TypeError(n)}function pm(t){return qt.isBuffer(t)||typeof t=="string"}function yn(t){return pm(t)||(t=JSON.stringify(t)),t}function Iu(t){return function(n,i){fm(i),n=yn(n);var o=Ge.createHmac("sha"+t,i),s=(o.update(n),o.digest("base64"));return Er(s)}}var gr,hm="timingSafeEqual"in Ge?function(e,n){return e.byteLength!==n.byteLength?!1:Ge.timingSafeEqual(e,n)}:function(e,n){return gr||(gr=_u()),gr(e,n)};function mm(t){return function(n,i,o){var s=Iu(t)(n,o);return hm(qt.from(i),qt.from(s))}}function wu(t){return function(n,i){Cu(i),n=yn(n);var o=Ge.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(i,"base64"));return Er(s)}}function Pu(t){return function(n,i,o){vu(o),n=yn(n),i=Su(i);var s=Ge.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,i,"base64")}}function gm(t){return function(n,i){Cu(i),n=yn(n);var o=Ge.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:i,padding:Ge.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ge.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Er(s)}}function ym(t){return function(n,i,o){vu(o),n=yn(n),i=Su(i);var s=Ge.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:Ge.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ge.constants.RSA_PSS_SALTLEN_DIGEST},i,"base64")}}function Em(t){var e=wu(t);return function(){var i=e.apply(null,arguments);return i=Au.derToJose(i,"ES"+t),i}}function _m(t){var e=Pu(t);return function(i,o,s){o=Au.joseToDer(o,"ES"+t).toString("base64");var l=e(i,o,s);return l}}function Tm(){return function(){return""}}function Am(){return function(e,n){return n===""}}Ru.exports=function(e){var n={hs:Iu,rs:wu,ps:gm,es:Em,none:Tm},i={hs:mm,rs:Pu,ps:ym,es:_m,none:Am},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw Ke(cm,e);var s=(o[1]||o[3]).toLowerCase(),l=o[2];return{sign:n[s](l),verify:i[s](l)}}});var Tr=B((uw,Nu)=>{D();var vm=Q("buffer").Buffer;Nu.exports=function(e){return typeof e=="string"?e:typeof e=="number"||vm.isBuffer(e)?e.toString():JSON.stringify(e)}});var Gu=B((dw,Uu)=>{D();var Cm=Lt().Buffer,Du=hr(),Sm=_r(),Im=Q("stream"),Mu=Tr(),Ar=Q("util");function xu(t,e){return Cm.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function wm(t,e,n){n=n||"utf8";var i=xu(Mu(t),"binary"),o=xu(Mu(e),n);return Ar.format("%s.%s",i,o)}function ku(t){var e=t.header,n=t.payload,i=t.secret||t.privateKey,o=t.encoding,s=Sm(e.alg),l=wm(e,n,o),u=s.sign(l,i);return Ar.format("%s.%s",l,u)}function ti(t){var e=t.secret;if(e=e??t.privateKey,e=e??t.key,/^hs/i.test(t.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var n=new Du(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new Du(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}Ar.inherits(ti,Im);ti.prototype.sign=function(){try{var e=ku({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};ti.sign=ku;Uu.exports=ti});var Ju=B((pw,$u)=>{D();var bu=Lt().Buffer,Lu=hr(),Pm=_r(),Rm=Q("stream"),Fu=Tr(),Nm=Q("util"),Dm=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function Mm(t){return Object.prototype.toString.call(t)==="[object Object]"}function xm(t){if(Mm(t))return t;try{return JSON.parse(t)}catch{return}}function Ou(t){var e=t.split(".",1)[0];return xm(bu.from(e,"base64").toString("binary"))}function km(t){return t.split(".",2).join(".")}function qu(t){return t.split(".")[2]}function Um(t,e){e=e||"utf8";var n=t.split(".")[1];return bu.from(n,"base64").toString(e)}function Bu(t){return Dm.test(t)&&!!Ou(t)}function Hu(t,e,n){if(!e){var i=new Error("Missing algorithm parameter for jws.verify");throw i.code="MISSING_ALGORITHM",i}t=Fu(t);var o=qu(t),s=km(t),l=Pm(e);return l.verify(s,o,n)}function Vu(t,e){if(e=e||{},t=Fu(t),!Bu(t))return null;var n=Ou(t);if(!n)return null;var i=Um(t);return(n.typ==="JWT"||e.json)&&(i=JSON.parse(i,e.encoding)),{header:n,payload:i,signature:qu(t)}}function Bt(t){t=t||{};var e=t.secret;if(e=e??t.publicKey,e=e??t.key,/^hs/i.test(t.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var n=new Lu(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new Lu(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}Nm.inherits(Bt,Rm);Bt.prototype.verify=function(){try{var e=Hu(this.signature.buffer,this.algorithm,this.key.buffer),n=Vu(this.signature.buffer,this.encoding);return this.emit("done",e,n),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(i){this.readable=!1,this.emit("error",i),this.emit("close")}};Bt.decode=Vu;Bt.isValid=Bu;Bt.verify=Hu;$u.exports=Bt});var vr=B(pt=>{D();var Ku=Gu(),ni=Ju(),Gm=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];pt.ALGORITHMS=Gm;pt.sign=Ku.sign;pt.verify=ni.verify;pt.decode=ni.decode;pt.isValid=ni.isValid;pt.createSign=function(e){return new Ku(e)};pt.createVerify=function(e){return new ni(e)}});var Yu=B(ii=>{"use strict";D();Object.defineProperty(ii,"__esModule",{value:!0});ii.buildPayloadForJwsSign=Wu;ii.getJwsSign=Om;var Lm=vr(),bm="RS256",Fm="https://oauth2.googleapis.com/token";function Wu(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:Fm,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function Om(t){let e=Wu(t);return(0,Lm.sign)({header:{alg:bm},payload:e,secret:t.key})}});var zu=B(Cr=>{"use strict";D();Object.defineProperty(Cr,"__esModule",{value:!0});Cr.getToken=$m;var qm=Yu(),Bm="https://oauth2.googleapis.com/token",Hm="urn:ietf:params:oauth:grant-type:jwt-bearer",Vm=t=>({method:"POST",url:Bm,data:new URLSearchParams({grant_type:Hm,assertion:(0,qm.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function $m(t){if(!t.transporter)throw new Error("No transporter set.");try{let e=Vm(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 Xu=B(oi=>{"use strict";D();Object.defineProperty(oi,"__esModule",{value:!0});oi.ErrorWithCode=void 0;var Sr=class extends Error{code;constructor(e,n){super(e),this.code=n}};oi.ErrorWithCode=Sr});var Dr=B(Nr=>{"use strict";D();Object.defineProperty(Nr,"__esModule",{value:!0});Nr.getCredentials=Wm;var Jm=Q("path"),Qu=Q("fs"),Km=Q("util"),ri=Xu(),Zu=Qu.readFile?(0,Km.promisify)(Qu.readFile):async()=>{throw new ri.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},ht;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(ht||(ht={}));var Ir=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await Zu(this.keyFilePath,"utf8"),n;try{n=JSON.parse(e)}catch(s){let l=s;throw new Error(`Invalid JSON key file: ${l.message}`)}let i=n.private_key,o=n.client_email;if(!i||!o)throw new ri.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:i,clientEmail:o}}},wr=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await Zu(this.keyFilePath,"utf8")}}},Pr=class{async getCredentials(){throw new ri.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")}},Rr=class{static create(e){switch(Jm.extname(e)){case ht.JSON:return new Ir(e);case ht.DER:case ht.CRT:case ht.PEM:return new wr(e);case ht.P12:case ht.PFX:return new Pr;default:throw new ri.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function Wm(t){return Rr.create(t).getCredentials()}});var ju=B(si=>{"use strict";D();Object.defineProperty(si,"__esModule",{value:!0});si.TokenHandler=void 0;var Ym=zu(),zm=Dr(),Mr=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,zm.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,Ym.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}}};si.TokenHandler=Mr});var ec=B(xr=>{"use strict";D();Object.defineProperty(xr,"__esModule",{value:!0});xr.revokeToken=Zm;var Xm="https://oauth2.googleapis.com/revoke?token=",Qm=!0;async function Zm(t,e){let n=Xm+t;return await e.request({url:n,retry:Qm})}});var Ur=B(ai=>{"use strict";D();Object.defineProperty(ai,"__esModule",{value:!0});ai.GoogleToken=void 0;var jm=me(),tc=ju(),eg=ec(),kr=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,jm.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 tc.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(s=>i(null,s),i),o}revokeToken(e){if(!this.accessToken)return Promise.reject(new Error("No token to revoke."));let n=(0,eg.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new tc.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};ai.GoogleToken=kr});var Lr=B(li=>{"use strict";D();Object.defineProperty(li,"__esModule",{value:!0});li.JWTAccess=void 0;var tg=vr(),ng=$e(),nc={alg:"RS256",typ:"JWT"},Gr=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new ng.LRUCache({capacity:500,maxAge:60*60*1e3});constructor(e,n,i,o){this.email=e,this.key=n,this.keyId=i,this.eagerRefreshThresholdMillis=o??5*60*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),s=this.cache.get(o),l=Date.now();if(s&&s.expiration-l>this.eagerRefreshThresholdMillis)return new Headers(s.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 E in d)if(n[E])throw new Error(`The '${E}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...nc,kid:this.keyId}:nc,p=Object.assign(d,n),h=tg.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",s=>o+=s).on("error",i).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){i(s)}})})}};li.JWTAccess=Gr});var Fr=B(ci=>{"use strict";D();Object.defineProperty(ci,"__esModule",{value:!0});ci.JWT=void 0;var ic=Ur(),ig=Dr(),og=Lr(),rg=Pt(),ui=Re(),br=class t extends rg.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!==ui.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==ui.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${ui.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 og.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!==ui.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?i:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new ic.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 ic.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",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){i(s)}})})}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,ig.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.")}};ci.JWT=br});var qr=B(Ht=>{"use strict";D();Object.defineProperty(Ht,"__esModule",{value:!0});Ht.UserRefreshClient=Ht.USER_REFRESH_ACCOUNT_TYPE=void 0;var sg=Pt(),ag=Re();Ht.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var Or=class t extends sg.OAuth2Client{_refreshToken;constructor(e,n,i,o,s){let l=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:i,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:s};super(l),this._refreshToken=l.refreshToken,this.credentials.refresh_token=l.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 ag.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",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),n()}catch(s){return i(s)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};Ht.UserRefreshClient=Or});var Hr=B(Vt=>{"use strict";D();Object.defineProperty(Vt,"__esModule",{value:!0});Vt.Impersonated=Vt.IMPERSONATED_ACCOUNT_TYPE=void 0;var oc=Pt(),lg=me(),ug=$e();Vt.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Br=class t extends oc.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 oc.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,ug.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"}),s=o.data;return this.credentials.access_token=s.accessToken,this.credentials.expiry_date=Date.parse(s.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let n=0,i="";throw e instanceof lg.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`,s={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};Vt.Impersonated=Br});var $r=B(En=>{"use strict";D();Object.defineProperty(En,"__esModule",{value:!0});En.OAuthClientAuthHandler=void 0;En.getErrorFromOAuthErrorResponse=fg;var $t=me(),cg=fn(),dg=["PUT","POST","PATCH"],Vr=class{#e=(0,cg.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new $t.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new $t.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=$t.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=$t.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=$t.Gaxios.mergeHeaders(e.headers);let i=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${i}:${o}`);$t.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!dg.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 s=new URLSearchParams(e.data??"");s.append("client_id",this.#t.clientId),s.append("client_secret",this.#t.clientSecret||""),e.data=s}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"]}}}};En.OAuthClientAuthHandler=Vr;function fg(t,e){let n=t.error,i=t.error_description,o=t.error_uri,s=`Error code ${n}`;typeof i<"u"&&(s+=`: ${i}`),typeof o<"u"&&(s+=` - ${o}`);let l=new Error(s);if(e){let u=Object.keys(e);e.stack&&u.push("stack"),u.forEach(c=>{c!=="message"&&Object.defineProperty(l,c,{value:e[c],writable:!1,enumerable:!0})})}return l}});var fi=B(di=>{"use strict";D();Object.defineProperty(di,"__esModule",{value:!0});di.StsCredentials=void 0;var pg=me(),hg=Re(),rc=$r(),mg=$e(),Jr=class t extends rc.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)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,mg.removeUndefinedValuesInObject)(o)),responseType:"json"};hg.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let l=await this.transporter.request(s),u=l.data;return u.res=l,u}catch(l){throw l instanceof pg.GaxiosError&&l.response?(0,rc.getErrorFromOAuthErrorResponse)(l.response.data,l):l}}};di.StsCredentials=Jr});var mt=B(Le=>{"use strict";D();Object.defineProperty(Le,"__esModule",{value:!0});Le.BaseExternalAccountClient=Le.CLOUD_RESOURCE_MANAGER=Le.EXTERNAL_ACCOUNT_TYPE=Le.EXPIRATION_TIME_OFFSET=void 0;var gg=me(),yg=Q("stream"),Kr=Re(),Eg=fi(),sc=$e(),_g=tr(),Tg="urn:ietf:params:oauth:grant-type:token-exchange",Ag="urn:ietf:params:oauth:token-type:access_token",Wr="https://www.googleapis.com/auth/cloud-platform",vg=3600;Le.EXPIRATION_TIME_OFFSET=5*60*1e3;Le.EXTERNAL_ACCOUNT_TYPE="external_account";Le.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var Cg="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",Sg="https://sts.{universeDomain}/v1/token",Yr=class t extends Kr.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,sc.originalOrCamelOptions)(e),i=n.get("type");if(i&&i!==Le.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Le.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??Sg.replace("{universeDomain}",this.universeDomain);let l=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,sc.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:s}),this.stsCredential=new Eg.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[Wr],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=l,this.workforcePoolUserProject=u;let p=new RegExp(Cg);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=vg),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"};Kr.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=gg.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),i=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let l=s.status,u=s.config.data instanceof yg.Readable;if(!n&&(l===401||l===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:Tg,audience:this.audience,requestedTokenType:Ag,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Wr]:this.getScopesArray()},i=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(n,o,i);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1e3,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.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"};Kr.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||[Wr]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,i=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${_g.pkg.version} google-byoid-sdk source/${i} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Le.BaseExternalAccountClient=Yr});var ac=B(pi=>{"use strict";D();Object.defineProperty(pi,"__esModule",{value:!0});pi.FileSubjectTokenSupplier=void 0;var Xr=Q("util"),Qr=Q("fs"),Ig=(0,Xr.promisify)(Qr.readFile??(()=>{})),wg=(0,Xr.promisify)(Qr.realpath??(()=>{})),Pg=(0,Xr.promisify)(Qr.lstat??(()=>{})),zr=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 wg(e),!(await Pg(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 Ig(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}};pi.FileSubjectTokenSupplier=zr});var lc=B(hi=>{"use strict";D();Object.defineProperty(hi,"__esModule",{value:!0});hi.UrlSubjectTokenSupplier=void 0;var Rg=Re(),Zr=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};Rg.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}};hi.UrlSubjectTokenSupplier=Zr});var uc=B(Ne=>{"use strict";D();Object.defineProperty(Ne,"__esModule",{value:!0});Ne.CertificateSubjectTokenSupplier=Ne.InvalidConfigurationError=Ne.CertificateSourceUnavailableError=Ne.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var mi=$e(),gi=Q("fs"),yi=Q("crypto"),Ng=Q("https");Ne.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var tt=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Ne.CertificateSourceUnavailableError=tt;var be=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Ne.InvalidConfigurationError=be;var jr=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new be("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new be("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new be("Cannot create mTLS Agent with missing certificate or key");return new Ng.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,mi.isValidFile)(e))return e;throw new tt(`Provided certificate config path is invalid: ${e}`)}let n=process.env[Ne.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,mi.isValidFile)(n))return n;throw new tt(`Path from environment variable "${Ne.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let i=(0,mi.getWellKnownCertificateConfigFileLocation)();if(await(0,mi.isValidFile)(i))return i;throw new tt(`Could not find certificate configuration file. Searched override path, the "${Ne.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${i}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await gi.promises.readFile(e,"utf8")}catch{throw new tt(`Failed to read certificate config file at: ${e}`)}try{let i=JSON.parse(n),o=i?.cert_configs?.workload?.cert_path,s=i?.cert_configs?.workload?.key_path;if(!o||!s)throw new be(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(i){throw i instanceof be?i:new be(`Failed to parse certificate config from ${e}: ${i.message}`)}}async#n(e,n){let i,o;try{i=await gi.promises.readFile(e),new yi.X509Certificate(i)}catch(s){let l=s instanceof Error?s.message:String(s);throw new tt(`Failed to read certificate file at ${e}: ${l}`)}try{o=await gi.promises.readFile(n),(0,yi.createPrivateKey)(o)}catch(s){let l=s instanceof Error?s.message:String(s);throw new tt(`Failed to read private key file at ${n}: ${l}`)}return{cert:i,key:o}}async#i(e){let n=new yi.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await gi.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((c,d)=>{try{return new yi.X509Certificate(c)}catch(f){let p=f instanceof Error?f.message:String(f);throw new be(`Failed to parse certificate at index ${d} in trust chain file ${this.trustChainPath}: ${p}`)}}),l=s.findIndex(c=>n.raw.equals(c.raw)),u;if(l===-1)u=[n,...s];else if(l===0)u=s;else throw new be(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${l}).`);return JSON.stringify(u.map(c=>c.raw.toString("base64")))}catch(i){if(i instanceof be)throw i;let o=i instanceof Error?i.message:String(i);throw new tt(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};Ne.CertificateSubjectTokenSupplier=jr});var ns=B(Ei=>{"use strict";D();Object.defineProperty(Ei,"__esModule",{value:!0});Ei.IdentityPoolClient=void 0;var Dg=mt(),es=$e(),Mg=ac(),xg=lc(),cc=uc(),kg=fi(),dc=me(),ts=class t extends Dg.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,es.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 s=(0,es.originalOrCamelOptions)(i),l=(0,es.originalOrCamelOptions)(s.get("format")),u=l.get("type")||"text",c=l.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=s.get("file"),f=s.get("url"),p=s.get("certificate"),h=s.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 Mg.FileSubjectTokenSupplier({filePath:d,formatType:u,subjectTokenFieldName:c});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new xg.UrlSubjectTokenSupplier({url:f,formatType:u,subjectTokenFieldName:c,headers:h,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let m=new cc.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 cc.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new kg.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new dc.Gaxios({agent:n})}),this.transporter=new dc.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};Ei.IdentityPoolClient=ts});var os=B(Ti=>{"use strict";D();Object.defineProperty(Ti,"__esModule",{value:!0});Ti.AwsRequestSigner=void 0;var _i=me(),pc=fn(),fc="AWS4-HMAC-SHA256",Ug="aws4_request",is=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,pc.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",s=e.body||n,l=e.headers,u=await this.getCredentials(),c=new URL(i);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let d=await Lg({crypto:this.crypto,host:c.host,canonicalUri:c.pathname,canonicalQuerystring:c.search.slice(1),method:o,region:this.region,securityCredentials:u,requestPayload:s,additionalAmzHeaders:l}),f=_i.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:c.host},l||{});u.token&&_i.Gaxios.mergeHeaders(f,{"x-amz-security-token":u.token});let p={url:i,method:o,headers:f};return s!==void 0&&(p.body=s),p}};Ti.AwsRequestSigner=is;async function _n(t,e,n){return await t.signWithHmacSha256(e,n)}async function Gg(t,e,n,i,o){let s=await _n(t,`AWS4${e}`,n),l=await _n(t,s,i),u=await _n(t,l,o);return await _n(t,u,"aws4_request")}async function Lg(t){let e=_i.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",i=t.host.split(".")[0],o=new Date,s=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),l=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let u=_i.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),c="",d=[...u.keys()].sort();d.forEach(b=>{c+=`${b}:${u.get(b)}
18
- `});let f=d.join(";"),p=await t.crypto.sha256DigestHex(n),h=`${t.method.toUpperCase()}
19
- ${t.canonicalUri}
20
- ${t.canonicalQuerystring}
21
- ${c}
22
- ${f}
23
- ${p}`,m=`${l}/${t.region}/${i}/${Ug}`,E=`${fc}
24
- ${s}
25
- ${m}
26
- `+await t.crypto.sha256DigestHex(h),A=await Gg(t.crypto,t.securityCredentials.secretAccessKey,l,t.region,i),T=await _n(t.crypto,A,E),S=`${fc} Credential=${t.securityCredentials.accessKeyId}/${m}, SignedHeaders=${f}, Signature=${(0,pc.fromArrayBufferToHex)(T)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:S,canonicalQuerystring:t.canonicalQuerystring}}});var hc=B(vi=>{"use strict";D();Object.defineProperty(vi,"__esModule",{value:!0});vi.DefaultAwsSecurityCredentialsSupplier=void 0;var Ai=Re(),rs=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};Ai.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 Ai.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 Ai.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 Ai.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}};vi.DefaultAwsSecurityCredentialsSupplier=rs});var as=B(Ci=>{"use strict";D();Object.defineProperty(Ci,"__esModule",{value:!0});Ci.AwsClient=void 0;var bg=os(),Fg=mt(),Og=hc(),mc=$e(),qg=me(),ss=class t extends Fg.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,mc.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 s=(0,mc.originalOrCamelOptions)(i);this.environmentId=s.get("environment_id");let l=s.get("region_url"),u=s.get("url"),c=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new Og.DefaultAwsSecurityCredentialsSupplier({regionUrl:l,securityCredentialsUrl:u,imdsV2SessionTokenUrl:c}),this.regionalCredVerificationUrl=s.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 bg.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 qg.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>n.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};Ci.AwsClient=ss});var fs=B(fe=>{"use strict";D();Object.defineProperty(fe,"__esModule",{value:!0});fe.InvalidSubjectTokenError=fe.InvalidMessageFieldError=fe.InvalidCodeFieldError=fe.InvalidTokenTypeFieldError=fe.InvalidExpirationTimeFieldError=fe.InvalidSuccessFieldError=fe.InvalidVersionFieldError=fe.ExecutableResponseError=fe.ExecutableResponse=void 0;var Si="urn:ietf:params:oauth:token-type:saml2",ls="urn:ietf:params:oauth:token-type:id_token",us="urn:ietf:params:oauth:token-type:jwt",cs=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 wi("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!==Si&&this.tokenType!==ls&&this.tokenType!==us)throw new Pi(`Executable response must contain a 'token_type' field when successful and it must be one of ${ls}, ${us}, or ${Si}.`);if(this.tokenType===Si){if(!e.saml_response)throw new Tn(`Executable response must contain a 'saml_response' field when token_type=${Si}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Tn(`Executable response must contain a 'id_token' field when token_type=${ls} or ${us}.`);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 Ni("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)}};fe.ExecutableResponse=cs;var nt=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};fe.ExecutableResponseError=nt;var Ii=class extends nt{};fe.InvalidVersionFieldError=Ii;var wi=class extends nt{};fe.InvalidSuccessFieldError=wi;var ds=class extends nt{};fe.InvalidExpirationTimeFieldError=ds;var Pi=class extends nt{};fe.InvalidTokenTypeFieldError=Pi;var Ri=class extends nt{};fe.InvalidCodeFieldError=Ri;var Ni=class extends nt{};fe.InvalidMessageFieldError=Ni;var Tn=class extends nt{};fe.InvalidSubjectTokenError=Tn});var ms=B(Jt=>{"use strict";D();Object.defineProperty(Jt,"__esModule",{value:!0});Jt.PluggableAuthHandler=Jt.ExecutableError=void 0;var Rt=fs(),Bg=Q("child_process"),ps=Q("fs"),Di=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)}};Jt.ExecutableError=Di;var hs=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=Bg.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";o.stdout.on("data",u=>{s+=u}),o.stderr.on("data",u=>{s+=u});let l=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(l),u===0)try{let c=JSON.parse(s),d=new Rt.ExecutableResponse(c);return n(d)}catch(c){return c instanceof Rt.ExecutableResponseError?i(c):i(new Rt.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return i(new Di(s,u.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await ps.promises.realpath(this.outputFile)}catch{return}if(!(await ps.promises.lstat(e)).isFile())return;let n=await ps.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let i=JSON.parse(n);return new Rt.ExecutableResponse(i).isValid()?new Rt.ExecutableResponse(i):void 0}catch(i){throw i instanceof Rt.ExecutableResponseError?i:new Rt.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}};Jt.PluggableAuthHandler=hs});var ys=B(Kt=>{"use strict";D();Object.defineProperty(Kt,"__esModule",{value:!0});Kt.PluggableAuthClient=Kt.ExecutableError=void 0;var Hg=mt(),Vg=fs(),gc=ms(),$g=ms();Object.defineProperty(Kt,"ExecutableError",{enumerable:!0,get:function(){return $g.ExecutableError}});var Jg=30*1e3,yc=5*1e3,Ec=120*1e3,Kg="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",_c=1,gs=class extends Hg.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=Jg;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<yc||this.timeoutMillis>Ec)throw new Error(`Timeout must be between ${yc} and ${Ec} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new gc.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[Kg]!=="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>_c)throw new Error(`Version of executable is not currently supported, maximum supported version is ${_c}.`);if(!e.success)throw new gc.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new Vg.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}};Kt.PluggableAuthClient=gs});var _s=B(Mi=>{"use strict";D();Object.defineProperty(Mi,"__esModule",{value:!0});Mi.ExternalAccountClient=void 0;var Wg=mt(),Yg=ns(),zg=as(),Xg=ys(),Es=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===Wg.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new zg.AwsClient(e):e.credential_source?.executable?new Xg.PluggableAuthClient(e):new Yg.IdentityPoolClient(e):null}};Mi.ExternalAccountClient=Es});var vs=B(Wt=>{"use strict";D();Object.defineProperty(Wt,"__esModule",{value:!0});Wt.ExternalAccountAuthorizedUserClient=Wt.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Ac=Re(),Tc=$r(),vc=me(),Qg=Q("stream"),Zg=mt();Wt.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var jg="https://sts.{universeDomain}/v1/oauthtoken",Ts=class t extends Tc.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"};Ac.AuthClient.setMethodName(i,"refreshToken"),this.applyClientAuthenticationOptions(i);try{let o=await this.transporter.request(i),s=o.data;return s.res=o,s}catch(o){throw o instanceof vc.GaxiosError&&o.response?(0,Tc.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},As=class extends Ac.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 Ts({tokenRefreshEndpoint:e.token_url??jg.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=Zg.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=vc.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),i=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let l=s.status,u=s.config.data instanceof Qg.Readable;if(!n&&(l===401||l===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}};Wt.ExternalAccountAuthorizedUserClient=As});var wc=B(We=>{"use strict";D();Object.defineProperty(We,"__esModule",{value:!0});We.GoogleAuth=We.GoogleAuthExceptionMessages=void 0;var ey=Q("child_process"),An=Q("fs"),ty=me(),vn=dn(),ny=Q("os"),Cs=Q("path"),iy=fn(),oy=cr(),ry=fr(),sy=pr(),Yt=Fr(),Cc=qr(),zt=Hr(),ay=_s(),Cn=mt(),Ss=Re(),Sc=vs(),Ic=$e();We.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.
27
- To learn more about authentication and Google APIs, visit:
28
- https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
29
- To learn more about authentication and Google APIs, visit:
30
- 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.
31
- To learn more about Universe Domain retrieval, visit:
32
- https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Is=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(We.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===We.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(We.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 vn.universe("universe-domain"),e||=Ss.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=Ss.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,Ic.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Ss.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 Yt.JWT?n.scopes=this.scopes:n instanceof Cn.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof Yt.JWT?n.scopes=this.scopes:n instanceof Cn.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new oy.Compute(e));throw new Error(We.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=vn.getGCPResidency()||await vn.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 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=null;if(this._isWindows())n=process.env.APPDATA;else{let o=process.env.HOME;o&&(n=Cs.join(o,".config"))}return n&&(n=Cs.join(n,"gcloud","application_default_credentials.json"),An.existsSync(n)||(n=null)),n?await this._getApplicationCredentialsFromFilePath(n,e):null}async _getApplicationCredentialsFromFilePath(e,n={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=An.realpathSync(e),!An.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=An.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!==zt.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${zt.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 zt.Impersonated({...e,sourceClient:n,targetPrincipal:i,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,n={}){let i,o=(0,Ic.originalOrCamelOptions)(n).get("universe_domain");return e.type===Cc.USER_REFRESH_ACCOUNT_TYPE?(i=new Cc.UserRefreshClient(n),i.fromJSON(e)):e.type===zt.IMPERSONATED_ACCOUNT_TYPE?i=this.fromImpersonatedJSON(e):e.type===Cn.EXTERNAL_ACCOUNT_TYPE?(i=ay.ExternalAccountClient.fromJSON({...e,...n}),i.scopes=this.getAnyScopes()):e.type===Sc.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?i=new Sc.ExternalAccountAuthorizedUserClient({...e,...n}):(n.scopes=this.scopes,i=new Yt.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(s=>i(null,s),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 s=[];e.setEncoding("utf8").on("error",o).on("data",l=>s.push(l)).on("end",()=>{try{try{let l=JSON.parse(s.join("")),u=this._cacheClientFromJSON(l,n);return i(u)}catch(l){if(!this.keyFilename)throw l;let u=new Yt.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=u,this.setGapicJWTValues(u),i(u)}}catch(l){return o(l)}})})}fromAPIKey(e,n={}){return new Yt.JWT({...n,apiKey:e})}_isWindows(){let e=ny.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,ey.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!==Cn.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await vn.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 zt.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Cn.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([vn.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:i}}throw new Error(We.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{return await this.#e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Cs.resolve(this.keyFilename),n=An.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 ry.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=ty.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,sy.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 zt.Impersonated)return(await i.sign(e)).signedBlob;let s=(0,iy.createCrypto)();if(i instanceof Yt.JWT&&i.key)return await s.sign(i.key,e);let l=await this.getCredentials();if(!l.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,l.client_email,e,n)}async signBlob(e,n,i,o){let s=new URL(o+`${n}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(i)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};We.GoogleAuth=Is});var Pc=B(xi=>{"use strict";D();Object.defineProperty(xi,"__esModule",{value:!0});xi.IAMAuth=void 0;var ws=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=ws});var Rc=B(it=>{"use strict";D();Object.defineProperty(it,"__esModule",{value:!0});it.DownscopedClient=it.EXPIRATION_TIME_OFFSET=it.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var ly=me(),uy=Q("stream"),Ps=Re(),cy=fi(),dy="urn:ietf:params:oauth:grant-type:token-exchange",fy="urn:ietf:params:oauth:token-type:access_token",py="urn:ietf:params:oauth:token-type:access_token";it.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;it.EXPIRATION_TIME_OFFSET=5*60*1e3;var Rs=class extends Ps.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Ps.AuthClient?{}:e),e instanceof Ps.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>it.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${it.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 cy.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=ly.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),i=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let l=s.status,u=s.config.data instanceof uy.Readable;if(!n&&(l===401||l===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:dy,requestedTokenType:fy,subjectToken:e,subjectTokenType:py},i=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=i.expires_in?new Date().getTime()+i.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:i.access_token,expiry_date:s,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}};it.DownscopedClient=Rs});var Nc=B(ki=>{"use strict";D();Object.defineProperty(ki,"__esModule",{value:!0});ki.PassThroughClient=void 0;var hy=Re(),Ns=class extends hy.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};ki.PassThroughClient=Ns});var Uc=B(V=>{"use strict";D();var my=V&&V.__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]}),gy=V&&V.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&my(e,t,n)};Object.defineProperty(V,"__esModule",{value:!0});V.GoogleAuth=V.auth=V.PassThroughClient=V.ExternalAccountAuthorizedUserClient=V.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=V.ExecutableError=V.PluggableAuthClient=V.DownscopedClient=V.BaseExternalAccountClient=V.ExternalAccountClient=V.IdentityPoolClient=V.AwsRequestSigner=V.AwsClient=V.UserRefreshClient=V.LoginTicket=V.ClientAuthentication=V.OAuth2Client=V.CodeChallengeMethod=V.Impersonated=V.JWT=V.JWTAccess=V.IdTokenClient=V.IAMAuth=V.GCPEnv=V.Compute=V.DEFAULT_UNIVERSE=V.AuthClient=V.gaxios=V.gcpMetadata=void 0;var Dc=wc();Object.defineProperty(V,"GoogleAuth",{enumerable:!0,get:function(){return Dc.GoogleAuth}});V.gcpMetadata=dn();V.gaxios=me();var Mc=Re();Object.defineProperty(V,"AuthClient",{enumerable:!0,get:function(){return Mc.AuthClient}});Object.defineProperty(V,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return Mc.DEFAULT_UNIVERSE}});var yy=cr();Object.defineProperty(V,"Compute",{enumerable:!0,get:function(){return yy.Compute}});var Ey=pr();Object.defineProperty(V,"GCPEnv",{enumerable:!0,get:function(){return Ey.GCPEnv}});var _y=Pc();Object.defineProperty(V,"IAMAuth",{enumerable:!0,get:function(){return _y.IAMAuth}});var Ty=fr();Object.defineProperty(V,"IdTokenClient",{enumerable:!0,get:function(){return Ty.IdTokenClient}});var Ay=Lr();Object.defineProperty(V,"JWTAccess",{enumerable:!0,get:function(){return Ay.JWTAccess}});var vy=Fr();Object.defineProperty(V,"JWT",{enumerable:!0,get:function(){return vy.JWT}});var Cy=Hr();Object.defineProperty(V,"Impersonated",{enumerable:!0,get:function(){return Cy.Impersonated}});var Ds=Pt();Object.defineProperty(V,"CodeChallengeMethod",{enumerable:!0,get:function(){return Ds.CodeChallengeMethod}});Object.defineProperty(V,"OAuth2Client",{enumerable:!0,get:function(){return Ds.OAuth2Client}});Object.defineProperty(V,"ClientAuthentication",{enumerable:!0,get:function(){return Ds.ClientAuthentication}});var Sy=sr();Object.defineProperty(V,"LoginTicket",{enumerable:!0,get:function(){return Sy.LoginTicket}});var Iy=qr();Object.defineProperty(V,"UserRefreshClient",{enumerable:!0,get:function(){return Iy.UserRefreshClient}});var wy=as();Object.defineProperty(V,"AwsClient",{enumerable:!0,get:function(){return wy.AwsClient}});var Py=os();Object.defineProperty(V,"AwsRequestSigner",{enumerable:!0,get:function(){return Py.AwsRequestSigner}});var Ry=ns();Object.defineProperty(V,"IdentityPoolClient",{enumerable:!0,get:function(){return Ry.IdentityPoolClient}});var Ny=_s();Object.defineProperty(V,"ExternalAccountClient",{enumerable:!0,get:function(){return Ny.ExternalAccountClient}});var Dy=mt();Object.defineProperty(V,"BaseExternalAccountClient",{enumerable:!0,get:function(){return Dy.BaseExternalAccountClient}});var My=Rc();Object.defineProperty(V,"DownscopedClient",{enumerable:!0,get:function(){return My.DownscopedClient}});var xc=ys();Object.defineProperty(V,"PluggableAuthClient",{enumerable:!0,get:function(){return xc.PluggableAuthClient}});Object.defineProperty(V,"ExecutableError",{enumerable:!0,get:function(){return xc.ExecutableError}});var kc=vs();Object.defineProperty(V,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return kc.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(V,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return kc.ExternalAccountAuthorizedUserClient}});var xy=Nc();Object.defineProperty(V,"PassThroughClient",{enumerable:!0,get:function(){return xy.PassThroughClient}});gy(Ur(),V);var ky=new Dc.GoogleAuth;V.auth=ky});D();var Eo=Ja(ja(),1),Af=Ja(Uc(),1);import{createWriteStream as Uy}from"fs";import*as _o from"fs/promises";import{writeFile as Gy}from"fs/promises";import{Readable as Ly}from"node:stream";import{finished as by}from"node:stream/promises";import*as vf from"path";var Fy,Oy;function qy(){return{geminiUrl:Fy,vertexUrl:Oy}}function By(t,e,n,i){var o,s;if(!t?.baseUrl){let l=qy();return e?(o=l.vertexUrl)!==null&&o!==void 0?o:n:(s=l.geminiUrl)!==null&&s!==void 0?s:i}return t.baseUrl}var Ye=class{};function H(t,e){let n=/\{([^}]+)\}/g;return t.replace(n,(i,o)=>{if(Object.prototype.hasOwnProperty.call(e,o)){let s=e[o];return s!=null?String(s):""}else throw new Error(`Key '${o}' not found in valueMap.`)})}function a(t,e,n){for(let s=0;s<e.length-1;s++){let l=e[s];if(l.endsWith("[]")){let u=l.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 ${l}`);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];a(f,e.slice(s+1),n[d])}else for(let d of c)a(d,e.slice(s+1),n)}return}else if(l.endsWith("[0]")){let u=l.slice(0,-3);u in t||(t[u]=[{}]);let c=t[u];a(c[0],e.slice(s+1),n);return}(!t[l]||typeof t[l]!="object")&&(t[l]={}),t=t[l]}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 r(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 s=o.slice(0,-2);if(s in t){let l=t[s];return Array.isArray(l)?l.map(u=>r(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 Hy(t,e){for(let[n,i]of Object.entries(e)){let o=n.split("."),s=i.split("."),l=new Set,u=-1;for(let c=0;c<o.length;c++)if(o[c]==="*"){u=c;break}if(u!==-1&&s.length>u)for(let c=u;c<s.length;c++){let d=s[c];d!=="*"&&!d.endsWith("[]")&&!d.endsWith("[0]")&&l.add(d)}Gs(t,o,s,0,l)}}function Gs(t,e,n,i,o){if(i>=e.length||typeof t!="object"||t===null)return;let s=e[i];if(s.endsWith("[]")){let l=s.slice(0,-2),u=t;if(l in u&&Array.isArray(u[l]))for(let c of u[l])Gs(c,e,n,i+1,o)}else if(s==="*"){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let l=t,u=Object.keys(l).filter(d=>!d.startsWith("_")&&!o.has(d)),c={};for(let d of u)c[d]=l[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);a(l,p,f)}for(let d of u)delete l[d]}}else{let l=t;s in l&&Gs(l[s],e,n,i+1,o)}}function La(t){if(typeof t!="string")throw new Error("fromImageBytes must be a string");return t}function Vy(t){let e={},n=r(t,["operationName"]);n!=null&&a(e,["operationName"],n);let i=r(t,["resourceName"]);return i!=null&&a(e,["_url","resourceName"],i),e}function $y(t){let e={},n=r(t,["name"]);n!=null&&a(e,["name"],n);let i=r(t,["metadata"]);i!=null&&a(e,["metadata"],i);let o=r(t,["done"]);o!=null&&a(e,["done"],o);let s=r(t,["error"]);s!=null&&a(e,["error"],s);let l=r(t,["response","generateVideoResponse"]);return l!=null&&a(e,["response"],Ky(l)),e}function Jy(t){let e={},n=r(t,["name"]);n!=null&&a(e,["name"],n);let i=r(t,["metadata"]);i!=null&&a(e,["metadata"],i);let o=r(t,["done"]);o!=null&&a(e,["done"],o);let s=r(t,["error"]);s!=null&&a(e,["error"],s);let l=r(t,["response"]);return l!=null&&a(e,["response"],Wy(l)),e}function Ky(t){let e={},n=r(t,["generatedSamples"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(l=>Yy(l))),a(e,["generatedVideos"],s)}let i=r(t,["raiMediaFilteredCount"]);i!=null&&a(e,["raiMediaFilteredCount"],i);let o=r(t,["raiMediaFilteredReasons"]);return o!=null&&a(e,["raiMediaFilteredReasons"],o),e}function Wy(t){let e={},n=r(t,["videos"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(l=>zy(l))),a(e,["generatedVideos"],s)}let i=r(t,["raiMediaFilteredCount"]);i!=null&&a(e,["raiMediaFilteredCount"],i);let o=r(t,["raiMediaFilteredReasons"]);return o!=null&&a(e,["raiMediaFilteredReasons"],o),e}function Yy(t){let e={},n=r(t,["video"]);return n!=null&&a(e,["video"],tE(n)),e}function zy(t){let e={},n=r(t,["_self"]);return n!=null&&a(e,["video"],nE(n)),e}function Xy(t){let e={},n=r(t,["operationName"]);return n!=null&&a(e,["_url","operationName"],n),e}function Qy(t){let e={},n=r(t,["operationName"]);return n!=null&&a(e,["_url","operationName"],n),e}function Zy(t){let e={},n=r(t,["name"]);n!=null&&a(e,["name"],n);let i=r(t,["metadata"]);i!=null&&a(e,["metadata"],i);let o=r(t,["done"]);o!=null&&a(e,["done"],o);let s=r(t,["error"]);s!=null&&a(e,["error"],s);let l=r(t,["response"]);return l!=null&&a(e,["response"],jy(l)),e}function jy(t){let e={},n=r(t,["sdkHttpResponse"]);n!=null&&a(e,["sdkHttpResponse"],n);let i=r(t,["parent"]);i!=null&&a(e,["parent"],i);let o=r(t,["documentName"]);return o!=null&&a(e,["documentName"],o),e}function ba(t){let e={},n=r(t,["name"]);n!=null&&a(e,["name"],n);let i=r(t,["metadata"]);i!=null&&a(e,["metadata"],i);let o=r(t,["done"]);o!=null&&a(e,["done"],o);let s=r(t,["error"]);s!=null&&a(e,["error"],s);let l=r(t,["response"]);return l!=null&&a(e,["response"],eE(l)),e}function eE(t){let e={},n=r(t,["sdkHttpResponse"]);n!=null&&a(e,["sdkHttpResponse"],n);let i=r(t,["parent"]);i!=null&&a(e,["parent"],i);let o=r(t,["documentName"]);return o!=null&&a(e,["documentName"],o),e}function tE(t){let e={},n=r(t,["uri"]);n!=null&&a(e,["uri"],n);let i=r(t,["encodedVideo"]);i!=null&&a(e,["videoBytes"],La(i));let o=r(t,["encoding"]);return o!=null&&a(e,["mimeType"],o),e}function nE(t){let e={},n=r(t,["gcsUri"]);n!=null&&a(e,["uri"],n);let i=r(t,["bytesBase64Encoded"]);i!=null&&a(e,["videoBytes"],La(i));let o=r(t,["mimeType"]);return o!=null&&a(e,["mimeType"],o),e}var Gc;(function(t){t.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",t.OUTCOME_OK="OUTCOME_OK",t.OUTCOME_FAILED="OUTCOME_FAILED",t.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(Gc||(Gc={}));var Lc;(function(t){t.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",t.PYTHON="PYTHON"})(Lc||(Lc={}));var bc;(function(t){t.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",t.SILENT="SILENT",t.WHEN_IDLE="WHEN_IDLE",t.INTERRUPT="INTERRUPT"})(bc||(bc={}));var gt;(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"})(gt||(gt={}));var Fc;(function(t){t.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",t.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",t.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",t.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(Fc||(Fc={}));var Oc;(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"})(Oc||(Oc={}));var qc;(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"})(qc||(qc={}));var Bc;(function(t){t.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",t.SIMPLE_SEARCH="SIMPLE_SEARCH",t.ELASTIC_SEARCH="ELASTIC_SEARCH"})(Bc||(Bc={}));var Hc;(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"})(Hc||(Hc={}));var Vc;(function(t){t.UNSPECIFIED="UNSPECIFIED",t.BLOCKING="BLOCKING",t.NON_BLOCKING="NON_BLOCKING"})(Vc||(Vc={}));var $c;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})($c||($c={}));var Jc;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE",t.VALIDATED="VALIDATED"})(Jc||(Jc={}));var Kc;(function(t){t.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Kc||(Kc={}));var Wc;(function(t){t.DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL"})(Wc||(Wc={}));var Yc;(function(t){t.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",t.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",t.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(Yc||(Yc={}));var zc;(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_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",t.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK"})(zc||(zc={}));var Xc;(function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"})(Xc||(Xc={}));var Qc;(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"})(Qc||(Qc={}));var Zc;(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.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",t.NO_IMAGE="NO_IMAGE",t.IMAGE_RECITATION="IMAGE_RECITATION",t.IMAGE_OTHER="IMAGE_OTHER"})(Zc||(Zc={}));var jc;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(jc||(jc={}));var ed;(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"})(ed||(ed={}));var td;(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"})(td||(td={}));var nd;(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"})(nd||(nd={}));var id;(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"})(id||(id={}));var Oi;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.AUDIO="AUDIO",t.VIDEO="VIDEO"})(Oi||(Oi={}));var od;(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"})(od||(od={}));var rd;(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"})(rd||(rd={}));var sd;(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"})(sd||(sd={}));var ad;(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"})(ad||(ad={}));var Ls;(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"})(Ls||(Ls={}));var ld;(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"})(ld||(ld={}));var ud;(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"})(ud||(ud={}));var cd;(function(t){t.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",t.BASELINE="BASELINE",t.CANDIDATE="CANDIDATE",t.TIE="TIE"})(cd||(cd={}));var dd;(function(t){t.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",t.REGULAR="REGULAR",t.FAST="FAST"})(dd||(dd={}));var fd;(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"})(fd||(fd={}));var pd;(function(t){t.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",t.LANDSCAPE="LANDSCAPE",t.PORTRAIT="PORTRAIT"})(pd||(pd={}));var hd;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.STATE_PENDING="STATE_PENDING",t.STATE_ACTIVE="STATE_ACTIVE",t.STATE_FAILED="STATE_FAILED"})(hd||(hd={}));var md;(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"})(md||(md={}));var gd;(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"})(gd||(gd={}));var bs;(function(t){t.COLLECTION="COLLECTION"})(bs||(bs={}));var yd;(function(t){t.UNSPECIFIED="unspecified",t.FLEX="flex",t.STANDARD="standard",t.PRIORITY="priority"})(yd||(yd={}));var Ed;(function(t){t.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",t.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",t.BALANCED="BALANCED",t.PRIORITIZE_COST="PRIORITIZE_COST"})(Ed||(Ed={}));var qi;(function(t){t.PREDICT="PREDICT",t.EMBED_CONTENT="EMBED_CONTENT"})(qi||(qi={}));var _d;(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"})(_d||(_d={}));var Td;(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"})(Td||(Td={}));var Ad;(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"})(Ad||(Ad={}));var vd;(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"})(vd||(vd={}));var Cd;(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"})(Cd||(Cd={}));var Sd;(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"})(Sd||(Sd={}));var Id;(function(t){t.FOREGROUND="FOREGROUND",t.BACKGROUND="BACKGROUND",t.PROMPT="PROMPT",t.SEMANTIC="SEMANTIC",t.INTERACTIVE="INTERACTIVE"})(Id||(Id={}));var wd;(function(t){t.ASSET="ASSET",t.STYLE="STYLE"})(wd||(wd={}));var Pd;(function(t){t.INSERT="INSERT",t.REMOVE="REMOVE",t.REMOVE_STATIC="REMOVE_STATIC",t.OUTPAINT="OUTPAINT"})(Pd||(Pd={}));var Rd;(function(t){t.OPTIMIZED="OPTIMIZED",t.LOSSLESS="LOSSLESS"})(Rd||(Rd={}));var Nd;(function(t){t.CROP="CROP",t.PAD="PAD"})(Nd||(Nd={}));var Dd;(function(t){t.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",t.PREFERENCE_TUNING="PREFERENCE_TUNING",t.DISTILLATION="DISTILLATION"})(Dd||(Dd={}));var Md;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.PROCESSING="PROCESSING",t.ACTIVE="ACTIVE",t.FAILED="FAILED"})(Md||(Md={}));var xd;(function(t){t.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",t.UPLOADED="UPLOADED",t.GENERATED="GENERATED",t.REGISTERED="REGISTERED"})(xd||(xd={}));var kd;(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"})(kd||(kd={}));var Ud;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.VIDEO="VIDEO",t.AUDIO="AUDIO",t.DOCUMENT="DOCUMENT"})(Ud||(Ud={}));var Gd;(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"})(Gd||(Gd={}));var Ld;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.ACTIVITY_START="ACTIVITY_START",t.ACTIVITY_END="ACTIVITY_END"})(Ld||(Ld={}));var bd;(function(t){t.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",t.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",t.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(bd||(bd={}));var Fd;(function(t){t.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",t.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",t.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(Fd||(Fd={}));var Od;(function(t){t.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",t.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",t.NO_INTERRUPTION="NO_INTERRUPTION"})(Od||(Od={}));var qd;(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"})(qd||(qd={}));var Bd;(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"})(Bd||(Bd={}));var Hd;(function(t){t.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",t.QUALITY="QUALITY",t.DIVERSITY="DIVERSITY",t.VOCALIZATION="VOCALIZATION"})(Hd||(Hd={}));var Xt;(function(t){t.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",t.PLAY="PLAY",t.PAUSE="PAUSE",t.STOP="STOP",t.RESET_CONTEXT="RESET_CONTEXT"})(Xt||(Xt={}));function Vd(t){return{text:t}}function $d(t){return typeof t=="object"&&t!==null?"fileData"in t||"text"in t||"functionCall"in t||"functionResponse"in t||"inlineData"in t||"videoMetadata"in t||"codeExecutionResult"in t||"executableCode"in t:!1}function Cf(t){let e=[];if(typeof t=="string")e.push(Vd(t));else if($d(t))e.push(t);else if(Array.isArray(t)){if(t.length===0)throw new Error("partOrString cannot be an empty array");for(let n of t)if(typeof n=="string")e.push(Vd(n));else if($d(n))e.push(n);else throw new Error("element in PartUnion must be a Part object or string")}else throw new Error("partOrString must be a Part object, string, or array");return e}function DP(t){return{role:"user",parts:Cf(t)}}function MP(t){return{role:"model",parts:Cf(t)}}var _t=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 Dt=class{get text(){var e,n,i,o,s,l,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=(l=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||l===void 0?void 0:l.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(let[m,E]of Object.entries(h))m!=="text"&&m!=="thought"&&m!=="thoughtSignature"&&(E!==null||E!==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,s,l,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=(l=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||l===void 0?void 0:l.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,s,l,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=(l=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||l===void 0?void 0:l.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,s,l,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=(l=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||l===void 0?void 0:l.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,s,l,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=(l=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||l===void 0?void 0:l.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}},Bi=class{},Hi=class{},Fs=class{},Os=class{},qs=class{},Bs=class{},Vi=class{},$i=class{},Ji=class{},Hs=class{};var Ki=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let i=new t,o,s=e;return n?o=Jy(s):o=$y(s),Object.assign(i,o),i}};var Vs=class{},Wi=class{},Yi=class{},zi=class{},$s=class{},Js=class{},Ks=class{};var Ws=class t{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){let i=new t,s=Zy(e);return Object.assign(i,s),i}},Ys=class{},zs=class{},Xs=class{},Qs=class{};var Xi=class{};var Zs=class{get text(){var e,n,i;let o="",s=!1,l=[];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&&l.push(c);if(typeof u.text=="string"){if(typeof u.thought=="boolean"&&u.thought)continue;s=!0,o+=u.text}}return l.length>0&&console.warn(`there are non-text parts ${l} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),s?o:void 0}get data(){var e,n,i;let o="",s=[];for(let l 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(l))u!=="inlineData"&&c!==null&&s.push(u);l.inlineData&&typeof l.inlineData.data=="string"&&(o+=atob(l.inlineData.data))}return s.length>0&&console.warn(`there are non-data parts ${s} 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 js=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,s=ba(e);return Object.assign(i,s),i}};function ee(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 Sf(t,e){let n=ee(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 If(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 wf(t){let e=Zi(t);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function Pf(t){let e=Zi(t);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function Jd(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 Rf(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("PartListUnion is required");return Array.isArray(t)?t.map(e=>Jd(e)):[Jd(t)]}function ea(t){return t!=null&&typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)}function Kd(t){return t!=null&&typeof t=="object"&&"functionCall"in t}function Wd(t){return t!=null&&typeof t=="object"&&"functionResponse"in t}function he(t){if(t==null)throw new Error("ContentUnion is required");return ea(t)?t:{role:"user",parts:Rf(t)}}function Fa(t,e){if(!e)return[];if(t.isVertexAI()&&Array.isArray(e))return e.flatMap(n=>{let i=he(n);return i.parts&&i.parts.length>0&&i.parts[0].text!==void 0?[i.parts[0].text]:[]});if(t.isVertexAI()){let n=he(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=>he(n)):[he(e)]}function ve(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("contents are required");if(!Array.isArray(t)){if(Kd(t)||Wd(t))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[he(t)]}let e=[],n=[],i=ea(t[0]);for(let o of t){let s=ea(o);if(s!=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(s)e.push(o);else{if(Kd(o)||Wd(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:Rf(n)}),e}function iE(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(i=>i!=="null");if(n.length===1)e.type=Object.values(gt).includes(n[0].toUpperCase())?n[0].toUpperCase():gt.TYPE_UNSPECIFIED;else{e.anyOf=[];for(let i of n)e.anyOf.push({type:Object.values(gt).includes(i.toUpperCase())?i.toUpperCase():gt.TYPE_UNSPECIFIED})}}function Qt(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 s=t.anyOf;s!=null&&s.length==2&&(s[0].type==="null"?(e.nullable=!0,t=s[1]):s[1].type==="null"&&(e.nullable=!0,t=s[0])),t.type instanceof Array&&iE(t.type,e);for(let[l,u]of Object.entries(t))if(u!=null)if(l=="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(gt).includes(u.toUpperCase())?u.toUpperCase():gt.TYPE_UNSPECIFIED}else if(n.includes(l))e[l]=Qt(u);else if(i.includes(l)){let c=[];for(let d of u){if(d.type=="null"){e.nullable=!0;continue}c.push(Qt(d))}e[l]=c}else if(o.includes(l)){let c={};for(let[d,f]of Object.entries(u))c[d]=Qt(f);e[l]=c}else{if(l==="additionalProperties")continue;e[l]=u}return e}function Oa(t){return Qt(t)}function qa(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 Ba(t){if("multiSpeakerVoiceConfig"in t)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return t}function nn(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=Qt(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Qt(e.response));return t}function on(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 oE(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 dt(t,e){if(typeof e!="string")throw new Error("name must be a string");return oE(t,e,"cachedContents")}function Nf(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 Tt(t){return La(t)}function rE(t){return t!=null&&typeof t=="object"&&"name"in t}function Df(t){return t!=null&&typeof t=="object"&&"video"in t}function Mf(t){return t!=null&&typeof t=="object"&&"uri"in t}function Ha(t){var e;let n;if(rE(t)&&(n=t.name),!(Mf(t)&&(n=t.uri,n===void 0))&&!(Df(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 xf(t,e){let n;return t.isVertexAI()?n=e?"publishers/google/models":"models":n=e?"models":"tunedModels",n}function kf(t){for(let e of["models","tunedModels","publisherModels"])if(sE(t,e))return t[e];return[]}function sE(t,e){return t!==null&&typeof t=="object"&&e in t}function aE(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 lE(t,e={}){let n=[],i=new Set;for(let o of t){let s=o.name;if(i.has(s))throw new Error(`Duplicate function name ${s} found in MCP tools. Please ensure function names are unique.`);i.add(s);let l=aE(o,e);l.functionDeclarations&&n.push(...l.functionDeclarations)}return{functionDeclarations:n}}function Uf(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 uE(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 Gf(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 s=!1;for(let l of o){if(typeof l!="object"||l===null)continue;let c=l.response;if(typeof c!="object"||c===null)continue;if(c.embedding!==void 0){s=!0;break}}return s&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),t}function rn(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 Lf(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 cE(t){return t.includes("gemini")&&t!=="gemini-embedding-001"||t.includes("maas")}function dE(t){let e={},n=r(t,["apiKey"]);if(n!=null&&a(e,["apiKey"],n),r(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(r(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(r(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(r(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(r(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(r(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 fE(t){let e={},n=r(t,["responsesFile"]);n!=null&&a(e,["fileName"],n);let i=r(t,["inlinedResponses","inlinedResponses"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(l=>KE(l))),a(e,["inlinedResponses"],s)}let o=r(t,["inlinedEmbedContentResponses","inlinedResponses"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>l)),a(e,["inlinedEmbedContentResponses"],s)}return e}function pE(t){let e={},n=r(t,["predictionsFormat"]);n!=null&&a(e,["format"],n);let i=r(t,["gcsDestination","outputUriPrefix"]);i!=null&&a(e,["gcsUri"],i);let o=r(t,["bigqueryDestination","outputUri"]);o!=null&&a(e,["bigqueryUri"],o);let s=r(t,["vertexMultimodalDatasetDestination"]);return s!=null&&a(e,["vertexDataset"],i_(s)),e}function hE(t){let e={},n=r(t,["format"]);n!=null&&a(e,["predictionsFormat"],n);let i=r(t,["gcsUri"]);i!=null&&a(e,["gcsDestination","outputUriPrefix"],i);let o=r(t,["bigqueryUri"]);if(o!=null&&a(e,["bigqueryDestination","outputUri"],o),r(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(r(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(r(t,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let s=r(t,["vertexDataset"]);return s!=null&&a(e,["vertexMultimodalDatasetDestination"],o_(s)),e}function bi(t){let e={},n=r(t,["name"]);n!=null&&a(e,["name"],n);let i=r(t,["metadata","displayName"]);i!=null&&a(e,["displayName"],i);let o=r(t,["metadata","state"]);o!=null&&a(e,["state"],Lf(o));let s=r(t,["metadata","createTime"]);s!=null&&a(e,["createTime"],s);let l=r(t,["metadata","endTime"]);l!=null&&a(e,["endTime"],l);let u=r(t,["metadata","updateTime"]);u!=null&&a(e,["updateTime"],u);let c=r(t,["metadata","model"]);c!=null&&a(e,["model"],c);let d=r(t,["metadata","output"]);return d!=null&&a(e,["dest"],fE(Gf(d))),e}function ta(t){let e={},n=r(t,["name"]);n!=null&&a(e,["name"],n);let i=r(t,["displayName"]);i!=null&&a(e,["displayName"],i);let o=r(t,["state"]);o!=null&&a(e,["state"],Lf(o));let s=r(t,["error"]);s!=null&&a(e,["error"],s);let l=r(t,["createTime"]);l!=null&&a(e,["createTime"],l);let u=r(t,["startTime"]);u!=null&&a(e,["startTime"],u);let c=r(t,["endTime"]);c!=null&&a(e,["endTime"],c);let d=r(t,["updateTime"]);d!=null&&a(e,["updateTime"],d);let f=r(t,["model"]);f!=null&&a(e,["model"],f);let p=r(t,["inputConfig"]);p!=null&&a(e,["src"],mE(p));let h=r(t,["outputConfig"]);h!=null&&a(e,["dest"],pE(Gf(h)));let m=r(t,["completionStats"]);m!=null&&a(e,["completionStats"],m);let E=r(t,["outputInfo"]);return E!=null&&a(e,["outputInfo"],E),e}function mE(t){let e={},n=r(t,["instancesFormat"]);n!=null&&a(e,["format"],n);let i=r(t,["gcsSource","uris"]);i!=null&&a(e,["gcsUri"],i);let o=r(t,["bigquerySource","inputUri"]);o!=null&&a(e,["bigqueryUri"],o);let s=r(t,["vertexMultimodalDatasetSource","datasetName"]);return s!=null&&a(e,["vertexDatasetName"],s),e}function gE(t,e){let n={};if(r(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(r(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(r(e,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let i=r(e,["fileName"]);i!=null&&a(n,["fileName"],i);let o=r(e,["inlinedRequests"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>JE(t,l))),a(n,["requests","requests"],s)}if(r(e,["vertexDatasetName"])!==void 0)throw new Error("vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function yE(t){let e={},n=r(t,["format"]);n!=null&&a(e,["instancesFormat"],n);let i=r(t,["gcsUri"]);i!=null&&a(e,["gcsSource","uris"],i);let o=r(t,["bigqueryUri"]);if(o!=null&&a(e,["bigquerySource","inputUri"],o),r(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(r(t,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let s=r(t,["vertexDatasetName"]);return s!=null&&a(e,["vertexMultimodalDatasetSource","datasetName"],s),e}function EE(t){let e={},n=r(t,["data"]);if(n!=null&&a(e,["data"],n),r(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=r(t,["mimeType"]);return i!=null&&a(e,["mimeType"],i),e}function _E(t,e){let n={},i=r(e,["name"]);return i!=null&&a(n,["_url","name"],rn(t,i)),n}function TE(t,e){let n={},i=r(e,["name"]);return i!=null&&a(n,["_url","name"],rn(t,i)),n}function AE(t){let e={},n=r(t,["content"]);n!=null&&a(e,["content"],n);let i=r(t,["citationMetadata"]);i!=null&&a(e,["citationMetadata"],vE(i));let o=r(t,["tokenCount"]);o!=null&&a(e,["tokenCount"],o);let s=r(t,["finishReason"]);s!=null&&a(e,["finishReason"],s);let l=r(t,["groundingMetadata"]);l!=null&&a(e,["groundingMetadata"],l);let u=r(t,["avgLogprobs"]);u!=null&&a(e,["avgLogprobs"],u);let c=r(t,["index"]);c!=null&&a(e,["index"],c);let d=r(t,["logprobsResult"]);d!=null&&a(e,["logprobsResult"],d);let f=r(t,["safetyRatings"]);if(f!=null){let h=f;Array.isArray(h)&&(h=h.map(m=>m)),a(e,["safetyRatings"],h)}let p=r(t,["urlContextMetadata"]);return p!=null&&a(e,["urlContextMetadata"],p),e}function vE(t){let e={},n=r(t,["citationSources"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>o)),a(e,["citations"],i)}return e}function bf(t){let e={},n=r(t,["parts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(s=>jE(s))),a(e,["parts"],o)}let i=r(t,["role"]);return i!=null&&a(e,["role"],i),e}function CE(t,e){let n={},i=r(t,["displayName"]);if(e!==void 0&&i!=null&&a(e,["batch","displayName"],i),r(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=r(t,["webhookConfig"]);return e!==void 0&&o!=null&&a(e,["batch","webhookConfig"],o),n}function SE(t,e){let n={},i=r(t,["displayName"]);e!==void 0&&i!=null&&a(e,["displayName"],i);let o=r(t,["dest"]);if(e!==void 0&&o!=null&&a(e,["outputConfig"],hE(uE(o))),r(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 Yd(t,e){let n={},i=r(e,["model"]);i!=null&&a(n,["_url","model"],ee(t,i));let o=r(e,["src"]);o!=null&&a(n,["batch","inputConfig"],gE(t,Uf(t,o)));let s=r(e,["config"]);return s!=null&&CE(s,n),n}function IE(t,e){let n={},i=r(e,["model"]);i!=null&&a(n,["model"],ee(t,i));let o=r(e,["src"]);o!=null&&a(n,["inputConfig"],yE(Uf(t,o)));let s=r(e,["config"]);return s!=null&&SE(s,n),n}function wE(t,e){let n={},i=r(t,["displayName"]);return e!==void 0&&i!=null&&a(e,["batch","displayName"],i),n}function PE(t,e){let n={},i=r(e,["model"]);i!=null&&a(n,["_url","model"],ee(t,i));let o=r(e,["src"]);o!=null&&a(n,["batch","inputConfig"],UE(t,o));let s=r(e,["config"]);return s!=null&&wE(s,n),n}function RE(t,e){let n={},i=r(e,["name"]);return i!=null&&a(n,["_url","name"],rn(t,i)),n}function NE(t,e){let n={},i=r(e,["name"]);return i!=null&&a(n,["_url","name"],rn(t,i)),n}function DE(t){let e={},n=r(t,["sdkHttpResponse"]);n!=null&&a(e,["sdkHttpResponse"],n);let i=r(t,["name"]);i!=null&&a(e,["name"],i);let o=r(t,["done"]);o!=null&&a(e,["done"],o);let s=r(t,["error"]);return s!=null&&a(e,["error"],s),e}function ME(t){let e={},n=r(t,["sdkHttpResponse"]);n!=null&&a(e,["sdkHttpResponse"],n);let i=r(t,["name"]);i!=null&&a(e,["name"],i);let o=r(t,["done"]);o!=null&&a(e,["done"],o);let s=r(t,["error"]);return s!=null&&a(e,["error"],s),e}function xE(t,e){let n={},i=r(e,["contents"]);if(i!=null){let s=Fa(t,i);Array.isArray(s)&&(s=s.map(l=>l)),a(n,["requests[]","request","content"],s)}let o=r(e,["config"]);return o!=null&&(a(n,["_self"],kE(o,n)),Hy(n,{"requests[].*":"requests[].request.*"})),n}function kE(t,e){let n={},i=r(t,["taskType"]);e!==void 0&&i!=null&&a(e,["requests[]","taskType"],i);let o=r(t,["title"]);e!==void 0&&o!=null&&a(e,["requests[]","title"],o);let s=r(t,["outputDimensionality"]);if(e!==void 0&&s!=null&&a(e,["requests[]","outputDimensionality"],s),r(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(r(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(r(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(r(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 UE(t,e){let n={},i=r(e,["fileName"]);i!=null&&a(n,["file_name"],i);let o=r(e,["inlinedRequests"]);return o!=null&&a(n,["requests"],xE(t,o)),n}function GE(t){let e={};if(r(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=r(t,["fileUri"]);n!=null&&a(e,["fileUri"],n);let i=r(t,["mimeType"]);return i!=null&&a(e,["mimeType"],i),e}function LE(t){let e={},n=r(t,["id"]);n!=null&&a(e,["id"],n);let i=r(t,["args"]);i!=null&&a(e,["args"],i);let o=r(t,["name"]);if(o!=null&&a(e,["name"],o),r(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(r(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 bE(t){let e={},n=r(t,["allowedFunctionNames"]);n!=null&&a(e,["allowedFunctionNames"],n);let i=r(t,["mode"]);if(i!=null&&a(e,["mode"],i),r(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 FE(t,e,n){let i={},o=r(e,["systemInstruction"]);n!==void 0&&o!=null&&a(n,["systemInstruction"],bf(he(o)));let s=r(e,["temperature"]);s!=null&&a(i,["temperature"],s);let l=r(e,["topP"]);l!=null&&a(i,["topP"],l);let u=r(e,["topK"]);u!=null&&a(i,["topK"],u);let c=r(e,["candidateCount"]);c!=null&&a(i,["candidateCount"],c);let d=r(e,["maxOutputTokens"]);d!=null&&a(i,["maxOutputTokens"],d);let f=r(e,["stopSequences"]);f!=null&&a(i,["stopSequences"],f);let p=r(e,["responseLogprobs"]);p!=null&&a(i,["responseLogprobs"],p);let h=r(e,["logprobs"]);h!=null&&a(i,["logprobs"],h);let m=r(e,["presencePenalty"]);m!=null&&a(i,["presencePenalty"],m);let E=r(e,["frequencyPenalty"]);E!=null&&a(i,["frequencyPenalty"],E);let A=r(e,["seed"]);A!=null&&a(i,["seed"],A);let T=r(e,["responseMimeType"]);T!=null&&a(i,["responseMimeType"],T);let S=r(e,["responseSchema"]);S!=null&&a(i,["responseSchema"],Oa(S));let b=r(e,["responseJsonSchema"]);if(b!=null&&a(i,["responseJsonSchema"],b),r(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(r(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 U=r(e,["safetySettings"]);if(n!==void 0&&U!=null){let te=U;Array.isArray(te)&&(te=te.map(re=>e_(re))),a(n,["safetySettings"],te)}let F=r(e,["tools"]);if(n!==void 0&&F!=null){let te=on(F);Array.isArray(te)&&(te=te.map(re=>n_(nn(re)))),a(n,["tools"],te)}let L=r(e,["toolConfig"]);if(n!==void 0&&L!=null&&a(n,["toolConfig"],t_(L)),r(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 P=r(e,["cachedContent"]);n!==void 0&&P!=null&&a(n,["cachedContent"],dt(t,P));let q=r(e,["responseModalities"]);q!=null&&a(i,["responseModalities"],q);let J=r(e,["mediaResolution"]);J!=null&&a(i,["mediaResolution"],J);let R=r(e,["speechConfig"]);if(R!=null&&a(i,["speechConfig"],qa(R)),r(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 $=r(e,["thinkingConfig"]);$!=null&&a(i,["thinkingConfig"],$);let X=r(e,["imageConfig"]);X!=null&&a(i,["imageConfig"],$E(X));let Z=r(e,["enableEnhancedCivicAnswers"]);if(Z!=null&&a(i,["enableEnhancedCivicAnswers"],Z),r(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let se=r(e,["serviceTier"]);return n!==void 0&&se!=null&&a(n,["serviceTier"],se),i}function OE(t){let e={},n=r(t,["sdkHttpResponse"]);n!=null&&a(e,["sdkHttpResponse"],n);let i=r(t,["candidates"]);if(i!=null){let d=i;Array.isArray(d)&&(d=d.map(f=>AE(f))),a(e,["candidates"],d)}let o=r(t,["modelVersion"]);o!=null&&a(e,["modelVersion"],o);let s=r(t,["promptFeedback"]);s!=null&&a(e,["promptFeedback"],s);let l=r(t,["responseId"]);l!=null&&a(e,["responseId"],l);let u=r(t,["usageMetadata"]);u!=null&&a(e,["usageMetadata"],u);let c=r(t,["modelStatus"]);return c!=null&&a(e,["modelStatus"],c),e}function qE(t,e){let n={},i=r(e,["name"]);return i!=null&&a(n,["_url","name"],rn(t,i)),n}function BE(t,e){let n={},i=r(e,["name"]);return i!=null&&a(n,["_url","name"],rn(t,i)),n}function HE(t){let e={},n=r(t,["authConfig"]);n!=null&&a(e,["authConfig"],dE(n));let i=r(t,["enableWidget"]);return i!=null&&a(e,["enableWidget"],i),e}function VE(t){let e={},n=r(t,["searchTypes"]);if(n!=null&&a(e,["searchTypes"],n),r(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(r(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=r(t,["timeRangeFilter"]);return i!=null&&a(e,["timeRangeFilter"],i),e}function $E(t){let e={},n=r(t,["aspectRatio"]);n!=null&&a(e,["aspectRatio"],n);let i=r(t,["imageSize"]);if(i!=null&&a(e,["imageSize"],i),r(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(r(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(r(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(r(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(r(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function JE(t,e){let n={},i=r(e,["model"]);i!=null&&a(n,["request","model"],ee(t,i));let o=r(e,["contents"]);if(o!=null){let u=ve(o);Array.isArray(u)&&(u=u.map(c=>bf(c))),a(n,["request","contents"],u)}let s=r(e,["metadata"]);s!=null&&a(n,["metadata"],s);let l=r(e,["config"]);return l!=null&&a(n,["request","generationConfig"],FE(t,l,r(n,["request"],{}))),n}function KE(t){let e={},n=r(t,["response"]);n!=null&&a(e,["response"],OE(n));let i=r(t,["metadata"]);i!=null&&a(e,["metadata"],i);let o=r(t,["error"]);return o!=null&&a(e,["error"],o),e}function WE(t,e){let n={},i=r(t,["pageSize"]);e!==void 0&&i!=null&&a(e,["_query","pageSize"],i);let o=r(t,["pageToken"]);if(e!==void 0&&o!=null&&a(e,["_query","pageToken"],o),r(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 YE(t,e){let n={},i=r(t,["pageSize"]);e!==void 0&&i!=null&&a(e,["_query","pageSize"],i);let o=r(t,["pageToken"]);e!==void 0&&o!=null&&a(e,["_query","pageToken"],o);let s=r(t,["filter"]);return e!==void 0&&s!=null&&a(e,["_query","filter"],s),n}function zE(t){let e={},n=r(t,["config"]);return n!=null&&WE(n,e),e}function XE(t){let e={},n=r(t,["config"]);return n!=null&&YE(n,e),e}function QE(t){let e={},n=r(t,["sdkHttpResponse"]);n!=null&&a(e,["sdkHttpResponse"],n);let i=r(t,["nextPageToken"]);i!=null&&a(e,["nextPageToken"],i);let o=r(t,["operations"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>bi(l))),a(e,["batchJobs"],s)}return e}function ZE(t){let e={},n=r(t,["sdkHttpResponse"]);n!=null&&a(e,["sdkHttpResponse"],n);let i=r(t,["nextPageToken"]);i!=null&&a(e,["nextPageToken"],i);let o=r(t,["batchPredictionJobs"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>ta(l))),a(e,["batchJobs"],s)}return e}function jE(t){let e={},n=r(t,["mediaResolution"]);n!=null&&a(e,["mediaResolution"],n);let i=r(t,["codeExecutionResult"]);i!=null&&a(e,["codeExecutionResult"],i);let o=r(t,["executableCode"]);o!=null&&a(e,["executableCode"],o);let s=r(t,["fileData"]);s!=null&&a(e,["fileData"],GE(s));let l=r(t,["functionCall"]);l!=null&&a(e,["functionCall"],LE(l));let u=r(t,["functionResponse"]);u!=null&&a(e,["functionResponse"],u);let c=r(t,["inlineData"]);c!=null&&a(e,["inlineData"],EE(c));let d=r(t,["text"]);d!=null&&a(e,["text"],d);let f=r(t,["thought"]);f!=null&&a(e,["thought"],f);let p=r(t,["thoughtSignature"]);p!=null&&a(e,["thoughtSignature"],p);let h=r(t,["videoMetadata"]);h!=null&&a(e,["videoMetadata"],h);let m=r(t,["toolCall"]);m!=null&&a(e,["toolCall"],m);let E=r(t,["toolResponse"]);E!=null&&a(e,["toolResponse"],E);let A=r(t,["partMetadata"]);return A!=null&&a(e,["partMetadata"],A),e}function e_(t){let e={},n=r(t,["category"]);if(n!=null&&a(e,["category"],n),r(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=r(t,["threshold"]);return i!=null&&a(e,["threshold"],i),e}function t_(t){let e={},n=r(t,["retrievalConfig"]);n!=null&&a(e,["retrievalConfig"],n);let i=r(t,["functionCallingConfig"]);i!=null&&a(e,["functionCallingConfig"],bE(i));let o=r(t,["includeServerSideToolInvocations"]);return o!=null&&a(e,["includeServerSideToolInvocations"],o),e}function n_(t){let e={};if(r(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=r(t,["computerUse"]);n!=null&&a(e,["computerUse"],n);let i=r(t,["fileSearch"]);i!=null&&a(e,["fileSearch"],i);let o=r(t,["googleSearch"]);o!=null&&a(e,["googleSearch"],VE(o));let s=r(t,["googleMaps"]);s!=null&&a(e,["googleMaps"],HE(s));let l=r(t,["codeExecution"]);if(l!=null&&a(e,["codeExecution"],l),r(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let u=r(t,["functionDeclarations"]);if(u!=null){let p=u;Array.isArray(p)&&(p=p.map(h=>h)),a(e,["functionDeclarations"],p)}let c=r(t,["googleSearchRetrieval"]);if(c!=null&&a(e,["googleSearchRetrieval"],c),r(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=r(t,["urlContext"]);d!=null&&a(e,["urlContext"],d);let f=r(t,["mcpServers"]);if(f!=null){let p=f;Array.isArray(p)&&(p=p.map(h=>h)),a(e,["mcpServers"],p)}return e}function i_(t){let e={},n=r(t,["bigqueryDestination","outputUri"]);n!=null&&a(e,["bigqueryDestination"],n);let i=r(t,["displayName"]);return i!=null&&a(e,["displayName"],i),e}function o_(t){let e={},n=r(t,["bigqueryDestination"]);n!=null&&a(e,["bigqueryDestination","outputUri"],n);let i=r(t,["displayName"]);return i!=null&&a(e,["displayName"],i),e}var ut;(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"})(ut||(ut={}));var ct=class{constructor(e,n,i,o){this.pageInternal=[],this.paramsInternal={},this.requestInternal=n,this.init(e,i,o)}init(e,n,i){var o,s;this.nameInternal=e,this.pageInternal=n[this.nameInternal]||[],this.sdkHttpResponseInternal=n?.sdkHttpResponse,this.idxInternal=0;let l={config:{}};!i||Object.keys(i).length===0?l={config:{}}:typeof i=="object"?l=Object.assign({},i):l=i,l.config&&(l.config.pageToken=n.nextPageToken),this.paramsInternal=l,this.pageInternalSize=(s=(o=l.config)===null||o===void 0?void 0:o.pageSize)!==null&&s!==void 0?s: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 na=class extends Ye{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new ct(ut.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=Yd(this.apiClient,e),i=n._url,o=H("{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 s=this.getGcsUri(e),l=this.getBigqueryUri(e);if(s)s.endsWith(".jsonl")?i.dest=`${s.slice(0,-6)}/dest`:i.dest=`${s}_dest_${o}`;else if(l)i.dest=`${l}_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,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=IE(this.apiClient,e);return u=H("batchPredictionJobs",d._url),c=d._query,delete d._url,delete d._query,l=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()),l.then(f=>ta(f))}else{let d=Yd(this.apiClient,e);return u=H("{model}:batchGenerateContent",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),l.then(f=>bi(f))}}async createEmbeddingsInternal(e){var n,i;let o,s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=PE(this.apiClient,e);return s=H("{model}:asyncBatchEmbedContent",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=>bi(c))}}async get(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=BE(this.apiClient,e);return u=H("batchPredictionJobs/{name}",d._url),c=d._query,delete d._url,delete d._query,l=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()),l.then(f=>ta(f))}else{let d=qE(this.apiClient,e);return u=H("batches/{name}",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),l.then(f=>bi(f))}}async cancel(e){var n,i,o,s;let l="",u={};if(this.apiClient.isVertexAI()){let c=TE(this.apiClient,e);l=H("batchPredictionJobs/{name}:cancel",c._url),u=c._query,delete c._url,delete c._query,await this.apiClient.request({path:l,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=_E(this.apiClient,e);l=H("batches/{name}:cancel",c._url),u=c._query,delete c._url,delete c._query,await this.apiClient.request({path:l,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(o=e.config)===null||o===void 0?void 0:o.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal})}}async listInternal(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=XE(e);return u=H("batchPredictionJobs",d._url),c=d._query,delete d._url,delete d._query,l=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})),l.then(f=>{let p=ZE(f),h=new Xi;return Object.assign(h,p),h})}else{let d=zE(e);return u=H("batches",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),l.then(f=>{let p=QE(f),h=new Xi;return Object.assign(h,p),h})}}async delete(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=NE(this.apiClient,e);return u=H("batchPredictionJobs/{name}",d._url),c=d._query,delete d._url,delete d._query,l=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})),l.then(f=>ME(f))}else{let d=RE(this.apiClient,e);return u=H("batches/{name}",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),l.then(f=>DE(f))}}};function r_(t){let e={},n=r(t,["apiKey"]);if(n!=null&&a(e,["apiKey"],n),r(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(r(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(r(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(r(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(r(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(r(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 s_(t){let e={},n=r(t,["data"]);if(n!=null&&a(e,["data"],n),r(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=r(t,["mimeType"]);return i!=null&&a(e,["mimeType"],i),e}function a_(t){let e={},n=r(t,["outcome"]);n!=null&&a(e,["outcome"],n);let i=r(t,["output"]);if(i!=null&&a(e,["output"],i),r(t,["id"])!==void 0)throw new Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function l_(t){let e={},n=r(t,["environment"]);n!=null&&a(e,["environment"],n);let i=r(t,["excludedPredefinedFunctions"]);if(i!=null&&a(e,["excludedPredefinedFunctions"],i),r(t,["enablePromptInjectionDetection"])!==void 0)throw new Error("enablePromptInjectionDetection parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function zd(t){let e={},n=r(t,["parts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(s=>M_(s))),a(e,["parts"],o)}let i=r(t,["role"]);return i!=null&&a(e,["role"],i),e}function Xd(t){let e={},n=r(t,["parts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(s=>x_(s))),a(e,["parts"],o)}let i=r(t,["role"]);return i!=null&&a(e,["role"],i),e}function u_(t,e){let n={},i=r(t,["ttl"]);e!==void 0&&i!=null&&a(e,["ttl"],i);let o=r(t,["expireTime"]);e!==void 0&&o!=null&&a(e,["expireTime"],o);let s=r(t,["displayName"]);e!==void 0&&s!=null&&a(e,["displayName"],s);let l=r(t,["contents"]);if(e!==void 0&&l!=null){let f=ve(l);Array.isArray(f)&&(f=f.map(p=>zd(p))),a(e,["contents"],f)}let u=r(t,["systemInstruction"]);e!==void 0&&u!=null&&a(e,["systemInstruction"],zd(he(u)));let c=r(t,["tools"]);if(e!==void 0&&c!=null){let f=c;Array.isArray(f)&&(f=f.map(p=>G_(p))),a(e,["tools"],f)}let d=r(t,["toolConfig"]);if(e!==void 0&&d!=null&&a(e,["toolConfig"],k_(d)),r(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 c_(t,e){let n={},i=r(t,["ttl"]);e!==void 0&&i!=null&&a(e,["ttl"],i);let o=r(t,["expireTime"]);e!==void 0&&o!=null&&a(e,["expireTime"],o);let s=r(t,["displayName"]);e!==void 0&&s!=null&&a(e,["displayName"],s);let l=r(t,["contents"]);if(e!==void 0&&l!=null){let p=ve(l);Array.isArray(p)&&(p=p.map(h=>Xd(h))),a(e,["contents"],p)}let u=r(t,["systemInstruction"]);e!==void 0&&u!=null&&a(e,["systemInstruction"],Xd(he(u)));let c=r(t,["tools"]);if(e!==void 0&&c!=null){let p=c;Array.isArray(p)&&(p=p.map(h=>L_(h))),a(e,["tools"],p)}let d=r(t,["toolConfig"]);e!==void 0&&d!=null&&a(e,["toolConfig"],U_(d));let f=r(t,["kmsKeyName"]);return e!==void 0&&f!=null&&a(e,["encryption_spec","kmsKeyName"],f),n}function d_(t,e){let n={},i=r(e,["model"]);i!=null&&a(n,["model"],Sf(t,i));let o=r(e,["config"]);return o!=null&&u_(o,n),n}function f_(t,e){let n={},i=r(e,["model"]);i!=null&&a(n,["model"],Sf(t,i));let o=r(e,["config"]);return o!=null&&c_(o,n),n}function p_(t,e){let n={},i=r(e,["name"]);return i!=null&&a(n,["_url","name"],dt(t,i)),n}function h_(t,e){let n={},i=r(e,["name"]);return i!=null&&a(n,["_url","name"],dt(t,i)),n}function m_(t){let e={},n=r(t,["sdkHttpResponse"]);return n!=null&&a(e,["sdkHttpResponse"],n),e}function g_(t){let e={},n=r(t,["sdkHttpResponse"]);return n!=null&&a(e,["sdkHttpResponse"],n),e}function y_(t){let e={},n=r(t,["code"]);n!=null&&a(e,["code"],n);let i=r(t,["language"]);if(i!=null&&a(e,["language"],i),r(t,["id"])!==void 0)throw new Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function E_(t){let e={};if(r(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=r(t,["fileUri"]);n!=null&&a(e,["fileUri"],n);let i=r(t,["mimeType"]);return i!=null&&a(e,["mimeType"],i),e}function __(t){let e={},n=r(t,["id"]);n!=null&&a(e,["id"],n);let i=r(t,["args"]);i!=null&&a(e,["args"],i);let o=r(t,["name"]);if(o!=null&&a(e,["name"],o),r(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(r(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 T_(t){let e={},n=r(t,["allowedFunctionNames"]);n!=null&&a(e,["allowedFunctionNames"],n);let i=r(t,["mode"]);if(i!=null&&a(e,["mode"],i),r(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 A_(t,e){let n={},i=r(e,["name"]);return i!=null&&a(n,["_url","name"],dt(t,i)),n}function v_(t,e){let n={},i=r(e,["name"]);return i!=null&&a(n,["_url","name"],dt(t,i)),n}function C_(t){let e={},n=r(t,["authConfig"]);n!=null&&a(e,["authConfig"],r_(n));let i=r(t,["enableWidget"]);return i!=null&&a(e,["enableWidget"],i),e}function S_(t){let e={},n=r(t,["searchTypes"]);if(n!=null&&a(e,["searchTypes"],n),r(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(r(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=r(t,["timeRangeFilter"]);return i!=null&&a(e,["timeRangeFilter"],i),e}function I_(t,e){let n={},i=r(t,["pageSize"]);e!==void 0&&i!=null&&a(e,["_query","pageSize"],i);let o=r(t,["pageToken"]);return e!==void 0&&o!=null&&a(e,["_query","pageToken"],o),n}function w_(t,e){let n={},i=r(t,["pageSize"]);e!==void 0&&i!=null&&a(e,["_query","pageSize"],i);let o=r(t,["pageToken"]);return e!==void 0&&o!=null&&a(e,["_query","pageToken"],o),n}function P_(t){let e={},n=r(t,["config"]);return n!=null&&I_(n,e),e}function R_(t){let e={},n=r(t,["config"]);return n!=null&&w_(n,e),e}function N_(t){let e={},n=r(t,["sdkHttpResponse"]);n!=null&&a(e,["sdkHttpResponse"],n);let i=r(t,["nextPageToken"]);i!=null&&a(e,["nextPageToken"],i);let o=r(t,["cachedContents"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>l)),a(e,["cachedContents"],s)}return e}function D_(t){let e={},n=r(t,["sdkHttpResponse"]);n!=null&&a(e,["sdkHttpResponse"],n);let i=r(t,["nextPageToken"]);i!=null&&a(e,["nextPageToken"],i);let o=r(t,["cachedContents"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>l)),a(e,["cachedContents"],s)}return e}function M_(t){let e={},n=r(t,["mediaResolution"]);n!=null&&a(e,["mediaResolution"],n);let i=r(t,["codeExecutionResult"]);i!=null&&a(e,["codeExecutionResult"],i);let o=r(t,["executableCode"]);o!=null&&a(e,["executableCode"],o);let s=r(t,["fileData"]);s!=null&&a(e,["fileData"],E_(s));let l=r(t,["functionCall"]);l!=null&&a(e,["functionCall"],__(l));let u=r(t,["functionResponse"]);u!=null&&a(e,["functionResponse"],u);let c=r(t,["inlineData"]);c!=null&&a(e,["inlineData"],s_(c));let d=r(t,["text"]);d!=null&&a(e,["text"],d);let f=r(t,["thought"]);f!=null&&a(e,["thought"],f);let p=r(t,["thoughtSignature"]);p!=null&&a(e,["thoughtSignature"],p);let h=r(t,["videoMetadata"]);h!=null&&a(e,["videoMetadata"],h);let m=r(t,["toolCall"]);m!=null&&a(e,["toolCall"],m);let E=r(t,["toolResponse"]);E!=null&&a(e,["toolResponse"],E);let A=r(t,["partMetadata"]);return A!=null&&a(e,["partMetadata"],A),e}function x_(t){let e={},n=r(t,["mediaResolution"]);n!=null&&a(e,["mediaResolution"],n);let i=r(t,["codeExecutionResult"]);i!=null&&a(e,["codeExecutionResult"],a_(i));let o=r(t,["executableCode"]);o!=null&&a(e,["executableCode"],y_(o));let s=r(t,["fileData"]);s!=null&&a(e,["fileData"],s);let l=r(t,["functionCall"]);l!=null&&a(e,["functionCall"],l);let u=r(t,["functionResponse"]);u!=null&&a(e,["functionResponse"],u);let c=r(t,["inlineData"]);c!=null&&a(e,["inlineData"],c);let d=r(t,["text"]);d!=null&&a(e,["text"],d);let f=r(t,["thought"]);f!=null&&a(e,["thought"],f);let p=r(t,["thoughtSignature"]);p!=null&&a(e,["thoughtSignature"],p);let h=r(t,["videoMetadata"]);if(h!=null&&a(e,["videoMetadata"],h),r(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(r(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(r(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function k_(t){let e={},n=r(t,["retrievalConfig"]);n!=null&&a(e,["retrievalConfig"],n);let i=r(t,["functionCallingConfig"]);i!=null&&a(e,["functionCallingConfig"],T_(i));let o=r(t,["includeServerSideToolInvocations"]);return o!=null&&a(e,["includeServerSideToolInvocations"],o),e}function U_(t){let e={},n=r(t,["retrievalConfig"]);n!=null&&a(e,["retrievalConfig"],n);let i=r(t,["functionCallingConfig"]);if(i!=null&&a(e,["functionCallingConfig"],i),r(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 G_(t){let e={};if(r(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=r(t,["computerUse"]);n!=null&&a(e,["computerUse"],n);let i=r(t,["fileSearch"]);i!=null&&a(e,["fileSearch"],i);let o=r(t,["googleSearch"]);o!=null&&a(e,["googleSearch"],S_(o));let s=r(t,["googleMaps"]);s!=null&&a(e,["googleMaps"],C_(s));let l=r(t,["codeExecution"]);if(l!=null&&a(e,["codeExecution"],l),r(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let u=r(t,["functionDeclarations"]);if(u!=null){let p=u;Array.isArray(p)&&(p=p.map(h=>h)),a(e,["functionDeclarations"],p)}let c=r(t,["googleSearchRetrieval"]);if(c!=null&&a(e,["googleSearchRetrieval"],c),r(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=r(t,["urlContext"]);d!=null&&a(e,["urlContext"],d);let f=r(t,["mcpServers"]);if(f!=null){let p=f;Array.isArray(p)&&(p=p.map(h=>h)),a(e,["mcpServers"],p)}return e}function L_(t){let e={},n=r(t,["retrieval"]);n!=null&&a(e,["retrieval"],n);let i=r(t,["computerUse"]);if(i!=null&&a(e,["computerUse"],l_(i)),r(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let o=r(t,["googleSearch"]);o!=null&&a(e,["googleSearch"],o);let s=r(t,["googleMaps"]);s!=null&&a(e,["googleMaps"],s);let l=r(t,["codeExecution"]);l!=null&&a(e,["codeExecution"],l);let u=r(t,["enterpriseWebSearch"]);u!=null&&a(e,["enterpriseWebSearch"],u);let c=r(t,["functionDeclarations"]);if(c!=null){let h=c;Array.isArray(h)&&(h=h.map(m=>m)),a(e,["functionDeclarations"],h)}let d=r(t,["googleSearchRetrieval"]);d!=null&&a(e,["googleSearchRetrieval"],d);let f=r(t,["parallelAiSearch"]);f!=null&&a(e,["parallelAiSearch"],f);let p=r(t,["urlContext"]);if(p!=null&&a(e,["urlContext"],p),r(t,["mcpServers"])!==void 0)throw new Error("mcpServers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function b_(t,e){let n={},i=r(t,["ttl"]);e!==void 0&&i!=null&&a(e,["ttl"],i);let o=r(t,["expireTime"]);return e!==void 0&&o!=null&&a(e,["expireTime"],o),n}function F_(t,e){let n={},i=r(t,["ttl"]);e!==void 0&&i!=null&&a(e,["ttl"],i);let o=r(t,["expireTime"]);return e!==void 0&&o!=null&&a(e,["expireTime"],o),n}function O_(t,e){let n={},i=r(e,["name"]);i!=null&&a(n,["_url","name"],dt(t,i));let o=r(e,["config"]);return o!=null&&b_(o,n),n}function q_(t,e){let n={},i=r(e,["name"]);i!=null&&a(n,["_url","name"],dt(t,i));let o=r(e,["config"]);return o!=null&&F_(o,n),n}var ia=class extends Ye{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new ct(ut.PAGED_ITEM_CACHED_CONTENTS,i=>this.listInternal(i),await this.listInternal(n),n)}async create(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=f_(this.apiClient,e);return u=H("cachedContents",d._url),c=d._query,delete d._url,delete d._query,l=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()),l.then(f=>f)}else{let d=d_(this.apiClient,e);return u=H("cachedContents",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),l.then(f=>f)}}async get(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=v_(this.apiClient,e);return u=H("{name}",d._url),c=d._query,delete d._url,delete d._query,l=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()),l.then(f=>f)}else{let d=A_(this.apiClient,e);return u=H("{name}",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),l.then(f=>f)}}async delete(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=h_(this.apiClient,e);return u=H("{name}",d._url),c=d._query,delete d._url,delete d._query,l=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})),l.then(f=>{let p=g_(f),h=new Yi;return Object.assign(h,p),h})}else{let d=p_(this.apiClient,e);return u=H("{name}",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),l.then(f=>{let p=m_(f),h=new Yi;return Object.assign(h,p),h})}}async update(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=q_(this.apiClient,e);return u=H("{name}",d._url),c=d._query,delete d._url,delete d._query,l=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()),l.then(f=>f)}else{let d=O_(this.apiClient,e);return u=H("{name}",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),l.then(f=>f)}}async listInternal(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=R_(e);return u=H("cachedContents",d._url),c=d._query,delete d._url,delete d._query,l=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})),l.then(f=>{let p=D_(f),h=new zi;return Object.assign(h,p),h})}else{let d=P_(e);return u=H("cachedContents",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),l.then(f=>{let p=N_(f),h=new zi;return Object.assign(h,p),h})}}};function Fe(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 Qd(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 z(t){return this instanceof z?(this.v=t,this):new z(t)}function Oe(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),u("next"),u("throw"),u("return",l),o[Symbol.asyncIterator]=function(){return this},o;function l(m){return function(E){return Promise.resolve(E).then(m,p)}}function u(m,E){i[m]&&(o[m]=function(A){return new Promise(function(T,S){s.push([m,A,T,S])>1||c(m,A)})},E&&(o[m]=E(o[m])))}function c(m,E){try{d(i[m](E))}catch(A){h(s[0][3],A)}}function d(m){m.value instanceof z?Promise.resolve(m.value.v).then(f,p):h(s[0][2],m)}function f(m){c("next",m)}function p(m){c("throw",m)}function h(m,E){m(E),s.shift(),s.length&&c(s[0][0],s[0][1])}}function qe(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 Qd=="function"?Qd(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(s){n[s]=t[s]&&function(l){return new Promise(function(u,c){l=t[s](l),o(u,c,l.done,l.value)})}}function o(s,l,u,c){Promise.resolve(c).then(function(d){s({value:d,done:u})},l)}}function B_(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:Ff(n)}function Ff(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 H_(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 Zd(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=[],s=!0;for(;i<n&&t[i].role==="model";)o.push(t[i]),s&&!Ff(t[i])&&(s=!1),i++;s?e.push(...o):e.pop()}return e}var oa=class{constructor(e,n){this.modelsModule=e,this.apiClient=n}create(e){return new ra(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},ra=class{constructor(e,n,i,o={},s=[]){this.apiClient=e,this.modelsModule=n,this.model=i,this.config=o,this.history=s,this.sendPromise=Promise.resolve(),H_(s)}async sendMessage(e){var n;await this.sendPromise;let i=he(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 s,l,u;let c=await o,d=(l=(s=c.candidates)===null||s===void 0?void 0:s[0])===null||l===void 0?void 0:l.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=he(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 s=await o;return this.processStreamResponse(s,i)}getHistory(e=!1){let n=e?Zd(this.history):this.history;return structuredClone(n)}processStreamResponse(e,n){return Oe(this,arguments,function*(){var o,s,l,u,c,d;let f=[];try{for(var p=!0,h=qe(e),m;m=yield z(h.next()),o=m.done,!o;p=!0){u=m.value,p=!1;let E=u;if(B_(E)){let A=(d=(c=E.candidates)===null||c===void 0?void 0:c[0])===null||d===void 0?void 0:d.content;A!==void 0&&f.push(A)}yield yield z(E)}}catch(E){s={error:E}}finally{try{!p&&!o&&(l=h.return)&&(yield z(l.call(h)))}finally{if(s)throw s.error}}this.recordHistory(n,f)})}recordHistory(e,n,i){let o=[];n.length>0&&n.every(s=>s.role!==void 0)?o=n:o.push({role:"model",parts:[]}),i&&i.length>0?this.history.push(...Zd(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 V_(t){let e={},n=r(t,["file"]);return n!=null&&a(e,["file"],n),e}function $_(t){let e={},n=r(t,["sdkHttpResponse"]);return n!=null&&a(e,["sdkHttpResponse"],n),e}function J_(t){let e={},n=r(t,["name"]);return n!=null&&a(e,["_url","file"],Ha(n)),e}function K_(t){let e={},n=r(t,["sdkHttpResponse"]);return n!=null&&a(e,["sdkHttpResponse"],n),e}function W_(t){let e={},n=r(t,["name"]);return n!=null&&a(e,["_url","file"],Ha(n)),e}function Y_(t){let e={},n=r(t,["uris"]);return n!=null&&a(e,["uris"],n),e}function z_(t,e){let n={},i=r(t,["pageSize"]);e!==void 0&&i!=null&&a(e,["_query","pageSize"],i);let o=r(t,["pageToken"]);return e!==void 0&&o!=null&&a(e,["_query","pageToken"],o),n}function X_(t){let e={},n=r(t,["config"]);return n!=null&&z_(n,e),e}function Q_(t){let e={},n=r(t,["sdkHttpResponse"]);n!=null&&a(e,["sdkHttpResponse"],n);let i=r(t,["nextPageToken"]);i!=null&&a(e,["nextPageToken"],i);let o=r(t,["files"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>l)),a(e,["files"],s)}return e}function Z_(t){let e={},n=r(t,["sdkHttpResponse"]);n!=null&&a(e,["sdkHttpResponse"],n);let i=r(t,["files"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>s)),a(e,["files"],o)}return e}var sa=class extends Ye{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new ct(ut.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,s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=X_(e);return s=H("files",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=Q_(c),f=new Ys;return Object.assign(f,d),f})}}async createInternal(e){var n,i;let o,s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=V_(e);return s=H("upload/v1beta/files",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=$_(c),f=new zs;return Object.assign(f,d),f})}}async get(e){var n,i;let o,s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=W_(e);return s=H("files/{file}",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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,s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=J_(e);return s=H("files/{file}",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=K_(c),f=new Xs;return Object.assign(f,d),f})}}async registerFilesInternal(e){var n,i;let o,s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=Y_(e);return s=H("files:register",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=Z_(c),f=new Qs;return Object.assign(f,d),f})}}};function jd(t){let e={};if(r(t,["languageCodes"])!==void 0)throw new Error("languageCodes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function j_(t){let e={},n=r(t,["apiKey"]);if(n!=null&&a(e,["apiKey"],n),r(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(r(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(r(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(r(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(r(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(r(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 Fi(t){let e={},n=r(t,["data"]);if(n!=null&&a(e,["data"],n),r(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=r(t,["mimeType"]);return i!=null&&a(e,["mimeType"],i),e}function eT(t){let e={},n=r(t,["outcome"]);n!=null&&a(e,["outcome"],n);let i=r(t,["output"]);if(i!=null&&a(e,["output"],i),r(t,["id"])!==void 0)throw new Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function tT(t){let e={},n=r(t,["environment"]);n!=null&&a(e,["environment"],n);let i=r(t,["excludedPredefinedFunctions"]);if(i!=null&&a(e,["excludedPredefinedFunctions"],i),r(t,["enablePromptInjectionDetection"])!==void 0)throw new Error("enablePromptInjectionDetection parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function nT(t){let e={},n=r(t,["parts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(s=>_T(s))),a(e,["parts"],o)}let i=r(t,["role"]);return i!=null&&a(e,["role"],i),e}function iT(t){let e={},n=r(t,["parts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(s=>TT(s))),a(e,["parts"],o)}let i=r(t,["role"]);return i!=null&&a(e,["role"],i),e}function oT(t){let e={},n=r(t,["code"]);n!=null&&a(e,["code"],n);let i=r(t,["language"]);if(i!=null&&a(e,["language"],i),r(t,["id"])!==void 0)throw new Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function rT(t){let e={};if(r(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=r(t,["fileUri"]);n!=null&&a(e,["fileUri"],n);let i=r(t,["mimeType"]);return i!=null&&a(e,["mimeType"],i),e}function sT(t){let e={},n=r(t,["id"]);n!=null&&a(e,["id"],n);let i=r(t,["args"]);i!=null&&a(e,["args"],i);let o=r(t,["name"]);if(o!=null&&a(e,["name"],o),r(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(r(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 aT(t){let e={},n=r(t,["modelSelectionConfig"]);n!=null&&a(e,["modelConfig"],n);let i=r(t,["responseJsonSchema"]);i!=null&&a(e,["responseJsonSchema"],i);let o=r(t,["audioTimestamp"]);o!=null&&a(e,["audioTimestamp"],o);let s=r(t,["candidateCount"]);s!=null&&a(e,["candidateCount"],s);let l=r(t,["enableAffectiveDialog"]);l!=null&&a(e,["enableAffectiveDialog"],l);let u=r(t,["frequencyPenalty"]);u!=null&&a(e,["frequencyPenalty"],u);let c=r(t,["logprobs"]);c!=null&&a(e,["logprobs"],c);let d=r(t,["maxOutputTokens"]);d!=null&&a(e,["maxOutputTokens"],d);let f=r(t,["mediaResolution"]);f!=null&&a(e,["mediaResolution"],f);let p=r(t,["presencePenalty"]);p!=null&&a(e,["presencePenalty"],p);let h=r(t,["responseLogprobs"]);h!=null&&a(e,["responseLogprobs"],h);let m=r(t,["responseMimeType"]);m!=null&&a(e,["responseMimeType"],m);let E=r(t,["responseModalities"]);E!=null&&a(e,["responseModalities"],E);let A=r(t,["responseSchema"]);A!=null&&a(e,["responseSchema"],A);let T=r(t,["routingConfig"]);T!=null&&a(e,["routingConfig"],T);let S=r(t,["seed"]);S!=null&&a(e,["seed"],S);let b=r(t,["speechConfig"]);b!=null&&a(e,["speechConfig"],b);let U=r(t,["stopSequences"]);U!=null&&a(e,["stopSequences"],U);let F=r(t,["temperature"]);F!=null&&a(e,["temperature"],F);let L=r(t,["thinkingConfig"]);L!=null&&a(e,["thinkingConfig"],L);let P=r(t,["topK"]);P!=null&&a(e,["topK"],P);let q=r(t,["topP"]);if(q!=null&&a(e,["topP"],q),r(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function lT(t){let e={},n=r(t,["authConfig"]);n!=null&&a(e,["authConfig"],j_(n));let i=r(t,["enableWidget"]);return i!=null&&a(e,["enableWidget"],i),e}function uT(t){let e={},n=r(t,["searchTypes"]);if(n!=null&&a(e,["searchTypes"],n),r(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(r(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=r(t,["timeRangeFilter"]);return i!=null&&a(e,["timeRangeFilter"],i),e}function cT(t,e){let n={},i=r(t,["generationConfig"]);e!==void 0&&i!=null&&a(e,["setup","generationConfig"],i);let o=r(t,["responseModalities"]);e!==void 0&&o!=null&&a(e,["setup","generationConfig","responseModalities"],o);let s=r(t,["temperature"]);e!==void 0&&s!=null&&a(e,["setup","generationConfig","temperature"],s);let l=r(t,["topP"]);e!==void 0&&l!=null&&a(e,["setup","generationConfig","topP"],l);let u=r(t,["topK"]);e!==void 0&&u!=null&&a(e,["setup","generationConfig","topK"],u);let c=r(t,["maxOutputTokens"]);e!==void 0&&c!=null&&a(e,["setup","generationConfig","maxOutputTokens"],c);let d=r(t,["mediaResolution"]);e!==void 0&&d!=null&&a(e,["setup","generationConfig","mediaResolution"],d);let f=r(t,["seed"]);e!==void 0&&f!=null&&a(e,["setup","generationConfig","seed"],f);let p=r(t,["speechConfig"]);e!==void 0&&p!=null&&a(e,["setup","generationConfig","speechConfig"],Ba(p));let h=r(t,["thinkingConfig"]);e!==void 0&&h!=null&&a(e,["setup","generationConfig","thinkingConfig"],h);let m=r(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&a(e,["setup","generationConfig","enableAffectiveDialog"],m);let E=r(t,["systemInstruction"]);e!==void 0&&E!=null&&a(e,["setup","systemInstruction"],nT(he(E)));let A=r(t,["tools"]);if(e!==void 0&&A!=null){let R=on(A);Array.isArray(R)&&(R=R.map($=>CT(nn($)))),a(e,["setup","tools"],R)}let T=r(t,["sessionResumption"]);e!==void 0&&T!=null&&a(e,["setup","sessionResumption"],vT(T));let S=r(t,["inputAudioTranscription"]);e!==void 0&&S!=null&&a(e,["setup","inputAudioTranscription"],jd(S));let b=r(t,["outputAudioTranscription"]);e!==void 0&&b!=null&&a(e,["setup","outputAudioTranscription"],jd(b));let U=r(t,["realtimeInputConfig"]);e!==void 0&&U!=null&&a(e,["setup","realtimeInputConfig"],U);let F=r(t,["contextWindowCompression"]);e!==void 0&&F!=null&&a(e,["setup","contextWindowCompression"],F);let L=r(t,["proactivity"]);if(e!==void 0&&L!=null&&a(e,["setup","proactivity"],L),r(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 P=r(t,["avatarConfig"]);e!==void 0&&P!=null&&a(e,["setup","avatarConfig"],P);let q=r(t,["safetySettings"]);if(e!==void 0&&q!=null){let R=q;Array.isArray(R)&&(R=R.map($=>AT($))),a(e,["setup","safetySettings"],R)}let J=r(t,["streamTranslationConfig"]);return e!==void 0&&J!=null&&a(e,["setup","generationConfig","streamTranslationConfig"],J),n}function dT(t,e){let n={},i=r(t,["generationConfig"]);e!==void 0&&i!=null&&a(e,["setup","generationConfig"],aT(i));let o=r(t,["responseModalities"]);e!==void 0&&o!=null&&a(e,["setup","generationConfig","responseModalities"],o);let s=r(t,["temperature"]);e!==void 0&&s!=null&&a(e,["setup","generationConfig","temperature"],s);let l=r(t,["topP"]);e!==void 0&&l!=null&&a(e,["setup","generationConfig","topP"],l);let u=r(t,["topK"]);e!==void 0&&u!=null&&a(e,["setup","generationConfig","topK"],u);let c=r(t,["maxOutputTokens"]);e!==void 0&&c!=null&&a(e,["setup","generationConfig","maxOutputTokens"],c);let d=r(t,["mediaResolution"]);e!==void 0&&d!=null&&a(e,["setup","generationConfig","mediaResolution"],d);let f=r(t,["seed"]);e!==void 0&&f!=null&&a(e,["setup","generationConfig","seed"],f);let p=r(t,["speechConfig"]);e!==void 0&&p!=null&&a(e,["setup","generationConfig","speechConfig"],Ba(p));let h=r(t,["thinkingConfig"]);e!==void 0&&h!=null&&a(e,["setup","generationConfig","thinkingConfig"],h);let m=r(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&a(e,["setup","generationConfig","enableAffectiveDialog"],m);let E=r(t,["systemInstruction"]);e!==void 0&&E!=null&&a(e,["setup","systemInstruction"],iT(he(E)));let A=r(t,["tools"]);if(e!==void 0&&A!=null){let R=on(A);Array.isArray(R)&&(R=R.map($=>ST(nn($)))),a(e,["setup","tools"],R)}let T=r(t,["sessionResumption"]);e!==void 0&&T!=null&&a(e,["setup","sessionResumption"],T);let S=r(t,["inputAudioTranscription"]);e!==void 0&&S!=null&&a(e,["setup","inputAudioTranscription"],S);let b=r(t,["outputAudioTranscription"]);e!==void 0&&b!=null&&a(e,["setup","outputAudioTranscription"],b);let U=r(t,["realtimeInputConfig"]);e!==void 0&&U!=null&&a(e,["setup","realtimeInputConfig"],U);let F=r(t,["contextWindowCompression"]);e!==void 0&&F!=null&&a(e,["setup","contextWindowCompression"],F);let L=r(t,["proactivity"]);e!==void 0&&L!=null&&a(e,["setup","proactivity"],L);let P=r(t,["explicitVadSignal"]);e!==void 0&&P!=null&&a(e,["setup","explicitVadSignal"],P);let q=r(t,["avatarConfig"]);e!==void 0&&q!=null&&a(e,["setup","avatarConfig"],q);let J=r(t,["safetySettings"]);if(e!==void 0&&J!=null){let R=J;Array.isArray(R)&&(R=R.map($=>$)),a(e,["setup","safetySettings"],R)}if(r(t,["streamTranslationConfig"])!==void 0)throw new Error("streamTranslationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function fT(t,e){let n={},i=r(e,["model"]);i!=null&&a(n,["setup","model"],ee(t,i));let o=r(e,["config"]);return o!=null&&a(n,["config"],cT(o,n)),n}function pT(t,e){let n={},i=r(e,["model"]);i!=null&&a(n,["setup","model"],ee(t,i));let o=r(e,["config"]);return o!=null&&a(n,["config"],dT(o,n)),n}function hT(t){let e={},n=r(t,["musicGenerationConfig"]);return n!=null&&a(e,["musicGenerationConfig"],n),e}function mT(t){let e={},n=r(t,["weightedPrompts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(o=>o)),a(e,["weightedPrompts"],i)}return e}function gT(t){let e={},n=r(t,["media"]);if(n!=null){let d=If(n);Array.isArray(d)&&(d=d.map(f=>Fi(f))),a(e,["mediaChunks"],d)}let i=r(t,["audio"]);i!=null&&a(e,["audio"],Fi(Pf(i)));let o=r(t,["audioStreamEnd"]);o!=null&&a(e,["audioStreamEnd"],o);let s=r(t,["video"]);s!=null&&a(e,["video"],Fi(wf(s)));let l=r(t,["text"]);l!=null&&a(e,["text"],l);let u=r(t,["activityStart"]);u!=null&&a(e,["activityStart"],u);let c=r(t,["activityEnd"]);return c!=null&&a(e,["activityEnd"],c),e}function yT(t){let e={},n=r(t,["media"]);if(n!=null){let d=If(n);Array.isArray(d)&&(d=d.map(f=>f)),a(e,["mediaChunks"],d)}let i=r(t,["audio"]);i!=null&&a(e,["audio"],Pf(i));let o=r(t,["audioStreamEnd"]);o!=null&&a(e,["audioStreamEnd"],o);let s=r(t,["video"]);s!=null&&a(e,["video"],wf(s));let l=r(t,["text"]);l!=null&&a(e,["text"],l);let u=r(t,["activityStart"]);u!=null&&a(e,["activityStart"],u);let c=r(t,["activityEnd"]);return c!=null&&a(e,["activityEnd"],c),e}function ET(t){let e={},n=r(t,["setupComplete"]);n!=null&&a(e,["setupComplete"],n);let i=r(t,["serverContent"]);i!=null&&a(e,["serverContent"],i);let o=r(t,["toolCall"]);o!=null&&a(e,["toolCall"],o);let s=r(t,["toolCallCancellation"]);s!=null&&a(e,["toolCallCancellation"],s);let l=r(t,["usageMetadata"]);l!=null&&a(e,["usageMetadata"],IT(l));let u=r(t,["goAway"]);u!=null&&a(e,["goAway"],u);let c=r(t,["sessionResumptionUpdate"]);c!=null&&a(e,["sessionResumptionUpdate"],c);let d=r(t,["voiceActivityDetectionSignal"]);d!=null&&a(e,["voiceActivityDetectionSignal"],d);let f=r(t,["voiceActivity"]);return f!=null&&a(e,["voiceActivity"],wT(f)),e}function _T(t){let e={},n=r(t,["mediaResolution"]);n!=null&&a(e,["mediaResolution"],n);let i=r(t,["codeExecutionResult"]);i!=null&&a(e,["codeExecutionResult"],i);let o=r(t,["executableCode"]);o!=null&&a(e,["executableCode"],o);let s=r(t,["fileData"]);s!=null&&a(e,["fileData"],rT(s));let l=r(t,["functionCall"]);l!=null&&a(e,["functionCall"],sT(l));let u=r(t,["functionResponse"]);u!=null&&a(e,["functionResponse"],u);let c=r(t,["inlineData"]);c!=null&&a(e,["inlineData"],Fi(c));let d=r(t,["text"]);d!=null&&a(e,["text"],d);let f=r(t,["thought"]);f!=null&&a(e,["thought"],f);let p=r(t,["thoughtSignature"]);p!=null&&a(e,["thoughtSignature"],p);let h=r(t,["videoMetadata"]);h!=null&&a(e,["videoMetadata"],h);let m=r(t,["toolCall"]);m!=null&&a(e,["toolCall"],m);let E=r(t,["toolResponse"]);E!=null&&a(e,["toolResponse"],E);let A=r(t,["partMetadata"]);return A!=null&&a(e,["partMetadata"],A),e}function TT(t){let e={},n=r(t,["mediaResolution"]);n!=null&&a(e,["mediaResolution"],n);let i=r(t,["codeExecutionResult"]);i!=null&&a(e,["codeExecutionResult"],eT(i));let o=r(t,["executableCode"]);o!=null&&a(e,["executableCode"],oT(o));let s=r(t,["fileData"]);s!=null&&a(e,["fileData"],s);let l=r(t,["functionCall"]);l!=null&&a(e,["functionCall"],l);let u=r(t,["functionResponse"]);u!=null&&a(e,["functionResponse"],u);let c=r(t,["inlineData"]);c!=null&&a(e,["inlineData"],c);let d=r(t,["text"]);d!=null&&a(e,["text"],d);let f=r(t,["thought"]);f!=null&&a(e,["thought"],f);let p=r(t,["thoughtSignature"]);p!=null&&a(e,["thoughtSignature"],p);let h=r(t,["videoMetadata"]);if(h!=null&&a(e,["videoMetadata"],h),r(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(r(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(r(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function AT(t){let e={},n=r(t,["category"]);if(n!=null&&a(e,["category"],n),r(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=r(t,["threshold"]);return i!=null&&a(e,["threshold"],i),e}function vT(t){let e={},n=r(t,["handle"]);if(n!=null&&a(e,["handle"],n),r(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 CT(t){let e={};if(r(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=r(t,["computerUse"]);n!=null&&a(e,["computerUse"],n);let i=r(t,["fileSearch"]);i!=null&&a(e,["fileSearch"],i);let o=r(t,["googleSearch"]);o!=null&&a(e,["googleSearch"],uT(o));let s=r(t,["googleMaps"]);s!=null&&a(e,["googleMaps"],lT(s));let l=r(t,["codeExecution"]);if(l!=null&&a(e,["codeExecution"],l),r(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let u=r(t,["functionDeclarations"]);if(u!=null){let p=u;Array.isArray(p)&&(p=p.map(h=>h)),a(e,["functionDeclarations"],p)}let c=r(t,["googleSearchRetrieval"]);if(c!=null&&a(e,["googleSearchRetrieval"],c),r(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=r(t,["urlContext"]);d!=null&&a(e,["urlContext"],d);let f=r(t,["mcpServers"]);if(f!=null){let p=f;Array.isArray(p)&&(p=p.map(h=>h)),a(e,["mcpServers"],p)}return e}function ST(t){let e={},n=r(t,["retrieval"]);n!=null&&a(e,["retrieval"],n);let i=r(t,["computerUse"]);if(i!=null&&a(e,["computerUse"],tT(i)),r(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let o=r(t,["googleSearch"]);o!=null&&a(e,["googleSearch"],o);let s=r(t,["googleMaps"]);s!=null&&a(e,["googleMaps"],s);let l=r(t,["codeExecution"]);l!=null&&a(e,["codeExecution"],l);let u=r(t,["enterpriseWebSearch"]);u!=null&&a(e,["enterpriseWebSearch"],u);let c=r(t,["functionDeclarations"]);if(c!=null){let h=c;Array.isArray(h)&&(h=h.map(m=>m)),a(e,["functionDeclarations"],h)}let d=r(t,["googleSearchRetrieval"]);d!=null&&a(e,["googleSearchRetrieval"],d);let f=r(t,["parallelAiSearch"]);f!=null&&a(e,["parallelAiSearch"],f);let p=r(t,["urlContext"]);if(p!=null&&a(e,["urlContext"],p),r(t,["mcpServers"])!==void 0)throw new Error("mcpServers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function IT(t){let e={},n=r(t,["promptTokenCount"]);n!=null&&a(e,["promptTokenCount"],n);let i=r(t,["cachedContentTokenCount"]);i!=null&&a(e,["cachedContentTokenCount"],i);let o=r(t,["candidatesTokenCount"]);o!=null&&a(e,["responseTokenCount"],o);let s=r(t,["toolUsePromptTokenCount"]);s!=null&&a(e,["toolUsePromptTokenCount"],s);let l=r(t,["thoughtsTokenCount"]);l!=null&&a(e,["thoughtsTokenCount"],l);let u=r(t,["totalTokenCount"]);u!=null&&a(e,["totalTokenCount"],u);let c=r(t,["promptTokensDetails"]);if(c!=null){let m=c;Array.isArray(m)&&(m=m.map(E=>E)),a(e,["promptTokensDetails"],m)}let d=r(t,["cacheTokensDetails"]);if(d!=null){let m=d;Array.isArray(m)&&(m=m.map(E=>E)),a(e,["cacheTokensDetails"],m)}let f=r(t,["candidatesTokensDetails"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(E=>E)),a(e,["responseTokensDetails"],m)}let p=r(t,["toolUsePromptTokensDetails"]);if(p!=null){let m=p;Array.isArray(m)&&(m=m.map(E=>E)),a(e,["toolUsePromptTokensDetails"],m)}let h=r(t,["trafficType"]);return h!=null&&a(e,["trafficType"],h),e}function wT(t){let e={},n=r(t,["type"]);return n!=null&&a(e,["voiceActivityType"],n),e}function PT(t,e){let n={},i=r(t,["apiKey"]);if(i!=null&&a(n,["apiKey"],i),r(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(r(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(r(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(r(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(r(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(r(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 RT(t,e){let n={},i=r(t,["data"]);if(i!=null&&a(n,["data"],i),r(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=r(t,["mimeType"]);return o!=null&&a(n,["mimeType"],o),n}function NT(t,e){let n={},i=r(t,["content"]);i!=null&&a(n,["content"],i);let o=r(t,["citationMetadata"]);o!=null&&a(n,["citationMetadata"],DT(o));let s=r(t,["tokenCount"]);s!=null&&a(n,["tokenCount"],s);let l=r(t,["finishReason"]);l!=null&&a(n,["finishReason"],l);let u=r(t,["groundingMetadata"]);u!=null&&a(n,["groundingMetadata"],u);let c=r(t,["avgLogprobs"]);c!=null&&a(n,["avgLogprobs"],c);let d=r(t,["index"]);d!=null&&a(n,["index"],d);let f=r(t,["logprobsResult"]);f!=null&&a(n,["logprobsResult"],f);let p=r(t,["safetyRatings"]);if(p!=null){let m=p;Array.isArray(m)&&(m=m.map(E=>E)),a(n,["safetyRatings"],m)}let h=r(t,["urlContextMetadata"]);return h!=null&&a(n,["urlContextMetadata"],h),n}function DT(t,e){let n={},i=r(t,["citationSources"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>s)),a(n,["citations"],o)}return n}function MT(t,e){let n={},i=r(t,["outcome"]);i!=null&&a(n,["outcome"],i);let o=r(t,["output"]);if(o!=null&&a(n,["output"],o),r(t,["id"])!==void 0)throw new Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function xT(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["contents"]);if(s!=null){let l=ve(s);Array.isArray(l)&&(l=l.map(u=>sn(u))),a(i,["contents"],l)}return i}function kT(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["tokensInfo"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>l)),a(n,["tokensInfo"],s)}return n}function UT(t,e){let n={},i=r(t,["environment"]);i!=null&&a(n,["environment"],i);let o=r(t,["excludedPredefinedFunctions"]);if(o!=null&&a(n,["excludedPredefinedFunctions"],o),r(t,["enablePromptInjectionDetection"])!==void 0)throw new Error("enablePromptInjectionDetection parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function GT(t,e){let n={},i=r(t,["values"]);i!=null&&a(n,["values"],i);let o=r(t,["statistics"]);return o!=null&&a(n,["statistics"],LT(o)),n}function LT(t,e){let n={},i=r(t,["truncated"]);i!=null&&a(n,["truncated"],i);let o=r(t,["token_count"]);return o!=null&&a(n,["tokenCount"],o),n}function Dn(t,e){let n={},i=r(t,["parts"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(l=>JA(l))),a(n,["parts"],s)}let o=r(t,["role"]);return o!=null&&a(n,["role"],o),n}function sn(t,e){let n={},i=r(t,["parts"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(l=>KA(l))),a(n,["parts"],s)}let o=r(t,["role"]);return o!=null&&a(n,["role"],o),n}function bT(t,e){let n={},i=r(t,["controlType"]);i!=null&&a(n,["controlType"],i);let o=r(t,["enableControlImageComputation"]);return o!=null&&a(n,["computeControl"],o),n}function FT(t,e){let n={};if(r(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(r(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(r(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 OT(t,e,n){let i={},o=r(t,["systemInstruction"]);e!==void 0&&o!=null&&a(e,["systemInstruction"],sn(he(o)));let s=r(t,["tools"]);if(e!==void 0&&s!=null){let u=s;Array.isArray(u)&&(u=u.map(c=>Hf(c))),a(e,["tools"],u)}let l=r(t,["generationConfig"]);return e!==void 0&&l!=null&&a(e,["generationConfig"],DA(l)),i}function qT(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["contents"]);if(s!=null){let u=ve(s);Array.isArray(u)&&(u=u.map(c=>Dn(c))),a(i,["contents"],u)}let l=r(e,["config"]);return l!=null&&FT(l),i}function BT(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["contents"]);if(s!=null){let u=ve(s);Array.isArray(u)&&(u=u.map(c=>sn(c))),a(i,["contents"],u)}let l=r(e,["config"]);return l!=null&&OT(l,i),i}function HT(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["totalTokens"]);o!=null&&a(n,["totalTokens"],o);let s=r(t,["cachedContentTokenCount"]);return s!=null&&a(n,["cachedContentTokenCount"],s),n}function VT(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["totalTokens"]);return o!=null&&a(n,["totalTokens"],o),n}function $T(t,e,n){let i={},o=r(e,["model"]);return o!=null&&a(i,["_url","name"],ee(t,o)),i}function JT(t,e,n){let i={},o=r(e,["model"]);return o!=null&&a(i,["_url","name"],ee(t,o)),i}function KT(t,e){let n={},i=r(t,["sdkHttpResponse"]);return i!=null&&a(n,["sdkHttpResponse"],i),n}function WT(t,e){let n={},i=r(t,["sdkHttpResponse"]);return i!=null&&a(n,["sdkHttpResponse"],i),n}function YT(t,e,n){let i={},o=r(t,["outputGcsUri"]);e!==void 0&&o!=null&&a(e,["parameters","storageUri"],o);let s=r(t,["negativePrompt"]);e!==void 0&&s!=null&&a(e,["parameters","negativePrompt"],s);let l=r(t,["numberOfImages"]);e!==void 0&&l!=null&&a(e,["parameters","sampleCount"],l);let u=r(t,["aspectRatio"]);e!==void 0&&u!=null&&a(e,["parameters","aspectRatio"],u);let c=r(t,["guidanceScale"]);e!==void 0&&c!=null&&a(e,["parameters","guidanceScale"],c);let d=r(t,["seed"]);e!==void 0&&d!=null&&a(e,["parameters","seed"],d);let f=r(t,["safetyFilterLevel"]);e!==void 0&&f!=null&&a(e,["parameters","safetySetting"],f);let p=r(t,["personGeneration"]);e!==void 0&&p!=null&&a(e,["parameters","personGeneration"],p);let h=r(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&a(e,["parameters","includeSafetyAttributes"],h);let m=r(t,["includeRaiReason"]);e!==void 0&&m!=null&&a(e,["parameters","includeRaiReason"],m);let E=r(t,["language"]);e!==void 0&&E!=null&&a(e,["parameters","language"],E);let A=r(t,["outputMimeType"]);e!==void 0&&A!=null&&a(e,["parameters","outputOptions","mimeType"],A);let T=r(t,["outputCompressionQuality"]);e!==void 0&&T!=null&&a(e,["parameters","outputOptions","compressionQuality"],T);let S=r(t,["addWatermark"]);e!==void 0&&S!=null&&a(e,["parameters","addWatermark"],S);let b=r(t,["labels"]);e!==void 0&&b!=null&&a(e,["labels"],b);let U=r(t,["editMode"]);e!==void 0&&U!=null&&a(e,["parameters","editMode"],U);let F=r(t,["baseSteps"]);return e!==void 0&&F!=null&&a(e,["parameters","editConfig","baseSteps"],F),i}function zT(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["prompt"]);s!=null&&a(i,["instances[0]","prompt"],s);let l=r(e,["referenceImages"]);if(l!=null){let c=l;Array.isArray(c)&&(c=c.map(d=>ZA(d))),a(i,["instances[0]","referenceImages"],c)}let u=r(e,["config"]);return u!=null&&YT(u,i),i}function XT(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["predictions"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>To(l))),a(n,["generatedImages"],s)}return n}function QT(t,e,n){let i={},o=r(t,["taskType"]);e!==void 0&&o!=null&&a(e,["requests[]","taskType"],o);let s=r(t,["title"]);e!==void 0&&s!=null&&a(e,["requests[]","title"],s);let l=r(t,["outputDimensionality"]);if(e!==void 0&&l!=null&&a(e,["requests[]","outputDimensionality"],l),r(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(r(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(r(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(r(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 ZT(t,e,n){let i={},o=r(n,["embeddingApiType"]);if(o===void 0&&(o="PREDICT"),o==="PREDICT"){let p=r(t,["taskType"]);e!==void 0&&p!=null&&a(e,["instances[]","task_type"],p)}else if(o==="EMBED_CONTENT"){let p=r(t,["taskType"]);e!==void 0&&p!=null&&a(e,["embedContentConfig","taskType"],p)}let s=r(n,["embeddingApiType"]);if(s===void 0&&(s="PREDICT"),s==="PREDICT"){let p=r(t,["title"]);e!==void 0&&p!=null&&a(e,["instances[]","title"],p)}else if(s==="EMBED_CONTENT"){let p=r(t,["title"]);e!==void 0&&p!=null&&a(e,["embedContentConfig","title"],p)}let l=r(n,["embeddingApiType"]);if(l===void 0&&(l="PREDICT"),l==="PREDICT"){let p=r(t,["outputDimensionality"]);e!==void 0&&p!=null&&a(e,["parameters","outputDimensionality"],p)}else if(l==="EMBED_CONTENT"){let p=r(t,["outputDimensionality"]);e!==void 0&&p!=null&&a(e,["embedContentConfig","outputDimensionality"],p)}let u=r(n,["embeddingApiType"]);if(u===void 0&&(u="PREDICT"),u==="PREDICT"){let p=r(t,["mimeType"]);e!==void 0&&p!=null&&a(e,["instances[]","mimeType"],p)}let c=r(n,["embeddingApiType"]);if(c===void 0&&(c="PREDICT"),c==="PREDICT"){let p=r(t,["autoTruncate"]);e!==void 0&&p!=null&&a(e,["parameters","autoTruncate"],p)}else if(c==="EMBED_CONTENT"){let p=r(t,["autoTruncate"]);e!==void 0&&p!=null&&a(e,["embedContentConfig","autoTruncate"],p)}let d=r(n,["embeddingApiType"]);if(d===void 0&&(d="PREDICT"),d==="EMBED_CONTENT"){let p=r(t,["documentOcr"]);e!==void 0&&p!=null&&a(e,["embedContentConfig","documentOcr"],p)}let f=r(n,["embeddingApiType"]);if(f===void 0&&(f="PREDICT"),f==="EMBED_CONTENT"){let p=r(t,["audioTrackExtraction"]);e!==void 0&&p!=null&&a(e,["embedContentConfig","audioTrackExtraction"],p)}return i}function jT(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["contents"]);if(s!=null){let d=Fa(t,s);Array.isArray(d)&&(d=d.map(f=>f)),a(i,["requests[]","content"],d)}let l=r(e,["content"]);l!=null&&Dn(he(l));let u=r(e,["config"]);u!=null&&QT(u,i);let c=r(e,["model"]);return c!==void 0&&a(i,["requests[]","model"],ee(t,c)),i}function eA(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(n,["embeddingApiType"]);if(s===void 0&&(s="PREDICT"),s==="PREDICT"){let c=r(e,["contents"]);if(c!=null){let d=Fa(t,c);Array.isArray(d)&&(d=d.map(f=>f)),a(i,["instances[]","content"],d)}}let l=r(n,["embeddingApiType"]);if(l===void 0&&(l="PREDICT"),l==="EMBED_CONTENT"){let c=r(e,["content"]);c!=null&&a(i,["content"],sn(he(c)))}let u=r(e,["config"]);return u!=null&&ZT(u,i,n),i}function tA(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["embeddings"]);if(o!=null){let l=o;Array.isArray(l)&&(l=l.map(u=>u)),a(n,["embeddings"],l)}let s=r(t,["metadata"]);return s!=null&&a(n,["metadata"],s),n}function nA(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["predictions[]","embeddings"]);if(o!=null){let l=o;Array.isArray(l)&&(l=l.map(u=>GT(u))),a(n,["embeddings"],l)}let s=r(t,["metadata"]);if(s!=null&&a(n,["metadata"],s),e&&r(e,["embeddingApiType"])==="EMBED_CONTENT"){let l=r(t,["embedding"]),u=r(t,["usageMetadata"]),c=r(t,["truncated"]);if(l){let d={};u&&u.promptTokenCount&&(d.tokenCount=u.promptTokenCount),c&&(d.truncated=c),l.statistics=d,a(n,["embeddings"],[l])}}return n}function iA(t,e){let n={},i=r(t,["endpoint"]);i!=null&&a(n,["name"],i);let o=r(t,["deployedModelId"]);return o!=null&&a(n,["deployedModelId"],o),n}function oA(t,e){let n={},i=r(t,["code"]);i!=null&&a(n,["code"],i);let o=r(t,["language"]);if(o!=null&&a(n,["language"],o),r(t,["id"])!==void 0)throw new Error("id parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function rA(t,e){let n={};if(r(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=r(t,["fileUri"]);i!=null&&a(n,["fileUri"],i);let o=r(t,["mimeType"]);return o!=null&&a(n,["mimeType"],o),n}function sA(t,e){let n={},i=r(t,["id"]);i!=null&&a(n,["id"],i);let o=r(t,["args"]);o!=null&&a(n,["args"],o);let s=r(t,["name"]);if(s!=null&&a(n,["name"],s),r(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(r(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 aA(t,e){let n={},i=r(t,["allowedFunctionNames"]);i!=null&&a(n,["allowedFunctionNames"],i);let o=r(t,["mode"]);if(o!=null&&a(n,["mode"],o),r(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 lA(t,e,n,i){let o={},s=r(e,["systemInstruction"]);n!==void 0&&s!=null&&a(n,["systemInstruction"],Dn(he(s)));let l=r(e,["temperature"]);l!=null&&a(o,["temperature"],l);let u=r(e,["topP"]);u!=null&&a(o,["topP"],u);let c=r(e,["topK"]);c!=null&&a(o,["topK"],c);let d=r(e,["candidateCount"]);d!=null&&a(o,["candidateCount"],d);let f=r(e,["maxOutputTokens"]);f!=null&&a(o,["maxOutputTokens"],f);let p=r(e,["stopSequences"]);p!=null&&a(o,["stopSequences"],p);let h=r(e,["responseLogprobs"]);h!=null&&a(o,["responseLogprobs"],h);let m=r(e,["logprobs"]);m!=null&&a(o,["logprobs"],m);let E=r(e,["presencePenalty"]);E!=null&&a(o,["presencePenalty"],E);let A=r(e,["frequencyPenalty"]);A!=null&&a(o,["frequencyPenalty"],A);let T=r(e,["seed"]);T!=null&&a(o,["seed"],T);let S=r(e,["responseMimeType"]);S!=null&&a(o,["responseMimeType"],S);let b=r(e,["responseSchema"]);b!=null&&a(o,["responseSchema"],Oa(b));let U=r(e,["responseJsonSchema"]);if(U!=null&&a(o,["responseJsonSchema"],U),r(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(r(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 F=r(e,["safetySettings"]);if(n!==void 0&&F!=null){let re=F;Array.isArray(re)&&(re=re.map(de=>jA(de))),a(n,["safetySettings"],re)}let L=r(e,["tools"]);if(n!==void 0&&L!=null){let re=on(L);Array.isArray(re)&&(re=re.map(de=>av(nn(de)))),a(n,["tools"],re)}let P=r(e,["toolConfig"]);if(n!==void 0&&P!=null&&a(n,["toolConfig"],rv(P)),r(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 q=r(e,["cachedContent"]);n!==void 0&&q!=null&&a(n,["cachedContent"],dt(t,q));let J=r(e,["responseModalities"]);J!=null&&a(o,["responseModalities"],J);let R=r(e,["mediaResolution"]);R!=null&&a(o,["mediaResolution"],R);let $=r(e,["speechConfig"]);if($!=null&&a(o,["speechConfig"],qa($)),r(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 X=r(e,["thinkingConfig"]);X!=null&&a(o,["thinkingConfig"],X);let Z=r(e,["imageConfig"]);Z!=null&&a(o,["imageConfig"],GA(Z));let se=r(e,["enableEnhancedCivicAnswers"]);if(se!=null&&a(o,["enableEnhancedCivicAnswers"],se),r(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let te=r(e,["serviceTier"]);return n!==void 0&&te!=null&&a(n,["serviceTier"],te),o}function uA(t,e,n,i){let o={},s=r(e,["systemInstruction"]);n!==void 0&&s!=null&&a(n,["systemInstruction"],sn(he(s)));let l=r(e,["temperature"]);l!=null&&a(o,["temperature"],l);let u=r(e,["topP"]);u!=null&&a(o,["topP"],u);let c=r(e,["topK"]);c!=null&&a(o,["topK"],c);let d=r(e,["candidateCount"]);d!=null&&a(o,["candidateCount"],d);let f=r(e,["maxOutputTokens"]);f!=null&&a(o,["maxOutputTokens"],f);let p=r(e,["stopSequences"]);p!=null&&a(o,["stopSequences"],p);let h=r(e,["responseLogprobs"]);h!=null&&a(o,["responseLogprobs"],h);let m=r(e,["logprobs"]);m!=null&&a(o,["logprobs"],m);let E=r(e,["presencePenalty"]);E!=null&&a(o,["presencePenalty"],E);let A=r(e,["frequencyPenalty"]);A!=null&&a(o,["frequencyPenalty"],A);let T=r(e,["seed"]);T!=null&&a(o,["seed"],T);let S=r(e,["responseMimeType"]);S!=null&&a(o,["responseMimeType"],S);let b=r(e,["responseSchema"]);b!=null&&a(o,["responseSchema"],Oa(b));let U=r(e,["responseJsonSchema"]);U!=null&&a(o,["responseJsonSchema"],U);let F=r(e,["routingConfig"]);F!=null&&a(o,["routingConfig"],F);let L=r(e,["modelSelectionConfig"]);L!=null&&a(o,["modelConfig"],L);let P=r(e,["safetySettings"]);if(n!==void 0&&P!=null){let ae=P;Array.isArray(ae)&&(ae=ae.map(ot=>ot)),a(n,["safetySettings"],ae)}let q=r(e,["tools"]);if(n!==void 0&&q!=null){let ae=on(q);Array.isArray(ae)&&(ae=ae.map(ot=>Hf(nn(ot)))),a(n,["tools"],ae)}let J=r(e,["toolConfig"]);n!==void 0&&J!=null&&a(n,["toolConfig"],sv(J));let R=r(e,["labels"]);n!==void 0&&R!=null&&a(n,["labels"],R);let $=r(e,["cachedContent"]);n!==void 0&&$!=null&&a(n,["cachedContent"],dt(t,$));let X=r(e,["responseModalities"]);X!=null&&a(o,["responseModalities"],X);let Z=r(e,["mediaResolution"]);Z!=null&&a(o,["mediaResolution"],Z);let se=r(e,["speechConfig"]);se!=null&&a(o,["speechConfig"],qa(se));let te=r(e,["audioTimestamp"]);te!=null&&a(o,["audioTimestamp"],te);let re=r(e,["thinkingConfig"]);re!=null&&a(o,["thinkingConfig"],re);let de=r(e,["imageConfig"]);if(de!=null&&a(o,["imageConfig"],LA(de)),r(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 Ie=r(e,["modelArmorConfig"]);n!==void 0&&Ie!=null&&a(n,["modelArmorConfig"],Ie);let Be=r(e,["serviceTier"]);return n!==void 0&&Be!=null&&a(n,["serviceTier"],Be),o}function ef(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["contents"]);if(s!=null){let u=ve(s);Array.isArray(u)&&(u=u.map(c=>Dn(c))),a(i,["contents"],u)}let l=r(e,["config"]);return l!=null&&a(i,["generationConfig"],lA(t,l,i)),i}function tf(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["contents"]);if(s!=null){let u=ve(s);Array.isArray(u)&&(u=u.map(c=>sn(c))),a(i,["contents"],u)}let l=r(e,["config"]);return l!=null&&a(i,["generationConfig"],uA(t,l,i)),i}function nf(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["candidates"]);if(o!=null){let f=o;Array.isArray(f)&&(f=f.map(p=>NT(p))),a(n,["candidates"],f)}let s=r(t,["modelVersion"]);s!=null&&a(n,["modelVersion"],s);let l=r(t,["promptFeedback"]);l!=null&&a(n,["promptFeedback"],l);let u=r(t,["responseId"]);u!=null&&a(n,["responseId"],u);let c=r(t,["usageMetadata"]);c!=null&&a(n,["usageMetadata"],c);let d=r(t,["modelStatus"]);return d!=null&&a(n,["modelStatus"],d),n}function of(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["candidates"]);if(o!=null){let f=o;Array.isArray(f)&&(f=f.map(p=>p)),a(n,["candidates"],f)}let s=r(t,["createTime"]);s!=null&&a(n,["createTime"],s);let l=r(t,["modelVersion"]);l!=null&&a(n,["modelVersion"],l);let u=r(t,["promptFeedback"]);u!=null&&a(n,["promptFeedback"],u);let c=r(t,["responseId"]);c!=null&&a(n,["responseId"],c);let d=r(t,["usageMetadata"]);return d!=null&&a(n,["usageMetadata"],d),n}function cA(t,e,n){let i={};if(r(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(r(t,["negativePrompt"])!==void 0)throw new Error("negativePrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let o=r(t,["numberOfImages"]);e!==void 0&&o!=null&&a(e,["parameters","sampleCount"],o);let s=r(t,["aspectRatio"]);e!==void 0&&s!=null&&a(e,["parameters","aspectRatio"],s);let l=r(t,["guidanceScale"]);if(e!==void 0&&l!=null&&a(e,["parameters","guidanceScale"],l),r(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 u=r(t,["safetyFilterLevel"]);e!==void 0&&u!=null&&a(e,["parameters","safetySetting"],u);let c=r(t,["personGeneration"]);e!==void 0&&c!=null&&a(e,["parameters","personGeneration"],c);let d=r(t,["includeSafetyAttributes"]);e!==void 0&&d!=null&&a(e,["parameters","includeSafetyAttributes"],d);let f=r(t,["includeRaiReason"]);e!==void 0&&f!=null&&a(e,["parameters","includeRaiReason"],f);let p=r(t,["language"]);e!==void 0&&p!=null&&a(e,["parameters","language"],p);let h=r(t,["outputMimeType"]);e!==void 0&&h!=null&&a(e,["parameters","outputOptions","mimeType"],h);let m=r(t,["outputCompressionQuality"]);if(e!==void 0&&m!=null&&a(e,["parameters","outputOptions","compressionQuality"],m),r(t,["addWatermark"])!==void 0)throw new Error("addWatermark parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(r(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 E=r(t,["imageSize"]);if(e!==void 0&&E!=null&&a(e,["parameters","sampleImageSize"],E),r(t,["enhancePrompt"])!==void 0)throw new Error("enhancePrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return i}function dA(t,e,n){let i={},o=r(t,["outputGcsUri"]);e!==void 0&&o!=null&&a(e,["parameters","storageUri"],o);let s=r(t,["negativePrompt"]);e!==void 0&&s!=null&&a(e,["parameters","negativePrompt"],s);let l=r(t,["numberOfImages"]);e!==void 0&&l!=null&&a(e,["parameters","sampleCount"],l);let u=r(t,["aspectRatio"]);e!==void 0&&u!=null&&a(e,["parameters","aspectRatio"],u);let c=r(t,["guidanceScale"]);e!==void 0&&c!=null&&a(e,["parameters","guidanceScale"],c);let d=r(t,["seed"]);e!==void 0&&d!=null&&a(e,["parameters","seed"],d);let f=r(t,["safetyFilterLevel"]);e!==void 0&&f!=null&&a(e,["parameters","safetySetting"],f);let p=r(t,["personGeneration"]);e!==void 0&&p!=null&&a(e,["parameters","personGeneration"],p);let h=r(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&a(e,["parameters","includeSafetyAttributes"],h);let m=r(t,["includeRaiReason"]);e!==void 0&&m!=null&&a(e,["parameters","includeRaiReason"],m);let E=r(t,["language"]);e!==void 0&&E!=null&&a(e,["parameters","language"],E);let A=r(t,["outputMimeType"]);e!==void 0&&A!=null&&a(e,["parameters","outputOptions","mimeType"],A);let T=r(t,["outputCompressionQuality"]);e!==void 0&&T!=null&&a(e,["parameters","outputOptions","compressionQuality"],T);let S=r(t,["addWatermark"]);e!==void 0&&S!=null&&a(e,["parameters","addWatermark"],S);let b=r(t,["labels"]);e!==void 0&&b!=null&&a(e,["labels"],b);let U=r(t,["imageSize"]);e!==void 0&&U!=null&&a(e,["parameters","sampleImageSize"],U);let F=r(t,["enhancePrompt"]);return e!==void 0&&F!=null&&a(e,["parameters","enhancePrompt"],F),i}function fA(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["prompt"]);s!=null&&a(i,["instances[0]","prompt"],s);let l=r(e,["config"]);return l!=null&&cA(l,i),i}function pA(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["prompt"]);s!=null&&a(i,["instances[0]","prompt"],s);let l=r(e,["config"]);return l!=null&&dA(l,i),i}function hA(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["predictions"]);if(o!=null){let l=o;Array.isArray(l)&&(l=l.map(u=>wA(u))),a(n,["generatedImages"],l)}let s=r(t,["positivePromptSafetyAttributes"]);return s!=null&&a(n,["positivePromptSafetyAttributes"],qf(s)),n}function mA(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["predictions"]);if(o!=null){let l=o;Array.isArray(l)&&(l=l.map(u=>To(u))),a(n,["generatedImages"],l)}let s=r(t,["positivePromptSafetyAttributes"]);return s!=null&&a(n,["positivePromptSafetyAttributes"],Bf(s)),n}function gA(t,e,n){let i={},o=r(t,["numberOfVideos"]);if(e!==void 0&&o!=null&&a(e,["parameters","sampleCount"],o),r(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(r(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 s=r(t,["durationSeconds"]);if(e!==void 0&&s!=null&&a(e,["parameters","durationSeconds"],s),r(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 l=r(t,["aspectRatio"]);e!==void 0&&l!=null&&a(e,["parameters","aspectRatio"],l);let u=r(t,["resolution"]);e!==void 0&&u!=null&&a(e,["parameters","resolution"],u);let c=r(t,["personGeneration"]);if(e!==void 0&&c!=null&&a(e,["parameters","personGeneration"],c),r(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=r(t,["negativePrompt"]);e!==void 0&&d!=null&&a(e,["parameters","negativePrompt"],d);let f=r(t,["enhancePrompt"]);if(e!==void 0&&f!=null&&a(e,["parameters","enhancePrompt"],f),r(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=r(t,["lastFrame"]);e!==void 0&&p!=null&&a(e,["instances[0]","lastFrame"],Ao(p));let h=r(t,["referenceImages"]);if(e!==void 0&&h!=null){let E=h;Array.isArray(E)&&(E=E.map(A=>Tv(A))),a(e,["instances[0]","referenceImages"],E)}if(r(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(r(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(r(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=r(t,["webhookConfig"]);if(e!==void 0&&m!=null&&a(e,["webhookConfig"],m),r(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 yA(t,e,n){let i={},o=r(t,["numberOfVideos"]);e!==void 0&&o!=null&&a(e,["parameters","sampleCount"],o);let s=r(t,["outputGcsUri"]);e!==void 0&&s!=null&&a(e,["parameters","storageUri"],s);let l=r(t,["fps"]);e!==void 0&&l!=null&&a(e,["parameters","fps"],l);let u=r(t,["durationSeconds"]);e!==void 0&&u!=null&&a(e,["parameters","durationSeconds"],u);let c=r(t,["seed"]);e!==void 0&&c!=null&&a(e,["parameters","seed"],c);let d=r(t,["aspectRatio"]);e!==void 0&&d!=null&&a(e,["parameters","aspectRatio"],d);let f=r(t,["resolution"]);e!==void 0&&f!=null&&a(e,["parameters","resolution"],f);let p=r(t,["personGeneration"]);e!==void 0&&p!=null&&a(e,["parameters","personGeneration"],p);let h=r(t,["pubsubTopic"]);e!==void 0&&h!=null&&a(e,["parameters","pubsubTopic"],h);let m=r(t,["negativePrompt"]);e!==void 0&&m!=null&&a(e,["parameters","negativePrompt"],m);let E=r(t,["enhancePrompt"]);e!==void 0&&E!=null&&a(e,["parameters","enhancePrompt"],E);let A=r(t,["generateAudio"]);e!==void 0&&A!=null&&a(e,["parameters","generateAudio"],A);let T=r(t,["lastFrame"]);e!==void 0&&T!=null&&a(e,["instances[0]","lastFrame"],ze(T));let S=r(t,["referenceImages"]);if(e!==void 0&&S!=null){let P=S;Array.isArray(P)&&(P=P.map(q=>Av(q))),a(e,["instances[0]","referenceImages"],P)}let b=r(t,["mask"]);e!==void 0&&b!=null&&a(e,["instances[0]","mask"],_v(b));let U=r(t,["compressionQuality"]);e!==void 0&&U!=null&&a(e,["parameters","compressionQuality"],U);let F=r(t,["labels"]);if(e!==void 0&&F!=null&&a(e,["labels"],F),r(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 L=r(t,["resizeMode"]);return e!==void 0&&L!=null&&a(e,["parameters","resizeMode"],L),i}function EA(t,e){let n={},i=r(t,["name"]);i!=null&&a(n,["name"],i);let o=r(t,["metadata"]);o!=null&&a(n,["metadata"],o);let s=r(t,["done"]);s!=null&&a(n,["done"],s);let l=r(t,["error"]);l!=null&&a(n,["error"],l);let u=r(t,["response","generateVideoResponse"]);return u!=null&&a(n,["response"],vA(u)),n}function _A(t,e){let n={},i=r(t,["name"]);i!=null&&a(n,["name"],i);let o=r(t,["metadata"]);o!=null&&a(n,["metadata"],o);let s=r(t,["done"]);s!=null&&a(n,["done"],s);let l=r(t,["error"]);l!=null&&a(n,["error"],l);let u=r(t,["response"]);return u!=null&&a(n,["response"],CA(u)),n}function TA(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["prompt"]);s!=null&&a(i,["instances[0]","prompt"],s);let l=r(e,["image"]);l!=null&&a(i,["instances[0]","image"],Ao(l));let u=r(e,["video"]);u!=null&&a(i,["instances[0]","video"],Vf(u));let c=r(e,["source"]);c!=null&&SA(c,i);let d=r(e,["config"]);return d!=null&&gA(d,i),i}function AA(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["prompt"]);s!=null&&a(i,["instances[0]","prompt"],s);let l=r(e,["image"]);l!=null&&a(i,["instances[0]","image"],ze(l));let u=r(e,["video"]);u!=null&&a(i,["instances[0]","video"],$f(u));let c=r(e,["source"]);c!=null&&IA(c,i);let d=r(e,["config"]);return d!=null&&yA(d,i),i}function vA(t,e){let n={},i=r(t,["generatedSamples"]);if(i!=null){let l=i;Array.isArray(l)&&(l=l.map(u=>RA(u))),a(n,["generatedVideos"],l)}let o=r(t,["raiMediaFilteredCount"]);o!=null&&a(n,["raiMediaFilteredCount"],o);let s=r(t,["raiMediaFilteredReasons"]);return s!=null&&a(n,["raiMediaFilteredReasons"],s),n}function CA(t,e){let n={},i=r(t,["videos"]);if(i!=null){let l=i;Array.isArray(l)&&(l=l.map(u=>NA(u))),a(n,["generatedVideos"],l)}let o=r(t,["raiMediaFilteredCount"]);o!=null&&a(n,["raiMediaFilteredCount"],o);let s=r(t,["raiMediaFilteredReasons"]);return s!=null&&a(n,["raiMediaFilteredReasons"],s),n}function SA(t,e,n){let i={},o=r(t,["prompt"]);e!==void 0&&o!=null&&a(e,["instances[0]","prompt"],o);let s=r(t,["image"]);e!==void 0&&s!=null&&a(e,["instances[0]","image"],Ao(s));let l=r(t,["video"]);return e!==void 0&&l!=null&&a(e,["instances[0]","video"],Vf(l)),i}function IA(t,e,n){let i={},o=r(t,["prompt"]);e!==void 0&&o!=null&&a(e,["instances[0]","prompt"],o);let s=r(t,["image"]);e!==void 0&&s!=null&&a(e,["instances[0]","image"],ze(s));let l=r(t,["video"]);return e!==void 0&&l!=null&&a(e,["instances[0]","video"],$f(l)),i}function wA(t,e){let n={},i=r(t,["_self"]);i!=null&&a(n,["image"],bA(i));let o=r(t,["raiFilteredReason"]);o!=null&&a(n,["raiFilteredReason"],o);let s=r(t,["_self"]);return s!=null&&a(n,["safetyAttributes"],qf(s)),n}function To(t,e){let n={},i=r(t,["_self"]);i!=null&&a(n,["image"],Of(i));let o=r(t,["raiFilteredReason"]);o!=null&&a(n,["raiFilteredReason"],o);let s=r(t,["_self"]);s!=null&&a(n,["safetyAttributes"],Bf(s));let l=r(t,["prompt"]);return l!=null&&a(n,["enhancedPrompt"],l),n}function PA(t,e){let n={},i=r(t,["_self"]);i!=null&&a(n,["mask"],Of(i));let o=r(t,["labels"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>l)),a(n,["labels"],s)}return n}function RA(t,e){let n={},i=r(t,["video"]);return i!=null&&a(n,["video"],yv(i)),n}function NA(t,e){let n={},i=r(t,["_self"]);return i!=null&&a(n,["video"],Ev(i)),n}function DA(t,e){let n={},i=r(t,["modelSelectionConfig"]);i!=null&&a(n,["modelConfig"],i);let o=r(t,["responseJsonSchema"]);o!=null&&a(n,["responseJsonSchema"],o);let s=r(t,["audioTimestamp"]);s!=null&&a(n,["audioTimestamp"],s);let l=r(t,["candidateCount"]);l!=null&&a(n,["candidateCount"],l);let u=r(t,["enableAffectiveDialog"]);u!=null&&a(n,["enableAffectiveDialog"],u);let c=r(t,["frequencyPenalty"]);c!=null&&a(n,["frequencyPenalty"],c);let d=r(t,["logprobs"]);d!=null&&a(n,["logprobs"],d);let f=r(t,["maxOutputTokens"]);f!=null&&a(n,["maxOutputTokens"],f);let p=r(t,["mediaResolution"]);p!=null&&a(n,["mediaResolution"],p);let h=r(t,["presencePenalty"]);h!=null&&a(n,["presencePenalty"],h);let m=r(t,["responseLogprobs"]);m!=null&&a(n,["responseLogprobs"],m);let E=r(t,["responseMimeType"]);E!=null&&a(n,["responseMimeType"],E);let A=r(t,["responseModalities"]);A!=null&&a(n,["responseModalities"],A);let T=r(t,["responseSchema"]);T!=null&&a(n,["responseSchema"],T);let S=r(t,["routingConfig"]);S!=null&&a(n,["routingConfig"],S);let b=r(t,["seed"]);b!=null&&a(n,["seed"],b);let U=r(t,["speechConfig"]);U!=null&&a(n,["speechConfig"],U);let F=r(t,["stopSequences"]);F!=null&&a(n,["stopSequences"],F);let L=r(t,["temperature"]);L!=null&&a(n,["temperature"],L);let P=r(t,["thinkingConfig"]);P!=null&&a(n,["thinkingConfig"],P);let q=r(t,["topK"]);q!=null&&a(n,["topK"],q);let J=r(t,["topP"]);if(J!=null&&a(n,["topP"],J),r(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function MA(t,e,n){let i={},o=r(e,["model"]);return o!=null&&a(i,["_url","name"],ee(t,o)),i}function xA(t,e,n){let i={},o=r(e,["model"]);return o!=null&&a(i,["_url","name"],ee(t,o)),i}function kA(t,e){let n={},i=r(t,["authConfig"]);i!=null&&a(n,["authConfig"],PT(i));let o=r(t,["enableWidget"]);return o!=null&&a(n,["enableWidget"],o),n}function UA(t,e){let n={},i=r(t,["searchTypes"]);if(i!=null&&a(n,["searchTypes"],i),r(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(r(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 o=r(t,["timeRangeFilter"]);return o!=null&&a(n,["timeRangeFilter"],o),n}function GA(t,e){let n={},i=r(t,["aspectRatio"]);i!=null&&a(n,["aspectRatio"],i);let o=r(t,["imageSize"]);if(o!=null&&a(n,["imageSize"],o),r(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(r(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(r(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(r(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(r(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function LA(t,e){let n={},i=r(t,["aspectRatio"]);i!=null&&a(n,["aspectRatio"],i);let o=r(t,["imageSize"]);o!=null&&a(n,["imageSize"],o);let s=r(t,["personGeneration"]);s!=null&&a(n,["personGeneration"],s);let l=r(t,["prominentPeople"]);l!=null&&a(n,["prominentPeople"],l);let u=r(t,["outputMimeType"]);u!=null&&a(n,["imageOutputOptions","mimeType"],u);let c=r(t,["outputCompressionQuality"]);c!=null&&a(n,["imageOutputOptions","compressionQuality"],c);let d=r(t,["imageOutputOptions"]);return d!=null&&a(n,["imageOutputOptions"],d),n}function bA(t,e){let n={},i=r(t,["bytesBase64Encoded"]);i!=null&&a(n,["imageBytes"],Tt(i));let o=r(t,["mimeType"]);return o!=null&&a(n,["mimeType"],o),n}function Of(t,e){let n={},i=r(t,["gcsUri"]);i!=null&&a(n,["gcsUri"],i);let o=r(t,["bytesBase64Encoded"]);o!=null&&a(n,["imageBytes"],Tt(o));let s=r(t,["mimeType"]);return s!=null&&a(n,["mimeType"],s),n}function Ao(t,e){let n={};if(r(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=r(t,["imageBytes"]);i!=null&&a(n,["bytesBase64Encoded"],Tt(i));let o=r(t,["mimeType"]);return o!=null&&a(n,["mimeType"],o),n}function ze(t,e){let n={},i=r(t,["gcsUri"]);i!=null&&a(n,["gcsUri"],i);let o=r(t,["imageBytes"]);o!=null&&a(n,["bytesBase64Encoded"],Tt(o));let s=r(t,["mimeType"]);return s!=null&&a(n,["mimeType"],s),n}function FA(t,e,n,i){let o={},s=r(e,["pageSize"]);n!==void 0&&s!=null&&a(n,["_query","pageSize"],s);let l=r(e,["pageToken"]);n!==void 0&&l!=null&&a(n,["_query","pageToken"],l);let u=r(e,["filter"]);n!==void 0&&u!=null&&a(n,["_query","filter"],u);let c=r(e,["queryBase"]);return n!==void 0&&c!=null&&a(n,["_url","models_url"],xf(t,c)),o}function OA(t,e,n,i){let o={},s=r(e,["pageSize"]);n!==void 0&&s!=null&&a(n,["_query","pageSize"],s);let l=r(e,["pageToken"]);n!==void 0&&l!=null&&a(n,["_query","pageToken"],l);let u=r(e,["filter"]);n!==void 0&&u!=null&&a(n,["_query","filter"],u);let c=r(e,["queryBase"]);return n!==void 0&&c!=null&&a(n,["_url","models_url"],xf(t,c)),o}function qA(t,e,n){let i={},o=r(e,["config"]);return o!=null&&FA(t,o,i),i}function BA(t,e,n){let i={},o=r(e,["config"]);return o!=null&&OA(t,o,i),i}function HA(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["nextPageToken"]);o!=null&&a(n,["nextPageToken"],o);let s=r(t,["_self"]);if(s!=null){let l=kf(s);Array.isArray(l)&&(l=l.map(u=>aa(u))),a(n,["models"],l)}return n}function VA(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["nextPageToken"]);o!=null&&a(n,["nextPageToken"],o);let s=r(t,["_self"]);if(s!=null){let l=kf(s);Array.isArray(l)&&(l=l.map(u=>la(u))),a(n,["models"],l)}return n}function $A(t,e){let n={},i=r(t,["maskMode"]);i!=null&&a(n,["maskMode"],i);let o=r(t,["segmentationClasses"]);o!=null&&a(n,["maskClasses"],o);let s=r(t,["maskDilation"]);return s!=null&&a(n,["dilation"],s),n}function aa(t,e){let n={},i=r(t,["name"]);i!=null&&a(n,["name"],i);let o=r(t,["displayName"]);o!=null&&a(n,["displayName"],o);let s=r(t,["description"]);s!=null&&a(n,["description"],s);let l=r(t,["version"]);l!=null&&a(n,["version"],l);let u=r(t,["_self"]);u!=null&&a(n,["tunedModelInfo"],lv(u));let c=r(t,["inputTokenLimit"]);c!=null&&a(n,["inputTokenLimit"],c);let d=r(t,["outputTokenLimit"]);d!=null&&a(n,["outputTokenLimit"],d);let f=r(t,["supportedGenerationMethods"]);f!=null&&a(n,["supportedActions"],f);let p=r(t,["temperature"]);p!=null&&a(n,["temperature"],p);let h=r(t,["maxTemperature"]);h!=null&&a(n,["maxTemperature"],h);let m=r(t,["topP"]);m!=null&&a(n,["topP"],m);let E=r(t,["topK"]);E!=null&&a(n,["topK"],E);let A=r(t,["thinking"]);return A!=null&&a(n,["thinking"],A),n}function la(t,e){let n={},i=r(t,["name"]);i!=null&&a(n,["name"],i);let o=r(t,["displayName"]);o!=null&&a(n,["displayName"],o);let s=r(t,["description"]);s!=null&&a(n,["description"],s);let l=r(t,["versionId"]);l!=null&&a(n,["version"],l);let u=r(t,["deployedModels"]);if(u!=null){let h=u;Array.isArray(h)&&(h=h.map(m=>iA(m))),a(n,["endpoints"],h)}let c=r(t,["labels"]);c!=null&&a(n,["labels"],c);let d=r(t,["_self"]);d!=null&&a(n,["tunedModelInfo"],uv(d));let f=r(t,["defaultCheckpointId"]);f!=null&&a(n,["defaultCheckpointId"],f);let p=r(t,["checkpoints"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(m=>m)),a(n,["checkpoints"],h)}return n}function JA(t,e){let n={},i=r(t,["mediaResolution"]);i!=null&&a(n,["mediaResolution"],i);let o=r(t,["codeExecutionResult"]);o!=null&&a(n,["codeExecutionResult"],o);let s=r(t,["executableCode"]);s!=null&&a(n,["executableCode"],s);let l=r(t,["fileData"]);l!=null&&a(n,["fileData"],rA(l));let u=r(t,["functionCall"]);u!=null&&a(n,["functionCall"],sA(u));let c=r(t,["functionResponse"]);c!=null&&a(n,["functionResponse"],c);let d=r(t,["inlineData"]);d!=null&&a(n,["inlineData"],RT(d));let f=r(t,["text"]);f!=null&&a(n,["text"],f);let p=r(t,["thought"]);p!=null&&a(n,["thought"],p);let h=r(t,["thoughtSignature"]);h!=null&&a(n,["thoughtSignature"],h);let m=r(t,["videoMetadata"]);m!=null&&a(n,["videoMetadata"],m);let E=r(t,["toolCall"]);E!=null&&a(n,["toolCall"],E);let A=r(t,["toolResponse"]);A!=null&&a(n,["toolResponse"],A);let T=r(t,["partMetadata"]);return T!=null&&a(n,["partMetadata"],T),n}function KA(t,e){let n={},i=r(t,["mediaResolution"]);i!=null&&a(n,["mediaResolution"],i);let o=r(t,["codeExecutionResult"]);o!=null&&a(n,["codeExecutionResult"],MT(o));let s=r(t,["executableCode"]);s!=null&&a(n,["executableCode"],oA(s));let l=r(t,["fileData"]);l!=null&&a(n,["fileData"],l);let u=r(t,["functionCall"]);u!=null&&a(n,["functionCall"],u);let c=r(t,["functionResponse"]);c!=null&&a(n,["functionResponse"],c);let d=r(t,["inlineData"]);d!=null&&a(n,["inlineData"],d);let f=r(t,["text"]);f!=null&&a(n,["text"],f);let p=r(t,["thought"]);p!=null&&a(n,["thought"],p);let h=r(t,["thoughtSignature"]);h!=null&&a(n,["thoughtSignature"],h);let m=r(t,["videoMetadata"]);if(m!=null&&a(n,["videoMetadata"],m),r(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(r(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(r(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function WA(t,e){let n={},i=r(t,["productImage"]);return i!=null&&a(n,["image"],ze(i)),n}function YA(t,e,n){let i={},o=r(t,["numberOfImages"]);e!==void 0&&o!=null&&a(e,["parameters","sampleCount"],o);let s=r(t,["baseSteps"]);e!==void 0&&s!=null&&a(e,["parameters","baseSteps"],s);let l=r(t,["outputGcsUri"]);e!==void 0&&l!=null&&a(e,["parameters","storageUri"],l);let u=r(t,["seed"]);e!==void 0&&u!=null&&a(e,["parameters","seed"],u);let c=r(t,["safetyFilterLevel"]);e!==void 0&&c!=null&&a(e,["parameters","safetySetting"],c);let d=r(t,["personGeneration"]);e!==void 0&&d!=null&&a(e,["parameters","personGeneration"],d);let f=r(t,["addWatermark"]);e!==void 0&&f!=null&&a(e,["parameters","addWatermark"],f);let p=r(t,["outputMimeType"]);e!==void 0&&p!=null&&a(e,["parameters","outputOptions","mimeType"],p);let h=r(t,["outputCompressionQuality"]);e!==void 0&&h!=null&&a(e,["parameters","outputOptions","compressionQuality"],h);let m=r(t,["enhancePrompt"]);e!==void 0&&m!=null&&a(e,["parameters","enhancePrompt"],m);let E=r(t,["labels"]);return e!==void 0&&E!=null&&a(e,["labels"],E),i}function zA(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["source"]);s!=null&&QA(s,i);let l=r(e,["config"]);return l!=null&&YA(l,i),i}function XA(t,e){let n={},i=r(t,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>To(s))),a(n,["generatedImages"],o)}return n}function QA(t,e,n){let i={},o=r(t,["prompt"]);e!==void 0&&o!=null&&a(e,["instances[0]","prompt"],o);let s=r(t,["personImage"]);e!==void 0&&s!=null&&a(e,["instances[0]","personImage","image"],ze(s));let l=r(t,["productImages"]);if(e!==void 0&&l!=null){let u=l;Array.isArray(u)&&(u=u.map(c=>WA(c))),a(e,["instances[0]","productImages"],u)}return i}function ZA(t,e){let n={},i=r(t,["referenceImage"]);i!=null&&a(n,["referenceImage"],ze(i));let o=r(t,["referenceId"]);o!=null&&a(n,["referenceId"],o);let s=r(t,["referenceType"]);s!=null&&a(n,["referenceType"],s);let l=r(t,["maskImageConfig"]);l!=null&&a(n,["maskImageConfig"],$A(l));let u=r(t,["controlImageConfig"]);u!=null&&a(n,["controlImageConfig"],bT(u));let c=r(t,["styleImageConfig"]);c!=null&&a(n,["styleImageConfig"],c);let d=r(t,["subjectImageConfig"]);return d!=null&&a(n,["subjectImageConfig"],d),n}function qf(t,e){let n={},i=r(t,["safetyAttributes","categories"]);i!=null&&a(n,["categories"],i);let o=r(t,["safetyAttributes","scores"]);o!=null&&a(n,["scores"],o);let s=r(t,["contentType"]);return s!=null&&a(n,["contentType"],s),n}function Bf(t,e){let n={},i=r(t,["safetyAttributes","categories"]);i!=null&&a(n,["categories"],i);let o=r(t,["safetyAttributes","scores"]);o!=null&&a(n,["scores"],o);let s=r(t,["contentType"]);return s!=null&&a(n,["contentType"],s),n}function jA(t,e){let n={},i=r(t,["category"]);if(i!=null&&a(n,["category"],i),r(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=r(t,["threshold"]);return o!=null&&a(n,["threshold"],o),n}function ev(t,e){let n={},i=r(t,["image"]);return i!=null&&a(n,["image"],ze(i)),n}function tv(t,e,n){let i={},o=r(t,["mode"]);e!==void 0&&o!=null&&a(e,["parameters","mode"],o);let s=r(t,["maxPredictions"]);e!==void 0&&s!=null&&a(e,["parameters","maxPredictions"],s);let l=r(t,["confidenceThreshold"]);e!==void 0&&l!=null&&a(e,["parameters","confidenceThreshold"],l);let u=r(t,["maskDilation"]);e!==void 0&&u!=null&&a(e,["parameters","maskDilation"],u);let c=r(t,["binaryColorThreshold"]);e!==void 0&&c!=null&&a(e,["parameters","binaryColorThreshold"],c);let d=r(t,["labels"]);return e!==void 0&&d!=null&&a(e,["labels"],d),i}function nv(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["source"]);s!=null&&ov(s,i);let l=r(e,["config"]);return l!=null&&tv(l,i),i}function iv(t,e){let n={},i=r(t,["predictions"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>PA(s))),a(n,["generatedMasks"],o)}return n}function ov(t,e,n){let i={},o=r(t,["prompt"]);e!==void 0&&o!=null&&a(e,["instances[0]","prompt"],o);let s=r(t,["image"]);e!==void 0&&s!=null&&a(e,["instances[0]","image"],ze(s));let l=r(t,["scribbleImage"]);return e!==void 0&&l!=null&&a(e,["instances[0]","scribble"],ev(l)),i}function rv(t,e){let n={},i=r(t,["retrievalConfig"]);i!=null&&a(n,["retrievalConfig"],i);let o=r(t,["functionCallingConfig"]);o!=null&&a(n,["functionCallingConfig"],aA(o));let s=r(t,["includeServerSideToolInvocations"]);return s!=null&&a(n,["includeServerSideToolInvocations"],s),n}function sv(t,e){let n={},i=r(t,["retrievalConfig"]);i!=null&&a(n,["retrievalConfig"],i);let o=r(t,["functionCallingConfig"]);if(o!=null&&a(n,["functionCallingConfig"],o),r(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 av(t,e){let n={};if(r(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=r(t,["computerUse"]);i!=null&&a(n,["computerUse"],i);let o=r(t,["fileSearch"]);o!=null&&a(n,["fileSearch"],o);let s=r(t,["googleSearch"]);s!=null&&a(n,["googleSearch"],UA(s));let l=r(t,["googleMaps"]);l!=null&&a(n,["googleMaps"],kA(l));let u=r(t,["codeExecution"]);if(u!=null&&a(n,["codeExecution"],u),r(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let c=r(t,["functionDeclarations"]);if(c!=null){let h=c;Array.isArray(h)&&(h=h.map(m=>m)),a(n,["functionDeclarations"],h)}let d=r(t,["googleSearchRetrieval"]);if(d!=null&&a(n,["googleSearchRetrieval"],d),r(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=r(t,["urlContext"]);f!=null&&a(n,["urlContext"],f);let p=r(t,["mcpServers"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(m=>m)),a(n,["mcpServers"],h)}return n}function Hf(t,e){let n={},i=r(t,["retrieval"]);i!=null&&a(n,["retrieval"],i);let o=r(t,["computerUse"]);if(o!=null&&a(n,["computerUse"],UT(o)),r(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let s=r(t,["googleSearch"]);s!=null&&a(n,["googleSearch"],s);let l=r(t,["googleMaps"]);l!=null&&a(n,["googleMaps"],l);let u=r(t,["codeExecution"]);u!=null&&a(n,["codeExecution"],u);let c=r(t,["enterpriseWebSearch"]);c!=null&&a(n,["enterpriseWebSearch"],c);let d=r(t,["functionDeclarations"]);if(d!=null){let m=d;Array.isArray(m)&&(m=m.map(E=>E)),a(n,["functionDeclarations"],m)}let f=r(t,["googleSearchRetrieval"]);f!=null&&a(n,["googleSearchRetrieval"],f);let p=r(t,["parallelAiSearch"]);p!=null&&a(n,["parallelAiSearch"],p);let h=r(t,["urlContext"]);if(h!=null&&a(n,["urlContext"],h),r(t,["mcpServers"])!==void 0)throw new Error("mcpServers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function lv(t,e){let n={},i=r(t,["baseModel"]);i!=null&&a(n,["baseModel"],i);let o=r(t,["createTime"]);o!=null&&a(n,["createTime"],o);let s=r(t,["updateTime"]);return s!=null&&a(n,["updateTime"],s),n}function uv(t,e){let n={},i=r(t,["labels","google-vertex-llm-tuning-base-model-id"]);i!=null&&a(n,["baseModel"],i);let o=r(t,["createTime"]);o!=null&&a(n,["createTime"],o);let s=r(t,["updateTime"]);return s!=null&&a(n,["updateTime"],s),n}function cv(t,e,n){let i={},o=r(t,["displayName"]);e!==void 0&&o!=null&&a(e,["displayName"],o);let s=r(t,["description"]);e!==void 0&&s!=null&&a(e,["description"],s);let l=r(t,["defaultCheckpointId"]);return e!==void 0&&l!=null&&a(e,["defaultCheckpointId"],l),i}function dv(t,e,n){let i={},o=r(t,["displayName"]);e!==void 0&&o!=null&&a(e,["displayName"],o);let s=r(t,["description"]);e!==void 0&&s!=null&&a(e,["description"],s);let l=r(t,["defaultCheckpointId"]);return e!==void 0&&l!=null&&a(e,["defaultCheckpointId"],l),i}function fv(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","name"],ee(t,o));let s=r(e,["config"]);return s!=null&&cv(s,i),i}function pv(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["config"]);return s!=null&&dv(s,i),i}function hv(t,e,n){let i={},o=r(t,["outputGcsUri"]);e!==void 0&&o!=null&&a(e,["parameters","storageUri"],o);let s=r(t,["safetyFilterLevel"]);e!==void 0&&s!=null&&a(e,["parameters","safetySetting"],s);let l=r(t,["personGeneration"]);e!==void 0&&l!=null&&a(e,["parameters","personGeneration"],l);let u=r(t,["includeRaiReason"]);e!==void 0&&u!=null&&a(e,["parameters","includeRaiReason"],u);let c=r(t,["outputMimeType"]);e!==void 0&&c!=null&&a(e,["parameters","outputOptions","mimeType"],c);let d=r(t,["outputCompressionQuality"]);e!==void 0&&d!=null&&a(e,["parameters","outputOptions","compressionQuality"],d);let f=r(t,["enhanceInputImage"]);e!==void 0&&f!=null&&a(e,["parameters","upscaleConfig","enhanceInputImage"],f);let p=r(t,["imagePreservationFactor"]);e!==void 0&&p!=null&&a(e,["parameters","upscaleConfig","imagePreservationFactor"],p);let h=r(t,["labels"]);e!==void 0&&h!=null&&a(e,["labels"],h);let m=r(t,["numberOfImages"]);e!==void 0&&m!=null&&a(e,["parameters","sampleCount"],m);let E=r(t,["mode"]);return e!==void 0&&E!=null&&a(e,["parameters","mode"],E),i}function mv(t,e,n){let i={},o=r(e,["model"]);o!=null&&a(i,["_url","model"],ee(t,o));let s=r(e,["image"]);s!=null&&a(i,["instances[0]","image"],ze(s));let l=r(e,["upscaleFactor"]);l!=null&&a(i,["parameters","upscaleConfig","upscaleFactor"],l);let u=r(e,["config"]);return u!=null&&hv(u,i),i}function gv(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["predictions"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>To(l))),a(n,["generatedImages"],s)}return n}function yv(t,e){let n={},i=r(t,["uri"]);i!=null&&a(n,["uri"],i);let o=r(t,["encodedVideo"]);o!=null&&a(n,["videoBytes"],Tt(o));let s=r(t,["encoding"]);return s!=null&&a(n,["mimeType"],s),n}function Ev(t,e){let n={},i=r(t,["gcsUri"]);i!=null&&a(n,["uri"],i);let o=r(t,["bytesBase64Encoded"]);o!=null&&a(n,["videoBytes"],Tt(o));let s=r(t,["mimeType"]);return s!=null&&a(n,["mimeType"],s),n}function _v(t,e){let n={},i=r(t,["image"]);i!=null&&a(n,["_self"],ze(i));let o=r(t,["maskMode"]);return o!=null&&a(n,["maskMode"],o),n}function Tv(t,e){let n={},i=r(t,["image"]);i!=null&&a(n,["image"],Ao(i));let o=r(t,["referenceType"]);return o!=null&&a(n,["referenceType"],o),n}function Av(t,e){let n={},i=r(t,["image"]);i!=null&&a(n,["image"],ze(i));let o=r(t,["referenceType"]);return o!=null&&a(n,["referenceType"],o),n}function Vf(t,e){let n={},i=r(t,["uri"]);i!=null&&a(n,["uri"],i);let o=r(t,["videoBytes"]);o!=null&&a(n,["encodedVideo"],Tt(o));let s=r(t,["mimeType"]);return s!=null&&a(n,["encoding"],s),n}function $f(t,e){let n={},i=r(t,["uri"]);i!=null&&a(n,["gcsUri"],i);let o=r(t,["videoBytes"]);o!=null&&a(n,["bytesBase64Encoded"],Tt(o));let s=r(t,["mimeType"]);return s!=null&&a(n,["mimeType"],s),n}function vv(t,e,n){let i={},o=r(e,["displayName"]);n!==void 0&&o!=null&&a(n,["displayName"],o);let s=r(e,["embeddingModel"]);return n!==void 0&&s!=null&&a(n,["embeddingModel"],ee(t,s)),i}function Cv(t,e){let n={},i=r(e,["config"]);return i!=null&&vv(t,i,n),n}function Sv(t,e){let n={},i=r(t,["force"]);return e!==void 0&&i!=null&&a(e,["_query","force"],i),n}function Iv(t){let e={},n=r(t,["name"]);n!=null&&a(e,["_url","name"],n);let i=r(t,["config"]);return i!=null&&Sv(i,e),e}function wv(t){let e={},n=r(t,["name"]);return n!=null&&a(e,["_url","name"],n),e}function Pv(t,e){let n={},i=r(t,["customMetadata"]);if(e!==void 0&&i!=null){let s=i;Array.isArray(s)&&(s=s.map(l=>l)),a(e,["customMetadata"],s)}let o=r(t,["chunkingConfig"]);return e!==void 0&&o!=null&&a(e,["chunkingConfig"],o),n}function Rv(t){let e={},n=r(t,["name"]);n!=null&&a(e,["name"],n);let i=r(t,["metadata"]);i!=null&&a(e,["metadata"],i);let o=r(t,["done"]);o!=null&&a(e,["done"],o);let s=r(t,["error"]);s!=null&&a(e,["error"],s);let l=r(t,["response"]);return l!=null&&a(e,["response"],Dv(l)),e}function Nv(t){let e={},n=r(t,["fileSearchStoreName"]);n!=null&&a(e,["_url","file_search_store_name"],n);let i=r(t,["fileName"]);i!=null&&a(e,["fileName"],i);let o=r(t,["config"]);return o!=null&&Pv(o,e),e}function Dv(t){let e={},n=r(t,["sdkHttpResponse"]);n!=null&&a(e,["sdkHttpResponse"],n);let i=r(t,["parent"]);i!=null&&a(e,["parent"],i);let o=r(t,["documentName"]);return o!=null&&a(e,["documentName"],o),e}function Mv(t,e){let n={},i=r(t,["pageSize"]);e!==void 0&&i!=null&&a(e,["_query","pageSize"],i);let o=r(t,["pageToken"]);return e!==void 0&&o!=null&&a(e,["_query","pageToken"],o),n}function xv(t){let e={},n=r(t,["config"]);return n!=null&&Mv(n,e),e}function kv(t){let e={},n=r(t,["sdkHttpResponse"]);n!=null&&a(e,["sdkHttpResponse"],n);let i=r(t,["nextPageToken"]);i!=null&&a(e,["nextPageToken"],i);let o=r(t,["fileSearchStores"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>l)),a(e,["fileSearchStores"],s)}return e}function Jf(t,e){let n={},i=r(t,["mimeType"]);e!==void 0&&i!=null&&a(e,["mimeType"],i);let o=r(t,["displayName"]);e!==void 0&&o!=null&&a(e,["displayName"],o);let s=r(t,["customMetadata"]);if(e!==void 0&&s!=null){let u=s;Array.isArray(u)&&(u=u.map(c=>c)),a(e,["customMetadata"],u)}let l=r(t,["chunkingConfig"]);return e!==void 0&&l!=null&&a(e,["chunkingConfig"],l),n}function Uv(t){let e={},n=r(t,["fileSearchStoreName"]);n!=null&&a(e,["_url","file_search_store_name"],n);let i=r(t,["config"]);return i!=null&&Jf(i,e),e}function Gv(t){let e={},n=r(t,["sdkHttpResponse"]);return n!=null&&a(e,["sdkHttpResponse"],n),e}var Lv="Content-Type",bv="X-Server-Timeout",Fv="User-Agent",ua="x-goog-api-client",Ov="2.6.0",qv=`google-genai-sdk/${Ov}`,Bv="v1beta1",Hv="v1beta",Vv=new Set(["us","eu"]),$v=5,Jv=[408,429,500,502,503,504],ca=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,this.clientOptions.vertexai&&(this.clientOptions.project&&this.clientOptions.location?this.clientOptions.apiKey=void 0:this.clientOptions.apiKey&&(this.clientOptions.project=void 0,this.clientOptions.location=void 0));let s={};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?(s.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey||this.clientOptions.location==="global"?s.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&Vv.has(this.clientOptions.location)?s.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(s.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),s.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:Bv}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),s.apiVersion=(o=this.clientOptions.apiVersion)!==null&&o!==void 0?o:Hv,s.baseUrl="https://generativelanguage.googleapis.com/";s.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=s,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(s,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===bs.COLLECTION||this.clientOptions.apiKey||!this.clientOptions.vertexai||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[l,u]of Object.entries(e.queryParams))o.searchParams.append(l,String(u));let s={};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 s.body=e.body;return s=await this.includeExtraHttpOptionsToRequestInit(s,n,o.toString(),e.abortSignal),this.unaryApiCall(o,s,e.httpMethod)}patchHttpOptions(e,n){let i=JSON.parse(JSON.stringify(e));for(let[o,s]of Object.entries(n))typeof s=="object"?i[o]=Object.assign(Object.assign({},i[o]),s):s!==void 0&&(i[o]=s);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 s={};return s.body=e.body,s=await this.includeExtraHttpOptionsToRequestInit(s,n,o.toString(),e.abortSignal),this.streamApiCall(o,s,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,n,i,o){if(n&&n.timeout||o){let s=new AbortController,l=s.signal;if(n.timeout&&n?.timeout>0){let u=Symbol.for("undici.globalDispatcher.1"),c=globalThis[u];if(c){let f=Object.getOwnPropertySymbols(c);for(let p of f){let h=p.description;if(h?.includes("headers timeout")||h?.includes("body timeout")){let m=c[p];typeof m=="number"&&(c[p]=Math.max(m,n.timeout))}}}let d=setTimeout(()=>s.abort(),n.timeout);d&&typeof d.unref=="function"&&d.unref()}o&&o.addEventListener("abort",()=>{s.abort()}),e.signal=l}return n&&n.extraBody!==null&&Kv(e,n.extraBody),e.headers=await this.getHeadersInternal(n,i),e}async unaryApiCall(e,n,i){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:i})).then(async o=>(await rf(o),new _t(o))).catch(o=>{throw o instanceof Error?o:new Error(`exception ${o} sending request`,{cause:o})})}async streamApiCall(e,n,i){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:i})).then(async o=>(await rf(o),this.processStreamResponse(o))).catch(o=>{throw o instanceof Error?o:new Error(`exception ${o} sending request`,{cause:o})})}processStreamResponse(e){return Oe(this,arguments,function*(){var i;let o=(i=e?.body)===null||i===void 0?void 0:i.getReader(),s=new TextDecoder("utf-8");if(!o)throw new Error("Response body is empty");try{let l="",u="data:",c=[`
33
-
34
- `,"\r\r",`\r
35
- \r
36
- `];for(;;){let{done:d,value:f}=yield z(o.read());if(d){if(l.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let p=s.decode(f,{stream:!0});try{let E=JSON.parse(p);if("error"in E){let A=JSON.parse(JSON.stringify(E.error)),T=A.status,S=A.code,b=`got status: ${T}. ${JSON.stringify(E)}`;if(S>=400&&S<600)throw new ji({message:b,status:S})}}catch(E){if(E.name==="ApiError")throw E}l+=p;let h=-1,m=0;for(;;){h=-1,m=0;for(let T of c){let S=l.indexOf(T);S!==-1&&(h===-1||S<h)&&(h=S,m=T.length)}if(h===-1)break;let E=l.substring(0,h);l=l.substring(h+m);let A=E.trim();if(A.startsWith(u)){let T=A.substring(u.length).trim();try{let S=new Response(T,{headers:e?.headers,status:e?.status,statusText:e?.statusText});yield yield z(new _t(S))}catch(S){throw new Error(`exception parsing stream chunk ${T}. ${S}`)}}}}}finally{o.releaseLock()}})}async apiCall(e,n){var i;if(!this.clientOptions.httpOptions||!this.clientOptions.httpOptions.retryOptions)return fetch(e,n);let o=this.clientOptions.httpOptions.retryOptions;return(0,Eo.default)(async()=>{let l=await fetch(e,n);if(l.ok)return l;throw Jv.includes(l.status)?new Error(`Retryable HTTP Error: ${l.statusText}`):new Eo.AbortError(`Non-retryable exception ${l.statusText} sending request`)},{retries:((i=o.attempts)!==null&&i!==void 0?i:$v)-1})}getDefaultHeaders(){let e={},n=qv+" "+this.clientOptions.userAgentExtra;return e[Fv]=n,e[ua]=n,e[Lv]="application/json",e}async getHeadersInternal(e,n){let i=new Headers;if(e&&e.headers)for(let[o,s]of Object.entries(e.headers))i.append(o,s);return e?.timeout&&e.timeout>0&&i.append(bv,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 s=this.clientOptions.uploader,l=await s.stat(e);o.sizeBytes=String(l.size);let u=(i=n?.mimeType)!==null&&i!==void 0?i:l.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=H("upload/v1beta/files",c._url),p=await this.fetchUploadUrl(f,o.sizeBytes,o.mimeType,d,c,n?.httpOptions);return s.upload(e,p,this)}async uploadFileToFileSearchStore(e,n,i){var o;let s=this.clientOptions.uploader,l=await s.stat(n),u=String(l.size),c=(o=i?.mimeType)!==null&&o!==void 0?o:l.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&&Jf(i,p);let h=await this.fetchUploadUrl(d,u,c,f,p,i?.httpOptions);return s.uploadToFileSearchStore(n,h,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,n,i,o,s,l){var u;let c={};l?c=l: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(s),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 rf(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 Kv(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 s=JSON.parse(t.body);if(typeof s=="object"&&s!==null&&!Array.isArray(s))n=s;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(s,l){let u=Object.assign({},s);for(let c in l)if(Object.prototype.hasOwnProperty.call(l,c)){let d=l[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 Wv="mcp_used/unknown",Kf=!1;function Wf(t){for(let e of t)if(Yv(e)||typeof e=="object"&&"inputSchema"in e)return!0;return Kf}function Yf(t){var e;let n=(e=t[ua])!==null&&e!==void 0?e:"";t[ua]=(n+` ${Wv}`).trimStart()}function Yv(t){return t!==null&&typeof t=="object"&&t instanceof Pn}function zv(t){return Oe(this,arguments,function*(n,i=100){let o,s=0;for(;s<i;){let l=yield z(n.listTools({cursor:o}));for(let u of l.tools)yield yield z(u),s++;if(!l.nextCursor)break;o=l.nextCursor}})}var Pn=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 s={},l=[];for(let f of this.mcpClients)try{for(var u=!0,c=(n=void 0,qe(zv(f))),d;d=await c.next(),e=d.done,!e;u=!0){o=d.value,u=!1;let p=o;l.push(p);let h=p.name;if(s[h])throw new Error(`Duplicate function name ${h} found in MCP tools. Please ensure function names are unique.`);s[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=l,this.functionNameToMcpClient=s}async tool(){return await this.initialize(),lE(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],s;this.config.timeout&&(s={timeout:this.config.timeout});let l=await o.callTool({name:i.name,arguments:i.args},void 0,s);n.push({functionResponse:{name:i.name,response:l.isError?{error:l}:l}})}return n}};function Xv(t){return t!==null&&typeof t=="object"&&"listTools"in t&&typeof t.listTools=="function"}function xP(...t){if(Kf=!0,t.length===0)throw new Error("No MCP clients provided");let e=t[t.length-1];return Xv(e)?Pn.create(t,{}):Pn.create(t.slice(0,t.length-1),e)}async function Qv(t,e,n){let i=new js,o;n.data instanceof Blob?o=JSON.parse(await n.data.text()):o=JSON.parse(n.data),Object.assign(i,o),e(i)}var da=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(),s=this.apiClient.getApiVersion(),l=jv(this.apiClient.getDefaultHeaders()),u=this.apiClient.getApiKey(),c=`${o}/ws/google.ai.generativelanguage.${s}.GenerativeService.BidiGenerateMusic?key=${u}`,d=()=>{},f=new Promise(U=>{d=U}),p=e.callbacks,h=function(){d({})},m=this.apiClient,E={onopen:h,onmessage:U=>{Qv(m,p.onmessage,U)},onerror:(n=p?.onerror)!==null&&n!==void 0?n:function(U){},onclose:(i=p?.onclose)!==null&&i!==void 0?i:function(U){}},A=this.webSocketFactory.create(c,Zv(l),E);A.connect(),await f;let b={setup:{model:ee(this.apiClient,e.model)}};return A.send(JSON.stringify(b)),new fa(A,this.apiClient)}},fa=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=mT(e);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});let n=hT(e);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){let n={playbackControl:e};this.conn.send(JSON.stringify(n))}play(){this.sendPlaybackControl(Xt.PLAY)}pause(){this.sendPlaybackControl(Xt.PAUSE)}stop(){this.sendPlaybackControl(Xt.STOP)}resetContext(){this.sendPlaybackControl(Xt.RESET_CONTEXT)}close(){this.conn.close()}};function Zv(t){let e={};return t.forEach((n,i)=>{e[i]=n}),e}function jv(t){let e=new Headers;for(let[n,i]of Object.entries(t))e.append(n,i);return e}var eC="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function tC(t,e,n){let i=new Zs,o;n.data instanceof Blob?o=await n.data.text():n.data instanceof ArrayBuffer?o=new TextDecoder().decode(n.data):o=n.data;let s=JSON.parse(o);if(t.isVertexAI()){let l=ET(s);Object.assign(i,l)}else Object.assign(i,s);e(i)}var pa=class{constructor(e,n,i){this.apiClient=e,this.auth=n,this.webSocketFactory=i,this.music=new da(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var n,i,o,s,l,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&&Wf(e.config.tools)&&Yf(p);let h=oC(p);if(this.apiClient.isVertexAI()){let R=this.apiClient.getProject(),$=this.apiClient.getLocation(),X=this.apiClient.getApiKey(),Z=!!R&&!!$||!!X;this.apiClient.getCustomBaseUrl()&&!Z?f=c:(f=`${c}/ws/google.cloud.aiplatform.${d}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(h,f))}else{let R=this.apiClient.getApiKey(),$="BidiGenerateContent",X="key";R?.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."),$="BidiGenerateContentConstrained",X="access_token"),f=`${c}/ws/google.ai.generativelanguage.${d}.GenerativeService.${$}?${X}=${R}`}let m=()=>{},E=new Promise(R=>{m=R}),A=e.callbacks,T=function(){var R;(R=A?.onopen)===null||R===void 0||R.call(A),m({})},S=this.apiClient,b={onopen:T,onmessage:R=>{tC(S,A.onmessage,R)},onerror:(n=A?.onerror)!==null&&n!==void 0?n:function(R){},onclose:(i=A?.onclose)!==null&&i!==void 0?i:function(R){}},U=this.webSocketFactory.create(f,iC(h),b);U.connect(),await E;let F=ee(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&F.startsWith("publishers/")){let R=this.apiClient.getProject(),$=this.apiClient.getLocation();R&&$&&(F=`projects/${R}/locations/${$}/`+F)}let L={};this.apiClient.isVertexAI()&&((o=e.config)===null||o===void 0?void 0:o.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[Oi.AUDIO]}:e.config.responseModalities=[Oi.AUDIO]),!((s=e.config)===null||s===void 0)&&s.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");let P=(u=(l=e.config)===null||l===void 0?void 0:l.tools)!==null&&u!==void 0?u:[],q=[];for(let R of P)if(this.isCallableTool(R)){let $=R;q.push(await $.tool())}else q.push(R);q.length>0&&(e.config.tools=q);let J={model:F,config:e.config,callbacks:e.callbacks};return this.apiClient.isVertexAI()?L=pT(this.apiClient,J):L=fT(this.apiClient,J),delete L.config,U.send(JSON.stringify(L)),new ha(U,this.apiClient)}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}},nC={turnComplete:!0},ha=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=ve(n.turns),e.isVertexAI()||(i=i.map(o=>Dn(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 s of i){if(typeof s!="object"||s===null||!("name"in s)||!("response"in s))throw new Error(`Could not parse function response, type '${typeof s}'.`);if(!e.isVertexAI()&&!("id"in s))throw new Error(eC)}return{toolResponse:{functionResponses:i}}}sendClientContent(e){e=Object.assign(Object.assign({},nC),e);let n=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendRealtimeInput(e){let n={};this.apiClient.isVertexAI()?n={realtimeInput:yT(e)}:n={realtimeInput:gT(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 iC(t){let e={};return t.forEach((n,i)=>{e[i]=n}),e}function oC(t){let e=new Headers;for(let[n,i]of Object.entries(t))e.append(n,i);return e}var sf=10;function af(t){var e,n,i;if(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let o=!1;for(let l of(n=t?.tools)!==null&&n!==void 0?n:[])if(Zt(l)){o=!0;break}if(!o)return!0;let s=(i=t?.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls;return s&&(s<0||!Number.isInteger(s))||s==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:",s),!0):!1}function Zt(t){return"callTool"in t&&typeof t.callTool=="function"}function rC(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=>Zt(o)))!==null&&i!==void 0?i:!1}function lf(t){var e;let n=[];return!((e=t?.config)===null||e===void 0)&&e.tools&&t.config.tools.forEach((i,o)=>{if(Zt(i))return;let s=i;s.functionDeclarations&&s.functionDeclarations.length>0&&n.push(o)}),n}function uf(t){var e;return!(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}var ma=class extends Ye{constructor(e){super(),this.apiClient=e,this.embedContent=async n=>{if(!this.apiClient.isVertexAI())return n.model.includes("gemini-embedding-2")&&(n.contents=ve(n.contents)),await this.embedContentInternal(n);if(n.model.includes("gemini")&&n.model!=="gemini-embedding-001"||n.model.includes("maas")){let o=ve(n.contents);if(o.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");let s=Object.assign(Object.assign({},n),{content:o[0],embeddingApiType:qi.EMBED_CONTENT});return await this.embedContentInternal(s)}else{let o=Object.assign(Object.assign({},n),{embeddingApiType:qi.PREDICT});return await this.embedContentInternal(o)}},this.generateContent=async n=>{var i,o,s,l,u;let c=await this.processParamsMaybeAddMcpUsage(n);if(this.maybeMoveToResponseJsonSchem(n),!rC(n)||af(n.config))return await this.generateContentInternal(c);let d=lf(n);if(d.length>0){let A=d.map(T=>`tools[${T}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${A}.`)}let f,p,h=ve(c.contents),m=(s=(o=(i=c.config)===null||i===void 0?void 0:i.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls)!==null&&s!==void 0?s:sf,E=0;for(;E<m&&(f=await this.generateContentInternal(c),!(!f.functionCalls||f.functionCalls.length===0));){let A=f.candidates[0].content,T=[];for(let S of(u=(l=n.config)===null||l===void 0?void 0:l.tools)!==null&&u!==void 0?u:[])if(Zt(S)){let U=await S.callTool(f.functionCalls);T.push(...U)}E++,p={role:"user",parts:T},c.contents=ve(c.contents),c.contents.push(A),c.contents.push(p),uf(c.config)&&(h.push(A),h.push(p))}return uf(c.config)&&(f.automaticFunctionCallingHistory=h),f},this.generateContentStream=async n=>{var i,o,s,l,u;if(this.maybeMoveToResponseJsonSchem(n),af(n.config)){let p=await this.processParamsMaybeAddMcpUsage(n);return await this.generateContentStreamInternal(p)}let c=lf(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=(s=(o=(i=n?.config)===null||i===void 0?void 0:i.toolConfig)===null||o===void 0?void 0:o.functionCallingConfig)===null||s===void 0?void 0:s.streamFunctionCallArguments,f=(u=(l=n?.config)===null||l===void 0?void 0:l.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=>await this.generateImagesInternal(n).then(i=>{var o;let s,l=[];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"?s=c?.safetyAttributes:l.push(c);let u;return s?u={generatedImages:l,positivePromptSafetyAttributes:s,sdkHttpResponse:i.sdkHttpResponse}:u={generatedImages:l,sdkHttpResponse:i.sdkHttpResponse},u}),this.list=async n=>{var i;let l={config:Object.assign(Object.assign({},{queryBase:!0}),n?.config)};if(this.apiClient.isVertexAI()&&!l.config.queryBase){if(!((i=l.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.");l.config.filter="labels.tune-type:*"}return new ct(ut.PAGED_ITEM_MODELS,u=>this.listInternal(u),await this.listInternal(l),l)},this.editImage=async n=>{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,s,l,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 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}:!((l=(s=n.source)===null||s===void 0?void 0:s.video)===null||l===void 0)&&l.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)}}maybeMoveToResponseJsonSchem(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 s=(n=e.config)===null||n===void 0?void 0:n.tools;if(!s)return e;let l=await Promise.all(s.map(async c=>Zt(c)?await c.tool():c)),u={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:l})};if(u.config.tools=l,e.config&&e.config.tools&&Wf(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()),Yf(d),u.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:d})}return u}async initAfcToolsMap(e){var n,i,o;let s=new Map;for(let l of(i=(n=e.config)===null||n===void 0?void 0:n.tools)!==null&&i!==void 0?i:[])if(Zt(l)){let u=l,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(s.has(d.name))throw new Error(`Duplicate tool declaration name: ${d.name}`);s.set(d.name,u)}}return s}async processAfcStream(e){var n,i,o;let s=(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:sf,l=!1,u=0,c=await this.initAfcToolsMap(e);return function(d,f,p){return Oe(this,arguments,function*(){for(var h,m,E,A,T,S;u<s;){l&&(u++,l=!1);let L=yield z(d.processParamsMaybeAddMcpUsage(p)),P=yield z(d.generateContentStreamInternal(L)),q=[],J=[];try{for(var b=!0,U=(m=void 0,qe(P)),F;F=yield z(U.next()),h=F.done,!h;b=!0){A=F.value,b=!1;let R=A;if(yield yield z(R),R.candidates&&(!((T=R.candidates[0])===null||T===void 0)&&T.content)){J.push(R.candidates[0].content);for(let $ of(S=R.candidates[0].content.parts)!==null&&S!==void 0?S:[])if(u<s&&$.functionCall){if(!$.functionCall.name)throw new Error("Function call name was not returned by the model.");if(f.has($.functionCall.name)){let X=yield z(f.get($.functionCall.name).callTool([$.functionCall]));q.push(...X)}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()}, mising tool: ${$.functionCall.name}`)}}}}catch(R){m={error:R}}finally{try{!b&&!h&&(E=U.return)&&(yield z(E.call(U)))}finally{if(m)throw m.error}}if(q.length>0){l=!0;let R=new Dt;R.candidates=[{content:{role:"user",parts:q}}],yield yield z(R);let $=[];$.push(...J),$.push({role:"user",parts:q});let X=ve(p.contents).concat($);p.contents=X}else break}})}(this,c,e)}async generateContentInternal(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=tf(this.apiClient,e);return u=H("{model}:generateContent",d._url),c=d._query,delete d._url,delete d._query,l=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})),l.then(f=>{let p=of(f),h=new Dt;return Object.assign(h,p),h})}else{let d=ef(this.apiClient,e);return u=H("{model}:generateContent",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),l.then(f=>{let p=nf(f),h=new Dt;return Object.assign(h,p),h})}}async generateContentStreamInternal(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=tf(this.apiClient,e);return u=H("{model}:streamGenerateContent?alt=sse",d._url),c=d._query,delete d._url,delete d._query,l=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}),l.then(function(p){return Oe(this,arguments,function*(){var h,m,E,A;try{for(var T=!0,S=qe(p),b;b=yield z(S.next()),h=b.done,!h;T=!0){A=b.value,T=!1;let U=A,F=of(yield z(U.json()),e);F.sdkHttpResponse={headers:U.headers};let L=new Dt;Object.assign(L,F),yield yield z(L)}}catch(U){m={error:U}}finally{try{!T&&!h&&(E=S.return)&&(yield z(E.call(S)))}finally{if(m)throw m.error}}})})}else{let d=ef(this.apiClient,e);return u=H("{model}:streamGenerateContent?alt=sse",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}),l.then(function(p){return Oe(this,arguments,function*(){var h,m,E,A;try{for(var T=!0,S=qe(p),b;b=yield z(S.next()),h=b.done,!h;T=!0){A=b.value,T=!1;let U=A,F=nf(yield z(U.json()),e);F.sdkHttpResponse={headers:U.headers};let L=new Dt;Object.assign(L,F),yield yield z(L)}}catch(U){m={error:U}}finally{try{!T&&!h&&(E=S.return)&&(yield z(E.call(S)))}finally{if(m)throw m.error}}})})}}async embedContentInternal(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=eA(this.apiClient,e,e),f=cE(e.model)?"{model}:embedContent":"{model}:predict";return u=H(f,d._url),c=d._query,delete d._url,delete d._query,l=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})),l.then(p=>{let h=nA(p,e),m=new Bi;return Object.assign(m,h),m})}else{let d=jT(this.apiClient,e);return u=H("{model}:batchEmbedContents",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),l.then(f=>{let p=tA(f),h=new Bi;return Object.assign(h,p),h})}}async generateImagesInternal(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=pA(this.apiClient,e);return u=H("{model}:predict",d._url),c=d._query,delete d._url,delete d._query,l=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})),l.then(f=>{let p=mA(f),h=new Hi;return Object.assign(h,p),h})}else{let d=fA(this.apiClient,e);return u=H("{model}:predict",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),l.then(f=>{let p=hA(f),h=new Hi;return Object.assign(h,p),h})}}async editImageInternal(e){var n,i;let o,s="",l={};if(this.apiClient.isVertexAI()){let u=zT(this.apiClient,e);return s=H("{model}:predict",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=XT(c),f=new Fs;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,s="",l={};if(this.apiClient.isVertexAI()){let u=mv(this.apiClient,e);return s=H("{model}:predict",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=gv(c),f=new Os;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,s="",l={};if(this.apiClient.isVertexAI()){let u=zA(this.apiClient,e);return s=H("{model}:predict",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=XA(c),f=new qs;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,s="",l={};if(this.apiClient.isVertexAI()){let u=nv(this.apiClient,e);return s=H("{model}:predict",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=iv(c),f=new Bs;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,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=xA(this.apiClient,e);return u=H("{name}",d._url),c=d._query,delete d._url,delete d._query,l=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()),l.then(f=>la(f))}else{let d=MA(this.apiClient,e);return u=H("{name}",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),l.then(f=>aa(f))}}async listInternal(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=BA(this.apiClient,e);return u=H("{models_url}",d._url),c=d._query,delete d._url,delete d._query,l=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})),l.then(f=>{let p=VA(f),h=new Vi;return Object.assign(h,p),h})}else{let d=qA(this.apiClient,e);return u=H("{models_url}",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),l.then(f=>{let p=HA(f),h=new Vi;return Object.assign(h,p),h})}}async update(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=pv(this.apiClient,e);return u=H("{model}",d._url),c=d._query,delete d._url,delete d._query,l=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()),l.then(f=>la(f))}else{let d=fv(this.apiClient,e);return u=H("{name}",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),l.then(f=>aa(f))}}async delete(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=JT(this.apiClient,e);return u=H("{name}",d._url),c=d._query,delete d._url,delete d._query,l=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})),l.then(f=>{let p=WT(f),h=new $i;return Object.assign(h,p),h})}else{let d=$T(this.apiClient,e);return u=H("{name}",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),l.then(f=>{let p=KT(f),h=new $i;return Object.assign(h,p),h})}}async countTokens(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=BT(this.apiClient,e);return u=H("{model}:countTokens",d._url),c=d._query,delete d._url,delete d._query,l=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})),l.then(f=>{let p=VT(f),h=new Ji;return Object.assign(h,p),h})}else{let d=qT(this.apiClient,e);return u=H("{model}:countTokens",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),l.then(f=>{let p=HT(f),h=new Ji;return Object.assign(h,p),h})}}async computeTokens(e){var n,i;let o,s="",l={};if(this.apiClient.isVertexAI()){let u=xT(this.apiClient,e);return s=H("{model}:computeTokens",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=kT(c),f=new Hs;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,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=AA(this.apiClient,e);return u=H("{model}:predictLongRunning",d._url),c=d._query,delete d._url,delete d._query,l=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()),l.then(f=>{let p=_A(f),h=new Ki;return Object.assign(h,p),h})}else{let d=TA(this.apiClient,e);return u=H("{model}:predictLongRunning",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),l.then(f=>{let p=EA(f),h=new Ki;return Object.assign(h,p),h})}}};var ga=class extends Ye{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],s;i&&"httpOptions"in i&&(s=i.httpOptions);let l=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:o,config:{httpOptions:s}});return n._fromAPIResponse({apiResponse:l,_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],s;i&&"httpOptions"in i&&(s=i.httpOptions);let l=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:o,config:{httpOptions:s}});return n._fromAPIResponse({apiResponse:l,_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,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=Qy(e);return u=H("{operationName}",d._url),c=d._query,delete d._url,delete d._query,l=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()),l}else{let d=Xy(e);return u=H("{operationName}",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json()),l}}async fetchPredictVideosOperationInternal(e){var n,i;let o,s="",l={};if(this.apiClient.isVertexAI()){let u=Vy(e);return s=H("{resourceName}:fetchPredictOperation",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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 cf(t){let e={};if(r(t,["languageCodes"])!==void 0)throw new Error("languageCodes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function sC(t){let e={},n=r(t,["apiKey"]);if(n!=null&&a(e,["apiKey"],n),r(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(r(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(r(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(r(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(r(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(r(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 aC(t){let e={},n=r(t,["data"]);if(n!=null&&a(e,["data"],n),r(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=r(t,["mimeType"]);return i!=null&&a(e,["mimeType"],i),e}function lC(t){let e={},n=r(t,["parts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(s=>yC(s))),a(e,["parts"],o)}let i=r(t,["role"]);return i!=null&&a(e,["role"],i),e}function uC(t,e,n){let i={},o=r(e,["expireTime"]);n!==void 0&&o!=null&&a(n,["expireTime"],o);let s=r(e,["newSessionExpireTime"]);n!==void 0&&s!=null&&a(n,["newSessionExpireTime"],s);let l=r(e,["uses"]);n!==void 0&&l!=null&&a(n,["uses"],l);let u=r(e,["liveConnectConstraints"]);n!==void 0&&u!=null&&a(n,["bidiGenerateContentSetup"],gC(t,u));let c=r(e,["lockAdditionalFields"]);return n!==void 0&&c!=null&&a(n,["fieldMask"],c),i}function cC(t,e){let n={},i=r(e,["config"]);return i!=null&&a(n,["config"],uC(t,i,n)),n}function dC(t){let e={};if(r(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=r(t,["fileUri"]);n!=null&&a(e,["fileUri"],n);let i=r(t,["mimeType"]);return i!=null&&a(e,["mimeType"],i),e}function fC(t){let e={},n=r(t,["id"]);n!=null&&a(e,["id"],n);let i=r(t,["args"]);i!=null&&a(e,["args"],i);let o=r(t,["name"]);if(o!=null&&a(e,["name"],o),r(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(r(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 pC(t){let e={},n=r(t,["authConfig"]);n!=null&&a(e,["authConfig"],sC(n));let i=r(t,["enableWidget"]);return i!=null&&a(e,["enableWidget"],i),e}function hC(t){let e={},n=r(t,["searchTypes"]);if(n!=null&&a(e,["searchTypes"],n),r(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(r(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=r(t,["timeRangeFilter"]);return i!=null&&a(e,["timeRangeFilter"],i),e}function mC(t,e){let n={},i=r(t,["generationConfig"]);e!==void 0&&i!=null&&a(e,["setup","generationConfig"],i);let o=r(t,["responseModalities"]);e!==void 0&&o!=null&&a(e,["setup","generationConfig","responseModalities"],o);let s=r(t,["temperature"]);e!==void 0&&s!=null&&a(e,["setup","generationConfig","temperature"],s);let l=r(t,["topP"]);e!==void 0&&l!=null&&a(e,["setup","generationConfig","topP"],l);let u=r(t,["topK"]);e!==void 0&&u!=null&&a(e,["setup","generationConfig","topK"],u);let c=r(t,["maxOutputTokens"]);e!==void 0&&c!=null&&a(e,["setup","generationConfig","maxOutputTokens"],c);let d=r(t,["mediaResolution"]);e!==void 0&&d!=null&&a(e,["setup","generationConfig","mediaResolution"],d);let f=r(t,["seed"]);e!==void 0&&f!=null&&a(e,["setup","generationConfig","seed"],f);let p=r(t,["speechConfig"]);e!==void 0&&p!=null&&a(e,["setup","generationConfig","speechConfig"],Ba(p));let h=r(t,["thinkingConfig"]);e!==void 0&&h!=null&&a(e,["setup","generationConfig","thinkingConfig"],h);let m=r(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&a(e,["setup","generationConfig","enableAffectiveDialog"],m);let E=r(t,["systemInstruction"]);e!==void 0&&E!=null&&a(e,["setup","systemInstruction"],lC(he(E)));let A=r(t,["tools"]);if(e!==void 0&&A!=null){let R=on(A);Array.isArray(R)&&(R=R.map($=>TC(nn($)))),a(e,["setup","tools"],R)}let T=r(t,["sessionResumption"]);e!==void 0&&T!=null&&a(e,["setup","sessionResumption"],_C(T));let S=r(t,["inputAudioTranscription"]);e!==void 0&&S!=null&&a(e,["setup","inputAudioTranscription"],cf(S));let b=r(t,["outputAudioTranscription"]);e!==void 0&&b!=null&&a(e,["setup","outputAudioTranscription"],cf(b));let U=r(t,["realtimeInputConfig"]);e!==void 0&&U!=null&&a(e,["setup","realtimeInputConfig"],U);let F=r(t,["contextWindowCompression"]);e!==void 0&&F!=null&&a(e,["setup","contextWindowCompression"],F);let L=r(t,["proactivity"]);if(e!==void 0&&L!=null&&a(e,["setup","proactivity"],L),r(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 P=r(t,["avatarConfig"]);e!==void 0&&P!=null&&a(e,["setup","avatarConfig"],P);let q=r(t,["safetySettings"]);if(e!==void 0&&q!=null){let R=q;Array.isArray(R)&&(R=R.map($=>EC($))),a(e,["setup","safetySettings"],R)}let J=r(t,["streamTranslationConfig"]);return e!==void 0&&J!=null&&a(e,["setup","generationConfig","streamTranslationConfig"],J),n}function gC(t,e){let n={},i=r(e,["model"]);i!=null&&a(n,["setup","model"],ee(t,i));let o=r(e,["config"]);return o!=null&&a(n,["config"],mC(o,n)),n}function yC(t){let e={},n=r(t,["mediaResolution"]);n!=null&&a(e,["mediaResolution"],n);let i=r(t,["codeExecutionResult"]);i!=null&&a(e,["codeExecutionResult"],i);let o=r(t,["executableCode"]);o!=null&&a(e,["executableCode"],o);let s=r(t,["fileData"]);s!=null&&a(e,["fileData"],dC(s));let l=r(t,["functionCall"]);l!=null&&a(e,["functionCall"],fC(l));let u=r(t,["functionResponse"]);u!=null&&a(e,["functionResponse"],u);let c=r(t,["inlineData"]);c!=null&&a(e,["inlineData"],aC(c));let d=r(t,["text"]);d!=null&&a(e,["text"],d);let f=r(t,["thought"]);f!=null&&a(e,["thought"],f);let p=r(t,["thoughtSignature"]);p!=null&&a(e,["thoughtSignature"],p);let h=r(t,["videoMetadata"]);h!=null&&a(e,["videoMetadata"],h);let m=r(t,["toolCall"]);m!=null&&a(e,["toolCall"],m);let E=r(t,["toolResponse"]);E!=null&&a(e,["toolResponse"],E);let A=r(t,["partMetadata"]);return A!=null&&a(e,["partMetadata"],A),e}function EC(t){let e={},n=r(t,["category"]);if(n!=null&&a(e,["category"],n),r(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=r(t,["threshold"]);return i!=null&&a(e,["threshold"],i),e}function _C(t){let e={},n=r(t,["handle"]);if(n!=null&&a(e,["handle"],n),r(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 TC(t){let e={};if(r(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=r(t,["computerUse"]);n!=null&&a(e,["computerUse"],n);let i=r(t,["fileSearch"]);i!=null&&a(e,["fileSearch"],i);let o=r(t,["googleSearch"]);o!=null&&a(e,["googleSearch"],hC(o));let s=r(t,["googleMaps"]);s!=null&&a(e,["googleMaps"],pC(s));let l=r(t,["codeExecution"]);if(l!=null&&a(e,["codeExecution"],l),r(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let u=r(t,["functionDeclarations"]);if(u!=null){let p=u;Array.isArray(p)&&(p=p.map(h=>h)),a(e,["functionDeclarations"],p)}let c=r(t,["googleSearchRetrieval"]);if(c!=null&&a(e,["googleSearchRetrieval"],c),r(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=r(t,["urlContext"]);d!=null&&a(e,["urlContext"],d);let f=r(t,["mcpServers"]);if(f!=null){let p=f;Array.isArray(p)&&(p=p.map(h=>h)),a(e,["mcpServers"],p)}return e}function AC(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(s=>`${n}.${s}`);e.push(...o)}else e.push(n)}return e.join(",")}function vC(t,e){let n=null,i=t.bidiGenerateContentSetup;if(typeof i=="object"&&i!==null&&"setup"in i){let s=i.setup;typeof s=="object"&&s!==null?(t.bidiGenerateContentSetup=s,n=s):delete t.bidiGenerateContentSetup}else i!==void 0&&delete t.bidiGenerateContentSetup;let o=t.fieldMask;if(n){let s=AC(n);if(Array.isArray(e?.lockAdditionalFields)&&e?.lockAdditionalFields.length===0)s?t.fieldMask=s:delete t.fieldMask;else if(e?.lockAdditionalFields&&e.lockAdditionalFields.length>0&&o!==null&&Array.isArray(o)&&o.length>0){let l=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],u=[];o.length>0&&(u=o.map(d=>l.includes(d)?`generationConfig.${d}`:d));let c=[];s&&c.push(s),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 ya=class extends Ye{constructor(e){super(),this.apiClient=e}async create(e){var n,i;let o,s="",l={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let u=cC(this.apiClient,e);s=H("auth_tokens",u._url),l=u._query,delete u.config,delete u._url,delete u._query;let c=vC(u,e.config);return o=this.apiClient.request({path:s,queryParams:l,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 CC(t,e){let n={},i=r(t,["force"]);return e!==void 0&&i!=null&&a(e,["_query","force"],i),n}function SC(t){let e={},n=r(t,["name"]);n!=null&&a(e,["_url","name"],n);let i=r(t,["config"]);return i!=null&&CC(i,e),e}function IC(t){let e={},n=r(t,["name"]);return n!=null&&a(e,["_url","name"],n),e}function wC(t,e){let n={},i=r(t,["pageSize"]);e!==void 0&&i!=null&&a(e,["_query","pageSize"],i);let o=r(t,["pageToken"]);return e!==void 0&&o!=null&&a(e,["_query","pageToken"],o),n}function PC(t){let e={},n=r(t,["parent"]);n!=null&&a(e,["_url","parent"],n);let i=r(t,["config"]);return i!=null&&wC(i,e),e}function RC(t){let e={},n=r(t,["sdkHttpResponse"]);n!=null&&a(e,["sdkHttpResponse"],n);let i=r(t,["nextPageToken"]);i!=null&&a(e,["nextPageToken"],i);let o=r(t,["documents"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(l=>l)),a(e,["documents"],s)}return e}var Ea=class extends Ye{constructor(e){super(),this.apiClient=e,this.list=async n=>new ct(ut.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,s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=IC(e);return s=H("{name}",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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="",s={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let l=SC(e);o=H("{name}",l._url),s=l._query,delete l._url,delete l._query,await this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(l),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,s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=PC(e);return s=H("{parent}/documents",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=RC(c),f=new $s;return Object.assign(f,d),f})}}};var _a=class extends Ye{constructor(e,n=new Ea(e)){super(),this.apiClient=e,this.documents=n,this.list=async(i={})=>new ct(ut.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 s={};i.searchParams.forEach((c,d)=>{s[d]=c}),s.alt="media";let l=Object.assign({},n?.httpOptions),u=await this.apiClient.request({path:o,httpMethod:"GET",queryParams:s,httpOptions:l});if(u instanceof _t){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,s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=Cv(this.apiClient,e);return s=H("fileSearchStores",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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,s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=wv(e);return s=H("{name}",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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="",s={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let l=Iv(e);o=H("{name}",l._url),s=l._query,delete l._url,delete l._query,await this.apiClient.request({path:o,queryParams:s,body:JSON.stringify(l),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,s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=xv(e);return s=H("fileSearchStores",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=kv(c),f=new Js;return Object.assign(f,d),f})}}async uploadToFileSearchStoreInternal(e){var n,i;let o,s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=Uv(e);return s=H("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=Gv(c),f=new Ks;return Object.assign(f,d),f})}}async importFile(e){var n,i;let o,s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=Nv(e);return s=H("{file_search_store_name}:importFile",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=Rv(c),f=new Ws;return Object.assign(f,d),f})}}};var zf=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return zf=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,i=>(+i^n()&15>>+i/4).toString(16))},NC=()=>zf();function Ta(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Aa=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var Ce=class extends Error{},Se=class t extends Ce{constructor(e,n,i,o){super(`${t.makeMessage(e,n,i)}`),this.status=e,this.headers=o,this.error=n}static makeMessage(e,n,i){let o=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):i;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,n,i,o){if(!e||!o)return new jt({message:i,cause:Aa(n)});let s=n;return e===400?new to(e,s,i,o):e===401?new no(e,s,i,o):e===403?new io(e,s,i,o):e===404?new oo(e,s,i,o):e===409?new ro(e,s,i,o):e===422?new so(e,s,i,o):e===429?new ao(e,s,i,o):e>=500?new lo(e,s,i,o):new t(e,s,i,o)}},Rn=class extends Se{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},jt=class extends Se{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},eo=class extends jt{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."})}},to=class extends Se{},no=class extends Se{},io=class extends Se{},oo=class extends Se{},ro=class extends Se{},so=class extends Se{},ao=class extends Se{},lo=class extends Se{};var DC=/^[a-z][a-z0-9+.-]*:/i,MC=t=>DC.test(t),va=t=>(va=Array.isArray,va(t)),xC=va,kC=xC,df=kC;function ff(t){if(!t)return!0;for(let e in t)return!1;return!0}function UC(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var GC=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Ce(`${t} must be an integer`);if(e<0)throw new Ce(`${t} must be a positive integer`);return e},LC=t=>{try{return JSON.parse(t)}catch{return}};var bC=t=>new Promise(e=>setTimeout(e,t));function FC(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Xf(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function OC(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Xf({start(){},async pull(n){let{done:i,value:o}=await e.next();i?n.close():n.enqueue(o)},async cancel(){var n;await((n=e.return)===null||n===void 0?void 0:n.call(e))}})}function Qf(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){let n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function qC(t){var e,n;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((n=(e=t[Symbol.asyncIterator]()).return)===null||n===void 0?void 0:n.call(e));return}let i=t.getReader(),o=i.cancel();i.releaseLock(),await o}var BC=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function HC(t){return Object.entries(t).filter(([e,n])=>typeof n<"u").map(([e,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(e)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(e)}=`;throw new Ce(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}var VC="0.0.1";var Zf=()=>{var t;if(typeof File>"u"){let{process:e}=globalThis,n=typeof((t=e?.versions)===null||t===void 0?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ms(t,e,n){return Zf(),new File(t,e??"unknown_file",n)}function $C(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var JC=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";var jf=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",KC=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&jf(t),WC=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function YC(t,e,n){if(Zf(),t=await t,KC(t))return t instanceof File?t:Ms([await t.arrayBuffer()],t.name);if(WC(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Ms(await Ca(o),e,n)}let i=await Ca(t);if(e||(e=$C(t)),!n?.type){let o=i.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(n=Object.assign(Object.assign({},n),{type:o}))}return Ms(i,e,n)}async function Ca(t){var e,n,i,o,s;let l=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)l.push(t);else if(jf(t))l.push(t instanceof Blob?t:await t.arrayBuffer());else if(JC(t))try{for(var u=!0,c=qe(t),d;d=await c.next(),e=d.done,!e;u=!0){o=d.value,u=!1;let f=o;l.push(...await Ca(f))}}catch(f){n={error:f}}finally{try{!u&&!e&&(i=c.return)&&await i.call(c)}finally{if(n)throw n.error}}else{let f=(s=t?.constructor)===null||s===void 0?void 0:s.name;throw new Error(`Unexpected data type: ${typeof t}${f?`; constructor: ${f}`:""}${zC(t)}`)}return l}function zC(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}var en=class{constructor(e){this._client=e}};en._key=[];function ep(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var pf=Object.freeze(Object.create(null)),XC=(t=ep)=>function(n,...i){if(n.length===1)return n[0];let o=!1,s=[],l=n.reduce((f,p,h)=>{var m,E,A;/[?#]/.test(p)&&(o=!0);let T=i[h],S=(o?encodeURIComponent:t)(""+T);return h!==i.length&&(T==null||typeof T=="object"&&T.toString===((A=Object.getPrototypeOf((E=Object.getPrototypeOf((m=T.hasOwnProperty)!==null&&m!==void 0?m:pf))!==null&&E!==void 0?E:pf))===null||A===void 0?void 0:A.toString))&&(S=T+"",s.push({start:f.length+p.length,length:S.length,error:`Value of type ${Object.prototype.toString.call(T).slice(8,-1)} is not a valid path parameter`})),f+p+(h===i.length?"":S)},""),u=l.split(/[?#]/,1)[0],c=/(^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=c.exec(u))!==null;){let f=d[0].startsWith("/"),p=f?1:0,h=f?d[0].slice(1):d[0];s.push({start:d.index+p,length:h.length,error:`Value "${h}" can't be safely passed as a path parameter`})}if(s.sort((f,p)=>f.start-p.start),s.length>0){let f=0,p=s.reduce((h,m)=>{let E=" ".repeat(m.start-f),A="^".repeat(m.length);return f=m.start+m.length,h+E+A},"");throw new Ce(`Path parameters result in path with invalid segments:
37
- ${s.map(h=>h.error).join(`
38
- `)}
39
- ${l}
40
- ${p}`)}return l},Ae=XC(ep);var uo=class extends en{create(e={},n){let i=e??{},{api_version:o=this._client.apiVersion}=i,s=Fe(i,["api_version"]);return this._client.post(Ae`/${o}/agents`,Object.assign({body:s},n))}list(e={},n){let i=e??{},{api_version:o=this._client.apiVersion}=i,s=Fe(i,["api_version"]);return this._client.get(Ae`/${o}/agents`,Object.assign({query:s},n))}delete(e,n={},i){let{api_version:o=this._client.apiVersion}=n??{};return this._client.delete(Ae`/${o}/agents/${e}`,i)}get(e,n={},i){let{api_version:o=this._client.apiVersion}=n??{};return this._client.get(Ae`/${o}/agents/${e}`,i)}};uo._key=Object.freeze(["agents"]);var co=class extends uo{};function QC(t){let e=0;for(let o of t)e+=o.length;let n=new Uint8Array(e),i=0;for(let o of t)n.set(o,i),i+=o.length;return n}var Ui;function Va(t){let e;return(Ui??(e=new globalThis.TextEncoder,Ui=e.encode.bind(e)))(t)}var Gi;function hf(t){let e;return(Gi??(e=new globalThis.TextDecoder,Gi=e.decode.bind(e)))(t)}var tn=class{constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null,this.searchIndex=0}decode(e){var n;if(e==null)return[];let i=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Va(e):e;this.buffer=QC([this.buffer,i]);let o=[],s;for(;(s=ZC(this.buffer,(n=this.carriageReturnIndex)!==null&&n!==void 0?n:this.searchIndex))!=null;){if(s.carriage&&this.carriageReturnIndex==null){this.carriageReturnIndex=s.index;continue}if(this.carriageReturnIndex!=null&&(s.index!==this.carriageReturnIndex+1||s.carriage)){o.push(hf(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null,this.searchIndex=0;continue}let l=this.carriageReturnIndex!==null?s.preceding-1:s.preceding,u=hf(this.buffer.subarray(0,l));o.push(u),this.buffer=this.buffer.subarray(s.index),this.carriageReturnIndex=null,this.searchIndex=0}return this.searchIndex=Math.max(0,this.buffer.length-1),o}flush(){return this.buffer.length?this.decode(`
41
- `):[]}};tn.NEWLINE_CHARS=new Set([`
42
- `,"\r"]);tn.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ZC(t,e){let o=e??0,s=t.indexOf(10,o),l=t.indexOf(13,o);if(s===-1&&l===-1)return null;let u;return s!==-1&&l!==-1?u=Math.min(s,l):u=s!==-1?s:l,t[u]===10?{preceding:u,index:u+1,carriage:!1}:{preceding:u,index:u+1,carriage:!0}}var fo={off:0,error:200,warn:300,info:400,debug:500},mf=(t,e,n)=>{if(t){if(UC(fo,t))return t;Te(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(fo))}`)}};function wn(){}function Li(t,e,n){return!e||fo[t]>fo[n]?wn:e[t].bind(e)}var jC={error:wn,warn:wn,info:wn,debug:wn},gf=new WeakMap;function Te(t){var e;let n=t.logger,i=(e=t.logLevel)!==null&&e!==void 0?e:"off";if(!n)return jC;let o=gf.get(n);if(o&&o[0]===i)return o[1];let s={error:Li("error",n,i),warn:Li("warn",n,i),info:Li("info",n,i),debug:Li("debug",n,i)};return gf.set(n,[i,s]),s}var Nt=t=>(t.options&&(t.options=Object.assign({},t.options),delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="x-goog-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var Nn=class t{constructor(e,n,i){this.iterator=e,this.controller=n,this.client=i}static fromSSEResponse(e,n,i){let o=!1,s=i?Te(i):console;function l(){return Oe(this,arguments,function*(){var c,d,f,p;if(o)throw new Ce("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let h=!1;try{try{for(var m=!0,E=qe(eS(e,n)),A;A=yield z(E.next()),c=A.done,!c;m=!0){p=A.value,m=!1;let T=p;if(!h)if(T.data.startsWith("[DONE]")){h=!0;continue}else try{yield yield z(JSON.parse(T.data))}catch(S){throw s.error("Could not parse message into JSON:",T.data),s.error("From chunk:",T.raw),S}}}catch(T){d={error:T}}finally{try{!m&&!c&&(f=E.return)&&(yield z(f.call(E)))}finally{if(d)throw d.error}}h=!0}catch(T){if(Ta(T))return yield z(void 0);throw T}finally{h||n.abort()}})}return new t(l,n,i)}static fromReadableStream(e,n,i){let o=!1;function s(){return Oe(this,arguments,function*(){var c,d,f,p;let h=new tn,m=Qf(e);try{for(var E=!0,A=qe(m),T;T=yield z(A.next()),c=T.done,!c;E=!0){p=T.value,E=!1;let S=p;for(let b of h.decode(S))yield yield z(b)}}catch(S){d={error:S}}finally{try{!E&&!c&&(f=A.return)&&(yield z(f.call(A)))}finally{if(d)throw d.error}}for(let S of h.flush())yield yield z(S)})}function l(){return Oe(this,arguments,function*(){var c,d,f,p;if(o)throw new Ce("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let h=!1;try{try{for(var m=!0,E=qe(s()),A;A=yield z(E.next()),c=A.done,!c;m=!0){p=A.value,m=!1;let T=p;h||T&&(yield yield z(JSON.parse(T)))}}catch(T){d={error:T}}finally{try{!m&&!c&&(f=E.return)&&(yield z(f.call(E)))}finally{if(d)throw d.error}}h=!0}catch(T){if(Ta(T))return yield z(void 0);throw T}finally{h||n.abort()}})}return new t(l,n,i)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],n=[],i=this.iterator(),o=s=>({next:()=>{if(s.length===0){let l=i.next();e.push(l),n.push(l)}return s.shift()}});return[new t(()=>o(e),this.controller,this.client),new t(()=>o(n),this.controller,this.client)]}toReadableStream(){let e=this,n;return Xf({async start(){n=e[Symbol.asyncIterator]()},async pull(i){try{let{value:o,done:s}=await n.next();if(s)return i.close();let l=Va(JSON.stringify(o)+`
43
- `);i.enqueue(l)}catch(o){i.error(o)}},async cancel(){var i;await((i=n.return)===null||i===void 0?void 0:i.call(n))}})}};function eS(t,e){return Oe(this,arguments,function*(){var i,o,s,l;if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Ce("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new Ce("Attempted to iterate over a response with no body");let u=new Sa,c=new tn,d=Qf(t.body);try{for(var f=!0,p=qe(tS(d)),h;h=yield z(p.next()),i=h.done,!i;f=!0){l=h.value,f=!1;let m=l;for(let E of c.decode(m)){let A=u.decode(E);A&&(yield yield z(A))}}}catch(m){o={error:m}}finally{try{!f&&!i&&(s=p.return)&&(yield z(s.call(p)))}finally{if(o)throw o.error}}for(let m of c.flush()){let E=u.decode(m);E&&(yield yield z(E))}})}function tS(t){return Oe(this,arguments,function*(){var n,i,o,s;try{for(var l=!0,u=qe(t),c;c=yield z(u.next()),n=c.done,!n;l=!0){s=c.value,l=!1;let d=s;if(d==null)continue;let f=d instanceof ArrayBuffer?new Uint8Array(d):typeof d=="string"?Va(d):d;yield yield z(f)}}catch(d){i={error:d}}finally{try{!l&&!n&&(o=u.return)&&(yield z(o.call(u)))}finally{if(i)throw i.error}}})}var Sa=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
44
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,i,o]=nS(e,":");return o.startsWith(" ")&&(o=o.substring(1)),n==="event"?this.event=o:n==="data"&&this.data.push(o),null}};function nS(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}var iS=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]),yf={"interaction.start":"interaction.created","content.start":"step.start","content.delta":"step.delta","content.stop":"step.stop","interaction.complete":"interaction.completed"};function oS({isVertex:t,model:e}){return!!t&&typeof e=="string"&&iS.has(e)}function rS(t){let e=t.clientAdapter;return!!(e&&e.isVertexAI())}function Ia(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function tp(t){if(!("outputs"in t)||"steps"in t)return t;let{outputs:e}=t,n=Fe(t,["outputs"]);return Object.assign(Object.assign({},n),{steps:[{type:"model_output",content:e}]})}function sS(t){return Ia(t)?tp(t):t}function aS(t){if(!Ia(t))return t;let e=t.event_type;if(typeof e!="string"||!(e in yf))return t;let n=Object.assign(Object.assign({},t),{event_type:yf[e]});if(e==="content.start"){let{content:i}=n,o=Fe(n,["content"]),s;return i==null?s=[]:Array.isArray(i)?s=i:s=[i],Object.assign(Object.assign({},o),{step:{type:"model_output",content:s}})}if(e==="interaction.start"||e==="interaction.complete"){let i=n.interaction;Ia(i)&&(n.interaction=tp(i))}return n}var wa=class t extends Nn{static fromSSEResponse(e,n,i){let o=Nn.fromSSEResponse(e,n,i);function s(){return Oe(this,arguments,function*(){var u,c,d,f;try{for(var p=!0,h=qe(o),m;m=yield z(h.next()),u=m.done,!u;p=!0)f=m.value,p=!1,yield yield z(aS(f))}catch(E){c={error:E}}finally{try{!p&&!u&&(d=h.return)&&(yield z(d.call(h)))}finally{if(c)throw c.error}}})}return new t(s,n,i)}};var po=class extends en{create(e,n){var i;let{api_version:o=this._client.apiVersion}=e,s=Fe(e,["api_version"]);if("model"in s&&"agent_config"in s)throw new Ce("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in s&&"generation_config"in s)throw new Ce("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");let l=oS({isVertex:rS(this._client),model:"model"in s?s.model:void 0}),u=(i=e.stream)!==null&&i!==void 0?i:!1,c=this._client.post(Ae`/${o}/interactions`,Object.assign(Object.assign(Object.assign({body:s},n),{stream:u}),l&&u?{__streamClass:wa}:{}));if(u)return c;let d=c;return l&&(d=d._thenUnwrap(f=>sS(f))),d._thenUnwrap(xs)}delete(e,n={},i){let{api_version:o=this._client.apiVersion}=n??{};return this._client.delete(Ae`/${o}/interactions/${e}`,i)}cancel(e,n={},i){let{api_version:o=this._client.apiVersion}=n??{};return this._client.post(Ae`/${o}/interactions/${e}/cancel`,i)._thenUnwrap(xs)}get(e,n={},i){var o;let s=n??{},{api_version:l=this._client.apiVersion}=s,u=Fe(s,["api_version"]),c=this._client.get(Ae`/${l}/interactions/${e}`,Object.assign(Object.assign({query:u},i),{stream:(o=n?.stream)!==null&&o!==void 0?o:!1}));return n?.stream?c:c._thenUnwrap(xs)}};po._key=Object.freeze(["interactions"]);var ho=class extends po{};function xs(t){var e,n;let i=(e=t.steps)!==null&&e!==void 0?e:[],o=[],s=!1;e:for(let f=i.length-1;f>=0;f--){let p=i[f];if(p.type==="user_input")break;if(p.type!=="model_output"||!p.content){if(s)break e;continue}let h=p.content;for(let m=h.length-1;m>=0;m--){let E=h[m];if(E.type==="text")s=!0,o.push((n=E.text)!==null&&n!==void 0?n:"");else if(s)break e}}let l=o.reverse().join(""),u,c,d;for(let f=i.length-1;f>=0;f--){let h=i[f];if(h.type==="user_input")break;if(h.type==="model_output"&&h.content)for(let m=h.content.length-1;m>=0;m--){let E=h.content[m];E.type==="image"&&!u&&(u=E),E.type==="audio"&&!c&&(c=E),E.type==="video"&&!d&&(d=E)}}return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t),l&&{output_text:l}),u&&{output_image:u}),c&&{output_audio:c}),d&&{output_video:d})}var mo=class extends en{create(e,n){let{api_version:i=this._client.apiVersion}=e,o=Fe(e,["api_version"]);return this._client.post(Ae`/${i}/webhooks`,Object.assign({body:o},n))}update(e,n={},i){let o=n??{},{api_version:s=this._client.apiVersion,update_mask:l}=o,u=Fe(o,["api_version","update_mask"]);return this._client.patch(Ae`/${s}/webhooks/${e}`,Object.assign({query:{update_mask:l},body:u},i))}list(e={},n){let i=e??{},{api_version:o=this._client.apiVersion}=i,s=Fe(i,["api_version"]);return this._client.get(Ae`/${o}/webhooks`,Object.assign({query:s},n))}delete(e,n={},i){let{api_version:o=this._client.apiVersion}=n??{};return this._client.delete(Ae`/${o}/webhooks/${e}`,i)}get(e,n={},i){let{api_version:o=this._client.apiVersion}=n??{};return this._client.get(Ae`/${o}/webhooks/${e}`,i)}ping(e,n=void 0,i){let{api_version:o=this._client.apiVersion,body:s}=n??{};return this._client.post(Ae`/${o}/webhooks/${e}:ping`,Object.assign({body:s},i))}rotateSigningSecret(e,n={},i){let o=n??{},{api_version:s=this._client.apiVersion}=o,l=Fe(o,["api_version"]);return this._client.post(Ae`/${s}/webhooks/${e}:rotateSigningSecret`,Object.assign({body:l},i))}};mo._key=Object.freeze(["webhooks"]);var go=class extends mo{};async function lS(t,e){let{response:n,requestLogID:i,retryOfRequestLogID:o,startTime:s}=e,l=await(async()=>{var u;if(e.options.stream)return Te(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t):Nn.fromSSEResponse(n,e.controller,t);if(n.status===204)return null;if(e.options.__binaryResponse)return n;let c=n.headers.get("content-type"),d=(u=c?.split(";")[0])===null||u===void 0?void 0:u.trim();return d?.includes("application/json")||d?.endsWith("+json")?n.headers.get("content-length")==="0"?void 0:await n.json():await n.text()})();return Te(t).debug(`[${i}] response parsed`,Nt({retryOfRequestLogID:o,url:n.url,status:n.status,body:l,durationMs:Date.now()-s})),l}var Pa=class t extends Promise{constructor(e,n,i=lS){super(o=>{o(null)}),this.responsePromise=n,this.parseResponse=i,this.client=e}_thenUnwrap(e){return new t(this.client,this.responsePromise,async(n,i)=>e(await this.parseResponse(n,i),i))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};var np=Symbol("brand.privateNullableHeaders");function*uS(t){if(!t)return;if(np in t){let{values:i,nulls:o}=t;yield*i.entries();for(let s of o)yield[s,null];return}let e=!1,n;t instanceof Headers?n=t.entries():df(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let i of n){let o=i[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=df(i[1])?i[1]:[i[1]],l=!1;for(let u of s)u!==void 0&&(e&&!l&&(l=!0,yield[o,null]),yield[o,u])}}var Sn=t=>{let e=new Headers,n=new Set;for(let i of t){let o=new Set;for(let[s,l]of uS(i)){let u=s.toLowerCase();o.has(u)||(e.delete(s),o.add(u)),l===null?(e.delete(s),n.add(u)):(e.append(s,l),n.delete(u))}}return{[np]:!0,values:e,nulls:n}};var ks=t=>{var e,n,i,o,s;if(typeof globalThis.process<"u")return((n=(e=globalThis.process.env)===null||e===void 0?void 0:e[t])===null||n===void 0?void 0:n.trim())||void 0;if(typeof globalThis.Deno<"u")return((s=(o=(i=globalThis.Deno.env)===null||i===void 0?void 0:i.get)===null||o===void 0?void 0:o.call(i,t))===null||s===void 0?void 0:s.trim())||void 0};var ip,yo=class t{constructor(e){var n,i,o,s,l,u,c,{baseURL:d=ks("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:f=(n=ks("GEMINI_API_KEY"))!==null&&n!==void 0?n:null,apiVersion:p="v1beta"}=e,h=Fe(e,["baseURL","apiKey","apiVersion"]);let m=Object.assign(Object.assign({apiKey:f,apiVersion:p},h),{baseURL:d||"https://generativelanguage.googleapis.com"});this.baseURL=m.baseURL,this.timeout=(i=m.timeout)!==null&&i!==void 0?i:t.DEFAULT_TIMEOUT,this.logger=(o=m.logger)!==null&&o!==void 0?o:console;let E="warn";this.logLevel=E,this.logLevel=(l=(s=mf(m.logLevel,"ClientOptions.logLevel",this))!==null&&s!==void 0?s:mf(ks("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&l!==void 0?l:E,this.fetchOptions=m.fetchOptions,this.maxRetries=(u=m.maxRetries)!==null&&u!==void 0?u:2,this.fetch=(c=m.fetch)!==null&&c!==void 0?c:FC(),this.encoder=BC,this._options=m,this.apiKey=f,this.apiVersion=p,this.clientAdapter=m.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return this.baseURL!=="https://generativelanguage.googleapis.com"}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(e.has("authorization")||e.has("x-goog-api-key"))&&!(this.apiKey&&e.get("x-goog-api-key"))&&!n.has("x-goog-api-key"))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){let n=Sn([e.headers]);if(!(n.values.has("authorization")||n.values.has("x-goog-api-key"))){if(this.apiKey)return Sn([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter&&this.clientAdapter.isVertexAI())return Sn([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return HC(e)}getUserAgent(){return`${this.constructor.name}/JS ${VC}`}defaultIdempotencyKey(){return`stainless-node-retry-${NC()}`}makeStatusError(e,n,i,o){return Se.generate(e,n,i,o)}buildURL(e,n,i){let o=!this.baseURLOverridden()&&i||this.baseURL,s=MC(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),l=this.defaultQuery(),u=Object.fromEntries(s.searchParams);return(!ff(l)||!ff(u))&&(n=Object.assign(Object.assign(Object.assign({},u),l),n)),typeof n=="object"&&n&&!Array.isArray(n)&&(s.search=this.stringifyQuery(n)),s.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){let n=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${n}`}}async prepareRequest(e,{url:n,options:i}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,i){return this.request(Promise.resolve(i).then(o=>Object.assign({method:e,path:n},o)))}request(e,n=null){return new Pa(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,i){var o,s,l;let u=await e,c=(o=u.maxRetries)!==null&&o!==void 0?o:this.maxRetries;n==null&&(n=c),await this.prepareOptions(u);let{req:d,url:f,timeout:p}=await this.buildRequest(u,{retryCount:c-n});await this.prepareRequest(d,{url:f,options:u});let h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=i===void 0?"":`, retryOf: ${i}`,E=Date.now();if(Te(this).debug(`[${h}] sending request`,Nt({retryOfRequestLogID:i,method:u.method,url:f,options:u,headers:d.headers})),!((s=u.signal)===null||s===void 0)&&s.aborted)throw new Rn;let A=new AbortController,T=await this.fetchWithTimeout(f,d,p,A).catch(Aa),S=Date.now();if(T instanceof globalThis.Error){let U=`retrying, ${n} attempts remaining`;if(!((l=u.signal)===null||l===void 0)&&l.aborted)throw new Rn;let F=Ta(T)||/timed? ?out/i.test(String(T)+("cause"in T?String(T.cause):""));if(n)return Te(this).info(`[${h}] connection ${F?"timed out":"failed"} - ${U}`),Te(this).debug(`[${h}] connection ${F?"timed out":"failed"} (${U})`,Nt({retryOfRequestLogID:i,url:f,durationMs:S-E,message:T.message})),this.retryRequest(u,n,i??h);throw Te(this).info(`[${h}] connection ${F?"timed out":"failed"} - error; no more retries left`),Te(this).debug(`[${h}] connection ${F?"timed out":"failed"} (error; no more retries left)`,Nt({retryOfRequestLogID:i,url:f,durationMs:S-E,message:T.message})),F?new eo:new jt({cause:T})}let b=`[${h}${m}] ${d.method} ${f} ${T.ok?"succeeded":"failed"} with status ${T.status} in ${S-E}ms`;if(!T.ok){let U=await this.shouldRetry(T);if(n&&U){let R=`retrying, ${n} attempts remaining`;return await qC(T.body),Te(this).info(`${b} - ${R}`),Te(this).debug(`[${h}] response error (${R})`,Nt({retryOfRequestLogID:i,url:T.url,status:T.status,headers:T.headers,durationMs:S-E})),this.retryRequest(u,n,i??h,T.headers)}let F=U?"error; no more retries left":"error; not retryable";Te(this).info(`${b} - ${F}`);let L=await T.text().catch(R=>Aa(R).message),P=LC(L),q=P?void 0:L;throw Te(this).debug(`[${h}] response error (${F})`,Nt({retryOfRequestLogID:i,url:T.url,status:T.status,headers:T.headers,message:q,durationMs:Date.now()-E})),this.makeStatusError(T.status,P,q,T.headers)}return Te(this).info(b),Te(this).debug(`[${h}] response start`,Nt({retryOfRequestLogID:i,url:T.url,status:T.status,headers:T.headers,durationMs:S-E})),{response:T,options:u,controller:A,requestLogID:h,retryOfRequestLogID:i,startTime:E}}async fetchWithTimeout(e,n,i,o){let s=n||{},{signal:l,method:u}=s,c=Fe(s,["signal","method"]),d=this._makeAbort(o);l&&l.addEventListener("abort",d,{once:!0});let f=setTimeout(d,i),p=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,h=Object.assign(Object.assign(Object.assign({signal:o.signal},p?{duplex:"half"}:{}),{method:"GET"}),c);u&&(h.method=u.toUpperCase());try{return await this.fetch.call(void 0,e,h)}finally{clearTimeout(f)}}async shouldRetry(e){let n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,i,o){var s;let l,u=o?.get("retry-after-ms");if(u){let d=parseFloat(u);Number.isNaN(d)||(l=d)}let c=o?.get("retry-after");if(c&&!l){let d=parseFloat(c);Number.isNaN(d)?l=Date.parse(c)-Date.now():l=d*1e3}if(l===void 0){let d=(s=e.maxRetries)!==null&&s!==void 0?s:this.maxRetries;l=this.calculateDefaultRetryTimeoutMillis(n,d)}return await bC(l),this.makeRequest(e,n-1,i)}calculateDefaultRetryTimeoutMillis(e,n){let s=n-e,l=Math.min(.5*Math.pow(2,s),8),u=1-Math.random()*.25;return l*u*1e3}async buildRequest(e,{retryCount:n=0}={}){var i,o,s;let l=Object.assign({},e),{method:u,path:c,query:d,defaultBaseURL:f}=l,p=this.buildURL(c,d,f);"timeout"in l&&GC("timeout",l.timeout),l.timeout=(i=l.timeout)!==null&&i!==void 0?i:this.timeout;let{bodyHeaders:h,body:m}=this.buildBody({options:l}),E=await this.buildHeaders({options:e,method:u,bodyHeaders:h,retryCount:n});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:u,headers:E},l.signal&&{signal:l.signal}),globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"}),m&&{body:m}),(o=this.fetchOptions)!==null&&o!==void 0?o:{}),(s=l.fetchOptions)!==null&&s!==void 0?s:{}),url:p,timeout:l.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:i,retryCount:o}){let s={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let l=await this.authHeaders(e),u=Sn([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"Api-Revision":"2026-05-20"},this._options.defaultHeaders,i,e.headers,l]);return this.validateHeaders(u),u.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};let i=Sn([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&i.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:OC(e)}:typeof e=="object"&&i.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:this.encoder({body:e,headers:i})}};yo.DEFAULT_TIMEOUT=6e4;var ce=class extends yo{constructor(){super(...arguments),this.interactions=new ho(this),this.webhooks=new go(this),this.agents=new co(this)}};ip=ce;ce.GeminiNextGenAPIClient=ip;ce.GeminiNextGenAPIClientError=Ce;ce.APIError=Se;ce.APIConnectionError=jt;ce.APIConnectionTimeoutError=eo;ce.APIUserAbortError=Rn;ce.NotFoundError=oo;ce.ConflictError=ro;ce.RateLimitError=ao;ce.BadRequestError=to;ce.AuthenticationError=no;ce.InternalServerError=lo;ce.PermissionDeniedError=io;ce.UnprocessableEntityError=so;ce.toFile=YC;ce.Interactions=ho;ce.Webhooks=go;ce.Agents=co;var Ef="x-goog-api-key",In="https://www.googleapis.com/auth/cloud-platform",Ra=class{constructor(e){if(e.apiKey!==void 0){this.apiKey=e.apiKey;return}let n=cS(e.googleAuthOptions);this.googleAuth=new Af.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,s]of i)e.get(o)===null&&e.append(o,s)}};function cS(t){let e;if(t){if(e=t,e.scopes){if(typeof e.scopes=="string"&&e.scopes!==In||Array.isArray(e.scopes)&&e.scopes.indexOf(In)<0)throw new Error(`Invalid auth scopes. Scopes must include: ${In}`)}else return e.scopes=[In],e;return e}else return e={scopes:[In]},e}var Na=class{async download(e,n){if(e.downloadPath){let i=await dS(e,n);if(i instanceof _t){let o=Uy(e.downloadPath);Ly.fromWeb(i.responseInternal.body).pipe(o),await by(o)}else try{await Gy(e.downloadPath,i,{encoding:"base64"})}catch(o){throw new Error(`Failed to write file to ${e.downloadPath}: ${o}`)}}}};async function dS(t,e){var n,i,o;let s=Ha(t.file);if(s!==void 0)return await e.request({path:`files/${s}: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(Df(t.file)){let l=(o=t.file.video)===null||o===void 0?void 0:o.videoBytes;if(typeof l=="string")return l;throw new Error("Failed to download generated video, Uri or videoBytes not found.")}else if(Mf(t.file)){let l=t.file.videoBytes;if(typeof l=="string")return l;throw new Error("Failed to download video, Uri or videoBytes not found.")}else throw new Error("Unsupported file type")}var Da=class{create(e,n,i){return new Ma(e,n,i)}},Ma=class{constructor(e,n,i){this.url=e,this.headers=n,this.callbacks=i}connect(){this.ws=new Ka.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 fS(t,e){let n={},i=r(t,["name"]);return i!=null&&a(n,["_url","name"],i),n}function pS(t,e){let n={},i=r(t,["name"]);return i!=null&&a(n,["_url","name"],i),n}function hS(t,e){let n={},i=r(t,["sdkHttpResponse"]);return i!=null&&a(n,["sdkHttpResponse"],i),n}function mS(t,e){let n={},i=r(t,["sdkHttpResponse"]);return i!=null&&a(n,["sdkHttpResponse"],i),n}function gS(t,e,n){let i={};if(r(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=r(t,["tunedModelDisplayName"]);if(e!==void 0&&o!=null&&a(e,["displayName"],o),r(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 s=r(t,["epochCount"]);e!==void 0&&s!=null&&a(e,["tuningTask","hyperparameters","epochCount"],s);let l=r(t,["learningRateMultiplier"]);if(l!=null&&a(i,["tuningTask","hyperparameters","learningRateMultiplier"],l),r(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(r(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(r(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(r(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(r(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=r(t,["batchSize"]);e!==void 0&&u!=null&&a(e,["tuningTask","hyperparameters","batchSize"],u);let c=r(t,["learningRate"]);if(e!==void 0&&c!=null&&a(e,["tuningTask","hyperparameters","learningRate"],c),r(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(r(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(r(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(r(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(r(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(r(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(r(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 yS(t,e,n){let i={},o=r(n,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){let P=r(t,["validationDataset"]);e!==void 0&&P!=null&&a(e,["supervisedTuningSpec"],Us(P))}else if(o==="PREFERENCE_TUNING"){let P=r(t,["validationDataset"]);e!==void 0&&P!=null&&a(e,["preferenceOptimizationSpec"],Us(P))}else if(o==="DISTILLATION"){let P=r(t,["validationDataset"]);e!==void 0&&P!=null&&a(e,["distillationSpec"],Us(P))}let s=r(t,["tunedModelDisplayName"]);e!==void 0&&s!=null&&a(e,["tunedModelDisplayName"],s);let l=r(t,["description"]);e!==void 0&&l!=null&&a(e,["description"],l);let u=r(n,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){let P=r(t,["epochCount"]);e!==void 0&&P!=null&&a(e,["supervisedTuningSpec","hyperParameters","epochCount"],P)}else if(u==="PREFERENCE_TUNING"){let P=r(t,["epochCount"]);e!==void 0&&P!=null&&a(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],P)}else if(u==="DISTILLATION"){let P=r(t,["epochCount"]);e!==void 0&&P!=null&&a(e,["distillationSpec","hyperParameters","epochCount"],P)}let c=r(n,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){let P=r(t,["learningRateMultiplier"]);e!==void 0&&P!=null&&a(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],P)}else if(c==="PREFERENCE_TUNING"){let P=r(t,["learningRateMultiplier"]);e!==void 0&&P!=null&&a(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],P)}else if(c==="DISTILLATION"){let P=r(t,["learningRateMultiplier"]);e!==void 0&&P!=null&&a(e,["distillationSpec","hyperParameters","learningRateMultiplier"],P)}let d=r(n,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){let P=r(t,["exportLastCheckpointOnly"]);e!==void 0&&P!=null&&a(e,["supervisedTuningSpec","exportLastCheckpointOnly"],P)}else if(d==="PREFERENCE_TUNING"){let P=r(t,["exportLastCheckpointOnly"]);e!==void 0&&P!=null&&a(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],P)}else if(d==="DISTILLATION"){let P=r(t,["exportLastCheckpointOnly"]);e!==void 0&&P!=null&&a(e,["distillationSpec","exportLastCheckpointOnly"],P)}let f=r(n,["config","method"]);if(f===void 0&&(f="SUPERVISED_FINE_TUNING"),f==="SUPERVISED_FINE_TUNING"){let P=r(t,["adapterSize"]);e!==void 0&&P!=null&&a(e,["supervisedTuningSpec","hyperParameters","adapterSize"],P)}else if(f==="PREFERENCE_TUNING"){let P=r(t,["adapterSize"]);e!==void 0&&P!=null&&a(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],P)}else if(f==="DISTILLATION"){let P=r(t,["adapterSize"]);e!==void 0&&P!=null&&a(e,["distillationSpec","hyperParameters","adapterSize"],P)}let p=r(n,["config","method"]);if(p===void 0&&(p="SUPERVISED_FINE_TUNING"),p==="SUPERVISED_FINE_TUNING"){let P=r(t,["tuningMode"]);e!==void 0&&P!=null&&a(e,["supervisedTuningSpec","tuningMode"],P)}else if(p==="DISTILLATION"){let P=r(t,["tuningMode"]);e!==void 0&&P!=null&&a(e,["distillationSpec","tuningMode"],P)}let h=r(t,["customBaseModel"]);e!==void 0&&h!=null&&a(e,["customBaseModel"],h);let m=r(n,["config","method"]);if(m===void 0&&(m="SUPERVISED_FINE_TUNING"),m==="SUPERVISED_FINE_TUNING"){let P=r(t,["batchSize"]);e!==void 0&&P!=null&&a(e,["supervisedTuningSpec","hyperParameters","batchSize"],P)}else if(m==="DISTILLATION"){let P=r(t,["batchSize"]);e!==void 0&&P!=null&&a(e,["distillationSpec","hyperParameters","batchSize"],P)}let E=r(n,["config","method"]);if(E===void 0&&(E="SUPERVISED_FINE_TUNING"),E==="SUPERVISED_FINE_TUNING"){let P=r(t,["learningRate"]);e!==void 0&&P!=null&&a(e,["supervisedTuningSpec","hyperParameters","learningRate"],P)}else if(E==="DISTILLATION"){let P=r(t,["learningRate"]);e!==void 0&&P!=null&&a(e,["distillationSpec","hyperParameters","learningRate"],P)}let A=r(t,["labels"]);e!==void 0&&A!=null&&a(e,["labels"],A);let T=r(t,["beta"]);e!==void 0&&T!=null&&a(e,["preferenceOptimizationSpec","hyperParameters","beta"],T);let S=r(t,["baseTeacherModel"]);e!==void 0&&S!=null&&a(e,["distillationSpec","baseTeacherModel"],S);let b=r(t,["tunedTeacherModelSource"]);e!==void 0&&b!=null&&a(e,["distillationSpec","tunedTeacherModelSource"],b);let U=r(t,["sftLossWeightMultiplier"]);e!==void 0&&U!=null&&a(e,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],U);let F=r(t,["outputUri"]);e!==void 0&&F!=null&&a(e,["outputUri"],F);let L=r(t,["encryptionSpec"]);return e!==void 0&&L!=null&&a(e,["encryptionSpec"],L),i}function ES(t,e){let n={},i=r(t,["baseModel"]);i!=null&&a(n,["baseModel"],i);let o=r(t,["preTunedModel"]);o!=null&&a(n,["preTunedModel"],o);let s=r(t,["trainingDataset"]);s!=null&&NS(s);let l=r(t,["config"]);return l!=null&&gS(l,n),n}function _S(t,e){let n={},i=r(t,["baseModel"]);i!=null&&a(n,["baseModel"],i);let o=r(t,["preTunedModel"]);o!=null&&a(n,["preTunedModel"],o);let s=r(t,["trainingDataset"]);s!=null&&DS(s,n,e);let l=r(t,["config"]);return l!=null&&yS(l,n,e),n}function op(t,e){let n={},i=r(t,["adapterSize"]);i!=null&&a(n,["adapterSize"],i);let o=r(t,["epochCount"]);o!=null&&a(n,["epochCount"],o);let s=r(t,["learningRateMultiplier"]);s!=null&&a(n,["learningRateMultiplier"],s);let l=r(t,["generationConfig"]);l!=null&&a(n,["generationConfig"],vS(l));let u=r(t,["learningRate"]);u!=null&&a(n,["learningRate"],u);let c=r(t,["batchSize"]);return c!=null&&a(n,["batchSize"],c),n}function TS(t,e){let n={},i=r(t,["baseTeacherModel"]);i!=null&&a(n,["baseTeacherModel"],i);let o=r(t,["tunedTeacherModelSource"]);o!=null&&a(n,["tunedTeacherModelSource"],o);let s=r(t,["validationDatasetUri"]);s!=null&&a(n,["validationDatasetUri"],s);let l=r(t,["promptDatasetUri"]);l!=null&&a(n,["promptDatasetUri"],l);let u=r(t,["hyperparameters"]);return u!=null&&a(n,["hyperparameters"],op(u)),n}function AS(t,e){let n={},i=r(t,["promptDatasetUri"]);i!=null&&a(n,["promptDatasetUri"],i);let o=r(t,["baseTeacherModel"]);o!=null&&a(n,["baseTeacherModel"],o);let s=r(t,["hyperParameters"]);s!=null&&a(n,["hyperParameters"],op(s));let l=r(t,["pipelineRootDirectory"]);l!=null&&a(n,["pipelineRootDirectory"],l);let u=r(t,["studentModel"]);u!=null&&a(n,["studentModel"],u);let c=r(t,["trainingDatasetUri"]);c!=null&&a(n,["trainingDatasetUri"],c);let d=r(t,["tunedTeacherModelSource"]);d!=null&&a(n,["tunedTeacherModelSource"],d);let f=r(t,["validationDatasetUri"]);f!=null&&a(n,["validationDatasetUri"],f);let p=r(t,["tuningMode"]);return p!=null&&a(n,["tuningMode"],p),n}function vS(t,e){let n={},i=r(t,["modelConfig"]);i!=null&&a(n,["modelSelectionConfig"],i);let o=r(t,["responseJsonSchema"]);o!=null&&a(n,["responseJsonSchema"],o);let s=r(t,["audioTimestamp"]);s!=null&&a(n,["audioTimestamp"],s);let l=r(t,["candidateCount"]);l!=null&&a(n,["candidateCount"],l);let u=r(t,["enableAffectiveDialog"]);u!=null&&a(n,["enableAffectiveDialog"],u);let c=r(t,["frequencyPenalty"]);c!=null&&a(n,["frequencyPenalty"],c);let d=r(t,["logprobs"]);d!=null&&a(n,["logprobs"],d);let f=r(t,["maxOutputTokens"]);f!=null&&a(n,["maxOutputTokens"],f);let p=r(t,["mediaResolution"]);p!=null&&a(n,["mediaResolution"],p);let h=r(t,["presencePenalty"]);h!=null&&a(n,["presencePenalty"],h);let m=r(t,["responseLogprobs"]);m!=null&&a(n,["responseLogprobs"],m);let E=r(t,["responseMimeType"]);E!=null&&a(n,["responseMimeType"],E);let A=r(t,["responseModalities"]);A!=null&&a(n,["responseModalities"],A);let T=r(t,["responseSchema"]);T!=null&&a(n,["responseSchema"],T);let S=r(t,["routingConfig"]);S!=null&&a(n,["routingConfig"],S);let b=r(t,["seed"]);b!=null&&a(n,["seed"],b);let U=r(t,["speechConfig"]);U!=null&&a(n,["speechConfig"],U);let F=r(t,["stopSequences"]);F!=null&&a(n,["stopSequences"],F);let L=r(t,["temperature"]);L!=null&&a(n,["temperature"],L);let P=r(t,["thinkingConfig"]);P!=null&&a(n,["thinkingConfig"],P);let q=r(t,["topK"]);q!=null&&a(n,["topK"],q);let J=r(t,["topP"]);return J!=null&&a(n,["topP"],J),n}function CS(t,e){let n={},i=r(t,["name"]);return i!=null&&a(n,["_url","name"],i),n}function SS(t,e){let n={},i=r(t,["name"]);return i!=null&&a(n,["_url","name"],i),n}function IS(t,e,n){let i={},o=r(t,["pageSize"]);e!==void 0&&o!=null&&a(e,["_query","pageSize"],o);let s=r(t,["pageToken"]);e!==void 0&&s!=null&&a(e,["_query","pageToken"],s);let l=r(t,["filter"]);return e!==void 0&&l!=null&&a(e,["_query","filter"],l),i}function wS(t,e){let n={},i=r(t,["config"]);return i!=null&&IS(i,n),n}function PS(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["nextPageToken"]);o!=null&&a(n,["nextPageToken"],o);let s=r(t,["tuningJobs"]);if(s!=null){let l=s;Array.isArray(l)&&(l=l.map(u=>xa(u))),a(n,["tuningJobs"],l)}return n}function RS(t,e){let n={},i=r(t,["name"]);i!=null&&a(n,["model"],i);let o=r(t,["name"]);return o!=null&&a(n,["endpoint"],o),n}function NS(t,e){let n={};if(r(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(r(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=r(t,["examples"]);if(i!=null){let o=i;Array.isArray(o)&&(o=o.map(s=>s)),a(n,["examples","examples"],o)}return n}function DS(t,e,n){let i={},o=r(n,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){let l=r(t,["gcsUri"]);e!==void 0&&l!=null&&a(e,["supervisedTuningSpec","trainingDatasetUri"],l)}else if(o==="PREFERENCE_TUNING"){let l=r(t,["gcsUri"]);e!==void 0&&l!=null&&a(e,["preferenceOptimizationSpec","trainingDatasetUri"],l)}else if(o==="DISTILLATION"){let l=r(t,["gcsUri"]);e!==void 0&&l!=null&&a(e,["distillationSpec","promptDatasetUri"],l)}let s=r(n,["config","method"]);if(s===void 0&&(s="SUPERVISED_FINE_TUNING"),s==="SUPERVISED_FINE_TUNING"){let l=r(t,["vertexDatasetResource"]);e!==void 0&&l!=null&&a(e,["supervisedTuningSpec","trainingDatasetUri"],l)}else if(s==="PREFERENCE_TUNING"){let l=r(t,["vertexDatasetResource"]);e!==void 0&&l!=null&&a(e,["preferenceOptimizationSpec","trainingDatasetUri"],l)}else if(s==="DISTILLATION"){let l=r(t,["vertexDatasetResource"]);e!==void 0&&l!=null&&a(e,["distillationSpec","promptDatasetUri"],l)}if(r(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 MS(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["name"]);o!=null&&a(n,["name"],o);let s=r(t,["state"]);s!=null&&a(n,["state"],Nf(s));let l=r(t,["createTime"]);l!=null&&a(n,["createTime"],l);let u=r(t,["tuningTask","startTime"]);u!=null&&a(n,["startTime"],u);let c=r(t,["tuningTask","completeTime"]);c!=null&&a(n,["endTime"],c);let d=r(t,["updateTime"]);d!=null&&a(n,["updateTime"],d);let f=r(t,["description"]);f!=null&&a(n,["description"],f);let p=r(t,["baseModel"]);p!=null&&a(n,["baseModel"],p);let h=r(t,["_self"]);return h!=null&&a(n,["tunedModel"],RS(h)),n}function xa(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["name"]);o!=null&&a(n,["name"],o);let s=r(t,["state"]);s!=null&&a(n,["state"],Nf(s));let l=r(t,["createTime"]);l!=null&&a(n,["createTime"],l);let u=r(t,["startTime"]);u!=null&&a(n,["startTime"],u);let c=r(t,["endTime"]);c!=null&&a(n,["endTime"],c);let d=r(t,["updateTime"]);d!=null&&a(n,["updateTime"],d);let f=r(t,["error"]);f!=null&&a(n,["error"],f);let p=r(t,["description"]);p!=null&&a(n,["description"],p);let h=r(t,["baseModel"]);h!=null&&a(n,["baseModel"],h);let m=r(t,["tunedModel"]);m!=null&&a(n,["tunedModel"],m);let E=r(t,["preTunedModel"]);E!=null&&a(n,["preTunedModel"],E);let A=r(t,["supervisedTuningSpec"]);A!=null&&a(n,["supervisedTuningSpec"],A);let T=r(t,["preferenceOptimizationSpec"]);T!=null&&a(n,["preferenceOptimizationSpec"],T);let S=r(t,["distillationSpec"]);S!=null&&a(n,["distillationSpec"],AS(S));let b=r(t,["tuningDataStats"]);b!=null&&a(n,["tuningDataStats"],b);let U=r(t,["encryptionSpec"]);U!=null&&a(n,["encryptionSpec"],U);let F=r(t,["partnerModelTuningSpec"]);F!=null&&a(n,["partnerModelTuningSpec"],F);let L=r(t,["customBaseModel"]);L!=null&&a(n,["customBaseModel"],L);let P=r(t,["evaluateDatasetRuns"]);if(P!=null){let ae=P;Array.isArray(ae)&&(ae=ae.map(ot=>ot)),a(n,["evaluateDatasetRuns"],ae)}let q=r(t,["experiment"]);q!=null&&a(n,["experiment"],q);let J=r(t,["fullFineTuningSpec"]);J!=null&&a(n,["fullFineTuningSpec"],J);let R=r(t,["labels"]);R!=null&&a(n,["labels"],R);let $=r(t,["outputUri"]);$!=null&&a(n,["outputUri"],$);let X=r(t,["pipelineJob"]);X!=null&&a(n,["pipelineJob"],X);let Z=r(t,["serviceAccount"]);Z!=null&&a(n,["serviceAccount"],Z);let se=r(t,["tunedModelDisplayName"]);se!=null&&a(n,["tunedModelDisplayName"],se);let te=r(t,["tuningJobState"]);te!=null&&a(n,["tuningJobState"],te);let re=r(t,["veoTuningSpec"]);re!=null&&a(n,["veoTuningSpec"],re);let de=r(t,["tuningJobMetadata"]);de!=null&&a(n,["tuningJobMetadata"],de);let Ie=r(t,["veoLoraTuningSpec"]);Ie!=null&&a(n,["veoLoraTuningSpec"],Ie);let Be=r(t,["distillationSamplingSpec"]);return Be!=null&&a(n,["distillationSamplingSpec"],TS(Be)),n}function xS(t,e){let n={},i=r(t,["sdkHttpResponse"]);i!=null&&a(n,["sdkHttpResponse"],i);let o=r(t,["name"]);o!=null&&a(n,["name"],o);let s=r(t,["metadata"]);s!=null&&a(n,["metadata"],s);let l=r(t,["done"]);l!=null&&a(n,["done"],l);let u=r(t,["error"]);return u!=null&&a(n,["error"],u),n}function Us(t,e){let n={},i=r(t,["gcsUri"]);i!=null&&a(n,["validationDatasetUri"],i);let o=r(t,["vertexDatasetResource"]);return o!=null&&a(n,["validationDatasetUri"],o),n}var ka=class extends Ye{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new ct(ut.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 s=Object.assign(Object.assign({},n),{preTunedModel:o});return s.baseModel=void 0,await this.tuneInternal(s)}else{let o=Object.assign({},n);return await this.tuneInternal(o)}else{let o=Object.assign({},n),s=await this.tuneMldevInternal(o),l="";return s.metadata!==void 0&&s.metadata.tunedModel!==void 0?l=s.metadata.tunedModel:s.name!==void 0&&s.name.includes("/operations/")&&(l=s.name.split("/operations/")[0]),{name:l,state:Ls.JOB_STATE_QUEUED}}}}async getInternal(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=SS(e);return u=H("{name}",d._url),c=d._query,delete d._url,delete d._query,l=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})),l.then(f=>xa(f))}else{let d=CS(e);return u=H("{name}",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),l.then(f=>MS(f))}}async listInternal(e){var n,i;let o,s="",l={};if(this.apiClient.isVertexAI()){let u=wS(e);return s=H("tuningJobs",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=PS(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 cancel(e){var n,i,o,s;let l,u="",c={};if(this.apiClient.isVertexAI()){let d=pS(e);return u=H("{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,l=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})),l.then(f=>{let p=mS(f),h=new Wi;return Object.assign(h,p),h})}else{let d=fS(e);return u=H("{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,l=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:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(f=>f.json().then(p=>{let h=p;return h.sdkHttpResponse={headers:f.headers},h})),l.then(f=>{let p=hS(f),h=new Wi;return Object.assign(h,p),h})}}async tuneInternal(e){var n,i;let o,s="",l={};if(this.apiClient.isVertexAI()){let u=_S(e,e);return s=H("tuningJobs",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=>xa(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,s="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let u=ES(e);return s=H("tunedModels",u._url),l=u._query,delete u._url,delete u._query,o=this.apiClient.request({path:s,queryParams:l,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=>xS(c))}}},rp=1024*1024*8,sp=3,ap=1e3,lp=2,yt="x-goog-upload-status";async function kS(t,e,n,i){var o;let s=await up(t,e,n,i),l=await s?.json();if(((o=s?.headers)===null||o===void 0?void 0:o[yt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return l.file}async function US(t,e,n,i){var o;let s=await up(t,e,n,i),l=await s?.json();if(((o=s?.headers)===null||o===void 0?void 0:o[yt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let u=ba(l),c=new Qi;return Object.assign(c,u),c}async function up(t,e,n,i){var o,s,l;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),E=new URL(e);E.protocol=m.protocol,E.host=m.host,E.port=m.port,u=E.toString()}let d=0,f=0,p=new _t(new Response),h="upload";for(d=t.size;f<d;){let m=Math.min(rp,d-f),E=t.slice(f,f+m);f+m>=d&&(h+=", finalize");let A=0,T=ap;for(;A<sp;){let S=Object.assign(Object.assign({},i?.headers||{}),{"X-Goog-Upload-Command":h,"X-Goog-Upload-Offset":String(f),"Content-Length":String(m)});if(p=await n.request({path:"",body:E,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},i),{apiVersion:"",baseUrl:u,headers:S})}),!((s=p?.headers)===null||s===void 0)&&s[yt])break;A++,await cp(T),T=T*lp}if(f+=m,((l=p?.headers)===null||l===void 0?void 0:l[yt])!=="active")break;if(d<=f)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return p}async function GS(t){return{size:t.size,type:t.type}}function cp(t){return new Promise(e=>setTimeout(e,t))}var Ua=class{async stat(e){let n={size:0,type:void 0};if(typeof e=="string"){let i=await _o.stat(e);return n.size=i.size,n.type=this.inferMimeType(e),n}else return await GS(e)}async upload(e,n,i,o){return typeof e=="string"?await this.uploadFileFromPath(e,n,i,o):kS(e,n,i,o)}async uploadToFileSearchStore(e,n,i,o){return typeof e=="string"?await this.uploadFileToFileSearchStoreFromPath(e,n,i,o):US(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 s;let l=await this.uploadFileFromPathInternal(e,n,i,o),u=await l?.json();if(((s=l?.headers)===null||s===void 0?void 0:s[yt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return u.file}async uploadFileToFileSearchStoreFromPath(e,n,i,o){var s;let l=await this.uploadFileFromPathInternal(e,n,i,o),u=await l?.json();if(((s=l?.headers)===null||s===void 0?void 0:s[yt])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let c=ba(u),d=new Qi;return Object.assign(d,c),d}async uploadFileFromPathInternal(e,n,i,o){var s,l,u;let c=n,d=o?.baseUrl||((s=i.clientOptions.httpOptions)===null||s===void 0?void 0:s.baseUrl);if(d){let T=new URL(d),S=new URL(n);S.protocol=T.protocol,S.host=T.host,S.port=T.port,c=S.toString()}let f=0,p=0,h=new _t(new Response),m="upload",E,A=vf.basename(e);try{if(E=await _o.open(e,"r"),!E)throw new Error("Failed to open file");for(f=(await E.stat()).size;p<f;){let T=Math.min(rp,f-p);p+T>=f&&(m+=", finalize");let S=new Uint8Array(T),{bytesRead:b}=await E.read(S,0,T,p);if(b!==T)throw new Error(`Failed to read ${T} bytes from file at offset ${p}. bytes actually read: ${b}`);let U=new Blob([S]),F=0,L=ap;for(;F<sp;){let P=Object.assign(Object.assign({},o?.headers||{}),{"X-Goog-Upload-Command":m,"X-Goog-Upload-Offset":String(p),"Content-Length":String(b),"X-Goog-Upload-File-Name":A});if(h=await i.request({path:"",body:U,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},o),{apiVersion:"",baseUrl:c,headers:P})}),!((l=h?.headers)===null||l===void 0)&&l[yt])break;F++,await cp(L),L=L*lp}if(p+=b,((u=h?.headers)===null||u===void 0?void 0:u[yt])!=="active")break;if(f<=p)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return h}finally{E&&await E.close()}}};var Ga=class extends sa{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||{},s=o.httpOptions||{},l=Object.assign({},s.headers||{});if(i)if(typeof i[Symbol.iterator]=="function")for(let[u,c]of i)l[u]=c;else for(let[u,c]of Object.entries(i))l[u]=c;return this._registerFiles({uris:e.uris,config:Object.assign(Object.assign({},o),{httpOptions:Object.assign(Object.assign({},s),{headers:l})})})}};var LS="gl-node/";function bS(t){var e;if(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=Et("GOOGLE_GENAI_USE_ENTERPRISE"),i=Et("GOOGLE_GENAI_USE_VERTEXAI"),o=Tf(n),s=Tf(i);return n!==void 0&&i!==void 0&&o!==s&&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?s:!1}var _f=class{getNextGenClient(){var e;let n=this.httpOptions;return this._nextGenClient===void 0&&(this._nextGenClient=new ce({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:n?.timeout,maxRetries:(e=n?.retryOptions)===null||e===void 0?void 0:e.attempts})),n?.extraBody&&console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored."),this._nextGenClient}get interactions(){return this._interactions!==void 0?this._interactions:(console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions."),this._interactions=this.getNextGenClient().interactions,this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=this.getNextGenClient().webhooks,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=this.getNextGenClient().agents,this._agents)}constructor(e){var n,i,o,s;if((e.project||e.location)&&e.apiKey)throw new Error("Project/location and API key are mutually exclusive in the client initializer.");this.vertexai=bS(e);let l=FS(),u=Et("GOOGLE_CLOUD_PROJECT"),c=Et("GOOGLE_CLOUD_LOCATION");this.apiKey=(n=e.apiKey)!==null&&n!==void 0?n:l,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&&(!((s=e.googleAuthOptions)===null||s===void 0)&&s.credentials&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),(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)&&l?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):(u||c)&&l&&(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=By(e.httpOptions,this.vertexai,Et("GOOGLE_VERTEX_BASE_URL"),Et("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 Ra({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new ca({auth:f,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:LS+process.version,uploader:new Ua,downloader:new Na}),this.models=new ma(this.apiClient),this.live=new pa(this.apiClient,f,new Da),this.batches=new na(this.apiClient),this.chats=new oa(this.models,this.apiClient),this.caches=new ia(this.apiClient),this.files=new Ga(this.apiClient),this.operations=new ga(this.apiClient),this.authTokens=new ya(this.apiClient),this.tunings=new ka(this.apiClient),this.fileSearchStores=new _a(this.apiClient)}};function Et(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 Tf(t){return t===void 0?!1:t.toLowerCase()==="true"}function FS(){let t=Et("GOOGLE_API_KEY"),e=Et("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}export{Uc as a,Zc as b,DP as c,MP as d,Dt as e,xP as f,_f as g};
45
- /*! Bundled license information:
46
-
47
- safe-buffer/index.js:
48
- (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
49
-
50
- @google/genai/dist/node/index.mjs:
51
- @google/genai/dist/node/index.mjs:
52
- @google/genai/dist/node/index.mjs:
53
- @google/genai/dist/node/index.mjs:
54
- (**
55
- * @license
56
- * Copyright 2025 Google LLC
57
- * SPDX-License-Identifier: Apache-2.0
58
- *)
59
- */